xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision aba1bea6731036ba05abfd5f595941e9306ac058)
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, 0);
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, 0);
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.getPtrExtOrTrunc(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, 0);
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, 0);
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, 0);
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   // If the expression refers to the entry value of an Argument, use the
5808   // corresponding livein physical register. As per the Verifier, this is only
5809   // allowed for swiftasync Arguments.
5810   if (Op->isReg() && Expr->isEntryValue()) {
5811     assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
5812     auto OpReg = Op->getReg();
5813     for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
5814       if (OpReg == VirtReg || OpReg == PhysReg) {
5815         SDDbgValue *SDV = DAG.getVRegDbgValue(
5816             Variable, Expr, PhysReg,
5817             Kind != FuncArgumentDbgValueKind::Value /*is indirect*/, DL,
5818             SDNodeOrder);
5819         DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
5820         return true;
5821       }
5822     LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
5823                          "couldn't find a physical register\n");
5824     return true;
5825   }
5826 
5827   assert(Variable->isValidLocationForIntrinsic(DL) &&
5828          "Expected inlined-at fields to agree");
5829   MachineInstr *NewMI = nullptr;
5830 
5831   if (Op->isReg())
5832     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5833   else
5834     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5835                     Variable, Expr);
5836 
5837   // Otherwise, use ArgDbgValues.
5838   FuncInfo.ArgDbgValues.push_back(NewMI);
5839   return true;
5840 }
5841 
5842 /// Return the appropriate SDDbgValue based on N.
5843 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5844                                              DILocalVariable *Variable,
5845                                              DIExpression *Expr,
5846                                              const DebugLoc &dl,
5847                                              unsigned DbgSDNodeOrder) {
5848   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5849     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5850     // stack slot locations.
5851     //
5852     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5853     // debug values here after optimization:
5854     //
5855     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5856     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5857     //
5858     // Both describe the direct values of their associated variables.
5859     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5860                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5861   }
5862   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5863                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5864 }
5865 
5866 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5867   switch (Intrinsic) {
5868   case Intrinsic::smul_fix:
5869     return ISD::SMULFIX;
5870   case Intrinsic::umul_fix:
5871     return ISD::UMULFIX;
5872   case Intrinsic::smul_fix_sat:
5873     return ISD::SMULFIXSAT;
5874   case Intrinsic::umul_fix_sat:
5875     return ISD::UMULFIXSAT;
5876   case Intrinsic::sdiv_fix:
5877     return ISD::SDIVFIX;
5878   case Intrinsic::udiv_fix:
5879     return ISD::UDIVFIX;
5880   case Intrinsic::sdiv_fix_sat:
5881     return ISD::SDIVFIXSAT;
5882   case Intrinsic::udiv_fix_sat:
5883     return ISD::UDIVFIXSAT;
5884   default:
5885     llvm_unreachable("Unhandled fixed point intrinsic");
5886   }
5887 }
5888 
5889 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5890                                            const char *FunctionName) {
5891   assert(FunctionName && "FunctionName must not be nullptr");
5892   SDValue Callee = DAG.getExternalSymbol(
5893       FunctionName,
5894       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5895   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5896 }
5897 
5898 /// Given a @llvm.call.preallocated.setup, return the corresponding
5899 /// preallocated call.
5900 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5901   assert(cast<CallBase>(PreallocatedSetup)
5902                  ->getCalledFunction()
5903                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5904          "expected call_preallocated_setup Value");
5905   for (const auto *U : PreallocatedSetup->users()) {
5906     auto *UseCall = cast<CallBase>(U);
5907     const Function *Fn = UseCall->getCalledFunction();
5908     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5909       return UseCall;
5910     }
5911   }
5912   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5913 }
5914 
5915 /// Lower the call to the specified intrinsic function.
5916 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5917                                              unsigned Intrinsic) {
5918   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5919   SDLoc sdl = getCurSDLoc();
5920   DebugLoc dl = getCurDebugLoc();
5921   SDValue Res;
5922 
5923   SDNodeFlags Flags;
5924   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5925     Flags.copyFMF(*FPOp);
5926 
5927   switch (Intrinsic) {
5928   default:
5929     // By default, turn this into a target intrinsic node.
5930     visitTargetIntrinsic(I, Intrinsic);
5931     return;
5932   case Intrinsic::vscale: {
5933     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5934     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5935     return;
5936   }
5937   case Intrinsic::vastart:  visitVAStart(I); return;
5938   case Intrinsic::vaend:    visitVAEnd(I); return;
5939   case Intrinsic::vacopy:   visitVACopy(I); return;
5940   case Intrinsic::returnaddress:
5941     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5942                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5943                              getValue(I.getArgOperand(0))));
5944     return;
5945   case Intrinsic::addressofreturnaddress:
5946     setValue(&I,
5947              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5948                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5949     return;
5950   case Intrinsic::sponentry:
5951     setValue(&I,
5952              DAG.getNode(ISD::SPONENTRY, sdl,
5953                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5954     return;
5955   case Intrinsic::frameaddress:
5956     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5957                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5958                              getValue(I.getArgOperand(0))));
5959     return;
5960   case Intrinsic::read_volatile_register:
5961   case Intrinsic::read_register: {
5962     Value *Reg = I.getArgOperand(0);
5963     SDValue Chain = getRoot();
5964     SDValue RegName =
5965         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5966     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5967     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5968       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5969     setValue(&I, Res);
5970     DAG.setRoot(Res.getValue(1));
5971     return;
5972   }
5973   case Intrinsic::write_register: {
5974     Value *Reg = I.getArgOperand(0);
5975     Value *RegValue = I.getArgOperand(1);
5976     SDValue Chain = getRoot();
5977     SDValue RegName =
5978         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5979     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5980                             RegName, getValue(RegValue)));
5981     return;
5982   }
5983   case Intrinsic::memcpy: {
5984     const auto &MCI = cast<MemCpyInst>(I);
5985     SDValue Op1 = getValue(I.getArgOperand(0));
5986     SDValue Op2 = getValue(I.getArgOperand(1));
5987     SDValue Op3 = getValue(I.getArgOperand(2));
5988     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5989     Align DstAlign = MCI.getDestAlign().valueOrOne();
5990     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5991     Align Alignment = std::min(DstAlign, SrcAlign);
5992     bool isVol = MCI.isVolatile();
5993     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5994     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5995     // node.
5996     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5997     SDValue MC = DAG.getMemcpy(
5998         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5999         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
6000         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6001     updateDAGForMaybeTailCall(MC);
6002     return;
6003   }
6004   case Intrinsic::memcpy_inline: {
6005     const auto &MCI = cast<MemCpyInlineInst>(I);
6006     SDValue Dst = getValue(I.getArgOperand(0));
6007     SDValue Src = getValue(I.getArgOperand(1));
6008     SDValue Size = getValue(I.getArgOperand(2));
6009     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6010     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6011     Align DstAlign = MCI.getDestAlign().valueOrOne();
6012     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6013     Align Alignment = std::min(DstAlign, SrcAlign);
6014     bool isVol = MCI.isVolatile();
6015     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6016     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6017     // node.
6018     SDValue MC = DAG.getMemcpy(
6019         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6020         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6021         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6022     updateDAGForMaybeTailCall(MC);
6023     return;
6024   }
6025   case Intrinsic::memset: {
6026     const auto &MSI = cast<MemSetInst>(I);
6027     SDValue Op1 = getValue(I.getArgOperand(0));
6028     SDValue Op2 = getValue(I.getArgOperand(1));
6029     SDValue Op3 = getValue(I.getArgOperand(2));
6030     // @llvm.memset defines 0 and 1 to both mean no alignment.
6031     Align Alignment = MSI.getDestAlign().valueOrOne();
6032     bool isVol = MSI.isVolatile();
6033     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6034     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6035     SDValue MS = DAG.getMemset(
6036         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6037         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6038     updateDAGForMaybeTailCall(MS);
6039     return;
6040   }
6041   case Intrinsic::memset_inline: {
6042     const auto &MSII = cast<MemSetInlineInst>(I);
6043     SDValue Dst = getValue(I.getArgOperand(0));
6044     SDValue Value = getValue(I.getArgOperand(1));
6045     SDValue Size = getValue(I.getArgOperand(2));
6046     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6047     // @llvm.memset defines 0 and 1 to both mean no alignment.
6048     Align DstAlign = MSII.getDestAlign().valueOrOne();
6049     bool isVol = MSII.isVolatile();
6050     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6051     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6052     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6053                                /* AlwaysInline */ true, isTC,
6054                                MachinePointerInfo(I.getArgOperand(0)),
6055                                I.getAAMetadata());
6056     updateDAGForMaybeTailCall(MC);
6057     return;
6058   }
6059   case Intrinsic::memmove: {
6060     const auto &MMI = cast<MemMoveInst>(I);
6061     SDValue Op1 = getValue(I.getArgOperand(0));
6062     SDValue Op2 = getValue(I.getArgOperand(1));
6063     SDValue Op3 = getValue(I.getArgOperand(2));
6064     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6065     Align DstAlign = MMI.getDestAlign().valueOrOne();
6066     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6067     Align Alignment = std::min(DstAlign, SrcAlign);
6068     bool isVol = MMI.isVolatile();
6069     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6070     // FIXME: Support passing different dest/src alignments to the memmove DAG
6071     // node.
6072     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6073     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6074                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6075                                 MachinePointerInfo(I.getArgOperand(1)),
6076                                 I.getAAMetadata(), AA);
6077     updateDAGForMaybeTailCall(MM);
6078     return;
6079   }
6080   case Intrinsic::memcpy_element_unordered_atomic: {
6081     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6082     SDValue Dst = getValue(MI.getRawDest());
6083     SDValue Src = getValue(MI.getRawSource());
6084     SDValue Length = getValue(MI.getLength());
6085 
6086     Type *LengthTy = MI.getLength()->getType();
6087     unsigned ElemSz = MI.getElementSizeInBytes();
6088     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6089     SDValue MC =
6090         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6091                             isTC, MachinePointerInfo(MI.getRawDest()),
6092                             MachinePointerInfo(MI.getRawSource()));
6093     updateDAGForMaybeTailCall(MC);
6094     return;
6095   }
6096   case Intrinsic::memmove_element_unordered_atomic: {
6097     auto &MI = cast<AtomicMemMoveInst>(I);
6098     SDValue Dst = getValue(MI.getRawDest());
6099     SDValue Src = getValue(MI.getRawSource());
6100     SDValue Length = getValue(MI.getLength());
6101 
6102     Type *LengthTy = MI.getLength()->getType();
6103     unsigned ElemSz = MI.getElementSizeInBytes();
6104     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6105     SDValue MC =
6106         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6107                              isTC, MachinePointerInfo(MI.getRawDest()),
6108                              MachinePointerInfo(MI.getRawSource()));
6109     updateDAGForMaybeTailCall(MC);
6110     return;
6111   }
6112   case Intrinsic::memset_element_unordered_atomic: {
6113     auto &MI = cast<AtomicMemSetInst>(I);
6114     SDValue Dst = getValue(MI.getRawDest());
6115     SDValue Val = getValue(MI.getValue());
6116     SDValue Length = getValue(MI.getLength());
6117 
6118     Type *LengthTy = MI.getLength()->getType();
6119     unsigned ElemSz = MI.getElementSizeInBytes();
6120     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6121     SDValue MC =
6122         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6123                             isTC, MachinePointerInfo(MI.getRawDest()));
6124     updateDAGForMaybeTailCall(MC);
6125     return;
6126   }
6127   case Intrinsic::call_preallocated_setup: {
6128     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6129     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6130     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6131                               getRoot(), SrcValue);
6132     setValue(&I, Res);
6133     DAG.setRoot(Res);
6134     return;
6135   }
6136   case Intrinsic::call_preallocated_arg: {
6137     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6138     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6139     SDValue Ops[3];
6140     Ops[0] = getRoot();
6141     Ops[1] = SrcValue;
6142     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6143                                    MVT::i32); // arg index
6144     SDValue Res = DAG.getNode(
6145         ISD::PREALLOCATED_ARG, sdl,
6146         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6147     setValue(&I, Res);
6148     DAG.setRoot(Res.getValue(1));
6149     return;
6150   }
6151   case Intrinsic::dbg_declare: {
6152     const auto &DI = cast<DbgDeclareInst>(I);
6153     // Debug intrinsics are handled separately in assignment tracking mode.
6154     // Some intrinsics are handled right after Argument lowering.
6155     if (AssignmentTrackingEnabled ||
6156         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6157       return;
6158     // Assume dbg.declare can not currently use DIArgList, i.e.
6159     // it is non-variadic.
6160     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6161     DILocalVariable *Variable = DI.getVariable();
6162     DIExpression *Expression = DI.getExpression();
6163     dropDanglingDebugInfo(Variable, Expression);
6164     assert(Variable && "Missing variable");
6165     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6166                       << "\n");
6167     // Check if address has undef value.
6168     const Value *Address = DI.getVariableLocationOp(0);
6169     if (!Address || isa<UndefValue>(Address) ||
6170         (Address->use_empty() && !isa<Argument>(Address))) {
6171       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6172                         << " (bad/undef/unused-arg address)\n");
6173       return;
6174     }
6175 
6176     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6177 
6178     SDValue &N = NodeMap[Address];
6179     if (!N.getNode() && isa<Argument>(Address))
6180       // Check unused arguments map.
6181       N = UnusedArgNodeMap[Address];
6182     SDDbgValue *SDV;
6183     if (N.getNode()) {
6184       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6185         Address = BCI->getOperand(0);
6186       // Parameters are handled specially.
6187       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6188       if (isParameter && FINode) {
6189         // Byval parameter. We have a frame index at this point.
6190         SDV =
6191             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6192                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6193       } else if (isa<Argument>(Address)) {
6194         // Address is an argument, so try to emit its dbg value using
6195         // virtual register info from the FuncInfo.ValueMap.
6196         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6197                                  FuncArgumentDbgValueKind::Declare, N);
6198         return;
6199       } else {
6200         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6201                               true, dl, SDNodeOrder);
6202       }
6203       DAG.AddDbgValue(SDV, isParameter);
6204     } else {
6205       // If Address is an argument then try to emit its dbg value using
6206       // virtual register info from the FuncInfo.ValueMap.
6207       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6208                                     FuncArgumentDbgValueKind::Declare, N)) {
6209         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6210                           << " (could not emit func-arg dbg_value)\n");
6211       }
6212     }
6213     return;
6214   }
6215   case Intrinsic::dbg_label: {
6216     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6217     DILabel *Label = DI.getLabel();
6218     assert(Label && "Missing label");
6219 
6220     SDDbgLabel *SDV;
6221     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6222     DAG.AddDbgLabel(SDV);
6223     return;
6224   }
6225   case Intrinsic::dbg_assign: {
6226     // Debug intrinsics are handled seperately in assignment tracking mode.
6227     if (AssignmentTrackingEnabled)
6228       return;
6229     // If assignment tracking hasn't been enabled then fall through and treat
6230     // the dbg.assign as a dbg.value.
6231     [[fallthrough]];
6232   }
6233   case Intrinsic::dbg_value: {
6234     // Debug intrinsics are handled seperately in assignment tracking mode.
6235     if (AssignmentTrackingEnabled)
6236       return;
6237     const DbgValueInst &DI = cast<DbgValueInst>(I);
6238     assert(DI.getVariable() && "Missing variable");
6239 
6240     DILocalVariable *Variable = DI.getVariable();
6241     DIExpression *Expression = DI.getExpression();
6242     dropDanglingDebugInfo(Variable, Expression);
6243 
6244     if (DI.isKillLocation()) {
6245       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6246       return;
6247     }
6248 
6249     SmallVector<Value *, 4> Values(DI.getValues());
6250     if (Values.empty())
6251       return;
6252 
6253     bool IsVariadic = DI.hasArgList();
6254     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6255                           SDNodeOrder, IsVariadic))
6256       addDanglingDebugInfo(&DI, SDNodeOrder);
6257     return;
6258   }
6259 
6260   case Intrinsic::eh_typeid_for: {
6261     // Find the type id for the given typeinfo.
6262     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6263     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6264     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6265     setValue(&I, Res);
6266     return;
6267   }
6268 
6269   case Intrinsic::eh_return_i32:
6270   case Intrinsic::eh_return_i64:
6271     DAG.getMachineFunction().setCallsEHReturn(true);
6272     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6273                             MVT::Other,
6274                             getControlRoot(),
6275                             getValue(I.getArgOperand(0)),
6276                             getValue(I.getArgOperand(1))));
6277     return;
6278   case Intrinsic::eh_unwind_init:
6279     DAG.getMachineFunction().setCallsUnwindInit(true);
6280     return;
6281   case Intrinsic::eh_dwarf_cfa:
6282     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6283                              TLI.getPointerTy(DAG.getDataLayout()),
6284                              getValue(I.getArgOperand(0))));
6285     return;
6286   case Intrinsic::eh_sjlj_callsite: {
6287     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6288     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6289     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6290 
6291     MMI.setCurrentCallSite(CI->getZExtValue());
6292     return;
6293   }
6294   case Intrinsic::eh_sjlj_functioncontext: {
6295     // Get and store the index of the function context.
6296     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6297     AllocaInst *FnCtx =
6298       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6299     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6300     MFI.setFunctionContextIndex(FI);
6301     return;
6302   }
6303   case Intrinsic::eh_sjlj_setjmp: {
6304     SDValue Ops[2];
6305     Ops[0] = getRoot();
6306     Ops[1] = getValue(I.getArgOperand(0));
6307     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6308                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6309     setValue(&I, Op.getValue(0));
6310     DAG.setRoot(Op.getValue(1));
6311     return;
6312   }
6313   case Intrinsic::eh_sjlj_longjmp:
6314     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6315                             getRoot(), getValue(I.getArgOperand(0))));
6316     return;
6317   case Intrinsic::eh_sjlj_setup_dispatch:
6318     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6319                             getRoot()));
6320     return;
6321   case Intrinsic::masked_gather:
6322     visitMaskedGather(I);
6323     return;
6324   case Intrinsic::masked_load:
6325     visitMaskedLoad(I);
6326     return;
6327   case Intrinsic::masked_scatter:
6328     visitMaskedScatter(I);
6329     return;
6330   case Intrinsic::masked_store:
6331     visitMaskedStore(I);
6332     return;
6333   case Intrinsic::masked_expandload:
6334     visitMaskedLoad(I, true /* IsExpanding */);
6335     return;
6336   case Intrinsic::masked_compressstore:
6337     visitMaskedStore(I, true /* IsCompressing */);
6338     return;
6339   case Intrinsic::powi:
6340     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6341                             getValue(I.getArgOperand(1)), DAG));
6342     return;
6343   case Intrinsic::log:
6344     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6345     return;
6346   case Intrinsic::log2:
6347     setValue(&I,
6348              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6349     return;
6350   case Intrinsic::log10:
6351     setValue(&I,
6352              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6353     return;
6354   case Intrinsic::exp:
6355     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6356     return;
6357   case Intrinsic::exp2:
6358     setValue(&I,
6359              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6360     return;
6361   case Intrinsic::pow:
6362     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6363                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6364     return;
6365   case Intrinsic::sqrt:
6366   case Intrinsic::fabs:
6367   case Intrinsic::sin:
6368   case Intrinsic::cos:
6369   case Intrinsic::floor:
6370   case Intrinsic::ceil:
6371   case Intrinsic::trunc:
6372   case Intrinsic::rint:
6373   case Intrinsic::nearbyint:
6374   case Intrinsic::round:
6375   case Intrinsic::roundeven:
6376   case Intrinsic::canonicalize: {
6377     unsigned Opcode;
6378     switch (Intrinsic) {
6379     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6380     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6381     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6382     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6383     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6384     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6385     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6386     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6387     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6388     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6389     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6390     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6391     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6392     }
6393 
6394     setValue(&I, DAG.getNode(Opcode, sdl,
6395                              getValue(I.getArgOperand(0)).getValueType(),
6396                              getValue(I.getArgOperand(0)), Flags));
6397     return;
6398   }
6399   case Intrinsic::lround:
6400   case Intrinsic::llround:
6401   case Intrinsic::lrint:
6402   case Intrinsic::llrint: {
6403     unsigned Opcode;
6404     switch (Intrinsic) {
6405     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6406     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6407     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6408     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6409     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6410     }
6411 
6412     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6413     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6414                              getValue(I.getArgOperand(0))));
6415     return;
6416   }
6417   case Intrinsic::minnum:
6418     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6419                              getValue(I.getArgOperand(0)).getValueType(),
6420                              getValue(I.getArgOperand(0)),
6421                              getValue(I.getArgOperand(1)), Flags));
6422     return;
6423   case Intrinsic::maxnum:
6424     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6425                              getValue(I.getArgOperand(0)).getValueType(),
6426                              getValue(I.getArgOperand(0)),
6427                              getValue(I.getArgOperand(1)), Flags));
6428     return;
6429   case Intrinsic::minimum:
6430     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6431                              getValue(I.getArgOperand(0)).getValueType(),
6432                              getValue(I.getArgOperand(0)),
6433                              getValue(I.getArgOperand(1)), Flags));
6434     return;
6435   case Intrinsic::maximum:
6436     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6437                              getValue(I.getArgOperand(0)).getValueType(),
6438                              getValue(I.getArgOperand(0)),
6439                              getValue(I.getArgOperand(1)), Flags));
6440     return;
6441   case Intrinsic::copysign:
6442     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6443                              getValue(I.getArgOperand(0)).getValueType(),
6444                              getValue(I.getArgOperand(0)),
6445                              getValue(I.getArgOperand(1)), Flags));
6446     return;
6447   case Intrinsic::arithmetic_fence: {
6448     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6449                              getValue(I.getArgOperand(0)).getValueType(),
6450                              getValue(I.getArgOperand(0)), Flags));
6451     return;
6452   }
6453   case Intrinsic::fma:
6454     setValue(&I, DAG.getNode(
6455                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6456                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6457                      getValue(I.getArgOperand(2)), Flags));
6458     return;
6459 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6460   case Intrinsic::INTRINSIC:
6461 #include "llvm/IR/ConstrainedOps.def"
6462     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6463     return;
6464 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6465 #include "llvm/IR/VPIntrinsics.def"
6466     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6467     return;
6468   case Intrinsic::fptrunc_round: {
6469     // Get the last argument, the metadata and convert it to an integer in the
6470     // call
6471     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6472     std::optional<RoundingMode> RoundMode =
6473         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6474 
6475     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6476 
6477     // Propagate fast-math-flags from IR to node(s).
6478     SDNodeFlags Flags;
6479     Flags.copyFMF(*cast<FPMathOperator>(&I));
6480     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6481 
6482     SDValue Result;
6483     Result = DAG.getNode(
6484         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6485         DAG.getTargetConstant((int)*RoundMode, sdl,
6486                               TLI.getPointerTy(DAG.getDataLayout())));
6487     setValue(&I, Result);
6488 
6489     return;
6490   }
6491   case Intrinsic::fmuladd: {
6492     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6493     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6494         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6495       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6496                                getValue(I.getArgOperand(0)).getValueType(),
6497                                getValue(I.getArgOperand(0)),
6498                                getValue(I.getArgOperand(1)),
6499                                getValue(I.getArgOperand(2)), Flags));
6500     } else {
6501       // TODO: Intrinsic calls should have fast-math-flags.
6502       SDValue Mul = DAG.getNode(
6503           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6504           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6505       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6506                                 getValue(I.getArgOperand(0)).getValueType(),
6507                                 Mul, getValue(I.getArgOperand(2)), Flags);
6508       setValue(&I, Add);
6509     }
6510     return;
6511   }
6512   case Intrinsic::convert_to_fp16:
6513     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6514                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6515                                          getValue(I.getArgOperand(0)),
6516                                          DAG.getTargetConstant(0, sdl,
6517                                                                MVT::i32))));
6518     return;
6519   case Intrinsic::convert_from_fp16:
6520     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6521                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6522                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6523                                          getValue(I.getArgOperand(0)))));
6524     return;
6525   case Intrinsic::fptosi_sat: {
6526     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6527     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6528                              getValue(I.getArgOperand(0)),
6529                              DAG.getValueType(VT.getScalarType())));
6530     return;
6531   }
6532   case Intrinsic::fptoui_sat: {
6533     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6534     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6535                              getValue(I.getArgOperand(0)),
6536                              DAG.getValueType(VT.getScalarType())));
6537     return;
6538   }
6539   case Intrinsic::set_rounding:
6540     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6541                       {getRoot(), getValue(I.getArgOperand(0))});
6542     setValue(&I, Res);
6543     DAG.setRoot(Res.getValue(0));
6544     return;
6545   case Intrinsic::is_fpclass: {
6546     const DataLayout DLayout = DAG.getDataLayout();
6547     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6548     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6549     FPClassTest Test = static_cast<FPClassTest>(
6550         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6551     MachineFunction &MF = DAG.getMachineFunction();
6552     const Function &F = MF.getFunction();
6553     SDValue Op = getValue(I.getArgOperand(0));
6554     SDNodeFlags Flags;
6555     Flags.setNoFPExcept(
6556         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6557     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6558     // expansion can use illegal types. Making expansion early allows
6559     // legalizing these types prior to selection.
6560     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6561       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6562       setValue(&I, Result);
6563       return;
6564     }
6565 
6566     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6567     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6568     setValue(&I, V);
6569     return;
6570   }
6571   case Intrinsic::pcmarker: {
6572     SDValue Tmp = getValue(I.getArgOperand(0));
6573     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6574     return;
6575   }
6576   case Intrinsic::readcyclecounter: {
6577     SDValue Op = getRoot();
6578     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6579                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6580     setValue(&I, Res);
6581     DAG.setRoot(Res.getValue(1));
6582     return;
6583   }
6584   case Intrinsic::bitreverse:
6585     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6586                              getValue(I.getArgOperand(0)).getValueType(),
6587                              getValue(I.getArgOperand(0))));
6588     return;
6589   case Intrinsic::bswap:
6590     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6591                              getValue(I.getArgOperand(0)).getValueType(),
6592                              getValue(I.getArgOperand(0))));
6593     return;
6594   case Intrinsic::cttz: {
6595     SDValue Arg = getValue(I.getArgOperand(0));
6596     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6597     EVT Ty = Arg.getValueType();
6598     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6599                              sdl, Ty, Arg));
6600     return;
6601   }
6602   case Intrinsic::ctlz: {
6603     SDValue Arg = getValue(I.getArgOperand(0));
6604     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6605     EVT Ty = Arg.getValueType();
6606     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6607                              sdl, Ty, Arg));
6608     return;
6609   }
6610   case Intrinsic::ctpop: {
6611     SDValue Arg = getValue(I.getArgOperand(0));
6612     EVT Ty = Arg.getValueType();
6613     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6614     return;
6615   }
6616   case Intrinsic::fshl:
6617   case Intrinsic::fshr: {
6618     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6619     SDValue X = getValue(I.getArgOperand(0));
6620     SDValue Y = getValue(I.getArgOperand(1));
6621     SDValue Z = getValue(I.getArgOperand(2));
6622     EVT VT = X.getValueType();
6623 
6624     if (X == Y) {
6625       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6626       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6627     } else {
6628       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6629       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6630     }
6631     return;
6632   }
6633   case Intrinsic::sadd_sat: {
6634     SDValue Op1 = getValue(I.getArgOperand(0));
6635     SDValue Op2 = getValue(I.getArgOperand(1));
6636     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6637     return;
6638   }
6639   case Intrinsic::uadd_sat: {
6640     SDValue Op1 = getValue(I.getArgOperand(0));
6641     SDValue Op2 = getValue(I.getArgOperand(1));
6642     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6643     return;
6644   }
6645   case Intrinsic::ssub_sat: {
6646     SDValue Op1 = getValue(I.getArgOperand(0));
6647     SDValue Op2 = getValue(I.getArgOperand(1));
6648     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6649     return;
6650   }
6651   case Intrinsic::usub_sat: {
6652     SDValue Op1 = getValue(I.getArgOperand(0));
6653     SDValue Op2 = getValue(I.getArgOperand(1));
6654     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6655     return;
6656   }
6657   case Intrinsic::sshl_sat: {
6658     SDValue Op1 = getValue(I.getArgOperand(0));
6659     SDValue Op2 = getValue(I.getArgOperand(1));
6660     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6661     return;
6662   }
6663   case Intrinsic::ushl_sat: {
6664     SDValue Op1 = getValue(I.getArgOperand(0));
6665     SDValue Op2 = getValue(I.getArgOperand(1));
6666     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6667     return;
6668   }
6669   case Intrinsic::smul_fix:
6670   case Intrinsic::umul_fix:
6671   case Intrinsic::smul_fix_sat:
6672   case Intrinsic::umul_fix_sat: {
6673     SDValue Op1 = getValue(I.getArgOperand(0));
6674     SDValue Op2 = getValue(I.getArgOperand(1));
6675     SDValue Op3 = getValue(I.getArgOperand(2));
6676     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6677                              Op1.getValueType(), Op1, Op2, Op3));
6678     return;
6679   }
6680   case Intrinsic::sdiv_fix:
6681   case Intrinsic::udiv_fix:
6682   case Intrinsic::sdiv_fix_sat:
6683   case Intrinsic::udiv_fix_sat: {
6684     SDValue Op1 = getValue(I.getArgOperand(0));
6685     SDValue Op2 = getValue(I.getArgOperand(1));
6686     SDValue Op3 = getValue(I.getArgOperand(2));
6687     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6688                               Op1, Op2, Op3, DAG, TLI));
6689     return;
6690   }
6691   case Intrinsic::smax: {
6692     SDValue Op1 = getValue(I.getArgOperand(0));
6693     SDValue Op2 = getValue(I.getArgOperand(1));
6694     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6695     return;
6696   }
6697   case Intrinsic::smin: {
6698     SDValue Op1 = getValue(I.getArgOperand(0));
6699     SDValue Op2 = getValue(I.getArgOperand(1));
6700     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6701     return;
6702   }
6703   case Intrinsic::umax: {
6704     SDValue Op1 = getValue(I.getArgOperand(0));
6705     SDValue Op2 = getValue(I.getArgOperand(1));
6706     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6707     return;
6708   }
6709   case Intrinsic::umin: {
6710     SDValue Op1 = getValue(I.getArgOperand(0));
6711     SDValue Op2 = getValue(I.getArgOperand(1));
6712     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6713     return;
6714   }
6715   case Intrinsic::abs: {
6716     // TODO: Preserve "int min is poison" arg in SDAG?
6717     SDValue Op1 = getValue(I.getArgOperand(0));
6718     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6719     return;
6720   }
6721   case Intrinsic::stacksave: {
6722     SDValue Op = getRoot();
6723     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6724     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6725     setValue(&I, Res);
6726     DAG.setRoot(Res.getValue(1));
6727     return;
6728   }
6729   case Intrinsic::stackrestore:
6730     Res = getValue(I.getArgOperand(0));
6731     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6732     return;
6733   case Intrinsic::get_dynamic_area_offset: {
6734     SDValue Op = getRoot();
6735     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6736     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6737     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6738     // target.
6739     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6740       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6741                          " intrinsic!");
6742     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6743                       Op);
6744     DAG.setRoot(Op);
6745     setValue(&I, Res);
6746     return;
6747   }
6748   case Intrinsic::stackguard: {
6749     MachineFunction &MF = DAG.getMachineFunction();
6750     const Module &M = *MF.getFunction().getParent();
6751     SDValue Chain = getRoot();
6752     if (TLI.useLoadStackGuardNode()) {
6753       Res = getLoadStackGuard(DAG, sdl, Chain);
6754     } else {
6755       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6756       const Value *Global = TLI.getSDagStackGuard(M);
6757       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6758       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6759                         MachinePointerInfo(Global, 0), Align,
6760                         MachineMemOperand::MOVolatile);
6761     }
6762     if (TLI.useStackGuardXorFP())
6763       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6764     DAG.setRoot(Chain);
6765     setValue(&I, Res);
6766     return;
6767   }
6768   case Intrinsic::stackprotector: {
6769     // Emit code into the DAG to store the stack guard onto the stack.
6770     MachineFunction &MF = DAG.getMachineFunction();
6771     MachineFrameInfo &MFI = MF.getFrameInfo();
6772     SDValue Src, Chain = getRoot();
6773 
6774     if (TLI.useLoadStackGuardNode())
6775       Src = getLoadStackGuard(DAG, sdl, Chain);
6776     else
6777       Src = getValue(I.getArgOperand(0));   // The guard's value.
6778 
6779     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6780 
6781     int FI = FuncInfo.StaticAllocaMap[Slot];
6782     MFI.setStackProtectorIndex(FI);
6783     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6784 
6785     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6786 
6787     // Store the stack protector onto the stack.
6788     Res = DAG.getStore(
6789         Chain, sdl, Src, FIN,
6790         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6791         MaybeAlign(), MachineMemOperand::MOVolatile);
6792     setValue(&I, Res);
6793     DAG.setRoot(Res);
6794     return;
6795   }
6796   case Intrinsic::objectsize:
6797     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6798 
6799   case Intrinsic::is_constant:
6800     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6801 
6802   case Intrinsic::annotation:
6803   case Intrinsic::ptr_annotation:
6804   case Intrinsic::launder_invariant_group:
6805   case Intrinsic::strip_invariant_group:
6806     // Drop the intrinsic, but forward the value
6807     setValue(&I, getValue(I.getOperand(0)));
6808     return;
6809 
6810   case Intrinsic::assume:
6811   case Intrinsic::experimental_noalias_scope_decl:
6812   case Intrinsic::var_annotation:
6813   case Intrinsic::sideeffect:
6814     // Discard annotate attributes, noalias scope declarations, assumptions, and
6815     // artificial side-effects.
6816     return;
6817 
6818   case Intrinsic::codeview_annotation: {
6819     // Emit a label associated with this metadata.
6820     MachineFunction &MF = DAG.getMachineFunction();
6821     MCSymbol *Label =
6822         MF.getMMI().getContext().createTempSymbol("annotation", true);
6823     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6824     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6825     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6826     DAG.setRoot(Res);
6827     return;
6828   }
6829 
6830   case Intrinsic::init_trampoline: {
6831     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6832 
6833     SDValue Ops[6];
6834     Ops[0] = getRoot();
6835     Ops[1] = getValue(I.getArgOperand(0));
6836     Ops[2] = getValue(I.getArgOperand(1));
6837     Ops[3] = getValue(I.getArgOperand(2));
6838     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6839     Ops[5] = DAG.getSrcValue(F);
6840 
6841     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6842 
6843     DAG.setRoot(Res);
6844     return;
6845   }
6846   case Intrinsic::adjust_trampoline:
6847     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6848                              TLI.getPointerTy(DAG.getDataLayout()),
6849                              getValue(I.getArgOperand(0))));
6850     return;
6851   case Intrinsic::gcroot: {
6852     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6853            "only valid in functions with gc specified, enforced by Verifier");
6854     assert(GFI && "implied by previous");
6855     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6856     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6857 
6858     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6859     GFI->addStackRoot(FI->getIndex(), TypeMap);
6860     return;
6861   }
6862   case Intrinsic::gcread:
6863   case Intrinsic::gcwrite:
6864     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6865   case Intrinsic::get_rounding:
6866     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
6867     setValue(&I, Res);
6868     DAG.setRoot(Res.getValue(1));
6869     return;
6870 
6871   case Intrinsic::expect:
6872     // Just replace __builtin_expect(exp, c) with EXP.
6873     setValue(&I, getValue(I.getArgOperand(0)));
6874     return;
6875 
6876   case Intrinsic::ubsantrap:
6877   case Intrinsic::debugtrap:
6878   case Intrinsic::trap: {
6879     StringRef TrapFuncName =
6880         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6881     if (TrapFuncName.empty()) {
6882       switch (Intrinsic) {
6883       case Intrinsic::trap:
6884         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6885         break;
6886       case Intrinsic::debugtrap:
6887         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6888         break;
6889       case Intrinsic::ubsantrap:
6890         DAG.setRoot(DAG.getNode(
6891             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6892             DAG.getTargetConstant(
6893                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6894                 MVT::i32)));
6895         break;
6896       default: llvm_unreachable("unknown trap intrinsic");
6897       }
6898       return;
6899     }
6900     TargetLowering::ArgListTy Args;
6901     if (Intrinsic == Intrinsic::ubsantrap) {
6902       Args.push_back(TargetLoweringBase::ArgListEntry());
6903       Args[0].Val = I.getArgOperand(0);
6904       Args[0].Node = getValue(Args[0].Val);
6905       Args[0].Ty = Args[0].Val->getType();
6906     }
6907 
6908     TargetLowering::CallLoweringInfo CLI(DAG);
6909     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6910         CallingConv::C, I.getType(),
6911         DAG.getExternalSymbol(TrapFuncName.data(),
6912                               TLI.getPointerTy(DAG.getDataLayout())),
6913         std::move(Args));
6914 
6915     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6916     DAG.setRoot(Result.second);
6917     return;
6918   }
6919 
6920   case Intrinsic::uadd_with_overflow:
6921   case Intrinsic::sadd_with_overflow:
6922   case Intrinsic::usub_with_overflow:
6923   case Intrinsic::ssub_with_overflow:
6924   case Intrinsic::umul_with_overflow:
6925   case Intrinsic::smul_with_overflow: {
6926     ISD::NodeType Op;
6927     switch (Intrinsic) {
6928     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6929     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6930     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6931     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6932     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6933     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6934     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6935     }
6936     SDValue Op1 = getValue(I.getArgOperand(0));
6937     SDValue Op2 = getValue(I.getArgOperand(1));
6938 
6939     EVT ResultVT = Op1.getValueType();
6940     EVT OverflowVT = MVT::i1;
6941     if (ResultVT.isVector())
6942       OverflowVT = EVT::getVectorVT(
6943           *Context, OverflowVT, ResultVT.getVectorElementCount());
6944 
6945     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6946     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6947     return;
6948   }
6949   case Intrinsic::prefetch: {
6950     SDValue Ops[5];
6951     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6952     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6953     Ops[0] = DAG.getRoot();
6954     Ops[1] = getValue(I.getArgOperand(0));
6955     Ops[2] = getValue(I.getArgOperand(1));
6956     Ops[3] = getValue(I.getArgOperand(2));
6957     Ops[4] = getValue(I.getArgOperand(3));
6958     SDValue Result = DAG.getMemIntrinsicNode(
6959         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6960         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6961         /* align */ std::nullopt, Flags);
6962 
6963     // Chain the prefetch in parallell with any pending loads, to stay out of
6964     // the way of later optimizations.
6965     PendingLoads.push_back(Result);
6966     Result = getRoot();
6967     DAG.setRoot(Result);
6968     return;
6969   }
6970   case Intrinsic::lifetime_start:
6971   case Intrinsic::lifetime_end: {
6972     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6973     // Stack coloring is not enabled in O0, discard region information.
6974     if (TM.getOptLevel() == CodeGenOpt::None)
6975       return;
6976 
6977     const int64_t ObjectSize =
6978         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6979     Value *const ObjectPtr = I.getArgOperand(1);
6980     SmallVector<const Value *, 4> Allocas;
6981     getUnderlyingObjects(ObjectPtr, Allocas);
6982 
6983     for (const Value *Alloca : Allocas) {
6984       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6985 
6986       // Could not find an Alloca.
6987       if (!LifetimeObject)
6988         continue;
6989 
6990       // First check that the Alloca is static, otherwise it won't have a
6991       // valid frame index.
6992       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6993       if (SI == FuncInfo.StaticAllocaMap.end())
6994         return;
6995 
6996       const int FrameIndex = SI->second;
6997       int64_t Offset;
6998       if (GetPointerBaseWithConstantOffset(
6999               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7000         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7001       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7002                                 Offset);
7003       DAG.setRoot(Res);
7004     }
7005     return;
7006   }
7007   case Intrinsic::pseudoprobe: {
7008     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7009     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7010     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7011     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7012     DAG.setRoot(Res);
7013     return;
7014   }
7015   case Intrinsic::invariant_start:
7016     // Discard region information.
7017     setValue(&I,
7018              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7019     return;
7020   case Intrinsic::invariant_end:
7021     // Discard region information.
7022     return;
7023   case Intrinsic::clear_cache:
7024     /// FunctionName may be null.
7025     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
7026       lowerCallToExternalSymbol(I, FunctionName);
7027     return;
7028   case Intrinsic::donothing:
7029   case Intrinsic::seh_try_begin:
7030   case Intrinsic::seh_scope_begin:
7031   case Intrinsic::seh_try_end:
7032   case Intrinsic::seh_scope_end:
7033     // ignore
7034     return;
7035   case Intrinsic::experimental_stackmap:
7036     visitStackmap(I);
7037     return;
7038   case Intrinsic::experimental_patchpoint_void:
7039   case Intrinsic::experimental_patchpoint_i64:
7040     visitPatchpoint(I);
7041     return;
7042   case Intrinsic::experimental_gc_statepoint:
7043     LowerStatepoint(cast<GCStatepointInst>(I));
7044     return;
7045   case Intrinsic::experimental_gc_result:
7046     visitGCResult(cast<GCResultInst>(I));
7047     return;
7048   case Intrinsic::experimental_gc_relocate:
7049     visitGCRelocate(cast<GCRelocateInst>(I));
7050     return;
7051   case Intrinsic::instrprof_cover:
7052     llvm_unreachable("instrprof failed to lower a cover");
7053   case Intrinsic::instrprof_increment:
7054     llvm_unreachable("instrprof failed to lower an increment");
7055   case Intrinsic::instrprof_timestamp:
7056     llvm_unreachable("instrprof failed to lower a timestamp");
7057   case Intrinsic::instrprof_value_profile:
7058     llvm_unreachable("instrprof failed to lower a value profiling call");
7059   case Intrinsic::localescape: {
7060     MachineFunction &MF = DAG.getMachineFunction();
7061     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7062 
7063     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7064     // is the same on all targets.
7065     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7066       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7067       if (isa<ConstantPointerNull>(Arg))
7068         continue; // Skip null pointers. They represent a hole in index space.
7069       AllocaInst *Slot = cast<AllocaInst>(Arg);
7070       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7071              "can only escape static allocas");
7072       int FI = FuncInfo.StaticAllocaMap[Slot];
7073       MCSymbol *FrameAllocSym =
7074           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7075               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7076       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7077               TII->get(TargetOpcode::LOCAL_ESCAPE))
7078           .addSym(FrameAllocSym)
7079           .addFrameIndex(FI);
7080     }
7081 
7082     return;
7083   }
7084 
7085   case Intrinsic::localrecover: {
7086     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7087     MachineFunction &MF = DAG.getMachineFunction();
7088 
7089     // Get the symbol that defines the frame offset.
7090     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7091     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7092     unsigned IdxVal =
7093         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7094     MCSymbol *FrameAllocSym =
7095         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7096             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7097 
7098     Value *FP = I.getArgOperand(1);
7099     SDValue FPVal = getValue(FP);
7100     EVT PtrVT = FPVal.getValueType();
7101 
7102     // Create a MCSymbol for the label to avoid any target lowering
7103     // that would make this PC relative.
7104     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7105     SDValue OffsetVal =
7106         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7107 
7108     // Add the offset to the FP.
7109     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7110     setValue(&I, Add);
7111 
7112     return;
7113   }
7114 
7115   case Intrinsic::eh_exceptionpointer:
7116   case Intrinsic::eh_exceptioncode: {
7117     // Get the exception pointer vreg, copy from it, and resize it to fit.
7118     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7119     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7120     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7121     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7122     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7123     if (Intrinsic == Intrinsic::eh_exceptioncode)
7124       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7125     setValue(&I, N);
7126     return;
7127   }
7128   case Intrinsic::xray_customevent: {
7129     // Here we want to make sure that the intrinsic behaves as if it has a
7130     // specific calling convention, and only for x86_64.
7131     // FIXME: Support other platforms later.
7132     const auto &Triple = DAG.getTarget().getTargetTriple();
7133     if (Triple.getArch() != Triple::x86_64)
7134       return;
7135 
7136     SmallVector<SDValue, 8> Ops;
7137 
7138     // We want to say that we always want the arguments in registers.
7139     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7140     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7141     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7142     SDValue Chain = getRoot();
7143     Ops.push_back(LogEntryVal);
7144     Ops.push_back(StrSizeVal);
7145     Ops.push_back(Chain);
7146 
7147     // We need to enforce the calling convention for the callsite, so that
7148     // argument ordering is enforced correctly, and that register allocation can
7149     // see that some registers may be assumed clobbered and have to preserve
7150     // them across calls to the intrinsic.
7151     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7152                                            sdl, NodeTys, Ops);
7153     SDValue patchableNode = SDValue(MN, 0);
7154     DAG.setRoot(patchableNode);
7155     setValue(&I, patchableNode);
7156     return;
7157   }
7158   case Intrinsic::xray_typedevent: {
7159     // Here we want to make sure that the intrinsic behaves as if it has a
7160     // specific calling convention, and only for x86_64.
7161     // FIXME: Support other platforms later.
7162     const auto &Triple = DAG.getTarget().getTargetTriple();
7163     if (Triple.getArch() != Triple::x86_64)
7164       return;
7165 
7166     SmallVector<SDValue, 8> Ops;
7167 
7168     // We want to say that we always want the arguments in registers.
7169     // It's unclear to me how manipulating the selection DAG here forces callers
7170     // to provide arguments in registers instead of on the stack.
7171     SDValue LogTypeId = getValue(I.getArgOperand(0));
7172     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7173     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7174     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7175     SDValue Chain = getRoot();
7176     Ops.push_back(LogTypeId);
7177     Ops.push_back(LogEntryVal);
7178     Ops.push_back(StrSizeVal);
7179     Ops.push_back(Chain);
7180 
7181     // We need to enforce the calling convention for the callsite, so that
7182     // argument ordering is enforced correctly, and that register allocation can
7183     // see that some registers may be assumed clobbered and have to preserve
7184     // them across calls to the intrinsic.
7185     MachineSDNode *MN = DAG.getMachineNode(
7186         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7187     SDValue patchableNode = SDValue(MN, 0);
7188     DAG.setRoot(patchableNode);
7189     setValue(&I, patchableNode);
7190     return;
7191   }
7192   case Intrinsic::experimental_deoptimize:
7193     LowerDeoptimizeCall(&I);
7194     return;
7195   case Intrinsic::experimental_stepvector:
7196     visitStepVector(I);
7197     return;
7198   case Intrinsic::vector_reduce_fadd:
7199   case Intrinsic::vector_reduce_fmul:
7200   case Intrinsic::vector_reduce_add:
7201   case Intrinsic::vector_reduce_mul:
7202   case Intrinsic::vector_reduce_and:
7203   case Intrinsic::vector_reduce_or:
7204   case Intrinsic::vector_reduce_xor:
7205   case Intrinsic::vector_reduce_smax:
7206   case Intrinsic::vector_reduce_smin:
7207   case Intrinsic::vector_reduce_umax:
7208   case Intrinsic::vector_reduce_umin:
7209   case Intrinsic::vector_reduce_fmax:
7210   case Intrinsic::vector_reduce_fmin:
7211     visitVectorReduce(I, Intrinsic);
7212     return;
7213 
7214   case Intrinsic::icall_branch_funnel: {
7215     SmallVector<SDValue, 16> Ops;
7216     Ops.push_back(getValue(I.getArgOperand(0)));
7217 
7218     int64_t Offset;
7219     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7220         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7221     if (!Base)
7222       report_fatal_error(
7223           "llvm.icall.branch.funnel operand must be a GlobalValue");
7224     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7225 
7226     struct BranchFunnelTarget {
7227       int64_t Offset;
7228       SDValue Target;
7229     };
7230     SmallVector<BranchFunnelTarget, 8> Targets;
7231 
7232     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7233       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7234           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7235       if (ElemBase != Base)
7236         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7237                            "to the same GlobalValue");
7238 
7239       SDValue Val = getValue(I.getArgOperand(Op + 1));
7240       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7241       if (!GA)
7242         report_fatal_error(
7243             "llvm.icall.branch.funnel operand must be a GlobalValue");
7244       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7245                                      GA->getGlobal(), sdl, Val.getValueType(),
7246                                      GA->getOffset())});
7247     }
7248     llvm::sort(Targets,
7249                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7250                  return T1.Offset < T2.Offset;
7251                });
7252 
7253     for (auto &T : Targets) {
7254       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7255       Ops.push_back(T.Target);
7256     }
7257 
7258     Ops.push_back(DAG.getRoot()); // Chain
7259     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7260                                  MVT::Other, Ops),
7261               0);
7262     DAG.setRoot(N);
7263     setValue(&I, N);
7264     HasTailCall = true;
7265     return;
7266   }
7267 
7268   case Intrinsic::wasm_landingpad_index:
7269     // Information this intrinsic contained has been transferred to
7270     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7271     // delete it now.
7272     return;
7273 
7274   case Intrinsic::aarch64_settag:
7275   case Intrinsic::aarch64_settag_zero: {
7276     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7277     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7278     SDValue Val = TSI.EmitTargetCodeForSetTag(
7279         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7280         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7281         ZeroMemory);
7282     DAG.setRoot(Val);
7283     setValue(&I, Val);
7284     return;
7285   }
7286   case Intrinsic::ptrmask: {
7287     SDValue Ptr = getValue(I.getOperand(0));
7288     SDValue Const = getValue(I.getOperand(1));
7289 
7290     EVT PtrVT = Ptr.getValueType();
7291     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7292                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7293     return;
7294   }
7295   case Intrinsic::threadlocal_address: {
7296     setValue(&I, getValue(I.getOperand(0)));
7297     return;
7298   }
7299   case Intrinsic::get_active_lane_mask: {
7300     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7301     SDValue Index = getValue(I.getOperand(0));
7302     EVT ElementVT = Index.getValueType();
7303 
7304     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7305       visitTargetIntrinsic(I, Intrinsic);
7306       return;
7307     }
7308 
7309     SDValue TripCount = getValue(I.getOperand(1));
7310     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7311 
7312     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7313     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7314     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7315     SDValue VectorInduction = DAG.getNode(
7316         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7317     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7318                                  VectorTripCount, ISD::CondCode::SETULT);
7319     setValue(&I, SetCC);
7320     return;
7321   }
7322   case Intrinsic::vector_insert: {
7323     SDValue Vec = getValue(I.getOperand(0));
7324     SDValue SubVec = getValue(I.getOperand(1));
7325     SDValue Index = getValue(I.getOperand(2));
7326 
7327     // The intrinsic's index type is i64, but the SDNode requires an index type
7328     // suitable for the target. Convert the index as required.
7329     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7330     if (Index.getValueType() != VectorIdxTy)
7331       Index = DAG.getVectorIdxConstant(
7332           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7333 
7334     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7335     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7336                              Index));
7337     return;
7338   }
7339   case Intrinsic::vector_extract: {
7340     SDValue Vec = getValue(I.getOperand(0));
7341     SDValue Index = getValue(I.getOperand(1));
7342     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7343 
7344     // The intrinsic's index type is i64, but the SDNode requires an index type
7345     // suitable for the target. Convert the index as required.
7346     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7347     if (Index.getValueType() != VectorIdxTy)
7348       Index = DAG.getVectorIdxConstant(
7349           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7350 
7351     setValue(&I,
7352              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7353     return;
7354   }
7355   case Intrinsic::experimental_vector_reverse:
7356     visitVectorReverse(I);
7357     return;
7358   case Intrinsic::experimental_vector_splice:
7359     visitVectorSplice(I);
7360     return;
7361   case Intrinsic::callbr_landingpad:
7362     visitCallBrLandingPad(I);
7363     return;
7364   case Intrinsic::experimental_vector_interleave2:
7365     visitVectorInterleave(I);
7366     return;
7367   case Intrinsic::experimental_vector_deinterleave2:
7368     visitVectorDeinterleave(I);
7369     return;
7370   }
7371 }
7372 
7373 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7374     const ConstrainedFPIntrinsic &FPI) {
7375   SDLoc sdl = getCurSDLoc();
7376 
7377   // We do not need to serialize constrained FP intrinsics against
7378   // each other or against (nonvolatile) loads, so they can be
7379   // chained like loads.
7380   SDValue Chain = DAG.getRoot();
7381   SmallVector<SDValue, 4> Opers;
7382   Opers.push_back(Chain);
7383   if (FPI.isUnaryOp()) {
7384     Opers.push_back(getValue(FPI.getArgOperand(0)));
7385   } else if (FPI.isTernaryOp()) {
7386     Opers.push_back(getValue(FPI.getArgOperand(0)));
7387     Opers.push_back(getValue(FPI.getArgOperand(1)));
7388     Opers.push_back(getValue(FPI.getArgOperand(2)));
7389   } else {
7390     Opers.push_back(getValue(FPI.getArgOperand(0)));
7391     Opers.push_back(getValue(FPI.getArgOperand(1)));
7392   }
7393 
7394   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7395     assert(Result.getNode()->getNumValues() == 2);
7396 
7397     // Push node to the appropriate list so that future instructions can be
7398     // chained up correctly.
7399     SDValue OutChain = Result.getValue(1);
7400     switch (EB) {
7401     case fp::ExceptionBehavior::ebIgnore:
7402       // The only reason why ebIgnore nodes still need to be chained is that
7403       // they might depend on the current rounding mode, and therefore must
7404       // not be moved across instruction that may change that mode.
7405       [[fallthrough]];
7406     case fp::ExceptionBehavior::ebMayTrap:
7407       // These must not be moved across calls or instructions that may change
7408       // floating-point exception masks.
7409       PendingConstrainedFP.push_back(OutChain);
7410       break;
7411     case fp::ExceptionBehavior::ebStrict:
7412       // These must not be moved across calls or instructions that may change
7413       // floating-point exception masks or read floating-point exception flags.
7414       // In addition, they cannot be optimized out even if unused.
7415       PendingConstrainedFPStrict.push_back(OutChain);
7416       break;
7417     }
7418   };
7419 
7420   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7421   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7422   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7423   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7424 
7425   SDNodeFlags Flags;
7426   if (EB == fp::ExceptionBehavior::ebIgnore)
7427     Flags.setNoFPExcept(true);
7428 
7429   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7430     Flags.copyFMF(*FPOp);
7431 
7432   unsigned Opcode;
7433   switch (FPI.getIntrinsicID()) {
7434   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7435 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7436   case Intrinsic::INTRINSIC:                                                   \
7437     Opcode = ISD::STRICT_##DAGN;                                               \
7438     break;
7439 #include "llvm/IR/ConstrainedOps.def"
7440   case Intrinsic::experimental_constrained_fmuladd: {
7441     Opcode = ISD::STRICT_FMA;
7442     // Break fmuladd into fmul and fadd.
7443     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7444         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7445       Opers.pop_back();
7446       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7447       pushOutChain(Mul, EB);
7448       Opcode = ISD::STRICT_FADD;
7449       Opers.clear();
7450       Opers.push_back(Mul.getValue(1));
7451       Opers.push_back(Mul.getValue(0));
7452       Opers.push_back(getValue(FPI.getArgOperand(2)));
7453     }
7454     break;
7455   }
7456   }
7457 
7458   // A few strict DAG nodes carry additional operands that are not
7459   // set up by the default code above.
7460   switch (Opcode) {
7461   default: break;
7462   case ISD::STRICT_FP_ROUND:
7463     Opers.push_back(
7464         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7465     break;
7466   case ISD::STRICT_FSETCC:
7467   case ISD::STRICT_FSETCCS: {
7468     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7469     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7470     if (TM.Options.NoNaNsFPMath)
7471       Condition = getFCmpCodeWithoutNaN(Condition);
7472     Opers.push_back(DAG.getCondCode(Condition));
7473     break;
7474   }
7475   }
7476 
7477   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7478   pushOutChain(Result, EB);
7479 
7480   SDValue FPResult = Result.getValue(0);
7481   setValue(&FPI, FPResult);
7482 }
7483 
7484 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7485   std::optional<unsigned> ResOPC;
7486   switch (VPIntrin.getIntrinsicID()) {
7487   case Intrinsic::vp_ctlz: {
7488     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7489     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
7490     break;
7491   }
7492   case Intrinsic::vp_cttz: {
7493     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7494     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
7495     break;
7496   }
7497 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7498   case Intrinsic::VPID:                                                        \
7499     ResOPC = ISD::VPSD;                                                        \
7500     break;
7501 #include "llvm/IR/VPIntrinsics.def"
7502   }
7503 
7504   if (!ResOPC)
7505     llvm_unreachable(
7506         "Inconsistency: no SDNode available for this VPIntrinsic!");
7507 
7508   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7509       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7510     if (VPIntrin.getFastMathFlags().allowReassoc())
7511       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7512                                                 : ISD::VP_REDUCE_FMUL;
7513   }
7514 
7515   return *ResOPC;
7516 }
7517 
7518 void SelectionDAGBuilder::visitVPLoad(
7519     const VPIntrinsic &VPIntrin, EVT VT,
7520     const SmallVectorImpl<SDValue> &OpValues) {
7521   SDLoc DL = getCurSDLoc();
7522   Value *PtrOperand = VPIntrin.getArgOperand(0);
7523   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7524   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7525   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7526   SDValue LD;
7527   // Do not serialize variable-length loads of constant memory with
7528   // anything.
7529   if (!Alignment)
7530     Alignment = DAG.getEVTAlign(VT);
7531   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7532   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7533   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7534   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7535       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7536       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7537   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7538                      MMO, false /*IsExpanding */);
7539   if (AddToChain)
7540     PendingLoads.push_back(LD.getValue(1));
7541   setValue(&VPIntrin, LD);
7542 }
7543 
7544 void SelectionDAGBuilder::visitVPGather(
7545     const VPIntrinsic &VPIntrin, EVT VT,
7546     const SmallVectorImpl<SDValue> &OpValues) {
7547   SDLoc DL = getCurSDLoc();
7548   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7549   Value *PtrOperand = VPIntrin.getArgOperand(0);
7550   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7551   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7552   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7553   SDValue LD;
7554   if (!Alignment)
7555     Alignment = DAG.getEVTAlign(VT.getScalarType());
7556   unsigned AS =
7557     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7558   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7559      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7560      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7561   SDValue Base, Index, Scale;
7562   ISD::MemIndexType IndexType;
7563   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7564                                     this, VPIntrin.getParent(),
7565                                     VT.getScalarStoreSize());
7566   if (!UniformBase) {
7567     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7568     Index = getValue(PtrOperand);
7569     IndexType = ISD::SIGNED_SCALED;
7570     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7571   }
7572   EVT IdxVT = Index.getValueType();
7573   EVT EltTy = IdxVT.getVectorElementType();
7574   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7575     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7576     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7577   }
7578   LD = DAG.getGatherVP(
7579       DAG.getVTList(VT, MVT::Other), VT, DL,
7580       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7581       IndexType);
7582   PendingLoads.push_back(LD.getValue(1));
7583   setValue(&VPIntrin, LD);
7584 }
7585 
7586 void SelectionDAGBuilder::visitVPStore(
7587     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7588   SDLoc DL = getCurSDLoc();
7589   Value *PtrOperand = VPIntrin.getArgOperand(1);
7590   EVT VT = OpValues[0].getValueType();
7591   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7592   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7593   SDValue ST;
7594   if (!Alignment)
7595     Alignment = DAG.getEVTAlign(VT);
7596   SDValue Ptr = OpValues[1];
7597   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7598   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7599       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7600       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7601   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7602                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7603                       /* IsTruncating */ false, /*IsCompressing*/ false);
7604   DAG.setRoot(ST);
7605   setValue(&VPIntrin, ST);
7606 }
7607 
7608 void SelectionDAGBuilder::visitVPScatter(
7609     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7610   SDLoc DL = getCurSDLoc();
7611   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7612   Value *PtrOperand = VPIntrin.getArgOperand(1);
7613   EVT VT = OpValues[0].getValueType();
7614   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7615   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7616   SDValue ST;
7617   if (!Alignment)
7618     Alignment = DAG.getEVTAlign(VT.getScalarType());
7619   unsigned AS =
7620       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7621   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7622       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7623       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7624   SDValue Base, Index, Scale;
7625   ISD::MemIndexType IndexType;
7626   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7627                                     this, VPIntrin.getParent(),
7628                                     VT.getScalarStoreSize());
7629   if (!UniformBase) {
7630     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7631     Index = getValue(PtrOperand);
7632     IndexType = ISD::SIGNED_SCALED;
7633     Scale =
7634       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7635   }
7636   EVT IdxVT = Index.getValueType();
7637   EVT EltTy = IdxVT.getVectorElementType();
7638   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7639     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7640     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7641   }
7642   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7643                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7644                          OpValues[2], OpValues[3]},
7645                         MMO, IndexType);
7646   DAG.setRoot(ST);
7647   setValue(&VPIntrin, ST);
7648 }
7649 
7650 void SelectionDAGBuilder::visitVPStridedLoad(
7651     const VPIntrinsic &VPIntrin, EVT VT,
7652     const SmallVectorImpl<SDValue> &OpValues) {
7653   SDLoc DL = getCurSDLoc();
7654   Value *PtrOperand = VPIntrin.getArgOperand(0);
7655   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7656   if (!Alignment)
7657     Alignment = DAG.getEVTAlign(VT.getScalarType());
7658   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7659   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7660   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7661   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7662   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7663   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7664       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7665       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7666 
7667   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7668                                     OpValues[2], OpValues[3], MMO,
7669                                     false /*IsExpanding*/);
7670 
7671   if (AddToChain)
7672     PendingLoads.push_back(LD.getValue(1));
7673   setValue(&VPIntrin, LD);
7674 }
7675 
7676 void SelectionDAGBuilder::visitVPStridedStore(
7677     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7678   SDLoc DL = getCurSDLoc();
7679   Value *PtrOperand = VPIntrin.getArgOperand(1);
7680   EVT VT = OpValues[0].getValueType();
7681   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7682   if (!Alignment)
7683     Alignment = DAG.getEVTAlign(VT.getScalarType());
7684   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7685   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7686       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7687       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7688 
7689   SDValue ST = DAG.getStridedStoreVP(
7690       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7691       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7692       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7693       /*IsCompressing*/ false);
7694 
7695   DAG.setRoot(ST);
7696   setValue(&VPIntrin, ST);
7697 }
7698 
7699 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
7700   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7701   SDLoc DL = getCurSDLoc();
7702 
7703   ISD::CondCode Condition;
7704   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
7705   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
7706   if (IsFP) {
7707     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
7708     // flags, but calls that don't return floating-point types can't be
7709     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
7710     Condition = getFCmpCondCode(CondCode);
7711     if (TM.Options.NoNaNsFPMath)
7712       Condition = getFCmpCodeWithoutNaN(Condition);
7713   } else {
7714     Condition = getICmpCondCode(CondCode);
7715   }
7716 
7717   SDValue Op1 = getValue(VPIntrin.getOperand(0));
7718   SDValue Op2 = getValue(VPIntrin.getOperand(1));
7719   // #2 is the condition code
7720   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
7721   SDValue EVL = getValue(VPIntrin.getOperand(4));
7722   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7723   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7724          "Unexpected target EVL type");
7725   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
7726 
7727   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7728                                                         VPIntrin.getType());
7729   setValue(&VPIntrin,
7730            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
7731 }
7732 
7733 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7734     const VPIntrinsic &VPIntrin) {
7735   SDLoc DL = getCurSDLoc();
7736   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7737 
7738   auto IID = VPIntrin.getIntrinsicID();
7739 
7740   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
7741     return visitVPCmp(*CmpI);
7742 
7743   SmallVector<EVT, 4> ValueVTs;
7744   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7745   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7746   SDVTList VTs = DAG.getVTList(ValueVTs);
7747 
7748   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
7749 
7750   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7751   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7752          "Unexpected target EVL type");
7753 
7754   // Request operands.
7755   SmallVector<SDValue, 7> OpValues;
7756   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7757     auto Op = getValue(VPIntrin.getArgOperand(I));
7758     if (I == EVLParamPos)
7759       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7760     OpValues.push_back(Op);
7761   }
7762 
7763   switch (Opcode) {
7764   default: {
7765     SDNodeFlags SDFlags;
7766     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7767       SDFlags.copyFMF(*FPMO);
7768     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
7769     setValue(&VPIntrin, Result);
7770     break;
7771   }
7772   case ISD::VP_LOAD:
7773     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
7774     break;
7775   case ISD::VP_GATHER:
7776     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
7777     break;
7778   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7779     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7780     break;
7781   case ISD::VP_STORE:
7782     visitVPStore(VPIntrin, OpValues);
7783     break;
7784   case ISD::VP_SCATTER:
7785     visitVPScatter(VPIntrin, OpValues);
7786     break;
7787   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7788     visitVPStridedStore(VPIntrin, OpValues);
7789     break;
7790   case ISD::VP_FMULADD: {
7791     assert(OpValues.size() == 5 && "Unexpected number of operands");
7792     SDNodeFlags SDFlags;
7793     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7794       SDFlags.copyFMF(*FPMO);
7795     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7796         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
7797       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
7798     } else {
7799       SDValue Mul = DAG.getNode(
7800           ISD::VP_FMUL, DL, VTs,
7801           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
7802       SDValue Add =
7803           DAG.getNode(ISD::VP_FADD, DL, VTs,
7804                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
7805       setValue(&VPIntrin, Add);
7806     }
7807     break;
7808   }
7809   case ISD::VP_INTTOPTR: {
7810     SDValue N = OpValues[0];
7811     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
7812     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
7813     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7814                                OpValues[2]);
7815     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7816                              OpValues[2]);
7817     setValue(&VPIntrin, N);
7818     break;
7819   }
7820   case ISD::VP_PTRTOINT: {
7821     SDValue N = OpValues[0];
7822     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7823                                                           VPIntrin.getType());
7824     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
7825                                        VPIntrin.getOperand(0)->getType());
7826     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7827                                OpValues[2]);
7828     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7829                              OpValues[2]);
7830     setValue(&VPIntrin, N);
7831     break;
7832   }
7833   case ISD::VP_ABS:
7834   case ISD::VP_CTLZ:
7835   case ISD::VP_CTLZ_ZERO_UNDEF:
7836   case ISD::VP_CTTZ:
7837   case ISD::VP_CTTZ_ZERO_UNDEF: {
7838     SDValue Result =
7839         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
7840     setValue(&VPIntrin, Result);
7841     break;
7842   }
7843   }
7844 }
7845 
7846 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7847                                           const BasicBlock *EHPadBB,
7848                                           MCSymbol *&BeginLabel) {
7849   MachineFunction &MF = DAG.getMachineFunction();
7850   MachineModuleInfo &MMI = MF.getMMI();
7851 
7852   // Insert a label before the invoke call to mark the try range.  This can be
7853   // used to detect deletion of the invoke via the MachineModuleInfo.
7854   BeginLabel = MMI.getContext().createTempSymbol();
7855 
7856   // For SjLj, keep track of which landing pads go with which invokes
7857   // so as to maintain the ordering of pads in the LSDA.
7858   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7859   if (CallSiteIndex) {
7860     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7861     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7862 
7863     // Now that the call site is handled, stop tracking it.
7864     MMI.setCurrentCallSite(0);
7865   }
7866 
7867   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7868 }
7869 
7870 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7871                                         const BasicBlock *EHPadBB,
7872                                         MCSymbol *BeginLabel) {
7873   assert(BeginLabel && "BeginLabel should've been set");
7874 
7875   MachineFunction &MF = DAG.getMachineFunction();
7876   MachineModuleInfo &MMI = MF.getMMI();
7877 
7878   // Insert a label at the end of the invoke call to mark the try range.  This
7879   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7880   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7881   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7882 
7883   // Inform MachineModuleInfo of range.
7884   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7885   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7886   // actually use outlined funclets and their LSDA info style.
7887   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7888     assert(II && "II should've been set");
7889     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7890     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7891   } else if (!isScopedEHPersonality(Pers)) {
7892     assert(EHPadBB);
7893     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7894   }
7895 
7896   return Chain;
7897 }
7898 
7899 std::pair<SDValue, SDValue>
7900 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7901                                     const BasicBlock *EHPadBB) {
7902   MCSymbol *BeginLabel = nullptr;
7903 
7904   if (EHPadBB) {
7905     // Both PendingLoads and PendingExports must be flushed here;
7906     // this call might not return.
7907     (void)getRoot();
7908     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7909     CLI.setChain(getRoot());
7910   }
7911 
7912   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7913   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7914 
7915   assert((CLI.IsTailCall || Result.second.getNode()) &&
7916          "Non-null chain expected with non-tail call!");
7917   assert((Result.second.getNode() || !Result.first.getNode()) &&
7918          "Null value expected with tail call!");
7919 
7920   if (!Result.second.getNode()) {
7921     // As a special case, a null chain means that a tail call has been emitted
7922     // and the DAG root is already updated.
7923     HasTailCall = true;
7924 
7925     // Since there's no actual continuation from this block, nothing can be
7926     // relying on us setting vregs for them.
7927     PendingExports.clear();
7928   } else {
7929     DAG.setRoot(Result.second);
7930   }
7931 
7932   if (EHPadBB) {
7933     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7934                            BeginLabel));
7935   }
7936 
7937   return Result;
7938 }
7939 
7940 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7941                                       bool isTailCall,
7942                                       bool isMustTailCall,
7943                                       const BasicBlock *EHPadBB) {
7944   auto &DL = DAG.getDataLayout();
7945   FunctionType *FTy = CB.getFunctionType();
7946   Type *RetTy = CB.getType();
7947 
7948   TargetLowering::ArgListTy Args;
7949   Args.reserve(CB.arg_size());
7950 
7951   const Value *SwiftErrorVal = nullptr;
7952   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7953 
7954   if (isTailCall) {
7955     // Avoid emitting tail calls in functions with the disable-tail-calls
7956     // attribute.
7957     auto *Caller = CB.getParent()->getParent();
7958     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7959         "true" && !isMustTailCall)
7960       isTailCall = false;
7961 
7962     // We can't tail call inside a function with a swifterror argument. Lowering
7963     // does not support this yet. It would have to move into the swifterror
7964     // register before the call.
7965     if (TLI.supportSwiftError() &&
7966         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7967       isTailCall = false;
7968   }
7969 
7970   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7971     TargetLowering::ArgListEntry Entry;
7972     const Value *V = *I;
7973 
7974     // Skip empty types
7975     if (V->getType()->isEmptyTy())
7976       continue;
7977 
7978     SDValue ArgNode = getValue(V);
7979     Entry.Node = ArgNode; Entry.Ty = V->getType();
7980 
7981     Entry.setAttributes(&CB, I - CB.arg_begin());
7982 
7983     // Use swifterror virtual register as input to the call.
7984     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7985       SwiftErrorVal = V;
7986       // We find the virtual register for the actual swifterror argument.
7987       // Instead of using the Value, we use the virtual register instead.
7988       Entry.Node =
7989           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7990                           EVT(TLI.getPointerTy(DL)));
7991     }
7992 
7993     Args.push_back(Entry);
7994 
7995     // If we have an explicit sret argument that is an Instruction, (i.e., it
7996     // might point to function-local memory), we can't meaningfully tail-call.
7997     if (Entry.IsSRet && isa<Instruction>(V))
7998       isTailCall = false;
7999   }
8000 
8001   // If call site has a cfguardtarget operand bundle, create and add an
8002   // additional ArgListEntry.
8003   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8004     TargetLowering::ArgListEntry Entry;
8005     Value *V = Bundle->Inputs[0];
8006     SDValue ArgNode = getValue(V);
8007     Entry.Node = ArgNode;
8008     Entry.Ty = V->getType();
8009     Entry.IsCFGuardTarget = true;
8010     Args.push_back(Entry);
8011   }
8012 
8013   // Check if target-independent constraints permit a tail call here.
8014   // Target-dependent constraints are checked within TLI->LowerCallTo.
8015   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8016     isTailCall = false;
8017 
8018   // Disable tail calls if there is an swifterror argument. Targets have not
8019   // been updated to support tail calls.
8020   if (TLI.supportSwiftError() && SwiftErrorVal)
8021     isTailCall = false;
8022 
8023   ConstantInt *CFIType = nullptr;
8024   if (CB.isIndirectCall()) {
8025     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8026       if (!TLI.supportKCFIBundles())
8027         report_fatal_error(
8028             "Target doesn't support calls with kcfi operand bundles.");
8029       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8030       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8031     }
8032   }
8033 
8034   TargetLowering::CallLoweringInfo CLI(DAG);
8035   CLI.setDebugLoc(getCurSDLoc())
8036       .setChain(getRoot())
8037       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8038       .setTailCall(isTailCall)
8039       .setConvergent(CB.isConvergent())
8040       .setIsPreallocated(
8041           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8042       .setCFIType(CFIType);
8043   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8044 
8045   if (Result.first.getNode()) {
8046     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8047     setValue(&CB, Result.first);
8048   }
8049 
8050   // The last element of CLI.InVals has the SDValue for swifterror return.
8051   // Here we copy it to a virtual register and update SwiftErrorMap for
8052   // book-keeping.
8053   if (SwiftErrorVal && TLI.supportSwiftError()) {
8054     // Get the last element of InVals.
8055     SDValue Src = CLI.InVals.back();
8056     Register VReg =
8057         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8058     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8059     DAG.setRoot(CopyNode);
8060   }
8061 }
8062 
8063 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8064                              SelectionDAGBuilder &Builder) {
8065   // Check to see if this load can be trivially constant folded, e.g. if the
8066   // input is from a string literal.
8067   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8068     // Cast pointer to the type we really want to load.
8069     Type *LoadTy =
8070         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8071     if (LoadVT.isVector())
8072       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8073 
8074     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8075                                          PointerType::getUnqual(LoadTy));
8076 
8077     if (const Constant *LoadCst =
8078             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8079                                          LoadTy, Builder.DAG.getDataLayout()))
8080       return Builder.getValue(LoadCst);
8081   }
8082 
8083   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8084   // still constant memory, the input chain can be the entry node.
8085   SDValue Root;
8086   bool ConstantMemory = false;
8087 
8088   // Do not serialize (non-volatile) loads of constant memory with anything.
8089   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8090     Root = Builder.DAG.getEntryNode();
8091     ConstantMemory = true;
8092   } else {
8093     // Do not serialize non-volatile loads against each other.
8094     Root = Builder.DAG.getRoot();
8095   }
8096 
8097   SDValue Ptr = Builder.getValue(PtrVal);
8098   SDValue LoadVal =
8099       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8100                           MachinePointerInfo(PtrVal), Align(1));
8101 
8102   if (!ConstantMemory)
8103     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8104   return LoadVal;
8105 }
8106 
8107 /// Record the value for an instruction that produces an integer result,
8108 /// converting the type where necessary.
8109 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8110                                                   SDValue Value,
8111                                                   bool IsSigned) {
8112   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8113                                                     I.getType(), true);
8114   if (IsSigned)
8115     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
8116   else
8117     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
8118   setValue(&I, Value);
8119 }
8120 
8121 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8122 /// true and lower it. Otherwise return false, and it will be lowered like a
8123 /// normal call.
8124 /// The caller already checked that \p I calls the appropriate LibFunc with a
8125 /// correct prototype.
8126 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8127   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8128   const Value *Size = I.getArgOperand(2);
8129   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8130   if (CSize && CSize->getZExtValue() == 0) {
8131     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8132                                                           I.getType(), true);
8133     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8134     return true;
8135   }
8136 
8137   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8138   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8139       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8140       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8141   if (Res.first.getNode()) {
8142     processIntegerCallValue(I, Res.first, true);
8143     PendingLoads.push_back(Res.second);
8144     return true;
8145   }
8146 
8147   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8148   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8149   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8150     return false;
8151 
8152   // If the target has a fast compare for the given size, it will return a
8153   // preferred load type for that size. Require that the load VT is legal and
8154   // that the target supports unaligned loads of that type. Otherwise, return
8155   // INVALID.
8156   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8157     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8158     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8159     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8160       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8161       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8162       // TODO: Check alignment of src and dest ptrs.
8163       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8164       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8165       if (!TLI.isTypeLegal(LVT) ||
8166           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8167           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8168         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8169     }
8170 
8171     return LVT;
8172   };
8173 
8174   // This turns into unaligned loads. We only do this if the target natively
8175   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8176   // we'll only produce a small number of byte loads.
8177   MVT LoadVT;
8178   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8179   switch (NumBitsToCompare) {
8180   default:
8181     return false;
8182   case 16:
8183     LoadVT = MVT::i16;
8184     break;
8185   case 32:
8186     LoadVT = MVT::i32;
8187     break;
8188   case 64:
8189   case 128:
8190   case 256:
8191     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8192     break;
8193   }
8194 
8195   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8196     return false;
8197 
8198   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8199   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8200 
8201   // Bitcast to a wide integer type if the loads are vectors.
8202   if (LoadVT.isVector()) {
8203     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8204     LoadL = DAG.getBitcast(CmpVT, LoadL);
8205     LoadR = DAG.getBitcast(CmpVT, LoadR);
8206   }
8207 
8208   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8209   processIntegerCallValue(I, Cmp, false);
8210   return true;
8211 }
8212 
8213 /// See if we can lower a memchr call into an optimized form. If so, return
8214 /// true and lower it. Otherwise return false, and it will be lowered like a
8215 /// normal call.
8216 /// The caller already checked that \p I calls the appropriate LibFunc with a
8217 /// correct prototype.
8218 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8219   const Value *Src = I.getArgOperand(0);
8220   const Value *Char = I.getArgOperand(1);
8221   const Value *Length = I.getArgOperand(2);
8222 
8223   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8224   std::pair<SDValue, SDValue> Res =
8225     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8226                                 getValue(Src), getValue(Char), getValue(Length),
8227                                 MachinePointerInfo(Src));
8228   if (Res.first.getNode()) {
8229     setValue(&I, Res.first);
8230     PendingLoads.push_back(Res.second);
8231     return true;
8232   }
8233 
8234   return false;
8235 }
8236 
8237 /// See if we can lower a mempcpy call into an optimized form. If so, return
8238 /// true and lower it. Otherwise return false, and it will be lowered like a
8239 /// normal call.
8240 /// The caller already checked that \p I calls the appropriate LibFunc with a
8241 /// correct prototype.
8242 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8243   SDValue Dst = getValue(I.getArgOperand(0));
8244   SDValue Src = getValue(I.getArgOperand(1));
8245   SDValue Size = getValue(I.getArgOperand(2));
8246 
8247   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8248   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8249   // DAG::getMemcpy needs Alignment to be defined.
8250   Align Alignment = std::min(DstAlign, SrcAlign);
8251 
8252   bool isVol = false;
8253   SDLoc sdl = getCurSDLoc();
8254 
8255   // In the mempcpy context we need to pass in a false value for isTailCall
8256   // because the return pointer needs to be adjusted by the size of
8257   // the copied memory.
8258   SDValue Root = isVol ? getRoot() : getMemoryRoot();
8259   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
8260                              /*isTailCall=*/false,
8261                              MachinePointerInfo(I.getArgOperand(0)),
8262                              MachinePointerInfo(I.getArgOperand(1)),
8263                              I.getAAMetadata());
8264   assert(MC.getNode() != nullptr &&
8265          "** memcpy should not be lowered as TailCall in mempcpy context **");
8266   DAG.setRoot(MC);
8267 
8268   // Check if Size needs to be truncated or extended.
8269   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8270 
8271   // Adjust return pointer to point just past the last dst byte.
8272   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8273                                     Dst, Size);
8274   setValue(&I, DstPlusSize);
8275   return true;
8276 }
8277 
8278 /// See if we can lower a strcpy call into an optimized form.  If so, return
8279 /// true and lower it, otherwise return false and it will be lowered like a
8280 /// normal call.
8281 /// The caller already checked that \p I calls the appropriate LibFunc with a
8282 /// correct prototype.
8283 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8284   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8285 
8286   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8287   std::pair<SDValue, SDValue> Res =
8288     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8289                                 getValue(Arg0), getValue(Arg1),
8290                                 MachinePointerInfo(Arg0),
8291                                 MachinePointerInfo(Arg1), isStpcpy);
8292   if (Res.first.getNode()) {
8293     setValue(&I, Res.first);
8294     DAG.setRoot(Res.second);
8295     return true;
8296   }
8297 
8298   return false;
8299 }
8300 
8301 /// See if we can lower a strcmp call into an optimized form.  If so, return
8302 /// true and lower it, otherwise return false and it will be lowered like a
8303 /// normal call.
8304 /// The caller already checked that \p I calls the appropriate LibFunc with a
8305 /// correct prototype.
8306 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8307   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8308 
8309   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8310   std::pair<SDValue, SDValue> Res =
8311     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8312                                 getValue(Arg0), getValue(Arg1),
8313                                 MachinePointerInfo(Arg0),
8314                                 MachinePointerInfo(Arg1));
8315   if (Res.first.getNode()) {
8316     processIntegerCallValue(I, Res.first, true);
8317     PendingLoads.push_back(Res.second);
8318     return true;
8319   }
8320 
8321   return false;
8322 }
8323 
8324 /// See if we can lower a strlen call into an optimized form.  If so, return
8325 /// true and lower it, otherwise return false and it will be lowered like a
8326 /// normal call.
8327 /// The caller already checked that \p I calls the appropriate LibFunc with a
8328 /// correct prototype.
8329 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8330   const Value *Arg0 = I.getArgOperand(0);
8331 
8332   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8333   std::pair<SDValue, SDValue> Res =
8334     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8335                                 getValue(Arg0), MachinePointerInfo(Arg0));
8336   if (Res.first.getNode()) {
8337     processIntegerCallValue(I, Res.first, false);
8338     PendingLoads.push_back(Res.second);
8339     return true;
8340   }
8341 
8342   return false;
8343 }
8344 
8345 /// See if we can lower a strnlen call into an optimized form.  If so, return
8346 /// true and lower it, otherwise return false and it will be lowered like a
8347 /// normal call.
8348 /// The caller already checked that \p I calls the appropriate LibFunc with a
8349 /// correct prototype.
8350 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8351   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8352 
8353   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8354   std::pair<SDValue, SDValue> Res =
8355     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8356                                  getValue(Arg0), getValue(Arg1),
8357                                  MachinePointerInfo(Arg0));
8358   if (Res.first.getNode()) {
8359     processIntegerCallValue(I, Res.first, false);
8360     PendingLoads.push_back(Res.second);
8361     return true;
8362   }
8363 
8364   return false;
8365 }
8366 
8367 /// See if we can lower a unary 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::visitUnaryFloatCall(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 Tmp = getValue(I.getArgOperand(0));
8382   setValue(&I,
8383            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8384   return true;
8385 }
8386 
8387 /// See if we can lower a binary floating-point operation into an SDNode with
8388 /// the specified Opcode. If so, return true and lower it. Otherwise return
8389 /// false, and it will be lowered like a normal call.
8390 /// The caller already checked that \p I calls the appropriate LibFunc with a
8391 /// correct prototype.
8392 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8393                                                unsigned Opcode) {
8394   // We already checked this call's prototype; verify it doesn't modify errno.
8395   if (!I.onlyReadsMemory())
8396     return false;
8397 
8398   SDNodeFlags Flags;
8399   Flags.copyFMF(cast<FPMathOperator>(I));
8400 
8401   SDValue Tmp0 = getValue(I.getArgOperand(0));
8402   SDValue Tmp1 = getValue(I.getArgOperand(1));
8403   EVT VT = Tmp0.getValueType();
8404   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8405   return true;
8406 }
8407 
8408 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8409   // Handle inline assembly differently.
8410   if (I.isInlineAsm()) {
8411     visitInlineAsm(I);
8412     return;
8413   }
8414 
8415   diagnoseDontCall(I);
8416 
8417   if (Function *F = I.getCalledFunction()) {
8418     if (F->isDeclaration()) {
8419       // Is this an LLVM intrinsic or a target-specific intrinsic?
8420       unsigned IID = F->getIntrinsicID();
8421       if (!IID)
8422         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8423           IID = II->getIntrinsicID(F);
8424 
8425       if (IID) {
8426         visitIntrinsicCall(I, IID);
8427         return;
8428       }
8429     }
8430 
8431     // Check for well-known libc/libm calls.  If the function is internal, it
8432     // can't be a library call.  Don't do the check if marked as nobuiltin for
8433     // some reason or the call site requires strict floating point semantics.
8434     LibFunc Func;
8435     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8436         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8437         LibInfo->hasOptimizedCodeGen(Func)) {
8438       switch (Func) {
8439       default: break;
8440       case LibFunc_bcmp:
8441         if (visitMemCmpBCmpCall(I))
8442           return;
8443         break;
8444       case LibFunc_copysign:
8445       case LibFunc_copysignf:
8446       case LibFunc_copysignl:
8447         // We already checked this call's prototype; verify it doesn't modify
8448         // errno.
8449         if (I.onlyReadsMemory()) {
8450           SDValue LHS = getValue(I.getArgOperand(0));
8451           SDValue RHS = getValue(I.getArgOperand(1));
8452           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8453                                    LHS.getValueType(), LHS, RHS));
8454           return;
8455         }
8456         break;
8457       case LibFunc_fabs:
8458       case LibFunc_fabsf:
8459       case LibFunc_fabsl:
8460         if (visitUnaryFloatCall(I, ISD::FABS))
8461           return;
8462         break;
8463       case LibFunc_fmin:
8464       case LibFunc_fminf:
8465       case LibFunc_fminl:
8466         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8467           return;
8468         break;
8469       case LibFunc_fmax:
8470       case LibFunc_fmaxf:
8471       case LibFunc_fmaxl:
8472         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8473           return;
8474         break;
8475       case LibFunc_sin:
8476       case LibFunc_sinf:
8477       case LibFunc_sinl:
8478         if (visitUnaryFloatCall(I, ISD::FSIN))
8479           return;
8480         break;
8481       case LibFunc_cos:
8482       case LibFunc_cosf:
8483       case LibFunc_cosl:
8484         if (visitUnaryFloatCall(I, ISD::FCOS))
8485           return;
8486         break;
8487       case LibFunc_sqrt:
8488       case LibFunc_sqrtf:
8489       case LibFunc_sqrtl:
8490       case LibFunc_sqrt_finite:
8491       case LibFunc_sqrtf_finite:
8492       case LibFunc_sqrtl_finite:
8493         if (visitUnaryFloatCall(I, ISD::FSQRT))
8494           return;
8495         break;
8496       case LibFunc_floor:
8497       case LibFunc_floorf:
8498       case LibFunc_floorl:
8499         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8500           return;
8501         break;
8502       case LibFunc_nearbyint:
8503       case LibFunc_nearbyintf:
8504       case LibFunc_nearbyintl:
8505         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8506           return;
8507         break;
8508       case LibFunc_ceil:
8509       case LibFunc_ceilf:
8510       case LibFunc_ceill:
8511         if (visitUnaryFloatCall(I, ISD::FCEIL))
8512           return;
8513         break;
8514       case LibFunc_rint:
8515       case LibFunc_rintf:
8516       case LibFunc_rintl:
8517         if (visitUnaryFloatCall(I, ISD::FRINT))
8518           return;
8519         break;
8520       case LibFunc_round:
8521       case LibFunc_roundf:
8522       case LibFunc_roundl:
8523         if (visitUnaryFloatCall(I, ISD::FROUND))
8524           return;
8525         break;
8526       case LibFunc_trunc:
8527       case LibFunc_truncf:
8528       case LibFunc_truncl:
8529         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8530           return;
8531         break;
8532       case LibFunc_log2:
8533       case LibFunc_log2f:
8534       case LibFunc_log2l:
8535         if (visitUnaryFloatCall(I, ISD::FLOG2))
8536           return;
8537         break;
8538       case LibFunc_exp2:
8539       case LibFunc_exp2f:
8540       case LibFunc_exp2l:
8541         if (visitUnaryFloatCall(I, ISD::FEXP2))
8542           return;
8543         break;
8544       case LibFunc_memcmp:
8545         if (visitMemCmpBCmpCall(I))
8546           return;
8547         break;
8548       case LibFunc_mempcpy:
8549         if (visitMemPCpyCall(I))
8550           return;
8551         break;
8552       case LibFunc_memchr:
8553         if (visitMemChrCall(I))
8554           return;
8555         break;
8556       case LibFunc_strcpy:
8557         if (visitStrCpyCall(I, false))
8558           return;
8559         break;
8560       case LibFunc_stpcpy:
8561         if (visitStrCpyCall(I, true))
8562           return;
8563         break;
8564       case LibFunc_strcmp:
8565         if (visitStrCmpCall(I))
8566           return;
8567         break;
8568       case LibFunc_strlen:
8569         if (visitStrLenCall(I))
8570           return;
8571         break;
8572       case LibFunc_strnlen:
8573         if (visitStrNLenCall(I))
8574           return;
8575         break;
8576       }
8577     }
8578   }
8579 
8580   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8581   // have to do anything here to lower funclet bundles.
8582   // CFGuardTarget bundles are lowered in LowerCallTo.
8583   assert(!I.hasOperandBundlesOtherThan(
8584              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8585               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8586               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8587          "Cannot lower calls with arbitrary operand bundles!");
8588 
8589   SDValue Callee = getValue(I.getCalledOperand());
8590 
8591   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8592     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8593   else
8594     // Check if we can potentially perform a tail call. More detailed checking
8595     // is be done within LowerCallTo, after more information about the call is
8596     // known.
8597     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8598 }
8599 
8600 namespace {
8601 
8602 /// AsmOperandInfo - This contains information for each constraint that we are
8603 /// lowering.
8604 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8605 public:
8606   /// CallOperand - If this is the result output operand or a clobber
8607   /// this is null, otherwise it is the incoming operand to the CallInst.
8608   /// This gets modified as the asm is processed.
8609   SDValue CallOperand;
8610 
8611   /// AssignedRegs - If this is a register or register class operand, this
8612   /// contains the set of register corresponding to the operand.
8613   RegsForValue AssignedRegs;
8614 
8615   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8616     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8617   }
8618 
8619   /// Whether or not this operand accesses memory
8620   bool hasMemory(const TargetLowering &TLI) const {
8621     // Indirect operand accesses access memory.
8622     if (isIndirect)
8623       return true;
8624 
8625     for (const auto &Code : Codes)
8626       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8627         return true;
8628 
8629     return false;
8630   }
8631 };
8632 
8633 
8634 } // end anonymous namespace
8635 
8636 /// Make sure that the output operand \p OpInfo and its corresponding input
8637 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8638 /// out).
8639 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8640                                SDISelAsmOperandInfo &MatchingOpInfo,
8641                                SelectionDAG &DAG) {
8642   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8643     return;
8644 
8645   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8646   const auto &TLI = DAG.getTargetLoweringInfo();
8647 
8648   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8649       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8650                                        OpInfo.ConstraintVT);
8651   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8652       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8653                                        MatchingOpInfo.ConstraintVT);
8654   if ((OpInfo.ConstraintVT.isInteger() !=
8655        MatchingOpInfo.ConstraintVT.isInteger()) ||
8656       (MatchRC.second != InputRC.second)) {
8657     // FIXME: error out in a more elegant fashion
8658     report_fatal_error("Unsupported asm: input constraint"
8659                        " with a matching output constraint of"
8660                        " incompatible type!");
8661   }
8662   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8663 }
8664 
8665 /// Get a direct memory input to behave well as an indirect operand.
8666 /// This may introduce stores, hence the need for a \p Chain.
8667 /// \return The (possibly updated) chain.
8668 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8669                                         SDISelAsmOperandInfo &OpInfo,
8670                                         SelectionDAG &DAG) {
8671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8672 
8673   // If we don't have an indirect input, put it in the constpool if we can,
8674   // otherwise spill it to a stack slot.
8675   // TODO: This isn't quite right. We need to handle these according to
8676   // the addressing mode that the constraint wants. Also, this may take
8677   // an additional register for the computation and we don't want that
8678   // either.
8679 
8680   // If the operand is a float, integer, or vector constant, spill to a
8681   // constant pool entry to get its address.
8682   const Value *OpVal = OpInfo.CallOperandVal;
8683   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8684       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8685     OpInfo.CallOperand = DAG.getConstantPool(
8686         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8687     return Chain;
8688   }
8689 
8690   // Otherwise, create a stack slot and emit a store to it before the asm.
8691   Type *Ty = OpVal->getType();
8692   auto &DL = DAG.getDataLayout();
8693   uint64_t TySize = DL.getTypeAllocSize(Ty);
8694   MachineFunction &MF = DAG.getMachineFunction();
8695   int SSFI = MF.getFrameInfo().CreateStackObject(
8696       TySize, DL.getPrefTypeAlign(Ty), false);
8697   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8698   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8699                             MachinePointerInfo::getFixedStack(MF, SSFI),
8700                             TLI.getMemValueType(DL, Ty));
8701   OpInfo.CallOperand = StackSlot;
8702 
8703   return Chain;
8704 }
8705 
8706 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8707 /// specified operand.  We prefer to assign virtual registers, to allow the
8708 /// register allocator to handle the assignment process.  However, if the asm
8709 /// uses features that we can't model on machineinstrs, we have SDISel do the
8710 /// allocation.  This produces generally horrible, but correct, code.
8711 ///
8712 ///   OpInfo describes the operand
8713 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8714 static std::optional<unsigned>
8715 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8716                      SDISelAsmOperandInfo &OpInfo,
8717                      SDISelAsmOperandInfo &RefOpInfo) {
8718   LLVMContext &Context = *DAG.getContext();
8719   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8720 
8721   MachineFunction &MF = DAG.getMachineFunction();
8722   SmallVector<unsigned, 4> Regs;
8723   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8724 
8725   // No work to do for memory/address operands.
8726   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8727       OpInfo.ConstraintType == TargetLowering::C_Address)
8728     return std::nullopt;
8729 
8730   // If this is a constraint for a single physreg, or a constraint for a
8731   // register class, find it.
8732   unsigned AssignedReg;
8733   const TargetRegisterClass *RC;
8734   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8735       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8736   // RC is unset only on failure. Return immediately.
8737   if (!RC)
8738     return std::nullopt;
8739 
8740   // Get the actual register value type.  This is important, because the user
8741   // may have asked for (e.g.) the AX register in i32 type.  We need to
8742   // remember that AX is actually i16 to get the right extension.
8743   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8744 
8745   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8746     // If this is an FP operand in an integer register (or visa versa), or more
8747     // generally if the operand value disagrees with the register class we plan
8748     // to stick it in, fix the operand type.
8749     //
8750     // If this is an input value, the bitcast to the new type is done now.
8751     // Bitcast for output value is done at the end of visitInlineAsm().
8752     if ((OpInfo.Type == InlineAsm::isOutput ||
8753          OpInfo.Type == InlineAsm::isInput) &&
8754         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8755       // Try to convert to the first EVT that the reg class contains.  If the
8756       // types are identical size, use a bitcast to convert (e.g. two differing
8757       // vector types).  Note: output bitcast is done at the end of
8758       // visitInlineAsm().
8759       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8760         // Exclude indirect inputs while they are unsupported because the code
8761         // to perform the load is missing and thus OpInfo.CallOperand still
8762         // refers to the input address rather than the pointed-to value.
8763         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8764           OpInfo.CallOperand =
8765               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8766         OpInfo.ConstraintVT = RegVT;
8767         // If the operand is an FP value and we want it in integer registers,
8768         // use the corresponding integer type. This turns an f64 value into
8769         // i64, which can be passed with two i32 values on a 32-bit machine.
8770       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8771         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8772         if (OpInfo.Type == InlineAsm::isInput)
8773           OpInfo.CallOperand =
8774               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8775         OpInfo.ConstraintVT = VT;
8776       }
8777     }
8778   }
8779 
8780   // No need to allocate a matching input constraint since the constraint it's
8781   // matching to has already been allocated.
8782   if (OpInfo.isMatchingInputConstraint())
8783     return std::nullopt;
8784 
8785   EVT ValueVT = OpInfo.ConstraintVT;
8786   if (OpInfo.ConstraintVT == MVT::Other)
8787     ValueVT = RegVT;
8788 
8789   // Initialize NumRegs.
8790   unsigned NumRegs = 1;
8791   if (OpInfo.ConstraintVT != MVT::Other)
8792     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8793 
8794   // If this is a constraint for a specific physical register, like {r17},
8795   // assign it now.
8796 
8797   // If this associated to a specific register, initialize iterator to correct
8798   // place. If virtual, make sure we have enough registers
8799 
8800   // Initialize iterator if necessary
8801   TargetRegisterClass::iterator I = RC->begin();
8802   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8803 
8804   // Do not check for single registers.
8805   if (AssignedReg) {
8806     I = std::find(I, RC->end(), AssignedReg);
8807     if (I == RC->end()) {
8808       // RC does not contain the selected register, which indicates a
8809       // mismatch between the register and the required type/bitwidth.
8810       return {AssignedReg};
8811     }
8812   }
8813 
8814   for (; NumRegs; --NumRegs, ++I) {
8815     assert(I != RC->end() && "Ran out of registers to allocate!");
8816     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8817     Regs.push_back(R);
8818   }
8819 
8820   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8821   return std::nullopt;
8822 }
8823 
8824 static unsigned
8825 findMatchingInlineAsmOperand(unsigned OperandNo,
8826                              const std::vector<SDValue> &AsmNodeOperands) {
8827   // Scan until we find the definition we already emitted of this operand.
8828   unsigned CurOp = InlineAsm::Op_FirstOperand;
8829   for (; OperandNo; --OperandNo) {
8830     // Advance to the next operand.
8831     unsigned OpFlag =
8832         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8833     assert((InlineAsm::isRegDefKind(OpFlag) ||
8834             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8835             InlineAsm::isMemKind(OpFlag)) &&
8836            "Skipped past definitions?");
8837     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8838   }
8839   return CurOp;
8840 }
8841 
8842 namespace {
8843 
8844 class ExtraFlags {
8845   unsigned Flags = 0;
8846 
8847 public:
8848   explicit ExtraFlags(const CallBase &Call) {
8849     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8850     if (IA->hasSideEffects())
8851       Flags |= InlineAsm::Extra_HasSideEffects;
8852     if (IA->isAlignStack())
8853       Flags |= InlineAsm::Extra_IsAlignStack;
8854     if (Call.isConvergent())
8855       Flags |= InlineAsm::Extra_IsConvergent;
8856     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8857   }
8858 
8859   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8860     // Ideally, we would only check against memory constraints.  However, the
8861     // meaning of an Other constraint can be target-specific and we can't easily
8862     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8863     // for Other constraints as well.
8864     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8865         OpInfo.ConstraintType == TargetLowering::C_Other) {
8866       if (OpInfo.Type == InlineAsm::isInput)
8867         Flags |= InlineAsm::Extra_MayLoad;
8868       else if (OpInfo.Type == InlineAsm::isOutput)
8869         Flags |= InlineAsm::Extra_MayStore;
8870       else if (OpInfo.Type == InlineAsm::isClobber)
8871         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8872     }
8873   }
8874 
8875   unsigned get() const { return Flags; }
8876 };
8877 
8878 } // end anonymous namespace
8879 
8880 static bool isFunction(SDValue Op) {
8881   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
8882     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8883       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
8884 
8885       // In normal "call dllimport func" instruction (non-inlineasm) it force
8886       // indirect access by specifing call opcode. And usually specially print
8887       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
8888       // not do in this way now. (In fact, this is similar with "Data Access"
8889       // action). So here we ignore dllimport function.
8890       if (Fn && !Fn->hasDLLImportStorageClass())
8891         return true;
8892     }
8893   }
8894   return false;
8895 }
8896 
8897 /// visitInlineAsm - Handle a call to an InlineAsm object.
8898 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8899                                          const BasicBlock *EHPadBB) {
8900   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8901 
8902   /// ConstraintOperands - Information about all of the constraints.
8903   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8904 
8905   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8906   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8907       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8908 
8909   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8910   // AsmDialect, MayLoad, MayStore).
8911   bool HasSideEffect = IA->hasSideEffects();
8912   ExtraFlags ExtraInfo(Call);
8913 
8914   for (auto &T : TargetConstraints) {
8915     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8916     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8917 
8918     if (OpInfo.CallOperandVal)
8919       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8920 
8921     if (!HasSideEffect)
8922       HasSideEffect = OpInfo.hasMemory(TLI);
8923 
8924     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8925     // FIXME: Could we compute this on OpInfo rather than T?
8926 
8927     // Compute the constraint code and ConstraintType to use.
8928     TLI.ComputeConstraintToUse(T, SDValue());
8929 
8930     if (T.ConstraintType == TargetLowering::C_Immediate &&
8931         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8932       // We've delayed emitting a diagnostic like the "n" constraint because
8933       // inlining could cause an integer showing up.
8934       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8935                                           "' expects an integer constant "
8936                                           "expression");
8937 
8938     ExtraInfo.update(T);
8939   }
8940 
8941   // We won't need to flush pending loads if this asm doesn't touch
8942   // memory and is nonvolatile.
8943   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8944 
8945   bool EmitEHLabels = isa<InvokeInst>(Call);
8946   if (EmitEHLabels) {
8947     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8948   }
8949   bool IsCallBr = isa<CallBrInst>(Call);
8950 
8951   if (IsCallBr || EmitEHLabels) {
8952     // If this is a callbr or invoke we need to flush pending exports since
8953     // inlineasm_br and invoke are terminators.
8954     // We need to do this before nodes are glued to the inlineasm_br node.
8955     Chain = getControlRoot();
8956   }
8957 
8958   MCSymbol *BeginLabel = nullptr;
8959   if (EmitEHLabels) {
8960     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8961   }
8962 
8963   int OpNo = -1;
8964   SmallVector<StringRef> AsmStrs;
8965   IA->collectAsmStrs(AsmStrs);
8966 
8967   // Second pass over the constraints: compute which constraint option to use.
8968   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8969     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
8970       OpNo++;
8971 
8972     // If this is an output operand with a matching input operand, look up the
8973     // matching input. If their types mismatch, e.g. one is an integer, the
8974     // other is floating point, or their sizes are different, flag it as an
8975     // error.
8976     if (OpInfo.hasMatchingInput()) {
8977       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8978       patchMatchingInput(OpInfo, Input, DAG);
8979     }
8980 
8981     // Compute the constraint code and ConstraintType to use.
8982     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8983 
8984     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
8985          OpInfo.Type == InlineAsm::isClobber) ||
8986         OpInfo.ConstraintType == TargetLowering::C_Address)
8987       continue;
8988 
8989     // In Linux PIC model, there are 4 cases about value/label addressing:
8990     //
8991     // 1: Function call or Label jmp inside the module.
8992     // 2: Data access (such as global variable, static variable) inside module.
8993     // 3: Function call or Label jmp outside the module.
8994     // 4: Data access (such as global variable) outside the module.
8995     //
8996     // Due to current llvm inline asm architecture designed to not "recognize"
8997     // the asm code, there are quite troubles for us to treat mem addressing
8998     // differently for same value/adress used in different instuctions.
8999     // For example, in pic model, call a func may in plt way or direclty
9000     // pc-related, but lea/mov a function adress may use got.
9001     //
9002     // Here we try to "recognize" function call for the case 1 and case 3 in
9003     // inline asm. And try to adjust the constraint for them.
9004     //
9005     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9006     // label, so here we don't handle jmp function label now, but we need to
9007     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9008     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9009         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9010         TM.getCodeModel() != CodeModel::Large) {
9011       OpInfo.isIndirect = false;
9012       OpInfo.ConstraintType = TargetLowering::C_Address;
9013     }
9014 
9015     // If this is a memory input, and if the operand is not indirect, do what we
9016     // need to provide an address for the memory input.
9017     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9018         !OpInfo.isIndirect) {
9019       assert((OpInfo.isMultipleAlternative ||
9020               (OpInfo.Type == InlineAsm::isInput)) &&
9021              "Can only indirectify direct input operands!");
9022 
9023       // Memory operands really want the address of the value.
9024       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9025 
9026       // There is no longer a Value* corresponding to this operand.
9027       OpInfo.CallOperandVal = nullptr;
9028 
9029       // It is now an indirect operand.
9030       OpInfo.isIndirect = true;
9031     }
9032 
9033   }
9034 
9035   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9036   std::vector<SDValue> AsmNodeOperands;
9037   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9038   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9039       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9040 
9041   // If we have a !srcloc metadata node associated with it, we want to attach
9042   // this to the ultimately generated inline asm machineinstr.  To do this, we
9043   // pass in the third operand as this (potentially null) inline asm MDNode.
9044   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9045   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9046 
9047   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9048   // bits as operand 3.
9049   AsmNodeOperands.push_back(DAG.getTargetConstant(
9050       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9051 
9052   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9053   // this, assign virtual and physical registers for inputs and otput.
9054   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9055     // Assign Registers.
9056     SDISelAsmOperandInfo &RefOpInfo =
9057         OpInfo.isMatchingInputConstraint()
9058             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9059             : OpInfo;
9060     const auto RegError =
9061         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9062     if (RegError) {
9063       const MachineFunction &MF = DAG.getMachineFunction();
9064       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9065       const char *RegName = TRI.getName(*RegError);
9066       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9067                                    "' allocated for constraint '" +
9068                                    Twine(OpInfo.ConstraintCode) +
9069                                    "' does not match required type");
9070       return;
9071     }
9072 
9073     auto DetectWriteToReservedRegister = [&]() {
9074       const MachineFunction &MF = DAG.getMachineFunction();
9075       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9076       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9077         if (Register::isPhysicalRegister(Reg) &&
9078             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9079           const char *RegName = TRI.getName(Reg);
9080           emitInlineAsmError(Call, "write to reserved register '" +
9081                                        Twine(RegName) + "'");
9082           return true;
9083         }
9084       }
9085       return false;
9086     };
9087     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9088             (OpInfo.Type == InlineAsm::isInput &&
9089              !OpInfo.isMatchingInputConstraint())) &&
9090            "Only address as input operand is allowed.");
9091 
9092     switch (OpInfo.Type) {
9093     case InlineAsm::isOutput:
9094       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9095         unsigned ConstraintID =
9096             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9097         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9098                "Failed to convert memory constraint code to constraint id.");
9099 
9100         // Add information to the INLINEASM node to know about this output.
9101         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9102         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
9103         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9104                                                         MVT::i32));
9105         AsmNodeOperands.push_back(OpInfo.CallOperand);
9106       } else {
9107         // Otherwise, this outputs to a register (directly for C_Register /
9108         // C_RegisterClass, and a target-defined fashion for
9109         // C_Immediate/C_Other). Find a register that we can use.
9110         if (OpInfo.AssignedRegs.Regs.empty()) {
9111           emitInlineAsmError(
9112               Call, "couldn't allocate output register for constraint '" +
9113                         Twine(OpInfo.ConstraintCode) + "'");
9114           return;
9115         }
9116 
9117         if (DetectWriteToReservedRegister())
9118           return;
9119 
9120         // Add information to the INLINEASM node to know that this register is
9121         // set.
9122         OpInfo.AssignedRegs.AddInlineAsmOperands(
9123             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
9124                                   : InlineAsm::Kind_RegDef,
9125             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9126       }
9127       break;
9128 
9129     case InlineAsm::isInput:
9130     case InlineAsm::isLabel: {
9131       SDValue InOperandVal = OpInfo.CallOperand;
9132 
9133       if (OpInfo.isMatchingInputConstraint()) {
9134         // If this is required to match an output register we have already set,
9135         // just use its register.
9136         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9137                                                   AsmNodeOperands);
9138         unsigned OpFlag =
9139           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
9140         if (InlineAsm::isRegDefKind(OpFlag) ||
9141             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
9142           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
9143           if (OpInfo.isIndirect) {
9144             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9145             emitInlineAsmError(Call, "inline asm not supported yet: "
9146                                      "don't know how to handle tied "
9147                                      "indirect register inputs");
9148             return;
9149           }
9150 
9151           SmallVector<unsigned, 4> Regs;
9152           MachineFunction &MF = DAG.getMachineFunction();
9153           MachineRegisterInfo &MRI = MF.getRegInfo();
9154           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9155           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9156           Register TiedReg = R->getReg();
9157           MVT RegVT = R->getSimpleValueType(0);
9158           const TargetRegisterClass *RC =
9159               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9160               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9161                                       : TRI.getMinimalPhysRegClass(TiedReg);
9162           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
9163           for (unsigned i = 0; i != NumRegs; ++i)
9164             Regs.push_back(MRI.createVirtualRegister(RC));
9165 
9166           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9167 
9168           SDLoc dl = getCurSDLoc();
9169           // Use the produced MatchedRegs object to
9170           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9171           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
9172                                            true, OpInfo.getMatchedOperand(), dl,
9173                                            DAG, AsmNodeOperands);
9174           break;
9175         }
9176 
9177         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
9178         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
9179                "Unexpected number of operands");
9180         // Add information to the INLINEASM node to know about this input.
9181         // See InlineAsm.h isUseOperandTiedToDef.
9182         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
9183         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
9184                                                     OpInfo.getMatchedOperand());
9185         AsmNodeOperands.push_back(DAG.getTargetConstant(
9186             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9187         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9188         break;
9189       }
9190 
9191       // Treat indirect 'X' constraint as memory.
9192       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9193           OpInfo.isIndirect)
9194         OpInfo.ConstraintType = TargetLowering::C_Memory;
9195 
9196       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9197           OpInfo.ConstraintType == TargetLowering::C_Other) {
9198         std::vector<SDValue> Ops;
9199         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9200                                           Ops, DAG);
9201         if (Ops.empty()) {
9202           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9203             if (isa<ConstantSDNode>(InOperandVal)) {
9204               emitInlineAsmError(Call, "value out of range for constraint '" +
9205                                            Twine(OpInfo.ConstraintCode) + "'");
9206               return;
9207             }
9208 
9209           emitInlineAsmError(Call,
9210                              "invalid operand for inline asm constraint '" +
9211                                  Twine(OpInfo.ConstraintCode) + "'");
9212           return;
9213         }
9214 
9215         // Add information to the INLINEASM node to know about this input.
9216         unsigned ResOpType =
9217           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
9218         AsmNodeOperands.push_back(DAG.getTargetConstant(
9219             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9220         llvm::append_range(AsmNodeOperands, Ops);
9221         break;
9222       }
9223 
9224       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9225         assert((OpInfo.isIndirect ||
9226                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9227                "Operand must be indirect to be a mem!");
9228         assert(InOperandVal.getValueType() ==
9229                    TLI.getPointerTy(DAG.getDataLayout()) &&
9230                "Memory 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         // Add information to the INLINEASM node to know about this input.
9238         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9239         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9240         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9241                                                         getCurSDLoc(),
9242                                                         MVT::i32));
9243         AsmNodeOperands.push_back(InOperandVal);
9244         break;
9245       }
9246 
9247       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9248         assert(InOperandVal.getValueType() ==
9249                    TLI.getPointerTy(DAG.getDataLayout()) &&
9250                "Address operands expect pointer values");
9251 
9252         unsigned ConstraintID =
9253             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9254         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9255                "Failed to convert memory constraint code to constraint id.");
9256 
9257         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9258 
9259         SDValue AsmOp = InOperandVal;
9260         if (isFunction(InOperandVal)) {
9261           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9262           ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1);
9263           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9264                                              InOperandVal.getValueType(),
9265                                              GA->getOffset());
9266         }
9267 
9268         // Add information to the INLINEASM node to know about this input.
9269         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9270 
9271         AsmNodeOperands.push_back(
9272             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9273 
9274         AsmNodeOperands.push_back(AsmOp);
9275         break;
9276       }
9277 
9278       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9279               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9280              "Unknown constraint type!");
9281 
9282       // TODO: Support this.
9283       if (OpInfo.isIndirect) {
9284         emitInlineAsmError(
9285             Call, "Don't know how to handle indirect register inputs yet "
9286                   "for constraint '" +
9287                       Twine(OpInfo.ConstraintCode) + "'");
9288         return;
9289       }
9290 
9291       // Copy the input into the appropriate registers.
9292       if (OpInfo.AssignedRegs.Regs.empty()) {
9293         emitInlineAsmError(Call,
9294                            "couldn't allocate input reg for constraint '" +
9295                                Twine(OpInfo.ConstraintCode) + "'");
9296         return;
9297       }
9298 
9299       if (DetectWriteToReservedRegister())
9300         return;
9301 
9302       SDLoc dl = getCurSDLoc();
9303 
9304       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
9305                                         &Call);
9306 
9307       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
9308                                                dl, DAG, AsmNodeOperands);
9309       break;
9310     }
9311     case InlineAsm::isClobber:
9312       // Add the clobbered value to the operand list, so that the register
9313       // allocator is aware that the physreg got clobbered.
9314       if (!OpInfo.AssignedRegs.Regs.empty())
9315         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
9316                                                  false, 0, getCurSDLoc(), DAG,
9317                                                  AsmNodeOperands);
9318       break;
9319     }
9320   }
9321 
9322   // Finish up input operands.  Set the input chain and add the flag last.
9323   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9324   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
9325 
9326   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9327   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9328                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9329   Glue = Chain.getValue(1);
9330 
9331   // Do additional work to generate outputs.
9332 
9333   SmallVector<EVT, 1> ResultVTs;
9334   SmallVector<SDValue, 1> ResultValues;
9335   SmallVector<SDValue, 8> OutChains;
9336 
9337   llvm::Type *CallResultType = Call.getType();
9338   ArrayRef<Type *> ResultTypes;
9339   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9340     ResultTypes = StructResult->elements();
9341   else if (!CallResultType->isVoidTy())
9342     ResultTypes = ArrayRef(CallResultType);
9343 
9344   auto CurResultType = ResultTypes.begin();
9345   auto handleRegAssign = [&](SDValue V) {
9346     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9347     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9348     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9349     ++CurResultType;
9350     // If the type of the inline asm call site return value is different but has
9351     // same size as the type of the asm output bitcast it.  One example of this
9352     // is for vectors with different width / number of elements.  This can
9353     // happen for register classes that can contain multiple different value
9354     // types.  The preg or vreg allocated may not have the same VT as was
9355     // expected.
9356     //
9357     // This can also happen for a return value that disagrees with the register
9358     // class it is put in, eg. a double in a general-purpose register on a
9359     // 32-bit machine.
9360     if (ResultVT != V.getValueType() &&
9361         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9362       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9363     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9364              V.getValueType().isInteger()) {
9365       // If a result value was tied to an input value, the computed result
9366       // may have a wider width than the expected result.  Extract the
9367       // relevant portion.
9368       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9369     }
9370     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9371     ResultVTs.push_back(ResultVT);
9372     ResultValues.push_back(V);
9373   };
9374 
9375   // Deal with output operands.
9376   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9377     if (OpInfo.Type == InlineAsm::isOutput) {
9378       SDValue Val;
9379       // Skip trivial output operands.
9380       if (OpInfo.AssignedRegs.Regs.empty())
9381         continue;
9382 
9383       switch (OpInfo.ConstraintType) {
9384       case TargetLowering::C_Register:
9385       case TargetLowering::C_RegisterClass:
9386         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9387                                                   Chain, &Glue, &Call);
9388         break;
9389       case TargetLowering::C_Immediate:
9390       case TargetLowering::C_Other:
9391         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
9392                                               OpInfo, DAG);
9393         break;
9394       case TargetLowering::C_Memory:
9395         break; // Already handled.
9396       case TargetLowering::C_Address:
9397         break; // Silence warning.
9398       case TargetLowering::C_Unknown:
9399         assert(false && "Unexpected unknown constraint");
9400       }
9401 
9402       // Indirect output manifest as stores. Record output chains.
9403       if (OpInfo.isIndirect) {
9404         const Value *Ptr = OpInfo.CallOperandVal;
9405         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9406         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9407                                      MachinePointerInfo(Ptr));
9408         OutChains.push_back(Store);
9409       } else {
9410         // generate CopyFromRegs to associated registers.
9411         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9412         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9413           for (const SDValue &V : Val->op_values())
9414             handleRegAssign(V);
9415         } else
9416           handleRegAssign(Val);
9417       }
9418     }
9419   }
9420 
9421   // Set results.
9422   if (!ResultValues.empty()) {
9423     assert(CurResultType == ResultTypes.end() &&
9424            "Mismatch in number of ResultTypes");
9425     assert(ResultValues.size() == ResultTypes.size() &&
9426            "Mismatch in number of output operands in asm result");
9427 
9428     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9429                             DAG.getVTList(ResultVTs), ResultValues);
9430     setValue(&Call, V);
9431   }
9432 
9433   // Collect store chains.
9434   if (!OutChains.empty())
9435     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9436 
9437   if (EmitEHLabels) {
9438     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9439   }
9440 
9441   // Only Update Root if inline assembly has a memory effect.
9442   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9443       EmitEHLabels)
9444     DAG.setRoot(Chain);
9445 }
9446 
9447 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9448                                              const Twine &Message) {
9449   LLVMContext &Ctx = *DAG.getContext();
9450   Ctx.emitError(&Call, Message);
9451 
9452   // Make sure we leave the DAG in a valid state
9453   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9454   SmallVector<EVT, 1> ValueVTs;
9455   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9456 
9457   if (ValueVTs.empty())
9458     return;
9459 
9460   SmallVector<SDValue, 1> Ops;
9461   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9462     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9463 
9464   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9465 }
9466 
9467 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9468   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9469                           MVT::Other, getRoot(),
9470                           getValue(I.getArgOperand(0)),
9471                           DAG.getSrcValue(I.getArgOperand(0))));
9472 }
9473 
9474 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9475   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9476   const DataLayout &DL = DAG.getDataLayout();
9477   SDValue V = DAG.getVAArg(
9478       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9479       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9480       DL.getABITypeAlign(I.getType()).value());
9481   DAG.setRoot(V.getValue(1));
9482 
9483   if (I.getType()->isPointerTy())
9484     V = DAG.getPtrExtOrTrunc(
9485         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9486   setValue(&I, V);
9487 }
9488 
9489 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9490   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9491                           MVT::Other, getRoot(),
9492                           getValue(I.getArgOperand(0)),
9493                           DAG.getSrcValue(I.getArgOperand(0))));
9494 }
9495 
9496 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9497   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9498                           MVT::Other, getRoot(),
9499                           getValue(I.getArgOperand(0)),
9500                           getValue(I.getArgOperand(1)),
9501                           DAG.getSrcValue(I.getArgOperand(0)),
9502                           DAG.getSrcValue(I.getArgOperand(1))));
9503 }
9504 
9505 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9506                                                     const Instruction &I,
9507                                                     SDValue Op) {
9508   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9509   if (!Range)
9510     return Op;
9511 
9512   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9513   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9514     return Op;
9515 
9516   APInt Lo = CR.getUnsignedMin();
9517   if (!Lo.isMinValue())
9518     return Op;
9519 
9520   APInt Hi = CR.getUnsignedMax();
9521   unsigned Bits = std::max(Hi.getActiveBits(),
9522                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9523 
9524   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9525 
9526   SDLoc SL = getCurSDLoc();
9527 
9528   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9529                              DAG.getValueType(SmallVT));
9530   unsigned NumVals = Op.getNode()->getNumValues();
9531   if (NumVals == 1)
9532     return ZExt;
9533 
9534   SmallVector<SDValue, 4> Ops;
9535 
9536   Ops.push_back(ZExt);
9537   for (unsigned I = 1; I != NumVals; ++I)
9538     Ops.push_back(Op.getValue(I));
9539 
9540   return DAG.getMergeValues(Ops, SL);
9541 }
9542 
9543 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9544 /// the call being lowered.
9545 ///
9546 /// This is a helper for lowering intrinsics that follow a target calling
9547 /// convention or require stack pointer adjustment. Only a subset of the
9548 /// intrinsic's operands need to participate in the calling convention.
9549 void SelectionDAGBuilder::populateCallLoweringInfo(
9550     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9551     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9552     bool IsPatchPoint) {
9553   TargetLowering::ArgListTy Args;
9554   Args.reserve(NumArgs);
9555 
9556   // Populate the argument list.
9557   // Attributes for args start at offset 1, after the return attribute.
9558   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9559        ArgI != ArgE; ++ArgI) {
9560     const Value *V = Call->getOperand(ArgI);
9561 
9562     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9563 
9564     TargetLowering::ArgListEntry Entry;
9565     Entry.Node = getValue(V);
9566     Entry.Ty = V->getType();
9567     Entry.setAttributes(Call, ArgI);
9568     Args.push_back(Entry);
9569   }
9570 
9571   CLI.setDebugLoc(getCurSDLoc())
9572       .setChain(getRoot())
9573       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9574       .setDiscardResult(Call->use_empty())
9575       .setIsPatchPoint(IsPatchPoint)
9576       .setIsPreallocated(
9577           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9578 }
9579 
9580 /// Add a stack map intrinsic call's live variable operands to a stackmap
9581 /// or patchpoint target node's operand list.
9582 ///
9583 /// Constants are converted to TargetConstants purely as an optimization to
9584 /// avoid constant materialization and register allocation.
9585 ///
9586 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9587 /// generate addess computation nodes, and so FinalizeISel can convert the
9588 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9589 /// address materialization and register allocation, but may also be required
9590 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9591 /// alloca in the entry block, then the runtime may assume that the alloca's
9592 /// StackMap location can be read immediately after compilation and that the
9593 /// location is valid at any point during execution (this is similar to the
9594 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9595 /// only available in a register, then the runtime would need to trap when
9596 /// execution reaches the StackMap in order to read the alloca's location.
9597 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9598                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9599                                 SelectionDAGBuilder &Builder) {
9600   SelectionDAG &DAG = Builder.DAG;
9601   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9602     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9603 
9604     // Things on the stack are pointer-typed, meaning that they are already
9605     // legal and can be emitted directly to target nodes.
9606     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9607       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9608     } else {
9609       // Otherwise emit a target independent node to be legalised.
9610       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9611     }
9612   }
9613 }
9614 
9615 /// Lower llvm.experimental.stackmap.
9616 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9617   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9618   //                                  [live variables...])
9619 
9620   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9621 
9622   SDValue Chain, InGlue, Callee;
9623   SmallVector<SDValue, 32> Ops;
9624 
9625   SDLoc DL = getCurSDLoc();
9626   Callee = getValue(CI.getCalledOperand());
9627 
9628   // The stackmap intrinsic only records the live variables (the arguments
9629   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9630   // intrinsic, this won't be lowered to a function call. This means we don't
9631   // have to worry about calling conventions and target specific lowering code.
9632   // Instead we perform the call lowering right here.
9633   //
9634   // chain, flag = CALLSEQ_START(chain, 0, 0)
9635   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9636   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9637   //
9638   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9639   InGlue = Chain.getValue(1);
9640 
9641   // Add the STACKMAP operands, starting with DAG house-keeping.
9642   Ops.push_back(Chain);
9643   Ops.push_back(InGlue);
9644 
9645   // Add the <id>, <numShadowBytes> operands.
9646   //
9647   // These do not require legalisation, and can be emitted directly to target
9648   // constant nodes.
9649   SDValue ID = getValue(CI.getArgOperand(0));
9650   assert(ID.getValueType() == MVT::i64);
9651   SDValue IDConst = DAG.getTargetConstant(
9652       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9653   Ops.push_back(IDConst);
9654 
9655   SDValue Shad = getValue(CI.getArgOperand(1));
9656   assert(Shad.getValueType() == MVT::i32);
9657   SDValue ShadConst = DAG.getTargetConstant(
9658       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9659   Ops.push_back(ShadConst);
9660 
9661   // Add the live variables.
9662   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9663 
9664   // Create the STACKMAP node.
9665   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9666   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9667   InGlue = Chain.getValue(1);
9668 
9669   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
9670 
9671   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9672 
9673   // Set the root to the target-lowered call chain.
9674   DAG.setRoot(Chain);
9675 
9676   // Inform the Frame Information that we have a stackmap in this function.
9677   FuncInfo.MF->getFrameInfo().setHasStackMap();
9678 }
9679 
9680 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9681 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9682                                           const BasicBlock *EHPadBB) {
9683   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9684   //                                                 i32 <numBytes>,
9685   //                                                 i8* <target>,
9686   //                                                 i32 <numArgs>,
9687   //                                                 [Args...],
9688   //                                                 [live variables...])
9689 
9690   CallingConv::ID CC = CB.getCallingConv();
9691   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9692   bool HasDef = !CB.getType()->isVoidTy();
9693   SDLoc dl = getCurSDLoc();
9694   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9695 
9696   // Handle immediate and symbolic callees.
9697   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9698     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9699                                    /*isTarget=*/true);
9700   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9701     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9702                                          SDLoc(SymbolicCallee),
9703                                          SymbolicCallee->getValueType(0));
9704 
9705   // Get the real number of arguments participating in the call <numArgs>
9706   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9707   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9708 
9709   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9710   // Intrinsics include all meta-operands up to but not including CC.
9711   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9712   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9713          "Not enough arguments provided to the patchpoint intrinsic");
9714 
9715   // For AnyRegCC the arguments are lowered later on manually.
9716   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9717   Type *ReturnTy =
9718       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9719 
9720   TargetLowering::CallLoweringInfo CLI(DAG);
9721   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9722                            ReturnTy, true);
9723   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9724 
9725   SDNode *CallEnd = Result.second.getNode();
9726   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9727     CallEnd = CallEnd->getOperand(0).getNode();
9728 
9729   /// Get a call instruction from the call sequence chain.
9730   /// Tail calls are not allowed.
9731   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9732          "Expected a callseq node.");
9733   SDNode *Call = CallEnd->getOperand(0).getNode();
9734   bool HasGlue = Call->getGluedNode();
9735 
9736   // Replace the target specific call node with the patchable intrinsic.
9737   SmallVector<SDValue, 8> Ops;
9738 
9739   // Push the chain.
9740   Ops.push_back(*(Call->op_begin()));
9741 
9742   // Optionally, push the glue (if any).
9743   if (HasGlue)
9744     Ops.push_back(*(Call->op_end() - 1));
9745 
9746   // Push the register mask info.
9747   if (HasGlue)
9748     Ops.push_back(*(Call->op_end() - 2));
9749   else
9750     Ops.push_back(*(Call->op_end() - 1));
9751 
9752   // Add the <id> and <numBytes> constants.
9753   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9754   Ops.push_back(DAG.getTargetConstant(
9755                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9756   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9757   Ops.push_back(DAG.getTargetConstant(
9758                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9759                   MVT::i32));
9760 
9761   // Add the callee.
9762   Ops.push_back(Callee);
9763 
9764   // Adjust <numArgs> to account for any arguments that have been passed on the
9765   // stack instead.
9766   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9767   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9768   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9769   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9770 
9771   // Add the calling convention
9772   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9773 
9774   // Add the arguments we omitted previously. The register allocator should
9775   // place these in any free register.
9776   if (IsAnyRegCC)
9777     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9778       Ops.push_back(getValue(CB.getArgOperand(i)));
9779 
9780   // Push the arguments from the call instruction.
9781   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9782   Ops.append(Call->op_begin() + 2, e);
9783 
9784   // Push live variables for the stack map.
9785   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9786 
9787   SDVTList NodeTys;
9788   if (IsAnyRegCC && HasDef) {
9789     // Create the return types based on the intrinsic definition
9790     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9791     SmallVector<EVT, 3> ValueVTs;
9792     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9793     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9794 
9795     // There is always a chain and a glue type at the end
9796     ValueVTs.push_back(MVT::Other);
9797     ValueVTs.push_back(MVT::Glue);
9798     NodeTys = DAG.getVTList(ValueVTs);
9799   } else
9800     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9801 
9802   // Replace the target specific call node with a PATCHPOINT node.
9803   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
9804 
9805   // Update the NodeMap.
9806   if (HasDef) {
9807     if (IsAnyRegCC)
9808       setValue(&CB, SDValue(PPV.getNode(), 0));
9809     else
9810       setValue(&CB, Result.first);
9811   }
9812 
9813   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9814   // call sequence. Furthermore the location of the chain and glue can change
9815   // when the AnyReg calling convention is used and the intrinsic returns a
9816   // value.
9817   if (IsAnyRegCC && HasDef) {
9818     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9819     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
9820     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9821   } else
9822     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
9823   DAG.DeleteNode(Call);
9824 
9825   // Inform the Frame Information that we have a patchpoint in this function.
9826   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9827 }
9828 
9829 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9830                                             unsigned Intrinsic) {
9831   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9832   SDValue Op1 = getValue(I.getArgOperand(0));
9833   SDValue Op2;
9834   if (I.arg_size() > 1)
9835     Op2 = getValue(I.getArgOperand(1));
9836   SDLoc dl = getCurSDLoc();
9837   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9838   SDValue Res;
9839   SDNodeFlags SDFlags;
9840   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9841     SDFlags.copyFMF(*FPMO);
9842 
9843   switch (Intrinsic) {
9844   case Intrinsic::vector_reduce_fadd:
9845     if (SDFlags.hasAllowReassociation())
9846       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9847                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9848                         SDFlags);
9849     else
9850       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9851     break;
9852   case Intrinsic::vector_reduce_fmul:
9853     if (SDFlags.hasAllowReassociation())
9854       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9855                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9856                         SDFlags);
9857     else
9858       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9859     break;
9860   case Intrinsic::vector_reduce_add:
9861     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9862     break;
9863   case Intrinsic::vector_reduce_mul:
9864     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9865     break;
9866   case Intrinsic::vector_reduce_and:
9867     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9868     break;
9869   case Intrinsic::vector_reduce_or:
9870     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9871     break;
9872   case Intrinsic::vector_reduce_xor:
9873     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9874     break;
9875   case Intrinsic::vector_reduce_smax:
9876     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9877     break;
9878   case Intrinsic::vector_reduce_smin:
9879     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9880     break;
9881   case Intrinsic::vector_reduce_umax:
9882     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9883     break;
9884   case Intrinsic::vector_reduce_umin:
9885     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9886     break;
9887   case Intrinsic::vector_reduce_fmax:
9888     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9889     break;
9890   case Intrinsic::vector_reduce_fmin:
9891     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9892     break;
9893   default:
9894     llvm_unreachable("Unhandled vector reduce intrinsic");
9895   }
9896   setValue(&I, Res);
9897 }
9898 
9899 /// Returns an AttributeList representing the attributes applied to the return
9900 /// value of the given call.
9901 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9902   SmallVector<Attribute::AttrKind, 2> Attrs;
9903   if (CLI.RetSExt)
9904     Attrs.push_back(Attribute::SExt);
9905   if (CLI.RetZExt)
9906     Attrs.push_back(Attribute::ZExt);
9907   if (CLI.IsInReg)
9908     Attrs.push_back(Attribute::InReg);
9909 
9910   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9911                             Attrs);
9912 }
9913 
9914 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9915 /// implementation, which just calls LowerCall.
9916 /// FIXME: When all targets are
9917 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9918 std::pair<SDValue, SDValue>
9919 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9920   // Handle the incoming return values from the call.
9921   CLI.Ins.clear();
9922   Type *OrigRetTy = CLI.RetTy;
9923   SmallVector<EVT, 4> RetTys;
9924   SmallVector<uint64_t, 4> Offsets;
9925   auto &DL = CLI.DAG.getDataLayout();
9926   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0);
9927 
9928   if (CLI.IsPostTypeLegalization) {
9929     // If we are lowering a libcall after legalization, split the return type.
9930     SmallVector<EVT, 4> OldRetTys;
9931     SmallVector<uint64_t, 4> OldOffsets;
9932     RetTys.swap(OldRetTys);
9933     Offsets.swap(OldOffsets);
9934 
9935     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9936       EVT RetVT = OldRetTys[i];
9937       uint64_t Offset = OldOffsets[i];
9938       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9939       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9940       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9941       RetTys.append(NumRegs, RegisterVT);
9942       for (unsigned j = 0; j != NumRegs; ++j)
9943         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9944     }
9945   }
9946 
9947   SmallVector<ISD::OutputArg, 4> Outs;
9948   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9949 
9950   bool CanLowerReturn =
9951       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9952                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9953 
9954   SDValue DemoteStackSlot;
9955   int DemoteStackIdx = -100;
9956   if (!CanLowerReturn) {
9957     // FIXME: equivalent assert?
9958     // assert(!CS.hasInAllocaArgument() &&
9959     //        "sret demotion is incompatible with inalloca");
9960     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9961     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9962     MachineFunction &MF = CLI.DAG.getMachineFunction();
9963     DemoteStackIdx =
9964         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9965     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9966                                               DL.getAllocaAddrSpace());
9967 
9968     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9969     ArgListEntry Entry;
9970     Entry.Node = DemoteStackSlot;
9971     Entry.Ty = StackSlotPtrType;
9972     Entry.IsSExt = false;
9973     Entry.IsZExt = false;
9974     Entry.IsInReg = false;
9975     Entry.IsSRet = true;
9976     Entry.IsNest = false;
9977     Entry.IsByVal = false;
9978     Entry.IsByRef = false;
9979     Entry.IsReturned = false;
9980     Entry.IsSwiftSelf = false;
9981     Entry.IsSwiftAsync = false;
9982     Entry.IsSwiftError = false;
9983     Entry.IsCFGuardTarget = false;
9984     Entry.Alignment = Alignment;
9985     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9986     CLI.NumFixedArgs += 1;
9987     CLI.getArgs()[0].IndirectType = CLI.RetTy;
9988     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9989 
9990     // sret demotion isn't compatible with tail-calls, since the sret argument
9991     // points into the callers stack frame.
9992     CLI.IsTailCall = false;
9993   } else {
9994     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9995         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9996     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9997       ISD::ArgFlagsTy Flags;
9998       if (NeedsRegBlock) {
9999         Flags.setInConsecutiveRegs();
10000         if (I == RetTys.size() - 1)
10001           Flags.setInConsecutiveRegsLast();
10002       }
10003       EVT VT = RetTys[I];
10004       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10005                                                      CLI.CallConv, VT);
10006       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10007                                                        CLI.CallConv, VT);
10008       for (unsigned i = 0; i != NumRegs; ++i) {
10009         ISD::InputArg MyFlags;
10010         MyFlags.Flags = Flags;
10011         MyFlags.VT = RegisterVT;
10012         MyFlags.ArgVT = VT;
10013         MyFlags.Used = CLI.IsReturnValueUsed;
10014         if (CLI.RetTy->isPointerTy()) {
10015           MyFlags.Flags.setPointer();
10016           MyFlags.Flags.setPointerAddrSpace(
10017               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10018         }
10019         if (CLI.RetSExt)
10020           MyFlags.Flags.setSExt();
10021         if (CLI.RetZExt)
10022           MyFlags.Flags.setZExt();
10023         if (CLI.IsInReg)
10024           MyFlags.Flags.setInReg();
10025         CLI.Ins.push_back(MyFlags);
10026       }
10027     }
10028   }
10029 
10030   // We push in swifterror return as the last element of CLI.Ins.
10031   ArgListTy &Args = CLI.getArgs();
10032   if (supportSwiftError()) {
10033     for (const ArgListEntry &Arg : Args) {
10034       if (Arg.IsSwiftError) {
10035         ISD::InputArg MyFlags;
10036         MyFlags.VT = getPointerTy(DL);
10037         MyFlags.ArgVT = EVT(getPointerTy(DL));
10038         MyFlags.Flags.setSwiftError();
10039         CLI.Ins.push_back(MyFlags);
10040       }
10041     }
10042   }
10043 
10044   // Handle all of the outgoing arguments.
10045   CLI.Outs.clear();
10046   CLI.OutVals.clear();
10047   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10048     SmallVector<EVT, 4> ValueVTs;
10049     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10050     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10051     Type *FinalType = Args[i].Ty;
10052     if (Args[i].IsByVal)
10053       FinalType = Args[i].IndirectType;
10054     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10055         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10056     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10057          ++Value) {
10058       EVT VT = ValueVTs[Value];
10059       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10060       SDValue Op = SDValue(Args[i].Node.getNode(),
10061                            Args[i].Node.getResNo() + Value);
10062       ISD::ArgFlagsTy Flags;
10063 
10064       // Certain targets (such as MIPS), may have a different ABI alignment
10065       // for a type depending on the context. Give the target a chance to
10066       // specify the alignment it wants.
10067       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10068       Flags.setOrigAlign(OriginalAlignment);
10069 
10070       if (Args[i].Ty->isPointerTy()) {
10071         Flags.setPointer();
10072         Flags.setPointerAddrSpace(
10073             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10074       }
10075       if (Args[i].IsZExt)
10076         Flags.setZExt();
10077       if (Args[i].IsSExt)
10078         Flags.setSExt();
10079       if (Args[i].IsInReg) {
10080         // If we are using vectorcall calling convention, a structure that is
10081         // passed InReg - is surely an HVA
10082         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10083             isa<StructType>(FinalType)) {
10084           // The first value of a structure is marked
10085           if (0 == Value)
10086             Flags.setHvaStart();
10087           Flags.setHva();
10088         }
10089         // Set InReg Flag
10090         Flags.setInReg();
10091       }
10092       if (Args[i].IsSRet)
10093         Flags.setSRet();
10094       if (Args[i].IsSwiftSelf)
10095         Flags.setSwiftSelf();
10096       if (Args[i].IsSwiftAsync)
10097         Flags.setSwiftAsync();
10098       if (Args[i].IsSwiftError)
10099         Flags.setSwiftError();
10100       if (Args[i].IsCFGuardTarget)
10101         Flags.setCFGuardTarget();
10102       if (Args[i].IsByVal)
10103         Flags.setByVal();
10104       if (Args[i].IsByRef)
10105         Flags.setByRef();
10106       if (Args[i].IsPreallocated) {
10107         Flags.setPreallocated();
10108         // Set the byval flag for CCAssignFn callbacks that don't know about
10109         // preallocated.  This way we can know how many bytes we should've
10110         // allocated and how many bytes a callee cleanup function will pop.  If
10111         // we port preallocated to more targets, we'll have to add custom
10112         // preallocated handling in the various CC lowering callbacks.
10113         Flags.setByVal();
10114       }
10115       if (Args[i].IsInAlloca) {
10116         Flags.setInAlloca();
10117         // Set the byval flag for CCAssignFn callbacks that don't know about
10118         // inalloca.  This way we can know how many bytes we should've allocated
10119         // and how many bytes a callee cleanup function will pop.  If we port
10120         // inalloca to more targets, we'll have to add custom inalloca handling
10121         // in the various CC lowering callbacks.
10122         Flags.setByVal();
10123       }
10124       Align MemAlign;
10125       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10126         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10127         Flags.setByValSize(FrameSize);
10128 
10129         // info is not there but there are cases it cannot get right.
10130         if (auto MA = Args[i].Alignment)
10131           MemAlign = *MA;
10132         else
10133           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10134       } else if (auto MA = Args[i].Alignment) {
10135         MemAlign = *MA;
10136       } else {
10137         MemAlign = OriginalAlignment;
10138       }
10139       Flags.setMemAlign(MemAlign);
10140       if (Args[i].IsNest)
10141         Flags.setNest();
10142       if (NeedsRegBlock)
10143         Flags.setInConsecutiveRegs();
10144 
10145       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10146                                                  CLI.CallConv, VT);
10147       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10148                                                         CLI.CallConv, VT);
10149       SmallVector<SDValue, 4> Parts(NumParts);
10150       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10151 
10152       if (Args[i].IsSExt)
10153         ExtendKind = ISD::SIGN_EXTEND;
10154       else if (Args[i].IsZExt)
10155         ExtendKind = ISD::ZERO_EXTEND;
10156 
10157       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10158       // for now.
10159       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10160           CanLowerReturn) {
10161         assert((CLI.RetTy == Args[i].Ty ||
10162                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10163                  CLI.RetTy->getPointerAddressSpace() ==
10164                      Args[i].Ty->getPointerAddressSpace())) &&
10165                RetTys.size() == NumValues && "unexpected use of 'returned'");
10166         // Before passing 'returned' to the target lowering code, ensure that
10167         // either the register MVT and the actual EVT are the same size or that
10168         // the return value and argument are extended in the same way; in these
10169         // cases it's safe to pass the argument register value unchanged as the
10170         // return register value (although it's at the target's option whether
10171         // to do so)
10172         // TODO: allow code generation to take advantage of partially preserved
10173         // registers rather than clobbering the entire register when the
10174         // parameter extension method is not compatible with the return
10175         // extension method
10176         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10177             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10178              CLI.RetZExt == Args[i].IsZExt))
10179           Flags.setReturned();
10180       }
10181 
10182       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10183                      CLI.CallConv, ExtendKind);
10184 
10185       for (unsigned j = 0; j != NumParts; ++j) {
10186         // if it isn't first piece, alignment must be 1
10187         // For scalable vectors the scalable part is currently handled
10188         // by individual targets, so we just use the known minimum size here.
10189         ISD::OutputArg MyFlags(
10190             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10191             i < CLI.NumFixedArgs, i,
10192             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10193         if (NumParts > 1 && j == 0)
10194           MyFlags.Flags.setSplit();
10195         else if (j != 0) {
10196           MyFlags.Flags.setOrigAlign(Align(1));
10197           if (j == NumParts - 1)
10198             MyFlags.Flags.setSplitEnd();
10199         }
10200 
10201         CLI.Outs.push_back(MyFlags);
10202         CLI.OutVals.push_back(Parts[j]);
10203       }
10204 
10205       if (NeedsRegBlock && Value == NumValues - 1)
10206         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10207     }
10208   }
10209 
10210   SmallVector<SDValue, 4> InVals;
10211   CLI.Chain = LowerCall(CLI, InVals);
10212 
10213   // Update CLI.InVals to use outside of this function.
10214   CLI.InVals = InVals;
10215 
10216   // Verify that the target's LowerCall behaved as expected.
10217   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10218          "LowerCall didn't return a valid chain!");
10219   assert((!CLI.IsTailCall || InVals.empty()) &&
10220          "LowerCall emitted a return value for a tail call!");
10221   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10222          "LowerCall didn't emit the correct number of values!");
10223 
10224   // For a tail call, the return value is merely live-out and there aren't
10225   // any nodes in the DAG representing it. Return a special value to
10226   // indicate that a tail call has been emitted and no more Instructions
10227   // should be processed in the current block.
10228   if (CLI.IsTailCall) {
10229     CLI.DAG.setRoot(CLI.Chain);
10230     return std::make_pair(SDValue(), SDValue());
10231   }
10232 
10233 #ifndef NDEBUG
10234   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10235     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10236     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10237            "LowerCall emitted a value with the wrong type!");
10238   }
10239 #endif
10240 
10241   SmallVector<SDValue, 4> ReturnValues;
10242   if (!CanLowerReturn) {
10243     // The instruction result is the result of loading from the
10244     // hidden sret parameter.
10245     SmallVector<EVT, 1> PVTs;
10246     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
10247 
10248     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10249     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10250     EVT PtrVT = PVTs[0];
10251 
10252     unsigned NumValues = RetTys.size();
10253     ReturnValues.resize(NumValues);
10254     SmallVector<SDValue, 4> Chains(NumValues);
10255 
10256     // An aggregate return value cannot wrap around the address space, so
10257     // offsets to its parts don't wrap either.
10258     SDNodeFlags Flags;
10259     Flags.setNoUnsignedWrap(true);
10260 
10261     MachineFunction &MF = CLI.DAG.getMachineFunction();
10262     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10263     for (unsigned i = 0; i < NumValues; ++i) {
10264       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10265                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10266                                                         PtrVT), Flags);
10267       SDValue L = CLI.DAG.getLoad(
10268           RetTys[i], CLI.DL, CLI.Chain, Add,
10269           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10270                                             DemoteStackIdx, Offsets[i]),
10271           HiddenSRetAlign);
10272       ReturnValues[i] = L;
10273       Chains[i] = L.getValue(1);
10274     }
10275 
10276     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10277   } else {
10278     // Collect the legal value parts into potentially illegal values
10279     // that correspond to the original function's return values.
10280     std::optional<ISD::NodeType> AssertOp;
10281     if (CLI.RetSExt)
10282       AssertOp = ISD::AssertSext;
10283     else if (CLI.RetZExt)
10284       AssertOp = ISD::AssertZext;
10285     unsigned CurReg = 0;
10286     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10287       EVT VT = RetTys[I];
10288       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10289                                                      CLI.CallConv, VT);
10290       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10291                                                        CLI.CallConv, VT);
10292 
10293       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10294                                               NumRegs, RegisterVT, VT, nullptr,
10295                                               CLI.CallConv, AssertOp));
10296       CurReg += NumRegs;
10297     }
10298 
10299     // For a function returning void, there is no return value. We can't create
10300     // such a node, so we just return a null return value in that case. In
10301     // that case, nothing will actually look at the value.
10302     if (ReturnValues.empty())
10303       return std::make_pair(SDValue(), CLI.Chain);
10304   }
10305 
10306   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10307                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10308   return std::make_pair(Res, CLI.Chain);
10309 }
10310 
10311 /// Places new result values for the node in Results (their number
10312 /// and types must exactly match those of the original return values of
10313 /// the node), or leaves Results empty, which indicates that the node is not
10314 /// to be custom lowered after all.
10315 void TargetLowering::LowerOperationWrapper(SDNode *N,
10316                                            SmallVectorImpl<SDValue> &Results,
10317                                            SelectionDAG &DAG) const {
10318   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10319 
10320   if (!Res.getNode())
10321     return;
10322 
10323   // If the original node has one result, take the return value from
10324   // LowerOperation as is. It might not be result number 0.
10325   if (N->getNumValues() == 1) {
10326     Results.push_back(Res);
10327     return;
10328   }
10329 
10330   // If the original node has multiple results, then the return node should
10331   // have the same number of results.
10332   assert((N->getNumValues() == Res->getNumValues()) &&
10333       "Lowering returned the wrong number of results!");
10334 
10335   // Places new result values base on N result number.
10336   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10337     Results.push_back(Res.getValue(I));
10338 }
10339 
10340 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10341   llvm_unreachable("LowerOperation not implemented for this target!");
10342 }
10343 
10344 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10345                                                      unsigned Reg,
10346                                                      ISD::NodeType ExtendType) {
10347   SDValue Op = getNonRegisterValue(V);
10348   assert((Op.getOpcode() != ISD::CopyFromReg ||
10349           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10350          "Copy from a reg to the same reg!");
10351   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10352 
10353   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10354   // If this is an InlineAsm we have to match the registers required, not the
10355   // notional registers required by the type.
10356 
10357   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10358                    std::nullopt); // This is not an ABI copy.
10359   SDValue Chain = DAG.getEntryNode();
10360 
10361   if (ExtendType == ISD::ANY_EXTEND) {
10362     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10363     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10364       ExtendType = PreferredExtendIt->second;
10365   }
10366   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10367   PendingExports.push_back(Chain);
10368 }
10369 
10370 #include "llvm/CodeGen/SelectionDAGISel.h"
10371 
10372 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10373 /// entry block, return true.  This includes arguments used by switches, since
10374 /// the switch may expand into multiple basic blocks.
10375 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10376   // With FastISel active, we may be splitting blocks, so force creation
10377   // of virtual registers for all non-dead arguments.
10378   if (FastISel)
10379     return A->use_empty();
10380 
10381   const BasicBlock &Entry = A->getParent()->front();
10382   for (const User *U : A->users())
10383     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10384       return false;  // Use not in entry block.
10385 
10386   return true;
10387 }
10388 
10389 using ArgCopyElisionMapTy =
10390     DenseMap<const Argument *,
10391              std::pair<const AllocaInst *, const StoreInst *>>;
10392 
10393 /// Scan the entry block of the function in FuncInfo for arguments that look
10394 /// like copies into a local alloca. Record any copied arguments in
10395 /// ArgCopyElisionCandidates.
10396 static void
10397 findArgumentCopyElisionCandidates(const DataLayout &DL,
10398                                   FunctionLoweringInfo *FuncInfo,
10399                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10400   // Record the state of every static alloca used in the entry block. Argument
10401   // allocas are all used in the entry block, so we need approximately as many
10402   // entries as we have arguments.
10403   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10404   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10405   unsigned NumArgs = FuncInfo->Fn->arg_size();
10406   StaticAllocas.reserve(NumArgs * 2);
10407 
10408   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10409     if (!V)
10410       return nullptr;
10411     V = V->stripPointerCasts();
10412     const auto *AI = dyn_cast<AllocaInst>(V);
10413     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10414       return nullptr;
10415     auto Iter = StaticAllocas.insert({AI, Unknown});
10416     return &Iter.first->second;
10417   };
10418 
10419   // Look for stores of arguments to static allocas. Look through bitcasts and
10420   // GEPs to handle type coercions, as long as the alloca is fully initialized
10421   // by the store. Any non-store use of an alloca escapes it and any subsequent
10422   // unanalyzed store might write it.
10423   // FIXME: Handle structs initialized with multiple stores.
10424   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10425     // Look for stores, and handle non-store uses conservatively.
10426     const auto *SI = dyn_cast<StoreInst>(&I);
10427     if (!SI) {
10428       // We will look through cast uses, so ignore them completely.
10429       if (I.isCast())
10430         continue;
10431       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10432       // to allocas.
10433       if (I.isDebugOrPseudoInst())
10434         continue;
10435       // This is an unknown instruction. Assume it escapes or writes to all
10436       // static alloca operands.
10437       for (const Use &U : I.operands()) {
10438         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10439           *Info = StaticAllocaInfo::Clobbered;
10440       }
10441       continue;
10442     }
10443 
10444     // If the stored value is a static alloca, mark it as escaped.
10445     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10446       *Info = StaticAllocaInfo::Clobbered;
10447 
10448     // Check if the destination is a static alloca.
10449     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10450     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10451     if (!Info)
10452       continue;
10453     const AllocaInst *AI = cast<AllocaInst>(Dst);
10454 
10455     // Skip allocas that have been initialized or clobbered.
10456     if (*Info != StaticAllocaInfo::Unknown)
10457       continue;
10458 
10459     // Check if the stored value is an argument, and that this store fully
10460     // initializes the alloca.
10461     // If the argument type has padding bits we can't directly forward a pointer
10462     // as the upper bits may contain garbage.
10463     // Don't elide copies from the same argument twice.
10464     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10465     const auto *Arg = dyn_cast<Argument>(Val);
10466     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10467         Arg->getType()->isEmptyTy() ||
10468         DL.getTypeStoreSize(Arg->getType()) !=
10469             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10470         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10471         ArgCopyElisionCandidates.count(Arg)) {
10472       *Info = StaticAllocaInfo::Clobbered;
10473       continue;
10474     }
10475 
10476     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10477                       << '\n');
10478 
10479     // Mark this alloca and store for argument copy elision.
10480     *Info = StaticAllocaInfo::Elidable;
10481     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10482 
10483     // Stop scanning if we've seen all arguments. This will happen early in -O0
10484     // builds, which is useful, because -O0 builds have large entry blocks and
10485     // many allocas.
10486     if (ArgCopyElisionCandidates.size() == NumArgs)
10487       break;
10488   }
10489 }
10490 
10491 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10492 /// ArgVal is a load from a suitable fixed stack object.
10493 static void tryToElideArgumentCopy(
10494     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10495     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10496     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10497     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10498     SDValue ArgVal, bool &ArgHasUses) {
10499   // Check if this is a load from a fixed stack object.
10500   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10501   if (!LNode)
10502     return;
10503   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10504   if (!FINode)
10505     return;
10506 
10507   // Check that the fixed stack object is the right size and alignment.
10508   // Look at the alignment that the user wrote on the alloca instead of looking
10509   // at the stack object.
10510   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10511   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10512   const AllocaInst *AI = ArgCopyIter->second.first;
10513   int FixedIndex = FINode->getIndex();
10514   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10515   int OldIndex = AllocaIndex;
10516   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10517   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10518     LLVM_DEBUG(
10519         dbgs() << "  argument copy elision failed due to bad fixed stack "
10520                   "object size\n");
10521     return;
10522   }
10523   Align RequiredAlignment = AI->getAlign();
10524   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10525     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10526                          "greater than stack argument alignment ("
10527                       << DebugStr(RequiredAlignment) << " vs "
10528                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10529     return;
10530   }
10531 
10532   // Perform the elision. Delete the old stack object and replace its only use
10533   // in the variable info map. Mark the stack object as mutable.
10534   LLVM_DEBUG({
10535     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10536            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10537            << '\n';
10538   });
10539   MFI.RemoveStackObject(OldIndex);
10540   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10541   AllocaIndex = FixedIndex;
10542   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10543   Chains.push_back(ArgVal.getValue(1));
10544 
10545   // Avoid emitting code for the store implementing the copy.
10546   const StoreInst *SI = ArgCopyIter->second.second;
10547   ElidedArgCopyInstrs.insert(SI);
10548 
10549   // Check for uses of the argument again so that we can avoid exporting ArgVal
10550   // if it is't used by anything other than the store.
10551   for (const Value *U : Arg.users()) {
10552     if (U != SI) {
10553       ArgHasUses = true;
10554       break;
10555     }
10556   }
10557 }
10558 
10559 void SelectionDAGISel::LowerArguments(const Function &F) {
10560   SelectionDAG &DAG = SDB->DAG;
10561   SDLoc dl = SDB->getCurSDLoc();
10562   const DataLayout &DL = DAG.getDataLayout();
10563   SmallVector<ISD::InputArg, 16> Ins;
10564 
10565   // In Naked functions we aren't going to save any registers.
10566   if (F.hasFnAttribute(Attribute::Naked))
10567     return;
10568 
10569   if (!FuncInfo->CanLowerReturn) {
10570     // Put in an sret pointer parameter before all the other parameters.
10571     SmallVector<EVT, 1> ValueVTs;
10572     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10573                     F.getReturnType()->getPointerTo(
10574                         DAG.getDataLayout().getAllocaAddrSpace()),
10575                     ValueVTs);
10576 
10577     // NOTE: Assuming that a pointer will never break down to more than one VT
10578     // or one register.
10579     ISD::ArgFlagsTy Flags;
10580     Flags.setSRet();
10581     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10582     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10583                          ISD::InputArg::NoArgIndex, 0);
10584     Ins.push_back(RetArg);
10585   }
10586 
10587   // Look for stores of arguments to static allocas. Mark such arguments with a
10588   // flag to ask the target to give us the memory location of that argument if
10589   // available.
10590   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10591   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10592                                     ArgCopyElisionCandidates);
10593 
10594   // Set up the incoming argument description vector.
10595   for (const Argument &Arg : F.args()) {
10596     unsigned ArgNo = Arg.getArgNo();
10597     SmallVector<EVT, 4> ValueVTs;
10598     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10599     bool isArgValueUsed = !Arg.use_empty();
10600     unsigned PartBase = 0;
10601     Type *FinalType = Arg.getType();
10602     if (Arg.hasAttribute(Attribute::ByVal))
10603       FinalType = Arg.getParamByValType();
10604     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10605         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10606     for (unsigned Value = 0, NumValues = ValueVTs.size();
10607          Value != NumValues; ++Value) {
10608       EVT VT = ValueVTs[Value];
10609       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10610       ISD::ArgFlagsTy Flags;
10611 
10612 
10613       if (Arg.getType()->isPointerTy()) {
10614         Flags.setPointer();
10615         Flags.setPointerAddrSpace(
10616             cast<PointerType>(Arg.getType())->getAddressSpace());
10617       }
10618       if (Arg.hasAttribute(Attribute::ZExt))
10619         Flags.setZExt();
10620       if (Arg.hasAttribute(Attribute::SExt))
10621         Flags.setSExt();
10622       if (Arg.hasAttribute(Attribute::InReg)) {
10623         // If we are using vectorcall calling convention, a structure that is
10624         // passed InReg - is surely an HVA
10625         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10626             isa<StructType>(Arg.getType())) {
10627           // The first value of a structure is marked
10628           if (0 == Value)
10629             Flags.setHvaStart();
10630           Flags.setHva();
10631         }
10632         // Set InReg Flag
10633         Flags.setInReg();
10634       }
10635       if (Arg.hasAttribute(Attribute::StructRet))
10636         Flags.setSRet();
10637       if (Arg.hasAttribute(Attribute::SwiftSelf))
10638         Flags.setSwiftSelf();
10639       if (Arg.hasAttribute(Attribute::SwiftAsync))
10640         Flags.setSwiftAsync();
10641       if (Arg.hasAttribute(Attribute::SwiftError))
10642         Flags.setSwiftError();
10643       if (Arg.hasAttribute(Attribute::ByVal))
10644         Flags.setByVal();
10645       if (Arg.hasAttribute(Attribute::ByRef))
10646         Flags.setByRef();
10647       if (Arg.hasAttribute(Attribute::InAlloca)) {
10648         Flags.setInAlloca();
10649         // Set the byval flag for CCAssignFn callbacks that don't know about
10650         // inalloca.  This way we can know how many bytes we should've allocated
10651         // and how many bytes a callee cleanup function will pop.  If we port
10652         // inalloca to more targets, we'll have to add custom inalloca handling
10653         // in the various CC lowering callbacks.
10654         Flags.setByVal();
10655       }
10656       if (Arg.hasAttribute(Attribute::Preallocated)) {
10657         Flags.setPreallocated();
10658         // Set the byval flag for CCAssignFn callbacks that don't know about
10659         // preallocated.  This way we can know how many bytes we should've
10660         // allocated and how many bytes a callee cleanup function will pop.  If
10661         // we port preallocated to more targets, we'll have to add custom
10662         // preallocated handling in the various CC lowering callbacks.
10663         Flags.setByVal();
10664       }
10665 
10666       // Certain targets (such as MIPS), may have a different ABI alignment
10667       // for a type depending on the context. Give the target a chance to
10668       // specify the alignment it wants.
10669       const Align OriginalAlignment(
10670           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10671       Flags.setOrigAlign(OriginalAlignment);
10672 
10673       Align MemAlign;
10674       Type *ArgMemTy = nullptr;
10675       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10676           Flags.isByRef()) {
10677         if (!ArgMemTy)
10678           ArgMemTy = Arg.getPointeeInMemoryValueType();
10679 
10680         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10681 
10682         // For in-memory arguments, size and alignment should be passed from FE.
10683         // BE will guess if this info is not there but there are cases it cannot
10684         // get right.
10685         if (auto ParamAlign = Arg.getParamStackAlign())
10686           MemAlign = *ParamAlign;
10687         else if ((ParamAlign = Arg.getParamAlign()))
10688           MemAlign = *ParamAlign;
10689         else
10690           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10691         if (Flags.isByRef())
10692           Flags.setByRefSize(MemSize);
10693         else
10694           Flags.setByValSize(MemSize);
10695       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10696         MemAlign = *ParamAlign;
10697       } else {
10698         MemAlign = OriginalAlignment;
10699       }
10700       Flags.setMemAlign(MemAlign);
10701 
10702       if (Arg.hasAttribute(Attribute::Nest))
10703         Flags.setNest();
10704       if (NeedsRegBlock)
10705         Flags.setInConsecutiveRegs();
10706       if (ArgCopyElisionCandidates.count(&Arg))
10707         Flags.setCopyElisionCandidate();
10708       if (Arg.hasAttribute(Attribute::Returned))
10709         Flags.setReturned();
10710 
10711       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10712           *CurDAG->getContext(), F.getCallingConv(), VT);
10713       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10714           *CurDAG->getContext(), F.getCallingConv(), VT);
10715       for (unsigned i = 0; i != NumRegs; ++i) {
10716         // For scalable vectors, use the minimum size; individual targets
10717         // are responsible for handling scalable vector arguments and
10718         // return values.
10719         ISD::InputArg MyFlags(
10720             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
10721             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
10722         if (NumRegs > 1 && i == 0)
10723           MyFlags.Flags.setSplit();
10724         // if it isn't first piece, alignment must be 1
10725         else if (i > 0) {
10726           MyFlags.Flags.setOrigAlign(Align(1));
10727           if (i == NumRegs - 1)
10728             MyFlags.Flags.setSplitEnd();
10729         }
10730         Ins.push_back(MyFlags);
10731       }
10732       if (NeedsRegBlock && Value == NumValues - 1)
10733         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10734       PartBase += VT.getStoreSize().getKnownMinValue();
10735     }
10736   }
10737 
10738   // Call the target to set up the argument values.
10739   SmallVector<SDValue, 8> InVals;
10740   SDValue NewRoot = TLI->LowerFormalArguments(
10741       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10742 
10743   // Verify that the target's LowerFormalArguments behaved as expected.
10744   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10745          "LowerFormalArguments didn't return a valid chain!");
10746   assert(InVals.size() == Ins.size() &&
10747          "LowerFormalArguments didn't emit the correct number of values!");
10748   LLVM_DEBUG({
10749     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10750       assert(InVals[i].getNode() &&
10751              "LowerFormalArguments emitted a null value!");
10752       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10753              "LowerFormalArguments emitted a value with the wrong type!");
10754     }
10755   });
10756 
10757   // Update the DAG with the new chain value resulting from argument lowering.
10758   DAG.setRoot(NewRoot);
10759 
10760   // Set up the argument values.
10761   unsigned i = 0;
10762   if (!FuncInfo->CanLowerReturn) {
10763     // Create a virtual register for the sret pointer, and put in a copy
10764     // from the sret argument into it.
10765     SmallVector<EVT, 1> ValueVTs;
10766     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10767                     F.getReturnType()->getPointerTo(
10768                         DAG.getDataLayout().getAllocaAddrSpace()),
10769                     ValueVTs);
10770     MVT VT = ValueVTs[0].getSimpleVT();
10771     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10772     std::optional<ISD::NodeType> AssertOp;
10773     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10774                                         nullptr, F.getCallingConv(), AssertOp);
10775 
10776     MachineFunction& MF = SDB->DAG.getMachineFunction();
10777     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10778     Register SRetReg =
10779         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10780     FuncInfo->DemoteRegister = SRetReg;
10781     NewRoot =
10782         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10783     DAG.setRoot(NewRoot);
10784 
10785     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10786     ++i;
10787   }
10788 
10789   SmallVector<SDValue, 4> Chains;
10790   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10791   for (const Argument &Arg : F.args()) {
10792     SmallVector<SDValue, 4> ArgValues;
10793     SmallVector<EVT, 4> ValueVTs;
10794     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10795     unsigned NumValues = ValueVTs.size();
10796     if (NumValues == 0)
10797       continue;
10798 
10799     bool ArgHasUses = !Arg.use_empty();
10800 
10801     // Elide the copying store if the target loaded this argument from a
10802     // suitable fixed stack object.
10803     if (Ins[i].Flags.isCopyElisionCandidate()) {
10804       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10805                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10806                              InVals[i], ArgHasUses);
10807     }
10808 
10809     // If this argument is unused then remember its value. It is used to generate
10810     // debugging information.
10811     bool isSwiftErrorArg =
10812         TLI->supportSwiftError() &&
10813         Arg.hasAttribute(Attribute::SwiftError);
10814     if (!ArgHasUses && !isSwiftErrorArg) {
10815       SDB->setUnusedArgValue(&Arg, InVals[i]);
10816 
10817       // Also remember any frame index for use in FastISel.
10818       if (FrameIndexSDNode *FI =
10819           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10820         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10821     }
10822 
10823     for (unsigned Val = 0; Val != NumValues; ++Val) {
10824       EVT VT = ValueVTs[Val];
10825       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10826                                                       F.getCallingConv(), VT);
10827       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10828           *CurDAG->getContext(), F.getCallingConv(), VT);
10829 
10830       // Even an apparent 'unused' swifterror argument needs to be returned. So
10831       // we do generate a copy for it that can be used on return from the
10832       // function.
10833       if (ArgHasUses || isSwiftErrorArg) {
10834         std::optional<ISD::NodeType> AssertOp;
10835         if (Arg.hasAttribute(Attribute::SExt))
10836           AssertOp = ISD::AssertSext;
10837         else if (Arg.hasAttribute(Attribute::ZExt))
10838           AssertOp = ISD::AssertZext;
10839 
10840         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10841                                              PartVT, VT, nullptr,
10842                                              F.getCallingConv(), AssertOp));
10843       }
10844 
10845       i += NumParts;
10846     }
10847 
10848     // We don't need to do anything else for unused arguments.
10849     if (ArgValues.empty())
10850       continue;
10851 
10852     // Note down frame index.
10853     if (FrameIndexSDNode *FI =
10854         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10855       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10856 
10857     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
10858                                      SDB->getCurSDLoc());
10859 
10860     SDB->setValue(&Arg, Res);
10861     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10862       // We want to associate the argument with the frame index, among
10863       // involved operands, that correspond to the lowest address. The
10864       // getCopyFromParts function, called earlier, is swapping the order of
10865       // the operands to BUILD_PAIR depending on endianness. The result of
10866       // that swapping is that the least significant bits of the argument will
10867       // be in the first operand of the BUILD_PAIR node, and the most
10868       // significant bits will be in the second operand.
10869       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10870       if (LoadSDNode *LNode =
10871           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10872         if (FrameIndexSDNode *FI =
10873             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10874           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10875     }
10876 
10877     // Analyses past this point are naive and don't expect an assertion.
10878     if (Res.getOpcode() == ISD::AssertZext)
10879       Res = Res.getOperand(0);
10880 
10881     // Update the SwiftErrorVRegDefMap.
10882     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10883       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10884       if (Register::isVirtualRegister(Reg))
10885         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10886                                    Reg);
10887     }
10888 
10889     // If this argument is live outside of the entry block, insert a copy from
10890     // wherever we got it to the vreg that other BB's will reference it as.
10891     if (Res.getOpcode() == ISD::CopyFromReg) {
10892       // If we can, though, try to skip creating an unnecessary vreg.
10893       // FIXME: This isn't very clean... it would be nice to make this more
10894       // general.
10895       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10896       if (Register::isVirtualRegister(Reg)) {
10897         FuncInfo->ValueMap[&Arg] = Reg;
10898         continue;
10899       }
10900     }
10901     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10902       FuncInfo->InitializeRegForValue(&Arg);
10903       SDB->CopyToExportRegsIfNeeded(&Arg);
10904     }
10905   }
10906 
10907   if (!Chains.empty()) {
10908     Chains.push_back(NewRoot);
10909     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10910   }
10911 
10912   DAG.setRoot(NewRoot);
10913 
10914   assert(i == InVals.size() && "Argument register count mismatch!");
10915 
10916   // If any argument copy elisions occurred and we have debug info, update the
10917   // stale frame indices used in the dbg.declare variable info table.
10918   if (!ArgCopyElisionFrameIndexMap.empty()) {
10919     for (MachineFunction::VariableDbgInfo &VI :
10920          MF->getInStackSlotVariableDbgInfo()) {
10921       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
10922       if (I != ArgCopyElisionFrameIndexMap.end())
10923         VI.updateStackSlot(I->second);
10924     }
10925   }
10926 
10927   // Finally, if the target has anything special to do, allow it to do so.
10928   emitFunctionEntryCode();
10929 }
10930 
10931 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10932 /// ensure constants are generated when needed.  Remember the virtual registers
10933 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10934 /// directly add them, because expansion might result in multiple MBB's for one
10935 /// BB.  As such, the start of the BB might correspond to a different MBB than
10936 /// the end.
10937 void
10938 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10939   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10940 
10941   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10942 
10943   // Check PHI nodes in successors that expect a value to be available from this
10944   // block.
10945   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
10946     if (!isa<PHINode>(SuccBB->begin())) continue;
10947     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10948 
10949     // If this terminator has multiple identical successors (common for
10950     // switches), only handle each succ once.
10951     if (!SuccsHandled.insert(SuccMBB).second)
10952       continue;
10953 
10954     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10955 
10956     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10957     // nodes and Machine PHI nodes, but the incoming operands have not been
10958     // emitted yet.
10959     for (const PHINode &PN : SuccBB->phis()) {
10960       // Ignore dead phi's.
10961       if (PN.use_empty())
10962         continue;
10963 
10964       // Skip empty types
10965       if (PN.getType()->isEmptyTy())
10966         continue;
10967 
10968       unsigned Reg;
10969       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10970 
10971       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
10972         unsigned &RegOut = ConstantsOut[C];
10973         if (RegOut == 0) {
10974           RegOut = FuncInfo.CreateRegs(C);
10975           // We need to zero/sign extend ConstantInt phi operands to match
10976           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
10977           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
10978           if (auto *CI = dyn_cast<ConstantInt>(C))
10979             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
10980                                                     : ISD::ZERO_EXTEND;
10981           CopyValueToVirtualRegister(C, RegOut, ExtendType);
10982         }
10983         Reg = RegOut;
10984       } else {
10985         DenseMap<const Value *, Register>::iterator I =
10986           FuncInfo.ValueMap.find(PHIOp);
10987         if (I != FuncInfo.ValueMap.end())
10988           Reg = I->second;
10989         else {
10990           assert(isa<AllocaInst>(PHIOp) &&
10991                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10992                  "Didn't codegen value into a register!??");
10993           Reg = FuncInfo.CreateRegs(PHIOp);
10994           CopyValueToVirtualRegister(PHIOp, Reg);
10995         }
10996       }
10997 
10998       // Remember that this register needs to added to the machine PHI node as
10999       // the input for this MBB.
11000       SmallVector<EVT, 4> ValueVTs;
11001       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11002       for (EVT VT : ValueVTs) {
11003         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11004         for (unsigned i = 0; i != NumRegisters; ++i)
11005           FuncInfo.PHINodesToUpdate.push_back(
11006               std::make_pair(&*MBBI++, Reg + i));
11007         Reg += NumRegisters;
11008       }
11009     }
11010   }
11011 
11012   ConstantsOut.clear();
11013 }
11014 
11015 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11016   MachineFunction::iterator I(MBB);
11017   if (++I == FuncInfo.MF->end())
11018     return nullptr;
11019   return &*I;
11020 }
11021 
11022 /// During lowering new call nodes can be created (such as memset, etc.).
11023 /// Those will become new roots of the current DAG, but complications arise
11024 /// when they are tail calls. In such cases, the call lowering will update
11025 /// the root, but the builder still needs to know that a tail call has been
11026 /// lowered in order to avoid generating an additional return.
11027 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11028   // If the node is null, we do have a tail call.
11029   if (MaybeTC.getNode() != nullptr)
11030     DAG.setRoot(MaybeTC);
11031   else
11032     HasTailCall = true;
11033 }
11034 
11035 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11036                                         MachineBasicBlock *SwitchMBB,
11037                                         MachineBasicBlock *DefaultMBB) {
11038   MachineFunction *CurMF = FuncInfo.MF;
11039   MachineBasicBlock *NextMBB = nullptr;
11040   MachineFunction::iterator BBI(W.MBB);
11041   if (++BBI != FuncInfo.MF->end())
11042     NextMBB = &*BBI;
11043 
11044   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11045 
11046   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11047 
11048   if (Size == 2 && W.MBB == SwitchMBB) {
11049     // If any two of the cases has the same destination, and if one value
11050     // is the same as the other, but has one bit unset that the other has set,
11051     // use bit manipulation to do two compares at once.  For example:
11052     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11053     // TODO: This could be extended to merge any 2 cases in switches with 3
11054     // cases.
11055     // TODO: Handle cases where W.CaseBB != SwitchBB.
11056     CaseCluster &Small = *W.FirstCluster;
11057     CaseCluster &Big = *W.LastCluster;
11058 
11059     if (Small.Low == Small.High && Big.Low == Big.High &&
11060         Small.MBB == Big.MBB) {
11061       const APInt &SmallValue = Small.Low->getValue();
11062       const APInt &BigValue = Big.Low->getValue();
11063 
11064       // Check that there is only one bit different.
11065       APInt CommonBit = BigValue ^ SmallValue;
11066       if (CommonBit.isPowerOf2()) {
11067         SDValue CondLHS = getValue(Cond);
11068         EVT VT = CondLHS.getValueType();
11069         SDLoc DL = getCurSDLoc();
11070 
11071         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11072                                  DAG.getConstant(CommonBit, DL, VT));
11073         SDValue Cond = DAG.getSetCC(
11074             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11075             ISD::SETEQ);
11076 
11077         // Update successor info.
11078         // Both Small and Big will jump to Small.BB, so we sum up the
11079         // probabilities.
11080         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11081         if (BPI)
11082           addSuccessorWithProb(
11083               SwitchMBB, DefaultMBB,
11084               // The default destination is the first successor in IR.
11085               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11086         else
11087           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11088 
11089         // Insert the true branch.
11090         SDValue BrCond =
11091             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11092                         DAG.getBasicBlock(Small.MBB));
11093         // Insert the false branch.
11094         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11095                              DAG.getBasicBlock(DefaultMBB));
11096 
11097         DAG.setRoot(BrCond);
11098         return;
11099       }
11100     }
11101   }
11102 
11103   if (TM.getOptLevel() != CodeGenOpt::None) {
11104     // Here, we order cases by probability so the most likely case will be
11105     // checked first. However, two clusters can have the same probability in
11106     // which case their relative ordering is non-deterministic. So we use Low
11107     // as a tie-breaker as clusters are guaranteed to never overlap.
11108     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11109                [](const CaseCluster &a, const CaseCluster &b) {
11110       return a.Prob != b.Prob ?
11111              a.Prob > b.Prob :
11112              a.Low->getValue().slt(b.Low->getValue());
11113     });
11114 
11115     // Rearrange the case blocks so that the last one falls through if possible
11116     // without changing the order of probabilities.
11117     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11118       --I;
11119       if (I->Prob > W.LastCluster->Prob)
11120         break;
11121       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11122         std::swap(*I, *W.LastCluster);
11123         break;
11124       }
11125     }
11126   }
11127 
11128   // Compute total probability.
11129   BranchProbability DefaultProb = W.DefaultProb;
11130   BranchProbability UnhandledProbs = DefaultProb;
11131   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11132     UnhandledProbs += I->Prob;
11133 
11134   MachineBasicBlock *CurMBB = W.MBB;
11135   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11136     bool FallthroughUnreachable = false;
11137     MachineBasicBlock *Fallthrough;
11138     if (I == W.LastCluster) {
11139       // For the last cluster, fall through to the default destination.
11140       Fallthrough = DefaultMBB;
11141       FallthroughUnreachable = isa<UnreachableInst>(
11142           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11143     } else {
11144       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11145       CurMF->insert(BBI, Fallthrough);
11146       // Put Cond in a virtual register to make it available from the new blocks.
11147       ExportFromCurrentBlock(Cond);
11148     }
11149     UnhandledProbs -= I->Prob;
11150 
11151     switch (I->Kind) {
11152       case CC_JumpTable: {
11153         // FIXME: Optimize away range check based on pivot comparisons.
11154         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11155         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11156 
11157         // The jump block hasn't been inserted yet; insert it here.
11158         MachineBasicBlock *JumpMBB = JT->MBB;
11159         CurMF->insert(BBI, JumpMBB);
11160 
11161         auto JumpProb = I->Prob;
11162         auto FallthroughProb = UnhandledProbs;
11163 
11164         // If the default statement is a target of the jump table, we evenly
11165         // distribute the default probability to successors of CurMBB. Also
11166         // update the probability on the edge from JumpMBB to Fallthrough.
11167         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11168                                               SE = JumpMBB->succ_end();
11169              SI != SE; ++SI) {
11170           if (*SI == DefaultMBB) {
11171             JumpProb += DefaultProb / 2;
11172             FallthroughProb -= DefaultProb / 2;
11173             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11174             JumpMBB->normalizeSuccProbs();
11175             break;
11176           }
11177         }
11178 
11179         if (FallthroughUnreachable)
11180           JTH->FallthroughUnreachable = true;
11181 
11182         if (!JTH->FallthroughUnreachable)
11183           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11184         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11185         CurMBB->normalizeSuccProbs();
11186 
11187         // The jump table header will be inserted in our current block, do the
11188         // range check, and fall through to our fallthrough block.
11189         JTH->HeaderBB = CurMBB;
11190         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11191 
11192         // If we're in the right place, emit the jump table header right now.
11193         if (CurMBB == SwitchMBB) {
11194           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11195           JTH->Emitted = true;
11196         }
11197         break;
11198       }
11199       case CC_BitTests: {
11200         // FIXME: Optimize away range check based on pivot comparisons.
11201         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11202 
11203         // The bit test blocks haven't been inserted yet; insert them here.
11204         for (BitTestCase &BTC : BTB->Cases)
11205           CurMF->insert(BBI, BTC.ThisBB);
11206 
11207         // Fill in fields of the BitTestBlock.
11208         BTB->Parent = CurMBB;
11209         BTB->Default = Fallthrough;
11210 
11211         BTB->DefaultProb = UnhandledProbs;
11212         // If the cases in bit test don't form a contiguous range, we evenly
11213         // distribute the probability on the edge to Fallthrough to two
11214         // successors of CurMBB.
11215         if (!BTB->ContiguousRange) {
11216           BTB->Prob += DefaultProb / 2;
11217           BTB->DefaultProb -= DefaultProb / 2;
11218         }
11219 
11220         if (FallthroughUnreachable)
11221           BTB->FallthroughUnreachable = true;
11222 
11223         // If we're in the right place, emit the bit test header right now.
11224         if (CurMBB == SwitchMBB) {
11225           visitBitTestHeader(*BTB, SwitchMBB);
11226           BTB->Emitted = true;
11227         }
11228         break;
11229       }
11230       case CC_Range: {
11231         const Value *RHS, *LHS, *MHS;
11232         ISD::CondCode CC;
11233         if (I->Low == I->High) {
11234           // Check Cond == I->Low.
11235           CC = ISD::SETEQ;
11236           LHS = Cond;
11237           RHS=I->Low;
11238           MHS = nullptr;
11239         } else {
11240           // Check I->Low <= Cond <= I->High.
11241           CC = ISD::SETLE;
11242           LHS = I->Low;
11243           MHS = Cond;
11244           RHS = I->High;
11245         }
11246 
11247         // If Fallthrough is unreachable, fold away the comparison.
11248         if (FallthroughUnreachable)
11249           CC = ISD::SETTRUE;
11250 
11251         // The false probability is the sum of all unhandled cases.
11252         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11253                      getCurSDLoc(), I->Prob, UnhandledProbs);
11254 
11255         if (CurMBB == SwitchMBB)
11256           visitSwitchCase(CB, SwitchMBB);
11257         else
11258           SL->SwitchCases.push_back(CB);
11259 
11260         break;
11261       }
11262     }
11263     CurMBB = Fallthrough;
11264   }
11265 }
11266 
11267 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11268                                               CaseClusterIt First,
11269                                               CaseClusterIt Last) {
11270   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11271     if (X.Prob != CC.Prob)
11272       return X.Prob > CC.Prob;
11273 
11274     // Ties are broken by comparing the case value.
11275     return X.Low->getValue().slt(CC.Low->getValue());
11276   });
11277 }
11278 
11279 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11280                                         const SwitchWorkListItem &W,
11281                                         Value *Cond,
11282                                         MachineBasicBlock *SwitchMBB) {
11283   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11284          "Clusters not sorted?");
11285 
11286   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11287 
11288   // Balance the tree based on branch probabilities to create a near-optimal (in
11289   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11290   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11291   CaseClusterIt LastLeft = W.FirstCluster;
11292   CaseClusterIt FirstRight = W.LastCluster;
11293   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11294   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11295 
11296   // Move LastLeft and FirstRight towards each other from opposite directions to
11297   // find a partitioning of the clusters which balances the probability on both
11298   // sides. If LeftProb and RightProb are equal, alternate which side is
11299   // taken to ensure 0-probability nodes are distributed evenly.
11300   unsigned I = 0;
11301   while (LastLeft + 1 < FirstRight) {
11302     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11303       LeftProb += (++LastLeft)->Prob;
11304     else
11305       RightProb += (--FirstRight)->Prob;
11306     I++;
11307   }
11308 
11309   while (true) {
11310     // Our binary search tree differs from a typical BST in that ours can have up
11311     // to three values in each leaf. The pivot selection above doesn't take that
11312     // into account, which means the tree might require more nodes and be less
11313     // efficient. We compensate for this here.
11314 
11315     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11316     unsigned NumRight = W.LastCluster - FirstRight + 1;
11317 
11318     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11319       // If one side has less than 3 clusters, and the other has more than 3,
11320       // consider taking a cluster from the other side.
11321 
11322       if (NumLeft < NumRight) {
11323         // Consider moving the first cluster on the right to the left side.
11324         CaseCluster &CC = *FirstRight;
11325         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11326         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11327         if (LeftSideRank <= RightSideRank) {
11328           // Moving the cluster to the left does not demote it.
11329           ++LastLeft;
11330           ++FirstRight;
11331           continue;
11332         }
11333       } else {
11334         assert(NumRight < NumLeft);
11335         // Consider moving the last element on the left to the right side.
11336         CaseCluster &CC = *LastLeft;
11337         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11338         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11339         if (RightSideRank <= LeftSideRank) {
11340           // Moving the cluster to the right does not demot it.
11341           --LastLeft;
11342           --FirstRight;
11343           continue;
11344         }
11345       }
11346     }
11347     break;
11348   }
11349 
11350   assert(LastLeft + 1 == FirstRight);
11351   assert(LastLeft >= W.FirstCluster);
11352   assert(FirstRight <= W.LastCluster);
11353 
11354   // Use the first element on the right as pivot since we will make less-than
11355   // comparisons against it.
11356   CaseClusterIt PivotCluster = FirstRight;
11357   assert(PivotCluster > W.FirstCluster);
11358   assert(PivotCluster <= W.LastCluster);
11359 
11360   CaseClusterIt FirstLeft = W.FirstCluster;
11361   CaseClusterIt LastRight = W.LastCluster;
11362 
11363   const ConstantInt *Pivot = PivotCluster->Low;
11364 
11365   // New blocks will be inserted immediately after the current one.
11366   MachineFunction::iterator BBI(W.MBB);
11367   ++BBI;
11368 
11369   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11370   // we can branch to its destination directly if it's squeezed exactly in
11371   // between the known lower bound and Pivot - 1.
11372   MachineBasicBlock *LeftMBB;
11373   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11374       FirstLeft->Low == W.GE &&
11375       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11376     LeftMBB = FirstLeft->MBB;
11377   } else {
11378     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11379     FuncInfo.MF->insert(BBI, LeftMBB);
11380     WorkList.push_back(
11381         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11382     // Put Cond in a virtual register to make it available from the new blocks.
11383     ExportFromCurrentBlock(Cond);
11384   }
11385 
11386   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11387   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11388   // directly if RHS.High equals the current upper bound.
11389   MachineBasicBlock *RightMBB;
11390   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11391       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11392     RightMBB = FirstRight->MBB;
11393   } else {
11394     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11395     FuncInfo.MF->insert(BBI, RightMBB);
11396     WorkList.push_back(
11397         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11398     // Put Cond in a virtual register to make it available from the new blocks.
11399     ExportFromCurrentBlock(Cond);
11400   }
11401 
11402   // Create the CaseBlock record that will be used to lower the branch.
11403   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11404                getCurSDLoc(), LeftProb, RightProb);
11405 
11406   if (W.MBB == SwitchMBB)
11407     visitSwitchCase(CB, SwitchMBB);
11408   else
11409     SL->SwitchCases.push_back(CB);
11410 }
11411 
11412 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11413 // from the swith statement.
11414 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11415                                             BranchProbability PeeledCaseProb) {
11416   if (PeeledCaseProb == BranchProbability::getOne())
11417     return BranchProbability::getZero();
11418   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11419 
11420   uint32_t Numerator = CaseProb.getNumerator();
11421   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11422   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11423 }
11424 
11425 // Try to peel the top probability case if it exceeds the threshold.
11426 // Return current MachineBasicBlock for the switch statement if the peeling
11427 // does not occur.
11428 // If the peeling is performed, return the newly created MachineBasicBlock
11429 // for the peeled switch statement. Also update Clusters to remove the peeled
11430 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11431 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11432     const SwitchInst &SI, CaseClusterVector &Clusters,
11433     BranchProbability &PeeledCaseProb) {
11434   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11435   // Don't perform if there is only one cluster or optimizing for size.
11436   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11437       TM.getOptLevel() == CodeGenOpt::None ||
11438       SwitchMBB->getParent()->getFunction().hasMinSize())
11439     return SwitchMBB;
11440 
11441   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11442   unsigned PeeledCaseIndex = 0;
11443   bool SwitchPeeled = false;
11444   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11445     CaseCluster &CC = Clusters[Index];
11446     if (CC.Prob < TopCaseProb)
11447       continue;
11448     TopCaseProb = CC.Prob;
11449     PeeledCaseIndex = Index;
11450     SwitchPeeled = true;
11451   }
11452   if (!SwitchPeeled)
11453     return SwitchMBB;
11454 
11455   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11456                     << TopCaseProb << "\n");
11457 
11458   // Record the MBB for the peeled switch statement.
11459   MachineFunction::iterator BBI(SwitchMBB);
11460   ++BBI;
11461   MachineBasicBlock *PeeledSwitchMBB =
11462       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11463   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11464 
11465   ExportFromCurrentBlock(SI.getCondition());
11466   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11467   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11468                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11469   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11470 
11471   Clusters.erase(PeeledCaseIt);
11472   for (CaseCluster &CC : Clusters) {
11473     LLVM_DEBUG(
11474         dbgs() << "Scale the probablity for one cluster, before scaling: "
11475                << CC.Prob << "\n");
11476     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11477     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11478   }
11479   PeeledCaseProb = TopCaseProb;
11480   return PeeledSwitchMBB;
11481 }
11482 
11483 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11484   // Extract cases from the switch.
11485   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11486   CaseClusterVector Clusters;
11487   Clusters.reserve(SI.getNumCases());
11488   for (auto I : SI.cases()) {
11489     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11490     const ConstantInt *CaseVal = I.getCaseValue();
11491     BranchProbability Prob =
11492         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11493             : BranchProbability(1, SI.getNumCases() + 1);
11494     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11495   }
11496 
11497   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11498 
11499   // Cluster adjacent cases with the same destination. We do this at all
11500   // optimization levels because it's cheap to do and will make codegen faster
11501   // if there are many clusters.
11502   sortAndRangeify(Clusters);
11503 
11504   // The branch probablity of the peeled case.
11505   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11506   MachineBasicBlock *PeeledSwitchMBB =
11507       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11508 
11509   // If there is only the default destination, jump there directly.
11510   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11511   if (Clusters.empty()) {
11512     assert(PeeledSwitchMBB == SwitchMBB);
11513     SwitchMBB->addSuccessor(DefaultMBB);
11514     if (DefaultMBB != NextBlock(SwitchMBB)) {
11515       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11516                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11517     }
11518     return;
11519   }
11520 
11521   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11522   SL->findBitTestClusters(Clusters, &SI);
11523 
11524   LLVM_DEBUG({
11525     dbgs() << "Case clusters: ";
11526     for (const CaseCluster &C : Clusters) {
11527       if (C.Kind == CC_JumpTable)
11528         dbgs() << "JT:";
11529       if (C.Kind == CC_BitTests)
11530         dbgs() << "BT:";
11531 
11532       C.Low->getValue().print(dbgs(), true);
11533       if (C.Low != C.High) {
11534         dbgs() << '-';
11535         C.High->getValue().print(dbgs(), true);
11536       }
11537       dbgs() << ' ';
11538     }
11539     dbgs() << '\n';
11540   });
11541 
11542   assert(!Clusters.empty());
11543   SwitchWorkList WorkList;
11544   CaseClusterIt First = Clusters.begin();
11545   CaseClusterIt Last = Clusters.end() - 1;
11546   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11547   // Scale the branchprobability for DefaultMBB if the peel occurs and
11548   // DefaultMBB is not replaced.
11549   if (PeeledCaseProb != BranchProbability::getZero() &&
11550       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11551     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11552   WorkList.push_back(
11553       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11554 
11555   while (!WorkList.empty()) {
11556     SwitchWorkListItem W = WorkList.pop_back_val();
11557     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11558 
11559     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11560         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11561       // For optimized builds, lower large range as a balanced binary tree.
11562       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11563       continue;
11564     }
11565 
11566     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11567   }
11568 }
11569 
11570 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11571   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11572   auto DL = getCurSDLoc();
11573   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11574   setValue(&I, DAG.getStepVector(DL, ResultVT));
11575 }
11576 
11577 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11578   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11579   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11580 
11581   SDLoc DL = getCurSDLoc();
11582   SDValue V = getValue(I.getOperand(0));
11583   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11584 
11585   if (VT.isScalableVector()) {
11586     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11587     return;
11588   }
11589 
11590   // Use VECTOR_SHUFFLE for the fixed-length vector
11591   // to maintain existing behavior.
11592   SmallVector<int, 8> Mask;
11593   unsigned NumElts = VT.getVectorMinNumElements();
11594   for (unsigned i = 0; i != NumElts; ++i)
11595     Mask.push_back(NumElts - 1 - i);
11596 
11597   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11598 }
11599 
11600 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
11601   auto DL = getCurSDLoc();
11602   SDValue InVec = getValue(I.getOperand(0));
11603   EVT OutVT =
11604       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
11605 
11606   unsigned OutNumElts = OutVT.getVectorMinNumElements();
11607 
11608   // ISD Node needs the input vectors split into two equal parts
11609   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11610                            DAG.getVectorIdxConstant(0, DL));
11611   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11612                            DAG.getVectorIdxConstant(OutNumElts, DL));
11613 
11614   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11615   // legalisation and combines.
11616   if (OutVT.isFixedLengthVector()) {
11617     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11618                                         createStrideMask(0, 2, OutNumElts));
11619     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11620                                        createStrideMask(1, 2, OutNumElts));
11621     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
11622     setValue(&I, Res);
11623     return;
11624   }
11625 
11626   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
11627                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
11628   setValue(&I, Res);
11629 }
11630 
11631 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
11632   auto DL = getCurSDLoc();
11633   EVT InVT = getValue(I.getOperand(0)).getValueType();
11634   SDValue InVec0 = getValue(I.getOperand(0));
11635   SDValue InVec1 = getValue(I.getOperand(1));
11636   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11637   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11638 
11639   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11640   // legalisation and combines.
11641   if (OutVT.isFixedLengthVector()) {
11642     unsigned NumElts = InVT.getVectorMinNumElements();
11643     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
11644     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
11645                                       createInterleaveMask(NumElts, 2)));
11646     return;
11647   }
11648 
11649   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
11650                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
11651   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
11652                     Res.getValue(1));
11653   setValue(&I, Res);
11654 }
11655 
11656 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11657   SmallVector<EVT, 4> ValueVTs;
11658   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11659                   ValueVTs);
11660   unsigned NumValues = ValueVTs.size();
11661   if (NumValues == 0) return;
11662 
11663   SmallVector<SDValue, 4> Values(NumValues);
11664   SDValue Op = getValue(I.getOperand(0));
11665 
11666   for (unsigned i = 0; i != NumValues; ++i)
11667     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11668                             SDValue(Op.getNode(), Op.getResNo() + i));
11669 
11670   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11671                            DAG.getVTList(ValueVTs), Values));
11672 }
11673 
11674 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11675   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11676   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11677 
11678   SDLoc DL = getCurSDLoc();
11679   SDValue V1 = getValue(I.getOperand(0));
11680   SDValue V2 = getValue(I.getOperand(1));
11681   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11682 
11683   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11684   if (VT.isScalableVector()) {
11685     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11686     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11687                              DAG.getConstant(Imm, DL, IdxVT)));
11688     return;
11689   }
11690 
11691   unsigned NumElts = VT.getVectorNumElements();
11692 
11693   uint64_t Idx = (NumElts + Imm) % NumElts;
11694 
11695   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11696   SmallVector<int, 8> Mask;
11697   for (unsigned i = 0; i < NumElts; ++i)
11698     Mask.push_back(Idx + i);
11699   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11700 }
11701 
11702 // Consider the following MIR after SelectionDAG, which produces output in
11703 // phyregs in the first case or virtregs in the second case.
11704 //
11705 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
11706 // %5:gr32 = COPY $ebx
11707 // %6:gr32 = COPY $edx
11708 // %1:gr32 = COPY %6:gr32
11709 // %0:gr32 = COPY %5:gr32
11710 //
11711 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
11712 // %1:gr32 = COPY %6:gr32
11713 // %0:gr32 = COPY %5:gr32
11714 //
11715 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
11716 // Given %1, we'd like to return $edx in the first case and %6 in the second.
11717 //
11718 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
11719 // to a single virtreg (such as %0). The remaining outputs monotonically
11720 // increase in virtreg number from there. If a callbr has no outputs, then it
11721 // should not have a corresponding callbr landingpad; in fact, the callbr
11722 // landingpad would not even be able to refer to such a callbr.
11723 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
11724   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
11725   // There is definitely at least one copy.
11726   assert(MI->getOpcode() == TargetOpcode::COPY &&
11727          "start of copy chain MUST be COPY");
11728   Reg = MI->getOperand(1).getReg();
11729   MI = MRI.def_begin(Reg)->getParent();
11730   // There may be an optional second copy.
11731   if (MI->getOpcode() == TargetOpcode::COPY) {
11732     assert(Reg.isVirtual() && "expected COPY of virtual register");
11733     Reg = MI->getOperand(1).getReg();
11734     assert(Reg.isPhysical() && "expected COPY of physical register");
11735     MI = MRI.def_begin(Reg)->getParent();
11736   }
11737   // The start of the chain must be an INLINEASM_BR.
11738   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
11739          "end of copy chain MUST be INLINEASM_BR");
11740   return Reg;
11741 }
11742 
11743 // We must do this walk rather than the simpler
11744 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
11745 // otherwise we will end up with copies of virtregs only valid along direct
11746 // edges.
11747 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
11748   SmallVector<EVT, 8> ResultVTs;
11749   SmallVector<SDValue, 8> ResultValues;
11750   const auto *CBR =
11751       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
11752 
11753   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11754   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
11755   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11756 
11757   unsigned InitialDef = FuncInfo.ValueMap[CBR];
11758   SDValue Chain = DAG.getRoot();
11759 
11760   // Re-parse the asm constraints string.
11761   TargetLowering::AsmOperandInfoVector TargetConstraints =
11762       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
11763   for (auto &T : TargetConstraints) {
11764     SDISelAsmOperandInfo OpInfo(T);
11765     if (OpInfo.Type != InlineAsm::isOutput)
11766       continue;
11767 
11768     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
11769     // individual constraint.
11770     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
11771 
11772     switch (OpInfo.ConstraintType) {
11773     case TargetLowering::C_Register:
11774     case TargetLowering::C_RegisterClass: {
11775       // Fill in OpInfo.AssignedRegs.Regs.
11776       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
11777 
11778       // getRegistersForValue may produce 1 to many registers based on whether
11779       // the OpInfo.ConstraintVT is legal on the target or not.
11780       for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) {
11781         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
11782         if (Register::isPhysicalRegister(OriginalDef))
11783           FuncInfo.MBB->addLiveIn(OriginalDef);
11784         // Update the assigned registers to use the original defs.
11785         OpInfo.AssignedRegs.Regs[i] = OriginalDef;
11786       }
11787 
11788       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
11789           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
11790       ResultValues.push_back(V);
11791       ResultVTs.push_back(OpInfo.ConstraintVT);
11792       break;
11793     }
11794     case TargetLowering::C_Other: {
11795       SDValue Flag;
11796       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
11797                                                   OpInfo, DAG);
11798       ++InitialDef;
11799       ResultValues.push_back(V);
11800       ResultVTs.push_back(OpInfo.ConstraintVT);
11801       break;
11802     }
11803     default:
11804       break;
11805     }
11806   }
11807   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11808                           DAG.getVTList(ResultVTs), ResultValues);
11809   setValue(&I, V);
11810 }
11811