xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 6c088972d2822bd10e5104fd8994b5c25f3070e0)
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/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
41 #include "llvm/CodeGen/MachineMemOperand.h"
42 #include "llvm/CodeGen/MachineModuleInfo.h"
43 #include "llvm/CodeGen/MachineOperand.h"
44 #include "llvm/CodeGen/MachineRegisterInfo.h"
45 #include "llvm/CodeGen/RuntimeLibcalls.h"
46 #include "llvm/CodeGen/SelectionDAG.h"
47 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
48 #include "llvm/CodeGen/StackMaps.h"
49 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
50 #include "llvm/CodeGen/TargetFrameLowering.h"
51 #include "llvm/CodeGen/TargetInstrInfo.h"
52 #include "llvm/CodeGen/TargetOpcodes.h"
53 #include "llvm/CodeGen/TargetRegisterInfo.h"
54 #include "llvm/CodeGen/TargetSubtargetInfo.h"
55 #include "llvm/CodeGen/WinEHFuncInfo.h"
56 #include "llvm/IR/Argument.h"
57 #include "llvm/IR/Attributes.h"
58 #include "llvm/IR/BasicBlock.h"
59 #include "llvm/IR/CFG.h"
60 #include "llvm/IR/CallingConv.h"
61 #include "llvm/IR/Constant.h"
62 #include "llvm/IR/ConstantRange.h"
63 #include "llvm/IR/Constants.h"
64 #include "llvm/IR/DataLayout.h"
65 #include "llvm/IR/DebugInfo.h"
66 #include "llvm/IR/DebugInfoMetadata.h"
67 #include "llvm/IR/DerivedTypes.h"
68 #include "llvm/IR/DiagnosticInfo.h"
69 #include "llvm/IR/EHPersonalities.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/GetElementPtrTypeIterator.h"
72 #include "llvm/IR/InlineAsm.h"
73 #include "llvm/IR/InstrTypes.h"
74 #include "llvm/IR/Instructions.h"
75 #include "llvm/IR/IntrinsicInst.h"
76 #include "llvm/IR/Intrinsics.h"
77 #include "llvm/IR/IntrinsicsAArch64.h"
78 #include "llvm/IR/IntrinsicsWebAssembly.h"
79 #include "llvm/IR/LLVMContext.h"
80 #include "llvm/IR/Metadata.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/Operator.h"
83 #include "llvm/IR/PatternMatch.h"
84 #include "llvm/IR/Statepoint.h"
85 #include "llvm/IR/Type.h"
86 #include "llvm/IR/User.h"
87 #include "llvm/IR/Value.h"
88 #include "llvm/MC/MCContext.h"
89 #include "llvm/Support/AtomicOrdering.h"
90 #include "llvm/Support/Casting.h"
91 #include "llvm/Support/CommandLine.h"
92 #include "llvm/Support/Compiler.h"
93 #include "llvm/Support/Debug.h"
94 #include "llvm/Support/MathExtras.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include "llvm/Target/TargetIntrinsicInfo.h"
97 #include "llvm/Target/TargetMachine.h"
98 #include "llvm/Target/TargetOptions.h"
99 #include "llvm/TargetParser/Triple.h"
100 #include "llvm/Transforms/Utils/Local.h"
101 #include <cstddef>
102 #include <iterator>
103 #include <limits>
104 #include <optional>
105 #include <tuple>
106 
107 using namespace llvm;
108 using namespace PatternMatch;
109 using namespace SwitchCG;
110 
111 #define DEBUG_TYPE "isel"
112 
113 /// LimitFloatPrecision - Generate low-precision inline sequences for
114 /// some float libcalls (6, 8 or 12 bits).
115 static unsigned LimitFloatPrecision;
116 
117 static cl::opt<bool>
118     InsertAssertAlign("insert-assert-align", cl::init(true),
119                       cl::desc("Insert the experimental `assertalign` node."),
120                       cl::ReallyHidden);
121 
122 static cl::opt<unsigned, true>
123     LimitFPPrecision("limit-float-precision",
124                      cl::desc("Generate low-precision inline sequences "
125                               "for some float libcalls"),
126                      cl::location(LimitFloatPrecision), cl::Hidden,
127                      cl::init(0));
128 
129 static cl::opt<unsigned> SwitchPeelThreshold(
130     "switch-peel-threshold", cl::Hidden, cl::init(66),
131     cl::desc("Set the case probability threshold for peeling the case from a "
132              "switch statement. A value greater than 100 will void this "
133              "optimization"));
134 
135 // Limit the width of DAG chains. This is important in general to prevent
136 // DAG-based analysis from blowing up. For example, alias analysis and
137 // load clustering may not complete in reasonable time. It is difficult to
138 // recognize and avoid this situation within each individual analysis, and
139 // future analyses are likely to have the same behavior. Limiting DAG width is
140 // the safe approach and will be especially important with global DAGs.
141 //
142 // MaxParallelChains default is arbitrarily high to avoid affecting
143 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
144 // sequence over this should have been converted to llvm.memcpy by the
145 // frontend. It is easy to induce this behavior with .ll code such as:
146 // %buffer = alloca [4096 x i8]
147 // %data = load [4096 x i8]* %argPtr
148 // store [4096 x i8] %data, [4096 x i8]* %buffer
149 static const unsigned MaxParallelChains = 64;
150 
151 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
152                                       const SDValue *Parts, unsigned NumParts,
153                                       MVT PartVT, EVT ValueVT, const Value *V,
154                                       std::optional<CallingConv::ID> CC);
155 
156 /// getCopyFromParts - Create a value that contains the specified legal parts
157 /// combined into the value they represent.  If the parts combine to a type
158 /// larger than ValueVT then AssertOp can be used to specify whether the extra
159 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
160 /// (ISD::AssertSext).
161 static SDValue
162 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
163                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
164                  std::optional<CallingConv::ID> CC = std::nullopt,
165                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
166   // Let the target assemble the parts if it wants to
167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
168   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
169                                                    PartVT, ValueVT, CC))
170     return Val;
171 
172   if (ValueVT.isVector())
173     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
174                                   CC);
175 
176   assert(NumParts > 0 && "No parts to assemble!");
177   SDValue Val = Parts[0];
178 
179   if (NumParts > 1) {
180     // Assemble the value from multiple parts.
181     if (ValueVT.isInteger()) {
182       unsigned PartBits = PartVT.getSizeInBits();
183       unsigned ValueBits = ValueVT.getSizeInBits();
184 
185       // Assemble the power of 2 part.
186       unsigned RoundParts = llvm::bit_floor(NumParts);
187       unsigned RoundBits = PartBits * RoundParts;
188       EVT RoundVT = RoundBits == ValueBits ?
189         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
190       SDValue Lo, Hi;
191 
192       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
193 
194       if (RoundParts > 2) {
195         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
196                               PartVT, HalfVT, V);
197         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
198                               RoundParts / 2, PartVT, HalfVT, V);
199       } else {
200         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
201         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
202       }
203 
204       if (DAG.getDataLayout().isBigEndian())
205         std::swap(Lo, Hi);
206 
207       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
208 
209       if (RoundParts < NumParts) {
210         // Assemble the trailing non-power-of-2 part.
211         unsigned OddParts = NumParts - RoundParts;
212         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
213         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
214                               OddVT, V, CC);
215 
216         // Combine the round and odd parts.
217         Lo = Val;
218         if (DAG.getDataLayout().isBigEndian())
219           std::swap(Lo, Hi);
220         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
221         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
222         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
223                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
224                                          TLI.getShiftAmountTy(
225                                              TotalVT, DAG.getDataLayout())));
226         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
227         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
228       }
229     } else if (PartVT.isFloatingPoint()) {
230       // FP split into multiple FP parts (for ppcf128)
231       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
232              "Unexpected split");
233       SDValue Lo, Hi;
234       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
235       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
236       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
237         std::swap(Lo, Hi);
238       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
239     } else {
240       // FP split into integer parts (soft fp)
241       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
242              !PartVT.isVector() && "Unexpected split");
243       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
244       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
245     }
246   }
247 
248   // There is now one part, held in Val.  Correct it to match ValueVT.
249   // PartEVT is the type of the register class that holds the value.
250   // ValueVT is the type of the inline asm operation.
251   EVT PartEVT = Val.getValueType();
252 
253   if (PartEVT == ValueVT)
254     return Val;
255 
256   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
257       ValueVT.bitsLT(PartEVT)) {
258     // For an FP value in an integer part, we need to truncate to the right
259     // width first.
260     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
261     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
262   }
263 
264   // Handle types that have the same size.
265   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
266     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
267 
268   // Handle types with different sizes.
269   if (PartEVT.isInteger() && ValueVT.isInteger()) {
270     if (ValueVT.bitsLT(PartEVT)) {
271       // For a truncate, see if we have any information to
272       // indicate whether the truncated bits will always be
273       // zero or sign-extension.
274       if (AssertOp)
275         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
276                           DAG.getValueType(ValueVT));
277       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
278     }
279     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
280   }
281 
282   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
283     // FP_ROUND's are always exact here.
284     if (ValueVT.bitsLT(Val.getValueType()))
285       return DAG.getNode(
286           ISD::FP_ROUND, DL, ValueVT, Val,
287           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
288 
289     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
290   }
291 
292   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
293   // then truncating.
294   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
295       ValueVT.bitsLT(PartEVT)) {
296     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
297     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
298   }
299 
300   report_fatal_error("Unknown mismatch in getCopyFromParts!");
301 }
302 
303 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
304                                               const Twine &ErrMsg) {
305   const Instruction *I = dyn_cast_or_null<Instruction>(V);
306   if (!V)
307     return Ctx.emitError(ErrMsg);
308 
309   const char *AsmError = ", possible invalid constraint for vector type";
310   if (const CallInst *CI = dyn_cast<CallInst>(I))
311     if (CI->isInlineAsm())
312       return Ctx.emitError(I, ErrMsg + AsmError);
313 
314   return Ctx.emitError(I, ErrMsg);
315 }
316 
317 /// getCopyFromPartsVector - Create a value that contains the specified legal
318 /// parts combined into the value they represent.  If the parts combine to a
319 /// type larger than ValueVT then AssertOp can be used to specify whether the
320 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
321 /// ValueVT (ISD::AssertSext).
322 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
323                                       const SDValue *Parts, unsigned NumParts,
324                                       MVT PartVT, EVT ValueVT, const Value *V,
325                                       std::optional<CallingConv::ID> CallConv) {
326   assert(ValueVT.isVector() && "Not a vector value");
327   assert(NumParts > 0 && "No parts to assemble!");
328   const bool IsABIRegCopy = CallConv.has_value();
329 
330   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
331   SDValue Val = Parts[0];
332 
333   // Handle a multi-element vector.
334   if (NumParts > 1) {
335     EVT IntermediateVT;
336     MVT RegisterVT;
337     unsigned NumIntermediates;
338     unsigned NumRegs;
339 
340     if (IsABIRegCopy) {
341       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
342           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
343           NumIntermediates, RegisterVT);
344     } else {
345       NumRegs =
346           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
347                                      NumIntermediates, RegisterVT);
348     }
349 
350     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
351     NumParts = NumRegs; // Silence a compiler warning.
352     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
353     assert(RegisterVT.getSizeInBits() ==
354            Parts[0].getSimpleValueType().getSizeInBits() &&
355            "Part type sizes don't match!");
356 
357     // Assemble the parts into intermediate operands.
358     SmallVector<SDValue, 8> Ops(NumIntermediates);
359     if (NumIntermediates == NumParts) {
360       // If the register was not expanded, truncate or copy the value,
361       // as appropriate.
362       for (unsigned i = 0; i != NumParts; ++i)
363         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
364                                   PartVT, IntermediateVT, V, CallConv);
365     } else if (NumParts > 0) {
366       // If the intermediate type was expanded, build the intermediate
367       // operands from the parts.
368       assert(NumParts % NumIntermediates == 0 &&
369              "Must expand into a divisible number of parts!");
370       unsigned Factor = NumParts / NumIntermediates;
371       for (unsigned i = 0; i != NumIntermediates; ++i)
372         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
373                                   PartVT, IntermediateVT, V, CallConv);
374     }
375 
376     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
377     // intermediate operands.
378     EVT BuiltVectorTy =
379         IntermediateVT.isVector()
380             ? EVT::getVectorVT(
381                   *DAG.getContext(), IntermediateVT.getScalarType(),
382                   IntermediateVT.getVectorElementCount() * NumParts)
383             : EVT::getVectorVT(*DAG.getContext(),
384                                IntermediateVT.getScalarType(),
385                                NumIntermediates);
386     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
387                                                 : ISD::BUILD_VECTOR,
388                       DL, BuiltVectorTy, Ops);
389   }
390 
391   // There is now one part, held in Val.  Correct it to match ValueVT.
392   EVT PartEVT = Val.getValueType();
393 
394   if (PartEVT == ValueVT)
395     return Val;
396 
397   if (PartEVT.isVector()) {
398     // Vector/Vector bitcast.
399     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
400       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
401 
402     // If the parts vector has more elements than the value vector, then we
403     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
404     // Extract the elements we want.
405     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
406       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
407               ValueVT.getVectorElementCount().getKnownMinValue()) &&
408              (PartEVT.getVectorElementCount().isScalable() ==
409               ValueVT.getVectorElementCount().isScalable()) &&
410              "Cannot narrow, it would be a lossy transformation");
411       PartEVT =
412           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
413                            ValueVT.getVectorElementCount());
414       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
415                         DAG.getVectorIdxConstant(0, DL));
416       if (PartEVT == ValueVT)
417         return Val;
418       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
419         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
420     }
421 
422     // Promoted vector extract
423     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
424   }
425 
426   // Trivial bitcast if the types are the same size and the destination
427   // vector type is legal.
428   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
429       TLI.isTypeLegal(ValueVT))
430     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
431 
432   if (ValueVT.getVectorNumElements() != 1) {
433      // Certain ABIs require that vectors are passed as integers. For vectors
434      // are the same size, this is an obvious bitcast.
435      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
436        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
437      } else if (ValueVT.bitsLT(PartEVT)) {
438        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
439        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
440        // Drop the extra bits.
441        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
442        return DAG.getBitcast(ValueVT, Val);
443      }
444 
445      diagnosePossiblyInvalidConstraint(
446          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
447      return DAG.getUNDEF(ValueVT);
448   }
449 
450   // Handle cases such as i8 -> <1 x i1>
451   EVT ValueSVT = ValueVT.getVectorElementType();
452   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
453     unsigned ValueSize = ValueSVT.getSizeInBits();
454     if (ValueSize == PartEVT.getSizeInBits()) {
455       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
456     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
457       // It's possible a scalar floating point type gets softened to integer and
458       // then promoted to a larger integer. If PartEVT is the larger integer
459       // we need to truncate it and then bitcast to the FP type.
460       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
461       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
462       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
463       Val = DAG.getBitcast(ValueSVT, Val);
464     } else {
465       Val = ValueVT.isFloatingPoint()
466                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
467                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
468     }
469   }
470 
471   return DAG.getBuildVector(ValueVT, DL, Val);
472 }
473 
474 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
475                                  SDValue Val, SDValue *Parts, unsigned NumParts,
476                                  MVT PartVT, const Value *V,
477                                  std::optional<CallingConv::ID> CallConv);
478 
479 /// getCopyToParts - Create a series of nodes that contain the specified value
480 /// split into legal parts.  If the parts contain more bits than Val, then, for
481 /// integers, ExtendKind can be used to specify how to generate the extra bits.
482 static void
483 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
484                unsigned NumParts, MVT PartVT, const Value *V,
485                std::optional<CallingConv::ID> CallConv = std::nullopt,
486                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
487   // Let the target split the parts if it wants to
488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
489   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
490                                       CallConv))
491     return;
492   EVT ValueVT = Val.getValueType();
493 
494   // Handle the vector case separately.
495   if (ValueVT.isVector())
496     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
497                                 CallConv);
498 
499   unsigned OrigNumParts = NumParts;
500   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
501          "Copying to an illegal type!");
502 
503   if (NumParts == 0)
504     return;
505 
506   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
507   EVT PartEVT = PartVT;
508   if (PartEVT == ValueVT) {
509     assert(NumParts == 1 && "No-op copy with multiple parts!");
510     Parts[0] = Val;
511     return;
512   }
513 
514   unsigned PartBits = PartVT.getSizeInBits();
515   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
516     // If the parts cover more bits than the value has, promote the value.
517     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
518       assert(NumParts == 1 && "Do not know what to promote to!");
519       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
520     } else {
521       if (ValueVT.isFloatingPoint()) {
522         // FP values need to be bitcast, then extended if they are being put
523         // into a larger container.
524         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
525         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
526       }
527       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
528              ValueVT.isInteger() &&
529              "Unknown mismatch!");
530       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
531       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
532       if (PartVT == MVT::x86mmx)
533         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
534     }
535   } else if (PartBits == ValueVT.getSizeInBits()) {
536     // Different types of the same size.
537     assert(NumParts == 1 && PartEVT != ValueVT);
538     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
540     // If the parts cover less bits than value has, truncate the value.
541     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
542            ValueVT.isInteger() &&
543            "Unknown mismatch!");
544     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
545     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
546     if (PartVT == MVT::x86mmx)
547       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
548   }
549 
550   // The value may have changed - recompute ValueVT.
551   ValueVT = Val.getValueType();
552   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
553          "Failed to tile the value with PartVT!");
554 
555   if (NumParts == 1) {
556     if (PartEVT != ValueVT) {
557       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
558                                         "scalar-to-vector conversion failed");
559       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
560     }
561 
562     Parts[0] = Val;
563     return;
564   }
565 
566   // Expand the value into multiple parts.
567   if (NumParts & (NumParts - 1)) {
568     // The number of parts is not a power of 2.  Split off and copy the tail.
569     assert(PartVT.isInteger() && ValueVT.isInteger() &&
570            "Do not know what to expand to!");
571     unsigned RoundParts = llvm::bit_floor(NumParts);
572     unsigned RoundBits = RoundParts * PartBits;
573     unsigned OddParts = NumParts - RoundParts;
574     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
575       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
576 
577     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
578                    CallConv);
579 
580     if (DAG.getDataLayout().isBigEndian())
581       // The odd parts were reversed by getCopyToParts - unreverse them.
582       std::reverse(Parts + RoundParts, Parts + NumParts);
583 
584     NumParts = RoundParts;
585     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
586     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
587   }
588 
589   // The number of parts is a power of 2.  Repeatedly bisect the value using
590   // EXTRACT_ELEMENT.
591   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
592                          EVT::getIntegerVT(*DAG.getContext(),
593                                            ValueVT.getSizeInBits()),
594                          Val);
595 
596   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
597     for (unsigned i = 0; i < NumParts; i += StepSize) {
598       unsigned ThisBits = StepSize * PartBits / 2;
599       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
600       SDValue &Part0 = Parts[i];
601       SDValue &Part1 = Parts[i+StepSize/2];
602 
603       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
604                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
605       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
606                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
607 
608       if (ThisBits == PartBits && ThisVT != PartVT) {
609         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
610         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
611       }
612     }
613   }
614 
615   if (DAG.getDataLayout().isBigEndian())
616     std::reverse(Parts, Parts + OrigNumParts);
617 }
618 
619 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
620                                      const SDLoc &DL, EVT PartVT) {
621   if (!PartVT.isVector())
622     return SDValue();
623 
624   EVT ValueVT = Val.getValueType();
625   ElementCount PartNumElts = PartVT.getVectorElementCount();
626   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
627 
628   // We only support widening vectors with equivalent element types and
629   // fixed/scalable properties. If a target needs to widen a fixed-length type
630   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
631   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
632       PartNumElts.isScalable() != ValueNumElts.isScalable() ||
633       PartVT.getVectorElementType() != ValueVT.getVectorElementType())
634     return SDValue();
635 
636   // Widening a scalable vector to another scalable vector is done by inserting
637   // the vector into a larger undef one.
638   if (PartNumElts.isScalable())
639     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
640                        Val, DAG.getVectorIdxConstant(0, DL));
641 
642   EVT ElementVT = PartVT.getVectorElementType();
643   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
644   // undef elements.
645   SmallVector<SDValue, 16> Ops;
646   DAG.ExtractVectorElements(Val, Ops);
647   SDValue EltUndef = DAG.getUNDEF(ElementVT);
648   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
649 
650   // FIXME: Use CONCAT for 2x -> 4x.
651   return DAG.getBuildVector(PartVT, DL, Ops);
652 }
653 
654 /// getCopyToPartsVector - Create a series of nodes that contain the specified
655 /// value split into legal parts.
656 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
657                                  SDValue Val, SDValue *Parts, unsigned NumParts,
658                                  MVT PartVT, const Value *V,
659                                  std::optional<CallingConv::ID> CallConv) {
660   EVT ValueVT = Val.getValueType();
661   assert(ValueVT.isVector() && "Not a vector");
662   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
663   const bool IsABIRegCopy = CallConv.has_value();
664 
665   if (NumParts == 1) {
666     EVT PartEVT = PartVT;
667     if (PartEVT == ValueVT) {
668       // Nothing to do.
669     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
670       // Bitconvert vector->vector case.
671       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
672     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
673       Val = Widened;
674     } else if (PartVT.isVector() &&
675                PartEVT.getVectorElementType().bitsGE(
676                    ValueVT.getVectorElementType()) &&
677                PartEVT.getVectorElementCount() ==
678                    ValueVT.getVectorElementCount()) {
679 
680       // Promoted vector extract
681       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
682     } else if (PartEVT.isVector() &&
683                PartEVT.getVectorElementType() !=
684                    ValueVT.getVectorElementType() &&
685                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
686                    TargetLowering::TypeWidenVector) {
687       // Combination of widening and promotion.
688       EVT WidenVT =
689           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
690                            PartVT.getVectorElementCount());
691       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
692       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
693     } else {
694       // Don't extract an integer from a float vector. This can happen if the
695       // FP type gets softened to integer and then promoted. The promotion
696       // prevents it from being picked up by the earlier bitcast case.
697       if (ValueVT.getVectorElementCount().isScalar() &&
698           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
699         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
700                           DAG.getVectorIdxConstant(0, DL));
701       } else {
702         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
703         assert(PartVT.getFixedSizeInBits() > ValueSize &&
704                "lossy conversion of vector to scalar type");
705         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
706         Val = DAG.getBitcast(IntermediateType, Val);
707         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
708       }
709     }
710 
711     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
712     Parts[0] = Val;
713     return;
714   }
715 
716   // Handle a multi-element vector.
717   EVT IntermediateVT;
718   MVT RegisterVT;
719   unsigned NumIntermediates;
720   unsigned NumRegs;
721   if (IsABIRegCopy) {
722     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
723         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
724         RegisterVT);
725   } else {
726     NumRegs =
727         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
728                                    NumIntermediates, RegisterVT);
729   }
730 
731   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
732   NumParts = NumRegs; // Silence a compiler warning.
733   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
734 
735   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
736          "Mixing scalable and fixed vectors when copying in parts");
737 
738   std::optional<ElementCount> DestEltCnt;
739 
740   if (IntermediateVT.isVector())
741     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
742   else
743     DestEltCnt = ElementCount::getFixed(NumIntermediates);
744 
745   EVT BuiltVectorTy = EVT::getVectorVT(
746       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
747 
748   if (ValueVT == BuiltVectorTy) {
749     // Nothing to do.
750   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
751     // Bitconvert vector->vector case.
752     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
753   } else {
754     if (BuiltVectorTy.getVectorElementType().bitsGT(
755             ValueVT.getVectorElementType())) {
756       // Integer promotion.
757       ValueVT = EVT::getVectorVT(*DAG.getContext(),
758                                  BuiltVectorTy.getVectorElementType(),
759                                  ValueVT.getVectorElementCount());
760       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
761     }
762 
763     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
764       Val = Widened;
765     }
766   }
767 
768   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
769 
770   // Split the vector into intermediate operands.
771   SmallVector<SDValue, 8> Ops(NumIntermediates);
772   for (unsigned i = 0; i != NumIntermediates; ++i) {
773     if (IntermediateVT.isVector()) {
774       // This does something sensible for scalable vectors - see the
775       // definition of EXTRACT_SUBVECTOR for further details.
776       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
777       Ops[i] =
778           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
779                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
780     } else {
781       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
782                            DAG.getVectorIdxConstant(i, DL));
783     }
784   }
785 
786   // Split the intermediate operands into legal parts.
787   if (NumParts == NumIntermediates) {
788     // If the register was not expanded, promote or copy the value,
789     // as appropriate.
790     for (unsigned i = 0; i != NumParts; ++i)
791       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
792   } else if (NumParts > 0) {
793     // If the intermediate type was expanded, split each the value into
794     // legal parts.
795     assert(NumIntermediates != 0 && "division by zero");
796     assert(NumParts % NumIntermediates == 0 &&
797            "Must expand into a divisible number of parts!");
798     unsigned Factor = NumParts / NumIntermediates;
799     for (unsigned i = 0; i != NumIntermediates; ++i)
800       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
801                      CallConv);
802   }
803 }
804 
805 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
806                            EVT valuevt, std::optional<CallingConv::ID> CC)
807     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
808       RegCount(1, regs.size()), CallConv(CC) {}
809 
810 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
811                            const DataLayout &DL, unsigned Reg, Type *Ty,
812                            std::optional<CallingConv::ID> CC) {
813   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
814 
815   CallConv = CC;
816 
817   for (EVT ValueVT : ValueVTs) {
818     unsigned NumRegs =
819         isABIMangled()
820             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
821             : TLI.getNumRegisters(Context, ValueVT);
822     MVT RegisterVT =
823         isABIMangled()
824             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
825             : TLI.getRegisterType(Context, ValueVT);
826     for (unsigned i = 0; i != NumRegs; ++i)
827       Regs.push_back(Reg + i);
828     RegVTs.push_back(RegisterVT);
829     RegCount.push_back(NumRegs);
830     Reg += NumRegs;
831   }
832 }
833 
834 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
835                                       FunctionLoweringInfo &FuncInfo,
836                                       const SDLoc &dl, SDValue &Chain,
837                                       SDValue *Glue, const Value *V) const {
838   // A Value with type {} or [0 x %t] needs no registers.
839   if (ValueVTs.empty())
840     return SDValue();
841 
842   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
843 
844   // Assemble the legal parts into the final values.
845   SmallVector<SDValue, 4> Values(ValueVTs.size());
846   SmallVector<SDValue, 8> Parts;
847   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
848     // Copy the legal parts from the registers.
849     EVT ValueVT = ValueVTs[Value];
850     unsigned NumRegs = RegCount[Value];
851     MVT RegisterVT = isABIMangled()
852                          ? TLI.getRegisterTypeForCallingConv(
853                                *DAG.getContext(), *CallConv, RegVTs[Value])
854                          : RegVTs[Value];
855 
856     Parts.resize(NumRegs);
857     for (unsigned i = 0; i != NumRegs; ++i) {
858       SDValue P;
859       if (!Glue) {
860         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
861       } else {
862         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
863         *Glue = P.getValue(2);
864       }
865 
866       Chain = P.getValue(1);
867       Parts[i] = P;
868 
869       // If the source register was virtual and if we know something about it,
870       // add an assert node.
871       if (!Register::isVirtualRegister(Regs[Part + i]) ||
872           !RegisterVT.isInteger())
873         continue;
874 
875       const FunctionLoweringInfo::LiveOutInfo *LOI =
876         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
877       if (!LOI)
878         continue;
879 
880       unsigned RegSize = RegisterVT.getScalarSizeInBits();
881       unsigned NumSignBits = LOI->NumSignBits;
882       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
883 
884       if (NumZeroBits == RegSize) {
885         // The current value is a zero.
886         // Explicitly express that as it would be easier for
887         // optimizations to kick in.
888         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
889         continue;
890       }
891 
892       // FIXME: We capture more information than the dag can represent.  For
893       // now, just use the tightest assertzext/assertsext possible.
894       bool isSExt;
895       EVT FromVT(MVT::Other);
896       if (NumZeroBits) {
897         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
898         isSExt = false;
899       } else if (NumSignBits > 1) {
900         FromVT =
901             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
902         isSExt = true;
903       } else {
904         continue;
905       }
906       // Add an assertion node.
907       assert(FromVT != MVT::Other);
908       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
909                              RegisterVT, P, DAG.getValueType(FromVT));
910     }
911 
912     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
913                                      RegisterVT, ValueVT, V, CallConv);
914     Part += NumRegs;
915     Parts.clear();
916   }
917 
918   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
919 }
920 
921 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
922                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
923                                  const Value *V,
924                                  ISD::NodeType PreferredExtendType) const {
925   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
926   ISD::NodeType ExtendKind = PreferredExtendType;
927 
928   // Get the list of the values's legal parts.
929   unsigned NumRegs = Regs.size();
930   SmallVector<SDValue, 8> Parts(NumRegs);
931   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
932     unsigned NumParts = RegCount[Value];
933 
934     MVT RegisterVT = isABIMangled()
935                          ? TLI.getRegisterTypeForCallingConv(
936                                *DAG.getContext(), *CallConv, RegVTs[Value])
937                          : RegVTs[Value];
938 
939     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
940       ExtendKind = ISD::ZERO_EXTEND;
941 
942     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
943                    NumParts, RegisterVT, V, CallConv, ExtendKind);
944     Part += NumParts;
945   }
946 
947   // Copy the parts into the registers.
948   SmallVector<SDValue, 8> Chains(NumRegs);
949   for (unsigned i = 0; i != NumRegs; ++i) {
950     SDValue Part;
951     if (!Glue) {
952       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
953     } else {
954       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
955       *Glue = Part.getValue(1);
956     }
957 
958     Chains[i] = Part.getValue(0);
959   }
960 
961   if (NumRegs == 1 || Glue)
962     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
963     // flagged to it. That is the CopyToReg nodes and the user are considered
964     // a single scheduling unit. If we create a TokenFactor and return it as
965     // chain, then the TokenFactor is both a predecessor (operand) of the
966     // user as well as a successor (the TF operands are flagged to the user).
967     // c1, f1 = CopyToReg
968     // c2, f2 = CopyToReg
969     // c3     = TokenFactor c1, c2
970     // ...
971     //        = op c3, ..., f2
972     Chain = Chains[NumRegs-1];
973   else
974     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
975 }
976 
977 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
978                                         unsigned MatchingIdx, const SDLoc &dl,
979                                         SelectionDAG &DAG,
980                                         std::vector<SDValue> &Ops) const {
981   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
982 
983   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
984   if (HasMatching)
985     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
986   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
987     // Put the register class of the virtual registers in the flag word.  That
988     // way, later passes can recompute register class constraints for inline
989     // assembly as well as normal instructions.
990     // Don't do this for tied operands that can use the regclass information
991     // from the def.
992     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
993     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
994     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
995   }
996 
997   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
998   Ops.push_back(Res);
999 
1000   if (Code == InlineAsm::Kind_Clobber) {
1001     // Clobbers should always have a 1:1 mapping with registers, and may
1002     // reference registers that have illegal (e.g. vector) types. Hence, we
1003     // shouldn't try to apply any sort of splitting logic to them.
1004     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1005            "No 1:1 mapping from clobbers to regs?");
1006     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1007     (void)SP;
1008     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1009       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1010       assert(
1011           (Regs[I] != SP ||
1012            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1013           "If we clobbered the stack pointer, MFI should know about it.");
1014     }
1015     return;
1016   }
1017 
1018   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1019     MVT RegisterVT = RegVTs[Value];
1020     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1021                                            RegisterVT);
1022     for (unsigned i = 0; i != NumRegs; ++i) {
1023       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1024       unsigned TheReg = Regs[Reg++];
1025       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1026     }
1027   }
1028 }
1029 
1030 SmallVector<std::pair<unsigned, TypeSize>, 4>
1031 RegsForValue::getRegsAndSizes() const {
1032   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1033   unsigned I = 0;
1034   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1035     unsigned RegCount = std::get<0>(CountAndVT);
1036     MVT RegisterVT = std::get<1>(CountAndVT);
1037     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1038     for (unsigned E = I + RegCount; I != E; ++I)
1039       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1040   }
1041   return OutVec;
1042 }
1043 
1044 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1045                                AssumptionCache *ac,
1046                                const TargetLibraryInfo *li) {
1047   AA = aa;
1048   AC = ac;
1049   GFI = gfi;
1050   LibInfo = li;
1051   Context = DAG.getContext();
1052   LPadToCallSiteMap.clear();
1053   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1054   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1055       *DAG.getMachineFunction().getFunction().getParent());
1056 }
1057 
1058 void SelectionDAGBuilder::clear() {
1059   NodeMap.clear();
1060   UnusedArgNodeMap.clear();
1061   PendingLoads.clear();
1062   PendingExports.clear();
1063   PendingConstrainedFP.clear();
1064   PendingConstrainedFPStrict.clear();
1065   CurInst = nullptr;
1066   HasTailCall = false;
1067   SDNodeOrder = LowestSDNodeOrder;
1068   StatepointLowering.clear();
1069 }
1070 
1071 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1072   DanglingDebugInfoMap.clear();
1073 }
1074 
1075 // Update DAG root to include dependencies on Pending chains.
1076 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1077   SDValue Root = DAG.getRoot();
1078 
1079   if (Pending.empty())
1080     return Root;
1081 
1082   // Add current root to PendingChains, unless we already indirectly
1083   // depend on it.
1084   if (Root.getOpcode() != ISD::EntryToken) {
1085     unsigned i = 0, e = Pending.size();
1086     for (; i != e; ++i) {
1087       assert(Pending[i].getNode()->getNumOperands() > 1);
1088       if (Pending[i].getNode()->getOperand(0) == Root)
1089         break;  // Don't add the root if we already indirectly depend on it.
1090     }
1091 
1092     if (i == e)
1093       Pending.push_back(Root);
1094   }
1095 
1096   if (Pending.size() == 1)
1097     Root = Pending[0];
1098   else
1099     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1100 
1101   DAG.setRoot(Root);
1102   Pending.clear();
1103   return Root;
1104 }
1105 
1106 SDValue SelectionDAGBuilder::getMemoryRoot() {
1107   return updateRoot(PendingLoads);
1108 }
1109 
1110 SDValue SelectionDAGBuilder::getRoot() {
1111   // Chain up all pending constrained intrinsics together with all
1112   // pending loads, by simply appending them to PendingLoads and
1113   // then calling getMemoryRoot().
1114   PendingLoads.reserve(PendingLoads.size() +
1115                        PendingConstrainedFP.size() +
1116                        PendingConstrainedFPStrict.size());
1117   PendingLoads.append(PendingConstrainedFP.begin(),
1118                       PendingConstrainedFP.end());
1119   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1120                       PendingConstrainedFPStrict.end());
1121   PendingConstrainedFP.clear();
1122   PendingConstrainedFPStrict.clear();
1123   return getMemoryRoot();
1124 }
1125 
1126 SDValue SelectionDAGBuilder::getControlRoot() {
1127   // We need to emit pending fpexcept.strict constrained intrinsics,
1128   // so append them to the PendingExports list.
1129   PendingExports.append(PendingConstrainedFPStrict.begin(),
1130                         PendingConstrainedFPStrict.end());
1131   PendingConstrainedFPStrict.clear();
1132   return updateRoot(PendingExports);
1133 }
1134 
1135 void SelectionDAGBuilder::visit(const Instruction &I) {
1136   // Set up outgoing PHI node register values before emitting the terminator.
1137   if (I.isTerminator()) {
1138     HandlePHINodesInSuccessorBlocks(I.getParent());
1139   }
1140 
1141   // Add SDDbgValue nodes for any var locs here. Do so before updating
1142   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1143   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1144     // Add SDDbgValue nodes for any var locs here. Do so before updating
1145     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1146     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1147          It != End; ++It) {
1148       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1149       dropDanglingDebugInfo(Var, It->Expr);
1150       if (It->Values.isKillLocation(It->Expr)) {
1151         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1152         continue;
1153       }
1154       SmallVector<Value *> Values(It->Values.location_ops());
1155       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1156                             It->Values.hasArgList()))
1157         addDanglingDebugInfo(It, SDNodeOrder);
1158     }
1159   }
1160 
1161   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1162   if (!isa<DbgInfoIntrinsic>(I))
1163     ++SDNodeOrder;
1164 
1165   CurInst = &I;
1166 
1167   // Set inserted listener only if required.
1168   bool NodeInserted = false;
1169   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1170   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1171   if (PCSectionsMD) {
1172     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1173         DAG, [&](SDNode *) { NodeInserted = true; });
1174   }
1175 
1176   visit(I.getOpcode(), I);
1177 
1178   if (!I.isTerminator() && !HasTailCall &&
1179       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1180     CopyToExportRegsIfNeeded(&I);
1181 
1182   // Handle metadata.
1183   if (PCSectionsMD) {
1184     auto It = NodeMap.find(&I);
1185     if (It != NodeMap.end()) {
1186       DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1187     } else if (NodeInserted) {
1188       // This should not happen; if it does, don't let it go unnoticed so we can
1189       // fix it. Relevant visit*() function is probably missing a setValue().
1190       errs() << "warning: loosing !pcsections metadata ["
1191              << I.getModule()->getName() << "]\n";
1192       LLVM_DEBUG(I.dump());
1193       assert(false);
1194     }
1195   }
1196 
1197   CurInst = nullptr;
1198 }
1199 
1200 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1201   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1202 }
1203 
1204 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1205   // Note: this doesn't use InstVisitor, because it has to work with
1206   // ConstantExpr's in addition to instructions.
1207   switch (Opcode) {
1208   default: llvm_unreachable("Unknown instruction type encountered!");
1209     // Build the switch statement using the Instruction.def file.
1210 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1211     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1212 #include "llvm/IR/Instruction.def"
1213   }
1214 }
1215 
1216 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1217                                             DILocalVariable *Variable,
1218                                             DebugLoc DL, unsigned Order,
1219                                             RawLocationWrapper Values,
1220                                             DIExpression *Expression) {
1221   if (!Values.hasArgList())
1222     return false;
1223   // For variadic dbg_values we will now insert an undef.
1224   // FIXME: We can potentially recover these!
1225   SmallVector<SDDbgOperand, 2> Locs;
1226   for (const Value *V : Values.location_ops()) {
1227     auto *Undef = UndefValue::get(V->getType());
1228     Locs.push_back(SDDbgOperand::fromConst(Undef));
1229   }
1230   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1231                                         /*IsIndirect=*/false, DL, Order,
1232                                         /*IsVariadic=*/true);
1233   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1234   return true;
1235 }
1236 
1237 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc,
1238                                                unsigned Order) {
1239   if (!handleDanglingVariadicDebugInfo(
1240           DAG,
1241           const_cast<DILocalVariable *>(DAG.getFunctionVarLocs()
1242                                             ->getVariable(VarLoc->VariableID)
1243                                             .getVariable()),
1244           VarLoc->DL, Order, VarLoc->Values, VarLoc->Expr)) {
1245     DanglingDebugInfoMap[VarLoc->Values.getVariableLocationOp(0)].emplace_back(
1246         VarLoc, Order);
1247   }
1248 }
1249 
1250 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1251                                                unsigned Order) {
1252   // We treat variadic dbg_values differently at this stage.
1253   if (!handleDanglingVariadicDebugInfo(
1254           DAG, DI->getVariable(), DI->getDebugLoc(), Order,
1255           DI->getWrappedLocation(), DI->getExpression())) {
1256     // TODO: Dangling debug info will eventually either be resolved or produce
1257     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1258     // between the original dbg.value location and its resolved DBG_VALUE,
1259     // which we should ideally fill with an extra Undef DBG_VALUE.
1260     assert(DI->getNumVariableLocationOps() == 1 &&
1261            "DbgValueInst without an ArgList should have a single location "
1262            "operand.");
1263     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order);
1264   }
1265 }
1266 
1267 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1268                                                 const DIExpression *Expr) {
1269   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1270     DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs());
1271     DIExpression *DanglingExpr = DDI.getExpression();
1272     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1273       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI)
1274                         << "\n");
1275       return true;
1276     }
1277     return false;
1278   };
1279 
1280   for (auto &DDIMI : DanglingDebugInfoMap) {
1281     DanglingDebugInfoVector &DDIV = DDIMI.second;
1282 
1283     // If debug info is to be dropped, run it through final checks to see
1284     // whether it can be salvaged.
1285     for (auto &DDI : DDIV)
1286       if (isMatchingDbgValue(DDI))
1287         salvageUnresolvedDbgValue(DDI);
1288 
1289     erase_if(DDIV, isMatchingDbgValue);
1290   }
1291 }
1292 
1293 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1294 // generate the debug data structures now that we've seen its definition.
1295 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1296                                                    SDValue Val) {
1297   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1298   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1299     return;
1300 
1301   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1302   for (auto &DDI : DDIV) {
1303     DebugLoc DL = DDI.getDebugLoc();
1304     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1305     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1306     DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs());
1307     DIExpression *Expr = DDI.getExpression();
1308     assert(Variable->isValidLocationForIntrinsic(DL) &&
1309            "Expected inlined-at fields to agree");
1310     SDDbgValue *SDV;
1311     if (Val.getNode()) {
1312       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1313       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1314       // we couldn't resolve it directly when examining the DbgValue intrinsic
1315       // in the first place we should not be more successful here). Unless we
1316       // have some test case that prove this to be correct we should avoid
1317       // calling EmitFuncArgumentDbgValue here.
1318       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1319                                     FuncArgumentDbgValueKind::Value, Val)) {
1320         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI)
1321                           << "\n");
1322         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1323         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1324         // inserted after the definition of Val when emitting the instructions
1325         // after ISel. An alternative could be to teach
1326         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1327         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1328                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1329                    << ValSDNodeOrder << "\n");
1330         SDV = getDbgValue(Val, Variable, Expr, DL,
1331                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1332         DAG.AddDbgValue(SDV, false);
1333       } else
1334         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1335                           << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n");
1336     } else {
1337       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n");
1338       auto Undef = UndefValue::get(V->getType());
1339       auto SDV =
1340           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1341       DAG.AddDbgValue(SDV, false);
1342     }
1343   }
1344   DDIV.clear();
1345 }
1346 
1347 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1348   // TODO: For the variadic implementation, instead of only checking the fail
1349   // state of `handleDebugValue`, we need know specifically which values were
1350   // invalid, so that we attempt to salvage only those values when processing
1351   // a DIArgList.
1352   Value *V = DDI.getVariableLocationOp(0);
1353   Value *OrigV = V;
1354   DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs());
1355   DIExpression *Expr = DDI.getExpression();
1356   DebugLoc DL = DDI.getDebugLoc();
1357   unsigned SDOrder = DDI.getSDNodeOrder();
1358 
1359   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1360   // that DW_OP_stack_value is desired.
1361   bool StackValue = true;
1362 
1363   // Can this Value can be encoded without any further work?
1364   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1365     return;
1366 
1367   // Attempt to salvage back through as many instructions as possible. Bail if
1368   // a non-instruction is seen, such as a constant expression or global
1369   // variable. FIXME: Further work could recover those too.
1370   while (isa<Instruction>(V)) {
1371     Instruction &VAsInst = *cast<Instruction>(V);
1372     // Temporary "0", awaiting real implementation.
1373     SmallVector<uint64_t, 16> Ops;
1374     SmallVector<Value *, 4> AdditionalValues;
1375     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1376                              AdditionalValues);
1377     // If we cannot salvage any further, and haven't yet found a suitable debug
1378     // expression, bail out.
1379     if (!V)
1380       break;
1381 
1382     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1383     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1384     // here for variadic dbg_values, remove that condition.
1385     if (!AdditionalValues.empty())
1386       break;
1387 
1388     // New value and expr now represent this debuginfo.
1389     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1390 
1391     // Some kind of simplification occurred: check whether the operand of the
1392     // salvaged debug expression can be encoded in this DAG.
1393     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1394       LLVM_DEBUG(
1395           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1396                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1397       return;
1398     }
1399   }
1400 
1401   // This was the final opportunity to salvage this debug information, and it
1402   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1403   // any earlier variable location.
1404   assert(OrigV && "V shouldn't be null");
1405   auto *Undef = UndefValue::get(OrigV->getType());
1406   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1407   DAG.AddDbgValue(SDV, false);
1408   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << printDDI(DDI)
1409                     << "\n");
1410 }
1411 
1412 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1413                                                DIExpression *Expr,
1414                                                DebugLoc DbgLoc,
1415                                                unsigned Order) {
1416   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1417   DIExpression *NewExpr =
1418       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1419   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1420                    /*IsVariadic*/ false);
1421 }
1422 
1423 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1424                                            DILocalVariable *Var,
1425                                            DIExpression *Expr, DebugLoc DbgLoc,
1426                                            unsigned Order, bool IsVariadic) {
1427   if (Values.empty())
1428     return true;
1429   SmallVector<SDDbgOperand> LocationOps;
1430   SmallVector<SDNode *> Dependencies;
1431   for (const Value *V : Values) {
1432     // Constant value.
1433     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1434         isa<ConstantPointerNull>(V)) {
1435       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1436       continue;
1437     }
1438 
1439     // Look through IntToPtr constants.
1440     if (auto *CE = dyn_cast<ConstantExpr>(V))
1441       if (CE->getOpcode() == Instruction::IntToPtr) {
1442         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1443         continue;
1444       }
1445 
1446     // If the Value is a frame index, we can create a FrameIndex debug value
1447     // without relying on the DAG at all.
1448     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1449       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1450       if (SI != FuncInfo.StaticAllocaMap.end()) {
1451         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1452         continue;
1453       }
1454     }
1455 
1456     // Do not use getValue() in here; we don't want to generate code at
1457     // this point if it hasn't been done yet.
1458     SDValue N = NodeMap[V];
1459     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1460       N = UnusedArgNodeMap[V];
1461     if (N.getNode()) {
1462       // Only emit func arg dbg value for non-variadic dbg.values for now.
1463       if (!IsVariadic &&
1464           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1465                                    FuncArgumentDbgValueKind::Value, N))
1466         return true;
1467       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1468         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1469         // describe stack slot locations.
1470         //
1471         // Consider "int x = 0; int *px = &x;". There are two kinds of
1472         // interesting debug values here after optimization:
1473         //
1474         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1475         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1476         //
1477         // Both describe the direct values of their associated variables.
1478         Dependencies.push_back(N.getNode());
1479         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1480         continue;
1481       }
1482       LocationOps.emplace_back(
1483           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1484       continue;
1485     }
1486 
1487     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1488     // Special rules apply for the first dbg.values of parameter variables in a
1489     // function. Identify them by the fact they reference Argument Values, that
1490     // they're parameters, and they are parameters of the current function. We
1491     // need to let them dangle until they get an SDNode.
1492     bool IsParamOfFunc =
1493         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1494     if (IsParamOfFunc)
1495       return false;
1496 
1497     // The value is not used in this block yet (or it would have an SDNode).
1498     // We still want the value to appear for the user if possible -- if it has
1499     // an associated VReg, we can refer to that instead.
1500     auto VMI = FuncInfo.ValueMap.find(V);
1501     if (VMI != FuncInfo.ValueMap.end()) {
1502       unsigned Reg = VMI->second;
1503       // If this is a PHI node, it may be split up into several MI PHI nodes
1504       // (in FunctionLoweringInfo::set).
1505       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1506                        V->getType(), std::nullopt);
1507       if (RFV.occupiesMultipleRegs()) {
1508         // FIXME: We could potentially support variadic dbg_values here.
1509         if (IsVariadic)
1510           return false;
1511         unsigned Offset = 0;
1512         unsigned BitsToDescribe = 0;
1513         if (auto VarSize = Var->getSizeInBits())
1514           BitsToDescribe = *VarSize;
1515         if (auto Fragment = Expr->getFragmentInfo())
1516           BitsToDescribe = Fragment->SizeInBits;
1517         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1518           // Bail out if all bits are described already.
1519           if (Offset >= BitsToDescribe)
1520             break;
1521           // TODO: handle scalable vectors.
1522           unsigned RegisterSize = RegAndSize.second;
1523           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1524                                       ? BitsToDescribe - Offset
1525                                       : RegisterSize;
1526           auto FragmentExpr = DIExpression::createFragmentExpression(
1527               Expr, Offset, FragmentSize);
1528           if (!FragmentExpr)
1529             continue;
1530           SDDbgValue *SDV = DAG.getVRegDbgValue(
1531               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1532           DAG.AddDbgValue(SDV, false);
1533           Offset += RegisterSize;
1534         }
1535         return true;
1536       }
1537       // We can use simple vreg locations for variadic dbg_values as well.
1538       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1539       continue;
1540     }
1541     // We failed to create a SDDbgOperand for V.
1542     return false;
1543   }
1544 
1545   // We have created a SDDbgOperand for each Value in Values.
1546   // Should use Order instead of SDNodeOrder?
1547   assert(!LocationOps.empty());
1548   SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1549                                         /*IsIndirect=*/false, DbgLoc,
1550                                         SDNodeOrder, IsVariadic);
1551   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1552   return true;
1553 }
1554 
1555 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1556   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1557   for (auto &Pair : DanglingDebugInfoMap)
1558     for (auto &DDI : Pair.second)
1559       salvageUnresolvedDbgValue(DDI);
1560   clearDanglingDebugInfo();
1561 }
1562 
1563 /// getCopyFromRegs - If there was virtual register allocated for the value V
1564 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1565 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1566   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1567   SDValue Result;
1568 
1569   if (It != FuncInfo.ValueMap.end()) {
1570     Register InReg = It->second;
1571 
1572     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1573                      DAG.getDataLayout(), InReg, Ty,
1574                      std::nullopt); // This is not an ABI copy.
1575     SDValue Chain = DAG.getEntryNode();
1576     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1577                                  V);
1578     resolveDanglingDebugInfo(V, Result);
1579   }
1580 
1581   return Result;
1582 }
1583 
1584 /// getValue - Return an SDValue for the given Value.
1585 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1586   // If we already have an SDValue for this value, use it. It's important
1587   // to do this first, so that we don't create a CopyFromReg if we already
1588   // have a regular SDValue.
1589   SDValue &N = NodeMap[V];
1590   if (N.getNode()) return N;
1591 
1592   // If there's a virtual register allocated and initialized for this
1593   // value, use it.
1594   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1595     return copyFromReg;
1596 
1597   // Otherwise create a new SDValue and remember it.
1598   SDValue Val = getValueImpl(V);
1599   NodeMap[V] = Val;
1600   resolveDanglingDebugInfo(V, Val);
1601   return Val;
1602 }
1603 
1604 /// getNonRegisterValue - Return an SDValue for the given Value, but
1605 /// don't look in FuncInfo.ValueMap for a virtual register.
1606 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1607   // If we already have an SDValue for this value, use it.
1608   SDValue &N = NodeMap[V];
1609   if (N.getNode()) {
1610     if (isIntOrFPConstant(N)) {
1611       // Remove the debug location from the node as the node is about to be used
1612       // in a location which may differ from the original debug location.  This
1613       // is relevant to Constant and ConstantFP nodes because they can appear
1614       // as constant expressions inside PHI nodes.
1615       N->setDebugLoc(DebugLoc());
1616     }
1617     return N;
1618   }
1619 
1620   // Otherwise create a new SDValue and remember it.
1621   SDValue Val = getValueImpl(V);
1622   NodeMap[V] = Val;
1623   resolveDanglingDebugInfo(V, Val);
1624   return Val;
1625 }
1626 
1627 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1628 /// Create an SDValue for the given value.
1629 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1630   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1631 
1632   if (const Constant *C = dyn_cast<Constant>(V)) {
1633     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1634 
1635     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1636       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1637 
1638     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1639       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1640 
1641     if (isa<ConstantPointerNull>(C)) {
1642       unsigned AS = V->getType()->getPointerAddressSpace();
1643       return DAG.getConstant(0, getCurSDLoc(),
1644                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1645     }
1646 
1647     if (match(C, m_VScale()))
1648       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1649 
1650     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1651       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1652 
1653     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1654       return DAG.getUNDEF(VT);
1655 
1656     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1657       visit(CE->getOpcode(), *CE);
1658       SDValue N1 = NodeMap[V];
1659       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1660       return N1;
1661     }
1662 
1663     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1664       SmallVector<SDValue, 4> Constants;
1665       for (const Use &U : C->operands()) {
1666         SDNode *Val = getValue(U).getNode();
1667         // If the operand is an empty aggregate, there are no values.
1668         if (!Val) continue;
1669         // Add each leaf value from the operand to the Constants list
1670         // to form a flattened list of all the values.
1671         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1672           Constants.push_back(SDValue(Val, i));
1673       }
1674 
1675       return DAG.getMergeValues(Constants, getCurSDLoc());
1676     }
1677 
1678     if (const ConstantDataSequential *CDS =
1679           dyn_cast<ConstantDataSequential>(C)) {
1680       SmallVector<SDValue, 4> Ops;
1681       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1682         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1683         // Add each leaf value from the operand to the Constants list
1684         // to form a flattened list of all the values.
1685         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1686           Ops.push_back(SDValue(Val, i));
1687       }
1688 
1689       if (isa<ArrayType>(CDS->getType()))
1690         return DAG.getMergeValues(Ops, getCurSDLoc());
1691       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1692     }
1693 
1694     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1695       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1696              "Unknown struct or array constant!");
1697 
1698       SmallVector<EVT, 4> ValueVTs;
1699       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1700       unsigned NumElts = ValueVTs.size();
1701       if (NumElts == 0)
1702         return SDValue(); // empty struct
1703       SmallVector<SDValue, 4> Constants(NumElts);
1704       for (unsigned i = 0; i != NumElts; ++i) {
1705         EVT EltVT = ValueVTs[i];
1706         if (isa<UndefValue>(C))
1707           Constants[i] = DAG.getUNDEF(EltVT);
1708         else if (EltVT.isFloatingPoint())
1709           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1710         else
1711           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1712       }
1713 
1714       return DAG.getMergeValues(Constants, getCurSDLoc());
1715     }
1716 
1717     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1718       return DAG.getBlockAddress(BA, VT);
1719 
1720     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1721       return getValue(Equiv->getGlobalValue());
1722 
1723     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1724       return getValue(NC->getGlobalValue());
1725 
1726     VectorType *VecTy = cast<VectorType>(V->getType());
1727 
1728     // Now that we know the number and type of the elements, get that number of
1729     // elements into the Ops array based on what kind of constant it is.
1730     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1731       SmallVector<SDValue, 16> Ops;
1732       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1733       for (unsigned i = 0; i != NumElements; ++i)
1734         Ops.push_back(getValue(CV->getOperand(i)));
1735 
1736       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1737     }
1738 
1739     if (isa<ConstantAggregateZero>(C)) {
1740       EVT EltVT =
1741           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1742 
1743       SDValue Op;
1744       if (EltVT.isFloatingPoint())
1745         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1746       else
1747         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1748 
1749       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1750     }
1751 
1752     llvm_unreachable("Unknown vector constant");
1753   }
1754 
1755   // If this is a static alloca, generate it as the frameindex instead of
1756   // computation.
1757   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1758     DenseMap<const AllocaInst*, int>::iterator SI =
1759       FuncInfo.StaticAllocaMap.find(AI);
1760     if (SI != FuncInfo.StaticAllocaMap.end())
1761       return DAG.getFrameIndex(
1762           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1763   }
1764 
1765   // If this is an instruction which fast-isel has deferred, select it now.
1766   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1767     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1768 
1769     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1770                      Inst->getType(), std::nullopt);
1771     SDValue Chain = DAG.getEntryNode();
1772     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1773   }
1774 
1775   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1776     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1777 
1778   if (const auto *BB = dyn_cast<BasicBlock>(V))
1779     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1780 
1781   llvm_unreachable("Can't get register for value!");
1782 }
1783 
1784 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1785   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1786   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1787   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1788   bool IsSEH = isAsynchronousEHPersonality(Pers);
1789   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1790   if (!IsSEH)
1791     CatchPadMBB->setIsEHScopeEntry();
1792   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1793   if (IsMSVCCXX || IsCoreCLR)
1794     CatchPadMBB->setIsEHFuncletEntry();
1795 }
1796 
1797 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1798   // Update machine-CFG edge.
1799   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1800   FuncInfo.MBB->addSuccessor(TargetMBB);
1801   TargetMBB->setIsEHCatchretTarget(true);
1802   DAG.getMachineFunction().setHasEHCatchret(true);
1803 
1804   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1805   bool IsSEH = isAsynchronousEHPersonality(Pers);
1806   if (IsSEH) {
1807     // If this is not a fall-through branch or optimizations are switched off,
1808     // emit the branch.
1809     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1810         TM.getOptLevel() == CodeGenOpt::None)
1811       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1812                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1813     return;
1814   }
1815 
1816   // Figure out the funclet membership for the catchret's successor.
1817   // This will be used by the FuncletLayout pass to determine how to order the
1818   // BB's.
1819   // A 'catchret' returns to the outer scope's color.
1820   Value *ParentPad = I.getCatchSwitchParentPad();
1821   const BasicBlock *SuccessorColor;
1822   if (isa<ConstantTokenNone>(ParentPad))
1823     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1824   else
1825     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1826   assert(SuccessorColor && "No parent funclet for catchret!");
1827   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1828   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1829 
1830   // Create the terminator node.
1831   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1832                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1833                             DAG.getBasicBlock(SuccessorColorMBB));
1834   DAG.setRoot(Ret);
1835 }
1836 
1837 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1838   // Don't emit any special code for the cleanuppad instruction. It just marks
1839   // the start of an EH scope/funclet.
1840   FuncInfo.MBB->setIsEHScopeEntry();
1841   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1842   if (Pers != EHPersonality::Wasm_CXX) {
1843     FuncInfo.MBB->setIsEHFuncletEntry();
1844     FuncInfo.MBB->setIsCleanupFuncletEntry();
1845   }
1846 }
1847 
1848 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1849 // not match, it is OK to add only the first unwind destination catchpad to the
1850 // successors, because there will be at least one invoke instruction within the
1851 // catch scope that points to the next unwind destination, if one exists, so
1852 // CFGSort cannot mess up with BB sorting order.
1853 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1854 // call within them, and catchpads only consisting of 'catch (...)' have a
1855 // '__cxa_end_catch' call within them, both of which generate invokes in case
1856 // the next unwind destination exists, i.e., the next unwind destination is not
1857 // the caller.)
1858 //
1859 // Having at most one EH pad successor is also simpler and helps later
1860 // transformations.
1861 //
1862 // For example,
1863 // current:
1864 //   invoke void @foo to ... unwind label %catch.dispatch
1865 // catch.dispatch:
1866 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1867 // catch.start:
1868 //   ...
1869 //   ... in this BB or some other child BB dominated by this BB there will be an
1870 //   invoke that points to 'next' BB as an unwind destination
1871 //
1872 // next: ; We don't need to add this to 'current' BB's successor
1873 //   ...
1874 static void findWasmUnwindDestinations(
1875     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1876     BranchProbability Prob,
1877     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1878         &UnwindDests) {
1879   while (EHPadBB) {
1880     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1881     if (isa<CleanupPadInst>(Pad)) {
1882       // Stop on cleanup pads.
1883       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1884       UnwindDests.back().first->setIsEHScopeEntry();
1885       break;
1886     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1887       // Add the catchpad handlers to the possible destinations. We don't
1888       // continue to the unwind destination of the catchswitch for wasm.
1889       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1890         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1891         UnwindDests.back().first->setIsEHScopeEntry();
1892       }
1893       break;
1894     } else {
1895       continue;
1896     }
1897   }
1898 }
1899 
1900 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1901 /// many places it could ultimately go. In the IR, we have a single unwind
1902 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1903 /// This function skips over imaginary basic blocks that hold catchswitch
1904 /// instructions, and finds all the "real" machine
1905 /// basic block destinations. As those destinations may not be successors of
1906 /// EHPadBB, here we also calculate the edge probability to those destinations.
1907 /// The passed-in Prob is the edge probability to EHPadBB.
1908 static void findUnwindDestinations(
1909     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1910     BranchProbability Prob,
1911     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1912         &UnwindDests) {
1913   EHPersonality Personality =
1914     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1915   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1916   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1917   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1918   bool IsSEH = isAsynchronousEHPersonality(Personality);
1919 
1920   if (IsWasmCXX) {
1921     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1922     assert(UnwindDests.size() <= 1 &&
1923            "There should be at most one unwind destination for wasm");
1924     return;
1925   }
1926 
1927   while (EHPadBB) {
1928     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1929     BasicBlock *NewEHPadBB = nullptr;
1930     if (isa<LandingPadInst>(Pad)) {
1931       // Stop on landingpads. They are not funclets.
1932       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1933       break;
1934     } else if (isa<CleanupPadInst>(Pad)) {
1935       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1936       // personalities.
1937       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1938       UnwindDests.back().first->setIsEHScopeEntry();
1939       UnwindDests.back().first->setIsEHFuncletEntry();
1940       break;
1941     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1942       // Add the catchpad handlers to the possible destinations.
1943       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1944         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1945         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1946         if (IsMSVCCXX || IsCoreCLR)
1947           UnwindDests.back().first->setIsEHFuncletEntry();
1948         if (!IsSEH)
1949           UnwindDests.back().first->setIsEHScopeEntry();
1950       }
1951       NewEHPadBB = CatchSwitch->getUnwindDest();
1952     } else {
1953       continue;
1954     }
1955 
1956     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1957     if (BPI && NewEHPadBB)
1958       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1959     EHPadBB = NewEHPadBB;
1960   }
1961 }
1962 
1963 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1964   // Update successor info.
1965   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1966   auto UnwindDest = I.getUnwindDest();
1967   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1968   BranchProbability UnwindDestProb =
1969       (BPI && UnwindDest)
1970           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1971           : BranchProbability::getZero();
1972   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1973   for (auto &UnwindDest : UnwindDests) {
1974     UnwindDest.first->setIsEHPad();
1975     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1976   }
1977   FuncInfo.MBB->normalizeSuccProbs();
1978 
1979   // Create the terminator node.
1980   SDValue Ret =
1981       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1982   DAG.setRoot(Ret);
1983 }
1984 
1985 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1986   report_fatal_error("visitCatchSwitch not yet implemented!");
1987 }
1988 
1989 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1990   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1991   auto &DL = DAG.getDataLayout();
1992   SDValue Chain = getControlRoot();
1993   SmallVector<ISD::OutputArg, 8> Outs;
1994   SmallVector<SDValue, 8> OutVals;
1995 
1996   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1997   // lower
1998   //
1999   //   %val = call <ty> @llvm.experimental.deoptimize()
2000   //   ret <ty> %val
2001   //
2002   // differently.
2003   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2004     LowerDeoptimizingReturn();
2005     return;
2006   }
2007 
2008   if (!FuncInfo.CanLowerReturn) {
2009     unsigned DemoteReg = FuncInfo.DemoteRegister;
2010     const Function *F = I.getParent()->getParent();
2011 
2012     // Emit a store of the return value through the virtual register.
2013     // Leave Outs empty so that LowerReturn won't try to load return
2014     // registers the usual way.
2015     SmallVector<EVT, 1> PtrValueVTs;
2016     ComputeValueVTs(TLI, DL,
2017                     F->getReturnType()->getPointerTo(
2018                         DAG.getDataLayout().getAllocaAddrSpace()),
2019                     PtrValueVTs);
2020 
2021     SDValue RetPtr =
2022         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2023     SDValue RetOp = getValue(I.getOperand(0));
2024 
2025     SmallVector<EVT, 4> ValueVTs, MemVTs;
2026     SmallVector<uint64_t, 4> Offsets;
2027     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2028                     &Offsets);
2029     unsigned NumValues = ValueVTs.size();
2030 
2031     SmallVector<SDValue, 4> Chains(NumValues);
2032     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2033     for (unsigned i = 0; i != NumValues; ++i) {
2034       // An aggregate return value cannot wrap around the address space, so
2035       // offsets to its parts don't wrap either.
2036       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2037                                            TypeSize::Fixed(Offsets[i]));
2038 
2039       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2040       if (MemVTs[i] != ValueVTs[i])
2041         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2042       Chains[i] = DAG.getStore(
2043           Chain, getCurSDLoc(), Val,
2044           // FIXME: better loc info would be nice.
2045           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2046           commonAlignment(BaseAlign, Offsets[i]));
2047     }
2048 
2049     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2050                         MVT::Other, Chains);
2051   } else if (I.getNumOperands() != 0) {
2052     SmallVector<EVT, 4> ValueVTs;
2053     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2054     unsigned NumValues = ValueVTs.size();
2055     if (NumValues) {
2056       SDValue RetOp = getValue(I.getOperand(0));
2057 
2058       const Function *F = I.getParent()->getParent();
2059 
2060       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2061           I.getOperand(0)->getType(), F->getCallingConv(),
2062           /*IsVarArg*/ false, DL);
2063 
2064       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2065       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2066         ExtendKind = ISD::SIGN_EXTEND;
2067       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2068         ExtendKind = ISD::ZERO_EXTEND;
2069 
2070       LLVMContext &Context = F->getContext();
2071       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2072 
2073       for (unsigned j = 0; j != NumValues; ++j) {
2074         EVT VT = ValueVTs[j];
2075 
2076         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2077           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2078 
2079         CallingConv::ID CC = F->getCallingConv();
2080 
2081         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2082         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2083         SmallVector<SDValue, 4> Parts(NumParts);
2084         getCopyToParts(DAG, getCurSDLoc(),
2085                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2086                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2087 
2088         // 'inreg' on function refers to return value
2089         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2090         if (RetInReg)
2091           Flags.setInReg();
2092 
2093         if (I.getOperand(0)->getType()->isPointerTy()) {
2094           Flags.setPointer();
2095           Flags.setPointerAddrSpace(
2096               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2097         }
2098 
2099         if (NeedsRegBlock) {
2100           Flags.setInConsecutiveRegs();
2101           if (j == NumValues - 1)
2102             Flags.setInConsecutiveRegsLast();
2103         }
2104 
2105         // Propagate extension type if any
2106         if (ExtendKind == ISD::SIGN_EXTEND)
2107           Flags.setSExt();
2108         else if (ExtendKind == ISD::ZERO_EXTEND)
2109           Flags.setZExt();
2110 
2111         for (unsigned i = 0; i < NumParts; ++i) {
2112           Outs.push_back(ISD::OutputArg(Flags,
2113                                         Parts[i].getValueType().getSimpleVT(),
2114                                         VT, /*isfixed=*/true, 0, 0));
2115           OutVals.push_back(Parts[i]);
2116         }
2117       }
2118     }
2119   }
2120 
2121   // Push in swifterror virtual register as the last element of Outs. This makes
2122   // sure swifterror virtual register will be returned in the swifterror
2123   // physical register.
2124   const Function *F = I.getParent()->getParent();
2125   if (TLI.supportSwiftError() &&
2126       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2127     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2128     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2129     Flags.setSwiftError();
2130     Outs.push_back(ISD::OutputArg(
2131         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2132         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2133     // Create SDNode for the swifterror virtual register.
2134     OutVals.push_back(
2135         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2136                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2137                         EVT(TLI.getPointerTy(DL))));
2138   }
2139 
2140   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2141   CallingConv::ID CallConv =
2142     DAG.getMachineFunction().getFunction().getCallingConv();
2143   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2144       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2145 
2146   // Verify that the target's LowerReturn behaved as expected.
2147   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2148          "LowerReturn didn't return a valid chain!");
2149 
2150   // Update the DAG with the new chain value resulting from return lowering.
2151   DAG.setRoot(Chain);
2152 }
2153 
2154 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2155 /// created for it, emit nodes to copy the value into the virtual
2156 /// registers.
2157 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2158   // Skip empty types
2159   if (V->getType()->isEmptyTy())
2160     return;
2161 
2162   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2163   if (VMI != FuncInfo.ValueMap.end()) {
2164     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2165            "Unused value assigned virtual registers!");
2166     CopyValueToVirtualRegister(V, VMI->second);
2167   }
2168 }
2169 
2170 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2171 /// the current basic block, add it to ValueMap now so that we'll get a
2172 /// CopyTo/FromReg.
2173 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2174   // No need to export constants.
2175   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2176 
2177   // Already exported?
2178   if (FuncInfo.isExportedInst(V)) return;
2179 
2180   Register Reg = FuncInfo.InitializeRegForValue(V);
2181   CopyValueToVirtualRegister(V, Reg);
2182 }
2183 
2184 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2185                                                      const BasicBlock *FromBB) {
2186   // The operands of the setcc have to be in this block.  We don't know
2187   // how to export them from some other block.
2188   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2189     // Can export from current BB.
2190     if (VI->getParent() == FromBB)
2191       return true;
2192 
2193     // Is already exported, noop.
2194     return FuncInfo.isExportedInst(V);
2195   }
2196 
2197   // If this is an argument, we can export it if the BB is the entry block or
2198   // if it is already exported.
2199   if (isa<Argument>(V)) {
2200     if (FromBB->isEntryBlock())
2201       return true;
2202 
2203     // Otherwise, can only export this if it is already exported.
2204     return FuncInfo.isExportedInst(V);
2205   }
2206 
2207   // Otherwise, constants can always be exported.
2208   return true;
2209 }
2210 
2211 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2212 BranchProbability
2213 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2214                                         const MachineBasicBlock *Dst) const {
2215   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2216   const BasicBlock *SrcBB = Src->getBasicBlock();
2217   const BasicBlock *DstBB = Dst->getBasicBlock();
2218   if (!BPI) {
2219     // If BPI is not available, set the default probability as 1 / N, where N is
2220     // the number of successors.
2221     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2222     return BranchProbability(1, SuccSize);
2223   }
2224   return BPI->getEdgeProbability(SrcBB, DstBB);
2225 }
2226 
2227 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2228                                                MachineBasicBlock *Dst,
2229                                                BranchProbability Prob) {
2230   if (!FuncInfo.BPI)
2231     Src->addSuccessorWithoutProb(Dst);
2232   else {
2233     if (Prob.isUnknown())
2234       Prob = getEdgeProbability(Src, Dst);
2235     Src->addSuccessor(Dst, Prob);
2236   }
2237 }
2238 
2239 static bool InBlock(const Value *V, const BasicBlock *BB) {
2240   if (const Instruction *I = dyn_cast<Instruction>(V))
2241     return I->getParent() == BB;
2242   return true;
2243 }
2244 
2245 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2246 /// This function emits a branch and is used at the leaves of an OR or an
2247 /// AND operator tree.
2248 void
2249 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2250                                                   MachineBasicBlock *TBB,
2251                                                   MachineBasicBlock *FBB,
2252                                                   MachineBasicBlock *CurBB,
2253                                                   MachineBasicBlock *SwitchBB,
2254                                                   BranchProbability TProb,
2255                                                   BranchProbability FProb,
2256                                                   bool InvertCond) {
2257   const BasicBlock *BB = CurBB->getBasicBlock();
2258 
2259   // If the leaf of the tree is a comparison, merge the condition into
2260   // the caseblock.
2261   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2262     // The operands of the cmp have to be in this block.  We don't know
2263     // how to export them from some other block.  If this is the first block
2264     // of the sequence, no exporting is needed.
2265     if (CurBB == SwitchBB ||
2266         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2267          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2268       ISD::CondCode Condition;
2269       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2270         ICmpInst::Predicate Pred =
2271             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2272         Condition = getICmpCondCode(Pred);
2273       } else {
2274         const FCmpInst *FC = cast<FCmpInst>(Cond);
2275         FCmpInst::Predicate Pred =
2276             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2277         Condition = getFCmpCondCode(Pred);
2278         if (TM.Options.NoNaNsFPMath)
2279           Condition = getFCmpCodeWithoutNaN(Condition);
2280       }
2281 
2282       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2283                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2284       SL->SwitchCases.push_back(CB);
2285       return;
2286     }
2287   }
2288 
2289   // Create a CaseBlock record representing this branch.
2290   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2291   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2292                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2293   SL->SwitchCases.push_back(CB);
2294 }
2295 
2296 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2297                                                MachineBasicBlock *TBB,
2298                                                MachineBasicBlock *FBB,
2299                                                MachineBasicBlock *CurBB,
2300                                                MachineBasicBlock *SwitchBB,
2301                                                Instruction::BinaryOps Opc,
2302                                                BranchProbability TProb,
2303                                                BranchProbability FProb,
2304                                                bool InvertCond) {
2305   // Skip over not part of the tree and remember to invert op and operands at
2306   // next level.
2307   Value *NotCond;
2308   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2309       InBlock(NotCond, CurBB->getBasicBlock())) {
2310     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2311                          !InvertCond);
2312     return;
2313   }
2314 
2315   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2316   const Value *BOpOp0, *BOpOp1;
2317   // Compute the effective opcode for Cond, taking into account whether it needs
2318   // to be inverted, e.g.
2319   //   and (not (or A, B)), C
2320   // gets lowered as
2321   //   and (and (not A, not B), C)
2322   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2323   if (BOp) {
2324     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2325                ? Instruction::And
2326                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2327                       ? Instruction::Or
2328                       : (Instruction::BinaryOps)0);
2329     if (InvertCond) {
2330       if (BOpc == Instruction::And)
2331         BOpc = Instruction::Or;
2332       else if (BOpc == Instruction::Or)
2333         BOpc = Instruction::And;
2334     }
2335   }
2336 
2337   // If this node is not part of the or/and tree, emit it as a branch.
2338   // Note that all nodes in the tree should have same opcode.
2339   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2340   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2341       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2342       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2343     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2344                                  TProb, FProb, InvertCond);
2345     return;
2346   }
2347 
2348   //  Create TmpBB after CurBB.
2349   MachineFunction::iterator BBI(CurBB);
2350   MachineFunction &MF = DAG.getMachineFunction();
2351   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2352   CurBB->getParent()->insert(++BBI, TmpBB);
2353 
2354   if (Opc == Instruction::Or) {
2355     // Codegen X | Y as:
2356     // BB1:
2357     //   jmp_if_X TBB
2358     //   jmp TmpBB
2359     // TmpBB:
2360     //   jmp_if_Y TBB
2361     //   jmp FBB
2362     //
2363 
2364     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2365     // The requirement is that
2366     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2367     //     = TrueProb for original BB.
2368     // Assuming the original probabilities are A and B, one choice is to set
2369     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2370     // A/(1+B) and 2B/(1+B). This choice assumes that
2371     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2372     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2373     // TmpBB, but the math is more complicated.
2374 
2375     auto NewTrueProb = TProb / 2;
2376     auto NewFalseProb = TProb / 2 + FProb;
2377     // Emit the LHS condition.
2378     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2379                          NewFalseProb, InvertCond);
2380 
2381     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2382     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2383     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2384     // Emit the RHS condition into TmpBB.
2385     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2386                          Probs[1], InvertCond);
2387   } else {
2388     assert(Opc == Instruction::And && "Unknown merge op!");
2389     // Codegen X & Y as:
2390     // BB1:
2391     //   jmp_if_X TmpBB
2392     //   jmp FBB
2393     // TmpBB:
2394     //   jmp_if_Y TBB
2395     //   jmp FBB
2396     //
2397     //  This requires creation of TmpBB after CurBB.
2398 
2399     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2400     // The requirement is that
2401     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2402     //     = FalseProb for original BB.
2403     // Assuming the original probabilities are A and B, one choice is to set
2404     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2405     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2406     // TrueProb for BB1 * FalseProb for TmpBB.
2407 
2408     auto NewTrueProb = TProb + FProb / 2;
2409     auto NewFalseProb = FProb / 2;
2410     // Emit the LHS condition.
2411     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2412                          NewFalseProb, InvertCond);
2413 
2414     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2415     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2416     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2417     // Emit the RHS condition into TmpBB.
2418     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2419                          Probs[1], InvertCond);
2420   }
2421 }
2422 
2423 /// If the set of cases should be emitted as a series of branches, return true.
2424 /// If we should emit this as a bunch of and/or'd together conditions, return
2425 /// false.
2426 bool
2427 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2428   if (Cases.size() != 2) return true;
2429 
2430   // If this is two comparisons of the same values or'd or and'd together, they
2431   // will get folded into a single comparison, so don't emit two blocks.
2432   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2433        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2434       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2435        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2436     return false;
2437   }
2438 
2439   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2440   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2441   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2442       Cases[0].CC == Cases[1].CC &&
2443       isa<Constant>(Cases[0].CmpRHS) &&
2444       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2445     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2446       return false;
2447     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2448       return false;
2449   }
2450 
2451   return true;
2452 }
2453 
2454 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2455   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2456 
2457   // Update machine-CFG edges.
2458   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2459 
2460   if (I.isUnconditional()) {
2461     // Update machine-CFG edges.
2462     BrMBB->addSuccessor(Succ0MBB);
2463 
2464     // If this is not a fall-through branch or optimizations are switched off,
2465     // emit the branch.
2466     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2467       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2468                               MVT::Other, getControlRoot(),
2469                               DAG.getBasicBlock(Succ0MBB)));
2470 
2471     return;
2472   }
2473 
2474   // If this condition is one of the special cases we handle, do special stuff
2475   // now.
2476   const Value *CondVal = I.getCondition();
2477   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2478 
2479   // If this is a series of conditions that are or'd or and'd together, emit
2480   // this as a sequence of branches instead of setcc's with and/or operations.
2481   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2482   // unpredictable branches, and vector extracts because those jumps are likely
2483   // expensive for any target), this should improve performance.
2484   // For example, instead of something like:
2485   //     cmp A, B
2486   //     C = seteq
2487   //     cmp D, E
2488   //     F = setle
2489   //     or C, F
2490   //     jnz foo
2491   // Emit:
2492   //     cmp A, B
2493   //     je foo
2494   //     cmp D, E
2495   //     jle foo
2496   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2497   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2498       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2499     Value *Vec;
2500     const Value *BOp0, *BOp1;
2501     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2502     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2503       Opcode = Instruction::And;
2504     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2505       Opcode = Instruction::Or;
2506 
2507     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2508                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2509       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2510                            getEdgeProbability(BrMBB, Succ0MBB),
2511                            getEdgeProbability(BrMBB, Succ1MBB),
2512                            /*InvertCond=*/false);
2513       // If the compares in later blocks need to use values not currently
2514       // exported from this block, export them now.  This block should always
2515       // be the first entry.
2516       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2517 
2518       // Allow some cases to be rejected.
2519       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2520         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2521           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2522           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2523         }
2524 
2525         // Emit the branch for this block.
2526         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2527         SL->SwitchCases.erase(SL->SwitchCases.begin());
2528         return;
2529       }
2530 
2531       // Okay, we decided not to do this, remove any inserted MBB's and clear
2532       // SwitchCases.
2533       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2534         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2535 
2536       SL->SwitchCases.clear();
2537     }
2538   }
2539 
2540   // Create a CaseBlock record representing this branch.
2541   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2542                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2543 
2544   // Use visitSwitchCase to actually insert the fast branch sequence for this
2545   // cond branch.
2546   visitSwitchCase(CB, BrMBB);
2547 }
2548 
2549 /// visitSwitchCase - Emits the necessary code to represent a single node in
2550 /// the binary search tree resulting from lowering a switch instruction.
2551 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2552                                           MachineBasicBlock *SwitchBB) {
2553   SDValue Cond;
2554   SDValue CondLHS = getValue(CB.CmpLHS);
2555   SDLoc dl = CB.DL;
2556 
2557   if (CB.CC == ISD::SETTRUE) {
2558     // Branch or fall through to TrueBB.
2559     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2560     SwitchBB->normalizeSuccProbs();
2561     if (CB.TrueBB != NextBlock(SwitchBB)) {
2562       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2563                               DAG.getBasicBlock(CB.TrueBB)));
2564     }
2565     return;
2566   }
2567 
2568   auto &TLI = DAG.getTargetLoweringInfo();
2569   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2570 
2571   // Build the setcc now.
2572   if (!CB.CmpMHS) {
2573     // Fold "(X == true)" to X and "(X == false)" to !X to
2574     // handle common cases produced by branch lowering.
2575     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2576         CB.CC == ISD::SETEQ)
2577       Cond = CondLHS;
2578     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2579              CB.CC == ISD::SETEQ) {
2580       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2581       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2582     } else {
2583       SDValue CondRHS = getValue(CB.CmpRHS);
2584 
2585       // If a pointer's DAG type is larger than its memory type then the DAG
2586       // values are zero-extended. This breaks signed comparisons so truncate
2587       // back to the underlying type before doing the compare.
2588       if (CondLHS.getValueType() != MemVT) {
2589         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2590         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2591       }
2592       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2593     }
2594   } else {
2595     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2596 
2597     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2598     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2599 
2600     SDValue CmpOp = getValue(CB.CmpMHS);
2601     EVT VT = CmpOp.getValueType();
2602 
2603     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2604       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2605                           ISD::SETLE);
2606     } else {
2607       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2608                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2609       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2610                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2611     }
2612   }
2613 
2614   // Update successor info
2615   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2616   // TrueBB and FalseBB are always different unless the incoming IR is
2617   // degenerate. This only happens when running llc on weird IR.
2618   if (CB.TrueBB != CB.FalseBB)
2619     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2620   SwitchBB->normalizeSuccProbs();
2621 
2622   // If the lhs block is the next block, invert the condition so that we can
2623   // fall through to the lhs instead of the rhs block.
2624   if (CB.TrueBB == NextBlock(SwitchBB)) {
2625     std::swap(CB.TrueBB, CB.FalseBB);
2626     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2627     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2628   }
2629 
2630   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2631                                MVT::Other, getControlRoot(), Cond,
2632                                DAG.getBasicBlock(CB.TrueBB));
2633 
2634   setValue(CurInst, BrCond);
2635 
2636   // Insert the false branch. Do this even if it's a fall through branch,
2637   // this makes it easier to do DAG optimizations which require inverting
2638   // the branch condition.
2639   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2640                        DAG.getBasicBlock(CB.FalseBB));
2641 
2642   DAG.setRoot(BrCond);
2643 }
2644 
2645 /// visitJumpTable - Emit JumpTable node in the current MBB
2646 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2647   // Emit the code for the jump table
2648   assert(JT.Reg != -1U && "Should lower JT Header first!");
2649   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2650   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2651                                      JT.Reg, PTy);
2652   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2653   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2654                                     MVT::Other, Index.getValue(1),
2655                                     Table, Index);
2656   DAG.setRoot(BrJumpTable);
2657 }
2658 
2659 /// visitJumpTableHeader - This function emits necessary code to produce index
2660 /// in the JumpTable from switch case.
2661 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2662                                                JumpTableHeader &JTH,
2663                                                MachineBasicBlock *SwitchBB) {
2664   SDLoc dl = getCurSDLoc();
2665 
2666   // Subtract the lowest switch case value from the value being switched on.
2667   SDValue SwitchOp = getValue(JTH.SValue);
2668   EVT VT = SwitchOp.getValueType();
2669   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2670                             DAG.getConstant(JTH.First, dl, VT));
2671 
2672   // The SDNode we just created, which holds the value being switched on minus
2673   // the smallest case value, needs to be copied to a virtual register so it
2674   // can be used as an index into the jump table in a subsequent basic block.
2675   // This value may be smaller or larger than the target's pointer type, and
2676   // therefore require extension or truncating.
2677   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2678   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2679 
2680   unsigned JumpTableReg =
2681       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2682   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2683                                     JumpTableReg, SwitchOp);
2684   JT.Reg = JumpTableReg;
2685 
2686   if (!JTH.FallthroughUnreachable) {
2687     // Emit the range check for the jump table, and branch to the default block
2688     // for the switch statement if the value being switched on exceeds the
2689     // largest case in the switch.
2690     SDValue CMP = DAG.getSetCC(
2691         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2692                                    Sub.getValueType()),
2693         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2694 
2695     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2696                                  MVT::Other, CopyTo, CMP,
2697                                  DAG.getBasicBlock(JT.Default));
2698 
2699     // Avoid emitting unnecessary branches to the next block.
2700     if (JT.MBB != NextBlock(SwitchBB))
2701       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2702                            DAG.getBasicBlock(JT.MBB));
2703 
2704     DAG.setRoot(BrCond);
2705   } else {
2706     // Avoid emitting unnecessary branches to the next block.
2707     if (JT.MBB != NextBlock(SwitchBB))
2708       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2709                               DAG.getBasicBlock(JT.MBB)));
2710     else
2711       DAG.setRoot(CopyTo);
2712   }
2713 }
2714 
2715 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2716 /// variable if there exists one.
2717 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2718                                  SDValue &Chain) {
2719   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2720   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2721   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2722   MachineFunction &MF = DAG.getMachineFunction();
2723   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2724   MachineSDNode *Node =
2725       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2726   if (Global) {
2727     MachinePointerInfo MPInfo(Global);
2728     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2729                  MachineMemOperand::MODereferenceable;
2730     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2731         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2732     DAG.setNodeMemRefs(Node, {MemRef});
2733   }
2734   if (PtrTy != PtrMemTy)
2735     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2736   return SDValue(Node, 0);
2737 }
2738 
2739 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2740 /// tail spliced into a stack protector check success bb.
2741 ///
2742 /// For a high level explanation of how this fits into the stack protector
2743 /// generation see the comment on the declaration of class
2744 /// StackProtectorDescriptor.
2745 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2746                                                   MachineBasicBlock *ParentBB) {
2747 
2748   // First create the loads to the guard/stack slot for the comparison.
2749   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2750   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2751   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2752 
2753   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2754   int FI = MFI.getStackProtectorIndex();
2755 
2756   SDValue Guard;
2757   SDLoc dl = getCurSDLoc();
2758   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2759   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2760   Align Align =
2761       DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2762 
2763   // Generate code to load the content of the guard slot.
2764   SDValue GuardVal = DAG.getLoad(
2765       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2766       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2767       MachineMemOperand::MOVolatile);
2768 
2769   if (TLI.useStackGuardXorFP())
2770     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2771 
2772   // Retrieve guard check function, nullptr if instrumentation is inlined.
2773   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2774     // The target provides a guard check function to validate the guard value.
2775     // Generate a call to that function with the content of the guard slot as
2776     // argument.
2777     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2778     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2779 
2780     TargetLowering::ArgListTy Args;
2781     TargetLowering::ArgListEntry Entry;
2782     Entry.Node = GuardVal;
2783     Entry.Ty = FnTy->getParamType(0);
2784     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2785       Entry.IsInReg = true;
2786     Args.push_back(Entry);
2787 
2788     TargetLowering::CallLoweringInfo CLI(DAG);
2789     CLI.setDebugLoc(getCurSDLoc())
2790         .setChain(DAG.getEntryNode())
2791         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2792                    getValue(GuardCheckFn), std::move(Args));
2793 
2794     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2795     DAG.setRoot(Result.second);
2796     return;
2797   }
2798 
2799   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2800   // Otherwise, emit a volatile load to retrieve the stack guard value.
2801   SDValue Chain = DAG.getEntryNode();
2802   if (TLI.useLoadStackGuardNode()) {
2803     Guard = getLoadStackGuard(DAG, dl, Chain);
2804   } else {
2805     const Value *IRGuard = TLI.getSDagStackGuard(M);
2806     SDValue GuardPtr = getValue(IRGuard);
2807 
2808     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2809                         MachinePointerInfo(IRGuard, 0), Align,
2810                         MachineMemOperand::MOVolatile);
2811   }
2812 
2813   // Perform the comparison via a getsetcc.
2814   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2815                                                         *DAG.getContext(),
2816                                                         Guard.getValueType()),
2817                              Guard, GuardVal, ISD::SETNE);
2818 
2819   // If the guard/stackslot do not equal, branch to failure MBB.
2820   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2821                                MVT::Other, GuardVal.getOperand(0),
2822                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2823   // Otherwise branch to success MBB.
2824   SDValue Br = DAG.getNode(ISD::BR, dl,
2825                            MVT::Other, BrCond,
2826                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2827 
2828   DAG.setRoot(Br);
2829 }
2830 
2831 /// Codegen the failure basic block for a stack protector check.
2832 ///
2833 /// A failure stack protector machine basic block consists simply of a call to
2834 /// __stack_chk_fail().
2835 ///
2836 /// For a high level explanation of how this fits into the stack protector
2837 /// generation see the comment on the declaration of class
2838 /// StackProtectorDescriptor.
2839 void
2840 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2841   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2842   TargetLowering::MakeLibCallOptions CallOptions;
2843   CallOptions.setDiscardResult(true);
2844   SDValue Chain =
2845       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2846                       std::nullopt, CallOptions, getCurSDLoc())
2847           .second;
2848   // On PS4/PS5, the "return address" must still be within the calling
2849   // function, even if it's at the very end, so emit an explicit TRAP here.
2850   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2851   if (TM.getTargetTriple().isPS())
2852     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2853   // WebAssembly needs an unreachable instruction after a non-returning call,
2854   // because the function return type can be different from __stack_chk_fail's
2855   // return type (void).
2856   if (TM.getTargetTriple().isWasm())
2857     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2858 
2859   DAG.setRoot(Chain);
2860 }
2861 
2862 /// visitBitTestHeader - This function emits necessary code to produce value
2863 /// suitable for "bit tests"
2864 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2865                                              MachineBasicBlock *SwitchBB) {
2866   SDLoc dl = getCurSDLoc();
2867 
2868   // Subtract the minimum value.
2869   SDValue SwitchOp = getValue(B.SValue);
2870   EVT VT = SwitchOp.getValueType();
2871   SDValue RangeSub =
2872       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2873 
2874   // Determine the type of the test operands.
2875   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2876   bool UsePtrType = false;
2877   if (!TLI.isTypeLegal(VT)) {
2878     UsePtrType = true;
2879   } else {
2880     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2881       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2882         // Switch table case range are encoded into series of masks.
2883         // Just use pointer type, it's guaranteed to fit.
2884         UsePtrType = true;
2885         break;
2886       }
2887   }
2888   SDValue Sub = RangeSub;
2889   if (UsePtrType) {
2890     VT = TLI.getPointerTy(DAG.getDataLayout());
2891     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2892   }
2893 
2894   B.RegVT = VT.getSimpleVT();
2895   B.Reg = FuncInfo.CreateReg(B.RegVT);
2896   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2897 
2898   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2899 
2900   if (!B.FallthroughUnreachable)
2901     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2902   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2903   SwitchBB->normalizeSuccProbs();
2904 
2905   SDValue Root = CopyTo;
2906   if (!B.FallthroughUnreachable) {
2907     // Conditional branch to the default block.
2908     SDValue RangeCmp = DAG.getSetCC(dl,
2909         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2910                                RangeSub.getValueType()),
2911         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2912         ISD::SETUGT);
2913 
2914     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2915                        DAG.getBasicBlock(B.Default));
2916   }
2917 
2918   // Avoid emitting unnecessary branches to the next block.
2919   if (MBB != NextBlock(SwitchBB))
2920     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2921 
2922   DAG.setRoot(Root);
2923 }
2924 
2925 /// visitBitTestCase - this function produces one "bit test"
2926 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2927                                            MachineBasicBlock* NextMBB,
2928                                            BranchProbability BranchProbToNext,
2929                                            unsigned Reg,
2930                                            BitTestCase &B,
2931                                            MachineBasicBlock *SwitchBB) {
2932   SDLoc dl = getCurSDLoc();
2933   MVT VT = BB.RegVT;
2934   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2935   SDValue Cmp;
2936   unsigned PopCount = llvm::popcount(B.Mask);
2937   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2938   if (PopCount == 1) {
2939     // Testing for a single bit; just compare the shift count with what it
2940     // would need to be to shift a 1 bit in that position.
2941     Cmp = DAG.getSetCC(
2942         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2943         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
2944         ISD::SETEQ);
2945   } else if (PopCount == BB.Range) {
2946     // There is only one zero bit in the range, test for it directly.
2947     Cmp = DAG.getSetCC(
2948         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2949         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
2950   } else {
2951     // Make desired shift
2952     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2953                                     DAG.getConstant(1, dl, VT), ShiftOp);
2954 
2955     // Emit bit tests and jumps
2956     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2957                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2958     Cmp = DAG.getSetCC(
2959         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2960         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2961   }
2962 
2963   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2964   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2965   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2966   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2967   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2968   // one as they are relative probabilities (and thus work more like weights),
2969   // and hence we need to normalize them to let the sum of them become one.
2970   SwitchBB->normalizeSuccProbs();
2971 
2972   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2973                               MVT::Other, getControlRoot(),
2974                               Cmp, DAG.getBasicBlock(B.TargetBB));
2975 
2976   // Avoid emitting unnecessary branches to the next block.
2977   if (NextMBB != NextBlock(SwitchBB))
2978     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2979                         DAG.getBasicBlock(NextMBB));
2980 
2981   DAG.setRoot(BrAnd);
2982 }
2983 
2984 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2985   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2986 
2987   // Retrieve successors. Look through artificial IR level blocks like
2988   // catchswitch for successors.
2989   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2990   const BasicBlock *EHPadBB = I.getSuccessor(1);
2991   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
2992 
2993   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2994   // have to do anything here to lower funclet bundles.
2995   assert(!I.hasOperandBundlesOtherThan(
2996              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2997               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2998               LLVMContext::OB_cfguardtarget,
2999               LLVMContext::OB_clang_arc_attachedcall}) &&
3000          "Cannot lower invokes with arbitrary operand bundles yet!");
3001 
3002   const Value *Callee(I.getCalledOperand());
3003   const Function *Fn = dyn_cast<Function>(Callee);
3004   if (isa<InlineAsm>(Callee))
3005     visitInlineAsm(I, EHPadBB);
3006   else if (Fn && Fn->isIntrinsic()) {
3007     switch (Fn->getIntrinsicID()) {
3008     default:
3009       llvm_unreachable("Cannot invoke this intrinsic");
3010     case Intrinsic::donothing:
3011       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3012     case Intrinsic::seh_try_begin:
3013     case Intrinsic::seh_scope_begin:
3014     case Intrinsic::seh_try_end:
3015     case Intrinsic::seh_scope_end:
3016       if (EHPadMBB)
3017           // a block referenced by EH table
3018           // so dtor-funclet not removed by opts
3019           EHPadMBB->setMachineBlockAddressTaken();
3020       break;
3021     case Intrinsic::experimental_patchpoint_void:
3022     case Intrinsic::experimental_patchpoint_i64:
3023       visitPatchpoint(I, EHPadBB);
3024       break;
3025     case Intrinsic::experimental_gc_statepoint:
3026       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3027       break;
3028     case Intrinsic::wasm_rethrow: {
3029       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3030       // special because it can be invoked, so we manually lower it to a DAG
3031       // node here.
3032       SmallVector<SDValue, 8> Ops;
3033       Ops.push_back(getRoot()); // inchain
3034       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3035       Ops.push_back(
3036           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3037                                 TLI.getPointerTy(DAG.getDataLayout())));
3038       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3039       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3040       break;
3041     }
3042     }
3043   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
3044     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3045     // Eventually we will support lowering the @llvm.experimental.deoptimize
3046     // intrinsic, and right now there are no plans to support other intrinsics
3047     // with deopt state.
3048     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3049   } else {
3050     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3051   }
3052 
3053   // If the value of the invoke is used outside of its defining block, make it
3054   // available as a virtual register.
3055   // We already took care of the exported value for the statepoint instruction
3056   // during call to the LowerStatepoint.
3057   if (!isa<GCStatepointInst>(I)) {
3058     CopyToExportRegsIfNeeded(&I);
3059   }
3060 
3061   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3062   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3063   BranchProbability EHPadBBProb =
3064       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3065           : BranchProbability::getZero();
3066   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3067 
3068   // Update successor info.
3069   addSuccessorWithProb(InvokeMBB, Return);
3070   for (auto &UnwindDest : UnwindDests) {
3071     UnwindDest.first->setIsEHPad();
3072     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3073   }
3074   InvokeMBB->normalizeSuccProbs();
3075 
3076   // Drop into normal successor.
3077   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3078                           DAG.getBasicBlock(Return)));
3079 }
3080 
3081 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3082   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3083 
3084   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3085   // have to do anything here to lower funclet bundles.
3086   assert(!I.hasOperandBundlesOtherThan(
3087              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3088          "Cannot lower callbrs with arbitrary operand bundles yet!");
3089 
3090   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3091   visitInlineAsm(I);
3092   CopyToExportRegsIfNeeded(&I);
3093 
3094   // Retrieve successors.
3095   SmallPtrSet<BasicBlock *, 8> Dests;
3096   Dests.insert(I.getDefaultDest());
3097   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3098 
3099   // Update successor info.
3100   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3101   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3102     BasicBlock *Dest = I.getIndirectDest(i);
3103     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3104     Target->setIsInlineAsmBrIndirectTarget();
3105     Target->setMachineBlockAddressTaken();
3106     Target->setLabelMustBeEmitted();
3107     // Don't add duplicate machine successors.
3108     if (Dests.insert(Dest).second)
3109       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3110   }
3111   CallBrMBB->normalizeSuccProbs();
3112 
3113   // Drop into default successor.
3114   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3115                           MVT::Other, getControlRoot(),
3116                           DAG.getBasicBlock(Return)));
3117 }
3118 
3119 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3120   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3121 }
3122 
3123 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3124   assert(FuncInfo.MBB->isEHPad() &&
3125          "Call to landingpad not in landing pad!");
3126 
3127   // If there aren't registers to copy the values into (e.g., during SjLj
3128   // exceptions), then don't bother to create these DAG nodes.
3129   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3130   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3131   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3132       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3133     return;
3134 
3135   // If landingpad's return type is token type, we don't create DAG nodes
3136   // for its exception pointer and selector value. The extraction of exception
3137   // pointer or selector value from token type landingpads is not currently
3138   // supported.
3139   if (LP.getType()->isTokenTy())
3140     return;
3141 
3142   SmallVector<EVT, 2> ValueVTs;
3143   SDLoc dl = getCurSDLoc();
3144   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3145   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3146 
3147   // Get the two live-in registers as SDValues. The physregs have already been
3148   // copied into virtual registers.
3149   SDValue Ops[2];
3150   if (FuncInfo.ExceptionPointerVirtReg) {
3151     Ops[0] = DAG.getZExtOrTrunc(
3152         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3153                            FuncInfo.ExceptionPointerVirtReg,
3154                            TLI.getPointerTy(DAG.getDataLayout())),
3155         dl, ValueVTs[0]);
3156   } else {
3157     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3158   }
3159   Ops[1] = DAG.getZExtOrTrunc(
3160       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3161                          FuncInfo.ExceptionSelectorVirtReg,
3162                          TLI.getPointerTy(DAG.getDataLayout())),
3163       dl, ValueVTs[1]);
3164 
3165   // Merge into one.
3166   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3167                             DAG.getVTList(ValueVTs), Ops);
3168   setValue(&LP, Res);
3169 }
3170 
3171 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3172                                            MachineBasicBlock *Last) {
3173   // Update JTCases.
3174   for (JumpTableBlock &JTB : SL->JTCases)
3175     if (JTB.first.HeaderBB == First)
3176       JTB.first.HeaderBB = Last;
3177 
3178   // Update BitTestCases.
3179   for (BitTestBlock &BTB : SL->BitTestCases)
3180     if (BTB.Parent == First)
3181       BTB.Parent = Last;
3182 }
3183 
3184 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3185   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3186 
3187   // Update machine-CFG edges with unique successors.
3188   SmallSet<BasicBlock*, 32> Done;
3189   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3190     BasicBlock *BB = I.getSuccessor(i);
3191     bool Inserted = Done.insert(BB).second;
3192     if (!Inserted)
3193         continue;
3194 
3195     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3196     addSuccessorWithProb(IndirectBrMBB, Succ);
3197   }
3198   IndirectBrMBB->normalizeSuccProbs();
3199 
3200   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3201                           MVT::Other, getControlRoot(),
3202                           getValue(I.getAddress())));
3203 }
3204 
3205 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3206   if (!DAG.getTarget().Options.TrapUnreachable)
3207     return;
3208 
3209   // We may be able to ignore unreachable behind a noreturn call.
3210   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3211     const BasicBlock &BB = *I.getParent();
3212     if (&I != &BB.front()) {
3213       BasicBlock::const_iterator PredI =
3214         std::prev(BasicBlock::const_iterator(&I));
3215       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3216         if (Call->doesNotReturn())
3217           return;
3218       }
3219     }
3220   }
3221 
3222   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3223 }
3224 
3225 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3226   SDNodeFlags Flags;
3227   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3228     Flags.copyFMF(*FPOp);
3229 
3230   SDValue Op = getValue(I.getOperand(0));
3231   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3232                                     Op, Flags);
3233   setValue(&I, UnNodeValue);
3234 }
3235 
3236 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3237   SDNodeFlags Flags;
3238   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3239     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3240     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3241   }
3242   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3243     Flags.setExact(ExactOp->isExact());
3244   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3245     Flags.copyFMF(*FPOp);
3246 
3247   SDValue Op1 = getValue(I.getOperand(0));
3248   SDValue Op2 = getValue(I.getOperand(1));
3249   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3250                                      Op1, Op2, Flags);
3251   setValue(&I, BinNodeValue);
3252 }
3253 
3254 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3255   SDValue Op1 = getValue(I.getOperand(0));
3256   SDValue Op2 = getValue(I.getOperand(1));
3257 
3258   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3259       Op1.getValueType(), DAG.getDataLayout());
3260 
3261   // Coerce the shift amount to the right type if we can. This exposes the
3262   // truncate or zext to optimization early.
3263   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3264     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3265            "Unexpected shift type");
3266     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3267   }
3268 
3269   bool nuw = false;
3270   bool nsw = false;
3271   bool exact = false;
3272 
3273   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3274 
3275     if (const OverflowingBinaryOperator *OFBinOp =
3276             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3277       nuw = OFBinOp->hasNoUnsignedWrap();
3278       nsw = OFBinOp->hasNoSignedWrap();
3279     }
3280     if (const PossiblyExactOperator *ExactOp =
3281             dyn_cast<const PossiblyExactOperator>(&I))
3282       exact = ExactOp->isExact();
3283   }
3284   SDNodeFlags Flags;
3285   Flags.setExact(exact);
3286   Flags.setNoSignedWrap(nsw);
3287   Flags.setNoUnsignedWrap(nuw);
3288   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3289                             Flags);
3290   setValue(&I, Res);
3291 }
3292 
3293 void SelectionDAGBuilder::visitSDiv(const User &I) {
3294   SDValue Op1 = getValue(I.getOperand(0));
3295   SDValue Op2 = getValue(I.getOperand(1));
3296 
3297   SDNodeFlags Flags;
3298   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3299                  cast<PossiblyExactOperator>(&I)->isExact());
3300   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3301                            Op2, Flags));
3302 }
3303 
3304 void SelectionDAGBuilder::visitICmp(const User &I) {
3305   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3306   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3307     predicate = IC->getPredicate();
3308   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3309     predicate = ICmpInst::Predicate(IC->getPredicate());
3310   SDValue Op1 = getValue(I.getOperand(0));
3311   SDValue Op2 = getValue(I.getOperand(1));
3312   ISD::CondCode Opcode = getICmpCondCode(predicate);
3313 
3314   auto &TLI = DAG.getTargetLoweringInfo();
3315   EVT MemVT =
3316       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3317 
3318   // If a pointer's DAG type is larger than its memory type then the DAG values
3319   // are zero-extended. This breaks signed comparisons so truncate back to the
3320   // underlying type before doing the compare.
3321   if (Op1.getValueType() != MemVT) {
3322     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3323     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3324   }
3325 
3326   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3327                                                         I.getType());
3328   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3329 }
3330 
3331 void SelectionDAGBuilder::visitFCmp(const User &I) {
3332   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3333   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3334     predicate = FC->getPredicate();
3335   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3336     predicate = FCmpInst::Predicate(FC->getPredicate());
3337   SDValue Op1 = getValue(I.getOperand(0));
3338   SDValue Op2 = getValue(I.getOperand(1));
3339 
3340   ISD::CondCode Condition = getFCmpCondCode(predicate);
3341   auto *FPMO = cast<FPMathOperator>(&I);
3342   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3343     Condition = getFCmpCodeWithoutNaN(Condition);
3344 
3345   SDNodeFlags Flags;
3346   Flags.copyFMF(*FPMO);
3347   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3348 
3349   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3350                                                         I.getType());
3351   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3352 }
3353 
3354 // Check if the condition of the select has one use or two users that are both
3355 // selects with the same condition.
3356 static bool hasOnlySelectUsers(const Value *Cond) {
3357   return llvm::all_of(Cond->users(), [](const Value *V) {
3358     return isa<SelectInst>(V);
3359   });
3360 }
3361 
3362 void SelectionDAGBuilder::visitSelect(const User &I) {
3363   SmallVector<EVT, 4> ValueVTs;
3364   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3365                   ValueVTs);
3366   unsigned NumValues = ValueVTs.size();
3367   if (NumValues == 0) return;
3368 
3369   SmallVector<SDValue, 4> Values(NumValues);
3370   SDValue Cond     = getValue(I.getOperand(0));
3371   SDValue LHSVal   = getValue(I.getOperand(1));
3372   SDValue RHSVal   = getValue(I.getOperand(2));
3373   SmallVector<SDValue, 1> BaseOps(1, Cond);
3374   ISD::NodeType OpCode =
3375       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3376 
3377   bool IsUnaryAbs = false;
3378   bool Negate = false;
3379 
3380   SDNodeFlags Flags;
3381   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3382     Flags.copyFMF(*FPOp);
3383 
3384   // Min/max matching is only viable if all output VTs are the same.
3385   if (all_equal(ValueVTs)) {
3386     EVT VT = ValueVTs[0];
3387     LLVMContext &Ctx = *DAG.getContext();
3388     auto &TLI = DAG.getTargetLoweringInfo();
3389 
3390     // We care about the legality of the operation after it has been type
3391     // legalized.
3392     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3393       VT = TLI.getTypeToTransformTo(Ctx, VT);
3394 
3395     // If the vselect is legal, assume we want to leave this as a vector setcc +
3396     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3397     // min/max is legal on the scalar type.
3398     bool UseScalarMinMax = VT.isVector() &&
3399       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3400 
3401     // ValueTracking's select pattern matching does not account for -0.0,
3402     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3403     // -0.0 is less than +0.0.
3404     Value *LHS, *RHS;
3405     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3406     ISD::NodeType Opc = ISD::DELETED_NODE;
3407     switch (SPR.Flavor) {
3408     case SPF_UMAX:    Opc = ISD::UMAX; break;
3409     case SPF_UMIN:    Opc = ISD::UMIN; break;
3410     case SPF_SMAX:    Opc = ISD::SMAX; break;
3411     case SPF_SMIN:    Opc = ISD::SMIN; break;
3412     case SPF_FMINNUM:
3413       switch (SPR.NaNBehavior) {
3414       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3415       case SPNB_RETURNS_NAN: break;
3416       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3417       case SPNB_RETURNS_ANY:
3418         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3419             (UseScalarMinMax &&
3420              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3421           Opc = ISD::FMINNUM;
3422         break;
3423       }
3424       break;
3425     case SPF_FMAXNUM:
3426       switch (SPR.NaNBehavior) {
3427       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3428       case SPNB_RETURNS_NAN: break;
3429       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3430       case SPNB_RETURNS_ANY:
3431         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3432             (UseScalarMinMax &&
3433              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3434           Opc = ISD::FMAXNUM;
3435         break;
3436       }
3437       break;
3438     case SPF_NABS:
3439       Negate = true;
3440       [[fallthrough]];
3441     case SPF_ABS:
3442       IsUnaryAbs = true;
3443       Opc = ISD::ABS;
3444       break;
3445     default: break;
3446     }
3447 
3448     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3449         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3450          (UseScalarMinMax &&
3451           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3452         // If the underlying comparison instruction is used by any other
3453         // instruction, the consumed instructions won't be destroyed, so it is
3454         // not profitable to convert to a min/max.
3455         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3456       OpCode = Opc;
3457       LHSVal = getValue(LHS);
3458       RHSVal = getValue(RHS);
3459       BaseOps.clear();
3460     }
3461 
3462     if (IsUnaryAbs) {
3463       OpCode = Opc;
3464       LHSVal = getValue(LHS);
3465       BaseOps.clear();
3466     }
3467   }
3468 
3469   if (IsUnaryAbs) {
3470     for (unsigned i = 0; i != NumValues; ++i) {
3471       SDLoc dl = getCurSDLoc();
3472       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3473       Values[i] =
3474           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3475       if (Negate)
3476         Values[i] = DAG.getNegative(Values[i], dl, VT);
3477     }
3478   } else {
3479     for (unsigned i = 0; i != NumValues; ++i) {
3480       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3481       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3482       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3483       Values[i] = DAG.getNode(
3484           OpCode, getCurSDLoc(),
3485           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3486     }
3487   }
3488 
3489   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3490                            DAG.getVTList(ValueVTs), Values));
3491 }
3492 
3493 void SelectionDAGBuilder::visitTrunc(const User &I) {
3494   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3495   SDValue N = getValue(I.getOperand(0));
3496   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3497                                                         I.getType());
3498   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3499 }
3500 
3501 void SelectionDAGBuilder::visitZExt(const User &I) {
3502   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3503   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3504   SDValue N = getValue(I.getOperand(0));
3505   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3506                                                         I.getType());
3507   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3508 }
3509 
3510 void SelectionDAGBuilder::visitSExt(const User &I) {
3511   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3512   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3513   SDValue N = getValue(I.getOperand(0));
3514   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3515                                                         I.getType());
3516   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3517 }
3518 
3519 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3520   // FPTrunc is never a no-op cast, no need to check
3521   SDValue N = getValue(I.getOperand(0));
3522   SDLoc dl = getCurSDLoc();
3523   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3524   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3525   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3526                            DAG.getTargetConstant(
3527                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3528 }
3529 
3530 void SelectionDAGBuilder::visitFPExt(const User &I) {
3531   // FPExt is never a no-op cast, no need to check
3532   SDValue N = getValue(I.getOperand(0));
3533   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3534                                                         I.getType());
3535   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3536 }
3537 
3538 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3539   // FPToUI is never a no-op cast, no need to check
3540   SDValue N = getValue(I.getOperand(0));
3541   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3542                                                         I.getType());
3543   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3544 }
3545 
3546 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3547   // FPToSI is never a no-op cast, no need to check
3548   SDValue N = getValue(I.getOperand(0));
3549   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3550                                                         I.getType());
3551   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3552 }
3553 
3554 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3555   // UIToFP is never a no-op cast, no need to check
3556   SDValue N = getValue(I.getOperand(0));
3557   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3558                                                         I.getType());
3559   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3560 }
3561 
3562 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3563   // SIToFP is never a no-op cast, no need to check
3564   SDValue N = getValue(I.getOperand(0));
3565   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3566                                                         I.getType());
3567   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3568 }
3569 
3570 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3571   // What to do depends on the size of the integer and the size of the pointer.
3572   // We can either truncate, zero extend, or no-op, accordingly.
3573   SDValue N = getValue(I.getOperand(0));
3574   auto &TLI = DAG.getTargetLoweringInfo();
3575   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3576                                                         I.getType());
3577   EVT PtrMemVT =
3578       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3579   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3580   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3581   setValue(&I, N);
3582 }
3583 
3584 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3585   // What to do depends on the size of the integer and the size of the pointer.
3586   // We can either truncate, zero extend, or no-op, accordingly.
3587   SDValue N = getValue(I.getOperand(0));
3588   auto &TLI = DAG.getTargetLoweringInfo();
3589   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3590   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3591   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3592   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3593   setValue(&I, N);
3594 }
3595 
3596 void SelectionDAGBuilder::visitBitCast(const User &I) {
3597   SDValue N = getValue(I.getOperand(0));
3598   SDLoc dl = getCurSDLoc();
3599   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3600                                                         I.getType());
3601 
3602   // BitCast assures us that source and destination are the same size so this is
3603   // either a BITCAST or a no-op.
3604   if (DestVT != N.getValueType())
3605     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3606                              DestVT, N)); // convert types.
3607   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3608   // might fold any kind of constant expression to an integer constant and that
3609   // is not what we are looking for. Only recognize a bitcast of a genuine
3610   // constant integer as an opaque constant.
3611   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3612     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3613                                  /*isOpaque*/true));
3614   else
3615     setValue(&I, N);            // noop cast.
3616 }
3617 
3618 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3619   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3620   const Value *SV = I.getOperand(0);
3621   SDValue N = getValue(SV);
3622   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3623 
3624   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3625   unsigned DestAS = I.getType()->getPointerAddressSpace();
3626 
3627   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3628     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3629 
3630   setValue(&I, N);
3631 }
3632 
3633 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3634   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3635   SDValue InVec = getValue(I.getOperand(0));
3636   SDValue InVal = getValue(I.getOperand(1));
3637   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3638                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3639   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3640                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3641                            InVec, InVal, InIdx));
3642 }
3643 
3644 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3645   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3646   SDValue InVec = getValue(I.getOperand(0));
3647   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3648                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3649   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3650                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3651                            InVec, InIdx));
3652 }
3653 
3654 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3655   SDValue Src1 = getValue(I.getOperand(0));
3656   SDValue Src2 = getValue(I.getOperand(1));
3657   ArrayRef<int> Mask;
3658   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3659     Mask = SVI->getShuffleMask();
3660   else
3661     Mask = cast<ConstantExpr>(I).getShuffleMask();
3662   SDLoc DL = getCurSDLoc();
3663   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3664   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3665   EVT SrcVT = Src1.getValueType();
3666 
3667   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3668       VT.isScalableVector()) {
3669     // Canonical splat form of first element of first input vector.
3670     SDValue FirstElt =
3671         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3672                     DAG.getVectorIdxConstant(0, DL));
3673     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3674     return;
3675   }
3676 
3677   // For now, we only handle splats for scalable vectors.
3678   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3679   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3680   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3681 
3682   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3683   unsigned MaskNumElts = Mask.size();
3684 
3685   if (SrcNumElts == MaskNumElts) {
3686     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3687     return;
3688   }
3689 
3690   // Normalize the shuffle vector since mask and vector length don't match.
3691   if (SrcNumElts < MaskNumElts) {
3692     // Mask is longer than the source vectors. We can use concatenate vector to
3693     // make the mask and vectors lengths match.
3694 
3695     if (MaskNumElts % SrcNumElts == 0) {
3696       // Mask length is a multiple of the source vector length.
3697       // Check if the shuffle is some kind of concatenation of the input
3698       // vectors.
3699       unsigned NumConcat = MaskNumElts / SrcNumElts;
3700       bool IsConcat = true;
3701       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3702       for (unsigned i = 0; i != MaskNumElts; ++i) {
3703         int Idx = Mask[i];
3704         if (Idx < 0)
3705           continue;
3706         // Ensure the indices in each SrcVT sized piece are sequential and that
3707         // the same source is used for the whole piece.
3708         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3709             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3710              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3711           IsConcat = false;
3712           break;
3713         }
3714         // Remember which source this index came from.
3715         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3716       }
3717 
3718       // The shuffle is concatenating multiple vectors together. Just emit
3719       // a CONCAT_VECTORS operation.
3720       if (IsConcat) {
3721         SmallVector<SDValue, 8> ConcatOps;
3722         for (auto Src : ConcatSrcs) {
3723           if (Src < 0)
3724             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3725           else if (Src == 0)
3726             ConcatOps.push_back(Src1);
3727           else
3728             ConcatOps.push_back(Src2);
3729         }
3730         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3731         return;
3732       }
3733     }
3734 
3735     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3736     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3737     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3738                                     PaddedMaskNumElts);
3739 
3740     // Pad both vectors with undefs to make them the same length as the mask.
3741     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3742 
3743     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3744     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3745     MOps1[0] = Src1;
3746     MOps2[0] = Src2;
3747 
3748     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3749     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3750 
3751     // Readjust mask for new input vector length.
3752     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3753     for (unsigned i = 0; i != MaskNumElts; ++i) {
3754       int Idx = Mask[i];
3755       if (Idx >= (int)SrcNumElts)
3756         Idx -= SrcNumElts - PaddedMaskNumElts;
3757       MappedOps[i] = Idx;
3758     }
3759 
3760     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3761 
3762     // If the concatenated vector was padded, extract a subvector with the
3763     // correct number of elements.
3764     if (MaskNumElts != PaddedMaskNumElts)
3765       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3766                            DAG.getVectorIdxConstant(0, DL));
3767 
3768     setValue(&I, Result);
3769     return;
3770   }
3771 
3772   if (SrcNumElts > MaskNumElts) {
3773     // Analyze the access pattern of the vector to see if we can extract
3774     // two subvectors and do the shuffle.
3775     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3776     bool CanExtract = true;
3777     for (int Idx : Mask) {
3778       unsigned Input = 0;
3779       if (Idx < 0)
3780         continue;
3781 
3782       if (Idx >= (int)SrcNumElts) {
3783         Input = 1;
3784         Idx -= SrcNumElts;
3785       }
3786 
3787       // If all the indices come from the same MaskNumElts sized portion of
3788       // the sources we can use extract. Also make sure the extract wouldn't
3789       // extract past the end of the source.
3790       int NewStartIdx = alignDown(Idx, MaskNumElts);
3791       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3792           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3793         CanExtract = false;
3794       // Make sure we always update StartIdx as we use it to track if all
3795       // elements are undef.
3796       StartIdx[Input] = NewStartIdx;
3797     }
3798 
3799     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3800       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3801       return;
3802     }
3803     if (CanExtract) {
3804       // Extract appropriate subvector and generate a vector shuffle
3805       for (unsigned Input = 0; Input < 2; ++Input) {
3806         SDValue &Src = Input == 0 ? Src1 : Src2;
3807         if (StartIdx[Input] < 0)
3808           Src = DAG.getUNDEF(VT);
3809         else {
3810           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3811                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3812         }
3813       }
3814 
3815       // Calculate new mask.
3816       SmallVector<int, 8> MappedOps(Mask);
3817       for (int &Idx : MappedOps) {
3818         if (Idx >= (int)SrcNumElts)
3819           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3820         else if (Idx >= 0)
3821           Idx -= StartIdx[0];
3822       }
3823 
3824       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3825       return;
3826     }
3827   }
3828 
3829   // We can't use either concat vectors or extract subvectors so fall back to
3830   // replacing the shuffle with extract and build vector.
3831   // to insert and build vector.
3832   EVT EltVT = VT.getVectorElementType();
3833   SmallVector<SDValue,8> Ops;
3834   for (int Idx : Mask) {
3835     SDValue Res;
3836 
3837     if (Idx < 0) {
3838       Res = DAG.getUNDEF(EltVT);
3839     } else {
3840       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3841       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3842 
3843       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3844                         DAG.getVectorIdxConstant(Idx, DL));
3845     }
3846 
3847     Ops.push_back(Res);
3848   }
3849 
3850   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3851 }
3852 
3853 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3854   ArrayRef<unsigned> Indices = I.getIndices();
3855   const Value *Op0 = I.getOperand(0);
3856   const Value *Op1 = I.getOperand(1);
3857   Type *AggTy = I.getType();
3858   Type *ValTy = Op1->getType();
3859   bool IntoUndef = isa<UndefValue>(Op0);
3860   bool FromUndef = isa<UndefValue>(Op1);
3861 
3862   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3863 
3864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3865   SmallVector<EVT, 4> AggValueVTs;
3866   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3867   SmallVector<EVT, 4> ValValueVTs;
3868   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3869 
3870   unsigned NumAggValues = AggValueVTs.size();
3871   unsigned NumValValues = ValValueVTs.size();
3872   SmallVector<SDValue, 4> Values(NumAggValues);
3873 
3874   // Ignore an insertvalue that produces an empty object
3875   if (!NumAggValues) {
3876     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3877     return;
3878   }
3879 
3880   SDValue Agg = getValue(Op0);
3881   unsigned i = 0;
3882   // Copy the beginning value(s) from the original aggregate.
3883   for (; i != LinearIndex; ++i)
3884     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3885                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3886   // Copy values from the inserted value(s).
3887   if (NumValValues) {
3888     SDValue Val = getValue(Op1);
3889     for (; i != LinearIndex + NumValValues; ++i)
3890       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3891                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3892   }
3893   // Copy remaining value(s) from the original aggregate.
3894   for (; i != NumAggValues; ++i)
3895     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3896                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3897 
3898   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3899                            DAG.getVTList(AggValueVTs), Values));
3900 }
3901 
3902 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3903   ArrayRef<unsigned> Indices = I.getIndices();
3904   const Value *Op0 = I.getOperand(0);
3905   Type *AggTy = Op0->getType();
3906   Type *ValTy = I.getType();
3907   bool OutOfUndef = isa<UndefValue>(Op0);
3908 
3909   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3910 
3911   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3912   SmallVector<EVT, 4> ValValueVTs;
3913   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3914 
3915   unsigned NumValValues = ValValueVTs.size();
3916 
3917   // Ignore a extractvalue that produces an empty object
3918   if (!NumValValues) {
3919     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3920     return;
3921   }
3922 
3923   SmallVector<SDValue, 4> Values(NumValValues);
3924 
3925   SDValue Agg = getValue(Op0);
3926   // Copy out the selected value(s).
3927   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3928     Values[i - LinearIndex] =
3929       OutOfUndef ?
3930         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3931         SDValue(Agg.getNode(), Agg.getResNo() + i);
3932 
3933   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3934                            DAG.getVTList(ValValueVTs), Values));
3935 }
3936 
3937 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3938   Value *Op0 = I.getOperand(0);
3939   // Note that the pointer operand may be a vector of pointers. Take the scalar
3940   // element which holds a pointer.
3941   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3942   SDValue N = getValue(Op0);
3943   SDLoc dl = getCurSDLoc();
3944   auto &TLI = DAG.getTargetLoweringInfo();
3945 
3946   // Normalize Vector GEP - all scalar operands should be converted to the
3947   // splat vector.
3948   bool IsVectorGEP = I.getType()->isVectorTy();
3949   ElementCount VectorElementCount =
3950       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3951                   : ElementCount::getFixed(0);
3952 
3953   if (IsVectorGEP && !N.getValueType().isVector()) {
3954     LLVMContext &Context = *DAG.getContext();
3955     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3956     N = DAG.getSplat(VT, dl, N);
3957   }
3958 
3959   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3960        GTI != E; ++GTI) {
3961     const Value *Idx = GTI.getOperand();
3962     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3963       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3964       if (Field) {
3965         // N = N + Offset
3966         uint64_t Offset =
3967             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3968 
3969         // In an inbounds GEP with an offset that is nonnegative even when
3970         // interpreted as signed, assume there is no unsigned overflow.
3971         SDNodeFlags Flags;
3972         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3973           Flags.setNoUnsignedWrap(true);
3974 
3975         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3976                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3977       }
3978     } else {
3979       // IdxSize is the width of the arithmetic according to IR semantics.
3980       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3981       // (and fix up the result later).
3982       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3983       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3984       TypeSize ElementSize =
3985           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3986       // We intentionally mask away the high bits here; ElementSize may not
3987       // fit in IdxTy.
3988       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
3989       bool ElementScalable = ElementSize.isScalable();
3990 
3991       // If this is a scalar constant or a splat vector of constants,
3992       // handle it quickly.
3993       const auto *C = dyn_cast<Constant>(Idx);
3994       if (C && isa<VectorType>(C->getType()))
3995         C = C->getSplatValue();
3996 
3997       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3998       if (CI && CI->isZero())
3999         continue;
4000       if (CI && !ElementScalable) {
4001         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4002         LLVMContext &Context = *DAG.getContext();
4003         SDValue OffsVal;
4004         if (IsVectorGEP)
4005           OffsVal = DAG.getConstant(
4006               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4007         else
4008           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4009 
4010         // In an inbounds GEP with an offset that is nonnegative even when
4011         // interpreted as signed, assume there is no unsigned overflow.
4012         SDNodeFlags Flags;
4013         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4014           Flags.setNoUnsignedWrap(true);
4015 
4016         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4017 
4018         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4019         continue;
4020       }
4021 
4022       // N = N + Idx * ElementMul;
4023       SDValue IdxN = getValue(Idx);
4024 
4025       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4026         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4027                                   VectorElementCount);
4028         IdxN = DAG.getSplat(VT, dl, IdxN);
4029       }
4030 
4031       // If the index is smaller or larger than intptr_t, truncate or extend
4032       // it.
4033       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4034 
4035       if (ElementScalable) {
4036         EVT VScaleTy = N.getValueType().getScalarType();
4037         SDValue VScale = DAG.getNode(
4038             ISD::VSCALE, dl, VScaleTy,
4039             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4040         if (IsVectorGEP)
4041           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4042         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4043       } else {
4044         // If this is a multiply by a power of two, turn it into a shl
4045         // immediately.  This is a very common case.
4046         if (ElementMul != 1) {
4047           if (ElementMul.isPowerOf2()) {
4048             unsigned Amt = ElementMul.logBase2();
4049             IdxN = DAG.getNode(ISD::SHL, dl,
4050                                N.getValueType(), IdxN,
4051                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4052           } else {
4053             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4054                                             IdxN.getValueType());
4055             IdxN = DAG.getNode(ISD::MUL, dl,
4056                                N.getValueType(), IdxN, Scale);
4057           }
4058         }
4059       }
4060 
4061       N = DAG.getNode(ISD::ADD, dl,
4062                       N.getValueType(), N, IdxN);
4063     }
4064   }
4065 
4066   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4067   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4068   if (IsVectorGEP) {
4069     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4070     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4071   }
4072 
4073   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4074     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4075 
4076   setValue(&I, N);
4077 }
4078 
4079 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4080   // If this is a fixed sized alloca in the entry block of the function,
4081   // allocate it statically on the stack.
4082   if (FuncInfo.StaticAllocaMap.count(&I))
4083     return;   // getValue will auto-populate this.
4084 
4085   SDLoc dl = getCurSDLoc();
4086   Type *Ty = I.getAllocatedType();
4087   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4088   auto &DL = DAG.getDataLayout();
4089   TypeSize TySize = DL.getTypeAllocSize(Ty);
4090   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4091 
4092   SDValue AllocSize = getValue(I.getArraySize());
4093 
4094   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace());
4095   if (AllocSize.getValueType() != IntPtr)
4096     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4097 
4098   if (TySize.isScalable())
4099     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4100                             DAG.getVScale(dl, IntPtr,
4101                                           APInt(IntPtr.getScalarSizeInBits(),
4102                                                 TySize.getKnownMinValue())));
4103   else
4104     AllocSize =
4105         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4106                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4107 
4108   // Handle alignment.  If the requested alignment is less than or equal to
4109   // the stack alignment, ignore it.  If the size is greater than or equal to
4110   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4111   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4112   if (*Alignment <= StackAlign)
4113     Alignment = std::nullopt;
4114 
4115   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4116   // Round the size of the allocation up to the stack alignment size
4117   // by add SA-1 to the size. This doesn't overflow because we're computing
4118   // an address inside an alloca.
4119   SDNodeFlags Flags;
4120   Flags.setNoUnsignedWrap(true);
4121   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4122                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4123 
4124   // Mask out the low bits for alignment purposes.
4125   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4126                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4127 
4128   SDValue Ops[] = {
4129       getRoot(), AllocSize,
4130       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4131   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4132   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4133   setValue(&I, DSA);
4134   DAG.setRoot(DSA.getValue(1));
4135 
4136   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4137 }
4138 
4139 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4140   if (I.isAtomic())
4141     return visitAtomicLoad(I);
4142 
4143   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4144   const Value *SV = I.getOperand(0);
4145   if (TLI.supportSwiftError()) {
4146     // Swifterror values can come from either a function parameter with
4147     // swifterror attribute or an alloca with swifterror attribute.
4148     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4149       if (Arg->hasSwiftErrorAttr())
4150         return visitLoadFromSwiftError(I);
4151     }
4152 
4153     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4154       if (Alloca->isSwiftError())
4155         return visitLoadFromSwiftError(I);
4156     }
4157   }
4158 
4159   SDValue Ptr = getValue(SV);
4160 
4161   Type *Ty = I.getType();
4162   SmallVector<EVT, 4> ValueVTs, MemVTs;
4163   SmallVector<uint64_t, 4> Offsets;
4164   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4165   unsigned NumValues = ValueVTs.size();
4166   if (NumValues == 0)
4167     return;
4168 
4169   Align Alignment = I.getAlign();
4170   AAMDNodes AAInfo = I.getAAMetadata();
4171   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4172   bool isVolatile = I.isVolatile();
4173   MachineMemOperand::Flags MMOFlags =
4174       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4175 
4176   SDValue Root;
4177   bool ConstantMemory = false;
4178   if (isVolatile)
4179     // Serialize volatile loads with other side effects.
4180     Root = getRoot();
4181   else if (NumValues > MaxParallelChains)
4182     Root = getMemoryRoot();
4183   else if (AA &&
4184            AA->pointsToConstantMemory(MemoryLocation(
4185                SV,
4186                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4187                AAInfo))) {
4188     // Do not serialize (non-volatile) loads of constant memory with anything.
4189     Root = DAG.getEntryNode();
4190     ConstantMemory = true;
4191     MMOFlags |= MachineMemOperand::MOInvariant;
4192   } else {
4193     // Do not serialize non-volatile loads against each other.
4194     Root = DAG.getRoot();
4195   }
4196 
4197   SDLoc dl = getCurSDLoc();
4198 
4199   if (isVolatile)
4200     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4201 
4202   // An aggregate load cannot wrap around the address space, so offsets to its
4203   // parts don't wrap either.
4204   SDNodeFlags Flags;
4205   Flags.setNoUnsignedWrap(true);
4206 
4207   SmallVector<SDValue, 4> Values(NumValues);
4208   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4209   EVT PtrVT = Ptr.getValueType();
4210 
4211   unsigned ChainI = 0;
4212   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4213     // Serializing loads here may result in excessive register pressure, and
4214     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4215     // could recover a bit by hoisting nodes upward in the chain by recognizing
4216     // they are side-effect free or do not alias. The optimizer should really
4217     // avoid this case by converting large object/array copies to llvm.memcpy
4218     // (MaxParallelChains should always remain as failsafe).
4219     if (ChainI == MaxParallelChains) {
4220       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4221       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4222                                   ArrayRef(Chains.data(), ChainI));
4223       Root = Chain;
4224       ChainI = 0;
4225     }
4226     SDValue A = DAG.getNode(ISD::ADD, dl,
4227                             PtrVT, Ptr,
4228                             DAG.getConstant(Offsets[i], dl, PtrVT),
4229                             Flags);
4230 
4231     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4232                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4233                             MMOFlags, AAInfo, Ranges);
4234     Chains[ChainI] = L.getValue(1);
4235 
4236     if (MemVTs[i] != ValueVTs[i])
4237       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4238 
4239     Values[i] = L;
4240   }
4241 
4242   if (!ConstantMemory) {
4243     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4244                                 ArrayRef(Chains.data(), ChainI));
4245     if (isVolatile)
4246       DAG.setRoot(Chain);
4247     else
4248       PendingLoads.push_back(Chain);
4249   }
4250 
4251   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4252                            DAG.getVTList(ValueVTs), Values));
4253 }
4254 
4255 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4256   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4257          "call visitStoreToSwiftError when backend supports swifterror");
4258 
4259   SmallVector<EVT, 4> ValueVTs;
4260   SmallVector<uint64_t, 4> Offsets;
4261   const Value *SrcV = I.getOperand(0);
4262   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4263                   SrcV->getType(), ValueVTs, &Offsets);
4264   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4265          "expect a single EVT for swifterror");
4266 
4267   SDValue Src = getValue(SrcV);
4268   // Create a virtual register, then update the virtual register.
4269   Register VReg =
4270       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4271   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4272   // Chain can be getRoot or getControlRoot.
4273   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4274                                       SDValue(Src.getNode(), Src.getResNo()));
4275   DAG.setRoot(CopyNode);
4276 }
4277 
4278 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4279   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4280          "call visitLoadFromSwiftError when backend supports swifterror");
4281 
4282   assert(!I.isVolatile() &&
4283          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4284          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4285          "Support volatile, non temporal, invariant for load_from_swift_error");
4286 
4287   const Value *SV = I.getOperand(0);
4288   Type *Ty = I.getType();
4289   assert(
4290       (!AA ||
4291        !AA->pointsToConstantMemory(MemoryLocation(
4292            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4293            I.getAAMetadata()))) &&
4294       "load_from_swift_error should not be constant memory");
4295 
4296   SmallVector<EVT, 4> ValueVTs;
4297   SmallVector<uint64_t, 4> Offsets;
4298   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4299                   ValueVTs, &Offsets);
4300   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4301          "expect a single EVT for swifterror");
4302 
4303   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4304   SDValue L = DAG.getCopyFromReg(
4305       getRoot(), getCurSDLoc(),
4306       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4307 
4308   setValue(&I, L);
4309 }
4310 
4311 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4312   if (I.isAtomic())
4313     return visitAtomicStore(I);
4314 
4315   const Value *SrcV = I.getOperand(0);
4316   const Value *PtrV = I.getOperand(1);
4317 
4318   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4319   if (TLI.supportSwiftError()) {
4320     // Swifterror values can come from either a function parameter with
4321     // swifterror attribute or an alloca with swifterror attribute.
4322     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4323       if (Arg->hasSwiftErrorAttr())
4324         return visitStoreToSwiftError(I);
4325     }
4326 
4327     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4328       if (Alloca->isSwiftError())
4329         return visitStoreToSwiftError(I);
4330     }
4331   }
4332 
4333   SmallVector<EVT, 4> ValueVTs, MemVTs;
4334   SmallVector<uint64_t, 4> Offsets;
4335   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4336                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4337   unsigned NumValues = ValueVTs.size();
4338   if (NumValues == 0)
4339     return;
4340 
4341   // Get the lowered operands. Note that we do this after
4342   // checking if NumResults is zero, because with zero results
4343   // the operands won't have values in the map.
4344   SDValue Src = getValue(SrcV);
4345   SDValue Ptr = getValue(PtrV);
4346 
4347   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4348   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4349   SDLoc dl = getCurSDLoc();
4350   Align Alignment = I.getAlign();
4351   AAMDNodes AAInfo = I.getAAMetadata();
4352 
4353   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4354 
4355   // An aggregate load cannot wrap around the address space, so offsets to its
4356   // parts don't wrap either.
4357   SDNodeFlags Flags;
4358   Flags.setNoUnsignedWrap(true);
4359 
4360   unsigned ChainI = 0;
4361   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4362     // See visitLoad comments.
4363     if (ChainI == MaxParallelChains) {
4364       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4365                                   ArrayRef(Chains.data(), ChainI));
4366       Root = Chain;
4367       ChainI = 0;
4368     }
4369     SDValue Add =
4370         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4371     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4372     if (MemVTs[i] != ValueVTs[i])
4373       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4374     SDValue St =
4375         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4376                      Alignment, MMOFlags, AAInfo);
4377     Chains[ChainI] = St;
4378   }
4379 
4380   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4381                                   ArrayRef(Chains.data(), ChainI));
4382   setValue(&I, StoreNode);
4383   DAG.setRoot(StoreNode);
4384 }
4385 
4386 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4387                                            bool IsCompressing) {
4388   SDLoc sdl = getCurSDLoc();
4389 
4390   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4391                                MaybeAlign &Alignment) {
4392     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4393     Src0 = I.getArgOperand(0);
4394     Ptr = I.getArgOperand(1);
4395     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4396     Mask = I.getArgOperand(3);
4397   };
4398   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4399                                     MaybeAlign &Alignment) {
4400     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4401     Src0 = I.getArgOperand(0);
4402     Ptr = I.getArgOperand(1);
4403     Mask = I.getArgOperand(2);
4404     Alignment = std::nullopt;
4405   };
4406 
4407   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4408   MaybeAlign Alignment;
4409   if (IsCompressing)
4410     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4411   else
4412     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4413 
4414   SDValue Ptr = getValue(PtrOperand);
4415   SDValue Src0 = getValue(Src0Operand);
4416   SDValue Mask = getValue(MaskOperand);
4417   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4418 
4419   EVT VT = Src0.getValueType();
4420   if (!Alignment)
4421     Alignment = DAG.getEVTAlign(VT);
4422 
4423   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4424       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4425       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4426   SDValue StoreNode =
4427       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4428                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4429   DAG.setRoot(StoreNode);
4430   setValue(&I, StoreNode);
4431 }
4432 
4433 // Get a uniform base for the Gather/Scatter intrinsic.
4434 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4435 // We try to represent it as a base pointer + vector of indices.
4436 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4437 // The first operand of the GEP may be a single pointer or a vector of pointers
4438 // Example:
4439 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4440 //  or
4441 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4442 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4443 //
4444 // When the first GEP operand is a single pointer - it is the uniform base we
4445 // are looking for. If first operand of the GEP is a splat vector - we
4446 // extract the splat value and use it as a uniform base.
4447 // In all other cases the function returns 'false'.
4448 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4449                            ISD::MemIndexType &IndexType, SDValue &Scale,
4450                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4451                            uint64_t ElemSize) {
4452   SelectionDAG& DAG = SDB->DAG;
4453   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4454   const DataLayout &DL = DAG.getDataLayout();
4455 
4456   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4457 
4458   // Handle splat constant pointer.
4459   if (auto *C = dyn_cast<Constant>(Ptr)) {
4460     C = C->getSplatValue();
4461     if (!C)
4462       return false;
4463 
4464     Base = SDB->getValue(C);
4465 
4466     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4467     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4468     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4469     IndexType = ISD::SIGNED_SCALED;
4470     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4471     return true;
4472   }
4473 
4474   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4475   if (!GEP || GEP->getParent() != CurBB)
4476     return false;
4477 
4478   if (GEP->getNumOperands() != 2)
4479     return false;
4480 
4481   const Value *BasePtr = GEP->getPointerOperand();
4482   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4483 
4484   // Make sure the base is scalar and the index is a vector.
4485   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4486     return false;
4487 
4488   uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4489 
4490   // Target may not support the required addressing mode.
4491   if (ScaleVal != 1 &&
4492       !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize))
4493     return false;
4494 
4495   Base = SDB->getValue(BasePtr);
4496   Index = SDB->getValue(IndexVal);
4497   IndexType = ISD::SIGNED_SCALED;
4498 
4499   Scale =
4500       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4501   return true;
4502 }
4503 
4504 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4505   SDLoc sdl = getCurSDLoc();
4506 
4507   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4508   const Value *Ptr = I.getArgOperand(1);
4509   SDValue Src0 = getValue(I.getArgOperand(0));
4510   SDValue Mask = getValue(I.getArgOperand(3));
4511   EVT VT = Src0.getValueType();
4512   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4513                         ->getMaybeAlignValue()
4514                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4515   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4516 
4517   SDValue Base;
4518   SDValue Index;
4519   ISD::MemIndexType IndexType;
4520   SDValue Scale;
4521   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4522                                     I.getParent(), VT.getScalarStoreSize());
4523 
4524   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4525   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4526       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4527       // TODO: Make MachineMemOperands aware of scalable
4528       // vectors.
4529       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4530   if (!UniformBase) {
4531     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4532     Index = getValue(Ptr);
4533     IndexType = ISD::SIGNED_SCALED;
4534     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4535   }
4536 
4537   EVT IdxVT = Index.getValueType();
4538   EVT EltTy = IdxVT.getVectorElementType();
4539   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4540     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4541     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4542   }
4543 
4544   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4545   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4546                                          Ops, MMO, IndexType, false);
4547   DAG.setRoot(Scatter);
4548   setValue(&I, Scatter);
4549 }
4550 
4551 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4552   SDLoc sdl = getCurSDLoc();
4553 
4554   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4555                               MaybeAlign &Alignment) {
4556     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4557     Ptr = I.getArgOperand(0);
4558     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4559     Mask = I.getArgOperand(2);
4560     Src0 = I.getArgOperand(3);
4561   };
4562   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4563                                  MaybeAlign &Alignment) {
4564     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4565     Ptr = I.getArgOperand(0);
4566     Alignment = std::nullopt;
4567     Mask = I.getArgOperand(1);
4568     Src0 = I.getArgOperand(2);
4569   };
4570 
4571   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4572   MaybeAlign Alignment;
4573   if (IsExpanding)
4574     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4575   else
4576     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4577 
4578   SDValue Ptr = getValue(PtrOperand);
4579   SDValue Src0 = getValue(Src0Operand);
4580   SDValue Mask = getValue(MaskOperand);
4581   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4582 
4583   EVT VT = Src0.getValueType();
4584   if (!Alignment)
4585     Alignment = DAG.getEVTAlign(VT);
4586 
4587   AAMDNodes AAInfo = I.getAAMetadata();
4588   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4589 
4590   // Do not serialize masked loads of constant memory with anything.
4591   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4592   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4593 
4594   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4595 
4596   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4597       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4598       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4599 
4600   SDValue Load =
4601       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4602                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4603   if (AddToChain)
4604     PendingLoads.push_back(Load.getValue(1));
4605   setValue(&I, Load);
4606 }
4607 
4608 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4609   SDLoc sdl = getCurSDLoc();
4610 
4611   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4612   const Value *Ptr = I.getArgOperand(0);
4613   SDValue Src0 = getValue(I.getArgOperand(3));
4614   SDValue Mask = getValue(I.getArgOperand(2));
4615 
4616   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4617   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4618   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4619                         ->getMaybeAlignValue()
4620                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4621 
4622   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4623 
4624   SDValue Root = DAG.getRoot();
4625   SDValue Base;
4626   SDValue Index;
4627   ISD::MemIndexType IndexType;
4628   SDValue Scale;
4629   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4630                                     I.getParent(), VT.getScalarStoreSize());
4631   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4632   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4633       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4634       // TODO: Make MachineMemOperands aware of scalable
4635       // vectors.
4636       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4637 
4638   if (!UniformBase) {
4639     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4640     Index = getValue(Ptr);
4641     IndexType = ISD::SIGNED_SCALED;
4642     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4643   }
4644 
4645   EVT IdxVT = Index.getValueType();
4646   EVT EltTy = IdxVT.getVectorElementType();
4647   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4648     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4649     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4650   }
4651 
4652   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4653   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4654                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4655 
4656   PendingLoads.push_back(Gather.getValue(1));
4657   setValue(&I, Gather);
4658 }
4659 
4660 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4661   SDLoc dl = getCurSDLoc();
4662   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4663   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4664   SyncScope::ID SSID = I.getSyncScopeID();
4665 
4666   SDValue InChain = getRoot();
4667 
4668   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4669   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4670 
4671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4672   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4673 
4674   MachineFunction &MF = DAG.getMachineFunction();
4675   MachineMemOperand *MMO = MF.getMachineMemOperand(
4676       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4677       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4678       FailureOrdering);
4679 
4680   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4681                                    dl, MemVT, VTs, InChain,
4682                                    getValue(I.getPointerOperand()),
4683                                    getValue(I.getCompareOperand()),
4684                                    getValue(I.getNewValOperand()), MMO);
4685 
4686   SDValue OutChain = L.getValue(2);
4687 
4688   setValue(&I, L);
4689   DAG.setRoot(OutChain);
4690 }
4691 
4692 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4693   SDLoc dl = getCurSDLoc();
4694   ISD::NodeType NT;
4695   switch (I.getOperation()) {
4696   default: llvm_unreachable("Unknown atomicrmw operation");
4697   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4698   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4699   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4700   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4701   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4702   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4703   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4704   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4705   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4706   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4707   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4708   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4709   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4710   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4711   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4712   case AtomicRMWInst::UIncWrap:
4713     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
4714     break;
4715   case AtomicRMWInst::UDecWrap:
4716     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
4717     break;
4718   }
4719   AtomicOrdering Ordering = I.getOrdering();
4720   SyncScope::ID SSID = I.getSyncScopeID();
4721 
4722   SDValue InChain = getRoot();
4723 
4724   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4725   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4726   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4727 
4728   MachineFunction &MF = DAG.getMachineFunction();
4729   MachineMemOperand *MMO = MF.getMachineMemOperand(
4730       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4731       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4732 
4733   SDValue L =
4734     DAG.getAtomic(NT, dl, MemVT, InChain,
4735                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4736                   MMO);
4737 
4738   SDValue OutChain = L.getValue(1);
4739 
4740   setValue(&I, L);
4741   DAG.setRoot(OutChain);
4742 }
4743 
4744 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4745   SDLoc dl = getCurSDLoc();
4746   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4747   SDValue Ops[3];
4748   Ops[0] = getRoot();
4749   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4750                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4751   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4752                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4753   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4754   setValue(&I, N);
4755   DAG.setRoot(N);
4756 }
4757 
4758 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4759   SDLoc dl = getCurSDLoc();
4760   AtomicOrdering Order = I.getOrdering();
4761   SyncScope::ID SSID = I.getSyncScopeID();
4762 
4763   SDValue InChain = getRoot();
4764 
4765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4766   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4767   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4768 
4769   if (!TLI.supportsUnalignedAtomics() &&
4770       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4771     report_fatal_error("Cannot generate unaligned atomic load");
4772 
4773   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4774 
4775   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4776       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4777       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4778 
4779   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4780 
4781   SDValue Ptr = getValue(I.getPointerOperand());
4782 
4783   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4784     // TODO: Once this is better exercised by tests, it should be merged with
4785     // the normal path for loads to prevent future divergence.
4786     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4787     if (MemVT != VT)
4788       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4789 
4790     setValue(&I, L);
4791     SDValue OutChain = L.getValue(1);
4792     if (!I.isUnordered())
4793       DAG.setRoot(OutChain);
4794     else
4795       PendingLoads.push_back(OutChain);
4796     return;
4797   }
4798 
4799   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4800                             Ptr, MMO);
4801 
4802   SDValue OutChain = L.getValue(1);
4803   if (MemVT != VT)
4804     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4805 
4806   setValue(&I, L);
4807   DAG.setRoot(OutChain);
4808 }
4809 
4810 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4811   SDLoc dl = getCurSDLoc();
4812 
4813   AtomicOrdering Ordering = I.getOrdering();
4814   SyncScope::ID SSID = I.getSyncScopeID();
4815 
4816   SDValue InChain = getRoot();
4817 
4818   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4819   EVT MemVT =
4820       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4821 
4822   if (!TLI.supportsUnalignedAtomics() &&
4823       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4824     report_fatal_error("Cannot generate unaligned atomic store");
4825 
4826   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4827 
4828   MachineFunction &MF = DAG.getMachineFunction();
4829   MachineMemOperand *MMO = MF.getMachineMemOperand(
4830       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4831       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4832 
4833   SDValue Val = getValue(I.getValueOperand());
4834   if (Val.getValueType() != MemVT)
4835     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4836   SDValue Ptr = getValue(I.getPointerOperand());
4837 
4838   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4839     // TODO: Once this is better exercised by tests, it should be merged with
4840     // the normal path for stores to prevent future divergence.
4841     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4842     setValue(&I, S);
4843     DAG.setRoot(S);
4844     return;
4845   }
4846   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4847                                    Ptr, Val, MMO);
4848 
4849   setValue(&I, OutChain);
4850   DAG.setRoot(OutChain);
4851 }
4852 
4853 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4854 /// node.
4855 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4856                                                unsigned Intrinsic) {
4857   // Ignore the callsite's attributes. A specific call site may be marked with
4858   // readnone, but the lowering code will expect the chain based on the
4859   // definition.
4860   const Function *F = I.getCalledFunction();
4861   bool HasChain = !F->doesNotAccessMemory();
4862   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4863 
4864   // Build the operand list.
4865   SmallVector<SDValue, 8> Ops;
4866   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4867     if (OnlyLoad) {
4868       // We don't need to serialize loads against other loads.
4869       Ops.push_back(DAG.getRoot());
4870     } else {
4871       Ops.push_back(getRoot());
4872     }
4873   }
4874 
4875   // Info is set by getTgtMemIntrinsic
4876   TargetLowering::IntrinsicInfo Info;
4877   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4878   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4879                                                DAG.getMachineFunction(),
4880                                                Intrinsic);
4881 
4882   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4883   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4884       Info.opc == ISD::INTRINSIC_W_CHAIN)
4885     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4886                                         TLI.getPointerTy(DAG.getDataLayout())));
4887 
4888   // Add all operands of the call to the operand list.
4889   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4890     const Value *Arg = I.getArgOperand(i);
4891     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4892       Ops.push_back(getValue(Arg));
4893       continue;
4894     }
4895 
4896     // Use TargetConstant instead of a regular constant for immarg.
4897     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4898     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4899       assert(CI->getBitWidth() <= 64 &&
4900              "large intrinsic immediates not handled");
4901       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4902     } else {
4903       Ops.push_back(
4904           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4905     }
4906   }
4907 
4908   SmallVector<EVT, 4> ValueVTs;
4909   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4910 
4911   if (HasChain)
4912     ValueVTs.push_back(MVT::Other);
4913 
4914   SDVTList VTs = DAG.getVTList(ValueVTs);
4915 
4916   // Propagate fast-math-flags from IR to node(s).
4917   SDNodeFlags Flags;
4918   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4919     Flags.copyFMF(*FPMO);
4920   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4921 
4922   // Create the node.
4923   SDValue Result;
4924   // In some cases, custom collection of operands from CallInst I may be needed.
4925   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4926   if (IsTgtIntrinsic) {
4927     // This is target intrinsic that touches memory
4928     //
4929     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
4930     //       didn't yield anything useful.
4931     MachinePointerInfo MPI;
4932     if (Info.ptrVal)
4933       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
4934     else if (Info.fallbackAddressSpace)
4935       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
4936     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
4937                                      Info.memVT, MPI, Info.align, Info.flags,
4938                                      Info.size, I.getAAMetadata());
4939   } else if (!HasChain) {
4940     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4941   } else if (!I.getType()->isVoidTy()) {
4942     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4943   } else {
4944     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4945   }
4946 
4947   if (HasChain) {
4948     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4949     if (OnlyLoad)
4950       PendingLoads.push_back(Chain);
4951     else
4952       DAG.setRoot(Chain);
4953   }
4954 
4955   if (!I.getType()->isVoidTy()) {
4956     if (!isa<VectorType>(I.getType()))
4957       Result = lowerRangeToAssertZExt(DAG, I, Result);
4958 
4959     MaybeAlign Alignment = I.getRetAlign();
4960 
4961     // Insert `assertalign` node if there's an alignment.
4962     if (InsertAssertAlign && Alignment) {
4963       Result =
4964           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4965     }
4966 
4967     setValue(&I, Result);
4968   }
4969 }
4970 
4971 /// GetSignificand - Get the significand and build it into a floating-point
4972 /// number with exponent of 1:
4973 ///
4974 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4975 ///
4976 /// where Op is the hexadecimal representation of floating point value.
4977 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4978   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4979                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4980   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4981                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4982   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4983 }
4984 
4985 /// GetExponent - Get the exponent:
4986 ///
4987 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4988 ///
4989 /// where Op is the hexadecimal representation of floating point value.
4990 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4991                            const TargetLowering &TLI, const SDLoc &dl) {
4992   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4993                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4994   SDValue t1 = DAG.getNode(
4995       ISD::SRL, dl, MVT::i32, t0,
4996       DAG.getConstant(23, dl,
4997                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
4998   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4999                            DAG.getConstant(127, dl, MVT::i32));
5000   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5001 }
5002 
5003 /// getF32Constant - Get 32-bit floating point constant.
5004 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5005                               const SDLoc &dl) {
5006   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5007                            MVT::f32);
5008 }
5009 
5010 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5011                                        SelectionDAG &DAG) {
5012   // TODO: What fast-math-flags should be set on the floating-point nodes?
5013 
5014   //   IntegerPartOfX = ((int32_t)(t0);
5015   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5016 
5017   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5018   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5019   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5020 
5021   //   IntegerPartOfX <<= 23;
5022   IntegerPartOfX =
5023       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5024                   DAG.getConstant(23, dl,
5025                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5026                                       MVT::i32, DAG.getDataLayout())));
5027 
5028   SDValue TwoToFractionalPartOfX;
5029   if (LimitFloatPrecision <= 6) {
5030     // For floating-point precision of 6:
5031     //
5032     //   TwoToFractionalPartOfX =
5033     //     0.997535578f +
5034     //       (0.735607626f + 0.252464424f * x) * x;
5035     //
5036     // error 0.0144103317, which is 6 bits
5037     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5038                              getF32Constant(DAG, 0x3e814304, dl));
5039     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5040                              getF32Constant(DAG, 0x3f3c50c8, dl));
5041     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5042     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5043                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5044   } else if (LimitFloatPrecision <= 12) {
5045     // For floating-point precision of 12:
5046     //
5047     //   TwoToFractionalPartOfX =
5048     //     0.999892986f +
5049     //       (0.696457318f +
5050     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5051     //
5052     // error 0.000107046256, which is 13 to 14 bits
5053     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5054                              getF32Constant(DAG, 0x3da235e3, dl));
5055     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5056                              getF32Constant(DAG, 0x3e65b8f3, dl));
5057     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5058     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5059                              getF32Constant(DAG, 0x3f324b07, dl));
5060     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5061     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5062                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5063   } else { // LimitFloatPrecision <= 18
5064     // For floating-point precision of 18:
5065     //
5066     //   TwoToFractionalPartOfX =
5067     //     0.999999982f +
5068     //       (0.693148872f +
5069     //         (0.240227044f +
5070     //           (0.554906021e-1f +
5071     //             (0.961591928e-2f +
5072     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5073     // error 2.47208000*10^(-7), which is better than 18 bits
5074     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5075                              getF32Constant(DAG, 0x3924b03e, dl));
5076     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5077                              getF32Constant(DAG, 0x3ab24b87, dl));
5078     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5079     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5080                              getF32Constant(DAG, 0x3c1d8c17, dl));
5081     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5082     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5083                              getF32Constant(DAG, 0x3d634a1d, dl));
5084     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5085     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5086                              getF32Constant(DAG, 0x3e75fe14, dl));
5087     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5088     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5089                               getF32Constant(DAG, 0x3f317234, dl));
5090     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5091     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5092                                          getF32Constant(DAG, 0x3f800000, dl));
5093   }
5094 
5095   // Add the exponent into the result in integer domain.
5096   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5097   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5098                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5099 }
5100 
5101 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5102 /// limited-precision mode.
5103 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5104                          const TargetLowering &TLI, SDNodeFlags Flags) {
5105   if (Op.getValueType() == MVT::f32 &&
5106       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5107 
5108     // Put the exponent in the right bit position for later addition to the
5109     // final result:
5110     //
5111     // t0 = Op * log2(e)
5112 
5113     // TODO: What fast-math-flags should be set here?
5114     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5115                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5116     return getLimitedPrecisionExp2(t0, dl, DAG);
5117   }
5118 
5119   // No special expansion.
5120   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5121 }
5122 
5123 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5124 /// limited-precision mode.
5125 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5126                          const TargetLowering &TLI, SDNodeFlags Flags) {
5127   // TODO: What fast-math-flags should be set on the floating-point nodes?
5128 
5129   if (Op.getValueType() == MVT::f32 &&
5130       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5131     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5132 
5133     // Scale the exponent by log(2).
5134     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5135     SDValue LogOfExponent =
5136         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5137                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5138 
5139     // Get the significand and build it into a floating-point number with
5140     // exponent of 1.
5141     SDValue X = GetSignificand(DAG, Op1, dl);
5142 
5143     SDValue LogOfMantissa;
5144     if (LimitFloatPrecision <= 6) {
5145       // For floating-point precision of 6:
5146       //
5147       //   LogofMantissa =
5148       //     -1.1609546f +
5149       //       (1.4034025f - 0.23903021f * x) * x;
5150       //
5151       // error 0.0034276066, which is better than 8 bits
5152       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5153                                getF32Constant(DAG, 0xbe74c456, dl));
5154       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5155                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5156       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5157       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5158                                   getF32Constant(DAG, 0x3f949a29, dl));
5159     } else if (LimitFloatPrecision <= 12) {
5160       // For floating-point precision of 12:
5161       //
5162       //   LogOfMantissa =
5163       //     -1.7417939f +
5164       //       (2.8212026f +
5165       //         (-1.4699568f +
5166       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5167       //
5168       // error 0.000061011436, which is 14 bits
5169       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5170                                getF32Constant(DAG, 0xbd67b6d6, dl));
5171       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5172                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5173       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5174       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5175                                getF32Constant(DAG, 0x3fbc278b, dl));
5176       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5177       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5178                                getF32Constant(DAG, 0x40348e95, dl));
5179       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5180       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5181                                   getF32Constant(DAG, 0x3fdef31a, dl));
5182     } else { // LimitFloatPrecision <= 18
5183       // For floating-point precision of 18:
5184       //
5185       //   LogOfMantissa =
5186       //     -2.1072184f +
5187       //       (4.2372794f +
5188       //         (-3.7029485f +
5189       //           (2.2781945f +
5190       //             (-0.87823314f +
5191       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5192       //
5193       // error 0.0000023660568, which is better than 18 bits
5194       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5195                                getF32Constant(DAG, 0xbc91e5ac, dl));
5196       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5197                                getF32Constant(DAG, 0x3e4350aa, dl));
5198       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5199       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5200                                getF32Constant(DAG, 0x3f60d3e3, dl));
5201       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5202       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5203                                getF32Constant(DAG, 0x4011cdf0, dl));
5204       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5205       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5206                                getF32Constant(DAG, 0x406cfd1c, dl));
5207       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5208       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5209                                getF32Constant(DAG, 0x408797cb, dl));
5210       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5211       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5212                                   getF32Constant(DAG, 0x4006dcab, dl));
5213     }
5214 
5215     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5216   }
5217 
5218   // No special expansion.
5219   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5220 }
5221 
5222 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5223 /// limited-precision mode.
5224 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5225                           const TargetLowering &TLI, SDNodeFlags Flags) {
5226   // TODO: What fast-math-flags should be set on the floating-point nodes?
5227 
5228   if (Op.getValueType() == MVT::f32 &&
5229       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5230     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5231 
5232     // Get the exponent.
5233     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5234 
5235     // Get the significand and build it into a floating-point number with
5236     // exponent of 1.
5237     SDValue X = GetSignificand(DAG, Op1, dl);
5238 
5239     // Different possible minimax approximations of significand in
5240     // floating-point for various degrees of accuracy over [1,2].
5241     SDValue Log2ofMantissa;
5242     if (LimitFloatPrecision <= 6) {
5243       // For floating-point precision of 6:
5244       //
5245       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5246       //
5247       // error 0.0049451742, which is more than 7 bits
5248       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5249                                getF32Constant(DAG, 0xbeb08fe0, dl));
5250       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5251                                getF32Constant(DAG, 0x40019463, dl));
5252       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5253       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5254                                    getF32Constant(DAG, 0x3fd6633d, dl));
5255     } else if (LimitFloatPrecision <= 12) {
5256       // For floating-point precision of 12:
5257       //
5258       //   Log2ofMantissa =
5259       //     -2.51285454f +
5260       //       (4.07009056f +
5261       //         (-2.12067489f +
5262       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5263       //
5264       // error 0.0000876136000, which is better than 13 bits
5265       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5266                                getF32Constant(DAG, 0xbda7262e, dl));
5267       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5268                                getF32Constant(DAG, 0x3f25280b, dl));
5269       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5270       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5271                                getF32Constant(DAG, 0x4007b923, dl));
5272       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5273       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5274                                getF32Constant(DAG, 0x40823e2f, dl));
5275       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5276       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5277                                    getF32Constant(DAG, 0x4020d29c, dl));
5278     } else { // LimitFloatPrecision <= 18
5279       // For floating-point precision of 18:
5280       //
5281       //   Log2ofMantissa =
5282       //     -3.0400495f +
5283       //       (6.1129976f +
5284       //         (-5.3420409f +
5285       //           (3.2865683f +
5286       //             (-1.2669343f +
5287       //               (0.27515199f -
5288       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5289       //
5290       // error 0.0000018516, which is better than 18 bits
5291       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5292                                getF32Constant(DAG, 0xbcd2769e, dl));
5293       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5294                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5295       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5296       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5297                                getF32Constant(DAG, 0x3fa22ae7, dl));
5298       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5299       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5300                                getF32Constant(DAG, 0x40525723, dl));
5301       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5302       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5303                                getF32Constant(DAG, 0x40aaf200, dl));
5304       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5305       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5306                                getF32Constant(DAG, 0x40c39dad, dl));
5307       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5308       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5309                                    getF32Constant(DAG, 0x4042902c, dl));
5310     }
5311 
5312     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5313   }
5314 
5315   // No special expansion.
5316   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5317 }
5318 
5319 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5320 /// limited-precision mode.
5321 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5322                            const TargetLowering &TLI, SDNodeFlags Flags) {
5323   // TODO: What fast-math-flags should be set on the floating-point nodes?
5324 
5325   if (Op.getValueType() == MVT::f32 &&
5326       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5327     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5328 
5329     // Scale the exponent by log10(2) [0.30102999f].
5330     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5331     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5332                                         getF32Constant(DAG, 0x3e9a209a, dl));
5333 
5334     // Get the significand and build it into a floating-point number with
5335     // exponent of 1.
5336     SDValue X = GetSignificand(DAG, Op1, dl);
5337 
5338     SDValue Log10ofMantissa;
5339     if (LimitFloatPrecision <= 6) {
5340       // For floating-point precision of 6:
5341       //
5342       //   Log10ofMantissa =
5343       //     -0.50419619f +
5344       //       (0.60948995f - 0.10380950f * x) * x;
5345       //
5346       // error 0.0014886165, which is 6 bits
5347       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5348                                getF32Constant(DAG, 0xbdd49a13, dl));
5349       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5350                                getF32Constant(DAG, 0x3f1c0789, dl));
5351       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5352       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5353                                     getF32Constant(DAG, 0x3f011300, dl));
5354     } else if (LimitFloatPrecision <= 12) {
5355       // For floating-point precision of 12:
5356       //
5357       //   Log10ofMantissa =
5358       //     -0.64831180f +
5359       //       (0.91751397f +
5360       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5361       //
5362       // error 0.00019228036, which is better than 12 bits
5363       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5364                                getF32Constant(DAG, 0x3d431f31, dl));
5365       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5366                                getF32Constant(DAG, 0x3ea21fb2, dl));
5367       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5368       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5369                                getF32Constant(DAG, 0x3f6ae232, dl));
5370       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5371       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5372                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5373     } else { // LimitFloatPrecision <= 18
5374       // For floating-point precision of 18:
5375       //
5376       //   Log10ofMantissa =
5377       //     -0.84299375f +
5378       //       (1.5327582f +
5379       //         (-1.0688956f +
5380       //           (0.49102474f +
5381       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5382       //
5383       // error 0.0000037995730, which is better than 18 bits
5384       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5385                                getF32Constant(DAG, 0x3c5d51ce, dl));
5386       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5387                                getF32Constant(DAG, 0x3e00685a, dl));
5388       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5389       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5390                                getF32Constant(DAG, 0x3efb6798, dl));
5391       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5392       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5393                                getF32Constant(DAG, 0x3f88d192, dl));
5394       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5395       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5396                                getF32Constant(DAG, 0x3fc4316c, dl));
5397       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5398       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5399                                     getF32Constant(DAG, 0x3f57ce70, dl));
5400     }
5401 
5402     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5403   }
5404 
5405   // No special expansion.
5406   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5407 }
5408 
5409 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5410 /// limited-precision mode.
5411 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5412                           const TargetLowering &TLI, SDNodeFlags Flags) {
5413   if (Op.getValueType() == MVT::f32 &&
5414       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5415     return getLimitedPrecisionExp2(Op, dl, DAG);
5416 
5417   // No special expansion.
5418   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5419 }
5420 
5421 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5422 /// limited-precision mode with x == 10.0f.
5423 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5424                          SelectionDAG &DAG, const TargetLowering &TLI,
5425                          SDNodeFlags Flags) {
5426   bool IsExp10 = false;
5427   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5428       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5429     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5430       APFloat Ten(10.0f);
5431       IsExp10 = LHSC->isExactlyValue(Ten);
5432     }
5433   }
5434 
5435   // TODO: What fast-math-flags should be set on the FMUL node?
5436   if (IsExp10) {
5437     // Put the exponent in the right bit position for later addition to the
5438     // final result:
5439     //
5440     //   #define LOG2OF10 3.3219281f
5441     //   t0 = Op * LOG2OF10;
5442     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5443                              getF32Constant(DAG, 0x40549a78, dl));
5444     return getLimitedPrecisionExp2(t0, dl, DAG);
5445   }
5446 
5447   // No special expansion.
5448   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5449 }
5450 
5451 /// ExpandPowI - Expand a llvm.powi intrinsic.
5452 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5453                           SelectionDAG &DAG) {
5454   // If RHS is a constant, we can expand this out to a multiplication tree if
5455   // it's beneficial on the target, otherwise we end up lowering to a call to
5456   // __powidf2 (for example).
5457   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5458     unsigned Val = RHSC->getSExtValue();
5459 
5460     // powi(x, 0) -> 1.0
5461     if (Val == 0)
5462       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5463 
5464     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5465             Val, DAG.shouldOptForSize())) {
5466       // Get the exponent as a positive value.
5467       if ((int)Val < 0)
5468         Val = -Val;
5469       // We use the simple binary decomposition method to generate the multiply
5470       // sequence.  There are more optimal ways to do this (for example,
5471       // powi(x,15) generates one more multiply than it should), but this has
5472       // the benefit of being both really simple and much better than a libcall.
5473       SDValue Res; // Logically starts equal to 1.0
5474       SDValue CurSquare = LHS;
5475       // TODO: Intrinsics should have fast-math-flags that propagate to these
5476       // nodes.
5477       while (Val) {
5478         if (Val & 1) {
5479           if (Res.getNode())
5480             Res =
5481                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5482           else
5483             Res = CurSquare; // 1.0*CurSquare.
5484         }
5485 
5486         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5487                                 CurSquare, CurSquare);
5488         Val >>= 1;
5489       }
5490 
5491       // If the original was negative, invert the result, producing 1/(x*x*x).
5492       if (RHSC->getSExtValue() < 0)
5493         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5494                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5495       return Res;
5496     }
5497   }
5498 
5499   // Otherwise, expand to a libcall.
5500   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5501 }
5502 
5503 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5504                             SDValue LHS, SDValue RHS, SDValue Scale,
5505                             SelectionDAG &DAG, const TargetLowering &TLI) {
5506   EVT VT = LHS.getValueType();
5507   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5508   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5509   LLVMContext &Ctx = *DAG.getContext();
5510 
5511   // If the type is legal but the operation isn't, this node might survive all
5512   // the way to operation legalization. If we end up there and we do not have
5513   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5514   // node.
5515 
5516   // Coax the legalizer into expanding the node during type legalization instead
5517   // by bumping the size by one bit. This will force it to Promote, enabling the
5518   // early expansion and avoiding the need to expand later.
5519 
5520   // We don't have to do this if Scale is 0; that can always be expanded, unless
5521   // it's a saturating signed operation. Those can experience true integer
5522   // division overflow, a case which we must avoid.
5523 
5524   // FIXME: We wouldn't have to do this (or any of the early
5525   // expansion/promotion) if it was possible to expand a libcall of an
5526   // illegal type during operation legalization. But it's not, so things
5527   // get a bit hacky.
5528   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5529   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5530       (TLI.isTypeLegal(VT) ||
5531        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5532     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5533         Opcode, VT, ScaleInt);
5534     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5535       EVT PromVT;
5536       if (VT.isScalarInteger())
5537         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5538       else if (VT.isVector()) {
5539         PromVT = VT.getVectorElementType();
5540         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5541         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5542       } else
5543         llvm_unreachable("Wrong VT for DIVFIX?");
5544       if (Signed) {
5545         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5546         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5547       } else {
5548         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5549         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5550       }
5551       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5552       // For saturating operations, we need to shift up the LHS to get the
5553       // proper saturation width, and then shift down again afterwards.
5554       if (Saturating)
5555         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5556                           DAG.getConstant(1, DL, ShiftTy));
5557       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5558       if (Saturating)
5559         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5560                           DAG.getConstant(1, DL, ShiftTy));
5561       return DAG.getZExtOrTrunc(Res, DL, VT);
5562     }
5563   }
5564 
5565   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5566 }
5567 
5568 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5569 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5570 static void
5571 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5572                      const SDValue &N) {
5573   switch (N.getOpcode()) {
5574   case ISD::CopyFromReg: {
5575     SDValue Op = N.getOperand(1);
5576     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5577                       Op.getValueType().getSizeInBits());
5578     return;
5579   }
5580   case ISD::BITCAST:
5581   case ISD::AssertZext:
5582   case ISD::AssertSext:
5583   case ISD::TRUNCATE:
5584     getUnderlyingArgRegs(Regs, N.getOperand(0));
5585     return;
5586   case ISD::BUILD_PAIR:
5587   case ISD::BUILD_VECTOR:
5588   case ISD::CONCAT_VECTORS:
5589     for (SDValue Op : N->op_values())
5590       getUnderlyingArgRegs(Regs, Op);
5591     return;
5592   default:
5593     return;
5594   }
5595 }
5596 
5597 /// If the DbgValueInst is a dbg_value of a function argument, create the
5598 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5599 /// instruction selection, they will be inserted to the entry BB.
5600 /// We don't currently support this for variadic dbg_values, as they shouldn't
5601 /// appear for function arguments or in the prologue.
5602 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5603     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5604     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5605   const Argument *Arg = dyn_cast<Argument>(V);
5606   if (!Arg)
5607     return false;
5608 
5609   MachineFunction &MF = DAG.getMachineFunction();
5610   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5611 
5612   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5613   // we've been asked to pursue.
5614   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5615                               bool Indirect) {
5616     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5617       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5618       // pointing at the VReg, which will be patched up later.
5619       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5620       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5621           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5622           /* isKill */ false, /* isDead */ false,
5623           /* isUndef */ false, /* isEarlyClobber */ false,
5624           /* SubReg */ 0, /* isDebug */ true)});
5625 
5626       auto *NewDIExpr = FragExpr;
5627       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5628       // the DIExpression.
5629       if (Indirect)
5630         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5631       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5632       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5633       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5634     } else {
5635       // Create a completely standard DBG_VALUE.
5636       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5637       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5638     }
5639   };
5640 
5641   if (Kind == FuncArgumentDbgValueKind::Value) {
5642     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5643     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5644     // the entry block.
5645     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5646     if (!IsInEntryBlock)
5647       return false;
5648 
5649     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5650     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5651     // variable that also is a param.
5652     //
5653     // Although, if we are at the top of the entry block already, we can still
5654     // emit using ArgDbgValue. This might catch some situations when the
5655     // dbg.value refers to an argument that isn't used in the entry block, so
5656     // any CopyToReg node would be optimized out and the only way to express
5657     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5658     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5659     // we should only emit as ArgDbgValue if the Variable is an argument to the
5660     // current function, and the dbg.value intrinsic is found in the entry
5661     // block.
5662     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5663         !DL->getInlinedAt();
5664     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5665     if (!IsInPrologue && !VariableIsFunctionInputArg)
5666       return false;
5667 
5668     // Here we assume that a function argument on IR level only can be used to
5669     // describe one input parameter on source level. If we for example have
5670     // source code like this
5671     //
5672     //    struct A { long x, y; };
5673     //    void foo(struct A a, long b) {
5674     //      ...
5675     //      b = a.x;
5676     //      ...
5677     //    }
5678     //
5679     // and IR like this
5680     //
5681     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5682     //  entry:
5683     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5684     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5685     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5686     //    ...
5687     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5688     //    ...
5689     //
5690     // then the last dbg.value is describing a parameter "b" using a value that
5691     // is an argument. But since we already has used %a1 to describe a parameter
5692     // we should not handle that last dbg.value here (that would result in an
5693     // incorrect hoisting of the DBG_VALUE to the function entry).
5694     // Notice that we allow one dbg.value per IR level argument, to accommodate
5695     // for the situation with fragments above.
5696     if (VariableIsFunctionInputArg) {
5697       unsigned ArgNo = Arg->getArgNo();
5698       if (ArgNo >= FuncInfo.DescribedArgs.size())
5699         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5700       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5701         return false;
5702       FuncInfo.DescribedArgs.set(ArgNo);
5703     }
5704   }
5705 
5706   bool IsIndirect = false;
5707   std::optional<MachineOperand> Op;
5708   // Some arguments' frame index is recorded during argument lowering.
5709   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5710   if (FI != std::numeric_limits<int>::max())
5711     Op = MachineOperand::CreateFI(FI);
5712 
5713   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5714   if (!Op && N.getNode()) {
5715     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5716     Register Reg;
5717     if (ArgRegsAndSizes.size() == 1)
5718       Reg = ArgRegsAndSizes.front().first;
5719 
5720     if (Reg && Reg.isVirtual()) {
5721       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5722       Register PR = RegInfo.getLiveInPhysReg(Reg);
5723       if (PR)
5724         Reg = PR;
5725     }
5726     if (Reg) {
5727       Op = MachineOperand::CreateReg(Reg, false);
5728       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5729     }
5730   }
5731 
5732   if (!Op && N.getNode()) {
5733     // Check if frame index is available.
5734     SDValue LCandidate = peekThroughBitcasts(N);
5735     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5736       if (FrameIndexSDNode *FINode =
5737           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5738         Op = MachineOperand::CreateFI(FINode->getIndex());
5739   }
5740 
5741   if (!Op) {
5742     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5743     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5744                                          SplitRegs) {
5745       unsigned Offset = 0;
5746       for (const auto &RegAndSize : SplitRegs) {
5747         // If the expression is already a fragment, the current register
5748         // offset+size might extend beyond the fragment. In this case, only
5749         // the register bits that are inside the fragment are relevant.
5750         int RegFragmentSizeInBits = RegAndSize.second;
5751         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5752           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5753           // The register is entirely outside the expression fragment,
5754           // so is irrelevant for debug info.
5755           if (Offset >= ExprFragmentSizeInBits)
5756             break;
5757           // The register is partially outside the expression fragment, only
5758           // the low bits within the fragment are relevant for debug info.
5759           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5760             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5761           }
5762         }
5763 
5764         auto FragmentExpr = DIExpression::createFragmentExpression(
5765             Expr, Offset, RegFragmentSizeInBits);
5766         Offset += RegAndSize.second;
5767         // If a valid fragment expression cannot be created, the variable's
5768         // correct value cannot be determined and so it is set as Undef.
5769         if (!FragmentExpr) {
5770           SDDbgValue *SDV = DAG.getConstantDbgValue(
5771               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5772           DAG.AddDbgValue(SDV, false);
5773           continue;
5774         }
5775         MachineInstr *NewMI =
5776             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5777                              Kind != FuncArgumentDbgValueKind::Value);
5778         FuncInfo.ArgDbgValues.push_back(NewMI);
5779       }
5780     };
5781 
5782     // Check if ValueMap has reg number.
5783     DenseMap<const Value *, Register>::const_iterator
5784       VMI = FuncInfo.ValueMap.find(V);
5785     if (VMI != FuncInfo.ValueMap.end()) {
5786       const auto &TLI = DAG.getTargetLoweringInfo();
5787       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5788                        V->getType(), std::nullopt);
5789       if (RFV.occupiesMultipleRegs()) {
5790         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5791         return true;
5792       }
5793 
5794       Op = MachineOperand::CreateReg(VMI->second, false);
5795       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5796     } else if (ArgRegsAndSizes.size() > 1) {
5797       // This was split due to the calling convention, and no virtual register
5798       // mapping exists for the value.
5799       splitMultiRegDbgValue(ArgRegsAndSizes);
5800       return true;
5801     }
5802   }
5803 
5804   if (!Op)
5805     return false;
5806 
5807   assert(Variable->isValidLocationForIntrinsic(DL) &&
5808          "Expected inlined-at fields to agree");
5809   MachineInstr *NewMI = nullptr;
5810 
5811   if (Op->isReg())
5812     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5813   else
5814     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5815                     Variable, Expr);
5816 
5817   // Otherwise, use ArgDbgValues.
5818   FuncInfo.ArgDbgValues.push_back(NewMI);
5819   return true;
5820 }
5821 
5822 /// Return the appropriate SDDbgValue based on N.
5823 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5824                                              DILocalVariable *Variable,
5825                                              DIExpression *Expr,
5826                                              const DebugLoc &dl,
5827                                              unsigned DbgSDNodeOrder) {
5828   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5829     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5830     // stack slot locations.
5831     //
5832     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5833     // debug values here after optimization:
5834     //
5835     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5836     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5837     //
5838     // Both describe the direct values of their associated variables.
5839     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5840                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5841   }
5842   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5843                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5844 }
5845 
5846 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5847   switch (Intrinsic) {
5848   case Intrinsic::smul_fix:
5849     return ISD::SMULFIX;
5850   case Intrinsic::umul_fix:
5851     return ISD::UMULFIX;
5852   case Intrinsic::smul_fix_sat:
5853     return ISD::SMULFIXSAT;
5854   case Intrinsic::umul_fix_sat:
5855     return ISD::UMULFIXSAT;
5856   case Intrinsic::sdiv_fix:
5857     return ISD::SDIVFIX;
5858   case Intrinsic::udiv_fix:
5859     return ISD::UDIVFIX;
5860   case Intrinsic::sdiv_fix_sat:
5861     return ISD::SDIVFIXSAT;
5862   case Intrinsic::udiv_fix_sat:
5863     return ISD::UDIVFIXSAT;
5864   default:
5865     llvm_unreachable("Unhandled fixed point intrinsic");
5866   }
5867 }
5868 
5869 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5870                                            const char *FunctionName) {
5871   assert(FunctionName && "FunctionName must not be nullptr");
5872   SDValue Callee = DAG.getExternalSymbol(
5873       FunctionName,
5874       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5875   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5876 }
5877 
5878 /// Given a @llvm.call.preallocated.setup, return the corresponding
5879 /// preallocated call.
5880 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5881   assert(cast<CallBase>(PreallocatedSetup)
5882                  ->getCalledFunction()
5883                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5884          "expected call_preallocated_setup Value");
5885   for (const auto *U : PreallocatedSetup->users()) {
5886     auto *UseCall = cast<CallBase>(U);
5887     const Function *Fn = UseCall->getCalledFunction();
5888     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5889       return UseCall;
5890     }
5891   }
5892   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5893 }
5894 
5895 /// Lower the call to the specified intrinsic function.
5896 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5897                                              unsigned Intrinsic) {
5898   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5899   SDLoc sdl = getCurSDLoc();
5900   DebugLoc dl = getCurDebugLoc();
5901   SDValue Res;
5902 
5903   SDNodeFlags Flags;
5904   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5905     Flags.copyFMF(*FPOp);
5906 
5907   switch (Intrinsic) {
5908   default:
5909     // By default, turn this into a target intrinsic node.
5910     visitTargetIntrinsic(I, Intrinsic);
5911     return;
5912   case Intrinsic::vscale: {
5913     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5914     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5915     return;
5916   }
5917   case Intrinsic::vastart:  visitVAStart(I); return;
5918   case Intrinsic::vaend:    visitVAEnd(I); return;
5919   case Intrinsic::vacopy:   visitVACopy(I); return;
5920   case Intrinsic::returnaddress:
5921     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5922                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5923                              getValue(I.getArgOperand(0))));
5924     return;
5925   case Intrinsic::addressofreturnaddress:
5926     setValue(&I,
5927              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5928                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5929     return;
5930   case Intrinsic::sponentry:
5931     setValue(&I,
5932              DAG.getNode(ISD::SPONENTRY, sdl,
5933                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5934     return;
5935   case Intrinsic::frameaddress:
5936     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5937                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5938                              getValue(I.getArgOperand(0))));
5939     return;
5940   case Intrinsic::read_volatile_register:
5941   case Intrinsic::read_register: {
5942     Value *Reg = I.getArgOperand(0);
5943     SDValue Chain = getRoot();
5944     SDValue RegName =
5945         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5946     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5947     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5948       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5949     setValue(&I, Res);
5950     DAG.setRoot(Res.getValue(1));
5951     return;
5952   }
5953   case Intrinsic::write_register: {
5954     Value *Reg = I.getArgOperand(0);
5955     Value *RegValue = I.getArgOperand(1);
5956     SDValue Chain = getRoot();
5957     SDValue RegName =
5958         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5959     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5960                             RegName, getValue(RegValue)));
5961     return;
5962   }
5963   case Intrinsic::memcpy: {
5964     const auto &MCI = cast<MemCpyInst>(I);
5965     SDValue Op1 = getValue(I.getArgOperand(0));
5966     SDValue Op2 = getValue(I.getArgOperand(1));
5967     SDValue Op3 = getValue(I.getArgOperand(2));
5968     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5969     Align DstAlign = MCI.getDestAlign().valueOrOne();
5970     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5971     Align Alignment = std::min(DstAlign, SrcAlign);
5972     bool isVol = MCI.isVolatile();
5973     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5974     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5975     // node.
5976     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5977     SDValue MC = DAG.getMemcpy(
5978         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5979         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
5980         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5981     updateDAGForMaybeTailCall(MC);
5982     return;
5983   }
5984   case Intrinsic::memcpy_inline: {
5985     const auto &MCI = cast<MemCpyInlineInst>(I);
5986     SDValue Dst = getValue(I.getArgOperand(0));
5987     SDValue Src = getValue(I.getArgOperand(1));
5988     SDValue Size = getValue(I.getArgOperand(2));
5989     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5990     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5991     Align DstAlign = MCI.getDestAlign().valueOrOne();
5992     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5993     Align Alignment = std::min(DstAlign, SrcAlign);
5994     bool isVol = MCI.isVolatile();
5995     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5996     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5997     // node.
5998     SDValue MC = DAG.getMemcpy(
5999         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6000         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6001         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6002     updateDAGForMaybeTailCall(MC);
6003     return;
6004   }
6005   case Intrinsic::memset: {
6006     const auto &MSI = cast<MemSetInst>(I);
6007     SDValue Op1 = getValue(I.getArgOperand(0));
6008     SDValue Op2 = getValue(I.getArgOperand(1));
6009     SDValue Op3 = getValue(I.getArgOperand(2));
6010     // @llvm.memset defines 0 and 1 to both mean no alignment.
6011     Align Alignment = MSI.getDestAlign().valueOrOne();
6012     bool isVol = MSI.isVolatile();
6013     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6014     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6015     SDValue MS = DAG.getMemset(
6016         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6017         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6018     updateDAGForMaybeTailCall(MS);
6019     return;
6020   }
6021   case Intrinsic::memset_inline: {
6022     const auto &MSII = cast<MemSetInlineInst>(I);
6023     SDValue Dst = getValue(I.getArgOperand(0));
6024     SDValue Value = getValue(I.getArgOperand(1));
6025     SDValue Size = getValue(I.getArgOperand(2));
6026     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6027     // @llvm.memset defines 0 and 1 to both mean no alignment.
6028     Align DstAlign = MSII.getDestAlign().valueOrOne();
6029     bool isVol = MSII.isVolatile();
6030     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6031     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6032     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6033                                /* AlwaysInline */ true, isTC,
6034                                MachinePointerInfo(I.getArgOperand(0)),
6035                                I.getAAMetadata());
6036     updateDAGForMaybeTailCall(MC);
6037     return;
6038   }
6039   case Intrinsic::memmove: {
6040     const auto &MMI = cast<MemMoveInst>(I);
6041     SDValue Op1 = getValue(I.getArgOperand(0));
6042     SDValue Op2 = getValue(I.getArgOperand(1));
6043     SDValue Op3 = getValue(I.getArgOperand(2));
6044     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6045     Align DstAlign = MMI.getDestAlign().valueOrOne();
6046     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6047     Align Alignment = std::min(DstAlign, SrcAlign);
6048     bool isVol = MMI.isVolatile();
6049     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6050     // FIXME: Support passing different dest/src alignments to the memmove DAG
6051     // node.
6052     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6053     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6054                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6055                                 MachinePointerInfo(I.getArgOperand(1)),
6056                                 I.getAAMetadata(), AA);
6057     updateDAGForMaybeTailCall(MM);
6058     return;
6059   }
6060   case Intrinsic::memcpy_element_unordered_atomic: {
6061     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6062     SDValue Dst = getValue(MI.getRawDest());
6063     SDValue Src = getValue(MI.getRawSource());
6064     SDValue Length = getValue(MI.getLength());
6065 
6066     Type *LengthTy = MI.getLength()->getType();
6067     unsigned ElemSz = MI.getElementSizeInBytes();
6068     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6069     SDValue MC =
6070         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6071                             isTC, MachinePointerInfo(MI.getRawDest()),
6072                             MachinePointerInfo(MI.getRawSource()));
6073     updateDAGForMaybeTailCall(MC);
6074     return;
6075   }
6076   case Intrinsic::memmove_element_unordered_atomic: {
6077     auto &MI = cast<AtomicMemMoveInst>(I);
6078     SDValue Dst = getValue(MI.getRawDest());
6079     SDValue Src = getValue(MI.getRawSource());
6080     SDValue Length = getValue(MI.getLength());
6081 
6082     Type *LengthTy = MI.getLength()->getType();
6083     unsigned ElemSz = MI.getElementSizeInBytes();
6084     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6085     SDValue MC =
6086         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6087                              isTC, MachinePointerInfo(MI.getRawDest()),
6088                              MachinePointerInfo(MI.getRawSource()));
6089     updateDAGForMaybeTailCall(MC);
6090     return;
6091   }
6092   case Intrinsic::memset_element_unordered_atomic: {
6093     auto &MI = cast<AtomicMemSetInst>(I);
6094     SDValue Dst = getValue(MI.getRawDest());
6095     SDValue Val = getValue(MI.getValue());
6096     SDValue Length = getValue(MI.getLength());
6097 
6098     Type *LengthTy = MI.getLength()->getType();
6099     unsigned ElemSz = MI.getElementSizeInBytes();
6100     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6101     SDValue MC =
6102         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6103                             isTC, MachinePointerInfo(MI.getRawDest()));
6104     updateDAGForMaybeTailCall(MC);
6105     return;
6106   }
6107   case Intrinsic::call_preallocated_setup: {
6108     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6109     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6110     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6111                               getRoot(), SrcValue);
6112     setValue(&I, Res);
6113     DAG.setRoot(Res);
6114     return;
6115   }
6116   case Intrinsic::call_preallocated_arg: {
6117     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6118     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6119     SDValue Ops[3];
6120     Ops[0] = getRoot();
6121     Ops[1] = SrcValue;
6122     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6123                                    MVT::i32); // arg index
6124     SDValue Res = DAG.getNode(
6125         ISD::PREALLOCATED_ARG, sdl,
6126         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6127     setValue(&I, Res);
6128     DAG.setRoot(Res.getValue(1));
6129     return;
6130   }
6131   case Intrinsic::dbg_declare: {
6132     const auto &DI = cast<DbgDeclareInst>(I);
6133     // Debug intrinsics are handled separately in assignment tracking mode.
6134     // Some intrinsics are handled right after Argument lowering.
6135     if (AssignmentTrackingEnabled ||
6136         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6137       return;
6138     // Assume dbg.declare can not currently use DIArgList, i.e.
6139     // it is non-variadic.
6140     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6141     DILocalVariable *Variable = DI.getVariable();
6142     DIExpression *Expression = DI.getExpression();
6143     dropDanglingDebugInfo(Variable, Expression);
6144     assert(Variable && "Missing variable");
6145     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6146                       << "\n");
6147     // Check if address has undef value.
6148     const Value *Address = DI.getVariableLocationOp(0);
6149     if (!Address || isa<UndefValue>(Address) ||
6150         (Address->use_empty() && !isa<Argument>(Address))) {
6151       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6152                         << " (bad/undef/unused-arg address)\n");
6153       return;
6154     }
6155 
6156     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6157 
6158     SDValue &N = NodeMap[Address];
6159     if (!N.getNode() && isa<Argument>(Address))
6160       // Check unused arguments map.
6161       N = UnusedArgNodeMap[Address];
6162     SDDbgValue *SDV;
6163     if (N.getNode()) {
6164       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6165         Address = BCI->getOperand(0);
6166       // Parameters are handled specially.
6167       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6168       if (isParameter && FINode) {
6169         // Byval parameter. We have a frame index at this point.
6170         SDV =
6171             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6172                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6173       } else if (isa<Argument>(Address)) {
6174         // Address is an argument, so try to emit its dbg value using
6175         // virtual register info from the FuncInfo.ValueMap.
6176         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6177                                  FuncArgumentDbgValueKind::Declare, N);
6178         return;
6179       } else {
6180         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6181                               true, dl, SDNodeOrder);
6182       }
6183       DAG.AddDbgValue(SDV, isParameter);
6184     } else {
6185       // If Address is an argument then try to emit its dbg value using
6186       // virtual register info from the FuncInfo.ValueMap.
6187       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6188                                     FuncArgumentDbgValueKind::Declare, N)) {
6189         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6190                           << " (could not emit func-arg dbg_value)\n");
6191       }
6192     }
6193     return;
6194   }
6195   case Intrinsic::dbg_label: {
6196     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6197     DILabel *Label = DI.getLabel();
6198     assert(Label && "Missing label");
6199 
6200     SDDbgLabel *SDV;
6201     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6202     DAG.AddDbgLabel(SDV);
6203     return;
6204   }
6205   case Intrinsic::dbg_assign: {
6206     // Debug intrinsics are handled seperately in assignment tracking mode.
6207     if (AssignmentTrackingEnabled)
6208       return;
6209     // If assignment tracking hasn't been enabled then fall through and treat
6210     // the dbg.assign as a dbg.value.
6211     [[fallthrough]];
6212   }
6213   case Intrinsic::dbg_value: {
6214     // Debug intrinsics are handled seperately in assignment tracking mode.
6215     if (AssignmentTrackingEnabled)
6216       return;
6217     const DbgValueInst &DI = cast<DbgValueInst>(I);
6218     assert(DI.getVariable() && "Missing variable");
6219 
6220     DILocalVariable *Variable = DI.getVariable();
6221     DIExpression *Expression = DI.getExpression();
6222     dropDanglingDebugInfo(Variable, Expression);
6223 
6224     if (DI.isKillLocation()) {
6225       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6226       return;
6227     }
6228 
6229     SmallVector<Value *, 4> Values(DI.getValues());
6230     if (Values.empty())
6231       return;
6232 
6233     bool IsVariadic = DI.hasArgList();
6234     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6235                           SDNodeOrder, IsVariadic))
6236       addDanglingDebugInfo(&DI, SDNodeOrder);
6237     return;
6238   }
6239 
6240   case Intrinsic::eh_typeid_for: {
6241     // Find the type id for the given typeinfo.
6242     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6243     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6244     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6245     setValue(&I, Res);
6246     return;
6247   }
6248 
6249   case Intrinsic::eh_return_i32:
6250   case Intrinsic::eh_return_i64:
6251     DAG.getMachineFunction().setCallsEHReturn(true);
6252     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6253                             MVT::Other,
6254                             getControlRoot(),
6255                             getValue(I.getArgOperand(0)),
6256                             getValue(I.getArgOperand(1))));
6257     return;
6258   case Intrinsic::eh_unwind_init:
6259     DAG.getMachineFunction().setCallsUnwindInit(true);
6260     return;
6261   case Intrinsic::eh_dwarf_cfa:
6262     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6263                              TLI.getPointerTy(DAG.getDataLayout()),
6264                              getValue(I.getArgOperand(0))));
6265     return;
6266   case Intrinsic::eh_sjlj_callsite: {
6267     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6268     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6269     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6270 
6271     MMI.setCurrentCallSite(CI->getZExtValue());
6272     return;
6273   }
6274   case Intrinsic::eh_sjlj_functioncontext: {
6275     // Get and store the index of the function context.
6276     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6277     AllocaInst *FnCtx =
6278       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6279     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6280     MFI.setFunctionContextIndex(FI);
6281     return;
6282   }
6283   case Intrinsic::eh_sjlj_setjmp: {
6284     SDValue Ops[2];
6285     Ops[0] = getRoot();
6286     Ops[1] = getValue(I.getArgOperand(0));
6287     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6288                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6289     setValue(&I, Op.getValue(0));
6290     DAG.setRoot(Op.getValue(1));
6291     return;
6292   }
6293   case Intrinsic::eh_sjlj_longjmp:
6294     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6295                             getRoot(), getValue(I.getArgOperand(0))));
6296     return;
6297   case Intrinsic::eh_sjlj_setup_dispatch:
6298     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6299                             getRoot()));
6300     return;
6301   case Intrinsic::masked_gather:
6302     visitMaskedGather(I);
6303     return;
6304   case Intrinsic::masked_load:
6305     visitMaskedLoad(I);
6306     return;
6307   case Intrinsic::masked_scatter:
6308     visitMaskedScatter(I);
6309     return;
6310   case Intrinsic::masked_store:
6311     visitMaskedStore(I);
6312     return;
6313   case Intrinsic::masked_expandload:
6314     visitMaskedLoad(I, true /* IsExpanding */);
6315     return;
6316   case Intrinsic::masked_compressstore:
6317     visitMaskedStore(I, true /* IsCompressing */);
6318     return;
6319   case Intrinsic::powi:
6320     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6321                             getValue(I.getArgOperand(1)), DAG));
6322     return;
6323   case Intrinsic::log:
6324     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6325     return;
6326   case Intrinsic::log2:
6327     setValue(&I,
6328              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6329     return;
6330   case Intrinsic::log10:
6331     setValue(&I,
6332              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6333     return;
6334   case Intrinsic::exp:
6335     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6336     return;
6337   case Intrinsic::exp2:
6338     setValue(&I,
6339              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6340     return;
6341   case Intrinsic::pow:
6342     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6343                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6344     return;
6345   case Intrinsic::sqrt:
6346   case Intrinsic::fabs:
6347   case Intrinsic::sin:
6348   case Intrinsic::cos:
6349   case Intrinsic::floor:
6350   case Intrinsic::ceil:
6351   case Intrinsic::trunc:
6352   case Intrinsic::rint:
6353   case Intrinsic::nearbyint:
6354   case Intrinsic::round:
6355   case Intrinsic::roundeven:
6356   case Intrinsic::canonicalize: {
6357     unsigned Opcode;
6358     switch (Intrinsic) {
6359     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6360     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6361     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6362     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6363     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6364     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6365     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6366     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6367     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6368     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6369     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6370     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6371     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6372     }
6373 
6374     setValue(&I, DAG.getNode(Opcode, sdl,
6375                              getValue(I.getArgOperand(0)).getValueType(),
6376                              getValue(I.getArgOperand(0)), Flags));
6377     return;
6378   }
6379   case Intrinsic::lround:
6380   case Intrinsic::llround:
6381   case Intrinsic::lrint:
6382   case Intrinsic::llrint: {
6383     unsigned Opcode;
6384     switch (Intrinsic) {
6385     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6386     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6387     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6388     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6389     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6390     }
6391 
6392     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6393     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6394                              getValue(I.getArgOperand(0))));
6395     return;
6396   }
6397   case Intrinsic::minnum:
6398     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6399                              getValue(I.getArgOperand(0)).getValueType(),
6400                              getValue(I.getArgOperand(0)),
6401                              getValue(I.getArgOperand(1)), Flags));
6402     return;
6403   case Intrinsic::maxnum:
6404     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6405                              getValue(I.getArgOperand(0)).getValueType(),
6406                              getValue(I.getArgOperand(0)),
6407                              getValue(I.getArgOperand(1)), Flags));
6408     return;
6409   case Intrinsic::minimum:
6410     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6411                              getValue(I.getArgOperand(0)).getValueType(),
6412                              getValue(I.getArgOperand(0)),
6413                              getValue(I.getArgOperand(1)), Flags));
6414     return;
6415   case Intrinsic::maximum:
6416     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6417                              getValue(I.getArgOperand(0)).getValueType(),
6418                              getValue(I.getArgOperand(0)),
6419                              getValue(I.getArgOperand(1)), Flags));
6420     return;
6421   case Intrinsic::copysign:
6422     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6423                              getValue(I.getArgOperand(0)).getValueType(),
6424                              getValue(I.getArgOperand(0)),
6425                              getValue(I.getArgOperand(1)), Flags));
6426     return;
6427   case Intrinsic::arithmetic_fence: {
6428     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6429                              getValue(I.getArgOperand(0)).getValueType(),
6430                              getValue(I.getArgOperand(0)), Flags));
6431     return;
6432   }
6433   case Intrinsic::fma:
6434     setValue(&I, DAG.getNode(
6435                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6436                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6437                      getValue(I.getArgOperand(2)), Flags));
6438     return;
6439 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6440   case Intrinsic::INTRINSIC:
6441 #include "llvm/IR/ConstrainedOps.def"
6442     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6443     return;
6444 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6445 #include "llvm/IR/VPIntrinsics.def"
6446     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6447     return;
6448   case Intrinsic::fptrunc_round: {
6449     // Get the last argument, the metadata and convert it to an integer in the
6450     // call
6451     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6452     std::optional<RoundingMode> RoundMode =
6453         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6454 
6455     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6456 
6457     // Propagate fast-math-flags from IR to node(s).
6458     SDNodeFlags Flags;
6459     Flags.copyFMF(*cast<FPMathOperator>(&I));
6460     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6461 
6462     SDValue Result;
6463     Result = DAG.getNode(
6464         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6465         DAG.getTargetConstant((int)*RoundMode, sdl,
6466                               TLI.getPointerTy(DAG.getDataLayout())));
6467     setValue(&I, Result);
6468 
6469     return;
6470   }
6471   case Intrinsic::fmuladd: {
6472     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6473     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6474         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6475       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6476                                getValue(I.getArgOperand(0)).getValueType(),
6477                                getValue(I.getArgOperand(0)),
6478                                getValue(I.getArgOperand(1)),
6479                                getValue(I.getArgOperand(2)), Flags));
6480     } else {
6481       // TODO: Intrinsic calls should have fast-math-flags.
6482       SDValue Mul = DAG.getNode(
6483           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6484           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6485       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6486                                 getValue(I.getArgOperand(0)).getValueType(),
6487                                 Mul, getValue(I.getArgOperand(2)), Flags);
6488       setValue(&I, Add);
6489     }
6490     return;
6491   }
6492   case Intrinsic::convert_to_fp16:
6493     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6494                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6495                                          getValue(I.getArgOperand(0)),
6496                                          DAG.getTargetConstant(0, sdl,
6497                                                                MVT::i32))));
6498     return;
6499   case Intrinsic::convert_from_fp16:
6500     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6501                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6502                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6503                                          getValue(I.getArgOperand(0)))));
6504     return;
6505   case Intrinsic::fptosi_sat: {
6506     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6507     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6508                              getValue(I.getArgOperand(0)),
6509                              DAG.getValueType(VT.getScalarType())));
6510     return;
6511   }
6512   case Intrinsic::fptoui_sat: {
6513     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6514     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6515                              getValue(I.getArgOperand(0)),
6516                              DAG.getValueType(VT.getScalarType())));
6517     return;
6518   }
6519   case Intrinsic::set_rounding:
6520     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6521                       {getRoot(), getValue(I.getArgOperand(0))});
6522     setValue(&I, Res);
6523     DAG.setRoot(Res.getValue(0));
6524     return;
6525   case Intrinsic::is_fpclass: {
6526     const DataLayout DLayout = DAG.getDataLayout();
6527     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6528     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6529     FPClassTest Test = static_cast<FPClassTest>(
6530         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6531     MachineFunction &MF = DAG.getMachineFunction();
6532     const Function &F = MF.getFunction();
6533     SDValue Op = getValue(I.getArgOperand(0));
6534     SDNodeFlags Flags;
6535     Flags.setNoFPExcept(
6536         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6537     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6538     // expansion can use illegal types. Making expansion early allows
6539     // legalizing these types prior to selection.
6540     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6541       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6542       setValue(&I, Result);
6543       return;
6544     }
6545 
6546     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6547     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6548     setValue(&I, V);
6549     return;
6550   }
6551   case Intrinsic::pcmarker: {
6552     SDValue Tmp = getValue(I.getArgOperand(0));
6553     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6554     return;
6555   }
6556   case Intrinsic::readcyclecounter: {
6557     SDValue Op = getRoot();
6558     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6559                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6560     setValue(&I, Res);
6561     DAG.setRoot(Res.getValue(1));
6562     return;
6563   }
6564   case Intrinsic::bitreverse:
6565     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6566                              getValue(I.getArgOperand(0)).getValueType(),
6567                              getValue(I.getArgOperand(0))));
6568     return;
6569   case Intrinsic::bswap:
6570     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6571                              getValue(I.getArgOperand(0)).getValueType(),
6572                              getValue(I.getArgOperand(0))));
6573     return;
6574   case Intrinsic::cttz: {
6575     SDValue Arg = getValue(I.getArgOperand(0));
6576     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6577     EVT Ty = Arg.getValueType();
6578     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6579                              sdl, Ty, Arg));
6580     return;
6581   }
6582   case Intrinsic::ctlz: {
6583     SDValue Arg = getValue(I.getArgOperand(0));
6584     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6585     EVT Ty = Arg.getValueType();
6586     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6587                              sdl, Ty, Arg));
6588     return;
6589   }
6590   case Intrinsic::ctpop: {
6591     SDValue Arg = getValue(I.getArgOperand(0));
6592     EVT Ty = Arg.getValueType();
6593     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6594     return;
6595   }
6596   case Intrinsic::fshl:
6597   case Intrinsic::fshr: {
6598     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6599     SDValue X = getValue(I.getArgOperand(0));
6600     SDValue Y = getValue(I.getArgOperand(1));
6601     SDValue Z = getValue(I.getArgOperand(2));
6602     EVT VT = X.getValueType();
6603 
6604     if (X == Y) {
6605       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6606       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6607     } else {
6608       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6609       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6610     }
6611     return;
6612   }
6613   case Intrinsic::sadd_sat: {
6614     SDValue Op1 = getValue(I.getArgOperand(0));
6615     SDValue Op2 = getValue(I.getArgOperand(1));
6616     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6617     return;
6618   }
6619   case Intrinsic::uadd_sat: {
6620     SDValue Op1 = getValue(I.getArgOperand(0));
6621     SDValue Op2 = getValue(I.getArgOperand(1));
6622     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6623     return;
6624   }
6625   case Intrinsic::ssub_sat: {
6626     SDValue Op1 = getValue(I.getArgOperand(0));
6627     SDValue Op2 = getValue(I.getArgOperand(1));
6628     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6629     return;
6630   }
6631   case Intrinsic::usub_sat: {
6632     SDValue Op1 = getValue(I.getArgOperand(0));
6633     SDValue Op2 = getValue(I.getArgOperand(1));
6634     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6635     return;
6636   }
6637   case Intrinsic::sshl_sat: {
6638     SDValue Op1 = getValue(I.getArgOperand(0));
6639     SDValue Op2 = getValue(I.getArgOperand(1));
6640     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6641     return;
6642   }
6643   case Intrinsic::ushl_sat: {
6644     SDValue Op1 = getValue(I.getArgOperand(0));
6645     SDValue Op2 = getValue(I.getArgOperand(1));
6646     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6647     return;
6648   }
6649   case Intrinsic::smul_fix:
6650   case Intrinsic::umul_fix:
6651   case Intrinsic::smul_fix_sat:
6652   case Intrinsic::umul_fix_sat: {
6653     SDValue Op1 = getValue(I.getArgOperand(0));
6654     SDValue Op2 = getValue(I.getArgOperand(1));
6655     SDValue Op3 = getValue(I.getArgOperand(2));
6656     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6657                              Op1.getValueType(), Op1, Op2, Op3));
6658     return;
6659   }
6660   case Intrinsic::sdiv_fix:
6661   case Intrinsic::udiv_fix:
6662   case Intrinsic::sdiv_fix_sat:
6663   case Intrinsic::udiv_fix_sat: {
6664     SDValue Op1 = getValue(I.getArgOperand(0));
6665     SDValue Op2 = getValue(I.getArgOperand(1));
6666     SDValue Op3 = getValue(I.getArgOperand(2));
6667     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6668                               Op1, Op2, Op3, DAG, TLI));
6669     return;
6670   }
6671   case Intrinsic::smax: {
6672     SDValue Op1 = getValue(I.getArgOperand(0));
6673     SDValue Op2 = getValue(I.getArgOperand(1));
6674     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6675     return;
6676   }
6677   case Intrinsic::smin: {
6678     SDValue Op1 = getValue(I.getArgOperand(0));
6679     SDValue Op2 = getValue(I.getArgOperand(1));
6680     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6681     return;
6682   }
6683   case Intrinsic::umax: {
6684     SDValue Op1 = getValue(I.getArgOperand(0));
6685     SDValue Op2 = getValue(I.getArgOperand(1));
6686     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6687     return;
6688   }
6689   case Intrinsic::umin: {
6690     SDValue Op1 = getValue(I.getArgOperand(0));
6691     SDValue Op2 = getValue(I.getArgOperand(1));
6692     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6693     return;
6694   }
6695   case Intrinsic::abs: {
6696     // TODO: Preserve "int min is poison" arg in SDAG?
6697     SDValue Op1 = getValue(I.getArgOperand(0));
6698     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6699     return;
6700   }
6701   case Intrinsic::stacksave: {
6702     SDValue Op = getRoot();
6703     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6704     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6705     setValue(&I, Res);
6706     DAG.setRoot(Res.getValue(1));
6707     return;
6708   }
6709   case Intrinsic::stackrestore:
6710     Res = getValue(I.getArgOperand(0));
6711     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6712     return;
6713   case Intrinsic::get_dynamic_area_offset: {
6714     SDValue Op = getRoot();
6715     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6716     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6717     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6718     // target.
6719     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6720       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6721                          " intrinsic!");
6722     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6723                       Op);
6724     DAG.setRoot(Op);
6725     setValue(&I, Res);
6726     return;
6727   }
6728   case Intrinsic::stackguard: {
6729     MachineFunction &MF = DAG.getMachineFunction();
6730     const Module &M = *MF.getFunction().getParent();
6731     SDValue Chain = getRoot();
6732     if (TLI.useLoadStackGuardNode()) {
6733       Res = getLoadStackGuard(DAG, sdl, Chain);
6734     } else {
6735       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6736       const Value *Global = TLI.getSDagStackGuard(M);
6737       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6738       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6739                         MachinePointerInfo(Global, 0), Align,
6740                         MachineMemOperand::MOVolatile);
6741     }
6742     if (TLI.useStackGuardXorFP())
6743       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6744     DAG.setRoot(Chain);
6745     setValue(&I, Res);
6746     return;
6747   }
6748   case Intrinsic::stackprotector: {
6749     // Emit code into the DAG to store the stack guard onto the stack.
6750     MachineFunction &MF = DAG.getMachineFunction();
6751     MachineFrameInfo &MFI = MF.getFrameInfo();
6752     SDValue Src, Chain = getRoot();
6753 
6754     if (TLI.useLoadStackGuardNode())
6755       Src = getLoadStackGuard(DAG, sdl, Chain);
6756     else
6757       Src = getValue(I.getArgOperand(0));   // The guard's value.
6758 
6759     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6760 
6761     int FI = FuncInfo.StaticAllocaMap[Slot];
6762     MFI.setStackProtectorIndex(FI);
6763     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6764 
6765     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6766 
6767     // Store the stack protector onto the stack.
6768     Res = DAG.getStore(
6769         Chain, sdl, Src, FIN,
6770         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6771         MaybeAlign(), MachineMemOperand::MOVolatile);
6772     setValue(&I, Res);
6773     DAG.setRoot(Res);
6774     return;
6775   }
6776   case Intrinsic::objectsize:
6777     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6778 
6779   case Intrinsic::is_constant:
6780     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6781 
6782   case Intrinsic::annotation:
6783   case Intrinsic::ptr_annotation:
6784   case Intrinsic::launder_invariant_group:
6785   case Intrinsic::strip_invariant_group:
6786     // Drop the intrinsic, but forward the value
6787     setValue(&I, getValue(I.getOperand(0)));
6788     return;
6789 
6790   case Intrinsic::assume:
6791   case Intrinsic::experimental_noalias_scope_decl:
6792   case Intrinsic::var_annotation:
6793   case Intrinsic::sideeffect:
6794     // Discard annotate attributes, noalias scope declarations, assumptions, and
6795     // artificial side-effects.
6796     return;
6797 
6798   case Intrinsic::codeview_annotation: {
6799     // Emit a label associated with this metadata.
6800     MachineFunction &MF = DAG.getMachineFunction();
6801     MCSymbol *Label =
6802         MF.getMMI().getContext().createTempSymbol("annotation", true);
6803     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6804     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6805     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6806     DAG.setRoot(Res);
6807     return;
6808   }
6809 
6810   case Intrinsic::init_trampoline: {
6811     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6812 
6813     SDValue Ops[6];
6814     Ops[0] = getRoot();
6815     Ops[1] = getValue(I.getArgOperand(0));
6816     Ops[2] = getValue(I.getArgOperand(1));
6817     Ops[3] = getValue(I.getArgOperand(2));
6818     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6819     Ops[5] = DAG.getSrcValue(F);
6820 
6821     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6822 
6823     DAG.setRoot(Res);
6824     return;
6825   }
6826   case Intrinsic::adjust_trampoline:
6827     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6828                              TLI.getPointerTy(DAG.getDataLayout()),
6829                              getValue(I.getArgOperand(0))));
6830     return;
6831   case Intrinsic::gcroot: {
6832     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6833            "only valid in functions with gc specified, enforced by Verifier");
6834     assert(GFI && "implied by previous");
6835     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6836     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6837 
6838     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6839     GFI->addStackRoot(FI->getIndex(), TypeMap);
6840     return;
6841   }
6842   case Intrinsic::gcread:
6843   case Intrinsic::gcwrite:
6844     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6845   case Intrinsic::get_rounding:
6846     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
6847     setValue(&I, Res);
6848     DAG.setRoot(Res.getValue(1));
6849     return;
6850 
6851   case Intrinsic::expect:
6852     // Just replace __builtin_expect(exp, c) with EXP.
6853     setValue(&I, getValue(I.getArgOperand(0)));
6854     return;
6855 
6856   case Intrinsic::ubsantrap:
6857   case Intrinsic::debugtrap:
6858   case Intrinsic::trap: {
6859     StringRef TrapFuncName =
6860         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6861     if (TrapFuncName.empty()) {
6862       switch (Intrinsic) {
6863       case Intrinsic::trap:
6864         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6865         break;
6866       case Intrinsic::debugtrap:
6867         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6868         break;
6869       case Intrinsic::ubsantrap:
6870         DAG.setRoot(DAG.getNode(
6871             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6872             DAG.getTargetConstant(
6873                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6874                 MVT::i32)));
6875         break;
6876       default: llvm_unreachable("unknown trap intrinsic");
6877       }
6878       return;
6879     }
6880     TargetLowering::ArgListTy Args;
6881     if (Intrinsic == Intrinsic::ubsantrap) {
6882       Args.push_back(TargetLoweringBase::ArgListEntry());
6883       Args[0].Val = I.getArgOperand(0);
6884       Args[0].Node = getValue(Args[0].Val);
6885       Args[0].Ty = Args[0].Val->getType();
6886     }
6887 
6888     TargetLowering::CallLoweringInfo CLI(DAG);
6889     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6890         CallingConv::C, I.getType(),
6891         DAG.getExternalSymbol(TrapFuncName.data(),
6892                               TLI.getPointerTy(DAG.getDataLayout())),
6893         std::move(Args));
6894 
6895     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6896     DAG.setRoot(Result.second);
6897     return;
6898   }
6899 
6900   case Intrinsic::uadd_with_overflow:
6901   case Intrinsic::sadd_with_overflow:
6902   case Intrinsic::usub_with_overflow:
6903   case Intrinsic::ssub_with_overflow:
6904   case Intrinsic::umul_with_overflow:
6905   case Intrinsic::smul_with_overflow: {
6906     ISD::NodeType Op;
6907     switch (Intrinsic) {
6908     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6909     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6910     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6911     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6912     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6913     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6914     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6915     }
6916     SDValue Op1 = getValue(I.getArgOperand(0));
6917     SDValue Op2 = getValue(I.getArgOperand(1));
6918 
6919     EVT ResultVT = Op1.getValueType();
6920     EVT OverflowVT = MVT::i1;
6921     if (ResultVT.isVector())
6922       OverflowVT = EVT::getVectorVT(
6923           *Context, OverflowVT, ResultVT.getVectorElementCount());
6924 
6925     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6926     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6927     return;
6928   }
6929   case Intrinsic::prefetch: {
6930     SDValue Ops[5];
6931     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6932     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6933     Ops[0] = DAG.getRoot();
6934     Ops[1] = getValue(I.getArgOperand(0));
6935     Ops[2] = getValue(I.getArgOperand(1));
6936     Ops[3] = getValue(I.getArgOperand(2));
6937     Ops[4] = getValue(I.getArgOperand(3));
6938     SDValue Result = DAG.getMemIntrinsicNode(
6939         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6940         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6941         /* align */ std::nullopt, Flags);
6942 
6943     // Chain the prefetch in parallell with any pending loads, to stay out of
6944     // the way of later optimizations.
6945     PendingLoads.push_back(Result);
6946     Result = getRoot();
6947     DAG.setRoot(Result);
6948     return;
6949   }
6950   case Intrinsic::lifetime_start:
6951   case Intrinsic::lifetime_end: {
6952     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6953     // Stack coloring is not enabled in O0, discard region information.
6954     if (TM.getOptLevel() == CodeGenOpt::None)
6955       return;
6956 
6957     const int64_t ObjectSize =
6958         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6959     Value *const ObjectPtr = I.getArgOperand(1);
6960     SmallVector<const Value *, 4> Allocas;
6961     getUnderlyingObjects(ObjectPtr, Allocas);
6962 
6963     for (const Value *Alloca : Allocas) {
6964       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6965 
6966       // Could not find an Alloca.
6967       if (!LifetimeObject)
6968         continue;
6969 
6970       // First check that the Alloca is static, otherwise it won't have a
6971       // valid frame index.
6972       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6973       if (SI == FuncInfo.StaticAllocaMap.end())
6974         return;
6975 
6976       const int FrameIndex = SI->second;
6977       int64_t Offset;
6978       if (GetPointerBaseWithConstantOffset(
6979               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6980         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6981       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6982                                 Offset);
6983       DAG.setRoot(Res);
6984     }
6985     return;
6986   }
6987   case Intrinsic::pseudoprobe: {
6988     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6989     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6990     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6991     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6992     DAG.setRoot(Res);
6993     return;
6994   }
6995   case Intrinsic::invariant_start:
6996     // Discard region information.
6997     setValue(&I,
6998              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
6999     return;
7000   case Intrinsic::invariant_end:
7001     // Discard region information.
7002     return;
7003   case Intrinsic::clear_cache:
7004     /// FunctionName may be null.
7005     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
7006       lowerCallToExternalSymbol(I, FunctionName);
7007     return;
7008   case Intrinsic::donothing:
7009   case Intrinsic::seh_try_begin:
7010   case Intrinsic::seh_scope_begin:
7011   case Intrinsic::seh_try_end:
7012   case Intrinsic::seh_scope_end:
7013     // ignore
7014     return;
7015   case Intrinsic::experimental_stackmap:
7016     visitStackmap(I);
7017     return;
7018   case Intrinsic::experimental_patchpoint_void:
7019   case Intrinsic::experimental_patchpoint_i64:
7020     visitPatchpoint(I);
7021     return;
7022   case Intrinsic::experimental_gc_statepoint:
7023     LowerStatepoint(cast<GCStatepointInst>(I));
7024     return;
7025   case Intrinsic::experimental_gc_result:
7026     visitGCResult(cast<GCResultInst>(I));
7027     return;
7028   case Intrinsic::experimental_gc_relocate:
7029     visitGCRelocate(cast<GCRelocateInst>(I));
7030     return;
7031   case Intrinsic::instrprof_cover:
7032     llvm_unreachable("instrprof failed to lower a cover");
7033   case Intrinsic::instrprof_increment:
7034     llvm_unreachable("instrprof failed to lower an increment");
7035   case Intrinsic::instrprof_timestamp:
7036     llvm_unreachable("instrprof failed to lower a timestamp");
7037   case Intrinsic::instrprof_value_profile:
7038     llvm_unreachable("instrprof failed to lower a value profiling call");
7039   case Intrinsic::localescape: {
7040     MachineFunction &MF = DAG.getMachineFunction();
7041     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7042 
7043     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7044     // is the same on all targets.
7045     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7046       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7047       if (isa<ConstantPointerNull>(Arg))
7048         continue; // Skip null pointers. They represent a hole in index space.
7049       AllocaInst *Slot = cast<AllocaInst>(Arg);
7050       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7051              "can only escape static allocas");
7052       int FI = FuncInfo.StaticAllocaMap[Slot];
7053       MCSymbol *FrameAllocSym =
7054           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7055               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7056       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7057               TII->get(TargetOpcode::LOCAL_ESCAPE))
7058           .addSym(FrameAllocSym)
7059           .addFrameIndex(FI);
7060     }
7061 
7062     return;
7063   }
7064 
7065   case Intrinsic::localrecover: {
7066     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7067     MachineFunction &MF = DAG.getMachineFunction();
7068 
7069     // Get the symbol that defines the frame offset.
7070     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7071     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7072     unsigned IdxVal =
7073         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7074     MCSymbol *FrameAllocSym =
7075         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7076             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7077 
7078     Value *FP = I.getArgOperand(1);
7079     SDValue FPVal = getValue(FP);
7080     EVT PtrVT = FPVal.getValueType();
7081 
7082     // Create a MCSymbol for the label to avoid any target lowering
7083     // that would make this PC relative.
7084     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7085     SDValue OffsetVal =
7086         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7087 
7088     // Add the offset to the FP.
7089     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7090     setValue(&I, Add);
7091 
7092     return;
7093   }
7094 
7095   case Intrinsic::eh_exceptionpointer:
7096   case Intrinsic::eh_exceptioncode: {
7097     // Get the exception pointer vreg, copy from it, and resize it to fit.
7098     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7099     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7100     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7101     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7102     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7103     if (Intrinsic == Intrinsic::eh_exceptioncode)
7104       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7105     setValue(&I, N);
7106     return;
7107   }
7108   case Intrinsic::xray_customevent: {
7109     // Here we want to make sure that the intrinsic behaves as if it has a
7110     // specific calling convention, and only for x86_64.
7111     // FIXME: Support other platforms later.
7112     const auto &Triple = DAG.getTarget().getTargetTriple();
7113     if (Triple.getArch() != Triple::x86_64)
7114       return;
7115 
7116     SmallVector<SDValue, 8> Ops;
7117 
7118     // We want to say that we always want the arguments in registers.
7119     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7120     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7121     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7122     SDValue Chain = getRoot();
7123     Ops.push_back(LogEntryVal);
7124     Ops.push_back(StrSizeVal);
7125     Ops.push_back(Chain);
7126 
7127     // We need to enforce the calling convention for the callsite, so that
7128     // argument ordering is enforced correctly, and that register allocation can
7129     // see that some registers may be assumed clobbered and have to preserve
7130     // them across calls to the intrinsic.
7131     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7132                                            sdl, NodeTys, Ops);
7133     SDValue patchableNode = SDValue(MN, 0);
7134     DAG.setRoot(patchableNode);
7135     setValue(&I, patchableNode);
7136     return;
7137   }
7138   case Intrinsic::xray_typedevent: {
7139     // Here we want to make sure that the intrinsic behaves as if it has a
7140     // specific calling convention, and only for x86_64.
7141     // FIXME: Support other platforms later.
7142     const auto &Triple = DAG.getTarget().getTargetTriple();
7143     if (Triple.getArch() != Triple::x86_64)
7144       return;
7145 
7146     SmallVector<SDValue, 8> Ops;
7147 
7148     // We want to say that we always want the arguments in registers.
7149     // It's unclear to me how manipulating the selection DAG here forces callers
7150     // to provide arguments in registers instead of on the stack.
7151     SDValue LogTypeId = getValue(I.getArgOperand(0));
7152     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7153     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7154     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7155     SDValue Chain = getRoot();
7156     Ops.push_back(LogTypeId);
7157     Ops.push_back(LogEntryVal);
7158     Ops.push_back(StrSizeVal);
7159     Ops.push_back(Chain);
7160 
7161     // We need to enforce the calling convention for the callsite, so that
7162     // argument ordering is enforced correctly, and that register allocation can
7163     // see that some registers may be assumed clobbered and have to preserve
7164     // them across calls to the intrinsic.
7165     MachineSDNode *MN = DAG.getMachineNode(
7166         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7167     SDValue patchableNode = SDValue(MN, 0);
7168     DAG.setRoot(patchableNode);
7169     setValue(&I, patchableNode);
7170     return;
7171   }
7172   case Intrinsic::experimental_deoptimize:
7173     LowerDeoptimizeCall(&I);
7174     return;
7175   case Intrinsic::experimental_stepvector:
7176     visitStepVector(I);
7177     return;
7178   case Intrinsic::vector_reduce_fadd:
7179   case Intrinsic::vector_reduce_fmul:
7180   case Intrinsic::vector_reduce_add:
7181   case Intrinsic::vector_reduce_mul:
7182   case Intrinsic::vector_reduce_and:
7183   case Intrinsic::vector_reduce_or:
7184   case Intrinsic::vector_reduce_xor:
7185   case Intrinsic::vector_reduce_smax:
7186   case Intrinsic::vector_reduce_smin:
7187   case Intrinsic::vector_reduce_umax:
7188   case Intrinsic::vector_reduce_umin:
7189   case Intrinsic::vector_reduce_fmax:
7190   case Intrinsic::vector_reduce_fmin:
7191     visitVectorReduce(I, Intrinsic);
7192     return;
7193 
7194   case Intrinsic::icall_branch_funnel: {
7195     SmallVector<SDValue, 16> Ops;
7196     Ops.push_back(getValue(I.getArgOperand(0)));
7197 
7198     int64_t Offset;
7199     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7200         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7201     if (!Base)
7202       report_fatal_error(
7203           "llvm.icall.branch.funnel operand must be a GlobalValue");
7204     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7205 
7206     struct BranchFunnelTarget {
7207       int64_t Offset;
7208       SDValue Target;
7209     };
7210     SmallVector<BranchFunnelTarget, 8> Targets;
7211 
7212     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7213       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7214           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7215       if (ElemBase != Base)
7216         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7217                            "to the same GlobalValue");
7218 
7219       SDValue Val = getValue(I.getArgOperand(Op + 1));
7220       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7221       if (!GA)
7222         report_fatal_error(
7223             "llvm.icall.branch.funnel operand must be a GlobalValue");
7224       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7225                                      GA->getGlobal(), sdl, Val.getValueType(),
7226                                      GA->getOffset())});
7227     }
7228     llvm::sort(Targets,
7229                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7230                  return T1.Offset < T2.Offset;
7231                });
7232 
7233     for (auto &T : Targets) {
7234       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7235       Ops.push_back(T.Target);
7236     }
7237 
7238     Ops.push_back(DAG.getRoot()); // Chain
7239     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7240                                  MVT::Other, Ops),
7241               0);
7242     DAG.setRoot(N);
7243     setValue(&I, N);
7244     HasTailCall = true;
7245     return;
7246   }
7247 
7248   case Intrinsic::wasm_landingpad_index:
7249     // Information this intrinsic contained has been transferred to
7250     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7251     // delete it now.
7252     return;
7253 
7254   case Intrinsic::aarch64_settag:
7255   case Intrinsic::aarch64_settag_zero: {
7256     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7257     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7258     SDValue Val = TSI.EmitTargetCodeForSetTag(
7259         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7260         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7261         ZeroMemory);
7262     DAG.setRoot(Val);
7263     setValue(&I, Val);
7264     return;
7265   }
7266   case Intrinsic::ptrmask: {
7267     SDValue Ptr = getValue(I.getOperand(0));
7268     SDValue Const = getValue(I.getOperand(1));
7269 
7270     EVT PtrVT = Ptr.getValueType();
7271     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7272                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7273     return;
7274   }
7275   case Intrinsic::threadlocal_address: {
7276     setValue(&I, getValue(I.getOperand(0)));
7277     return;
7278   }
7279   case Intrinsic::get_active_lane_mask: {
7280     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7281     SDValue Index = getValue(I.getOperand(0));
7282     EVT ElementVT = Index.getValueType();
7283 
7284     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7285       visitTargetIntrinsic(I, Intrinsic);
7286       return;
7287     }
7288 
7289     SDValue TripCount = getValue(I.getOperand(1));
7290     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7291 
7292     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7293     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7294     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7295     SDValue VectorInduction = DAG.getNode(
7296         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7297     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7298                                  VectorTripCount, ISD::CondCode::SETULT);
7299     setValue(&I, SetCC);
7300     return;
7301   }
7302   case Intrinsic::vector_insert: {
7303     SDValue Vec = getValue(I.getOperand(0));
7304     SDValue SubVec = getValue(I.getOperand(1));
7305     SDValue Index = getValue(I.getOperand(2));
7306 
7307     // The intrinsic's index type is i64, but the SDNode requires an index type
7308     // suitable for the target. Convert the index as required.
7309     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7310     if (Index.getValueType() != VectorIdxTy)
7311       Index = DAG.getVectorIdxConstant(
7312           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7313 
7314     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7315     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7316                              Index));
7317     return;
7318   }
7319   case Intrinsic::vector_extract: {
7320     SDValue Vec = getValue(I.getOperand(0));
7321     SDValue Index = getValue(I.getOperand(1));
7322     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7323 
7324     // The intrinsic's index type is i64, but the SDNode requires an index type
7325     // suitable for the target. Convert the index as required.
7326     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7327     if (Index.getValueType() != VectorIdxTy)
7328       Index = DAG.getVectorIdxConstant(
7329           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7330 
7331     setValue(&I,
7332              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7333     return;
7334   }
7335   case Intrinsic::experimental_vector_reverse:
7336     visitVectorReverse(I);
7337     return;
7338   case Intrinsic::experimental_vector_splice:
7339     visitVectorSplice(I);
7340     return;
7341   case Intrinsic::callbr_landingpad:
7342     visitCallBrLandingPad(I);
7343     return;
7344   case Intrinsic::experimental_vector_interleave2:
7345     visitVectorInterleave(I);
7346     return;
7347   case Intrinsic::experimental_vector_deinterleave2:
7348     visitVectorDeinterleave(I);
7349     return;
7350   }
7351 }
7352 
7353 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7354     const ConstrainedFPIntrinsic &FPI) {
7355   SDLoc sdl = getCurSDLoc();
7356 
7357   // We do not need to serialize constrained FP intrinsics against
7358   // each other or against (nonvolatile) loads, so they can be
7359   // chained like loads.
7360   SDValue Chain = DAG.getRoot();
7361   SmallVector<SDValue, 4> Opers;
7362   Opers.push_back(Chain);
7363   if (FPI.isUnaryOp()) {
7364     Opers.push_back(getValue(FPI.getArgOperand(0)));
7365   } else if (FPI.isTernaryOp()) {
7366     Opers.push_back(getValue(FPI.getArgOperand(0)));
7367     Opers.push_back(getValue(FPI.getArgOperand(1)));
7368     Opers.push_back(getValue(FPI.getArgOperand(2)));
7369   } else {
7370     Opers.push_back(getValue(FPI.getArgOperand(0)));
7371     Opers.push_back(getValue(FPI.getArgOperand(1)));
7372   }
7373 
7374   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7375     assert(Result.getNode()->getNumValues() == 2);
7376 
7377     // Push node to the appropriate list so that future instructions can be
7378     // chained up correctly.
7379     SDValue OutChain = Result.getValue(1);
7380     switch (EB) {
7381     case fp::ExceptionBehavior::ebIgnore:
7382       // The only reason why ebIgnore nodes still need to be chained is that
7383       // they might depend on the current rounding mode, and therefore must
7384       // not be moved across instruction that may change that mode.
7385       [[fallthrough]];
7386     case fp::ExceptionBehavior::ebMayTrap:
7387       // These must not be moved across calls or instructions that may change
7388       // floating-point exception masks.
7389       PendingConstrainedFP.push_back(OutChain);
7390       break;
7391     case fp::ExceptionBehavior::ebStrict:
7392       // These must not be moved across calls or instructions that may change
7393       // floating-point exception masks or read floating-point exception flags.
7394       // In addition, they cannot be optimized out even if unused.
7395       PendingConstrainedFPStrict.push_back(OutChain);
7396       break;
7397     }
7398   };
7399 
7400   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7401   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7402   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7403   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7404 
7405   SDNodeFlags Flags;
7406   if (EB == fp::ExceptionBehavior::ebIgnore)
7407     Flags.setNoFPExcept(true);
7408 
7409   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7410     Flags.copyFMF(*FPOp);
7411 
7412   unsigned Opcode;
7413   switch (FPI.getIntrinsicID()) {
7414   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7415 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7416   case Intrinsic::INTRINSIC:                                                   \
7417     Opcode = ISD::STRICT_##DAGN;                                               \
7418     break;
7419 #include "llvm/IR/ConstrainedOps.def"
7420   case Intrinsic::experimental_constrained_fmuladd: {
7421     Opcode = ISD::STRICT_FMA;
7422     // Break fmuladd into fmul and fadd.
7423     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7424         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7425       Opers.pop_back();
7426       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7427       pushOutChain(Mul, EB);
7428       Opcode = ISD::STRICT_FADD;
7429       Opers.clear();
7430       Opers.push_back(Mul.getValue(1));
7431       Opers.push_back(Mul.getValue(0));
7432       Opers.push_back(getValue(FPI.getArgOperand(2)));
7433     }
7434     break;
7435   }
7436   }
7437 
7438   // A few strict DAG nodes carry additional operands that are not
7439   // set up by the default code above.
7440   switch (Opcode) {
7441   default: break;
7442   case ISD::STRICT_FP_ROUND:
7443     Opers.push_back(
7444         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7445     break;
7446   case ISD::STRICT_FSETCC:
7447   case ISD::STRICT_FSETCCS: {
7448     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7449     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7450     if (TM.Options.NoNaNsFPMath)
7451       Condition = getFCmpCodeWithoutNaN(Condition);
7452     Opers.push_back(DAG.getCondCode(Condition));
7453     break;
7454   }
7455   }
7456 
7457   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7458   pushOutChain(Result, EB);
7459 
7460   SDValue FPResult = Result.getValue(0);
7461   setValue(&FPI, FPResult);
7462 }
7463 
7464 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7465   std::optional<unsigned> ResOPC;
7466   switch (VPIntrin.getIntrinsicID()) {
7467   case Intrinsic::vp_ctlz: {
7468     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7469     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
7470     break;
7471   }
7472   case Intrinsic::vp_cttz: {
7473     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7474     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
7475     break;
7476   }
7477 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7478   case Intrinsic::VPID:                                                        \
7479     ResOPC = ISD::VPSD;                                                        \
7480     break;
7481 #include "llvm/IR/VPIntrinsics.def"
7482   }
7483 
7484   if (!ResOPC)
7485     llvm_unreachable(
7486         "Inconsistency: no SDNode available for this VPIntrinsic!");
7487 
7488   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7489       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7490     if (VPIntrin.getFastMathFlags().allowReassoc())
7491       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7492                                                 : ISD::VP_REDUCE_FMUL;
7493   }
7494 
7495   return *ResOPC;
7496 }
7497 
7498 void SelectionDAGBuilder::visitVPLoad(
7499     const VPIntrinsic &VPIntrin, EVT VT,
7500     const SmallVectorImpl<SDValue> &OpValues) {
7501   SDLoc DL = getCurSDLoc();
7502   Value *PtrOperand = VPIntrin.getArgOperand(0);
7503   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7504   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7505   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7506   SDValue LD;
7507   // Do not serialize variable-length loads of constant memory with
7508   // anything.
7509   if (!Alignment)
7510     Alignment = DAG.getEVTAlign(VT);
7511   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7512   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7513   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7514   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7515       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7516       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7517   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7518                      MMO, false /*IsExpanding */);
7519   if (AddToChain)
7520     PendingLoads.push_back(LD.getValue(1));
7521   setValue(&VPIntrin, LD);
7522 }
7523 
7524 void SelectionDAGBuilder::visitVPGather(
7525     const VPIntrinsic &VPIntrin, EVT VT,
7526     const SmallVectorImpl<SDValue> &OpValues) {
7527   SDLoc DL = getCurSDLoc();
7528   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7529   Value *PtrOperand = VPIntrin.getArgOperand(0);
7530   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7531   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7532   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7533   SDValue LD;
7534   if (!Alignment)
7535     Alignment = DAG.getEVTAlign(VT.getScalarType());
7536   unsigned AS =
7537     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7538   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7539      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7540      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7541   SDValue Base, Index, Scale;
7542   ISD::MemIndexType IndexType;
7543   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7544                                     this, VPIntrin.getParent(),
7545                                     VT.getScalarStoreSize());
7546   if (!UniformBase) {
7547     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7548     Index = getValue(PtrOperand);
7549     IndexType = ISD::SIGNED_SCALED;
7550     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7551   }
7552   EVT IdxVT = Index.getValueType();
7553   EVT EltTy = IdxVT.getVectorElementType();
7554   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7555     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7556     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7557   }
7558   LD = DAG.getGatherVP(
7559       DAG.getVTList(VT, MVT::Other), VT, DL,
7560       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7561       IndexType);
7562   PendingLoads.push_back(LD.getValue(1));
7563   setValue(&VPIntrin, LD);
7564 }
7565 
7566 void SelectionDAGBuilder::visitVPStore(
7567     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7568   SDLoc DL = getCurSDLoc();
7569   Value *PtrOperand = VPIntrin.getArgOperand(1);
7570   EVT VT = OpValues[0].getValueType();
7571   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7572   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7573   SDValue ST;
7574   if (!Alignment)
7575     Alignment = DAG.getEVTAlign(VT);
7576   SDValue Ptr = OpValues[1];
7577   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7578   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7579       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7580       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7581   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7582                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7583                       /* IsTruncating */ false, /*IsCompressing*/ false);
7584   DAG.setRoot(ST);
7585   setValue(&VPIntrin, ST);
7586 }
7587 
7588 void SelectionDAGBuilder::visitVPScatter(
7589     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7590   SDLoc DL = getCurSDLoc();
7591   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7592   Value *PtrOperand = VPIntrin.getArgOperand(1);
7593   EVT VT = OpValues[0].getValueType();
7594   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7595   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7596   SDValue ST;
7597   if (!Alignment)
7598     Alignment = DAG.getEVTAlign(VT.getScalarType());
7599   unsigned AS =
7600       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7601   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7602       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7603       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7604   SDValue Base, Index, Scale;
7605   ISD::MemIndexType IndexType;
7606   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7607                                     this, VPIntrin.getParent(),
7608                                     VT.getScalarStoreSize());
7609   if (!UniformBase) {
7610     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7611     Index = getValue(PtrOperand);
7612     IndexType = ISD::SIGNED_SCALED;
7613     Scale =
7614       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7615   }
7616   EVT IdxVT = Index.getValueType();
7617   EVT EltTy = IdxVT.getVectorElementType();
7618   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7619     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7620     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7621   }
7622   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7623                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7624                          OpValues[2], OpValues[3]},
7625                         MMO, IndexType);
7626   DAG.setRoot(ST);
7627   setValue(&VPIntrin, ST);
7628 }
7629 
7630 void SelectionDAGBuilder::visitVPStridedLoad(
7631     const VPIntrinsic &VPIntrin, EVT VT,
7632     const SmallVectorImpl<SDValue> &OpValues) {
7633   SDLoc DL = getCurSDLoc();
7634   Value *PtrOperand = VPIntrin.getArgOperand(0);
7635   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7636   if (!Alignment)
7637     Alignment = DAG.getEVTAlign(VT.getScalarType());
7638   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7639   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7640   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7641   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7642   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7643   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7644       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7645       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7646 
7647   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7648                                     OpValues[2], OpValues[3], MMO,
7649                                     false /*IsExpanding*/);
7650 
7651   if (AddToChain)
7652     PendingLoads.push_back(LD.getValue(1));
7653   setValue(&VPIntrin, LD);
7654 }
7655 
7656 void SelectionDAGBuilder::visitVPStridedStore(
7657     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7658   SDLoc DL = getCurSDLoc();
7659   Value *PtrOperand = VPIntrin.getArgOperand(1);
7660   EVT VT = OpValues[0].getValueType();
7661   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7662   if (!Alignment)
7663     Alignment = DAG.getEVTAlign(VT.getScalarType());
7664   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7665   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7666       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7667       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7668 
7669   SDValue ST = DAG.getStridedStoreVP(
7670       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7671       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7672       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7673       /*IsCompressing*/ false);
7674 
7675   DAG.setRoot(ST);
7676   setValue(&VPIntrin, ST);
7677 }
7678 
7679 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
7680   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7681   SDLoc DL = getCurSDLoc();
7682 
7683   ISD::CondCode Condition;
7684   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
7685   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
7686   if (IsFP) {
7687     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
7688     // flags, but calls that don't return floating-point types can't be
7689     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
7690     Condition = getFCmpCondCode(CondCode);
7691     if (TM.Options.NoNaNsFPMath)
7692       Condition = getFCmpCodeWithoutNaN(Condition);
7693   } else {
7694     Condition = getICmpCondCode(CondCode);
7695   }
7696 
7697   SDValue Op1 = getValue(VPIntrin.getOperand(0));
7698   SDValue Op2 = getValue(VPIntrin.getOperand(1));
7699   // #2 is the condition code
7700   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
7701   SDValue EVL = getValue(VPIntrin.getOperand(4));
7702   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7703   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7704          "Unexpected target EVL type");
7705   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
7706 
7707   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7708                                                         VPIntrin.getType());
7709   setValue(&VPIntrin,
7710            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
7711 }
7712 
7713 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7714     const VPIntrinsic &VPIntrin) {
7715   SDLoc DL = getCurSDLoc();
7716   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7717 
7718   auto IID = VPIntrin.getIntrinsicID();
7719 
7720   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
7721     return visitVPCmp(*CmpI);
7722 
7723   SmallVector<EVT, 4> ValueVTs;
7724   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7725   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7726   SDVTList VTs = DAG.getVTList(ValueVTs);
7727 
7728   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
7729 
7730   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7731   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7732          "Unexpected target EVL type");
7733 
7734   // Request operands.
7735   SmallVector<SDValue, 7> OpValues;
7736   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7737     auto Op = getValue(VPIntrin.getArgOperand(I));
7738     if (I == EVLParamPos)
7739       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7740     OpValues.push_back(Op);
7741   }
7742 
7743   switch (Opcode) {
7744   default: {
7745     SDNodeFlags SDFlags;
7746     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7747       SDFlags.copyFMF(*FPMO);
7748     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
7749     setValue(&VPIntrin, Result);
7750     break;
7751   }
7752   case ISD::VP_LOAD:
7753     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
7754     break;
7755   case ISD::VP_GATHER:
7756     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
7757     break;
7758   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7759     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7760     break;
7761   case ISD::VP_STORE:
7762     visitVPStore(VPIntrin, OpValues);
7763     break;
7764   case ISD::VP_SCATTER:
7765     visitVPScatter(VPIntrin, OpValues);
7766     break;
7767   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7768     visitVPStridedStore(VPIntrin, OpValues);
7769     break;
7770   case ISD::VP_FMULADD: {
7771     assert(OpValues.size() == 5 && "Unexpected number of operands");
7772     SDNodeFlags SDFlags;
7773     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7774       SDFlags.copyFMF(*FPMO);
7775     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7776         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
7777       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
7778     } else {
7779       SDValue Mul = DAG.getNode(
7780           ISD::VP_FMUL, DL, VTs,
7781           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
7782       SDValue Add =
7783           DAG.getNode(ISD::VP_FADD, DL, VTs,
7784                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
7785       setValue(&VPIntrin, Add);
7786     }
7787     break;
7788   }
7789   case ISD::VP_INTTOPTR: {
7790     SDValue N = OpValues[0];
7791     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
7792     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
7793     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7794                                OpValues[2]);
7795     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7796                              OpValues[2]);
7797     setValue(&VPIntrin, N);
7798     break;
7799   }
7800   case ISD::VP_PTRTOINT: {
7801     SDValue N = OpValues[0];
7802     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7803                                                           VPIntrin.getType());
7804     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
7805                                        VPIntrin.getOperand(0)->getType());
7806     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7807                                OpValues[2]);
7808     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7809                              OpValues[2]);
7810     setValue(&VPIntrin, N);
7811     break;
7812   }
7813   case ISD::VP_ABS:
7814   case ISD::VP_CTLZ:
7815   case ISD::VP_CTLZ_ZERO_UNDEF:
7816   case ISD::VP_CTTZ:
7817   case ISD::VP_CTTZ_ZERO_UNDEF: {
7818     SDValue Result =
7819         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
7820     setValue(&VPIntrin, Result);
7821     break;
7822   }
7823   }
7824 }
7825 
7826 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7827                                           const BasicBlock *EHPadBB,
7828                                           MCSymbol *&BeginLabel) {
7829   MachineFunction &MF = DAG.getMachineFunction();
7830   MachineModuleInfo &MMI = MF.getMMI();
7831 
7832   // Insert a label before the invoke call to mark the try range.  This can be
7833   // used to detect deletion of the invoke via the MachineModuleInfo.
7834   BeginLabel = MMI.getContext().createTempSymbol();
7835 
7836   // For SjLj, keep track of which landing pads go with which invokes
7837   // so as to maintain the ordering of pads in the LSDA.
7838   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7839   if (CallSiteIndex) {
7840     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7841     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7842 
7843     // Now that the call site is handled, stop tracking it.
7844     MMI.setCurrentCallSite(0);
7845   }
7846 
7847   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7848 }
7849 
7850 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7851                                         const BasicBlock *EHPadBB,
7852                                         MCSymbol *BeginLabel) {
7853   assert(BeginLabel && "BeginLabel should've been set");
7854 
7855   MachineFunction &MF = DAG.getMachineFunction();
7856   MachineModuleInfo &MMI = MF.getMMI();
7857 
7858   // Insert a label at the end of the invoke call to mark the try range.  This
7859   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7860   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7861   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7862 
7863   // Inform MachineModuleInfo of range.
7864   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7865   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7866   // actually use outlined funclets and their LSDA info style.
7867   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7868     assert(II && "II should've been set");
7869     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7870     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7871   } else if (!isScopedEHPersonality(Pers)) {
7872     assert(EHPadBB);
7873     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7874   }
7875 
7876   return Chain;
7877 }
7878 
7879 std::pair<SDValue, SDValue>
7880 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7881                                     const BasicBlock *EHPadBB) {
7882   MCSymbol *BeginLabel = nullptr;
7883 
7884   if (EHPadBB) {
7885     // Both PendingLoads and PendingExports must be flushed here;
7886     // this call might not return.
7887     (void)getRoot();
7888     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7889     CLI.setChain(getRoot());
7890   }
7891 
7892   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7893   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7894 
7895   assert((CLI.IsTailCall || Result.second.getNode()) &&
7896          "Non-null chain expected with non-tail call!");
7897   assert((Result.second.getNode() || !Result.first.getNode()) &&
7898          "Null value expected with tail call!");
7899 
7900   if (!Result.second.getNode()) {
7901     // As a special case, a null chain means that a tail call has been emitted
7902     // and the DAG root is already updated.
7903     HasTailCall = true;
7904 
7905     // Since there's no actual continuation from this block, nothing can be
7906     // relying on us setting vregs for them.
7907     PendingExports.clear();
7908   } else {
7909     DAG.setRoot(Result.second);
7910   }
7911 
7912   if (EHPadBB) {
7913     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7914                            BeginLabel));
7915   }
7916 
7917   return Result;
7918 }
7919 
7920 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7921                                       bool isTailCall,
7922                                       bool isMustTailCall,
7923                                       const BasicBlock *EHPadBB) {
7924   auto &DL = DAG.getDataLayout();
7925   FunctionType *FTy = CB.getFunctionType();
7926   Type *RetTy = CB.getType();
7927 
7928   TargetLowering::ArgListTy Args;
7929   Args.reserve(CB.arg_size());
7930 
7931   const Value *SwiftErrorVal = nullptr;
7932   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7933 
7934   if (isTailCall) {
7935     // Avoid emitting tail calls in functions with the disable-tail-calls
7936     // attribute.
7937     auto *Caller = CB.getParent()->getParent();
7938     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7939         "true" && !isMustTailCall)
7940       isTailCall = false;
7941 
7942     // We can't tail call inside a function with a swifterror argument. Lowering
7943     // does not support this yet. It would have to move into the swifterror
7944     // register before the call.
7945     if (TLI.supportSwiftError() &&
7946         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7947       isTailCall = false;
7948   }
7949 
7950   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7951     TargetLowering::ArgListEntry Entry;
7952     const Value *V = *I;
7953 
7954     // Skip empty types
7955     if (V->getType()->isEmptyTy())
7956       continue;
7957 
7958     SDValue ArgNode = getValue(V);
7959     Entry.Node = ArgNode; Entry.Ty = V->getType();
7960 
7961     Entry.setAttributes(&CB, I - CB.arg_begin());
7962 
7963     // Use swifterror virtual register as input to the call.
7964     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7965       SwiftErrorVal = V;
7966       // We find the virtual register for the actual swifterror argument.
7967       // Instead of using the Value, we use the virtual register instead.
7968       Entry.Node =
7969           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7970                           EVT(TLI.getPointerTy(DL)));
7971     }
7972 
7973     Args.push_back(Entry);
7974 
7975     // If we have an explicit sret argument that is an Instruction, (i.e., it
7976     // might point to function-local memory), we can't meaningfully tail-call.
7977     if (Entry.IsSRet && isa<Instruction>(V))
7978       isTailCall = false;
7979   }
7980 
7981   // If call site has a cfguardtarget operand bundle, create and add an
7982   // additional ArgListEntry.
7983   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7984     TargetLowering::ArgListEntry Entry;
7985     Value *V = Bundle->Inputs[0];
7986     SDValue ArgNode = getValue(V);
7987     Entry.Node = ArgNode;
7988     Entry.Ty = V->getType();
7989     Entry.IsCFGuardTarget = true;
7990     Args.push_back(Entry);
7991   }
7992 
7993   // Check if target-independent constraints permit a tail call here.
7994   // Target-dependent constraints are checked within TLI->LowerCallTo.
7995   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7996     isTailCall = false;
7997 
7998   // Disable tail calls if there is an swifterror argument. Targets have not
7999   // been updated to support tail calls.
8000   if (TLI.supportSwiftError() && SwiftErrorVal)
8001     isTailCall = false;
8002 
8003   ConstantInt *CFIType = nullptr;
8004   if (CB.isIndirectCall()) {
8005     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8006       if (!TLI.supportKCFIBundles())
8007         report_fatal_error(
8008             "Target doesn't support calls with kcfi operand bundles.");
8009       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8010       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8011     }
8012   }
8013 
8014   TargetLowering::CallLoweringInfo CLI(DAG);
8015   CLI.setDebugLoc(getCurSDLoc())
8016       .setChain(getRoot())
8017       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8018       .setTailCall(isTailCall)
8019       .setConvergent(CB.isConvergent())
8020       .setIsPreallocated(
8021           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8022       .setCFIType(CFIType);
8023   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8024 
8025   if (Result.first.getNode()) {
8026     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8027     setValue(&CB, Result.first);
8028   }
8029 
8030   // The last element of CLI.InVals has the SDValue for swifterror return.
8031   // Here we copy it to a virtual register and update SwiftErrorMap for
8032   // book-keeping.
8033   if (SwiftErrorVal && TLI.supportSwiftError()) {
8034     // Get the last element of InVals.
8035     SDValue Src = CLI.InVals.back();
8036     Register VReg =
8037         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8038     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8039     DAG.setRoot(CopyNode);
8040   }
8041 }
8042 
8043 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8044                              SelectionDAGBuilder &Builder) {
8045   // Check to see if this load can be trivially constant folded, e.g. if the
8046   // input is from a string literal.
8047   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8048     // Cast pointer to the type we really want to load.
8049     Type *LoadTy =
8050         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8051     if (LoadVT.isVector())
8052       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8053 
8054     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8055                                          PointerType::getUnqual(LoadTy));
8056 
8057     if (const Constant *LoadCst =
8058             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8059                                          LoadTy, Builder.DAG.getDataLayout()))
8060       return Builder.getValue(LoadCst);
8061   }
8062 
8063   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8064   // still constant memory, the input chain can be the entry node.
8065   SDValue Root;
8066   bool ConstantMemory = false;
8067 
8068   // Do not serialize (non-volatile) loads of constant memory with anything.
8069   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8070     Root = Builder.DAG.getEntryNode();
8071     ConstantMemory = true;
8072   } else {
8073     // Do not serialize non-volatile loads against each other.
8074     Root = Builder.DAG.getRoot();
8075   }
8076 
8077   SDValue Ptr = Builder.getValue(PtrVal);
8078   SDValue LoadVal =
8079       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8080                           MachinePointerInfo(PtrVal), Align(1));
8081 
8082   if (!ConstantMemory)
8083     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8084   return LoadVal;
8085 }
8086 
8087 /// Record the value for an instruction that produces an integer result,
8088 /// converting the type where necessary.
8089 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8090                                                   SDValue Value,
8091                                                   bool IsSigned) {
8092   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8093                                                     I.getType(), true);
8094   if (IsSigned)
8095     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
8096   else
8097     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
8098   setValue(&I, Value);
8099 }
8100 
8101 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8102 /// true and lower it. Otherwise return false, and it will be lowered like a
8103 /// normal call.
8104 /// The caller already checked that \p I calls the appropriate LibFunc with a
8105 /// correct prototype.
8106 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8107   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8108   const Value *Size = I.getArgOperand(2);
8109   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8110   if (CSize && CSize->getZExtValue() == 0) {
8111     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8112                                                           I.getType(), true);
8113     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8114     return true;
8115   }
8116 
8117   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8118   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8119       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8120       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8121   if (Res.first.getNode()) {
8122     processIntegerCallValue(I, Res.first, true);
8123     PendingLoads.push_back(Res.second);
8124     return true;
8125   }
8126 
8127   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8128   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8129   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8130     return false;
8131 
8132   // If the target has a fast compare for the given size, it will return a
8133   // preferred load type for that size. Require that the load VT is legal and
8134   // that the target supports unaligned loads of that type. Otherwise, return
8135   // INVALID.
8136   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8137     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8138     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8139     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8140       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8141       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8142       // TODO: Check alignment of src and dest ptrs.
8143       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8144       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8145       if (!TLI.isTypeLegal(LVT) ||
8146           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8147           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8148         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8149     }
8150 
8151     return LVT;
8152   };
8153 
8154   // This turns into unaligned loads. We only do this if the target natively
8155   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8156   // we'll only produce a small number of byte loads.
8157   MVT LoadVT;
8158   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8159   switch (NumBitsToCompare) {
8160   default:
8161     return false;
8162   case 16:
8163     LoadVT = MVT::i16;
8164     break;
8165   case 32:
8166     LoadVT = MVT::i32;
8167     break;
8168   case 64:
8169   case 128:
8170   case 256:
8171     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8172     break;
8173   }
8174 
8175   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8176     return false;
8177 
8178   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8179   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8180 
8181   // Bitcast to a wide integer type if the loads are vectors.
8182   if (LoadVT.isVector()) {
8183     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8184     LoadL = DAG.getBitcast(CmpVT, LoadL);
8185     LoadR = DAG.getBitcast(CmpVT, LoadR);
8186   }
8187 
8188   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8189   processIntegerCallValue(I, Cmp, false);
8190   return true;
8191 }
8192 
8193 /// See if we can lower a memchr call into an optimized form. If so, return
8194 /// true and lower it. Otherwise return false, and it will be lowered like a
8195 /// normal call.
8196 /// The caller already checked that \p I calls the appropriate LibFunc with a
8197 /// correct prototype.
8198 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8199   const Value *Src = I.getArgOperand(0);
8200   const Value *Char = I.getArgOperand(1);
8201   const Value *Length = I.getArgOperand(2);
8202 
8203   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8204   std::pair<SDValue, SDValue> Res =
8205     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8206                                 getValue(Src), getValue(Char), getValue(Length),
8207                                 MachinePointerInfo(Src));
8208   if (Res.first.getNode()) {
8209     setValue(&I, Res.first);
8210     PendingLoads.push_back(Res.second);
8211     return true;
8212   }
8213 
8214   return false;
8215 }
8216 
8217 /// See if we can lower a mempcpy call into an optimized form. If so, return
8218 /// true and lower it. Otherwise return false, and it will be lowered like a
8219 /// normal call.
8220 /// The caller already checked that \p I calls the appropriate LibFunc with a
8221 /// correct prototype.
8222 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8223   SDValue Dst = getValue(I.getArgOperand(0));
8224   SDValue Src = getValue(I.getArgOperand(1));
8225   SDValue Size = getValue(I.getArgOperand(2));
8226 
8227   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8228   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8229   // DAG::getMemcpy needs Alignment to be defined.
8230   Align Alignment = std::min(DstAlign, SrcAlign);
8231 
8232   bool isVol = false;
8233   SDLoc sdl = getCurSDLoc();
8234 
8235   // In the mempcpy context we need to pass in a false value for isTailCall
8236   // because the return pointer needs to be adjusted by the size of
8237   // the copied memory.
8238   SDValue Root = isVol ? getRoot() : getMemoryRoot();
8239   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
8240                              /*isTailCall=*/false,
8241                              MachinePointerInfo(I.getArgOperand(0)),
8242                              MachinePointerInfo(I.getArgOperand(1)),
8243                              I.getAAMetadata());
8244   assert(MC.getNode() != nullptr &&
8245          "** memcpy should not be lowered as TailCall in mempcpy context **");
8246   DAG.setRoot(MC);
8247 
8248   // Check if Size needs to be truncated or extended.
8249   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8250 
8251   // Adjust return pointer to point just past the last dst byte.
8252   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8253                                     Dst, Size);
8254   setValue(&I, DstPlusSize);
8255   return true;
8256 }
8257 
8258 /// See if we can lower a strcpy call into an optimized form.  If so, return
8259 /// true and lower it, otherwise return false and it will be lowered like a
8260 /// normal call.
8261 /// The caller already checked that \p I calls the appropriate LibFunc with a
8262 /// correct prototype.
8263 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8264   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8265 
8266   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8267   std::pair<SDValue, SDValue> Res =
8268     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8269                                 getValue(Arg0), getValue(Arg1),
8270                                 MachinePointerInfo(Arg0),
8271                                 MachinePointerInfo(Arg1), isStpcpy);
8272   if (Res.first.getNode()) {
8273     setValue(&I, Res.first);
8274     DAG.setRoot(Res.second);
8275     return true;
8276   }
8277 
8278   return false;
8279 }
8280 
8281 /// See if we can lower a strcmp call into an optimized form.  If so, return
8282 /// true and lower it, otherwise return false and it will be lowered like a
8283 /// normal call.
8284 /// The caller already checked that \p I calls the appropriate LibFunc with a
8285 /// correct prototype.
8286 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8287   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8288 
8289   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8290   std::pair<SDValue, SDValue> Res =
8291     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8292                                 getValue(Arg0), getValue(Arg1),
8293                                 MachinePointerInfo(Arg0),
8294                                 MachinePointerInfo(Arg1));
8295   if (Res.first.getNode()) {
8296     processIntegerCallValue(I, Res.first, true);
8297     PendingLoads.push_back(Res.second);
8298     return true;
8299   }
8300 
8301   return false;
8302 }
8303 
8304 /// See if we can lower a strlen call into an optimized form.  If so, return
8305 /// true and lower it, otherwise return false and it will be lowered like a
8306 /// normal call.
8307 /// The caller already checked that \p I calls the appropriate LibFunc with a
8308 /// correct prototype.
8309 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8310   const Value *Arg0 = I.getArgOperand(0);
8311 
8312   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8313   std::pair<SDValue, SDValue> Res =
8314     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8315                                 getValue(Arg0), MachinePointerInfo(Arg0));
8316   if (Res.first.getNode()) {
8317     processIntegerCallValue(I, Res.first, false);
8318     PendingLoads.push_back(Res.second);
8319     return true;
8320   }
8321 
8322   return false;
8323 }
8324 
8325 /// See if we can lower a strnlen call into an optimized form.  If so, return
8326 /// true and lower it, otherwise return false and it will be lowered like a
8327 /// normal call.
8328 /// The caller already checked that \p I calls the appropriate LibFunc with a
8329 /// correct prototype.
8330 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8331   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8332 
8333   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8334   std::pair<SDValue, SDValue> Res =
8335     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8336                                  getValue(Arg0), getValue(Arg1),
8337                                  MachinePointerInfo(Arg0));
8338   if (Res.first.getNode()) {
8339     processIntegerCallValue(I, Res.first, false);
8340     PendingLoads.push_back(Res.second);
8341     return true;
8342   }
8343 
8344   return false;
8345 }
8346 
8347 /// See if we can lower a unary floating-point operation into an SDNode with
8348 /// the specified Opcode.  If so, return true and lower it, otherwise return
8349 /// false and it will be lowered like a normal call.
8350 /// The caller already checked that \p I calls the appropriate LibFunc with a
8351 /// correct prototype.
8352 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8353                                               unsigned Opcode) {
8354   // We already checked this call's prototype; verify it doesn't modify errno.
8355   if (!I.onlyReadsMemory())
8356     return false;
8357 
8358   SDNodeFlags Flags;
8359   Flags.copyFMF(cast<FPMathOperator>(I));
8360 
8361   SDValue Tmp = getValue(I.getArgOperand(0));
8362   setValue(&I,
8363            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8364   return true;
8365 }
8366 
8367 /// See if we can lower a binary floating-point operation into an SDNode with
8368 /// the specified Opcode. If so, return true and lower it. Otherwise return
8369 /// false, and it will be lowered like a normal call.
8370 /// The caller already checked that \p I calls the appropriate LibFunc with a
8371 /// correct prototype.
8372 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8373                                                unsigned Opcode) {
8374   // We already checked this call's prototype; verify it doesn't modify errno.
8375   if (!I.onlyReadsMemory())
8376     return false;
8377 
8378   SDNodeFlags Flags;
8379   Flags.copyFMF(cast<FPMathOperator>(I));
8380 
8381   SDValue Tmp0 = getValue(I.getArgOperand(0));
8382   SDValue Tmp1 = getValue(I.getArgOperand(1));
8383   EVT VT = Tmp0.getValueType();
8384   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8385   return true;
8386 }
8387 
8388 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8389   // Handle inline assembly differently.
8390   if (I.isInlineAsm()) {
8391     visitInlineAsm(I);
8392     return;
8393   }
8394 
8395   diagnoseDontCall(I);
8396 
8397   if (Function *F = I.getCalledFunction()) {
8398     if (F->isDeclaration()) {
8399       // Is this an LLVM intrinsic or a target-specific intrinsic?
8400       unsigned IID = F->getIntrinsicID();
8401       if (!IID)
8402         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8403           IID = II->getIntrinsicID(F);
8404 
8405       if (IID) {
8406         visitIntrinsicCall(I, IID);
8407         return;
8408       }
8409     }
8410 
8411     // Check for well-known libc/libm calls.  If the function is internal, it
8412     // can't be a library call.  Don't do the check if marked as nobuiltin for
8413     // some reason or the call site requires strict floating point semantics.
8414     LibFunc Func;
8415     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8416         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8417         LibInfo->hasOptimizedCodeGen(Func)) {
8418       switch (Func) {
8419       default: break;
8420       case LibFunc_bcmp:
8421         if (visitMemCmpBCmpCall(I))
8422           return;
8423         break;
8424       case LibFunc_copysign:
8425       case LibFunc_copysignf:
8426       case LibFunc_copysignl:
8427         // We already checked this call's prototype; verify it doesn't modify
8428         // errno.
8429         if (I.onlyReadsMemory()) {
8430           SDValue LHS = getValue(I.getArgOperand(0));
8431           SDValue RHS = getValue(I.getArgOperand(1));
8432           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8433                                    LHS.getValueType(), LHS, RHS));
8434           return;
8435         }
8436         break;
8437       case LibFunc_fabs:
8438       case LibFunc_fabsf:
8439       case LibFunc_fabsl:
8440         if (visitUnaryFloatCall(I, ISD::FABS))
8441           return;
8442         break;
8443       case LibFunc_fmin:
8444       case LibFunc_fminf:
8445       case LibFunc_fminl:
8446         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8447           return;
8448         break;
8449       case LibFunc_fmax:
8450       case LibFunc_fmaxf:
8451       case LibFunc_fmaxl:
8452         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8453           return;
8454         break;
8455       case LibFunc_sin:
8456       case LibFunc_sinf:
8457       case LibFunc_sinl:
8458         if (visitUnaryFloatCall(I, ISD::FSIN))
8459           return;
8460         break;
8461       case LibFunc_cos:
8462       case LibFunc_cosf:
8463       case LibFunc_cosl:
8464         if (visitUnaryFloatCall(I, ISD::FCOS))
8465           return;
8466         break;
8467       case LibFunc_sqrt:
8468       case LibFunc_sqrtf:
8469       case LibFunc_sqrtl:
8470       case LibFunc_sqrt_finite:
8471       case LibFunc_sqrtf_finite:
8472       case LibFunc_sqrtl_finite:
8473         if (visitUnaryFloatCall(I, ISD::FSQRT))
8474           return;
8475         break;
8476       case LibFunc_floor:
8477       case LibFunc_floorf:
8478       case LibFunc_floorl:
8479         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8480           return;
8481         break;
8482       case LibFunc_nearbyint:
8483       case LibFunc_nearbyintf:
8484       case LibFunc_nearbyintl:
8485         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8486           return;
8487         break;
8488       case LibFunc_ceil:
8489       case LibFunc_ceilf:
8490       case LibFunc_ceill:
8491         if (visitUnaryFloatCall(I, ISD::FCEIL))
8492           return;
8493         break;
8494       case LibFunc_rint:
8495       case LibFunc_rintf:
8496       case LibFunc_rintl:
8497         if (visitUnaryFloatCall(I, ISD::FRINT))
8498           return;
8499         break;
8500       case LibFunc_round:
8501       case LibFunc_roundf:
8502       case LibFunc_roundl:
8503         if (visitUnaryFloatCall(I, ISD::FROUND))
8504           return;
8505         break;
8506       case LibFunc_trunc:
8507       case LibFunc_truncf:
8508       case LibFunc_truncl:
8509         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8510           return;
8511         break;
8512       case LibFunc_log2:
8513       case LibFunc_log2f:
8514       case LibFunc_log2l:
8515         if (visitUnaryFloatCall(I, ISD::FLOG2))
8516           return;
8517         break;
8518       case LibFunc_exp2:
8519       case LibFunc_exp2f:
8520       case LibFunc_exp2l:
8521         if (visitUnaryFloatCall(I, ISD::FEXP2))
8522           return;
8523         break;
8524       case LibFunc_memcmp:
8525         if (visitMemCmpBCmpCall(I))
8526           return;
8527         break;
8528       case LibFunc_mempcpy:
8529         if (visitMemPCpyCall(I))
8530           return;
8531         break;
8532       case LibFunc_memchr:
8533         if (visitMemChrCall(I))
8534           return;
8535         break;
8536       case LibFunc_strcpy:
8537         if (visitStrCpyCall(I, false))
8538           return;
8539         break;
8540       case LibFunc_stpcpy:
8541         if (visitStrCpyCall(I, true))
8542           return;
8543         break;
8544       case LibFunc_strcmp:
8545         if (visitStrCmpCall(I))
8546           return;
8547         break;
8548       case LibFunc_strlen:
8549         if (visitStrLenCall(I))
8550           return;
8551         break;
8552       case LibFunc_strnlen:
8553         if (visitStrNLenCall(I))
8554           return;
8555         break;
8556       }
8557     }
8558   }
8559 
8560   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8561   // have to do anything here to lower funclet bundles.
8562   // CFGuardTarget bundles are lowered in LowerCallTo.
8563   assert(!I.hasOperandBundlesOtherThan(
8564              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8565               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8566               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8567          "Cannot lower calls with arbitrary operand bundles!");
8568 
8569   SDValue Callee = getValue(I.getCalledOperand());
8570 
8571   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8572     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8573   else
8574     // Check if we can potentially perform a tail call. More detailed checking
8575     // is be done within LowerCallTo, after more information about the call is
8576     // known.
8577     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8578 }
8579 
8580 namespace {
8581 
8582 /// AsmOperandInfo - This contains information for each constraint that we are
8583 /// lowering.
8584 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8585 public:
8586   /// CallOperand - If this is the result output operand or a clobber
8587   /// this is null, otherwise it is the incoming operand to the CallInst.
8588   /// This gets modified as the asm is processed.
8589   SDValue CallOperand;
8590 
8591   /// AssignedRegs - If this is a register or register class operand, this
8592   /// contains the set of register corresponding to the operand.
8593   RegsForValue AssignedRegs;
8594 
8595   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8596     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8597   }
8598 
8599   /// Whether or not this operand accesses memory
8600   bool hasMemory(const TargetLowering &TLI) const {
8601     // Indirect operand accesses access memory.
8602     if (isIndirect)
8603       return true;
8604 
8605     for (const auto &Code : Codes)
8606       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8607         return true;
8608 
8609     return false;
8610   }
8611 };
8612 
8613 
8614 } // end anonymous namespace
8615 
8616 /// Make sure that the output operand \p OpInfo and its corresponding input
8617 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8618 /// out).
8619 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8620                                SDISelAsmOperandInfo &MatchingOpInfo,
8621                                SelectionDAG &DAG) {
8622   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8623     return;
8624 
8625   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8626   const auto &TLI = DAG.getTargetLoweringInfo();
8627 
8628   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8629       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8630                                        OpInfo.ConstraintVT);
8631   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8632       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8633                                        MatchingOpInfo.ConstraintVT);
8634   if ((OpInfo.ConstraintVT.isInteger() !=
8635        MatchingOpInfo.ConstraintVT.isInteger()) ||
8636       (MatchRC.second != InputRC.second)) {
8637     // FIXME: error out in a more elegant fashion
8638     report_fatal_error("Unsupported asm: input constraint"
8639                        " with a matching output constraint of"
8640                        " incompatible type!");
8641   }
8642   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8643 }
8644 
8645 /// Get a direct memory input to behave well as an indirect operand.
8646 /// This may introduce stores, hence the need for a \p Chain.
8647 /// \return The (possibly updated) chain.
8648 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8649                                         SDISelAsmOperandInfo &OpInfo,
8650                                         SelectionDAG &DAG) {
8651   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8652 
8653   // If we don't have an indirect input, put it in the constpool if we can,
8654   // otherwise spill it to a stack slot.
8655   // TODO: This isn't quite right. We need to handle these according to
8656   // the addressing mode that the constraint wants. Also, this may take
8657   // an additional register for the computation and we don't want that
8658   // either.
8659 
8660   // If the operand is a float, integer, or vector constant, spill to a
8661   // constant pool entry to get its address.
8662   const Value *OpVal = OpInfo.CallOperandVal;
8663   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8664       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8665     OpInfo.CallOperand = DAG.getConstantPool(
8666         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8667     return Chain;
8668   }
8669 
8670   // Otherwise, create a stack slot and emit a store to it before the asm.
8671   Type *Ty = OpVal->getType();
8672   auto &DL = DAG.getDataLayout();
8673   uint64_t TySize = DL.getTypeAllocSize(Ty);
8674   MachineFunction &MF = DAG.getMachineFunction();
8675   int SSFI = MF.getFrameInfo().CreateStackObject(
8676       TySize, DL.getPrefTypeAlign(Ty), false);
8677   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8678   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8679                             MachinePointerInfo::getFixedStack(MF, SSFI),
8680                             TLI.getMemValueType(DL, Ty));
8681   OpInfo.CallOperand = StackSlot;
8682 
8683   return Chain;
8684 }
8685 
8686 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8687 /// specified operand.  We prefer to assign virtual registers, to allow the
8688 /// register allocator to handle the assignment process.  However, if the asm
8689 /// uses features that we can't model on machineinstrs, we have SDISel do the
8690 /// allocation.  This produces generally horrible, but correct, code.
8691 ///
8692 ///   OpInfo describes the operand
8693 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8694 static std::optional<unsigned>
8695 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8696                      SDISelAsmOperandInfo &OpInfo,
8697                      SDISelAsmOperandInfo &RefOpInfo) {
8698   LLVMContext &Context = *DAG.getContext();
8699   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8700 
8701   MachineFunction &MF = DAG.getMachineFunction();
8702   SmallVector<unsigned, 4> Regs;
8703   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8704 
8705   // No work to do for memory/address operands.
8706   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8707       OpInfo.ConstraintType == TargetLowering::C_Address)
8708     return std::nullopt;
8709 
8710   // If this is a constraint for a single physreg, or a constraint for a
8711   // register class, find it.
8712   unsigned AssignedReg;
8713   const TargetRegisterClass *RC;
8714   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8715       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8716   // RC is unset only on failure. Return immediately.
8717   if (!RC)
8718     return std::nullopt;
8719 
8720   // Get the actual register value type.  This is important, because the user
8721   // may have asked for (e.g.) the AX register in i32 type.  We need to
8722   // remember that AX is actually i16 to get the right extension.
8723   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8724 
8725   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8726     // If this is an FP operand in an integer register (or visa versa), or more
8727     // generally if the operand value disagrees with the register class we plan
8728     // to stick it in, fix the operand type.
8729     //
8730     // If this is an input value, the bitcast to the new type is done now.
8731     // Bitcast for output value is done at the end of visitInlineAsm().
8732     if ((OpInfo.Type == InlineAsm::isOutput ||
8733          OpInfo.Type == InlineAsm::isInput) &&
8734         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8735       // Try to convert to the first EVT that the reg class contains.  If the
8736       // types are identical size, use a bitcast to convert (e.g. two differing
8737       // vector types).  Note: output bitcast is done at the end of
8738       // visitInlineAsm().
8739       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8740         // Exclude indirect inputs while they are unsupported because the code
8741         // to perform the load is missing and thus OpInfo.CallOperand still
8742         // refers to the input address rather than the pointed-to value.
8743         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8744           OpInfo.CallOperand =
8745               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8746         OpInfo.ConstraintVT = RegVT;
8747         // If the operand is an FP value and we want it in integer registers,
8748         // use the corresponding integer type. This turns an f64 value into
8749         // i64, which can be passed with two i32 values on a 32-bit machine.
8750       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8751         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8752         if (OpInfo.Type == InlineAsm::isInput)
8753           OpInfo.CallOperand =
8754               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8755         OpInfo.ConstraintVT = VT;
8756       }
8757     }
8758   }
8759 
8760   // No need to allocate a matching input constraint since the constraint it's
8761   // matching to has already been allocated.
8762   if (OpInfo.isMatchingInputConstraint())
8763     return std::nullopt;
8764 
8765   EVT ValueVT = OpInfo.ConstraintVT;
8766   if (OpInfo.ConstraintVT == MVT::Other)
8767     ValueVT = RegVT;
8768 
8769   // Initialize NumRegs.
8770   unsigned NumRegs = 1;
8771   if (OpInfo.ConstraintVT != MVT::Other)
8772     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8773 
8774   // If this is a constraint for a specific physical register, like {r17},
8775   // assign it now.
8776 
8777   // If this associated to a specific register, initialize iterator to correct
8778   // place. If virtual, make sure we have enough registers
8779 
8780   // Initialize iterator if necessary
8781   TargetRegisterClass::iterator I = RC->begin();
8782   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8783 
8784   // Do not check for single registers.
8785   if (AssignedReg) {
8786     I = std::find(I, RC->end(), AssignedReg);
8787     if (I == RC->end()) {
8788       // RC does not contain the selected register, which indicates a
8789       // mismatch between the register and the required type/bitwidth.
8790       return {AssignedReg};
8791     }
8792   }
8793 
8794   for (; NumRegs; --NumRegs, ++I) {
8795     assert(I != RC->end() && "Ran out of registers to allocate!");
8796     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8797     Regs.push_back(R);
8798   }
8799 
8800   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8801   return std::nullopt;
8802 }
8803 
8804 static unsigned
8805 findMatchingInlineAsmOperand(unsigned OperandNo,
8806                              const std::vector<SDValue> &AsmNodeOperands) {
8807   // Scan until we find the definition we already emitted of this operand.
8808   unsigned CurOp = InlineAsm::Op_FirstOperand;
8809   for (; OperandNo; --OperandNo) {
8810     // Advance to the next operand.
8811     unsigned OpFlag =
8812         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8813     assert((InlineAsm::isRegDefKind(OpFlag) ||
8814             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8815             InlineAsm::isMemKind(OpFlag)) &&
8816            "Skipped past definitions?");
8817     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8818   }
8819   return CurOp;
8820 }
8821 
8822 namespace {
8823 
8824 class ExtraFlags {
8825   unsigned Flags = 0;
8826 
8827 public:
8828   explicit ExtraFlags(const CallBase &Call) {
8829     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8830     if (IA->hasSideEffects())
8831       Flags |= InlineAsm::Extra_HasSideEffects;
8832     if (IA->isAlignStack())
8833       Flags |= InlineAsm::Extra_IsAlignStack;
8834     if (Call.isConvergent())
8835       Flags |= InlineAsm::Extra_IsConvergent;
8836     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8837   }
8838 
8839   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8840     // Ideally, we would only check against memory constraints.  However, the
8841     // meaning of an Other constraint can be target-specific and we can't easily
8842     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8843     // for Other constraints as well.
8844     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8845         OpInfo.ConstraintType == TargetLowering::C_Other) {
8846       if (OpInfo.Type == InlineAsm::isInput)
8847         Flags |= InlineAsm::Extra_MayLoad;
8848       else if (OpInfo.Type == InlineAsm::isOutput)
8849         Flags |= InlineAsm::Extra_MayStore;
8850       else if (OpInfo.Type == InlineAsm::isClobber)
8851         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8852     }
8853   }
8854 
8855   unsigned get() const { return Flags; }
8856 };
8857 
8858 } // end anonymous namespace
8859 
8860 static bool isFunction(SDValue Op) {
8861   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
8862     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8863       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
8864 
8865       // In normal "call dllimport func" instruction (non-inlineasm) it force
8866       // indirect access by specifing call opcode. And usually specially print
8867       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
8868       // not do in this way now. (In fact, this is similar with "Data Access"
8869       // action). So here we ignore dllimport function.
8870       if (Fn && !Fn->hasDLLImportStorageClass())
8871         return true;
8872     }
8873   }
8874   return false;
8875 }
8876 
8877 /// visitInlineAsm - Handle a call to an InlineAsm object.
8878 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8879                                          const BasicBlock *EHPadBB) {
8880   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8881 
8882   /// ConstraintOperands - Information about all of the constraints.
8883   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8884 
8885   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8886   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8887       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8888 
8889   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8890   // AsmDialect, MayLoad, MayStore).
8891   bool HasSideEffect = IA->hasSideEffects();
8892   ExtraFlags ExtraInfo(Call);
8893 
8894   for (auto &T : TargetConstraints) {
8895     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8896     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8897 
8898     if (OpInfo.CallOperandVal)
8899       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8900 
8901     if (!HasSideEffect)
8902       HasSideEffect = OpInfo.hasMemory(TLI);
8903 
8904     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8905     // FIXME: Could we compute this on OpInfo rather than T?
8906 
8907     // Compute the constraint code and ConstraintType to use.
8908     TLI.ComputeConstraintToUse(T, SDValue());
8909 
8910     if (T.ConstraintType == TargetLowering::C_Immediate &&
8911         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8912       // We've delayed emitting a diagnostic like the "n" constraint because
8913       // inlining could cause an integer showing up.
8914       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8915                                           "' expects an integer constant "
8916                                           "expression");
8917 
8918     ExtraInfo.update(T);
8919   }
8920 
8921   // We won't need to flush pending loads if this asm doesn't touch
8922   // memory and is nonvolatile.
8923   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8924 
8925   bool EmitEHLabels = isa<InvokeInst>(Call);
8926   if (EmitEHLabels) {
8927     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8928   }
8929   bool IsCallBr = isa<CallBrInst>(Call);
8930 
8931   if (IsCallBr || EmitEHLabels) {
8932     // If this is a callbr or invoke we need to flush pending exports since
8933     // inlineasm_br and invoke are terminators.
8934     // We need to do this before nodes are glued to the inlineasm_br node.
8935     Chain = getControlRoot();
8936   }
8937 
8938   MCSymbol *BeginLabel = nullptr;
8939   if (EmitEHLabels) {
8940     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8941   }
8942 
8943   int OpNo = -1;
8944   SmallVector<StringRef> AsmStrs;
8945   IA->collectAsmStrs(AsmStrs);
8946 
8947   // Second pass over the constraints: compute which constraint option to use.
8948   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8949     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
8950       OpNo++;
8951 
8952     // If this is an output operand with a matching input operand, look up the
8953     // matching input. If their types mismatch, e.g. one is an integer, the
8954     // other is floating point, or their sizes are different, flag it as an
8955     // error.
8956     if (OpInfo.hasMatchingInput()) {
8957       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8958       patchMatchingInput(OpInfo, Input, DAG);
8959     }
8960 
8961     // Compute the constraint code and ConstraintType to use.
8962     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8963 
8964     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
8965          OpInfo.Type == InlineAsm::isClobber) ||
8966         OpInfo.ConstraintType == TargetLowering::C_Address)
8967       continue;
8968 
8969     // In Linux PIC model, there are 4 cases about value/label addressing:
8970     //
8971     // 1: Function call or Label jmp inside the module.
8972     // 2: Data access (such as global variable, static variable) inside module.
8973     // 3: Function call or Label jmp outside the module.
8974     // 4: Data access (such as global variable) outside the module.
8975     //
8976     // Due to current llvm inline asm architecture designed to not "recognize"
8977     // the asm code, there are quite troubles for us to treat mem addressing
8978     // differently for same value/adress used in different instuctions.
8979     // For example, in pic model, call a func may in plt way or direclty
8980     // pc-related, but lea/mov a function adress may use got.
8981     //
8982     // Here we try to "recognize" function call for the case 1 and case 3 in
8983     // inline asm. And try to adjust the constraint for them.
8984     //
8985     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
8986     // label, so here we don't handle jmp function label now, but we need to
8987     // enhance it (especilly in PIC model) if we meet meaningful requirements.
8988     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
8989         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
8990         TM.getCodeModel() != CodeModel::Large) {
8991       OpInfo.isIndirect = false;
8992       OpInfo.ConstraintType = TargetLowering::C_Address;
8993     }
8994 
8995     // If this is a memory input, and if the operand is not indirect, do what we
8996     // need to provide an address for the memory input.
8997     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8998         !OpInfo.isIndirect) {
8999       assert((OpInfo.isMultipleAlternative ||
9000               (OpInfo.Type == InlineAsm::isInput)) &&
9001              "Can only indirectify direct input operands!");
9002 
9003       // Memory operands really want the address of the value.
9004       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9005 
9006       // There is no longer a Value* corresponding to this operand.
9007       OpInfo.CallOperandVal = nullptr;
9008 
9009       // It is now an indirect operand.
9010       OpInfo.isIndirect = true;
9011     }
9012 
9013   }
9014 
9015   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9016   std::vector<SDValue> AsmNodeOperands;
9017   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9018   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9019       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9020 
9021   // If we have a !srcloc metadata node associated with it, we want to attach
9022   // this to the ultimately generated inline asm machineinstr.  To do this, we
9023   // pass in the third operand as this (potentially null) inline asm MDNode.
9024   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9025   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9026 
9027   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9028   // bits as operand 3.
9029   AsmNodeOperands.push_back(DAG.getTargetConstant(
9030       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9031 
9032   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9033   // this, assign virtual and physical registers for inputs and otput.
9034   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9035     // Assign Registers.
9036     SDISelAsmOperandInfo &RefOpInfo =
9037         OpInfo.isMatchingInputConstraint()
9038             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9039             : OpInfo;
9040     const auto RegError =
9041         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9042     if (RegError) {
9043       const MachineFunction &MF = DAG.getMachineFunction();
9044       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9045       const char *RegName = TRI.getName(*RegError);
9046       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9047                                    "' allocated for constraint '" +
9048                                    Twine(OpInfo.ConstraintCode) +
9049                                    "' does not match required type");
9050       return;
9051     }
9052 
9053     auto DetectWriteToReservedRegister = [&]() {
9054       const MachineFunction &MF = DAG.getMachineFunction();
9055       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9056       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9057         if (Register::isPhysicalRegister(Reg) &&
9058             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9059           const char *RegName = TRI.getName(Reg);
9060           emitInlineAsmError(Call, "write to reserved register '" +
9061                                        Twine(RegName) + "'");
9062           return true;
9063         }
9064       }
9065       return false;
9066     };
9067     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9068             (OpInfo.Type == InlineAsm::isInput &&
9069              !OpInfo.isMatchingInputConstraint())) &&
9070            "Only address as input operand is allowed.");
9071 
9072     switch (OpInfo.Type) {
9073     case InlineAsm::isOutput:
9074       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9075         unsigned ConstraintID =
9076             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9077         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9078                "Failed to convert memory constraint code to constraint id.");
9079 
9080         // Add information to the INLINEASM node to know about this output.
9081         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9082         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
9083         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9084                                                         MVT::i32));
9085         AsmNodeOperands.push_back(OpInfo.CallOperand);
9086       } else {
9087         // Otherwise, this outputs to a register (directly for C_Register /
9088         // C_RegisterClass, and a target-defined fashion for
9089         // C_Immediate/C_Other). Find a register that we can use.
9090         if (OpInfo.AssignedRegs.Regs.empty()) {
9091           emitInlineAsmError(
9092               Call, "couldn't allocate output register for constraint '" +
9093                         Twine(OpInfo.ConstraintCode) + "'");
9094           return;
9095         }
9096 
9097         if (DetectWriteToReservedRegister())
9098           return;
9099 
9100         // Add information to the INLINEASM node to know that this register is
9101         // set.
9102         OpInfo.AssignedRegs.AddInlineAsmOperands(
9103             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
9104                                   : InlineAsm::Kind_RegDef,
9105             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9106       }
9107       break;
9108 
9109     case InlineAsm::isInput:
9110     case InlineAsm::isLabel: {
9111       SDValue InOperandVal = OpInfo.CallOperand;
9112 
9113       if (OpInfo.isMatchingInputConstraint()) {
9114         // If this is required to match an output register we have already set,
9115         // just use its register.
9116         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9117                                                   AsmNodeOperands);
9118         unsigned OpFlag =
9119           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
9120         if (InlineAsm::isRegDefKind(OpFlag) ||
9121             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
9122           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
9123           if (OpInfo.isIndirect) {
9124             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9125             emitInlineAsmError(Call, "inline asm not supported yet: "
9126                                      "don't know how to handle tied "
9127                                      "indirect register inputs");
9128             return;
9129           }
9130 
9131           SmallVector<unsigned, 4> Regs;
9132           MachineFunction &MF = DAG.getMachineFunction();
9133           MachineRegisterInfo &MRI = MF.getRegInfo();
9134           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9135           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9136           Register TiedReg = R->getReg();
9137           MVT RegVT = R->getSimpleValueType(0);
9138           const TargetRegisterClass *RC =
9139               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9140               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9141                                       : TRI.getMinimalPhysRegClass(TiedReg);
9142           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
9143           for (unsigned i = 0; i != NumRegs; ++i)
9144             Regs.push_back(MRI.createVirtualRegister(RC));
9145 
9146           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9147 
9148           SDLoc dl = getCurSDLoc();
9149           // Use the produced MatchedRegs object to
9150           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9151           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
9152                                            true, OpInfo.getMatchedOperand(), dl,
9153                                            DAG, AsmNodeOperands);
9154           break;
9155         }
9156 
9157         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
9158         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
9159                "Unexpected number of operands");
9160         // Add information to the INLINEASM node to know about this input.
9161         // See InlineAsm.h isUseOperandTiedToDef.
9162         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
9163         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
9164                                                     OpInfo.getMatchedOperand());
9165         AsmNodeOperands.push_back(DAG.getTargetConstant(
9166             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9167         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9168         break;
9169       }
9170 
9171       // Treat indirect 'X' constraint as memory.
9172       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9173           OpInfo.isIndirect)
9174         OpInfo.ConstraintType = TargetLowering::C_Memory;
9175 
9176       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9177           OpInfo.ConstraintType == TargetLowering::C_Other) {
9178         std::vector<SDValue> Ops;
9179         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9180                                           Ops, DAG);
9181         if (Ops.empty()) {
9182           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9183             if (isa<ConstantSDNode>(InOperandVal)) {
9184               emitInlineAsmError(Call, "value out of range for constraint '" +
9185                                            Twine(OpInfo.ConstraintCode) + "'");
9186               return;
9187             }
9188 
9189           emitInlineAsmError(Call,
9190                              "invalid operand for inline asm constraint '" +
9191                                  Twine(OpInfo.ConstraintCode) + "'");
9192           return;
9193         }
9194 
9195         // Add information to the INLINEASM node to know about this input.
9196         unsigned ResOpType =
9197           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
9198         AsmNodeOperands.push_back(DAG.getTargetConstant(
9199             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9200         llvm::append_range(AsmNodeOperands, Ops);
9201         break;
9202       }
9203 
9204       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9205         assert((OpInfo.isIndirect ||
9206                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9207                "Operand must be indirect to be a mem!");
9208         assert(InOperandVal.getValueType() ==
9209                    TLI.getPointerTy(DAG.getDataLayout()) &&
9210                "Memory operands expect pointer values");
9211 
9212         unsigned ConstraintID =
9213             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9214         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9215                "Failed to convert memory constraint code to constraint id.");
9216 
9217         // Add information to the INLINEASM node to know about this input.
9218         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9219         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9220         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9221                                                         getCurSDLoc(),
9222                                                         MVT::i32));
9223         AsmNodeOperands.push_back(InOperandVal);
9224         break;
9225       }
9226 
9227       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9228         assert(InOperandVal.getValueType() ==
9229                    TLI.getPointerTy(DAG.getDataLayout()) &&
9230                "Address operands expect pointer values");
9231 
9232         unsigned ConstraintID =
9233             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9234         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9235                "Failed to convert memory constraint code to constraint id.");
9236 
9237         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9238 
9239         SDValue AsmOp = InOperandVal;
9240         if (isFunction(InOperandVal)) {
9241           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9242           ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1);
9243           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9244                                              InOperandVal.getValueType(),
9245                                              GA->getOffset());
9246         }
9247 
9248         // Add information to the INLINEASM node to know about this input.
9249         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9250 
9251         AsmNodeOperands.push_back(
9252             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9253 
9254         AsmNodeOperands.push_back(AsmOp);
9255         break;
9256       }
9257 
9258       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9259               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9260              "Unknown constraint type!");
9261 
9262       // TODO: Support this.
9263       if (OpInfo.isIndirect) {
9264         emitInlineAsmError(
9265             Call, "Don't know how to handle indirect register inputs yet "
9266                   "for constraint '" +
9267                       Twine(OpInfo.ConstraintCode) + "'");
9268         return;
9269       }
9270 
9271       // Copy the input into the appropriate registers.
9272       if (OpInfo.AssignedRegs.Regs.empty()) {
9273         emitInlineAsmError(Call,
9274                            "couldn't allocate input reg for constraint '" +
9275                                Twine(OpInfo.ConstraintCode) + "'");
9276         return;
9277       }
9278 
9279       if (DetectWriteToReservedRegister())
9280         return;
9281 
9282       SDLoc dl = getCurSDLoc();
9283 
9284       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
9285                                         &Call);
9286 
9287       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
9288                                                dl, DAG, AsmNodeOperands);
9289       break;
9290     }
9291     case InlineAsm::isClobber:
9292       // Add the clobbered value to the operand list, so that the register
9293       // allocator is aware that the physreg got clobbered.
9294       if (!OpInfo.AssignedRegs.Regs.empty())
9295         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
9296                                                  false, 0, getCurSDLoc(), DAG,
9297                                                  AsmNodeOperands);
9298       break;
9299     }
9300   }
9301 
9302   // Finish up input operands.  Set the input chain and add the flag last.
9303   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9304   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
9305 
9306   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9307   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9308                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9309   Glue = Chain.getValue(1);
9310 
9311   // Do additional work to generate outputs.
9312 
9313   SmallVector<EVT, 1> ResultVTs;
9314   SmallVector<SDValue, 1> ResultValues;
9315   SmallVector<SDValue, 8> OutChains;
9316 
9317   llvm::Type *CallResultType = Call.getType();
9318   ArrayRef<Type *> ResultTypes;
9319   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9320     ResultTypes = StructResult->elements();
9321   else if (!CallResultType->isVoidTy())
9322     ResultTypes = ArrayRef(CallResultType);
9323 
9324   auto CurResultType = ResultTypes.begin();
9325   auto handleRegAssign = [&](SDValue V) {
9326     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9327     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9328     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9329     ++CurResultType;
9330     // If the type of the inline asm call site return value is different but has
9331     // same size as the type of the asm output bitcast it.  One example of this
9332     // is for vectors with different width / number of elements.  This can
9333     // happen for register classes that can contain multiple different value
9334     // types.  The preg or vreg allocated may not have the same VT as was
9335     // expected.
9336     //
9337     // This can also happen for a return value that disagrees with the register
9338     // class it is put in, eg. a double in a general-purpose register on a
9339     // 32-bit machine.
9340     if (ResultVT != V.getValueType() &&
9341         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9342       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9343     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9344              V.getValueType().isInteger()) {
9345       // If a result value was tied to an input value, the computed result
9346       // may have a wider width than the expected result.  Extract the
9347       // relevant portion.
9348       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9349     }
9350     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9351     ResultVTs.push_back(ResultVT);
9352     ResultValues.push_back(V);
9353   };
9354 
9355   // Deal with output operands.
9356   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9357     if (OpInfo.Type == InlineAsm::isOutput) {
9358       SDValue Val;
9359       // Skip trivial output operands.
9360       if (OpInfo.AssignedRegs.Regs.empty())
9361         continue;
9362 
9363       switch (OpInfo.ConstraintType) {
9364       case TargetLowering::C_Register:
9365       case TargetLowering::C_RegisterClass:
9366         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9367                                                   Chain, &Glue, &Call);
9368         break;
9369       case TargetLowering::C_Immediate:
9370       case TargetLowering::C_Other:
9371         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
9372                                               OpInfo, DAG);
9373         break;
9374       case TargetLowering::C_Memory:
9375         break; // Already handled.
9376       case TargetLowering::C_Address:
9377         break; // Silence warning.
9378       case TargetLowering::C_Unknown:
9379         assert(false && "Unexpected unknown constraint");
9380       }
9381 
9382       // Indirect output manifest as stores. Record output chains.
9383       if (OpInfo.isIndirect) {
9384         const Value *Ptr = OpInfo.CallOperandVal;
9385         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9386         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9387                                      MachinePointerInfo(Ptr));
9388         OutChains.push_back(Store);
9389       } else {
9390         // generate CopyFromRegs to associated registers.
9391         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9392         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9393           for (const SDValue &V : Val->op_values())
9394             handleRegAssign(V);
9395         } else
9396           handleRegAssign(Val);
9397       }
9398     }
9399   }
9400 
9401   // Set results.
9402   if (!ResultValues.empty()) {
9403     assert(CurResultType == ResultTypes.end() &&
9404            "Mismatch in number of ResultTypes");
9405     assert(ResultValues.size() == ResultTypes.size() &&
9406            "Mismatch in number of output operands in asm result");
9407 
9408     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9409                             DAG.getVTList(ResultVTs), ResultValues);
9410     setValue(&Call, V);
9411   }
9412 
9413   // Collect store chains.
9414   if (!OutChains.empty())
9415     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9416 
9417   if (EmitEHLabels) {
9418     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9419   }
9420 
9421   // Only Update Root if inline assembly has a memory effect.
9422   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9423       EmitEHLabels)
9424     DAG.setRoot(Chain);
9425 }
9426 
9427 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9428                                              const Twine &Message) {
9429   LLVMContext &Ctx = *DAG.getContext();
9430   Ctx.emitError(&Call, Message);
9431 
9432   // Make sure we leave the DAG in a valid state
9433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9434   SmallVector<EVT, 1> ValueVTs;
9435   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9436 
9437   if (ValueVTs.empty())
9438     return;
9439 
9440   SmallVector<SDValue, 1> Ops;
9441   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9442     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9443 
9444   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9445 }
9446 
9447 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9448   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9449                           MVT::Other, getRoot(),
9450                           getValue(I.getArgOperand(0)),
9451                           DAG.getSrcValue(I.getArgOperand(0))));
9452 }
9453 
9454 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9455   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9456   const DataLayout &DL = DAG.getDataLayout();
9457   SDValue V = DAG.getVAArg(
9458       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9459       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9460       DL.getABITypeAlign(I.getType()).value());
9461   DAG.setRoot(V.getValue(1));
9462 
9463   if (I.getType()->isPointerTy())
9464     V = DAG.getPtrExtOrTrunc(
9465         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9466   setValue(&I, V);
9467 }
9468 
9469 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9470   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9471                           MVT::Other, getRoot(),
9472                           getValue(I.getArgOperand(0)),
9473                           DAG.getSrcValue(I.getArgOperand(0))));
9474 }
9475 
9476 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9477   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9478                           MVT::Other, getRoot(),
9479                           getValue(I.getArgOperand(0)),
9480                           getValue(I.getArgOperand(1)),
9481                           DAG.getSrcValue(I.getArgOperand(0)),
9482                           DAG.getSrcValue(I.getArgOperand(1))));
9483 }
9484 
9485 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9486                                                     const Instruction &I,
9487                                                     SDValue Op) {
9488   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9489   if (!Range)
9490     return Op;
9491 
9492   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9493   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9494     return Op;
9495 
9496   APInt Lo = CR.getUnsignedMin();
9497   if (!Lo.isMinValue())
9498     return Op;
9499 
9500   APInt Hi = CR.getUnsignedMax();
9501   unsigned Bits = std::max(Hi.getActiveBits(),
9502                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9503 
9504   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9505 
9506   SDLoc SL = getCurSDLoc();
9507 
9508   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9509                              DAG.getValueType(SmallVT));
9510   unsigned NumVals = Op.getNode()->getNumValues();
9511   if (NumVals == 1)
9512     return ZExt;
9513 
9514   SmallVector<SDValue, 4> Ops;
9515 
9516   Ops.push_back(ZExt);
9517   for (unsigned I = 1; I != NumVals; ++I)
9518     Ops.push_back(Op.getValue(I));
9519 
9520   return DAG.getMergeValues(Ops, SL);
9521 }
9522 
9523 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9524 /// the call being lowered.
9525 ///
9526 /// This is a helper for lowering intrinsics that follow a target calling
9527 /// convention or require stack pointer adjustment. Only a subset of the
9528 /// intrinsic's operands need to participate in the calling convention.
9529 void SelectionDAGBuilder::populateCallLoweringInfo(
9530     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9531     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9532     bool IsPatchPoint) {
9533   TargetLowering::ArgListTy Args;
9534   Args.reserve(NumArgs);
9535 
9536   // Populate the argument list.
9537   // Attributes for args start at offset 1, after the return attribute.
9538   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9539        ArgI != ArgE; ++ArgI) {
9540     const Value *V = Call->getOperand(ArgI);
9541 
9542     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9543 
9544     TargetLowering::ArgListEntry Entry;
9545     Entry.Node = getValue(V);
9546     Entry.Ty = V->getType();
9547     Entry.setAttributes(Call, ArgI);
9548     Args.push_back(Entry);
9549   }
9550 
9551   CLI.setDebugLoc(getCurSDLoc())
9552       .setChain(getRoot())
9553       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9554       .setDiscardResult(Call->use_empty())
9555       .setIsPatchPoint(IsPatchPoint)
9556       .setIsPreallocated(
9557           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9558 }
9559 
9560 /// Add a stack map intrinsic call's live variable operands to a stackmap
9561 /// or patchpoint target node's operand list.
9562 ///
9563 /// Constants are converted to TargetConstants purely as an optimization to
9564 /// avoid constant materialization and register allocation.
9565 ///
9566 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9567 /// generate addess computation nodes, and so FinalizeISel can convert the
9568 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9569 /// address materialization and register allocation, but may also be required
9570 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9571 /// alloca in the entry block, then the runtime may assume that the alloca's
9572 /// StackMap location can be read immediately after compilation and that the
9573 /// location is valid at any point during execution (this is similar to the
9574 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9575 /// only available in a register, then the runtime would need to trap when
9576 /// execution reaches the StackMap in order to read the alloca's location.
9577 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9578                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9579                                 SelectionDAGBuilder &Builder) {
9580   SelectionDAG &DAG = Builder.DAG;
9581   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9582     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9583 
9584     // Things on the stack are pointer-typed, meaning that they are already
9585     // legal and can be emitted directly to target nodes.
9586     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9587       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9588     } else {
9589       // Otherwise emit a target independent node to be legalised.
9590       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9591     }
9592   }
9593 }
9594 
9595 /// Lower llvm.experimental.stackmap.
9596 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9597   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9598   //                                  [live variables...])
9599 
9600   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9601 
9602   SDValue Chain, InGlue, Callee;
9603   SmallVector<SDValue, 32> Ops;
9604 
9605   SDLoc DL = getCurSDLoc();
9606   Callee = getValue(CI.getCalledOperand());
9607 
9608   // The stackmap intrinsic only records the live variables (the arguments
9609   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9610   // intrinsic, this won't be lowered to a function call. This means we don't
9611   // have to worry about calling conventions and target specific lowering code.
9612   // Instead we perform the call lowering right here.
9613   //
9614   // chain, flag = CALLSEQ_START(chain, 0, 0)
9615   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9616   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9617   //
9618   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9619   InGlue = Chain.getValue(1);
9620 
9621   // Add the STACKMAP operands, starting with DAG house-keeping.
9622   Ops.push_back(Chain);
9623   Ops.push_back(InGlue);
9624 
9625   // Add the <id>, <numShadowBytes> operands.
9626   //
9627   // These do not require legalisation, and can be emitted directly to target
9628   // constant nodes.
9629   SDValue ID = getValue(CI.getArgOperand(0));
9630   assert(ID.getValueType() == MVT::i64);
9631   SDValue IDConst = DAG.getTargetConstant(
9632       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9633   Ops.push_back(IDConst);
9634 
9635   SDValue Shad = getValue(CI.getArgOperand(1));
9636   assert(Shad.getValueType() == MVT::i32);
9637   SDValue ShadConst = DAG.getTargetConstant(
9638       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9639   Ops.push_back(ShadConst);
9640 
9641   // Add the live variables.
9642   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9643 
9644   // Create the STACKMAP node.
9645   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9646   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9647   InGlue = Chain.getValue(1);
9648 
9649   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
9650 
9651   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9652 
9653   // Set the root to the target-lowered call chain.
9654   DAG.setRoot(Chain);
9655 
9656   // Inform the Frame Information that we have a stackmap in this function.
9657   FuncInfo.MF->getFrameInfo().setHasStackMap();
9658 }
9659 
9660 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9661 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9662                                           const BasicBlock *EHPadBB) {
9663   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9664   //                                                 i32 <numBytes>,
9665   //                                                 i8* <target>,
9666   //                                                 i32 <numArgs>,
9667   //                                                 [Args...],
9668   //                                                 [live variables...])
9669 
9670   CallingConv::ID CC = CB.getCallingConv();
9671   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9672   bool HasDef = !CB.getType()->isVoidTy();
9673   SDLoc dl = getCurSDLoc();
9674   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9675 
9676   // Handle immediate and symbolic callees.
9677   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9678     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9679                                    /*isTarget=*/true);
9680   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9681     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9682                                          SDLoc(SymbolicCallee),
9683                                          SymbolicCallee->getValueType(0));
9684 
9685   // Get the real number of arguments participating in the call <numArgs>
9686   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9687   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9688 
9689   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9690   // Intrinsics include all meta-operands up to but not including CC.
9691   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9692   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9693          "Not enough arguments provided to the patchpoint intrinsic");
9694 
9695   // For AnyRegCC the arguments are lowered later on manually.
9696   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9697   Type *ReturnTy =
9698       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9699 
9700   TargetLowering::CallLoweringInfo CLI(DAG);
9701   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9702                            ReturnTy, true);
9703   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9704 
9705   SDNode *CallEnd = Result.second.getNode();
9706   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9707     CallEnd = CallEnd->getOperand(0).getNode();
9708 
9709   /// Get a call instruction from the call sequence chain.
9710   /// Tail calls are not allowed.
9711   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9712          "Expected a callseq node.");
9713   SDNode *Call = CallEnd->getOperand(0).getNode();
9714   bool HasGlue = Call->getGluedNode();
9715 
9716   // Replace the target specific call node with the patchable intrinsic.
9717   SmallVector<SDValue, 8> Ops;
9718 
9719   // Push the chain.
9720   Ops.push_back(*(Call->op_begin()));
9721 
9722   // Optionally, push the glue (if any).
9723   if (HasGlue)
9724     Ops.push_back(*(Call->op_end() - 1));
9725 
9726   // Push the register mask info.
9727   if (HasGlue)
9728     Ops.push_back(*(Call->op_end() - 2));
9729   else
9730     Ops.push_back(*(Call->op_end() - 1));
9731 
9732   // Add the <id> and <numBytes> constants.
9733   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9734   Ops.push_back(DAG.getTargetConstant(
9735                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9736   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9737   Ops.push_back(DAG.getTargetConstant(
9738                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9739                   MVT::i32));
9740 
9741   // Add the callee.
9742   Ops.push_back(Callee);
9743 
9744   // Adjust <numArgs> to account for any arguments that have been passed on the
9745   // stack instead.
9746   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9747   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9748   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9749   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9750 
9751   // Add the calling convention
9752   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9753 
9754   // Add the arguments we omitted previously. The register allocator should
9755   // place these in any free register.
9756   if (IsAnyRegCC)
9757     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9758       Ops.push_back(getValue(CB.getArgOperand(i)));
9759 
9760   // Push the arguments from the call instruction.
9761   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9762   Ops.append(Call->op_begin() + 2, e);
9763 
9764   // Push live variables for the stack map.
9765   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9766 
9767   SDVTList NodeTys;
9768   if (IsAnyRegCC && HasDef) {
9769     // Create the return types based on the intrinsic definition
9770     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9771     SmallVector<EVT, 3> ValueVTs;
9772     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9773     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9774 
9775     // There is always a chain and a glue type at the end
9776     ValueVTs.push_back(MVT::Other);
9777     ValueVTs.push_back(MVT::Glue);
9778     NodeTys = DAG.getVTList(ValueVTs);
9779   } else
9780     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9781 
9782   // Replace the target specific call node with a PATCHPOINT node.
9783   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
9784 
9785   // Update the NodeMap.
9786   if (HasDef) {
9787     if (IsAnyRegCC)
9788       setValue(&CB, SDValue(PPV.getNode(), 0));
9789     else
9790       setValue(&CB, Result.first);
9791   }
9792 
9793   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9794   // call sequence. Furthermore the location of the chain and glue can change
9795   // when the AnyReg calling convention is used and the intrinsic returns a
9796   // value.
9797   if (IsAnyRegCC && HasDef) {
9798     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9799     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
9800     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9801   } else
9802     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
9803   DAG.DeleteNode(Call);
9804 
9805   // Inform the Frame Information that we have a patchpoint in this function.
9806   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9807 }
9808 
9809 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9810                                             unsigned Intrinsic) {
9811   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9812   SDValue Op1 = getValue(I.getArgOperand(0));
9813   SDValue Op2;
9814   if (I.arg_size() > 1)
9815     Op2 = getValue(I.getArgOperand(1));
9816   SDLoc dl = getCurSDLoc();
9817   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9818   SDValue Res;
9819   SDNodeFlags SDFlags;
9820   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9821     SDFlags.copyFMF(*FPMO);
9822 
9823   switch (Intrinsic) {
9824   case Intrinsic::vector_reduce_fadd:
9825     if (SDFlags.hasAllowReassociation())
9826       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9827                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9828                         SDFlags);
9829     else
9830       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9831     break;
9832   case Intrinsic::vector_reduce_fmul:
9833     if (SDFlags.hasAllowReassociation())
9834       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9835                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9836                         SDFlags);
9837     else
9838       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9839     break;
9840   case Intrinsic::vector_reduce_add:
9841     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9842     break;
9843   case Intrinsic::vector_reduce_mul:
9844     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9845     break;
9846   case Intrinsic::vector_reduce_and:
9847     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9848     break;
9849   case Intrinsic::vector_reduce_or:
9850     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9851     break;
9852   case Intrinsic::vector_reduce_xor:
9853     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9854     break;
9855   case Intrinsic::vector_reduce_smax:
9856     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9857     break;
9858   case Intrinsic::vector_reduce_smin:
9859     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9860     break;
9861   case Intrinsic::vector_reduce_umax:
9862     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9863     break;
9864   case Intrinsic::vector_reduce_umin:
9865     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9866     break;
9867   case Intrinsic::vector_reduce_fmax:
9868     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9869     break;
9870   case Intrinsic::vector_reduce_fmin:
9871     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9872     break;
9873   default:
9874     llvm_unreachable("Unhandled vector reduce intrinsic");
9875   }
9876   setValue(&I, Res);
9877 }
9878 
9879 /// Returns an AttributeList representing the attributes applied to the return
9880 /// value of the given call.
9881 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9882   SmallVector<Attribute::AttrKind, 2> Attrs;
9883   if (CLI.RetSExt)
9884     Attrs.push_back(Attribute::SExt);
9885   if (CLI.RetZExt)
9886     Attrs.push_back(Attribute::ZExt);
9887   if (CLI.IsInReg)
9888     Attrs.push_back(Attribute::InReg);
9889 
9890   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9891                             Attrs);
9892 }
9893 
9894 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9895 /// implementation, which just calls LowerCall.
9896 /// FIXME: When all targets are
9897 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9898 std::pair<SDValue, SDValue>
9899 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9900   // Handle the incoming return values from the call.
9901   CLI.Ins.clear();
9902   Type *OrigRetTy = CLI.RetTy;
9903   SmallVector<EVT, 4> RetTys;
9904   SmallVector<uint64_t, 4> Offsets;
9905   auto &DL = CLI.DAG.getDataLayout();
9906   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9907 
9908   if (CLI.IsPostTypeLegalization) {
9909     // If we are lowering a libcall after legalization, split the return type.
9910     SmallVector<EVT, 4> OldRetTys;
9911     SmallVector<uint64_t, 4> OldOffsets;
9912     RetTys.swap(OldRetTys);
9913     Offsets.swap(OldOffsets);
9914 
9915     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9916       EVT RetVT = OldRetTys[i];
9917       uint64_t Offset = OldOffsets[i];
9918       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9919       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9920       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9921       RetTys.append(NumRegs, RegisterVT);
9922       for (unsigned j = 0; j != NumRegs; ++j)
9923         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9924     }
9925   }
9926 
9927   SmallVector<ISD::OutputArg, 4> Outs;
9928   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9929 
9930   bool CanLowerReturn =
9931       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9932                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9933 
9934   SDValue DemoteStackSlot;
9935   int DemoteStackIdx = -100;
9936   if (!CanLowerReturn) {
9937     // FIXME: equivalent assert?
9938     // assert(!CS.hasInAllocaArgument() &&
9939     //        "sret demotion is incompatible with inalloca");
9940     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9941     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9942     MachineFunction &MF = CLI.DAG.getMachineFunction();
9943     DemoteStackIdx =
9944         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9945     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9946                                               DL.getAllocaAddrSpace());
9947 
9948     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9949     ArgListEntry Entry;
9950     Entry.Node = DemoteStackSlot;
9951     Entry.Ty = StackSlotPtrType;
9952     Entry.IsSExt = false;
9953     Entry.IsZExt = false;
9954     Entry.IsInReg = false;
9955     Entry.IsSRet = true;
9956     Entry.IsNest = false;
9957     Entry.IsByVal = false;
9958     Entry.IsByRef = false;
9959     Entry.IsReturned = false;
9960     Entry.IsSwiftSelf = false;
9961     Entry.IsSwiftAsync = false;
9962     Entry.IsSwiftError = false;
9963     Entry.IsCFGuardTarget = false;
9964     Entry.Alignment = Alignment;
9965     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9966     CLI.NumFixedArgs += 1;
9967     CLI.getArgs()[0].IndirectType = CLI.RetTy;
9968     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9969 
9970     // sret demotion isn't compatible with tail-calls, since the sret argument
9971     // points into the callers stack frame.
9972     CLI.IsTailCall = false;
9973   } else {
9974     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9975         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9976     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9977       ISD::ArgFlagsTy Flags;
9978       if (NeedsRegBlock) {
9979         Flags.setInConsecutiveRegs();
9980         if (I == RetTys.size() - 1)
9981           Flags.setInConsecutiveRegsLast();
9982       }
9983       EVT VT = RetTys[I];
9984       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9985                                                      CLI.CallConv, VT);
9986       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9987                                                        CLI.CallConv, VT);
9988       for (unsigned i = 0; i != NumRegs; ++i) {
9989         ISD::InputArg MyFlags;
9990         MyFlags.Flags = Flags;
9991         MyFlags.VT = RegisterVT;
9992         MyFlags.ArgVT = VT;
9993         MyFlags.Used = CLI.IsReturnValueUsed;
9994         if (CLI.RetTy->isPointerTy()) {
9995           MyFlags.Flags.setPointer();
9996           MyFlags.Flags.setPointerAddrSpace(
9997               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9998         }
9999         if (CLI.RetSExt)
10000           MyFlags.Flags.setSExt();
10001         if (CLI.RetZExt)
10002           MyFlags.Flags.setZExt();
10003         if (CLI.IsInReg)
10004           MyFlags.Flags.setInReg();
10005         CLI.Ins.push_back(MyFlags);
10006       }
10007     }
10008   }
10009 
10010   // We push in swifterror return as the last element of CLI.Ins.
10011   ArgListTy &Args = CLI.getArgs();
10012   if (supportSwiftError()) {
10013     for (const ArgListEntry &Arg : Args) {
10014       if (Arg.IsSwiftError) {
10015         ISD::InputArg MyFlags;
10016         MyFlags.VT = getPointerTy(DL);
10017         MyFlags.ArgVT = EVT(getPointerTy(DL));
10018         MyFlags.Flags.setSwiftError();
10019         CLI.Ins.push_back(MyFlags);
10020       }
10021     }
10022   }
10023 
10024   // Handle all of the outgoing arguments.
10025   CLI.Outs.clear();
10026   CLI.OutVals.clear();
10027   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10028     SmallVector<EVT, 4> ValueVTs;
10029     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10030     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10031     Type *FinalType = Args[i].Ty;
10032     if (Args[i].IsByVal)
10033       FinalType = Args[i].IndirectType;
10034     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10035         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10036     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10037          ++Value) {
10038       EVT VT = ValueVTs[Value];
10039       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10040       SDValue Op = SDValue(Args[i].Node.getNode(),
10041                            Args[i].Node.getResNo() + Value);
10042       ISD::ArgFlagsTy Flags;
10043 
10044       // Certain targets (such as MIPS), may have a different ABI alignment
10045       // for a type depending on the context. Give the target a chance to
10046       // specify the alignment it wants.
10047       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10048       Flags.setOrigAlign(OriginalAlignment);
10049 
10050       if (Args[i].Ty->isPointerTy()) {
10051         Flags.setPointer();
10052         Flags.setPointerAddrSpace(
10053             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10054       }
10055       if (Args[i].IsZExt)
10056         Flags.setZExt();
10057       if (Args[i].IsSExt)
10058         Flags.setSExt();
10059       if (Args[i].IsInReg) {
10060         // If we are using vectorcall calling convention, a structure that is
10061         // passed InReg - is surely an HVA
10062         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10063             isa<StructType>(FinalType)) {
10064           // The first value of a structure is marked
10065           if (0 == Value)
10066             Flags.setHvaStart();
10067           Flags.setHva();
10068         }
10069         // Set InReg Flag
10070         Flags.setInReg();
10071       }
10072       if (Args[i].IsSRet)
10073         Flags.setSRet();
10074       if (Args[i].IsSwiftSelf)
10075         Flags.setSwiftSelf();
10076       if (Args[i].IsSwiftAsync)
10077         Flags.setSwiftAsync();
10078       if (Args[i].IsSwiftError)
10079         Flags.setSwiftError();
10080       if (Args[i].IsCFGuardTarget)
10081         Flags.setCFGuardTarget();
10082       if (Args[i].IsByVal)
10083         Flags.setByVal();
10084       if (Args[i].IsByRef)
10085         Flags.setByRef();
10086       if (Args[i].IsPreallocated) {
10087         Flags.setPreallocated();
10088         // Set the byval flag for CCAssignFn callbacks that don't know about
10089         // preallocated.  This way we can know how many bytes we should've
10090         // allocated and how many bytes a callee cleanup function will pop.  If
10091         // we port preallocated to more targets, we'll have to add custom
10092         // preallocated handling in the various CC lowering callbacks.
10093         Flags.setByVal();
10094       }
10095       if (Args[i].IsInAlloca) {
10096         Flags.setInAlloca();
10097         // Set the byval flag for CCAssignFn callbacks that don't know about
10098         // inalloca.  This way we can know how many bytes we should've allocated
10099         // and how many bytes a callee cleanup function will pop.  If we port
10100         // inalloca to more targets, we'll have to add custom inalloca handling
10101         // in the various CC lowering callbacks.
10102         Flags.setByVal();
10103       }
10104       Align MemAlign;
10105       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10106         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10107         Flags.setByValSize(FrameSize);
10108 
10109         // info is not there but there are cases it cannot get right.
10110         if (auto MA = Args[i].Alignment)
10111           MemAlign = *MA;
10112         else
10113           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10114       } else if (auto MA = Args[i].Alignment) {
10115         MemAlign = *MA;
10116       } else {
10117         MemAlign = OriginalAlignment;
10118       }
10119       Flags.setMemAlign(MemAlign);
10120       if (Args[i].IsNest)
10121         Flags.setNest();
10122       if (NeedsRegBlock)
10123         Flags.setInConsecutiveRegs();
10124 
10125       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10126                                                  CLI.CallConv, VT);
10127       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10128                                                         CLI.CallConv, VT);
10129       SmallVector<SDValue, 4> Parts(NumParts);
10130       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10131 
10132       if (Args[i].IsSExt)
10133         ExtendKind = ISD::SIGN_EXTEND;
10134       else if (Args[i].IsZExt)
10135         ExtendKind = ISD::ZERO_EXTEND;
10136 
10137       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10138       // for now.
10139       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10140           CanLowerReturn) {
10141         assert((CLI.RetTy == Args[i].Ty ||
10142                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10143                  CLI.RetTy->getPointerAddressSpace() ==
10144                      Args[i].Ty->getPointerAddressSpace())) &&
10145                RetTys.size() == NumValues && "unexpected use of 'returned'");
10146         // Before passing 'returned' to the target lowering code, ensure that
10147         // either the register MVT and the actual EVT are the same size or that
10148         // the return value and argument are extended in the same way; in these
10149         // cases it's safe to pass the argument register value unchanged as the
10150         // return register value (although it's at the target's option whether
10151         // to do so)
10152         // TODO: allow code generation to take advantage of partially preserved
10153         // registers rather than clobbering the entire register when the
10154         // parameter extension method is not compatible with the return
10155         // extension method
10156         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10157             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10158              CLI.RetZExt == Args[i].IsZExt))
10159           Flags.setReturned();
10160       }
10161 
10162       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10163                      CLI.CallConv, ExtendKind);
10164 
10165       for (unsigned j = 0; j != NumParts; ++j) {
10166         // if it isn't first piece, alignment must be 1
10167         // For scalable vectors the scalable part is currently handled
10168         // by individual targets, so we just use the known minimum size here.
10169         ISD::OutputArg MyFlags(
10170             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10171             i < CLI.NumFixedArgs, i,
10172             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10173         if (NumParts > 1 && j == 0)
10174           MyFlags.Flags.setSplit();
10175         else if (j != 0) {
10176           MyFlags.Flags.setOrigAlign(Align(1));
10177           if (j == NumParts - 1)
10178             MyFlags.Flags.setSplitEnd();
10179         }
10180 
10181         CLI.Outs.push_back(MyFlags);
10182         CLI.OutVals.push_back(Parts[j]);
10183       }
10184 
10185       if (NeedsRegBlock && Value == NumValues - 1)
10186         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10187     }
10188   }
10189 
10190   SmallVector<SDValue, 4> InVals;
10191   CLI.Chain = LowerCall(CLI, InVals);
10192 
10193   // Update CLI.InVals to use outside of this function.
10194   CLI.InVals = InVals;
10195 
10196   // Verify that the target's LowerCall behaved as expected.
10197   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10198          "LowerCall didn't return a valid chain!");
10199   assert((!CLI.IsTailCall || InVals.empty()) &&
10200          "LowerCall emitted a return value for a tail call!");
10201   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10202          "LowerCall didn't emit the correct number of values!");
10203 
10204   // For a tail call, the return value is merely live-out and there aren't
10205   // any nodes in the DAG representing it. Return a special value to
10206   // indicate that a tail call has been emitted and no more Instructions
10207   // should be processed in the current block.
10208   if (CLI.IsTailCall) {
10209     CLI.DAG.setRoot(CLI.Chain);
10210     return std::make_pair(SDValue(), SDValue());
10211   }
10212 
10213 #ifndef NDEBUG
10214   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10215     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10216     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10217            "LowerCall emitted a value with the wrong type!");
10218   }
10219 #endif
10220 
10221   SmallVector<SDValue, 4> ReturnValues;
10222   if (!CanLowerReturn) {
10223     // The instruction result is the result of loading from the
10224     // hidden sret parameter.
10225     SmallVector<EVT, 1> PVTs;
10226     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
10227 
10228     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10229     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10230     EVT PtrVT = PVTs[0];
10231 
10232     unsigned NumValues = RetTys.size();
10233     ReturnValues.resize(NumValues);
10234     SmallVector<SDValue, 4> Chains(NumValues);
10235 
10236     // An aggregate return value cannot wrap around the address space, so
10237     // offsets to its parts don't wrap either.
10238     SDNodeFlags Flags;
10239     Flags.setNoUnsignedWrap(true);
10240 
10241     MachineFunction &MF = CLI.DAG.getMachineFunction();
10242     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10243     for (unsigned i = 0; i < NumValues; ++i) {
10244       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10245                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10246                                                         PtrVT), Flags);
10247       SDValue L = CLI.DAG.getLoad(
10248           RetTys[i], CLI.DL, CLI.Chain, Add,
10249           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10250                                             DemoteStackIdx, Offsets[i]),
10251           HiddenSRetAlign);
10252       ReturnValues[i] = L;
10253       Chains[i] = L.getValue(1);
10254     }
10255 
10256     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10257   } else {
10258     // Collect the legal value parts into potentially illegal values
10259     // that correspond to the original function's return values.
10260     std::optional<ISD::NodeType> AssertOp;
10261     if (CLI.RetSExt)
10262       AssertOp = ISD::AssertSext;
10263     else if (CLI.RetZExt)
10264       AssertOp = ISD::AssertZext;
10265     unsigned CurReg = 0;
10266     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10267       EVT VT = RetTys[I];
10268       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10269                                                      CLI.CallConv, VT);
10270       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10271                                                        CLI.CallConv, VT);
10272 
10273       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10274                                               NumRegs, RegisterVT, VT, nullptr,
10275                                               CLI.CallConv, AssertOp));
10276       CurReg += NumRegs;
10277     }
10278 
10279     // For a function returning void, there is no return value. We can't create
10280     // such a node, so we just return a null return value in that case. In
10281     // that case, nothing will actually look at the value.
10282     if (ReturnValues.empty())
10283       return std::make_pair(SDValue(), CLI.Chain);
10284   }
10285 
10286   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10287                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10288   return std::make_pair(Res, CLI.Chain);
10289 }
10290 
10291 /// Places new result values for the node in Results (their number
10292 /// and types must exactly match those of the original return values of
10293 /// the node), or leaves Results empty, which indicates that the node is not
10294 /// to be custom lowered after all.
10295 void TargetLowering::LowerOperationWrapper(SDNode *N,
10296                                            SmallVectorImpl<SDValue> &Results,
10297                                            SelectionDAG &DAG) const {
10298   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10299 
10300   if (!Res.getNode())
10301     return;
10302 
10303   // If the original node has one result, take the return value from
10304   // LowerOperation as is. It might not be result number 0.
10305   if (N->getNumValues() == 1) {
10306     Results.push_back(Res);
10307     return;
10308   }
10309 
10310   // If the original node has multiple results, then the return node should
10311   // have the same number of results.
10312   assert((N->getNumValues() == Res->getNumValues()) &&
10313       "Lowering returned the wrong number of results!");
10314 
10315   // Places new result values base on N result number.
10316   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10317     Results.push_back(Res.getValue(I));
10318 }
10319 
10320 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10321   llvm_unreachable("LowerOperation not implemented for this target!");
10322 }
10323 
10324 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10325                                                      unsigned Reg,
10326                                                      ISD::NodeType ExtendType) {
10327   SDValue Op = getNonRegisterValue(V);
10328   assert((Op.getOpcode() != ISD::CopyFromReg ||
10329           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10330          "Copy from a reg to the same reg!");
10331   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10332 
10333   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10334   // If this is an InlineAsm we have to match the registers required, not the
10335   // notional registers required by the type.
10336 
10337   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10338                    std::nullopt); // This is not an ABI copy.
10339   SDValue Chain = DAG.getEntryNode();
10340 
10341   if (ExtendType == ISD::ANY_EXTEND) {
10342     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10343     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10344       ExtendType = PreferredExtendIt->second;
10345   }
10346   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10347   PendingExports.push_back(Chain);
10348 }
10349 
10350 #include "llvm/CodeGen/SelectionDAGISel.h"
10351 
10352 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10353 /// entry block, return true.  This includes arguments used by switches, since
10354 /// the switch may expand into multiple basic blocks.
10355 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10356   // With FastISel active, we may be splitting blocks, so force creation
10357   // of virtual registers for all non-dead arguments.
10358   if (FastISel)
10359     return A->use_empty();
10360 
10361   const BasicBlock &Entry = A->getParent()->front();
10362   for (const User *U : A->users())
10363     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10364       return false;  // Use not in entry block.
10365 
10366   return true;
10367 }
10368 
10369 using ArgCopyElisionMapTy =
10370     DenseMap<const Argument *,
10371              std::pair<const AllocaInst *, const StoreInst *>>;
10372 
10373 /// Scan the entry block of the function in FuncInfo for arguments that look
10374 /// like copies into a local alloca. Record any copied arguments in
10375 /// ArgCopyElisionCandidates.
10376 static void
10377 findArgumentCopyElisionCandidates(const DataLayout &DL,
10378                                   FunctionLoweringInfo *FuncInfo,
10379                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10380   // Record the state of every static alloca used in the entry block. Argument
10381   // allocas are all used in the entry block, so we need approximately as many
10382   // entries as we have arguments.
10383   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10384   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10385   unsigned NumArgs = FuncInfo->Fn->arg_size();
10386   StaticAllocas.reserve(NumArgs * 2);
10387 
10388   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10389     if (!V)
10390       return nullptr;
10391     V = V->stripPointerCasts();
10392     const auto *AI = dyn_cast<AllocaInst>(V);
10393     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10394       return nullptr;
10395     auto Iter = StaticAllocas.insert({AI, Unknown});
10396     return &Iter.first->second;
10397   };
10398 
10399   // Look for stores of arguments to static allocas. Look through bitcasts and
10400   // GEPs to handle type coercions, as long as the alloca is fully initialized
10401   // by the store. Any non-store use of an alloca escapes it and any subsequent
10402   // unanalyzed store might write it.
10403   // FIXME: Handle structs initialized with multiple stores.
10404   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10405     // Look for stores, and handle non-store uses conservatively.
10406     const auto *SI = dyn_cast<StoreInst>(&I);
10407     if (!SI) {
10408       // We will look through cast uses, so ignore them completely.
10409       if (I.isCast())
10410         continue;
10411       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10412       // to allocas.
10413       if (I.isDebugOrPseudoInst())
10414         continue;
10415       // This is an unknown instruction. Assume it escapes or writes to all
10416       // static alloca operands.
10417       for (const Use &U : I.operands()) {
10418         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10419           *Info = StaticAllocaInfo::Clobbered;
10420       }
10421       continue;
10422     }
10423 
10424     // If the stored value is a static alloca, mark it as escaped.
10425     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10426       *Info = StaticAllocaInfo::Clobbered;
10427 
10428     // Check if the destination is a static alloca.
10429     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10430     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10431     if (!Info)
10432       continue;
10433     const AllocaInst *AI = cast<AllocaInst>(Dst);
10434 
10435     // Skip allocas that have been initialized or clobbered.
10436     if (*Info != StaticAllocaInfo::Unknown)
10437       continue;
10438 
10439     // Check if the stored value is an argument, and that this store fully
10440     // initializes the alloca.
10441     // If the argument type has padding bits we can't directly forward a pointer
10442     // as the upper bits may contain garbage.
10443     // Don't elide copies from the same argument twice.
10444     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10445     const auto *Arg = dyn_cast<Argument>(Val);
10446     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10447         Arg->getType()->isEmptyTy() ||
10448         DL.getTypeStoreSize(Arg->getType()) !=
10449             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10450         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10451         ArgCopyElisionCandidates.count(Arg)) {
10452       *Info = StaticAllocaInfo::Clobbered;
10453       continue;
10454     }
10455 
10456     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10457                       << '\n');
10458 
10459     // Mark this alloca and store for argument copy elision.
10460     *Info = StaticAllocaInfo::Elidable;
10461     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10462 
10463     // Stop scanning if we've seen all arguments. This will happen early in -O0
10464     // builds, which is useful, because -O0 builds have large entry blocks and
10465     // many allocas.
10466     if (ArgCopyElisionCandidates.size() == NumArgs)
10467       break;
10468   }
10469 }
10470 
10471 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10472 /// ArgVal is a load from a suitable fixed stack object.
10473 static void tryToElideArgumentCopy(
10474     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10475     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10476     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10477     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10478     SDValue ArgVal, bool &ArgHasUses) {
10479   // Check if this is a load from a fixed stack object.
10480   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10481   if (!LNode)
10482     return;
10483   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10484   if (!FINode)
10485     return;
10486 
10487   // Check that the fixed stack object is the right size and alignment.
10488   // Look at the alignment that the user wrote on the alloca instead of looking
10489   // at the stack object.
10490   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10491   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10492   const AllocaInst *AI = ArgCopyIter->second.first;
10493   int FixedIndex = FINode->getIndex();
10494   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10495   int OldIndex = AllocaIndex;
10496   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10497   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10498     LLVM_DEBUG(
10499         dbgs() << "  argument copy elision failed due to bad fixed stack "
10500                   "object size\n");
10501     return;
10502   }
10503   Align RequiredAlignment = AI->getAlign();
10504   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10505     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10506                          "greater than stack argument alignment ("
10507                       << DebugStr(RequiredAlignment) << " vs "
10508                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10509     return;
10510   }
10511 
10512   // Perform the elision. Delete the old stack object and replace its only use
10513   // in the variable info map. Mark the stack object as mutable.
10514   LLVM_DEBUG({
10515     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10516            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10517            << '\n';
10518   });
10519   MFI.RemoveStackObject(OldIndex);
10520   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10521   AllocaIndex = FixedIndex;
10522   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10523   Chains.push_back(ArgVal.getValue(1));
10524 
10525   // Avoid emitting code for the store implementing the copy.
10526   const StoreInst *SI = ArgCopyIter->second.second;
10527   ElidedArgCopyInstrs.insert(SI);
10528 
10529   // Check for uses of the argument again so that we can avoid exporting ArgVal
10530   // if it is't used by anything other than the store.
10531   for (const Value *U : Arg.users()) {
10532     if (U != SI) {
10533       ArgHasUses = true;
10534       break;
10535     }
10536   }
10537 }
10538 
10539 void SelectionDAGISel::LowerArguments(const Function &F) {
10540   SelectionDAG &DAG = SDB->DAG;
10541   SDLoc dl = SDB->getCurSDLoc();
10542   const DataLayout &DL = DAG.getDataLayout();
10543   SmallVector<ISD::InputArg, 16> Ins;
10544 
10545   // In Naked functions we aren't going to save any registers.
10546   if (F.hasFnAttribute(Attribute::Naked))
10547     return;
10548 
10549   if (!FuncInfo->CanLowerReturn) {
10550     // Put in an sret pointer parameter before all the other parameters.
10551     SmallVector<EVT, 1> ValueVTs;
10552     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10553                     F.getReturnType()->getPointerTo(
10554                         DAG.getDataLayout().getAllocaAddrSpace()),
10555                     ValueVTs);
10556 
10557     // NOTE: Assuming that a pointer will never break down to more than one VT
10558     // or one register.
10559     ISD::ArgFlagsTy Flags;
10560     Flags.setSRet();
10561     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10562     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10563                          ISD::InputArg::NoArgIndex, 0);
10564     Ins.push_back(RetArg);
10565   }
10566 
10567   // Look for stores of arguments to static allocas. Mark such arguments with a
10568   // flag to ask the target to give us the memory location of that argument if
10569   // available.
10570   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10571   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10572                                     ArgCopyElisionCandidates);
10573 
10574   // Set up the incoming argument description vector.
10575   for (const Argument &Arg : F.args()) {
10576     unsigned ArgNo = Arg.getArgNo();
10577     SmallVector<EVT, 4> ValueVTs;
10578     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10579     bool isArgValueUsed = !Arg.use_empty();
10580     unsigned PartBase = 0;
10581     Type *FinalType = Arg.getType();
10582     if (Arg.hasAttribute(Attribute::ByVal))
10583       FinalType = Arg.getParamByValType();
10584     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10585         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10586     for (unsigned Value = 0, NumValues = ValueVTs.size();
10587          Value != NumValues; ++Value) {
10588       EVT VT = ValueVTs[Value];
10589       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10590       ISD::ArgFlagsTy Flags;
10591 
10592 
10593       if (Arg.getType()->isPointerTy()) {
10594         Flags.setPointer();
10595         Flags.setPointerAddrSpace(
10596             cast<PointerType>(Arg.getType())->getAddressSpace());
10597       }
10598       if (Arg.hasAttribute(Attribute::ZExt))
10599         Flags.setZExt();
10600       if (Arg.hasAttribute(Attribute::SExt))
10601         Flags.setSExt();
10602       if (Arg.hasAttribute(Attribute::InReg)) {
10603         // If we are using vectorcall calling convention, a structure that is
10604         // passed InReg - is surely an HVA
10605         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10606             isa<StructType>(Arg.getType())) {
10607           // The first value of a structure is marked
10608           if (0 == Value)
10609             Flags.setHvaStart();
10610           Flags.setHva();
10611         }
10612         // Set InReg Flag
10613         Flags.setInReg();
10614       }
10615       if (Arg.hasAttribute(Attribute::StructRet))
10616         Flags.setSRet();
10617       if (Arg.hasAttribute(Attribute::SwiftSelf))
10618         Flags.setSwiftSelf();
10619       if (Arg.hasAttribute(Attribute::SwiftAsync))
10620         Flags.setSwiftAsync();
10621       if (Arg.hasAttribute(Attribute::SwiftError))
10622         Flags.setSwiftError();
10623       if (Arg.hasAttribute(Attribute::ByVal))
10624         Flags.setByVal();
10625       if (Arg.hasAttribute(Attribute::ByRef))
10626         Flags.setByRef();
10627       if (Arg.hasAttribute(Attribute::InAlloca)) {
10628         Flags.setInAlloca();
10629         // Set the byval flag for CCAssignFn callbacks that don't know about
10630         // inalloca.  This way we can know how many bytes we should've allocated
10631         // and how many bytes a callee cleanup function will pop.  If we port
10632         // inalloca to more targets, we'll have to add custom inalloca handling
10633         // in the various CC lowering callbacks.
10634         Flags.setByVal();
10635       }
10636       if (Arg.hasAttribute(Attribute::Preallocated)) {
10637         Flags.setPreallocated();
10638         // Set the byval flag for CCAssignFn callbacks that don't know about
10639         // preallocated.  This way we can know how many bytes we should've
10640         // allocated and how many bytes a callee cleanup function will pop.  If
10641         // we port preallocated to more targets, we'll have to add custom
10642         // preallocated handling in the various CC lowering callbacks.
10643         Flags.setByVal();
10644       }
10645 
10646       // Certain targets (such as MIPS), may have a different ABI alignment
10647       // for a type depending on the context. Give the target a chance to
10648       // specify the alignment it wants.
10649       const Align OriginalAlignment(
10650           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10651       Flags.setOrigAlign(OriginalAlignment);
10652 
10653       Align MemAlign;
10654       Type *ArgMemTy = nullptr;
10655       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10656           Flags.isByRef()) {
10657         if (!ArgMemTy)
10658           ArgMemTy = Arg.getPointeeInMemoryValueType();
10659 
10660         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10661 
10662         // For in-memory arguments, size and alignment should be passed from FE.
10663         // BE will guess if this info is not there but there are cases it cannot
10664         // get right.
10665         if (auto ParamAlign = Arg.getParamStackAlign())
10666           MemAlign = *ParamAlign;
10667         else if ((ParamAlign = Arg.getParamAlign()))
10668           MemAlign = *ParamAlign;
10669         else
10670           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10671         if (Flags.isByRef())
10672           Flags.setByRefSize(MemSize);
10673         else
10674           Flags.setByValSize(MemSize);
10675       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10676         MemAlign = *ParamAlign;
10677       } else {
10678         MemAlign = OriginalAlignment;
10679       }
10680       Flags.setMemAlign(MemAlign);
10681 
10682       if (Arg.hasAttribute(Attribute::Nest))
10683         Flags.setNest();
10684       if (NeedsRegBlock)
10685         Flags.setInConsecutiveRegs();
10686       if (ArgCopyElisionCandidates.count(&Arg))
10687         Flags.setCopyElisionCandidate();
10688       if (Arg.hasAttribute(Attribute::Returned))
10689         Flags.setReturned();
10690 
10691       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10692           *CurDAG->getContext(), F.getCallingConv(), VT);
10693       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10694           *CurDAG->getContext(), F.getCallingConv(), VT);
10695       for (unsigned i = 0; i != NumRegs; ++i) {
10696         // For scalable vectors, use the minimum size; individual targets
10697         // are responsible for handling scalable vector arguments and
10698         // return values.
10699         ISD::InputArg MyFlags(
10700             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
10701             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
10702         if (NumRegs > 1 && i == 0)
10703           MyFlags.Flags.setSplit();
10704         // if it isn't first piece, alignment must be 1
10705         else if (i > 0) {
10706           MyFlags.Flags.setOrigAlign(Align(1));
10707           if (i == NumRegs - 1)
10708             MyFlags.Flags.setSplitEnd();
10709         }
10710         Ins.push_back(MyFlags);
10711       }
10712       if (NeedsRegBlock && Value == NumValues - 1)
10713         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10714       PartBase += VT.getStoreSize().getKnownMinValue();
10715     }
10716   }
10717 
10718   // Call the target to set up the argument values.
10719   SmallVector<SDValue, 8> InVals;
10720   SDValue NewRoot = TLI->LowerFormalArguments(
10721       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10722 
10723   // Verify that the target's LowerFormalArguments behaved as expected.
10724   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10725          "LowerFormalArguments didn't return a valid chain!");
10726   assert(InVals.size() == Ins.size() &&
10727          "LowerFormalArguments didn't emit the correct number of values!");
10728   LLVM_DEBUG({
10729     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10730       assert(InVals[i].getNode() &&
10731              "LowerFormalArguments emitted a null value!");
10732       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10733              "LowerFormalArguments emitted a value with the wrong type!");
10734     }
10735   });
10736 
10737   // Update the DAG with the new chain value resulting from argument lowering.
10738   DAG.setRoot(NewRoot);
10739 
10740   // Set up the argument values.
10741   unsigned i = 0;
10742   if (!FuncInfo->CanLowerReturn) {
10743     // Create a virtual register for the sret pointer, and put in a copy
10744     // from the sret argument into it.
10745     SmallVector<EVT, 1> ValueVTs;
10746     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10747                     F.getReturnType()->getPointerTo(
10748                         DAG.getDataLayout().getAllocaAddrSpace()),
10749                     ValueVTs);
10750     MVT VT = ValueVTs[0].getSimpleVT();
10751     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10752     std::optional<ISD::NodeType> AssertOp;
10753     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10754                                         nullptr, F.getCallingConv(), AssertOp);
10755 
10756     MachineFunction& MF = SDB->DAG.getMachineFunction();
10757     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10758     Register SRetReg =
10759         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10760     FuncInfo->DemoteRegister = SRetReg;
10761     NewRoot =
10762         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10763     DAG.setRoot(NewRoot);
10764 
10765     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10766     ++i;
10767   }
10768 
10769   SmallVector<SDValue, 4> Chains;
10770   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10771   for (const Argument &Arg : F.args()) {
10772     SmallVector<SDValue, 4> ArgValues;
10773     SmallVector<EVT, 4> ValueVTs;
10774     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10775     unsigned NumValues = ValueVTs.size();
10776     if (NumValues == 0)
10777       continue;
10778 
10779     bool ArgHasUses = !Arg.use_empty();
10780 
10781     // Elide the copying store if the target loaded this argument from a
10782     // suitable fixed stack object.
10783     if (Ins[i].Flags.isCopyElisionCandidate()) {
10784       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10785                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10786                              InVals[i], ArgHasUses);
10787     }
10788 
10789     // If this argument is unused then remember its value. It is used to generate
10790     // debugging information.
10791     bool isSwiftErrorArg =
10792         TLI->supportSwiftError() &&
10793         Arg.hasAttribute(Attribute::SwiftError);
10794     if (!ArgHasUses && !isSwiftErrorArg) {
10795       SDB->setUnusedArgValue(&Arg, InVals[i]);
10796 
10797       // Also remember any frame index for use in FastISel.
10798       if (FrameIndexSDNode *FI =
10799           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10800         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10801     }
10802 
10803     for (unsigned Val = 0; Val != NumValues; ++Val) {
10804       EVT VT = ValueVTs[Val];
10805       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10806                                                       F.getCallingConv(), VT);
10807       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10808           *CurDAG->getContext(), F.getCallingConv(), VT);
10809 
10810       // Even an apparent 'unused' swifterror argument needs to be returned. So
10811       // we do generate a copy for it that can be used on return from the
10812       // function.
10813       if (ArgHasUses || isSwiftErrorArg) {
10814         std::optional<ISD::NodeType> AssertOp;
10815         if (Arg.hasAttribute(Attribute::SExt))
10816           AssertOp = ISD::AssertSext;
10817         else if (Arg.hasAttribute(Attribute::ZExt))
10818           AssertOp = ISD::AssertZext;
10819 
10820         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10821                                              PartVT, VT, nullptr,
10822                                              F.getCallingConv(), AssertOp));
10823       }
10824 
10825       i += NumParts;
10826     }
10827 
10828     // We don't need to do anything else for unused arguments.
10829     if (ArgValues.empty())
10830       continue;
10831 
10832     // Note down frame index.
10833     if (FrameIndexSDNode *FI =
10834         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10835       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10836 
10837     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
10838                                      SDB->getCurSDLoc());
10839 
10840     SDB->setValue(&Arg, Res);
10841     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10842       // We want to associate the argument with the frame index, among
10843       // involved operands, that correspond to the lowest address. The
10844       // getCopyFromParts function, called earlier, is swapping the order of
10845       // the operands to BUILD_PAIR depending on endianness. The result of
10846       // that swapping is that the least significant bits of the argument will
10847       // be in the first operand of the BUILD_PAIR node, and the most
10848       // significant bits will be in the second operand.
10849       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10850       if (LoadSDNode *LNode =
10851           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10852         if (FrameIndexSDNode *FI =
10853             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10854           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10855     }
10856 
10857     // Analyses past this point are naive and don't expect an assertion.
10858     if (Res.getOpcode() == ISD::AssertZext)
10859       Res = Res.getOperand(0);
10860 
10861     // Update the SwiftErrorVRegDefMap.
10862     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10863       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10864       if (Register::isVirtualRegister(Reg))
10865         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10866                                    Reg);
10867     }
10868 
10869     // If this argument is live outside of the entry block, insert a copy from
10870     // wherever we got it to the vreg that other BB's will reference it as.
10871     if (Res.getOpcode() == ISD::CopyFromReg) {
10872       // If we can, though, try to skip creating an unnecessary vreg.
10873       // FIXME: This isn't very clean... it would be nice to make this more
10874       // general.
10875       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10876       if (Register::isVirtualRegister(Reg)) {
10877         FuncInfo->ValueMap[&Arg] = Reg;
10878         continue;
10879       }
10880     }
10881     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10882       FuncInfo->InitializeRegForValue(&Arg);
10883       SDB->CopyToExportRegsIfNeeded(&Arg);
10884     }
10885   }
10886 
10887   if (!Chains.empty()) {
10888     Chains.push_back(NewRoot);
10889     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10890   }
10891 
10892   DAG.setRoot(NewRoot);
10893 
10894   assert(i == InVals.size() && "Argument register count mismatch!");
10895 
10896   // If any argument copy elisions occurred and we have debug info, update the
10897   // stale frame indices used in the dbg.declare variable info table.
10898   if (!ArgCopyElisionFrameIndexMap.empty()) {
10899     for (MachineFunction::VariableDbgInfo &VI :
10900          MF->getInStackSlotVariableDbgInfo()) {
10901       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
10902       if (I != ArgCopyElisionFrameIndexMap.end())
10903         VI.updateStackSlot(I->second);
10904     }
10905   }
10906 
10907   // Finally, if the target has anything special to do, allow it to do so.
10908   emitFunctionEntryCode();
10909 }
10910 
10911 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10912 /// ensure constants are generated when needed.  Remember the virtual registers
10913 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10914 /// directly add them, because expansion might result in multiple MBB's for one
10915 /// BB.  As such, the start of the BB might correspond to a different MBB than
10916 /// the end.
10917 void
10918 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10919   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10920 
10921   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10922 
10923   // Check PHI nodes in successors that expect a value to be available from this
10924   // block.
10925   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
10926     if (!isa<PHINode>(SuccBB->begin())) continue;
10927     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10928 
10929     // If this terminator has multiple identical successors (common for
10930     // switches), only handle each succ once.
10931     if (!SuccsHandled.insert(SuccMBB).second)
10932       continue;
10933 
10934     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10935 
10936     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10937     // nodes and Machine PHI nodes, but the incoming operands have not been
10938     // emitted yet.
10939     for (const PHINode &PN : SuccBB->phis()) {
10940       // Ignore dead phi's.
10941       if (PN.use_empty())
10942         continue;
10943 
10944       // Skip empty types
10945       if (PN.getType()->isEmptyTy())
10946         continue;
10947 
10948       unsigned Reg;
10949       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10950 
10951       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
10952         unsigned &RegOut = ConstantsOut[C];
10953         if (RegOut == 0) {
10954           RegOut = FuncInfo.CreateRegs(C);
10955           // We need to zero/sign extend ConstantInt phi operands to match
10956           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
10957           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
10958           if (auto *CI = dyn_cast<ConstantInt>(C))
10959             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
10960                                                     : ISD::ZERO_EXTEND;
10961           CopyValueToVirtualRegister(C, RegOut, ExtendType);
10962         }
10963         Reg = RegOut;
10964       } else {
10965         DenseMap<const Value *, Register>::iterator I =
10966           FuncInfo.ValueMap.find(PHIOp);
10967         if (I != FuncInfo.ValueMap.end())
10968           Reg = I->second;
10969         else {
10970           assert(isa<AllocaInst>(PHIOp) &&
10971                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10972                  "Didn't codegen value into a register!??");
10973           Reg = FuncInfo.CreateRegs(PHIOp);
10974           CopyValueToVirtualRegister(PHIOp, Reg);
10975         }
10976       }
10977 
10978       // Remember that this register needs to added to the machine PHI node as
10979       // the input for this MBB.
10980       SmallVector<EVT, 4> ValueVTs;
10981       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10982       for (EVT VT : ValueVTs) {
10983         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10984         for (unsigned i = 0; i != NumRegisters; ++i)
10985           FuncInfo.PHINodesToUpdate.push_back(
10986               std::make_pair(&*MBBI++, Reg + i));
10987         Reg += NumRegisters;
10988       }
10989     }
10990   }
10991 
10992   ConstantsOut.clear();
10993 }
10994 
10995 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10996   MachineFunction::iterator I(MBB);
10997   if (++I == FuncInfo.MF->end())
10998     return nullptr;
10999   return &*I;
11000 }
11001 
11002 /// During lowering new call nodes can be created (such as memset, etc.).
11003 /// Those will become new roots of the current DAG, but complications arise
11004 /// when they are tail calls. In such cases, the call lowering will update
11005 /// the root, but the builder still needs to know that a tail call has been
11006 /// lowered in order to avoid generating an additional return.
11007 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11008   // If the node is null, we do have a tail call.
11009   if (MaybeTC.getNode() != nullptr)
11010     DAG.setRoot(MaybeTC);
11011   else
11012     HasTailCall = true;
11013 }
11014 
11015 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11016                                         MachineBasicBlock *SwitchMBB,
11017                                         MachineBasicBlock *DefaultMBB) {
11018   MachineFunction *CurMF = FuncInfo.MF;
11019   MachineBasicBlock *NextMBB = nullptr;
11020   MachineFunction::iterator BBI(W.MBB);
11021   if (++BBI != FuncInfo.MF->end())
11022     NextMBB = &*BBI;
11023 
11024   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11025 
11026   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11027 
11028   if (Size == 2 && W.MBB == SwitchMBB) {
11029     // If any two of the cases has the same destination, and if one value
11030     // is the same as the other, but has one bit unset that the other has set,
11031     // use bit manipulation to do two compares at once.  For example:
11032     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11033     // TODO: This could be extended to merge any 2 cases in switches with 3
11034     // cases.
11035     // TODO: Handle cases where W.CaseBB != SwitchBB.
11036     CaseCluster &Small = *W.FirstCluster;
11037     CaseCluster &Big = *W.LastCluster;
11038 
11039     if (Small.Low == Small.High && Big.Low == Big.High &&
11040         Small.MBB == Big.MBB) {
11041       const APInt &SmallValue = Small.Low->getValue();
11042       const APInt &BigValue = Big.Low->getValue();
11043 
11044       // Check that there is only one bit different.
11045       APInt CommonBit = BigValue ^ SmallValue;
11046       if (CommonBit.isPowerOf2()) {
11047         SDValue CondLHS = getValue(Cond);
11048         EVT VT = CondLHS.getValueType();
11049         SDLoc DL = getCurSDLoc();
11050 
11051         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11052                                  DAG.getConstant(CommonBit, DL, VT));
11053         SDValue Cond = DAG.getSetCC(
11054             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11055             ISD::SETEQ);
11056 
11057         // Update successor info.
11058         // Both Small and Big will jump to Small.BB, so we sum up the
11059         // probabilities.
11060         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11061         if (BPI)
11062           addSuccessorWithProb(
11063               SwitchMBB, DefaultMBB,
11064               // The default destination is the first successor in IR.
11065               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11066         else
11067           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11068 
11069         // Insert the true branch.
11070         SDValue BrCond =
11071             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11072                         DAG.getBasicBlock(Small.MBB));
11073         // Insert the false branch.
11074         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11075                              DAG.getBasicBlock(DefaultMBB));
11076 
11077         DAG.setRoot(BrCond);
11078         return;
11079       }
11080     }
11081   }
11082 
11083   if (TM.getOptLevel() != CodeGenOpt::None) {
11084     // Here, we order cases by probability so the most likely case will be
11085     // checked first. However, two clusters can have the same probability in
11086     // which case their relative ordering is non-deterministic. So we use Low
11087     // as a tie-breaker as clusters are guaranteed to never overlap.
11088     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11089                [](const CaseCluster &a, const CaseCluster &b) {
11090       return a.Prob != b.Prob ?
11091              a.Prob > b.Prob :
11092              a.Low->getValue().slt(b.Low->getValue());
11093     });
11094 
11095     // Rearrange the case blocks so that the last one falls through if possible
11096     // without changing the order of probabilities.
11097     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11098       --I;
11099       if (I->Prob > W.LastCluster->Prob)
11100         break;
11101       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11102         std::swap(*I, *W.LastCluster);
11103         break;
11104       }
11105     }
11106   }
11107 
11108   // Compute total probability.
11109   BranchProbability DefaultProb = W.DefaultProb;
11110   BranchProbability UnhandledProbs = DefaultProb;
11111   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11112     UnhandledProbs += I->Prob;
11113 
11114   MachineBasicBlock *CurMBB = W.MBB;
11115   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11116     bool FallthroughUnreachable = false;
11117     MachineBasicBlock *Fallthrough;
11118     if (I == W.LastCluster) {
11119       // For the last cluster, fall through to the default destination.
11120       Fallthrough = DefaultMBB;
11121       FallthroughUnreachable = isa<UnreachableInst>(
11122           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11123     } else {
11124       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11125       CurMF->insert(BBI, Fallthrough);
11126       // Put Cond in a virtual register to make it available from the new blocks.
11127       ExportFromCurrentBlock(Cond);
11128     }
11129     UnhandledProbs -= I->Prob;
11130 
11131     switch (I->Kind) {
11132       case CC_JumpTable: {
11133         // FIXME: Optimize away range check based on pivot comparisons.
11134         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11135         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11136 
11137         // The jump block hasn't been inserted yet; insert it here.
11138         MachineBasicBlock *JumpMBB = JT->MBB;
11139         CurMF->insert(BBI, JumpMBB);
11140 
11141         auto JumpProb = I->Prob;
11142         auto FallthroughProb = UnhandledProbs;
11143 
11144         // If the default statement is a target of the jump table, we evenly
11145         // distribute the default probability to successors of CurMBB. Also
11146         // update the probability on the edge from JumpMBB to Fallthrough.
11147         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11148                                               SE = JumpMBB->succ_end();
11149              SI != SE; ++SI) {
11150           if (*SI == DefaultMBB) {
11151             JumpProb += DefaultProb / 2;
11152             FallthroughProb -= DefaultProb / 2;
11153             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11154             JumpMBB->normalizeSuccProbs();
11155             break;
11156           }
11157         }
11158 
11159         if (FallthroughUnreachable)
11160           JTH->FallthroughUnreachable = true;
11161 
11162         if (!JTH->FallthroughUnreachable)
11163           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11164         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11165         CurMBB->normalizeSuccProbs();
11166 
11167         // The jump table header will be inserted in our current block, do the
11168         // range check, and fall through to our fallthrough block.
11169         JTH->HeaderBB = CurMBB;
11170         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11171 
11172         // If we're in the right place, emit the jump table header right now.
11173         if (CurMBB == SwitchMBB) {
11174           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11175           JTH->Emitted = true;
11176         }
11177         break;
11178       }
11179       case CC_BitTests: {
11180         // FIXME: Optimize away range check based on pivot comparisons.
11181         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11182 
11183         // The bit test blocks haven't been inserted yet; insert them here.
11184         for (BitTestCase &BTC : BTB->Cases)
11185           CurMF->insert(BBI, BTC.ThisBB);
11186 
11187         // Fill in fields of the BitTestBlock.
11188         BTB->Parent = CurMBB;
11189         BTB->Default = Fallthrough;
11190 
11191         BTB->DefaultProb = UnhandledProbs;
11192         // If the cases in bit test don't form a contiguous range, we evenly
11193         // distribute the probability on the edge to Fallthrough to two
11194         // successors of CurMBB.
11195         if (!BTB->ContiguousRange) {
11196           BTB->Prob += DefaultProb / 2;
11197           BTB->DefaultProb -= DefaultProb / 2;
11198         }
11199 
11200         if (FallthroughUnreachable)
11201           BTB->FallthroughUnreachable = true;
11202 
11203         // If we're in the right place, emit the bit test header right now.
11204         if (CurMBB == SwitchMBB) {
11205           visitBitTestHeader(*BTB, SwitchMBB);
11206           BTB->Emitted = true;
11207         }
11208         break;
11209       }
11210       case CC_Range: {
11211         const Value *RHS, *LHS, *MHS;
11212         ISD::CondCode CC;
11213         if (I->Low == I->High) {
11214           // Check Cond == I->Low.
11215           CC = ISD::SETEQ;
11216           LHS = Cond;
11217           RHS=I->Low;
11218           MHS = nullptr;
11219         } else {
11220           // Check I->Low <= Cond <= I->High.
11221           CC = ISD::SETLE;
11222           LHS = I->Low;
11223           MHS = Cond;
11224           RHS = I->High;
11225         }
11226 
11227         // If Fallthrough is unreachable, fold away the comparison.
11228         if (FallthroughUnreachable)
11229           CC = ISD::SETTRUE;
11230 
11231         // The false probability is the sum of all unhandled cases.
11232         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11233                      getCurSDLoc(), I->Prob, UnhandledProbs);
11234 
11235         if (CurMBB == SwitchMBB)
11236           visitSwitchCase(CB, SwitchMBB);
11237         else
11238           SL->SwitchCases.push_back(CB);
11239 
11240         break;
11241       }
11242     }
11243     CurMBB = Fallthrough;
11244   }
11245 }
11246 
11247 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11248                                               CaseClusterIt First,
11249                                               CaseClusterIt Last) {
11250   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11251     if (X.Prob != CC.Prob)
11252       return X.Prob > CC.Prob;
11253 
11254     // Ties are broken by comparing the case value.
11255     return X.Low->getValue().slt(CC.Low->getValue());
11256   });
11257 }
11258 
11259 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11260                                         const SwitchWorkListItem &W,
11261                                         Value *Cond,
11262                                         MachineBasicBlock *SwitchMBB) {
11263   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11264          "Clusters not sorted?");
11265 
11266   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11267 
11268   // Balance the tree based on branch probabilities to create a near-optimal (in
11269   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11270   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11271   CaseClusterIt LastLeft = W.FirstCluster;
11272   CaseClusterIt FirstRight = W.LastCluster;
11273   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11274   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11275 
11276   // Move LastLeft and FirstRight towards each other from opposite directions to
11277   // find a partitioning of the clusters which balances the probability on both
11278   // sides. If LeftProb and RightProb are equal, alternate which side is
11279   // taken to ensure 0-probability nodes are distributed evenly.
11280   unsigned I = 0;
11281   while (LastLeft + 1 < FirstRight) {
11282     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11283       LeftProb += (++LastLeft)->Prob;
11284     else
11285       RightProb += (--FirstRight)->Prob;
11286     I++;
11287   }
11288 
11289   while (true) {
11290     // Our binary search tree differs from a typical BST in that ours can have up
11291     // to three values in each leaf. The pivot selection above doesn't take that
11292     // into account, which means the tree might require more nodes and be less
11293     // efficient. We compensate for this here.
11294 
11295     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11296     unsigned NumRight = W.LastCluster - FirstRight + 1;
11297 
11298     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11299       // If one side has less than 3 clusters, and the other has more than 3,
11300       // consider taking a cluster from the other side.
11301 
11302       if (NumLeft < NumRight) {
11303         // Consider moving the first cluster on the right to the left side.
11304         CaseCluster &CC = *FirstRight;
11305         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11306         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11307         if (LeftSideRank <= RightSideRank) {
11308           // Moving the cluster to the left does not demote it.
11309           ++LastLeft;
11310           ++FirstRight;
11311           continue;
11312         }
11313       } else {
11314         assert(NumRight < NumLeft);
11315         // Consider moving the last element on the left to the right side.
11316         CaseCluster &CC = *LastLeft;
11317         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11318         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11319         if (RightSideRank <= LeftSideRank) {
11320           // Moving the cluster to the right does not demot it.
11321           --LastLeft;
11322           --FirstRight;
11323           continue;
11324         }
11325       }
11326     }
11327     break;
11328   }
11329 
11330   assert(LastLeft + 1 == FirstRight);
11331   assert(LastLeft >= W.FirstCluster);
11332   assert(FirstRight <= W.LastCluster);
11333 
11334   // Use the first element on the right as pivot since we will make less-than
11335   // comparisons against it.
11336   CaseClusterIt PivotCluster = FirstRight;
11337   assert(PivotCluster > W.FirstCluster);
11338   assert(PivotCluster <= W.LastCluster);
11339 
11340   CaseClusterIt FirstLeft = W.FirstCluster;
11341   CaseClusterIt LastRight = W.LastCluster;
11342 
11343   const ConstantInt *Pivot = PivotCluster->Low;
11344 
11345   // New blocks will be inserted immediately after the current one.
11346   MachineFunction::iterator BBI(W.MBB);
11347   ++BBI;
11348 
11349   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11350   // we can branch to its destination directly if it's squeezed exactly in
11351   // between the known lower bound and Pivot - 1.
11352   MachineBasicBlock *LeftMBB;
11353   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11354       FirstLeft->Low == W.GE &&
11355       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11356     LeftMBB = FirstLeft->MBB;
11357   } else {
11358     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11359     FuncInfo.MF->insert(BBI, LeftMBB);
11360     WorkList.push_back(
11361         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11362     // Put Cond in a virtual register to make it available from the new blocks.
11363     ExportFromCurrentBlock(Cond);
11364   }
11365 
11366   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11367   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11368   // directly if RHS.High equals the current upper bound.
11369   MachineBasicBlock *RightMBB;
11370   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11371       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11372     RightMBB = FirstRight->MBB;
11373   } else {
11374     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11375     FuncInfo.MF->insert(BBI, RightMBB);
11376     WorkList.push_back(
11377         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11378     // Put Cond in a virtual register to make it available from the new blocks.
11379     ExportFromCurrentBlock(Cond);
11380   }
11381 
11382   // Create the CaseBlock record that will be used to lower the branch.
11383   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11384                getCurSDLoc(), LeftProb, RightProb);
11385 
11386   if (W.MBB == SwitchMBB)
11387     visitSwitchCase(CB, SwitchMBB);
11388   else
11389     SL->SwitchCases.push_back(CB);
11390 }
11391 
11392 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11393 // from the swith statement.
11394 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11395                                             BranchProbability PeeledCaseProb) {
11396   if (PeeledCaseProb == BranchProbability::getOne())
11397     return BranchProbability::getZero();
11398   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11399 
11400   uint32_t Numerator = CaseProb.getNumerator();
11401   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11402   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11403 }
11404 
11405 // Try to peel the top probability case if it exceeds the threshold.
11406 // Return current MachineBasicBlock for the switch statement if the peeling
11407 // does not occur.
11408 // If the peeling is performed, return the newly created MachineBasicBlock
11409 // for the peeled switch statement. Also update Clusters to remove the peeled
11410 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11411 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11412     const SwitchInst &SI, CaseClusterVector &Clusters,
11413     BranchProbability &PeeledCaseProb) {
11414   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11415   // Don't perform if there is only one cluster or optimizing for size.
11416   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11417       TM.getOptLevel() == CodeGenOpt::None ||
11418       SwitchMBB->getParent()->getFunction().hasMinSize())
11419     return SwitchMBB;
11420 
11421   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11422   unsigned PeeledCaseIndex = 0;
11423   bool SwitchPeeled = false;
11424   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11425     CaseCluster &CC = Clusters[Index];
11426     if (CC.Prob < TopCaseProb)
11427       continue;
11428     TopCaseProb = CC.Prob;
11429     PeeledCaseIndex = Index;
11430     SwitchPeeled = true;
11431   }
11432   if (!SwitchPeeled)
11433     return SwitchMBB;
11434 
11435   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11436                     << TopCaseProb << "\n");
11437 
11438   // Record the MBB for the peeled switch statement.
11439   MachineFunction::iterator BBI(SwitchMBB);
11440   ++BBI;
11441   MachineBasicBlock *PeeledSwitchMBB =
11442       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11443   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11444 
11445   ExportFromCurrentBlock(SI.getCondition());
11446   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11447   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11448                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11449   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11450 
11451   Clusters.erase(PeeledCaseIt);
11452   for (CaseCluster &CC : Clusters) {
11453     LLVM_DEBUG(
11454         dbgs() << "Scale the probablity for one cluster, before scaling: "
11455                << CC.Prob << "\n");
11456     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11457     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11458   }
11459   PeeledCaseProb = TopCaseProb;
11460   return PeeledSwitchMBB;
11461 }
11462 
11463 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11464   // Extract cases from the switch.
11465   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11466   CaseClusterVector Clusters;
11467   Clusters.reserve(SI.getNumCases());
11468   for (auto I : SI.cases()) {
11469     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11470     const ConstantInt *CaseVal = I.getCaseValue();
11471     BranchProbability Prob =
11472         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11473             : BranchProbability(1, SI.getNumCases() + 1);
11474     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11475   }
11476 
11477   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11478 
11479   // Cluster adjacent cases with the same destination. We do this at all
11480   // optimization levels because it's cheap to do and will make codegen faster
11481   // if there are many clusters.
11482   sortAndRangeify(Clusters);
11483 
11484   // The branch probablity of the peeled case.
11485   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11486   MachineBasicBlock *PeeledSwitchMBB =
11487       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11488 
11489   // If there is only the default destination, jump there directly.
11490   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11491   if (Clusters.empty()) {
11492     assert(PeeledSwitchMBB == SwitchMBB);
11493     SwitchMBB->addSuccessor(DefaultMBB);
11494     if (DefaultMBB != NextBlock(SwitchMBB)) {
11495       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11496                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11497     }
11498     return;
11499   }
11500 
11501   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11502   SL->findBitTestClusters(Clusters, &SI);
11503 
11504   LLVM_DEBUG({
11505     dbgs() << "Case clusters: ";
11506     for (const CaseCluster &C : Clusters) {
11507       if (C.Kind == CC_JumpTable)
11508         dbgs() << "JT:";
11509       if (C.Kind == CC_BitTests)
11510         dbgs() << "BT:";
11511 
11512       C.Low->getValue().print(dbgs(), true);
11513       if (C.Low != C.High) {
11514         dbgs() << '-';
11515         C.High->getValue().print(dbgs(), true);
11516       }
11517       dbgs() << ' ';
11518     }
11519     dbgs() << '\n';
11520   });
11521 
11522   assert(!Clusters.empty());
11523   SwitchWorkList WorkList;
11524   CaseClusterIt First = Clusters.begin();
11525   CaseClusterIt Last = Clusters.end() - 1;
11526   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11527   // Scale the branchprobability for DefaultMBB if the peel occurs and
11528   // DefaultMBB is not replaced.
11529   if (PeeledCaseProb != BranchProbability::getZero() &&
11530       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11531     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11532   WorkList.push_back(
11533       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11534 
11535   while (!WorkList.empty()) {
11536     SwitchWorkListItem W = WorkList.pop_back_val();
11537     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11538 
11539     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11540         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11541       // For optimized builds, lower large range as a balanced binary tree.
11542       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11543       continue;
11544     }
11545 
11546     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11547   }
11548 }
11549 
11550 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11551   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11552   auto DL = getCurSDLoc();
11553   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11554   setValue(&I, DAG.getStepVector(DL, ResultVT));
11555 }
11556 
11557 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11558   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11559   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11560 
11561   SDLoc DL = getCurSDLoc();
11562   SDValue V = getValue(I.getOperand(0));
11563   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11564 
11565   if (VT.isScalableVector()) {
11566     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11567     return;
11568   }
11569 
11570   // Use VECTOR_SHUFFLE for the fixed-length vector
11571   // to maintain existing behavior.
11572   SmallVector<int, 8> Mask;
11573   unsigned NumElts = VT.getVectorMinNumElements();
11574   for (unsigned i = 0; i != NumElts; ++i)
11575     Mask.push_back(NumElts - 1 - i);
11576 
11577   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11578 }
11579 
11580 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
11581   auto DL = getCurSDLoc();
11582   SDValue InVec = getValue(I.getOperand(0));
11583   EVT OutVT =
11584       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
11585 
11586   unsigned OutNumElts = OutVT.getVectorMinNumElements();
11587 
11588   // ISD Node needs the input vectors split into two equal parts
11589   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11590                            DAG.getVectorIdxConstant(0, DL));
11591   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11592                            DAG.getVectorIdxConstant(OutNumElts, DL));
11593 
11594   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11595   // legalisation and combines.
11596   if (OutVT.isFixedLengthVector()) {
11597     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11598                                         createStrideMask(0, 2, OutNumElts));
11599     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11600                                        createStrideMask(1, 2, OutNumElts));
11601     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
11602     setValue(&I, Res);
11603     return;
11604   }
11605 
11606   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
11607                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
11608   setValue(&I, Res);
11609 }
11610 
11611 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
11612   auto DL = getCurSDLoc();
11613   EVT InVT = getValue(I.getOperand(0)).getValueType();
11614   SDValue InVec0 = getValue(I.getOperand(0));
11615   SDValue InVec1 = getValue(I.getOperand(1));
11616   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11617   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11618 
11619   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11620   // legalisation and combines.
11621   if (OutVT.isFixedLengthVector()) {
11622     unsigned NumElts = InVT.getVectorMinNumElements();
11623     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
11624     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
11625                                       createInterleaveMask(NumElts, 2)));
11626     return;
11627   }
11628 
11629   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
11630                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
11631   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
11632                     Res.getValue(1));
11633   setValue(&I, Res);
11634 }
11635 
11636 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11637   SmallVector<EVT, 4> ValueVTs;
11638   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11639                   ValueVTs);
11640   unsigned NumValues = ValueVTs.size();
11641   if (NumValues == 0) return;
11642 
11643   SmallVector<SDValue, 4> Values(NumValues);
11644   SDValue Op = getValue(I.getOperand(0));
11645 
11646   for (unsigned i = 0; i != NumValues; ++i)
11647     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11648                             SDValue(Op.getNode(), Op.getResNo() + i));
11649 
11650   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11651                            DAG.getVTList(ValueVTs), Values));
11652 }
11653 
11654 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11655   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11656   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11657 
11658   SDLoc DL = getCurSDLoc();
11659   SDValue V1 = getValue(I.getOperand(0));
11660   SDValue V2 = getValue(I.getOperand(1));
11661   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11662 
11663   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11664   if (VT.isScalableVector()) {
11665     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11666     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11667                              DAG.getConstant(Imm, DL, IdxVT)));
11668     return;
11669   }
11670 
11671   unsigned NumElts = VT.getVectorNumElements();
11672 
11673   uint64_t Idx = (NumElts + Imm) % NumElts;
11674 
11675   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11676   SmallVector<int, 8> Mask;
11677   for (unsigned i = 0; i < NumElts; ++i)
11678     Mask.push_back(Idx + i);
11679   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11680 }
11681 
11682 // Consider the following MIR after SelectionDAG, which produces output in
11683 // phyregs in the first case or virtregs in the second case.
11684 //
11685 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
11686 // %5:gr32 = COPY $ebx
11687 // %6:gr32 = COPY $edx
11688 // %1:gr32 = COPY %6:gr32
11689 // %0:gr32 = COPY %5:gr32
11690 //
11691 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
11692 // %1:gr32 = COPY %6:gr32
11693 // %0:gr32 = COPY %5:gr32
11694 //
11695 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
11696 // Given %1, we'd like to return $edx in the first case and %6 in the second.
11697 //
11698 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
11699 // to a single virtreg (such as %0). The remaining outputs monotonically
11700 // increase in virtreg number from there. If a callbr has no outputs, then it
11701 // should not have a corresponding callbr landingpad; in fact, the callbr
11702 // landingpad would not even be able to refer to such a callbr.
11703 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
11704   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
11705   // There is definitely at least one copy.
11706   assert(MI->getOpcode() == TargetOpcode::COPY &&
11707          "start of copy chain MUST be COPY");
11708   Reg = MI->getOperand(1).getReg();
11709   MI = MRI.def_begin(Reg)->getParent();
11710   // There may be an optional second copy.
11711   if (MI->getOpcode() == TargetOpcode::COPY) {
11712     assert(Reg.isVirtual() && "expected COPY of virtual register");
11713     Reg = MI->getOperand(1).getReg();
11714     assert(Reg.isPhysical() && "expected COPY of physical register");
11715     MI = MRI.def_begin(Reg)->getParent();
11716   }
11717   // The start of the chain must be an INLINEASM_BR.
11718   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
11719          "end of copy chain MUST be INLINEASM_BR");
11720   return Reg;
11721 }
11722 
11723 // We must do this walk rather than the simpler
11724 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
11725 // otherwise we will end up with copies of virtregs only valid along direct
11726 // edges.
11727 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
11728   SmallVector<EVT, 8> ResultVTs;
11729   SmallVector<SDValue, 8> ResultValues;
11730   const auto *CBR =
11731       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
11732 
11733   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11734   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
11735   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11736 
11737   unsigned InitialDef = FuncInfo.ValueMap[CBR];
11738   SDValue Chain = DAG.getRoot();
11739 
11740   // Re-parse the asm constraints string.
11741   TargetLowering::AsmOperandInfoVector TargetConstraints =
11742       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
11743   for (auto &T : TargetConstraints) {
11744     SDISelAsmOperandInfo OpInfo(T);
11745     if (OpInfo.Type != InlineAsm::isOutput)
11746       continue;
11747 
11748     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
11749     // individual constraint.
11750     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
11751 
11752     switch (OpInfo.ConstraintType) {
11753     case TargetLowering::C_Register:
11754     case TargetLowering::C_RegisterClass: {
11755       // Fill in OpInfo.AssignedRegs.Regs.
11756       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
11757 
11758       // getRegistersForValue may produce 1 to many registers based on whether
11759       // the OpInfo.ConstraintVT is legal on the target or not.
11760       for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) {
11761         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
11762         if (Register::isPhysicalRegister(OriginalDef))
11763           FuncInfo.MBB->addLiveIn(OriginalDef);
11764         // Update the assigned registers to use the original defs.
11765         OpInfo.AssignedRegs.Regs[i] = OriginalDef;
11766       }
11767 
11768       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
11769           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
11770       ResultValues.push_back(V);
11771       ResultVTs.push_back(OpInfo.ConstraintVT);
11772       break;
11773     }
11774     case TargetLowering::C_Other: {
11775       SDValue Flag;
11776       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
11777                                                   OpInfo, DAG);
11778       ++InitialDef;
11779       ResultValues.push_back(V);
11780       ResultVTs.push_back(OpInfo.ConstraintVT);
11781       break;
11782     }
11783     default:
11784       break;
11785     }
11786   }
11787   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11788                           DAG.getVTList(ResultVTs), ResultValues);
11789   setValue(&I, V);
11790 }
11791