xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision eecaeb6f100a328e93dee4e35e34731cdef04d6d)
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   Flags.setUnpredictable(
3385       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3386 
3387   // Min/max matching is only viable if all output VTs are the same.
3388   if (all_equal(ValueVTs)) {
3389     EVT VT = ValueVTs[0];
3390     LLVMContext &Ctx = *DAG.getContext();
3391     auto &TLI = DAG.getTargetLoweringInfo();
3392 
3393     // We care about the legality of the operation after it has been type
3394     // legalized.
3395     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3396       VT = TLI.getTypeToTransformTo(Ctx, VT);
3397 
3398     // If the vselect is legal, assume we want to leave this as a vector setcc +
3399     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3400     // min/max is legal on the scalar type.
3401     bool UseScalarMinMax = VT.isVector() &&
3402       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3403 
3404     // ValueTracking's select pattern matching does not account for -0.0,
3405     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3406     // -0.0 is less than +0.0.
3407     Value *LHS, *RHS;
3408     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3409     ISD::NodeType Opc = ISD::DELETED_NODE;
3410     switch (SPR.Flavor) {
3411     case SPF_UMAX:    Opc = ISD::UMAX; break;
3412     case SPF_UMIN:    Opc = ISD::UMIN; break;
3413     case SPF_SMAX:    Opc = ISD::SMAX; break;
3414     case SPF_SMIN:    Opc = ISD::SMIN; break;
3415     case SPF_FMINNUM:
3416       switch (SPR.NaNBehavior) {
3417       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3418       case SPNB_RETURNS_NAN: break;
3419       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3420       case SPNB_RETURNS_ANY:
3421         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3422             (UseScalarMinMax &&
3423              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3424           Opc = ISD::FMINNUM;
3425         break;
3426       }
3427       break;
3428     case SPF_FMAXNUM:
3429       switch (SPR.NaNBehavior) {
3430       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3431       case SPNB_RETURNS_NAN: break;
3432       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3433       case SPNB_RETURNS_ANY:
3434         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3435             (UseScalarMinMax &&
3436              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3437           Opc = ISD::FMAXNUM;
3438         break;
3439       }
3440       break;
3441     case SPF_NABS:
3442       Negate = true;
3443       [[fallthrough]];
3444     case SPF_ABS:
3445       IsUnaryAbs = true;
3446       Opc = ISD::ABS;
3447       break;
3448     default: break;
3449     }
3450 
3451     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3452         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3453          (UseScalarMinMax &&
3454           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3455         // If the underlying comparison instruction is used by any other
3456         // instruction, the consumed instructions won't be destroyed, so it is
3457         // not profitable to convert to a min/max.
3458         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3459       OpCode = Opc;
3460       LHSVal = getValue(LHS);
3461       RHSVal = getValue(RHS);
3462       BaseOps.clear();
3463     }
3464 
3465     if (IsUnaryAbs) {
3466       OpCode = Opc;
3467       LHSVal = getValue(LHS);
3468       BaseOps.clear();
3469     }
3470   }
3471 
3472   if (IsUnaryAbs) {
3473     for (unsigned i = 0; i != NumValues; ++i) {
3474       SDLoc dl = getCurSDLoc();
3475       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3476       Values[i] =
3477           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3478       if (Negate)
3479         Values[i] = DAG.getNegative(Values[i], dl, VT);
3480     }
3481   } else {
3482     for (unsigned i = 0; i != NumValues; ++i) {
3483       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3484       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3485       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3486       Values[i] = DAG.getNode(
3487           OpCode, getCurSDLoc(),
3488           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3489     }
3490   }
3491 
3492   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3493                            DAG.getVTList(ValueVTs), Values));
3494 }
3495 
3496 void SelectionDAGBuilder::visitTrunc(const User &I) {
3497   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3498   SDValue N = getValue(I.getOperand(0));
3499   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3500                                                         I.getType());
3501   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3502 }
3503 
3504 void SelectionDAGBuilder::visitZExt(const User &I) {
3505   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3506   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3507   SDValue N = getValue(I.getOperand(0));
3508   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3509                                                         I.getType());
3510   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3511 }
3512 
3513 void SelectionDAGBuilder::visitSExt(const User &I) {
3514   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3515   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3516   SDValue N = getValue(I.getOperand(0));
3517   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3518                                                         I.getType());
3519   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3520 }
3521 
3522 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3523   // FPTrunc is never a no-op cast, no need to check
3524   SDValue N = getValue(I.getOperand(0));
3525   SDLoc dl = getCurSDLoc();
3526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3527   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3528   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3529                            DAG.getTargetConstant(
3530                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3531 }
3532 
3533 void SelectionDAGBuilder::visitFPExt(const User &I) {
3534   // FPExt is never a no-op cast, no need to check
3535   SDValue N = getValue(I.getOperand(0));
3536   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3537                                                         I.getType());
3538   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3539 }
3540 
3541 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3542   // FPToUI is never a no-op cast, no need to check
3543   SDValue N = getValue(I.getOperand(0));
3544   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3545                                                         I.getType());
3546   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3547 }
3548 
3549 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3550   // FPToSI is never a no-op cast, no need to check
3551   SDValue N = getValue(I.getOperand(0));
3552   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3553                                                         I.getType());
3554   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3555 }
3556 
3557 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3558   // UIToFP is never a no-op cast, no need to check
3559   SDValue N = getValue(I.getOperand(0));
3560   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3561                                                         I.getType());
3562   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3563 }
3564 
3565 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3566   // SIToFP is never a no-op cast, no need to check
3567   SDValue N = getValue(I.getOperand(0));
3568   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3569                                                         I.getType());
3570   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3571 }
3572 
3573 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3574   // What to do depends on the size of the integer and the size of the pointer.
3575   // We can either truncate, zero extend, or no-op, accordingly.
3576   SDValue N = getValue(I.getOperand(0));
3577   auto &TLI = DAG.getTargetLoweringInfo();
3578   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3579                                                         I.getType());
3580   EVT PtrMemVT =
3581       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3582   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3583   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3584   setValue(&I, N);
3585 }
3586 
3587 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3588   // What to do depends on the size of the integer and the size of the pointer.
3589   // We can either truncate, zero extend, or no-op, accordingly.
3590   SDValue N = getValue(I.getOperand(0));
3591   auto &TLI = DAG.getTargetLoweringInfo();
3592   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3593   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3594   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3595   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3596   setValue(&I, N);
3597 }
3598 
3599 void SelectionDAGBuilder::visitBitCast(const User &I) {
3600   SDValue N = getValue(I.getOperand(0));
3601   SDLoc dl = getCurSDLoc();
3602   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3603                                                         I.getType());
3604 
3605   // BitCast assures us that source and destination are the same size so this is
3606   // either a BITCAST or a no-op.
3607   if (DestVT != N.getValueType())
3608     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3609                              DestVT, N)); // convert types.
3610   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3611   // might fold any kind of constant expression to an integer constant and that
3612   // is not what we are looking for. Only recognize a bitcast of a genuine
3613   // constant integer as an opaque constant.
3614   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3615     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3616                                  /*isOpaque*/true));
3617   else
3618     setValue(&I, N);            // noop cast.
3619 }
3620 
3621 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3622   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3623   const Value *SV = I.getOperand(0);
3624   SDValue N = getValue(SV);
3625   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3626 
3627   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3628   unsigned DestAS = I.getType()->getPointerAddressSpace();
3629 
3630   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3631     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3632 
3633   setValue(&I, N);
3634 }
3635 
3636 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3637   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3638   SDValue InVec = getValue(I.getOperand(0));
3639   SDValue InVal = getValue(I.getOperand(1));
3640   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3641                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3642   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3643                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3644                            InVec, InVal, InIdx));
3645 }
3646 
3647 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3648   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3649   SDValue InVec = getValue(I.getOperand(0));
3650   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3651                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3652   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3653                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3654                            InVec, InIdx));
3655 }
3656 
3657 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3658   SDValue Src1 = getValue(I.getOperand(0));
3659   SDValue Src2 = getValue(I.getOperand(1));
3660   ArrayRef<int> Mask;
3661   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3662     Mask = SVI->getShuffleMask();
3663   else
3664     Mask = cast<ConstantExpr>(I).getShuffleMask();
3665   SDLoc DL = getCurSDLoc();
3666   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3667   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3668   EVT SrcVT = Src1.getValueType();
3669 
3670   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3671       VT.isScalableVector()) {
3672     // Canonical splat form of first element of first input vector.
3673     SDValue FirstElt =
3674         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3675                     DAG.getVectorIdxConstant(0, DL));
3676     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3677     return;
3678   }
3679 
3680   // For now, we only handle splats for scalable vectors.
3681   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3682   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3683   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3684 
3685   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3686   unsigned MaskNumElts = Mask.size();
3687 
3688   if (SrcNumElts == MaskNumElts) {
3689     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3690     return;
3691   }
3692 
3693   // Normalize the shuffle vector since mask and vector length don't match.
3694   if (SrcNumElts < MaskNumElts) {
3695     // Mask is longer than the source vectors. We can use concatenate vector to
3696     // make the mask and vectors lengths match.
3697 
3698     if (MaskNumElts % SrcNumElts == 0) {
3699       // Mask length is a multiple of the source vector length.
3700       // Check if the shuffle is some kind of concatenation of the input
3701       // vectors.
3702       unsigned NumConcat = MaskNumElts / SrcNumElts;
3703       bool IsConcat = true;
3704       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3705       for (unsigned i = 0; i != MaskNumElts; ++i) {
3706         int Idx = Mask[i];
3707         if (Idx < 0)
3708           continue;
3709         // Ensure the indices in each SrcVT sized piece are sequential and that
3710         // the same source is used for the whole piece.
3711         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3712             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3713              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3714           IsConcat = false;
3715           break;
3716         }
3717         // Remember which source this index came from.
3718         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3719       }
3720 
3721       // The shuffle is concatenating multiple vectors together. Just emit
3722       // a CONCAT_VECTORS operation.
3723       if (IsConcat) {
3724         SmallVector<SDValue, 8> ConcatOps;
3725         for (auto Src : ConcatSrcs) {
3726           if (Src < 0)
3727             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3728           else if (Src == 0)
3729             ConcatOps.push_back(Src1);
3730           else
3731             ConcatOps.push_back(Src2);
3732         }
3733         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3734         return;
3735       }
3736     }
3737 
3738     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3739     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3740     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3741                                     PaddedMaskNumElts);
3742 
3743     // Pad both vectors with undefs to make them the same length as the mask.
3744     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3745 
3746     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3747     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3748     MOps1[0] = Src1;
3749     MOps2[0] = Src2;
3750 
3751     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3752     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3753 
3754     // Readjust mask for new input vector length.
3755     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3756     for (unsigned i = 0; i != MaskNumElts; ++i) {
3757       int Idx = Mask[i];
3758       if (Idx >= (int)SrcNumElts)
3759         Idx -= SrcNumElts - PaddedMaskNumElts;
3760       MappedOps[i] = Idx;
3761     }
3762 
3763     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3764 
3765     // If the concatenated vector was padded, extract a subvector with the
3766     // correct number of elements.
3767     if (MaskNumElts != PaddedMaskNumElts)
3768       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3769                            DAG.getVectorIdxConstant(0, DL));
3770 
3771     setValue(&I, Result);
3772     return;
3773   }
3774 
3775   if (SrcNumElts > MaskNumElts) {
3776     // Analyze the access pattern of the vector to see if we can extract
3777     // two subvectors and do the shuffle.
3778     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3779     bool CanExtract = true;
3780     for (int Idx : Mask) {
3781       unsigned Input = 0;
3782       if (Idx < 0)
3783         continue;
3784 
3785       if (Idx >= (int)SrcNumElts) {
3786         Input = 1;
3787         Idx -= SrcNumElts;
3788       }
3789 
3790       // If all the indices come from the same MaskNumElts sized portion of
3791       // the sources we can use extract. Also make sure the extract wouldn't
3792       // extract past the end of the source.
3793       int NewStartIdx = alignDown(Idx, MaskNumElts);
3794       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3795           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3796         CanExtract = false;
3797       // Make sure we always update StartIdx as we use it to track if all
3798       // elements are undef.
3799       StartIdx[Input] = NewStartIdx;
3800     }
3801 
3802     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3803       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3804       return;
3805     }
3806     if (CanExtract) {
3807       // Extract appropriate subvector and generate a vector shuffle
3808       for (unsigned Input = 0; Input < 2; ++Input) {
3809         SDValue &Src = Input == 0 ? Src1 : Src2;
3810         if (StartIdx[Input] < 0)
3811           Src = DAG.getUNDEF(VT);
3812         else {
3813           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3814                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3815         }
3816       }
3817 
3818       // Calculate new mask.
3819       SmallVector<int, 8> MappedOps(Mask);
3820       for (int &Idx : MappedOps) {
3821         if (Idx >= (int)SrcNumElts)
3822           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3823         else if (Idx >= 0)
3824           Idx -= StartIdx[0];
3825       }
3826 
3827       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3828       return;
3829     }
3830   }
3831 
3832   // We can't use either concat vectors or extract subvectors so fall back to
3833   // replacing the shuffle with extract and build vector.
3834   // to insert and build vector.
3835   EVT EltVT = VT.getVectorElementType();
3836   SmallVector<SDValue,8> Ops;
3837   for (int Idx : Mask) {
3838     SDValue Res;
3839 
3840     if (Idx < 0) {
3841       Res = DAG.getUNDEF(EltVT);
3842     } else {
3843       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3844       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3845 
3846       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3847                         DAG.getVectorIdxConstant(Idx, DL));
3848     }
3849 
3850     Ops.push_back(Res);
3851   }
3852 
3853   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3854 }
3855 
3856 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3857   ArrayRef<unsigned> Indices = I.getIndices();
3858   const Value *Op0 = I.getOperand(0);
3859   const Value *Op1 = I.getOperand(1);
3860   Type *AggTy = I.getType();
3861   Type *ValTy = Op1->getType();
3862   bool IntoUndef = isa<UndefValue>(Op0);
3863   bool FromUndef = isa<UndefValue>(Op1);
3864 
3865   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3866 
3867   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3868   SmallVector<EVT, 4> AggValueVTs;
3869   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3870   SmallVector<EVT, 4> ValValueVTs;
3871   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3872 
3873   unsigned NumAggValues = AggValueVTs.size();
3874   unsigned NumValValues = ValValueVTs.size();
3875   SmallVector<SDValue, 4> Values(NumAggValues);
3876 
3877   // Ignore an insertvalue that produces an empty object
3878   if (!NumAggValues) {
3879     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3880     return;
3881   }
3882 
3883   SDValue Agg = getValue(Op0);
3884   unsigned i = 0;
3885   // Copy the beginning value(s) from the original aggregate.
3886   for (; i != LinearIndex; ++i)
3887     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3888                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3889   // Copy values from the inserted value(s).
3890   if (NumValValues) {
3891     SDValue Val = getValue(Op1);
3892     for (; i != LinearIndex + NumValValues; ++i)
3893       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3894                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3895   }
3896   // Copy remaining value(s) from the original aggregate.
3897   for (; i != NumAggValues; ++i)
3898     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3899                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3900 
3901   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3902                            DAG.getVTList(AggValueVTs), Values));
3903 }
3904 
3905 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3906   ArrayRef<unsigned> Indices = I.getIndices();
3907   const Value *Op0 = I.getOperand(0);
3908   Type *AggTy = Op0->getType();
3909   Type *ValTy = I.getType();
3910   bool OutOfUndef = isa<UndefValue>(Op0);
3911 
3912   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3913 
3914   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3915   SmallVector<EVT, 4> ValValueVTs;
3916   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3917 
3918   unsigned NumValValues = ValValueVTs.size();
3919 
3920   // Ignore a extractvalue that produces an empty object
3921   if (!NumValValues) {
3922     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3923     return;
3924   }
3925 
3926   SmallVector<SDValue, 4> Values(NumValValues);
3927 
3928   SDValue Agg = getValue(Op0);
3929   // Copy out the selected value(s).
3930   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3931     Values[i - LinearIndex] =
3932       OutOfUndef ?
3933         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3934         SDValue(Agg.getNode(), Agg.getResNo() + i);
3935 
3936   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3937                            DAG.getVTList(ValValueVTs), Values));
3938 }
3939 
3940 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3941   Value *Op0 = I.getOperand(0);
3942   // Note that the pointer operand may be a vector of pointers. Take the scalar
3943   // element which holds a pointer.
3944   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3945   SDValue N = getValue(Op0);
3946   SDLoc dl = getCurSDLoc();
3947   auto &TLI = DAG.getTargetLoweringInfo();
3948 
3949   // Normalize Vector GEP - all scalar operands should be converted to the
3950   // splat vector.
3951   bool IsVectorGEP = I.getType()->isVectorTy();
3952   ElementCount VectorElementCount =
3953       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3954                   : ElementCount::getFixed(0);
3955 
3956   if (IsVectorGEP && !N.getValueType().isVector()) {
3957     LLVMContext &Context = *DAG.getContext();
3958     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3959     N = DAG.getSplat(VT, dl, N);
3960   }
3961 
3962   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3963        GTI != E; ++GTI) {
3964     const Value *Idx = GTI.getOperand();
3965     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3966       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3967       if (Field) {
3968         // N = N + Offset
3969         uint64_t Offset =
3970             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3971 
3972         // In an inbounds GEP with an offset that is nonnegative even when
3973         // interpreted as signed, assume there is no unsigned overflow.
3974         SDNodeFlags Flags;
3975         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3976           Flags.setNoUnsignedWrap(true);
3977 
3978         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3979                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3980       }
3981     } else {
3982       // IdxSize is the width of the arithmetic according to IR semantics.
3983       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3984       // (and fix up the result later).
3985       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3986       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3987       TypeSize ElementSize =
3988           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3989       // We intentionally mask away the high bits here; ElementSize may not
3990       // fit in IdxTy.
3991       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
3992       bool ElementScalable = ElementSize.isScalable();
3993 
3994       // If this is a scalar constant or a splat vector of constants,
3995       // handle it quickly.
3996       const auto *C = dyn_cast<Constant>(Idx);
3997       if (C && isa<VectorType>(C->getType()))
3998         C = C->getSplatValue();
3999 
4000       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4001       if (CI && CI->isZero())
4002         continue;
4003       if (CI && !ElementScalable) {
4004         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4005         LLVMContext &Context = *DAG.getContext();
4006         SDValue OffsVal;
4007         if (IsVectorGEP)
4008           OffsVal = DAG.getConstant(
4009               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4010         else
4011           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4012 
4013         // In an inbounds GEP with an offset that is nonnegative even when
4014         // interpreted as signed, assume there is no unsigned overflow.
4015         SDNodeFlags Flags;
4016         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4017           Flags.setNoUnsignedWrap(true);
4018 
4019         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4020 
4021         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4022         continue;
4023       }
4024 
4025       // N = N + Idx * ElementMul;
4026       SDValue IdxN = getValue(Idx);
4027 
4028       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4029         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4030                                   VectorElementCount);
4031         IdxN = DAG.getSplat(VT, dl, IdxN);
4032       }
4033 
4034       // If the index is smaller or larger than intptr_t, truncate or extend
4035       // it.
4036       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4037 
4038       if (ElementScalable) {
4039         EVT VScaleTy = N.getValueType().getScalarType();
4040         SDValue VScale = DAG.getNode(
4041             ISD::VSCALE, dl, VScaleTy,
4042             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4043         if (IsVectorGEP)
4044           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4045         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4046       } else {
4047         // If this is a multiply by a power of two, turn it into a shl
4048         // immediately.  This is a very common case.
4049         if (ElementMul != 1) {
4050           if (ElementMul.isPowerOf2()) {
4051             unsigned Amt = ElementMul.logBase2();
4052             IdxN = DAG.getNode(ISD::SHL, dl,
4053                                N.getValueType(), IdxN,
4054                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4055           } else {
4056             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4057                                             IdxN.getValueType());
4058             IdxN = DAG.getNode(ISD::MUL, dl,
4059                                N.getValueType(), IdxN, Scale);
4060           }
4061         }
4062       }
4063 
4064       N = DAG.getNode(ISD::ADD, dl,
4065                       N.getValueType(), N, IdxN);
4066     }
4067   }
4068 
4069   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4070   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4071   if (IsVectorGEP) {
4072     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4073     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4074   }
4075 
4076   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4077     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4078 
4079   setValue(&I, N);
4080 }
4081 
4082 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4083   // If this is a fixed sized alloca in the entry block of the function,
4084   // allocate it statically on the stack.
4085   if (FuncInfo.StaticAllocaMap.count(&I))
4086     return;   // getValue will auto-populate this.
4087 
4088   SDLoc dl = getCurSDLoc();
4089   Type *Ty = I.getAllocatedType();
4090   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4091   auto &DL = DAG.getDataLayout();
4092   TypeSize TySize = DL.getTypeAllocSize(Ty);
4093   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4094 
4095   SDValue AllocSize = getValue(I.getArraySize());
4096 
4097   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace());
4098   if (AllocSize.getValueType() != IntPtr)
4099     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4100 
4101   if (TySize.isScalable())
4102     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4103                             DAG.getVScale(dl, IntPtr,
4104                                           APInt(IntPtr.getScalarSizeInBits(),
4105                                                 TySize.getKnownMinValue())));
4106   else
4107     AllocSize =
4108         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4109                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4110 
4111   // Handle alignment.  If the requested alignment is less than or equal to
4112   // the stack alignment, ignore it.  If the size is greater than or equal to
4113   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4114   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4115   if (*Alignment <= StackAlign)
4116     Alignment = std::nullopt;
4117 
4118   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4119   // Round the size of the allocation up to the stack alignment size
4120   // by add SA-1 to the size. This doesn't overflow because we're computing
4121   // an address inside an alloca.
4122   SDNodeFlags Flags;
4123   Flags.setNoUnsignedWrap(true);
4124   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4125                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4126 
4127   // Mask out the low bits for alignment purposes.
4128   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4129                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4130 
4131   SDValue Ops[] = {
4132       getRoot(), AllocSize,
4133       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4134   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4135   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4136   setValue(&I, DSA);
4137   DAG.setRoot(DSA.getValue(1));
4138 
4139   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4140 }
4141 
4142 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4143   if (I.isAtomic())
4144     return visitAtomicLoad(I);
4145 
4146   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4147   const Value *SV = I.getOperand(0);
4148   if (TLI.supportSwiftError()) {
4149     // Swifterror values can come from either a function parameter with
4150     // swifterror attribute or an alloca with swifterror attribute.
4151     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4152       if (Arg->hasSwiftErrorAttr())
4153         return visitLoadFromSwiftError(I);
4154     }
4155 
4156     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4157       if (Alloca->isSwiftError())
4158         return visitLoadFromSwiftError(I);
4159     }
4160   }
4161 
4162   SDValue Ptr = getValue(SV);
4163 
4164   Type *Ty = I.getType();
4165   SmallVector<EVT, 4> ValueVTs, MemVTs;
4166   SmallVector<uint64_t, 4> Offsets;
4167   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0);
4168   unsigned NumValues = ValueVTs.size();
4169   if (NumValues == 0)
4170     return;
4171 
4172   Align Alignment = I.getAlign();
4173   AAMDNodes AAInfo = I.getAAMetadata();
4174   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4175   bool isVolatile = I.isVolatile();
4176   MachineMemOperand::Flags MMOFlags =
4177       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4178 
4179   SDValue Root;
4180   bool ConstantMemory = false;
4181   if (isVolatile)
4182     // Serialize volatile loads with other side effects.
4183     Root = getRoot();
4184   else if (NumValues > MaxParallelChains)
4185     Root = getMemoryRoot();
4186   else if (AA &&
4187            AA->pointsToConstantMemory(MemoryLocation(
4188                SV,
4189                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4190                AAInfo))) {
4191     // Do not serialize (non-volatile) loads of constant memory with anything.
4192     Root = DAG.getEntryNode();
4193     ConstantMemory = true;
4194     MMOFlags |= MachineMemOperand::MOInvariant;
4195   } else {
4196     // Do not serialize non-volatile loads against each other.
4197     Root = DAG.getRoot();
4198   }
4199 
4200   SDLoc dl = getCurSDLoc();
4201 
4202   if (isVolatile)
4203     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4204 
4205   // An aggregate load cannot wrap around the address space, so offsets to its
4206   // parts don't wrap either.
4207   SDNodeFlags Flags;
4208   Flags.setNoUnsignedWrap(true);
4209 
4210   SmallVector<SDValue, 4> Values(NumValues);
4211   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4212   EVT PtrVT = Ptr.getValueType();
4213 
4214   unsigned ChainI = 0;
4215   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4216     // Serializing loads here may result in excessive register pressure, and
4217     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4218     // could recover a bit by hoisting nodes upward in the chain by recognizing
4219     // they are side-effect free or do not alias. The optimizer should really
4220     // avoid this case by converting large object/array copies to llvm.memcpy
4221     // (MaxParallelChains should always remain as failsafe).
4222     if (ChainI == MaxParallelChains) {
4223       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4224       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4225                                   ArrayRef(Chains.data(), ChainI));
4226       Root = Chain;
4227       ChainI = 0;
4228     }
4229     SDValue A = DAG.getNode(ISD::ADD, dl,
4230                             PtrVT, Ptr,
4231                             DAG.getConstant(Offsets[i], dl, PtrVT),
4232                             Flags);
4233 
4234     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4235                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4236                             MMOFlags, AAInfo, Ranges);
4237     Chains[ChainI] = L.getValue(1);
4238 
4239     if (MemVTs[i] != ValueVTs[i])
4240       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4241 
4242     Values[i] = L;
4243   }
4244 
4245   if (!ConstantMemory) {
4246     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4247                                 ArrayRef(Chains.data(), ChainI));
4248     if (isVolatile)
4249       DAG.setRoot(Chain);
4250     else
4251       PendingLoads.push_back(Chain);
4252   }
4253 
4254   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4255                            DAG.getVTList(ValueVTs), Values));
4256 }
4257 
4258 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4259   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4260          "call visitStoreToSwiftError when backend supports swifterror");
4261 
4262   SmallVector<EVT, 4> ValueVTs;
4263   SmallVector<uint64_t, 4> Offsets;
4264   const Value *SrcV = I.getOperand(0);
4265   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4266                   SrcV->getType(), ValueVTs, &Offsets, 0);
4267   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4268          "expect a single EVT for swifterror");
4269 
4270   SDValue Src = getValue(SrcV);
4271   // Create a virtual register, then update the virtual register.
4272   Register VReg =
4273       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4274   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4275   // Chain can be getRoot or getControlRoot.
4276   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4277                                       SDValue(Src.getNode(), Src.getResNo()));
4278   DAG.setRoot(CopyNode);
4279 }
4280 
4281 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4282   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4283          "call visitLoadFromSwiftError when backend supports swifterror");
4284 
4285   assert(!I.isVolatile() &&
4286          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4287          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4288          "Support volatile, non temporal, invariant for load_from_swift_error");
4289 
4290   const Value *SV = I.getOperand(0);
4291   Type *Ty = I.getType();
4292   assert(
4293       (!AA ||
4294        !AA->pointsToConstantMemory(MemoryLocation(
4295            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4296            I.getAAMetadata()))) &&
4297       "load_from_swift_error should not be constant memory");
4298 
4299   SmallVector<EVT, 4> ValueVTs;
4300   SmallVector<uint64_t, 4> Offsets;
4301   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4302                   ValueVTs, &Offsets, 0);
4303   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4304          "expect a single EVT for swifterror");
4305 
4306   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4307   SDValue L = DAG.getCopyFromReg(
4308       getRoot(), getCurSDLoc(),
4309       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4310 
4311   setValue(&I, L);
4312 }
4313 
4314 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4315   if (I.isAtomic())
4316     return visitAtomicStore(I);
4317 
4318   const Value *SrcV = I.getOperand(0);
4319   const Value *PtrV = I.getOperand(1);
4320 
4321   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4322   if (TLI.supportSwiftError()) {
4323     // Swifterror values can come from either a function parameter with
4324     // swifterror attribute or an alloca with swifterror attribute.
4325     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4326       if (Arg->hasSwiftErrorAttr())
4327         return visitStoreToSwiftError(I);
4328     }
4329 
4330     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4331       if (Alloca->isSwiftError())
4332         return visitStoreToSwiftError(I);
4333     }
4334   }
4335 
4336   SmallVector<EVT, 4> ValueVTs, MemVTs;
4337   SmallVector<uint64_t, 4> Offsets;
4338   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4339                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0);
4340   unsigned NumValues = ValueVTs.size();
4341   if (NumValues == 0)
4342     return;
4343 
4344   // Get the lowered operands. Note that we do this after
4345   // checking if NumResults is zero, because with zero results
4346   // the operands won't have values in the map.
4347   SDValue Src = getValue(SrcV);
4348   SDValue Ptr = getValue(PtrV);
4349 
4350   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4351   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4352   SDLoc dl = getCurSDLoc();
4353   Align Alignment = I.getAlign();
4354   AAMDNodes AAInfo = I.getAAMetadata();
4355 
4356   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4357 
4358   // An aggregate load cannot wrap around the address space, so offsets to its
4359   // parts don't wrap either.
4360   SDNodeFlags Flags;
4361   Flags.setNoUnsignedWrap(true);
4362 
4363   unsigned ChainI = 0;
4364   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4365     // See visitLoad comments.
4366     if (ChainI == MaxParallelChains) {
4367       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4368                                   ArrayRef(Chains.data(), ChainI));
4369       Root = Chain;
4370       ChainI = 0;
4371     }
4372     SDValue Add =
4373         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4374     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4375     if (MemVTs[i] != ValueVTs[i])
4376       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4377     SDValue St =
4378         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4379                      Alignment, MMOFlags, AAInfo);
4380     Chains[ChainI] = St;
4381   }
4382 
4383   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4384                                   ArrayRef(Chains.data(), ChainI));
4385   setValue(&I, StoreNode);
4386   DAG.setRoot(StoreNode);
4387 }
4388 
4389 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4390                                            bool IsCompressing) {
4391   SDLoc sdl = getCurSDLoc();
4392 
4393   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4394                                MaybeAlign &Alignment) {
4395     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4396     Src0 = I.getArgOperand(0);
4397     Ptr = I.getArgOperand(1);
4398     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4399     Mask = I.getArgOperand(3);
4400   };
4401   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4402                                     MaybeAlign &Alignment) {
4403     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4404     Src0 = I.getArgOperand(0);
4405     Ptr = I.getArgOperand(1);
4406     Mask = I.getArgOperand(2);
4407     Alignment = std::nullopt;
4408   };
4409 
4410   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4411   MaybeAlign Alignment;
4412   if (IsCompressing)
4413     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4414   else
4415     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4416 
4417   SDValue Ptr = getValue(PtrOperand);
4418   SDValue Src0 = getValue(Src0Operand);
4419   SDValue Mask = getValue(MaskOperand);
4420   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4421 
4422   EVT VT = Src0.getValueType();
4423   if (!Alignment)
4424     Alignment = DAG.getEVTAlign(VT);
4425 
4426   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4427       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4428       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4429   SDValue StoreNode =
4430       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4431                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4432   DAG.setRoot(StoreNode);
4433   setValue(&I, StoreNode);
4434 }
4435 
4436 // Get a uniform base for the Gather/Scatter intrinsic.
4437 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4438 // We try to represent it as a base pointer + vector of indices.
4439 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4440 // The first operand of the GEP may be a single pointer or a vector of pointers
4441 // Example:
4442 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4443 //  or
4444 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4445 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4446 //
4447 // When the first GEP operand is a single pointer - it is the uniform base we
4448 // are looking for. If first operand of the GEP is a splat vector - we
4449 // extract the splat value and use it as a uniform base.
4450 // In all other cases the function returns 'false'.
4451 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4452                            ISD::MemIndexType &IndexType, SDValue &Scale,
4453                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4454                            uint64_t ElemSize) {
4455   SelectionDAG& DAG = SDB->DAG;
4456   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4457   const DataLayout &DL = DAG.getDataLayout();
4458 
4459   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4460 
4461   // Handle splat constant pointer.
4462   if (auto *C = dyn_cast<Constant>(Ptr)) {
4463     C = C->getSplatValue();
4464     if (!C)
4465       return false;
4466 
4467     Base = SDB->getValue(C);
4468 
4469     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4470     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4471     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4472     IndexType = ISD::SIGNED_SCALED;
4473     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4474     return true;
4475   }
4476 
4477   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4478   if (!GEP || GEP->getParent() != CurBB)
4479     return false;
4480 
4481   if (GEP->getNumOperands() != 2)
4482     return false;
4483 
4484   const Value *BasePtr = GEP->getPointerOperand();
4485   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4486 
4487   // Make sure the base is scalar and the index is a vector.
4488   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4489     return false;
4490 
4491   uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4492 
4493   // Target may not support the required addressing mode.
4494   if (ScaleVal != 1 &&
4495       !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize))
4496     return false;
4497 
4498   Base = SDB->getValue(BasePtr);
4499   Index = SDB->getValue(IndexVal);
4500   IndexType = ISD::SIGNED_SCALED;
4501 
4502   Scale =
4503       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4504   return true;
4505 }
4506 
4507 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4508   SDLoc sdl = getCurSDLoc();
4509 
4510   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4511   const Value *Ptr = I.getArgOperand(1);
4512   SDValue Src0 = getValue(I.getArgOperand(0));
4513   SDValue Mask = getValue(I.getArgOperand(3));
4514   EVT VT = Src0.getValueType();
4515   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4516                         ->getMaybeAlignValue()
4517                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4518   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4519 
4520   SDValue Base;
4521   SDValue Index;
4522   ISD::MemIndexType IndexType;
4523   SDValue Scale;
4524   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4525                                     I.getParent(), VT.getScalarStoreSize());
4526 
4527   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4528   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4529       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4530       // TODO: Make MachineMemOperands aware of scalable
4531       // vectors.
4532       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4533   if (!UniformBase) {
4534     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4535     Index = getValue(Ptr);
4536     IndexType = ISD::SIGNED_SCALED;
4537     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4538   }
4539 
4540   EVT IdxVT = Index.getValueType();
4541   EVT EltTy = IdxVT.getVectorElementType();
4542   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4543     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4544     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4545   }
4546 
4547   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4548   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4549                                          Ops, MMO, IndexType, false);
4550   DAG.setRoot(Scatter);
4551   setValue(&I, Scatter);
4552 }
4553 
4554 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4555   SDLoc sdl = getCurSDLoc();
4556 
4557   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4558                               MaybeAlign &Alignment) {
4559     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4560     Ptr = I.getArgOperand(0);
4561     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4562     Mask = I.getArgOperand(2);
4563     Src0 = I.getArgOperand(3);
4564   };
4565   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4566                                  MaybeAlign &Alignment) {
4567     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4568     Ptr = I.getArgOperand(0);
4569     Alignment = std::nullopt;
4570     Mask = I.getArgOperand(1);
4571     Src0 = I.getArgOperand(2);
4572   };
4573 
4574   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4575   MaybeAlign Alignment;
4576   if (IsExpanding)
4577     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4578   else
4579     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4580 
4581   SDValue Ptr = getValue(PtrOperand);
4582   SDValue Src0 = getValue(Src0Operand);
4583   SDValue Mask = getValue(MaskOperand);
4584   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4585 
4586   EVT VT = Src0.getValueType();
4587   if (!Alignment)
4588     Alignment = DAG.getEVTAlign(VT);
4589 
4590   AAMDNodes AAInfo = I.getAAMetadata();
4591   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4592 
4593   // Do not serialize masked loads of constant memory with anything.
4594   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4595   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4596 
4597   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4598 
4599   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4600       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4601       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4602 
4603   SDValue Load =
4604       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4605                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4606   if (AddToChain)
4607     PendingLoads.push_back(Load.getValue(1));
4608   setValue(&I, Load);
4609 }
4610 
4611 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4612   SDLoc sdl = getCurSDLoc();
4613 
4614   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4615   const Value *Ptr = I.getArgOperand(0);
4616   SDValue Src0 = getValue(I.getArgOperand(3));
4617   SDValue Mask = getValue(I.getArgOperand(2));
4618 
4619   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4620   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4621   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4622                         ->getMaybeAlignValue()
4623                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4624 
4625   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4626 
4627   SDValue Root = DAG.getRoot();
4628   SDValue Base;
4629   SDValue Index;
4630   ISD::MemIndexType IndexType;
4631   SDValue Scale;
4632   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4633                                     I.getParent(), VT.getScalarStoreSize());
4634   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4635   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4636       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4637       // TODO: Make MachineMemOperands aware of scalable
4638       // vectors.
4639       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4640 
4641   if (!UniformBase) {
4642     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4643     Index = getValue(Ptr);
4644     IndexType = ISD::SIGNED_SCALED;
4645     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4646   }
4647 
4648   EVT IdxVT = Index.getValueType();
4649   EVT EltTy = IdxVT.getVectorElementType();
4650   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4651     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4652     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4653   }
4654 
4655   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4656   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4657                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4658 
4659   PendingLoads.push_back(Gather.getValue(1));
4660   setValue(&I, Gather);
4661 }
4662 
4663 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4664   SDLoc dl = getCurSDLoc();
4665   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4666   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4667   SyncScope::ID SSID = I.getSyncScopeID();
4668 
4669   SDValue InChain = getRoot();
4670 
4671   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4672   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4673 
4674   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4675   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4676 
4677   MachineFunction &MF = DAG.getMachineFunction();
4678   MachineMemOperand *MMO = MF.getMachineMemOperand(
4679       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4680       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4681       FailureOrdering);
4682 
4683   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4684                                    dl, MemVT, VTs, InChain,
4685                                    getValue(I.getPointerOperand()),
4686                                    getValue(I.getCompareOperand()),
4687                                    getValue(I.getNewValOperand()), MMO);
4688 
4689   SDValue OutChain = L.getValue(2);
4690 
4691   setValue(&I, L);
4692   DAG.setRoot(OutChain);
4693 }
4694 
4695 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4696   SDLoc dl = getCurSDLoc();
4697   ISD::NodeType NT;
4698   switch (I.getOperation()) {
4699   default: llvm_unreachable("Unknown atomicrmw operation");
4700   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4701   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4702   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4703   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4704   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4705   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4706   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4707   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4708   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4709   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4710   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4711   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4712   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4713   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4714   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4715   case AtomicRMWInst::UIncWrap:
4716     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
4717     break;
4718   case AtomicRMWInst::UDecWrap:
4719     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
4720     break;
4721   }
4722   AtomicOrdering Ordering = I.getOrdering();
4723   SyncScope::ID SSID = I.getSyncScopeID();
4724 
4725   SDValue InChain = getRoot();
4726 
4727   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4728   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4729   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4730 
4731   MachineFunction &MF = DAG.getMachineFunction();
4732   MachineMemOperand *MMO = MF.getMachineMemOperand(
4733       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4734       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4735 
4736   SDValue L =
4737     DAG.getAtomic(NT, dl, MemVT, InChain,
4738                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4739                   MMO);
4740 
4741   SDValue OutChain = L.getValue(1);
4742 
4743   setValue(&I, L);
4744   DAG.setRoot(OutChain);
4745 }
4746 
4747 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4748   SDLoc dl = getCurSDLoc();
4749   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4750   SDValue Ops[3];
4751   Ops[0] = getRoot();
4752   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4753                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4754   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4755                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4756   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4757   setValue(&I, N);
4758   DAG.setRoot(N);
4759 }
4760 
4761 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4762   SDLoc dl = getCurSDLoc();
4763   AtomicOrdering Order = I.getOrdering();
4764   SyncScope::ID SSID = I.getSyncScopeID();
4765 
4766   SDValue InChain = getRoot();
4767 
4768   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4769   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4770   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4771 
4772   if (!TLI.supportsUnalignedAtomics() &&
4773       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4774     report_fatal_error("Cannot generate unaligned atomic load");
4775 
4776   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4777 
4778   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4779       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4780       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4781 
4782   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4783 
4784   SDValue Ptr = getValue(I.getPointerOperand());
4785 
4786   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4787     // TODO: Once this is better exercised by tests, it should be merged with
4788     // the normal path for loads to prevent future divergence.
4789     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4790     if (MemVT != VT)
4791       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4792 
4793     setValue(&I, L);
4794     SDValue OutChain = L.getValue(1);
4795     if (!I.isUnordered())
4796       DAG.setRoot(OutChain);
4797     else
4798       PendingLoads.push_back(OutChain);
4799     return;
4800   }
4801 
4802   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4803                             Ptr, MMO);
4804 
4805   SDValue OutChain = L.getValue(1);
4806   if (MemVT != VT)
4807     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4808 
4809   setValue(&I, L);
4810   DAG.setRoot(OutChain);
4811 }
4812 
4813 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4814   SDLoc dl = getCurSDLoc();
4815 
4816   AtomicOrdering Ordering = I.getOrdering();
4817   SyncScope::ID SSID = I.getSyncScopeID();
4818 
4819   SDValue InChain = getRoot();
4820 
4821   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4822   EVT MemVT =
4823       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4824 
4825   if (!TLI.supportsUnalignedAtomics() &&
4826       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4827     report_fatal_error("Cannot generate unaligned atomic store");
4828 
4829   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4830 
4831   MachineFunction &MF = DAG.getMachineFunction();
4832   MachineMemOperand *MMO = MF.getMachineMemOperand(
4833       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4834       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4835 
4836   SDValue Val = getValue(I.getValueOperand());
4837   if (Val.getValueType() != MemVT)
4838     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4839   SDValue Ptr = getValue(I.getPointerOperand());
4840 
4841   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4842     // TODO: Once this is better exercised by tests, it should be merged with
4843     // the normal path for stores to prevent future divergence.
4844     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4845     setValue(&I, S);
4846     DAG.setRoot(S);
4847     return;
4848   }
4849   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4850                                    Ptr, Val, MMO);
4851 
4852   setValue(&I, OutChain);
4853   DAG.setRoot(OutChain);
4854 }
4855 
4856 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4857 /// node.
4858 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4859                                                unsigned Intrinsic) {
4860   // Ignore the callsite's attributes. A specific call site may be marked with
4861   // readnone, but the lowering code will expect the chain based on the
4862   // definition.
4863   const Function *F = I.getCalledFunction();
4864   bool HasChain = !F->doesNotAccessMemory();
4865   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4866 
4867   // Build the operand list.
4868   SmallVector<SDValue, 8> Ops;
4869   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4870     if (OnlyLoad) {
4871       // We don't need to serialize loads against other loads.
4872       Ops.push_back(DAG.getRoot());
4873     } else {
4874       Ops.push_back(getRoot());
4875     }
4876   }
4877 
4878   // Info is set by getTgtMemIntrinsic
4879   TargetLowering::IntrinsicInfo Info;
4880   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4881   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4882                                                DAG.getMachineFunction(),
4883                                                Intrinsic);
4884 
4885   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4886   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4887       Info.opc == ISD::INTRINSIC_W_CHAIN)
4888     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4889                                         TLI.getPointerTy(DAG.getDataLayout())));
4890 
4891   // Add all operands of the call to the operand list.
4892   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4893     const Value *Arg = I.getArgOperand(i);
4894     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4895       Ops.push_back(getValue(Arg));
4896       continue;
4897     }
4898 
4899     // Use TargetConstant instead of a regular constant for immarg.
4900     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4901     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4902       assert(CI->getBitWidth() <= 64 &&
4903              "large intrinsic immediates not handled");
4904       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4905     } else {
4906       Ops.push_back(
4907           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4908     }
4909   }
4910 
4911   SmallVector<EVT, 4> ValueVTs;
4912   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4913 
4914   if (HasChain)
4915     ValueVTs.push_back(MVT::Other);
4916 
4917   SDVTList VTs = DAG.getVTList(ValueVTs);
4918 
4919   // Propagate fast-math-flags from IR to node(s).
4920   SDNodeFlags Flags;
4921   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4922     Flags.copyFMF(*FPMO);
4923   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4924 
4925   // Create the node.
4926   SDValue Result;
4927   // In some cases, custom collection of operands from CallInst I may be needed.
4928   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4929   if (IsTgtIntrinsic) {
4930     // This is target intrinsic that touches memory
4931     //
4932     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
4933     //       didn't yield anything useful.
4934     MachinePointerInfo MPI;
4935     if (Info.ptrVal)
4936       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
4937     else if (Info.fallbackAddressSpace)
4938       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
4939     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
4940                                      Info.memVT, MPI, Info.align, Info.flags,
4941                                      Info.size, I.getAAMetadata());
4942   } else if (!HasChain) {
4943     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4944   } else if (!I.getType()->isVoidTy()) {
4945     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4946   } else {
4947     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4948   }
4949 
4950   if (HasChain) {
4951     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4952     if (OnlyLoad)
4953       PendingLoads.push_back(Chain);
4954     else
4955       DAG.setRoot(Chain);
4956   }
4957 
4958   if (!I.getType()->isVoidTy()) {
4959     if (!isa<VectorType>(I.getType()))
4960       Result = lowerRangeToAssertZExt(DAG, I, Result);
4961 
4962     MaybeAlign Alignment = I.getRetAlign();
4963 
4964     // Insert `assertalign` node if there's an alignment.
4965     if (InsertAssertAlign && Alignment) {
4966       Result =
4967           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4968     }
4969 
4970     setValue(&I, Result);
4971   }
4972 }
4973 
4974 /// GetSignificand - Get the significand and build it into a floating-point
4975 /// number with exponent of 1:
4976 ///
4977 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4978 ///
4979 /// where Op is the hexadecimal representation of floating point value.
4980 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4981   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4982                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4983   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4984                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4985   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4986 }
4987 
4988 /// GetExponent - Get the exponent:
4989 ///
4990 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4991 ///
4992 /// where Op is the hexadecimal representation of floating point value.
4993 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4994                            const TargetLowering &TLI, const SDLoc &dl) {
4995   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4996                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4997   SDValue t1 = DAG.getNode(
4998       ISD::SRL, dl, MVT::i32, t0,
4999       DAG.getConstant(23, dl,
5000                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5001   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5002                            DAG.getConstant(127, dl, MVT::i32));
5003   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5004 }
5005 
5006 /// getF32Constant - Get 32-bit floating point constant.
5007 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5008                               const SDLoc &dl) {
5009   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5010                            MVT::f32);
5011 }
5012 
5013 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5014                                        SelectionDAG &DAG) {
5015   // TODO: What fast-math-flags should be set on the floating-point nodes?
5016 
5017   //   IntegerPartOfX = ((int32_t)(t0);
5018   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5019 
5020   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5021   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5022   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5023 
5024   //   IntegerPartOfX <<= 23;
5025   IntegerPartOfX =
5026       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5027                   DAG.getConstant(23, dl,
5028                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5029                                       MVT::i32, DAG.getDataLayout())));
5030 
5031   SDValue TwoToFractionalPartOfX;
5032   if (LimitFloatPrecision <= 6) {
5033     // For floating-point precision of 6:
5034     //
5035     //   TwoToFractionalPartOfX =
5036     //     0.997535578f +
5037     //       (0.735607626f + 0.252464424f * x) * x;
5038     //
5039     // error 0.0144103317, which is 6 bits
5040     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5041                              getF32Constant(DAG, 0x3e814304, dl));
5042     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5043                              getF32Constant(DAG, 0x3f3c50c8, dl));
5044     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5045     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5046                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5047   } else if (LimitFloatPrecision <= 12) {
5048     // For floating-point precision of 12:
5049     //
5050     //   TwoToFractionalPartOfX =
5051     //     0.999892986f +
5052     //       (0.696457318f +
5053     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5054     //
5055     // error 0.000107046256, which is 13 to 14 bits
5056     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5057                              getF32Constant(DAG, 0x3da235e3, dl));
5058     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5059                              getF32Constant(DAG, 0x3e65b8f3, dl));
5060     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5061     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5062                              getF32Constant(DAG, 0x3f324b07, dl));
5063     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5064     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5065                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5066   } else { // LimitFloatPrecision <= 18
5067     // For floating-point precision of 18:
5068     //
5069     //   TwoToFractionalPartOfX =
5070     //     0.999999982f +
5071     //       (0.693148872f +
5072     //         (0.240227044f +
5073     //           (0.554906021e-1f +
5074     //             (0.961591928e-2f +
5075     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5076     // error 2.47208000*10^(-7), which is better than 18 bits
5077     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5078                              getF32Constant(DAG, 0x3924b03e, dl));
5079     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5080                              getF32Constant(DAG, 0x3ab24b87, dl));
5081     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5082     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5083                              getF32Constant(DAG, 0x3c1d8c17, dl));
5084     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5085     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5086                              getF32Constant(DAG, 0x3d634a1d, dl));
5087     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5088     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5089                              getF32Constant(DAG, 0x3e75fe14, dl));
5090     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5091     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5092                               getF32Constant(DAG, 0x3f317234, dl));
5093     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5094     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5095                                          getF32Constant(DAG, 0x3f800000, dl));
5096   }
5097 
5098   // Add the exponent into the result in integer domain.
5099   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5100   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5101                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5102 }
5103 
5104 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5105 /// limited-precision mode.
5106 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5107                          const TargetLowering &TLI, SDNodeFlags Flags) {
5108   if (Op.getValueType() == MVT::f32 &&
5109       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5110 
5111     // Put the exponent in the right bit position for later addition to the
5112     // final result:
5113     //
5114     // t0 = Op * log2(e)
5115 
5116     // TODO: What fast-math-flags should be set here?
5117     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5118                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5119     return getLimitedPrecisionExp2(t0, dl, DAG);
5120   }
5121 
5122   // No special expansion.
5123   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5124 }
5125 
5126 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5127 /// limited-precision mode.
5128 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5129                          const TargetLowering &TLI, SDNodeFlags Flags) {
5130   // TODO: What fast-math-flags should be set on the floating-point nodes?
5131 
5132   if (Op.getValueType() == MVT::f32 &&
5133       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5134     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5135 
5136     // Scale the exponent by log(2).
5137     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5138     SDValue LogOfExponent =
5139         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5140                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5141 
5142     // Get the significand and build it into a floating-point number with
5143     // exponent of 1.
5144     SDValue X = GetSignificand(DAG, Op1, dl);
5145 
5146     SDValue LogOfMantissa;
5147     if (LimitFloatPrecision <= 6) {
5148       // For floating-point precision of 6:
5149       //
5150       //   LogofMantissa =
5151       //     -1.1609546f +
5152       //       (1.4034025f - 0.23903021f * x) * x;
5153       //
5154       // error 0.0034276066, which is better than 8 bits
5155       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5156                                getF32Constant(DAG, 0xbe74c456, dl));
5157       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5158                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5159       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5160       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5161                                   getF32Constant(DAG, 0x3f949a29, dl));
5162     } else if (LimitFloatPrecision <= 12) {
5163       // For floating-point precision of 12:
5164       //
5165       //   LogOfMantissa =
5166       //     -1.7417939f +
5167       //       (2.8212026f +
5168       //         (-1.4699568f +
5169       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5170       //
5171       // error 0.000061011436, which is 14 bits
5172       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5173                                getF32Constant(DAG, 0xbd67b6d6, dl));
5174       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5175                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5176       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5177       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5178                                getF32Constant(DAG, 0x3fbc278b, dl));
5179       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5180       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5181                                getF32Constant(DAG, 0x40348e95, dl));
5182       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5183       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5184                                   getF32Constant(DAG, 0x3fdef31a, dl));
5185     } else { // LimitFloatPrecision <= 18
5186       // For floating-point precision of 18:
5187       //
5188       //   LogOfMantissa =
5189       //     -2.1072184f +
5190       //       (4.2372794f +
5191       //         (-3.7029485f +
5192       //           (2.2781945f +
5193       //             (-0.87823314f +
5194       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5195       //
5196       // error 0.0000023660568, which is better than 18 bits
5197       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5198                                getF32Constant(DAG, 0xbc91e5ac, dl));
5199       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5200                                getF32Constant(DAG, 0x3e4350aa, dl));
5201       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5202       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5203                                getF32Constant(DAG, 0x3f60d3e3, dl));
5204       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5205       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5206                                getF32Constant(DAG, 0x4011cdf0, dl));
5207       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5208       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5209                                getF32Constant(DAG, 0x406cfd1c, dl));
5210       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5211       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5212                                getF32Constant(DAG, 0x408797cb, dl));
5213       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5214       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5215                                   getF32Constant(DAG, 0x4006dcab, dl));
5216     }
5217 
5218     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5219   }
5220 
5221   // No special expansion.
5222   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5223 }
5224 
5225 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5226 /// limited-precision mode.
5227 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5228                           const TargetLowering &TLI, SDNodeFlags Flags) {
5229   // TODO: What fast-math-flags should be set on the floating-point nodes?
5230 
5231   if (Op.getValueType() == MVT::f32 &&
5232       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5233     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5234 
5235     // Get the exponent.
5236     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5237 
5238     // Get the significand and build it into a floating-point number with
5239     // exponent of 1.
5240     SDValue X = GetSignificand(DAG, Op1, dl);
5241 
5242     // Different possible minimax approximations of significand in
5243     // floating-point for various degrees of accuracy over [1,2].
5244     SDValue Log2ofMantissa;
5245     if (LimitFloatPrecision <= 6) {
5246       // For floating-point precision of 6:
5247       //
5248       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5249       //
5250       // error 0.0049451742, which is more than 7 bits
5251       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5252                                getF32Constant(DAG, 0xbeb08fe0, dl));
5253       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5254                                getF32Constant(DAG, 0x40019463, dl));
5255       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5256       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5257                                    getF32Constant(DAG, 0x3fd6633d, dl));
5258     } else if (LimitFloatPrecision <= 12) {
5259       // For floating-point precision of 12:
5260       //
5261       //   Log2ofMantissa =
5262       //     -2.51285454f +
5263       //       (4.07009056f +
5264       //         (-2.12067489f +
5265       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5266       //
5267       // error 0.0000876136000, which is better than 13 bits
5268       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5269                                getF32Constant(DAG, 0xbda7262e, dl));
5270       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5271                                getF32Constant(DAG, 0x3f25280b, dl));
5272       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5273       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5274                                getF32Constant(DAG, 0x4007b923, dl));
5275       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5276       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5277                                getF32Constant(DAG, 0x40823e2f, dl));
5278       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5279       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5280                                    getF32Constant(DAG, 0x4020d29c, dl));
5281     } else { // LimitFloatPrecision <= 18
5282       // For floating-point precision of 18:
5283       //
5284       //   Log2ofMantissa =
5285       //     -3.0400495f +
5286       //       (6.1129976f +
5287       //         (-5.3420409f +
5288       //           (3.2865683f +
5289       //             (-1.2669343f +
5290       //               (0.27515199f -
5291       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5292       //
5293       // error 0.0000018516, which is better than 18 bits
5294       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5295                                getF32Constant(DAG, 0xbcd2769e, dl));
5296       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5297                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5298       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5299       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5300                                getF32Constant(DAG, 0x3fa22ae7, dl));
5301       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5302       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5303                                getF32Constant(DAG, 0x40525723, dl));
5304       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5305       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5306                                getF32Constant(DAG, 0x40aaf200, dl));
5307       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5308       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5309                                getF32Constant(DAG, 0x40c39dad, dl));
5310       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5311       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5312                                    getF32Constant(DAG, 0x4042902c, dl));
5313     }
5314 
5315     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5316   }
5317 
5318   // No special expansion.
5319   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5320 }
5321 
5322 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5323 /// limited-precision mode.
5324 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5325                            const TargetLowering &TLI, SDNodeFlags Flags) {
5326   // TODO: What fast-math-flags should be set on the floating-point nodes?
5327 
5328   if (Op.getValueType() == MVT::f32 &&
5329       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5330     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5331 
5332     // Scale the exponent by log10(2) [0.30102999f].
5333     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5334     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5335                                         getF32Constant(DAG, 0x3e9a209a, dl));
5336 
5337     // Get the significand and build it into a floating-point number with
5338     // exponent of 1.
5339     SDValue X = GetSignificand(DAG, Op1, dl);
5340 
5341     SDValue Log10ofMantissa;
5342     if (LimitFloatPrecision <= 6) {
5343       // For floating-point precision of 6:
5344       //
5345       //   Log10ofMantissa =
5346       //     -0.50419619f +
5347       //       (0.60948995f - 0.10380950f * x) * x;
5348       //
5349       // error 0.0014886165, which is 6 bits
5350       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5351                                getF32Constant(DAG, 0xbdd49a13, dl));
5352       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5353                                getF32Constant(DAG, 0x3f1c0789, dl));
5354       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5355       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5356                                     getF32Constant(DAG, 0x3f011300, dl));
5357     } else if (LimitFloatPrecision <= 12) {
5358       // For floating-point precision of 12:
5359       //
5360       //   Log10ofMantissa =
5361       //     -0.64831180f +
5362       //       (0.91751397f +
5363       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5364       //
5365       // error 0.00019228036, which is better than 12 bits
5366       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5367                                getF32Constant(DAG, 0x3d431f31, dl));
5368       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5369                                getF32Constant(DAG, 0x3ea21fb2, dl));
5370       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5371       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5372                                getF32Constant(DAG, 0x3f6ae232, dl));
5373       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5374       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5375                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5376     } else { // LimitFloatPrecision <= 18
5377       // For floating-point precision of 18:
5378       //
5379       //   Log10ofMantissa =
5380       //     -0.84299375f +
5381       //       (1.5327582f +
5382       //         (-1.0688956f +
5383       //           (0.49102474f +
5384       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5385       //
5386       // error 0.0000037995730, which is better than 18 bits
5387       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5388                                getF32Constant(DAG, 0x3c5d51ce, dl));
5389       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5390                                getF32Constant(DAG, 0x3e00685a, dl));
5391       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5392       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5393                                getF32Constant(DAG, 0x3efb6798, dl));
5394       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5395       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5396                                getF32Constant(DAG, 0x3f88d192, dl));
5397       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5398       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5399                                getF32Constant(DAG, 0x3fc4316c, dl));
5400       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5401       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5402                                     getF32Constant(DAG, 0x3f57ce70, dl));
5403     }
5404 
5405     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5406   }
5407 
5408   // No special expansion.
5409   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5410 }
5411 
5412 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5413 /// limited-precision mode.
5414 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5415                           const TargetLowering &TLI, SDNodeFlags Flags) {
5416   if (Op.getValueType() == MVT::f32 &&
5417       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5418     return getLimitedPrecisionExp2(Op, dl, DAG);
5419 
5420   // No special expansion.
5421   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5422 }
5423 
5424 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5425 /// limited-precision mode with x == 10.0f.
5426 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5427                          SelectionDAG &DAG, const TargetLowering &TLI,
5428                          SDNodeFlags Flags) {
5429   bool IsExp10 = false;
5430   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5431       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5432     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5433       APFloat Ten(10.0f);
5434       IsExp10 = LHSC->isExactlyValue(Ten);
5435     }
5436   }
5437 
5438   // TODO: What fast-math-flags should be set on the FMUL node?
5439   if (IsExp10) {
5440     // Put the exponent in the right bit position for later addition to the
5441     // final result:
5442     //
5443     //   #define LOG2OF10 3.3219281f
5444     //   t0 = Op * LOG2OF10;
5445     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5446                              getF32Constant(DAG, 0x40549a78, dl));
5447     return getLimitedPrecisionExp2(t0, dl, DAG);
5448   }
5449 
5450   // No special expansion.
5451   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5452 }
5453 
5454 /// ExpandPowI - Expand a llvm.powi intrinsic.
5455 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5456                           SelectionDAG &DAG) {
5457   // If RHS is a constant, we can expand this out to a multiplication tree if
5458   // it's beneficial on the target, otherwise we end up lowering to a call to
5459   // __powidf2 (for example).
5460   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5461     unsigned Val = RHSC->getSExtValue();
5462 
5463     // powi(x, 0) -> 1.0
5464     if (Val == 0)
5465       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5466 
5467     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5468             Val, DAG.shouldOptForSize())) {
5469       // Get the exponent as a positive value.
5470       if ((int)Val < 0)
5471         Val = -Val;
5472       // We use the simple binary decomposition method to generate the multiply
5473       // sequence.  There are more optimal ways to do this (for example,
5474       // powi(x,15) generates one more multiply than it should), but this has
5475       // the benefit of being both really simple and much better than a libcall.
5476       SDValue Res; // Logically starts equal to 1.0
5477       SDValue CurSquare = LHS;
5478       // TODO: Intrinsics should have fast-math-flags that propagate to these
5479       // nodes.
5480       while (Val) {
5481         if (Val & 1) {
5482           if (Res.getNode())
5483             Res =
5484                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5485           else
5486             Res = CurSquare; // 1.0*CurSquare.
5487         }
5488 
5489         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5490                                 CurSquare, CurSquare);
5491         Val >>= 1;
5492       }
5493 
5494       // If the original was negative, invert the result, producing 1/(x*x*x).
5495       if (RHSC->getSExtValue() < 0)
5496         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5497                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5498       return Res;
5499     }
5500   }
5501 
5502   // Otherwise, expand to a libcall.
5503   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5504 }
5505 
5506 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5507                             SDValue LHS, SDValue RHS, SDValue Scale,
5508                             SelectionDAG &DAG, const TargetLowering &TLI) {
5509   EVT VT = LHS.getValueType();
5510   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5511   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5512   LLVMContext &Ctx = *DAG.getContext();
5513 
5514   // If the type is legal but the operation isn't, this node might survive all
5515   // the way to operation legalization. If we end up there and we do not have
5516   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5517   // node.
5518 
5519   // Coax the legalizer into expanding the node during type legalization instead
5520   // by bumping the size by one bit. This will force it to Promote, enabling the
5521   // early expansion and avoiding the need to expand later.
5522 
5523   // We don't have to do this if Scale is 0; that can always be expanded, unless
5524   // it's a saturating signed operation. Those can experience true integer
5525   // division overflow, a case which we must avoid.
5526 
5527   // FIXME: We wouldn't have to do this (or any of the early
5528   // expansion/promotion) if it was possible to expand a libcall of an
5529   // illegal type during operation legalization. But it's not, so things
5530   // get a bit hacky.
5531   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5532   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5533       (TLI.isTypeLegal(VT) ||
5534        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5535     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5536         Opcode, VT, ScaleInt);
5537     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5538       EVT PromVT;
5539       if (VT.isScalarInteger())
5540         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5541       else if (VT.isVector()) {
5542         PromVT = VT.getVectorElementType();
5543         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5544         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5545       } else
5546         llvm_unreachable("Wrong VT for DIVFIX?");
5547       if (Signed) {
5548         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5549         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5550       } else {
5551         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5552         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5553       }
5554       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5555       // For saturating operations, we need to shift up the LHS to get the
5556       // proper saturation width, and then shift down again afterwards.
5557       if (Saturating)
5558         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5559                           DAG.getConstant(1, DL, ShiftTy));
5560       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5561       if (Saturating)
5562         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5563                           DAG.getConstant(1, DL, ShiftTy));
5564       return DAG.getZExtOrTrunc(Res, DL, VT);
5565     }
5566   }
5567 
5568   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5569 }
5570 
5571 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5572 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5573 static void
5574 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5575                      const SDValue &N) {
5576   switch (N.getOpcode()) {
5577   case ISD::CopyFromReg: {
5578     SDValue Op = N.getOperand(1);
5579     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5580                       Op.getValueType().getSizeInBits());
5581     return;
5582   }
5583   case ISD::BITCAST:
5584   case ISD::AssertZext:
5585   case ISD::AssertSext:
5586   case ISD::TRUNCATE:
5587     getUnderlyingArgRegs(Regs, N.getOperand(0));
5588     return;
5589   case ISD::BUILD_PAIR:
5590   case ISD::BUILD_VECTOR:
5591   case ISD::CONCAT_VECTORS:
5592     for (SDValue Op : N->op_values())
5593       getUnderlyingArgRegs(Regs, Op);
5594     return;
5595   default:
5596     return;
5597   }
5598 }
5599 
5600 /// If the DbgValueInst is a dbg_value of a function argument, create the
5601 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5602 /// instruction selection, they will be inserted to the entry BB.
5603 /// We don't currently support this for variadic dbg_values, as they shouldn't
5604 /// appear for function arguments or in the prologue.
5605 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5606     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5607     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5608   const Argument *Arg = dyn_cast<Argument>(V);
5609   if (!Arg)
5610     return false;
5611 
5612   MachineFunction &MF = DAG.getMachineFunction();
5613   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5614 
5615   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5616   // we've been asked to pursue.
5617   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5618                               bool Indirect) {
5619     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5620       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5621       // pointing at the VReg, which will be patched up later.
5622       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5623       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5624           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5625           /* isKill */ false, /* isDead */ false,
5626           /* isUndef */ false, /* isEarlyClobber */ false,
5627           /* SubReg */ 0, /* isDebug */ true)});
5628 
5629       auto *NewDIExpr = FragExpr;
5630       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5631       // the DIExpression.
5632       if (Indirect)
5633         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5634       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5635       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5636       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5637     } else {
5638       // Create a completely standard DBG_VALUE.
5639       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5640       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5641     }
5642   };
5643 
5644   if (Kind == FuncArgumentDbgValueKind::Value) {
5645     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5646     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5647     // the entry block.
5648     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5649     if (!IsInEntryBlock)
5650       return false;
5651 
5652     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5653     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5654     // variable that also is a param.
5655     //
5656     // Although, if we are at the top of the entry block already, we can still
5657     // emit using ArgDbgValue. This might catch some situations when the
5658     // dbg.value refers to an argument that isn't used in the entry block, so
5659     // any CopyToReg node would be optimized out and the only way to express
5660     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5661     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5662     // we should only emit as ArgDbgValue if the Variable is an argument to the
5663     // current function, and the dbg.value intrinsic is found in the entry
5664     // block.
5665     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5666         !DL->getInlinedAt();
5667     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5668     if (!IsInPrologue && !VariableIsFunctionInputArg)
5669       return false;
5670 
5671     // Here we assume that a function argument on IR level only can be used to
5672     // describe one input parameter on source level. If we for example have
5673     // source code like this
5674     //
5675     //    struct A { long x, y; };
5676     //    void foo(struct A a, long b) {
5677     //      ...
5678     //      b = a.x;
5679     //      ...
5680     //    }
5681     //
5682     // and IR like this
5683     //
5684     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5685     //  entry:
5686     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5687     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5688     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5689     //    ...
5690     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5691     //    ...
5692     //
5693     // then the last dbg.value is describing a parameter "b" using a value that
5694     // is an argument. But since we already has used %a1 to describe a parameter
5695     // we should not handle that last dbg.value here (that would result in an
5696     // incorrect hoisting of the DBG_VALUE to the function entry).
5697     // Notice that we allow one dbg.value per IR level argument, to accommodate
5698     // for the situation with fragments above.
5699     if (VariableIsFunctionInputArg) {
5700       unsigned ArgNo = Arg->getArgNo();
5701       if (ArgNo >= FuncInfo.DescribedArgs.size())
5702         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5703       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5704         return false;
5705       FuncInfo.DescribedArgs.set(ArgNo);
5706     }
5707   }
5708 
5709   bool IsIndirect = false;
5710   std::optional<MachineOperand> Op;
5711   // Some arguments' frame index is recorded during argument lowering.
5712   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5713   if (FI != std::numeric_limits<int>::max())
5714     Op = MachineOperand::CreateFI(FI);
5715 
5716   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5717   if (!Op && N.getNode()) {
5718     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5719     Register Reg;
5720     if (ArgRegsAndSizes.size() == 1)
5721       Reg = ArgRegsAndSizes.front().first;
5722 
5723     if (Reg && Reg.isVirtual()) {
5724       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5725       Register PR = RegInfo.getLiveInPhysReg(Reg);
5726       if (PR)
5727         Reg = PR;
5728     }
5729     if (Reg) {
5730       Op = MachineOperand::CreateReg(Reg, false);
5731       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5732     }
5733   }
5734 
5735   if (!Op && N.getNode()) {
5736     // Check if frame index is available.
5737     SDValue LCandidate = peekThroughBitcasts(N);
5738     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5739       if (FrameIndexSDNode *FINode =
5740           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5741         Op = MachineOperand::CreateFI(FINode->getIndex());
5742   }
5743 
5744   if (!Op) {
5745     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5746     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5747                                          SplitRegs) {
5748       unsigned Offset = 0;
5749       for (const auto &RegAndSize : SplitRegs) {
5750         // If the expression is already a fragment, the current register
5751         // offset+size might extend beyond the fragment. In this case, only
5752         // the register bits that are inside the fragment are relevant.
5753         int RegFragmentSizeInBits = RegAndSize.second;
5754         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5755           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5756           // The register is entirely outside the expression fragment,
5757           // so is irrelevant for debug info.
5758           if (Offset >= ExprFragmentSizeInBits)
5759             break;
5760           // The register is partially outside the expression fragment, only
5761           // the low bits within the fragment are relevant for debug info.
5762           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5763             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5764           }
5765         }
5766 
5767         auto FragmentExpr = DIExpression::createFragmentExpression(
5768             Expr, Offset, RegFragmentSizeInBits);
5769         Offset += RegAndSize.second;
5770         // If a valid fragment expression cannot be created, the variable's
5771         // correct value cannot be determined and so it is set as Undef.
5772         if (!FragmentExpr) {
5773           SDDbgValue *SDV = DAG.getConstantDbgValue(
5774               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5775           DAG.AddDbgValue(SDV, false);
5776           continue;
5777         }
5778         MachineInstr *NewMI =
5779             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5780                              Kind != FuncArgumentDbgValueKind::Value);
5781         FuncInfo.ArgDbgValues.push_back(NewMI);
5782       }
5783     };
5784 
5785     // Check if ValueMap has reg number.
5786     DenseMap<const Value *, Register>::const_iterator
5787       VMI = FuncInfo.ValueMap.find(V);
5788     if (VMI != FuncInfo.ValueMap.end()) {
5789       const auto &TLI = DAG.getTargetLoweringInfo();
5790       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5791                        V->getType(), std::nullopt);
5792       if (RFV.occupiesMultipleRegs()) {
5793         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5794         return true;
5795       }
5796 
5797       Op = MachineOperand::CreateReg(VMI->second, false);
5798       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5799     } else if (ArgRegsAndSizes.size() > 1) {
5800       // This was split due to the calling convention, and no virtual register
5801       // mapping exists for the value.
5802       splitMultiRegDbgValue(ArgRegsAndSizes);
5803       return true;
5804     }
5805   }
5806 
5807   if (!Op)
5808     return false;
5809 
5810   // If the expression refers to the entry value of an Argument, use the
5811   // corresponding livein physical register. As per the Verifier, this is only
5812   // allowed for swiftasync Arguments.
5813   if (Op->isReg() && Expr->isEntryValue()) {
5814     assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
5815     auto OpReg = Op->getReg();
5816     for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
5817       if (OpReg == VirtReg || OpReg == PhysReg) {
5818         SDDbgValue *SDV = DAG.getVRegDbgValue(
5819             Variable, Expr, PhysReg,
5820             Kind != FuncArgumentDbgValueKind::Value /*is indirect*/, DL,
5821             SDNodeOrder);
5822         DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
5823         return true;
5824       }
5825     LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
5826                          "couldn't find a physical register\n");
5827     return true;
5828   }
5829 
5830   assert(Variable->isValidLocationForIntrinsic(DL) &&
5831          "Expected inlined-at fields to agree");
5832   MachineInstr *NewMI = nullptr;
5833 
5834   if (Op->isReg())
5835     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5836   else
5837     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5838                     Variable, Expr);
5839 
5840   // Otherwise, use ArgDbgValues.
5841   FuncInfo.ArgDbgValues.push_back(NewMI);
5842   return true;
5843 }
5844 
5845 /// Return the appropriate SDDbgValue based on N.
5846 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5847                                              DILocalVariable *Variable,
5848                                              DIExpression *Expr,
5849                                              const DebugLoc &dl,
5850                                              unsigned DbgSDNodeOrder) {
5851   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5852     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5853     // stack slot locations.
5854     //
5855     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5856     // debug values here after optimization:
5857     //
5858     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5859     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5860     //
5861     // Both describe the direct values of their associated variables.
5862     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5863                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5864   }
5865   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5866                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5867 }
5868 
5869 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5870   switch (Intrinsic) {
5871   case Intrinsic::smul_fix:
5872     return ISD::SMULFIX;
5873   case Intrinsic::umul_fix:
5874     return ISD::UMULFIX;
5875   case Intrinsic::smul_fix_sat:
5876     return ISD::SMULFIXSAT;
5877   case Intrinsic::umul_fix_sat:
5878     return ISD::UMULFIXSAT;
5879   case Intrinsic::sdiv_fix:
5880     return ISD::SDIVFIX;
5881   case Intrinsic::udiv_fix:
5882     return ISD::UDIVFIX;
5883   case Intrinsic::sdiv_fix_sat:
5884     return ISD::SDIVFIXSAT;
5885   case Intrinsic::udiv_fix_sat:
5886     return ISD::UDIVFIXSAT;
5887   default:
5888     llvm_unreachable("Unhandled fixed point intrinsic");
5889   }
5890 }
5891 
5892 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5893                                            const char *FunctionName) {
5894   assert(FunctionName && "FunctionName must not be nullptr");
5895   SDValue Callee = DAG.getExternalSymbol(
5896       FunctionName,
5897       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5898   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5899 }
5900 
5901 /// Given a @llvm.call.preallocated.setup, return the corresponding
5902 /// preallocated call.
5903 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5904   assert(cast<CallBase>(PreallocatedSetup)
5905                  ->getCalledFunction()
5906                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5907          "expected call_preallocated_setup Value");
5908   for (const auto *U : PreallocatedSetup->users()) {
5909     auto *UseCall = cast<CallBase>(U);
5910     const Function *Fn = UseCall->getCalledFunction();
5911     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5912       return UseCall;
5913     }
5914   }
5915   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5916 }
5917 
5918 /// Lower the call to the specified intrinsic function.
5919 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5920                                              unsigned Intrinsic) {
5921   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5922   SDLoc sdl = getCurSDLoc();
5923   DebugLoc dl = getCurDebugLoc();
5924   SDValue Res;
5925 
5926   SDNodeFlags Flags;
5927   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5928     Flags.copyFMF(*FPOp);
5929 
5930   switch (Intrinsic) {
5931   default:
5932     // By default, turn this into a target intrinsic node.
5933     visitTargetIntrinsic(I, Intrinsic);
5934     return;
5935   case Intrinsic::vscale: {
5936     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5937     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5938     return;
5939   }
5940   case Intrinsic::vastart:  visitVAStart(I); return;
5941   case Intrinsic::vaend:    visitVAEnd(I); return;
5942   case Intrinsic::vacopy:   visitVACopy(I); return;
5943   case Intrinsic::returnaddress:
5944     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5945                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5946                              getValue(I.getArgOperand(0))));
5947     return;
5948   case Intrinsic::addressofreturnaddress:
5949     setValue(&I,
5950              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5951                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5952     return;
5953   case Intrinsic::sponentry:
5954     setValue(&I,
5955              DAG.getNode(ISD::SPONENTRY, sdl,
5956                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5957     return;
5958   case Intrinsic::frameaddress:
5959     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5960                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5961                              getValue(I.getArgOperand(0))));
5962     return;
5963   case Intrinsic::read_volatile_register:
5964   case Intrinsic::read_register: {
5965     Value *Reg = I.getArgOperand(0);
5966     SDValue Chain = getRoot();
5967     SDValue RegName =
5968         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5969     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5970     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5971       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5972     setValue(&I, Res);
5973     DAG.setRoot(Res.getValue(1));
5974     return;
5975   }
5976   case Intrinsic::write_register: {
5977     Value *Reg = I.getArgOperand(0);
5978     Value *RegValue = I.getArgOperand(1);
5979     SDValue Chain = getRoot();
5980     SDValue RegName =
5981         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5982     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5983                             RegName, getValue(RegValue)));
5984     return;
5985   }
5986   case Intrinsic::memcpy: {
5987     const auto &MCI = cast<MemCpyInst>(I);
5988     SDValue Op1 = getValue(I.getArgOperand(0));
5989     SDValue Op2 = getValue(I.getArgOperand(1));
5990     SDValue Op3 = getValue(I.getArgOperand(2));
5991     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5992     Align DstAlign = MCI.getDestAlign().valueOrOne();
5993     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5994     Align Alignment = std::min(DstAlign, SrcAlign);
5995     bool isVol = MCI.isVolatile();
5996     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5997     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5998     // node.
5999     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6000     SDValue MC = DAG.getMemcpy(
6001         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6002         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
6003         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6004     updateDAGForMaybeTailCall(MC);
6005     return;
6006   }
6007   case Intrinsic::memcpy_inline: {
6008     const auto &MCI = cast<MemCpyInlineInst>(I);
6009     SDValue Dst = getValue(I.getArgOperand(0));
6010     SDValue Src = getValue(I.getArgOperand(1));
6011     SDValue Size = getValue(I.getArgOperand(2));
6012     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6013     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6014     Align DstAlign = MCI.getDestAlign().valueOrOne();
6015     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6016     Align Alignment = std::min(DstAlign, SrcAlign);
6017     bool isVol = MCI.isVolatile();
6018     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6019     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6020     // node.
6021     SDValue MC = DAG.getMemcpy(
6022         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6023         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6024         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6025     updateDAGForMaybeTailCall(MC);
6026     return;
6027   }
6028   case Intrinsic::memset: {
6029     const auto &MSI = cast<MemSetInst>(I);
6030     SDValue Op1 = getValue(I.getArgOperand(0));
6031     SDValue Op2 = getValue(I.getArgOperand(1));
6032     SDValue Op3 = getValue(I.getArgOperand(2));
6033     // @llvm.memset defines 0 and 1 to both mean no alignment.
6034     Align Alignment = MSI.getDestAlign().valueOrOne();
6035     bool isVol = MSI.isVolatile();
6036     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6037     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6038     SDValue MS = DAG.getMemset(
6039         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6040         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6041     updateDAGForMaybeTailCall(MS);
6042     return;
6043   }
6044   case Intrinsic::memset_inline: {
6045     const auto &MSII = cast<MemSetInlineInst>(I);
6046     SDValue Dst = getValue(I.getArgOperand(0));
6047     SDValue Value = getValue(I.getArgOperand(1));
6048     SDValue Size = getValue(I.getArgOperand(2));
6049     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6050     // @llvm.memset defines 0 and 1 to both mean no alignment.
6051     Align DstAlign = MSII.getDestAlign().valueOrOne();
6052     bool isVol = MSII.isVolatile();
6053     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6054     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6055     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6056                                /* AlwaysInline */ true, isTC,
6057                                MachinePointerInfo(I.getArgOperand(0)),
6058                                I.getAAMetadata());
6059     updateDAGForMaybeTailCall(MC);
6060     return;
6061   }
6062   case Intrinsic::memmove: {
6063     const auto &MMI = cast<MemMoveInst>(I);
6064     SDValue Op1 = getValue(I.getArgOperand(0));
6065     SDValue Op2 = getValue(I.getArgOperand(1));
6066     SDValue Op3 = getValue(I.getArgOperand(2));
6067     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6068     Align DstAlign = MMI.getDestAlign().valueOrOne();
6069     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6070     Align Alignment = std::min(DstAlign, SrcAlign);
6071     bool isVol = MMI.isVolatile();
6072     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6073     // FIXME: Support passing different dest/src alignments to the memmove DAG
6074     // node.
6075     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6076     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6077                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6078                                 MachinePointerInfo(I.getArgOperand(1)),
6079                                 I.getAAMetadata(), AA);
6080     updateDAGForMaybeTailCall(MM);
6081     return;
6082   }
6083   case Intrinsic::memcpy_element_unordered_atomic: {
6084     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6085     SDValue Dst = getValue(MI.getRawDest());
6086     SDValue Src = getValue(MI.getRawSource());
6087     SDValue Length = getValue(MI.getLength());
6088 
6089     Type *LengthTy = MI.getLength()->getType();
6090     unsigned ElemSz = MI.getElementSizeInBytes();
6091     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6092     SDValue MC =
6093         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6094                             isTC, MachinePointerInfo(MI.getRawDest()),
6095                             MachinePointerInfo(MI.getRawSource()));
6096     updateDAGForMaybeTailCall(MC);
6097     return;
6098   }
6099   case Intrinsic::memmove_element_unordered_atomic: {
6100     auto &MI = cast<AtomicMemMoveInst>(I);
6101     SDValue Dst = getValue(MI.getRawDest());
6102     SDValue Src = getValue(MI.getRawSource());
6103     SDValue Length = getValue(MI.getLength());
6104 
6105     Type *LengthTy = MI.getLength()->getType();
6106     unsigned ElemSz = MI.getElementSizeInBytes();
6107     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6108     SDValue MC =
6109         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6110                              isTC, MachinePointerInfo(MI.getRawDest()),
6111                              MachinePointerInfo(MI.getRawSource()));
6112     updateDAGForMaybeTailCall(MC);
6113     return;
6114   }
6115   case Intrinsic::memset_element_unordered_atomic: {
6116     auto &MI = cast<AtomicMemSetInst>(I);
6117     SDValue Dst = getValue(MI.getRawDest());
6118     SDValue Val = getValue(MI.getValue());
6119     SDValue Length = getValue(MI.getLength());
6120 
6121     Type *LengthTy = MI.getLength()->getType();
6122     unsigned ElemSz = MI.getElementSizeInBytes();
6123     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6124     SDValue MC =
6125         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6126                             isTC, MachinePointerInfo(MI.getRawDest()));
6127     updateDAGForMaybeTailCall(MC);
6128     return;
6129   }
6130   case Intrinsic::call_preallocated_setup: {
6131     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6132     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6133     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6134                               getRoot(), SrcValue);
6135     setValue(&I, Res);
6136     DAG.setRoot(Res);
6137     return;
6138   }
6139   case Intrinsic::call_preallocated_arg: {
6140     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6141     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6142     SDValue Ops[3];
6143     Ops[0] = getRoot();
6144     Ops[1] = SrcValue;
6145     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6146                                    MVT::i32); // arg index
6147     SDValue Res = DAG.getNode(
6148         ISD::PREALLOCATED_ARG, sdl,
6149         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6150     setValue(&I, Res);
6151     DAG.setRoot(Res.getValue(1));
6152     return;
6153   }
6154   case Intrinsic::dbg_declare: {
6155     const auto &DI = cast<DbgDeclareInst>(I);
6156     // Debug intrinsics are handled separately in assignment tracking mode.
6157     // Some intrinsics are handled right after Argument lowering.
6158     if (AssignmentTrackingEnabled ||
6159         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6160       return;
6161     // Assume dbg.declare can not currently use DIArgList, i.e.
6162     // it is non-variadic.
6163     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6164     DILocalVariable *Variable = DI.getVariable();
6165     DIExpression *Expression = DI.getExpression();
6166     dropDanglingDebugInfo(Variable, Expression);
6167     assert(Variable && "Missing variable");
6168     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6169                       << "\n");
6170     // Check if address has undef value.
6171     const Value *Address = DI.getVariableLocationOp(0);
6172     if (!Address || isa<UndefValue>(Address) ||
6173         (Address->use_empty() && !isa<Argument>(Address))) {
6174       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6175                         << " (bad/undef/unused-arg address)\n");
6176       return;
6177     }
6178 
6179     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6180 
6181     SDValue &N = NodeMap[Address];
6182     if (!N.getNode() && isa<Argument>(Address))
6183       // Check unused arguments map.
6184       N = UnusedArgNodeMap[Address];
6185     SDDbgValue *SDV;
6186     if (N.getNode()) {
6187       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6188         Address = BCI->getOperand(0);
6189       // Parameters are handled specially.
6190       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6191       if (isParameter && FINode) {
6192         // Byval parameter. We have a frame index at this point.
6193         SDV =
6194             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6195                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6196       } else if (isa<Argument>(Address)) {
6197         // Address is an argument, so try to emit its dbg value using
6198         // virtual register info from the FuncInfo.ValueMap.
6199         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6200                                  FuncArgumentDbgValueKind::Declare, N);
6201         return;
6202       } else {
6203         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6204                               true, dl, SDNodeOrder);
6205       }
6206       DAG.AddDbgValue(SDV, isParameter);
6207     } else {
6208       // If Address is an argument then try to emit its dbg value using
6209       // virtual register info from the FuncInfo.ValueMap.
6210       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6211                                     FuncArgumentDbgValueKind::Declare, N)) {
6212         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6213                           << " (could not emit func-arg dbg_value)\n");
6214       }
6215     }
6216     return;
6217   }
6218   case Intrinsic::dbg_label: {
6219     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6220     DILabel *Label = DI.getLabel();
6221     assert(Label && "Missing label");
6222 
6223     SDDbgLabel *SDV;
6224     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6225     DAG.AddDbgLabel(SDV);
6226     return;
6227   }
6228   case Intrinsic::dbg_assign: {
6229     // Debug intrinsics are handled seperately in assignment tracking mode.
6230     if (AssignmentTrackingEnabled)
6231       return;
6232     // If assignment tracking hasn't been enabled then fall through and treat
6233     // the dbg.assign as a dbg.value.
6234     [[fallthrough]];
6235   }
6236   case Intrinsic::dbg_value: {
6237     // Debug intrinsics are handled seperately in assignment tracking mode.
6238     if (AssignmentTrackingEnabled)
6239       return;
6240     const DbgValueInst &DI = cast<DbgValueInst>(I);
6241     assert(DI.getVariable() && "Missing variable");
6242 
6243     DILocalVariable *Variable = DI.getVariable();
6244     DIExpression *Expression = DI.getExpression();
6245     dropDanglingDebugInfo(Variable, Expression);
6246 
6247     if (DI.isKillLocation()) {
6248       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6249       return;
6250     }
6251 
6252     SmallVector<Value *, 4> Values(DI.getValues());
6253     if (Values.empty())
6254       return;
6255 
6256     bool IsVariadic = DI.hasArgList();
6257     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6258                           SDNodeOrder, IsVariadic))
6259       addDanglingDebugInfo(&DI, SDNodeOrder);
6260     return;
6261   }
6262 
6263   case Intrinsic::eh_typeid_for: {
6264     // Find the type id for the given typeinfo.
6265     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6266     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6267     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6268     setValue(&I, Res);
6269     return;
6270   }
6271 
6272   case Intrinsic::eh_return_i32:
6273   case Intrinsic::eh_return_i64:
6274     DAG.getMachineFunction().setCallsEHReturn(true);
6275     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6276                             MVT::Other,
6277                             getControlRoot(),
6278                             getValue(I.getArgOperand(0)),
6279                             getValue(I.getArgOperand(1))));
6280     return;
6281   case Intrinsic::eh_unwind_init:
6282     DAG.getMachineFunction().setCallsUnwindInit(true);
6283     return;
6284   case Intrinsic::eh_dwarf_cfa:
6285     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6286                              TLI.getPointerTy(DAG.getDataLayout()),
6287                              getValue(I.getArgOperand(0))));
6288     return;
6289   case Intrinsic::eh_sjlj_callsite: {
6290     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6291     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6292     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6293 
6294     MMI.setCurrentCallSite(CI->getZExtValue());
6295     return;
6296   }
6297   case Intrinsic::eh_sjlj_functioncontext: {
6298     // Get and store the index of the function context.
6299     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6300     AllocaInst *FnCtx =
6301       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6302     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6303     MFI.setFunctionContextIndex(FI);
6304     return;
6305   }
6306   case Intrinsic::eh_sjlj_setjmp: {
6307     SDValue Ops[2];
6308     Ops[0] = getRoot();
6309     Ops[1] = getValue(I.getArgOperand(0));
6310     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6311                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6312     setValue(&I, Op.getValue(0));
6313     DAG.setRoot(Op.getValue(1));
6314     return;
6315   }
6316   case Intrinsic::eh_sjlj_longjmp:
6317     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6318                             getRoot(), getValue(I.getArgOperand(0))));
6319     return;
6320   case Intrinsic::eh_sjlj_setup_dispatch:
6321     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6322                             getRoot()));
6323     return;
6324   case Intrinsic::masked_gather:
6325     visitMaskedGather(I);
6326     return;
6327   case Intrinsic::masked_load:
6328     visitMaskedLoad(I);
6329     return;
6330   case Intrinsic::masked_scatter:
6331     visitMaskedScatter(I);
6332     return;
6333   case Intrinsic::masked_store:
6334     visitMaskedStore(I);
6335     return;
6336   case Intrinsic::masked_expandload:
6337     visitMaskedLoad(I, true /* IsExpanding */);
6338     return;
6339   case Intrinsic::masked_compressstore:
6340     visitMaskedStore(I, true /* IsCompressing */);
6341     return;
6342   case Intrinsic::powi:
6343     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6344                             getValue(I.getArgOperand(1)), DAG));
6345     return;
6346   case Intrinsic::log:
6347     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6348     return;
6349   case Intrinsic::log2:
6350     setValue(&I,
6351              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6352     return;
6353   case Intrinsic::log10:
6354     setValue(&I,
6355              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6356     return;
6357   case Intrinsic::exp:
6358     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6359     return;
6360   case Intrinsic::exp2:
6361     setValue(&I,
6362              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6363     return;
6364   case Intrinsic::pow:
6365     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6366                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6367     return;
6368   case Intrinsic::sqrt:
6369   case Intrinsic::fabs:
6370   case Intrinsic::sin:
6371   case Intrinsic::cos:
6372   case Intrinsic::floor:
6373   case Intrinsic::ceil:
6374   case Intrinsic::trunc:
6375   case Intrinsic::rint:
6376   case Intrinsic::nearbyint:
6377   case Intrinsic::round:
6378   case Intrinsic::roundeven:
6379   case Intrinsic::canonicalize: {
6380     unsigned Opcode;
6381     switch (Intrinsic) {
6382     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6383     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6384     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6385     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6386     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6387     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6388     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6389     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6390     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6391     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6392     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6393     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6394     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6395     }
6396 
6397     setValue(&I, DAG.getNode(Opcode, sdl,
6398                              getValue(I.getArgOperand(0)).getValueType(),
6399                              getValue(I.getArgOperand(0)), Flags));
6400     return;
6401   }
6402   case Intrinsic::lround:
6403   case Intrinsic::llround:
6404   case Intrinsic::lrint:
6405   case Intrinsic::llrint: {
6406     unsigned Opcode;
6407     switch (Intrinsic) {
6408     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6409     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6410     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6411     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6412     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6413     }
6414 
6415     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6416     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6417                              getValue(I.getArgOperand(0))));
6418     return;
6419   }
6420   case Intrinsic::minnum:
6421     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6422                              getValue(I.getArgOperand(0)).getValueType(),
6423                              getValue(I.getArgOperand(0)),
6424                              getValue(I.getArgOperand(1)), Flags));
6425     return;
6426   case Intrinsic::maxnum:
6427     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6428                              getValue(I.getArgOperand(0)).getValueType(),
6429                              getValue(I.getArgOperand(0)),
6430                              getValue(I.getArgOperand(1)), Flags));
6431     return;
6432   case Intrinsic::minimum:
6433     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6434                              getValue(I.getArgOperand(0)).getValueType(),
6435                              getValue(I.getArgOperand(0)),
6436                              getValue(I.getArgOperand(1)), Flags));
6437     return;
6438   case Intrinsic::maximum:
6439     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6440                              getValue(I.getArgOperand(0)).getValueType(),
6441                              getValue(I.getArgOperand(0)),
6442                              getValue(I.getArgOperand(1)), Flags));
6443     return;
6444   case Intrinsic::copysign:
6445     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6446                              getValue(I.getArgOperand(0)).getValueType(),
6447                              getValue(I.getArgOperand(0)),
6448                              getValue(I.getArgOperand(1)), Flags));
6449     return;
6450   case Intrinsic::arithmetic_fence: {
6451     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6452                              getValue(I.getArgOperand(0)).getValueType(),
6453                              getValue(I.getArgOperand(0)), Flags));
6454     return;
6455   }
6456   case Intrinsic::fma:
6457     setValue(&I, DAG.getNode(
6458                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6459                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6460                      getValue(I.getArgOperand(2)), Flags));
6461     return;
6462 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6463   case Intrinsic::INTRINSIC:
6464 #include "llvm/IR/ConstrainedOps.def"
6465     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6466     return;
6467 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6468 #include "llvm/IR/VPIntrinsics.def"
6469     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6470     return;
6471   case Intrinsic::fptrunc_round: {
6472     // Get the last argument, the metadata and convert it to an integer in the
6473     // call
6474     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6475     std::optional<RoundingMode> RoundMode =
6476         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6477 
6478     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6479 
6480     // Propagate fast-math-flags from IR to node(s).
6481     SDNodeFlags Flags;
6482     Flags.copyFMF(*cast<FPMathOperator>(&I));
6483     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6484 
6485     SDValue Result;
6486     Result = DAG.getNode(
6487         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6488         DAG.getTargetConstant((int)*RoundMode, sdl,
6489                               TLI.getPointerTy(DAG.getDataLayout())));
6490     setValue(&I, Result);
6491 
6492     return;
6493   }
6494   case Intrinsic::fmuladd: {
6495     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6496     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6497         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6498       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6499                                getValue(I.getArgOperand(0)).getValueType(),
6500                                getValue(I.getArgOperand(0)),
6501                                getValue(I.getArgOperand(1)),
6502                                getValue(I.getArgOperand(2)), Flags));
6503     } else {
6504       // TODO: Intrinsic calls should have fast-math-flags.
6505       SDValue Mul = DAG.getNode(
6506           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6507           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6508       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6509                                 getValue(I.getArgOperand(0)).getValueType(),
6510                                 Mul, getValue(I.getArgOperand(2)), Flags);
6511       setValue(&I, Add);
6512     }
6513     return;
6514   }
6515   case Intrinsic::convert_to_fp16:
6516     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6517                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6518                                          getValue(I.getArgOperand(0)),
6519                                          DAG.getTargetConstant(0, sdl,
6520                                                                MVT::i32))));
6521     return;
6522   case Intrinsic::convert_from_fp16:
6523     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6524                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6525                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6526                                          getValue(I.getArgOperand(0)))));
6527     return;
6528   case Intrinsic::fptosi_sat: {
6529     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6530     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6531                              getValue(I.getArgOperand(0)),
6532                              DAG.getValueType(VT.getScalarType())));
6533     return;
6534   }
6535   case Intrinsic::fptoui_sat: {
6536     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6537     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6538                              getValue(I.getArgOperand(0)),
6539                              DAG.getValueType(VT.getScalarType())));
6540     return;
6541   }
6542   case Intrinsic::set_rounding:
6543     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6544                       {getRoot(), getValue(I.getArgOperand(0))});
6545     setValue(&I, Res);
6546     DAG.setRoot(Res.getValue(0));
6547     return;
6548   case Intrinsic::is_fpclass: {
6549     const DataLayout DLayout = DAG.getDataLayout();
6550     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6551     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6552     FPClassTest Test = static_cast<FPClassTest>(
6553         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6554     MachineFunction &MF = DAG.getMachineFunction();
6555     const Function &F = MF.getFunction();
6556     SDValue Op = getValue(I.getArgOperand(0));
6557     SDNodeFlags Flags;
6558     Flags.setNoFPExcept(
6559         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6560     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6561     // expansion can use illegal types. Making expansion early allows
6562     // legalizing these types prior to selection.
6563     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6564       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6565       setValue(&I, Result);
6566       return;
6567     }
6568 
6569     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6570     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6571     setValue(&I, V);
6572     return;
6573   }
6574   case Intrinsic::get_fpenv: {
6575     const DataLayout DLayout = DAG.getDataLayout();
6576     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
6577     Align TempAlign = DAG.getEVTAlign(EnvVT);
6578     SDValue Chain = DAG.getRoot();
6579     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
6580     // and temporary storage in stack.
6581     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
6582       Res = DAG.getNode(
6583           ISD::GET_FPENV, sdl,
6584           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6585                         MVT::Other),
6586           Chain);
6587     } else {
6588       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6589       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6590       auto MPI =
6591           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6592       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6593           MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize,
6594           TempAlign);
6595       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6596       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
6597     }
6598     setValue(&I, Res);
6599     DAG.setRoot(Res.getValue(1));
6600     return;
6601   }
6602   case Intrinsic::set_fpenv: {
6603     const DataLayout DLayout = DAG.getDataLayout();
6604     SDValue Env = getValue(I.getArgOperand(0));
6605     EVT EnvVT = Env.getValueType();
6606     Align TempAlign = DAG.getEVTAlign(EnvVT);
6607     SDValue Chain = getRoot();
6608     // If SET_FPENV is custom or legal, use it. Otherwise use loading
6609     // environment from memory.
6610     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
6611       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
6612     } else {
6613       // Allocate space in stack, copy environment bits into it and use this
6614       // memory in SET_FPENV_MEM.
6615       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6616       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6617       auto MPI =
6618           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6619       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
6620                            MachineMemOperand::MOStore);
6621       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6622           MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize,
6623           TempAlign);
6624       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6625     }
6626     DAG.setRoot(Chain);
6627     return;
6628   }
6629   case Intrinsic::reset_fpenv:
6630     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
6631     return;
6632   case Intrinsic::pcmarker: {
6633     SDValue Tmp = getValue(I.getArgOperand(0));
6634     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6635     return;
6636   }
6637   case Intrinsic::readcyclecounter: {
6638     SDValue Op = getRoot();
6639     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6640                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6641     setValue(&I, Res);
6642     DAG.setRoot(Res.getValue(1));
6643     return;
6644   }
6645   case Intrinsic::bitreverse:
6646     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6647                              getValue(I.getArgOperand(0)).getValueType(),
6648                              getValue(I.getArgOperand(0))));
6649     return;
6650   case Intrinsic::bswap:
6651     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6652                              getValue(I.getArgOperand(0)).getValueType(),
6653                              getValue(I.getArgOperand(0))));
6654     return;
6655   case Intrinsic::cttz: {
6656     SDValue Arg = getValue(I.getArgOperand(0));
6657     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6658     EVT Ty = Arg.getValueType();
6659     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6660                              sdl, Ty, Arg));
6661     return;
6662   }
6663   case Intrinsic::ctlz: {
6664     SDValue Arg = getValue(I.getArgOperand(0));
6665     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6666     EVT Ty = Arg.getValueType();
6667     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6668                              sdl, Ty, Arg));
6669     return;
6670   }
6671   case Intrinsic::ctpop: {
6672     SDValue Arg = getValue(I.getArgOperand(0));
6673     EVT Ty = Arg.getValueType();
6674     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6675     return;
6676   }
6677   case Intrinsic::fshl:
6678   case Intrinsic::fshr: {
6679     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6680     SDValue X = getValue(I.getArgOperand(0));
6681     SDValue Y = getValue(I.getArgOperand(1));
6682     SDValue Z = getValue(I.getArgOperand(2));
6683     EVT VT = X.getValueType();
6684 
6685     if (X == Y) {
6686       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6687       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6688     } else {
6689       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6690       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6691     }
6692     return;
6693   }
6694   case Intrinsic::sadd_sat: {
6695     SDValue Op1 = getValue(I.getArgOperand(0));
6696     SDValue Op2 = getValue(I.getArgOperand(1));
6697     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6698     return;
6699   }
6700   case Intrinsic::uadd_sat: {
6701     SDValue Op1 = getValue(I.getArgOperand(0));
6702     SDValue Op2 = getValue(I.getArgOperand(1));
6703     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6704     return;
6705   }
6706   case Intrinsic::ssub_sat: {
6707     SDValue Op1 = getValue(I.getArgOperand(0));
6708     SDValue Op2 = getValue(I.getArgOperand(1));
6709     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6710     return;
6711   }
6712   case Intrinsic::usub_sat: {
6713     SDValue Op1 = getValue(I.getArgOperand(0));
6714     SDValue Op2 = getValue(I.getArgOperand(1));
6715     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6716     return;
6717   }
6718   case Intrinsic::sshl_sat: {
6719     SDValue Op1 = getValue(I.getArgOperand(0));
6720     SDValue Op2 = getValue(I.getArgOperand(1));
6721     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6722     return;
6723   }
6724   case Intrinsic::ushl_sat: {
6725     SDValue Op1 = getValue(I.getArgOperand(0));
6726     SDValue Op2 = getValue(I.getArgOperand(1));
6727     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6728     return;
6729   }
6730   case Intrinsic::smul_fix:
6731   case Intrinsic::umul_fix:
6732   case Intrinsic::smul_fix_sat:
6733   case Intrinsic::umul_fix_sat: {
6734     SDValue Op1 = getValue(I.getArgOperand(0));
6735     SDValue Op2 = getValue(I.getArgOperand(1));
6736     SDValue Op3 = getValue(I.getArgOperand(2));
6737     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6738                              Op1.getValueType(), Op1, Op2, Op3));
6739     return;
6740   }
6741   case Intrinsic::sdiv_fix:
6742   case Intrinsic::udiv_fix:
6743   case Intrinsic::sdiv_fix_sat:
6744   case Intrinsic::udiv_fix_sat: {
6745     SDValue Op1 = getValue(I.getArgOperand(0));
6746     SDValue Op2 = getValue(I.getArgOperand(1));
6747     SDValue Op3 = getValue(I.getArgOperand(2));
6748     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6749                               Op1, Op2, Op3, DAG, TLI));
6750     return;
6751   }
6752   case Intrinsic::smax: {
6753     SDValue Op1 = getValue(I.getArgOperand(0));
6754     SDValue Op2 = getValue(I.getArgOperand(1));
6755     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6756     return;
6757   }
6758   case Intrinsic::smin: {
6759     SDValue Op1 = getValue(I.getArgOperand(0));
6760     SDValue Op2 = getValue(I.getArgOperand(1));
6761     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6762     return;
6763   }
6764   case Intrinsic::umax: {
6765     SDValue Op1 = getValue(I.getArgOperand(0));
6766     SDValue Op2 = getValue(I.getArgOperand(1));
6767     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6768     return;
6769   }
6770   case Intrinsic::umin: {
6771     SDValue Op1 = getValue(I.getArgOperand(0));
6772     SDValue Op2 = getValue(I.getArgOperand(1));
6773     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6774     return;
6775   }
6776   case Intrinsic::abs: {
6777     // TODO: Preserve "int min is poison" arg in SDAG?
6778     SDValue Op1 = getValue(I.getArgOperand(0));
6779     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6780     return;
6781   }
6782   case Intrinsic::stacksave: {
6783     SDValue Op = getRoot();
6784     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6785     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6786     setValue(&I, Res);
6787     DAG.setRoot(Res.getValue(1));
6788     return;
6789   }
6790   case Intrinsic::stackrestore:
6791     Res = getValue(I.getArgOperand(0));
6792     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6793     return;
6794   case Intrinsic::get_dynamic_area_offset: {
6795     SDValue Op = getRoot();
6796     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6797     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6798     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6799     // target.
6800     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6801       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6802                          " intrinsic!");
6803     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6804                       Op);
6805     DAG.setRoot(Op);
6806     setValue(&I, Res);
6807     return;
6808   }
6809   case Intrinsic::stackguard: {
6810     MachineFunction &MF = DAG.getMachineFunction();
6811     const Module &M = *MF.getFunction().getParent();
6812     SDValue Chain = getRoot();
6813     if (TLI.useLoadStackGuardNode()) {
6814       Res = getLoadStackGuard(DAG, sdl, Chain);
6815     } else {
6816       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6817       const Value *Global = TLI.getSDagStackGuard(M);
6818       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6819       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6820                         MachinePointerInfo(Global, 0), Align,
6821                         MachineMemOperand::MOVolatile);
6822     }
6823     if (TLI.useStackGuardXorFP())
6824       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6825     DAG.setRoot(Chain);
6826     setValue(&I, Res);
6827     return;
6828   }
6829   case Intrinsic::stackprotector: {
6830     // Emit code into the DAG to store the stack guard onto the stack.
6831     MachineFunction &MF = DAG.getMachineFunction();
6832     MachineFrameInfo &MFI = MF.getFrameInfo();
6833     SDValue Src, Chain = getRoot();
6834 
6835     if (TLI.useLoadStackGuardNode())
6836       Src = getLoadStackGuard(DAG, sdl, Chain);
6837     else
6838       Src = getValue(I.getArgOperand(0));   // The guard's value.
6839 
6840     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6841 
6842     int FI = FuncInfo.StaticAllocaMap[Slot];
6843     MFI.setStackProtectorIndex(FI);
6844     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6845 
6846     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6847 
6848     // Store the stack protector onto the stack.
6849     Res = DAG.getStore(
6850         Chain, sdl, Src, FIN,
6851         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6852         MaybeAlign(), MachineMemOperand::MOVolatile);
6853     setValue(&I, Res);
6854     DAG.setRoot(Res);
6855     return;
6856   }
6857   case Intrinsic::objectsize:
6858     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6859 
6860   case Intrinsic::is_constant:
6861     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6862 
6863   case Intrinsic::annotation:
6864   case Intrinsic::ptr_annotation:
6865   case Intrinsic::launder_invariant_group:
6866   case Intrinsic::strip_invariant_group:
6867     // Drop the intrinsic, but forward the value
6868     setValue(&I, getValue(I.getOperand(0)));
6869     return;
6870 
6871   case Intrinsic::assume:
6872   case Intrinsic::experimental_noalias_scope_decl:
6873   case Intrinsic::var_annotation:
6874   case Intrinsic::sideeffect:
6875     // Discard annotate attributes, noalias scope declarations, assumptions, and
6876     // artificial side-effects.
6877     return;
6878 
6879   case Intrinsic::codeview_annotation: {
6880     // Emit a label associated with this metadata.
6881     MachineFunction &MF = DAG.getMachineFunction();
6882     MCSymbol *Label =
6883         MF.getMMI().getContext().createTempSymbol("annotation", true);
6884     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6885     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6886     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6887     DAG.setRoot(Res);
6888     return;
6889   }
6890 
6891   case Intrinsic::init_trampoline: {
6892     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6893 
6894     SDValue Ops[6];
6895     Ops[0] = getRoot();
6896     Ops[1] = getValue(I.getArgOperand(0));
6897     Ops[2] = getValue(I.getArgOperand(1));
6898     Ops[3] = getValue(I.getArgOperand(2));
6899     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6900     Ops[5] = DAG.getSrcValue(F);
6901 
6902     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6903 
6904     DAG.setRoot(Res);
6905     return;
6906   }
6907   case Intrinsic::adjust_trampoline:
6908     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6909                              TLI.getPointerTy(DAG.getDataLayout()),
6910                              getValue(I.getArgOperand(0))));
6911     return;
6912   case Intrinsic::gcroot: {
6913     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6914            "only valid in functions with gc specified, enforced by Verifier");
6915     assert(GFI && "implied by previous");
6916     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6917     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6918 
6919     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6920     GFI->addStackRoot(FI->getIndex(), TypeMap);
6921     return;
6922   }
6923   case Intrinsic::gcread:
6924   case Intrinsic::gcwrite:
6925     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6926   case Intrinsic::get_rounding:
6927     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
6928     setValue(&I, Res);
6929     DAG.setRoot(Res.getValue(1));
6930     return;
6931 
6932   case Intrinsic::expect:
6933     // Just replace __builtin_expect(exp, c) with EXP.
6934     setValue(&I, getValue(I.getArgOperand(0)));
6935     return;
6936 
6937   case Intrinsic::ubsantrap:
6938   case Intrinsic::debugtrap:
6939   case Intrinsic::trap: {
6940     StringRef TrapFuncName =
6941         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6942     if (TrapFuncName.empty()) {
6943       switch (Intrinsic) {
6944       case Intrinsic::trap:
6945         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6946         break;
6947       case Intrinsic::debugtrap:
6948         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6949         break;
6950       case Intrinsic::ubsantrap:
6951         DAG.setRoot(DAG.getNode(
6952             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6953             DAG.getTargetConstant(
6954                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6955                 MVT::i32)));
6956         break;
6957       default: llvm_unreachable("unknown trap intrinsic");
6958       }
6959       return;
6960     }
6961     TargetLowering::ArgListTy Args;
6962     if (Intrinsic == Intrinsic::ubsantrap) {
6963       Args.push_back(TargetLoweringBase::ArgListEntry());
6964       Args[0].Val = I.getArgOperand(0);
6965       Args[0].Node = getValue(Args[0].Val);
6966       Args[0].Ty = Args[0].Val->getType();
6967     }
6968 
6969     TargetLowering::CallLoweringInfo CLI(DAG);
6970     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6971         CallingConv::C, I.getType(),
6972         DAG.getExternalSymbol(TrapFuncName.data(),
6973                               TLI.getPointerTy(DAG.getDataLayout())),
6974         std::move(Args));
6975 
6976     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6977     DAG.setRoot(Result.second);
6978     return;
6979   }
6980 
6981   case Intrinsic::uadd_with_overflow:
6982   case Intrinsic::sadd_with_overflow:
6983   case Intrinsic::usub_with_overflow:
6984   case Intrinsic::ssub_with_overflow:
6985   case Intrinsic::umul_with_overflow:
6986   case Intrinsic::smul_with_overflow: {
6987     ISD::NodeType Op;
6988     switch (Intrinsic) {
6989     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6990     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6991     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6992     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6993     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6994     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6995     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6996     }
6997     SDValue Op1 = getValue(I.getArgOperand(0));
6998     SDValue Op2 = getValue(I.getArgOperand(1));
6999 
7000     EVT ResultVT = Op1.getValueType();
7001     EVT OverflowVT = MVT::i1;
7002     if (ResultVT.isVector())
7003       OverflowVT = EVT::getVectorVT(
7004           *Context, OverflowVT, ResultVT.getVectorElementCount());
7005 
7006     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7007     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7008     return;
7009   }
7010   case Intrinsic::prefetch: {
7011     SDValue Ops[5];
7012     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7013     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7014     Ops[0] = DAG.getRoot();
7015     Ops[1] = getValue(I.getArgOperand(0));
7016     Ops[2] = getValue(I.getArgOperand(1));
7017     Ops[3] = getValue(I.getArgOperand(2));
7018     Ops[4] = getValue(I.getArgOperand(3));
7019     SDValue Result = DAG.getMemIntrinsicNode(
7020         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7021         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7022         /* align */ std::nullopt, Flags);
7023 
7024     // Chain the prefetch in parallell with any pending loads, to stay out of
7025     // the way of later optimizations.
7026     PendingLoads.push_back(Result);
7027     Result = getRoot();
7028     DAG.setRoot(Result);
7029     return;
7030   }
7031   case Intrinsic::lifetime_start:
7032   case Intrinsic::lifetime_end: {
7033     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7034     // Stack coloring is not enabled in O0, discard region information.
7035     if (TM.getOptLevel() == CodeGenOpt::None)
7036       return;
7037 
7038     const int64_t ObjectSize =
7039         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7040     Value *const ObjectPtr = I.getArgOperand(1);
7041     SmallVector<const Value *, 4> Allocas;
7042     getUnderlyingObjects(ObjectPtr, Allocas);
7043 
7044     for (const Value *Alloca : Allocas) {
7045       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7046 
7047       // Could not find an Alloca.
7048       if (!LifetimeObject)
7049         continue;
7050 
7051       // First check that the Alloca is static, otherwise it won't have a
7052       // valid frame index.
7053       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7054       if (SI == FuncInfo.StaticAllocaMap.end())
7055         return;
7056 
7057       const int FrameIndex = SI->second;
7058       int64_t Offset;
7059       if (GetPointerBaseWithConstantOffset(
7060               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7061         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7062       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7063                                 Offset);
7064       DAG.setRoot(Res);
7065     }
7066     return;
7067   }
7068   case Intrinsic::pseudoprobe: {
7069     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7070     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7071     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7072     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7073     DAG.setRoot(Res);
7074     return;
7075   }
7076   case Intrinsic::invariant_start:
7077     // Discard region information.
7078     setValue(&I,
7079              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7080     return;
7081   case Intrinsic::invariant_end:
7082     // Discard region information.
7083     return;
7084   case Intrinsic::clear_cache:
7085     /// FunctionName may be null.
7086     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
7087       lowerCallToExternalSymbol(I, FunctionName);
7088     return;
7089   case Intrinsic::donothing:
7090   case Intrinsic::seh_try_begin:
7091   case Intrinsic::seh_scope_begin:
7092   case Intrinsic::seh_try_end:
7093   case Intrinsic::seh_scope_end:
7094     // ignore
7095     return;
7096   case Intrinsic::experimental_stackmap:
7097     visitStackmap(I);
7098     return;
7099   case Intrinsic::experimental_patchpoint_void:
7100   case Intrinsic::experimental_patchpoint_i64:
7101     visitPatchpoint(I);
7102     return;
7103   case Intrinsic::experimental_gc_statepoint:
7104     LowerStatepoint(cast<GCStatepointInst>(I));
7105     return;
7106   case Intrinsic::experimental_gc_result:
7107     visitGCResult(cast<GCResultInst>(I));
7108     return;
7109   case Intrinsic::experimental_gc_relocate:
7110     visitGCRelocate(cast<GCRelocateInst>(I));
7111     return;
7112   case Intrinsic::instrprof_cover:
7113     llvm_unreachable("instrprof failed to lower a cover");
7114   case Intrinsic::instrprof_increment:
7115     llvm_unreachable("instrprof failed to lower an increment");
7116   case Intrinsic::instrprof_timestamp:
7117     llvm_unreachable("instrprof failed to lower a timestamp");
7118   case Intrinsic::instrprof_value_profile:
7119     llvm_unreachable("instrprof failed to lower a value profiling call");
7120   case Intrinsic::localescape: {
7121     MachineFunction &MF = DAG.getMachineFunction();
7122     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7123 
7124     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7125     // is the same on all targets.
7126     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7127       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7128       if (isa<ConstantPointerNull>(Arg))
7129         continue; // Skip null pointers. They represent a hole in index space.
7130       AllocaInst *Slot = cast<AllocaInst>(Arg);
7131       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7132              "can only escape static allocas");
7133       int FI = FuncInfo.StaticAllocaMap[Slot];
7134       MCSymbol *FrameAllocSym =
7135           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7136               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7137       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7138               TII->get(TargetOpcode::LOCAL_ESCAPE))
7139           .addSym(FrameAllocSym)
7140           .addFrameIndex(FI);
7141     }
7142 
7143     return;
7144   }
7145 
7146   case Intrinsic::localrecover: {
7147     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7148     MachineFunction &MF = DAG.getMachineFunction();
7149 
7150     // Get the symbol that defines the frame offset.
7151     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7152     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7153     unsigned IdxVal =
7154         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7155     MCSymbol *FrameAllocSym =
7156         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7157             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7158 
7159     Value *FP = I.getArgOperand(1);
7160     SDValue FPVal = getValue(FP);
7161     EVT PtrVT = FPVal.getValueType();
7162 
7163     // Create a MCSymbol for the label to avoid any target lowering
7164     // that would make this PC relative.
7165     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7166     SDValue OffsetVal =
7167         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7168 
7169     // Add the offset to the FP.
7170     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7171     setValue(&I, Add);
7172 
7173     return;
7174   }
7175 
7176   case Intrinsic::eh_exceptionpointer:
7177   case Intrinsic::eh_exceptioncode: {
7178     // Get the exception pointer vreg, copy from it, and resize it to fit.
7179     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7180     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7181     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7182     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7183     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7184     if (Intrinsic == Intrinsic::eh_exceptioncode)
7185       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7186     setValue(&I, N);
7187     return;
7188   }
7189   case Intrinsic::xray_customevent: {
7190     // Here we want to make sure that the intrinsic behaves as if it has a
7191     // specific calling convention, and only for x86_64.
7192     // FIXME: Support other platforms later.
7193     const auto &Triple = DAG.getTarget().getTargetTriple();
7194     if (Triple.getArch() != Triple::x86_64)
7195       return;
7196 
7197     SmallVector<SDValue, 8> Ops;
7198 
7199     // We want to say that we always want the arguments in registers.
7200     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7201     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7202     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7203     SDValue Chain = getRoot();
7204     Ops.push_back(LogEntryVal);
7205     Ops.push_back(StrSizeVal);
7206     Ops.push_back(Chain);
7207 
7208     // We need to enforce the calling convention for the callsite, so that
7209     // argument ordering is enforced correctly, and that register allocation can
7210     // see that some registers may be assumed clobbered and have to preserve
7211     // them across calls to the intrinsic.
7212     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7213                                            sdl, NodeTys, Ops);
7214     SDValue patchableNode = SDValue(MN, 0);
7215     DAG.setRoot(patchableNode);
7216     setValue(&I, patchableNode);
7217     return;
7218   }
7219   case Intrinsic::xray_typedevent: {
7220     // Here we want to make sure that the intrinsic behaves as if it has a
7221     // specific calling convention, and only for x86_64.
7222     // FIXME: Support other platforms later.
7223     const auto &Triple = DAG.getTarget().getTargetTriple();
7224     if (Triple.getArch() != Triple::x86_64)
7225       return;
7226 
7227     SmallVector<SDValue, 8> Ops;
7228 
7229     // We want to say that we always want the arguments in registers.
7230     // It's unclear to me how manipulating the selection DAG here forces callers
7231     // to provide arguments in registers instead of on the stack.
7232     SDValue LogTypeId = getValue(I.getArgOperand(0));
7233     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7234     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7235     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7236     SDValue Chain = getRoot();
7237     Ops.push_back(LogTypeId);
7238     Ops.push_back(LogEntryVal);
7239     Ops.push_back(StrSizeVal);
7240     Ops.push_back(Chain);
7241 
7242     // We need to enforce the calling convention for the callsite, so that
7243     // argument ordering is enforced correctly, and that register allocation can
7244     // see that some registers may be assumed clobbered and have to preserve
7245     // them across calls to the intrinsic.
7246     MachineSDNode *MN = DAG.getMachineNode(
7247         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7248     SDValue patchableNode = SDValue(MN, 0);
7249     DAG.setRoot(patchableNode);
7250     setValue(&I, patchableNode);
7251     return;
7252   }
7253   case Intrinsic::experimental_deoptimize:
7254     LowerDeoptimizeCall(&I);
7255     return;
7256   case Intrinsic::experimental_stepvector:
7257     visitStepVector(I);
7258     return;
7259   case Intrinsic::vector_reduce_fadd:
7260   case Intrinsic::vector_reduce_fmul:
7261   case Intrinsic::vector_reduce_add:
7262   case Intrinsic::vector_reduce_mul:
7263   case Intrinsic::vector_reduce_and:
7264   case Intrinsic::vector_reduce_or:
7265   case Intrinsic::vector_reduce_xor:
7266   case Intrinsic::vector_reduce_smax:
7267   case Intrinsic::vector_reduce_smin:
7268   case Intrinsic::vector_reduce_umax:
7269   case Intrinsic::vector_reduce_umin:
7270   case Intrinsic::vector_reduce_fmax:
7271   case Intrinsic::vector_reduce_fmin:
7272     visitVectorReduce(I, Intrinsic);
7273     return;
7274 
7275   case Intrinsic::icall_branch_funnel: {
7276     SmallVector<SDValue, 16> Ops;
7277     Ops.push_back(getValue(I.getArgOperand(0)));
7278 
7279     int64_t Offset;
7280     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7281         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7282     if (!Base)
7283       report_fatal_error(
7284           "llvm.icall.branch.funnel operand must be a GlobalValue");
7285     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7286 
7287     struct BranchFunnelTarget {
7288       int64_t Offset;
7289       SDValue Target;
7290     };
7291     SmallVector<BranchFunnelTarget, 8> Targets;
7292 
7293     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7294       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7295           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7296       if (ElemBase != Base)
7297         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7298                            "to the same GlobalValue");
7299 
7300       SDValue Val = getValue(I.getArgOperand(Op + 1));
7301       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7302       if (!GA)
7303         report_fatal_error(
7304             "llvm.icall.branch.funnel operand must be a GlobalValue");
7305       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7306                                      GA->getGlobal(), sdl, Val.getValueType(),
7307                                      GA->getOffset())});
7308     }
7309     llvm::sort(Targets,
7310                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7311                  return T1.Offset < T2.Offset;
7312                });
7313 
7314     for (auto &T : Targets) {
7315       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7316       Ops.push_back(T.Target);
7317     }
7318 
7319     Ops.push_back(DAG.getRoot()); // Chain
7320     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7321                                  MVT::Other, Ops),
7322               0);
7323     DAG.setRoot(N);
7324     setValue(&I, N);
7325     HasTailCall = true;
7326     return;
7327   }
7328 
7329   case Intrinsic::wasm_landingpad_index:
7330     // Information this intrinsic contained has been transferred to
7331     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7332     // delete it now.
7333     return;
7334 
7335   case Intrinsic::aarch64_settag:
7336   case Intrinsic::aarch64_settag_zero: {
7337     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7338     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7339     SDValue Val = TSI.EmitTargetCodeForSetTag(
7340         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7341         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7342         ZeroMemory);
7343     DAG.setRoot(Val);
7344     setValue(&I, Val);
7345     return;
7346   }
7347   case Intrinsic::ptrmask: {
7348     SDValue Ptr = getValue(I.getOperand(0));
7349     SDValue Const = getValue(I.getOperand(1));
7350 
7351     EVT PtrVT = Ptr.getValueType();
7352     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7353                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7354     return;
7355   }
7356   case Intrinsic::threadlocal_address: {
7357     setValue(&I, getValue(I.getOperand(0)));
7358     return;
7359   }
7360   case Intrinsic::get_active_lane_mask: {
7361     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7362     SDValue Index = getValue(I.getOperand(0));
7363     EVT ElementVT = Index.getValueType();
7364 
7365     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7366       visitTargetIntrinsic(I, Intrinsic);
7367       return;
7368     }
7369 
7370     SDValue TripCount = getValue(I.getOperand(1));
7371     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7372 
7373     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7374     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7375     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7376     SDValue VectorInduction = DAG.getNode(
7377         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7378     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7379                                  VectorTripCount, ISD::CondCode::SETULT);
7380     setValue(&I, SetCC);
7381     return;
7382   }
7383   case Intrinsic::experimental_get_vector_length: {
7384     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7385            "Expected positive VF");
7386     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7387     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7388 
7389     SDValue Count = getValue(I.getOperand(0));
7390     EVT CountVT = Count.getValueType();
7391 
7392     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7393       visitTargetIntrinsic(I, Intrinsic);
7394       return;
7395     }
7396 
7397     // Expand to a umin between the trip count and the maximum elements the type
7398     // can hold.
7399     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7400 
7401     // Extend the trip count to at least the result VT.
7402     if (CountVT.bitsLT(VT)) {
7403       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7404       CountVT = VT;
7405     }
7406 
7407     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7408                                          ElementCount::get(VF, IsScalable));
7409 
7410     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7411     // Clip to the result type if needed.
7412     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7413 
7414     setValue(&I, Trunc);
7415     return;
7416   }
7417   case Intrinsic::vector_insert: {
7418     SDValue Vec = getValue(I.getOperand(0));
7419     SDValue SubVec = getValue(I.getOperand(1));
7420     SDValue Index = getValue(I.getOperand(2));
7421 
7422     // The intrinsic's index type is i64, but the SDNode requires an index type
7423     // suitable for the target. Convert the index as required.
7424     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7425     if (Index.getValueType() != VectorIdxTy)
7426       Index = DAG.getVectorIdxConstant(
7427           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7428 
7429     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7430     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7431                              Index));
7432     return;
7433   }
7434   case Intrinsic::vector_extract: {
7435     SDValue Vec = getValue(I.getOperand(0));
7436     SDValue Index = getValue(I.getOperand(1));
7437     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7438 
7439     // The intrinsic's index type is i64, but the SDNode requires an index type
7440     // suitable for the target. Convert the index as required.
7441     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7442     if (Index.getValueType() != VectorIdxTy)
7443       Index = DAG.getVectorIdxConstant(
7444           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7445 
7446     setValue(&I,
7447              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7448     return;
7449   }
7450   case Intrinsic::experimental_vector_reverse:
7451     visitVectorReverse(I);
7452     return;
7453   case Intrinsic::experimental_vector_splice:
7454     visitVectorSplice(I);
7455     return;
7456   case Intrinsic::callbr_landingpad:
7457     visitCallBrLandingPad(I);
7458     return;
7459   case Intrinsic::experimental_vector_interleave2:
7460     visitVectorInterleave(I);
7461     return;
7462   case Intrinsic::experimental_vector_deinterleave2:
7463     visitVectorDeinterleave(I);
7464     return;
7465   }
7466 }
7467 
7468 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7469     const ConstrainedFPIntrinsic &FPI) {
7470   SDLoc sdl = getCurSDLoc();
7471 
7472   // We do not need to serialize constrained FP intrinsics against
7473   // each other or against (nonvolatile) loads, so they can be
7474   // chained like loads.
7475   SDValue Chain = DAG.getRoot();
7476   SmallVector<SDValue, 4> Opers;
7477   Opers.push_back(Chain);
7478   if (FPI.isUnaryOp()) {
7479     Opers.push_back(getValue(FPI.getArgOperand(0)));
7480   } else if (FPI.isTernaryOp()) {
7481     Opers.push_back(getValue(FPI.getArgOperand(0)));
7482     Opers.push_back(getValue(FPI.getArgOperand(1)));
7483     Opers.push_back(getValue(FPI.getArgOperand(2)));
7484   } else {
7485     Opers.push_back(getValue(FPI.getArgOperand(0)));
7486     Opers.push_back(getValue(FPI.getArgOperand(1)));
7487   }
7488 
7489   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7490     assert(Result.getNode()->getNumValues() == 2);
7491 
7492     // Push node to the appropriate list so that future instructions can be
7493     // chained up correctly.
7494     SDValue OutChain = Result.getValue(1);
7495     switch (EB) {
7496     case fp::ExceptionBehavior::ebIgnore:
7497       // The only reason why ebIgnore nodes still need to be chained is that
7498       // they might depend on the current rounding mode, and therefore must
7499       // not be moved across instruction that may change that mode.
7500       [[fallthrough]];
7501     case fp::ExceptionBehavior::ebMayTrap:
7502       // These must not be moved across calls or instructions that may change
7503       // floating-point exception masks.
7504       PendingConstrainedFP.push_back(OutChain);
7505       break;
7506     case fp::ExceptionBehavior::ebStrict:
7507       // These must not be moved across calls or instructions that may change
7508       // floating-point exception masks or read floating-point exception flags.
7509       // In addition, they cannot be optimized out even if unused.
7510       PendingConstrainedFPStrict.push_back(OutChain);
7511       break;
7512     }
7513   };
7514 
7515   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7516   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7517   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7518   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7519 
7520   SDNodeFlags Flags;
7521   if (EB == fp::ExceptionBehavior::ebIgnore)
7522     Flags.setNoFPExcept(true);
7523 
7524   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7525     Flags.copyFMF(*FPOp);
7526 
7527   unsigned Opcode;
7528   switch (FPI.getIntrinsicID()) {
7529   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7530 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7531   case Intrinsic::INTRINSIC:                                                   \
7532     Opcode = ISD::STRICT_##DAGN;                                               \
7533     break;
7534 #include "llvm/IR/ConstrainedOps.def"
7535   case Intrinsic::experimental_constrained_fmuladd: {
7536     Opcode = ISD::STRICT_FMA;
7537     // Break fmuladd into fmul and fadd.
7538     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7539         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7540       Opers.pop_back();
7541       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7542       pushOutChain(Mul, EB);
7543       Opcode = ISD::STRICT_FADD;
7544       Opers.clear();
7545       Opers.push_back(Mul.getValue(1));
7546       Opers.push_back(Mul.getValue(0));
7547       Opers.push_back(getValue(FPI.getArgOperand(2)));
7548     }
7549     break;
7550   }
7551   }
7552 
7553   // A few strict DAG nodes carry additional operands that are not
7554   // set up by the default code above.
7555   switch (Opcode) {
7556   default: break;
7557   case ISD::STRICT_FP_ROUND:
7558     Opers.push_back(
7559         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7560     break;
7561   case ISD::STRICT_FSETCC:
7562   case ISD::STRICT_FSETCCS: {
7563     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7564     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7565     if (TM.Options.NoNaNsFPMath)
7566       Condition = getFCmpCodeWithoutNaN(Condition);
7567     Opers.push_back(DAG.getCondCode(Condition));
7568     break;
7569   }
7570   }
7571 
7572   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7573   pushOutChain(Result, EB);
7574 
7575   SDValue FPResult = Result.getValue(0);
7576   setValue(&FPI, FPResult);
7577 }
7578 
7579 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7580   std::optional<unsigned> ResOPC;
7581   switch (VPIntrin.getIntrinsicID()) {
7582   case Intrinsic::vp_ctlz: {
7583     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7584     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
7585     break;
7586   }
7587   case Intrinsic::vp_cttz: {
7588     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7589     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
7590     break;
7591   }
7592 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7593   case Intrinsic::VPID:                                                        \
7594     ResOPC = ISD::VPSD;                                                        \
7595     break;
7596 #include "llvm/IR/VPIntrinsics.def"
7597   }
7598 
7599   if (!ResOPC)
7600     llvm_unreachable(
7601         "Inconsistency: no SDNode available for this VPIntrinsic!");
7602 
7603   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7604       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7605     if (VPIntrin.getFastMathFlags().allowReassoc())
7606       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7607                                                 : ISD::VP_REDUCE_FMUL;
7608   }
7609 
7610   return *ResOPC;
7611 }
7612 
7613 void SelectionDAGBuilder::visitVPLoad(
7614     const VPIntrinsic &VPIntrin, EVT VT,
7615     const SmallVectorImpl<SDValue> &OpValues) {
7616   SDLoc DL = getCurSDLoc();
7617   Value *PtrOperand = VPIntrin.getArgOperand(0);
7618   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7619   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7620   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7621   SDValue LD;
7622   // Do not serialize variable-length loads of constant memory with
7623   // anything.
7624   if (!Alignment)
7625     Alignment = DAG.getEVTAlign(VT);
7626   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7627   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7628   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7629   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7630       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7631       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7632   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7633                      MMO, false /*IsExpanding */);
7634   if (AddToChain)
7635     PendingLoads.push_back(LD.getValue(1));
7636   setValue(&VPIntrin, LD);
7637 }
7638 
7639 void SelectionDAGBuilder::visitVPGather(
7640     const VPIntrinsic &VPIntrin, EVT VT,
7641     const SmallVectorImpl<SDValue> &OpValues) {
7642   SDLoc DL = getCurSDLoc();
7643   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7644   Value *PtrOperand = VPIntrin.getArgOperand(0);
7645   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7646   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7647   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7648   SDValue LD;
7649   if (!Alignment)
7650     Alignment = DAG.getEVTAlign(VT.getScalarType());
7651   unsigned AS =
7652     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7653   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7654      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7655      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7656   SDValue Base, Index, Scale;
7657   ISD::MemIndexType IndexType;
7658   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7659                                     this, VPIntrin.getParent(),
7660                                     VT.getScalarStoreSize());
7661   if (!UniformBase) {
7662     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7663     Index = getValue(PtrOperand);
7664     IndexType = ISD::SIGNED_SCALED;
7665     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7666   }
7667   EVT IdxVT = Index.getValueType();
7668   EVT EltTy = IdxVT.getVectorElementType();
7669   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7670     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7671     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7672   }
7673   LD = DAG.getGatherVP(
7674       DAG.getVTList(VT, MVT::Other), VT, DL,
7675       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7676       IndexType);
7677   PendingLoads.push_back(LD.getValue(1));
7678   setValue(&VPIntrin, LD);
7679 }
7680 
7681 void SelectionDAGBuilder::visitVPStore(
7682     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7683   SDLoc DL = getCurSDLoc();
7684   Value *PtrOperand = VPIntrin.getArgOperand(1);
7685   EVT VT = OpValues[0].getValueType();
7686   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7687   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7688   SDValue ST;
7689   if (!Alignment)
7690     Alignment = DAG.getEVTAlign(VT);
7691   SDValue Ptr = OpValues[1];
7692   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7693   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7694       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7695       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7696   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7697                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7698                       /* IsTruncating */ false, /*IsCompressing*/ false);
7699   DAG.setRoot(ST);
7700   setValue(&VPIntrin, ST);
7701 }
7702 
7703 void SelectionDAGBuilder::visitVPScatter(
7704     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7705   SDLoc DL = getCurSDLoc();
7706   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7707   Value *PtrOperand = VPIntrin.getArgOperand(1);
7708   EVT VT = OpValues[0].getValueType();
7709   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7710   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7711   SDValue ST;
7712   if (!Alignment)
7713     Alignment = DAG.getEVTAlign(VT.getScalarType());
7714   unsigned AS =
7715       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7716   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7717       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7718       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7719   SDValue Base, Index, Scale;
7720   ISD::MemIndexType IndexType;
7721   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7722                                     this, VPIntrin.getParent(),
7723                                     VT.getScalarStoreSize());
7724   if (!UniformBase) {
7725     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7726     Index = getValue(PtrOperand);
7727     IndexType = ISD::SIGNED_SCALED;
7728     Scale =
7729       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7730   }
7731   EVT IdxVT = Index.getValueType();
7732   EVT EltTy = IdxVT.getVectorElementType();
7733   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7734     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7735     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7736   }
7737   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7738                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7739                          OpValues[2], OpValues[3]},
7740                         MMO, IndexType);
7741   DAG.setRoot(ST);
7742   setValue(&VPIntrin, ST);
7743 }
7744 
7745 void SelectionDAGBuilder::visitVPStridedLoad(
7746     const VPIntrinsic &VPIntrin, EVT VT,
7747     const SmallVectorImpl<SDValue> &OpValues) {
7748   SDLoc DL = getCurSDLoc();
7749   Value *PtrOperand = VPIntrin.getArgOperand(0);
7750   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7751   if (!Alignment)
7752     Alignment = DAG.getEVTAlign(VT.getScalarType());
7753   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7754   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7755   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7756   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7757   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7758   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7759       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7760       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7761 
7762   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7763                                     OpValues[2], OpValues[3], MMO,
7764                                     false /*IsExpanding*/);
7765 
7766   if (AddToChain)
7767     PendingLoads.push_back(LD.getValue(1));
7768   setValue(&VPIntrin, LD);
7769 }
7770 
7771 void SelectionDAGBuilder::visitVPStridedStore(
7772     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7773   SDLoc DL = getCurSDLoc();
7774   Value *PtrOperand = VPIntrin.getArgOperand(1);
7775   EVT VT = OpValues[0].getValueType();
7776   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7777   if (!Alignment)
7778     Alignment = DAG.getEVTAlign(VT.getScalarType());
7779   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7780   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7781       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7782       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7783 
7784   SDValue ST = DAG.getStridedStoreVP(
7785       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7786       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7787       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7788       /*IsCompressing*/ false);
7789 
7790   DAG.setRoot(ST);
7791   setValue(&VPIntrin, ST);
7792 }
7793 
7794 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
7795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7796   SDLoc DL = getCurSDLoc();
7797 
7798   ISD::CondCode Condition;
7799   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
7800   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
7801   if (IsFP) {
7802     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
7803     // flags, but calls that don't return floating-point types can't be
7804     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
7805     Condition = getFCmpCondCode(CondCode);
7806     if (TM.Options.NoNaNsFPMath)
7807       Condition = getFCmpCodeWithoutNaN(Condition);
7808   } else {
7809     Condition = getICmpCondCode(CondCode);
7810   }
7811 
7812   SDValue Op1 = getValue(VPIntrin.getOperand(0));
7813   SDValue Op2 = getValue(VPIntrin.getOperand(1));
7814   // #2 is the condition code
7815   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
7816   SDValue EVL = getValue(VPIntrin.getOperand(4));
7817   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7818   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7819          "Unexpected target EVL type");
7820   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
7821 
7822   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7823                                                         VPIntrin.getType());
7824   setValue(&VPIntrin,
7825            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
7826 }
7827 
7828 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7829     const VPIntrinsic &VPIntrin) {
7830   SDLoc DL = getCurSDLoc();
7831   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7832 
7833   auto IID = VPIntrin.getIntrinsicID();
7834 
7835   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
7836     return visitVPCmp(*CmpI);
7837 
7838   SmallVector<EVT, 4> ValueVTs;
7839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7840   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7841   SDVTList VTs = DAG.getVTList(ValueVTs);
7842 
7843   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
7844 
7845   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7846   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7847          "Unexpected target EVL type");
7848 
7849   // Request operands.
7850   SmallVector<SDValue, 7> OpValues;
7851   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7852     auto Op = getValue(VPIntrin.getArgOperand(I));
7853     if (I == EVLParamPos)
7854       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7855     OpValues.push_back(Op);
7856   }
7857 
7858   switch (Opcode) {
7859   default: {
7860     SDNodeFlags SDFlags;
7861     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7862       SDFlags.copyFMF(*FPMO);
7863     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
7864     setValue(&VPIntrin, Result);
7865     break;
7866   }
7867   case ISD::VP_LOAD:
7868     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
7869     break;
7870   case ISD::VP_GATHER:
7871     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
7872     break;
7873   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7874     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7875     break;
7876   case ISD::VP_STORE:
7877     visitVPStore(VPIntrin, OpValues);
7878     break;
7879   case ISD::VP_SCATTER:
7880     visitVPScatter(VPIntrin, OpValues);
7881     break;
7882   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7883     visitVPStridedStore(VPIntrin, OpValues);
7884     break;
7885   case ISD::VP_FMULADD: {
7886     assert(OpValues.size() == 5 && "Unexpected number of operands");
7887     SDNodeFlags SDFlags;
7888     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7889       SDFlags.copyFMF(*FPMO);
7890     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7891         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
7892       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
7893     } else {
7894       SDValue Mul = DAG.getNode(
7895           ISD::VP_FMUL, DL, VTs,
7896           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
7897       SDValue Add =
7898           DAG.getNode(ISD::VP_FADD, DL, VTs,
7899                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
7900       setValue(&VPIntrin, Add);
7901     }
7902     break;
7903   }
7904   case ISD::VP_INTTOPTR: {
7905     SDValue N = OpValues[0];
7906     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
7907     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
7908     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7909                                OpValues[2]);
7910     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7911                              OpValues[2]);
7912     setValue(&VPIntrin, N);
7913     break;
7914   }
7915   case ISD::VP_PTRTOINT: {
7916     SDValue N = OpValues[0];
7917     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7918                                                           VPIntrin.getType());
7919     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
7920                                        VPIntrin.getOperand(0)->getType());
7921     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7922                                OpValues[2]);
7923     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7924                              OpValues[2]);
7925     setValue(&VPIntrin, N);
7926     break;
7927   }
7928   case ISD::VP_ABS:
7929   case ISD::VP_CTLZ:
7930   case ISD::VP_CTLZ_ZERO_UNDEF:
7931   case ISD::VP_CTTZ:
7932   case ISD::VP_CTTZ_ZERO_UNDEF: {
7933     SDValue Result =
7934         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
7935     setValue(&VPIntrin, Result);
7936     break;
7937   }
7938   }
7939 }
7940 
7941 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7942                                           const BasicBlock *EHPadBB,
7943                                           MCSymbol *&BeginLabel) {
7944   MachineFunction &MF = DAG.getMachineFunction();
7945   MachineModuleInfo &MMI = MF.getMMI();
7946 
7947   // Insert a label before the invoke call to mark the try range.  This can be
7948   // used to detect deletion of the invoke via the MachineModuleInfo.
7949   BeginLabel = MMI.getContext().createTempSymbol();
7950 
7951   // For SjLj, keep track of which landing pads go with which invokes
7952   // so as to maintain the ordering of pads in the LSDA.
7953   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7954   if (CallSiteIndex) {
7955     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7956     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7957 
7958     // Now that the call site is handled, stop tracking it.
7959     MMI.setCurrentCallSite(0);
7960   }
7961 
7962   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7963 }
7964 
7965 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7966                                         const BasicBlock *EHPadBB,
7967                                         MCSymbol *BeginLabel) {
7968   assert(BeginLabel && "BeginLabel should've been set");
7969 
7970   MachineFunction &MF = DAG.getMachineFunction();
7971   MachineModuleInfo &MMI = MF.getMMI();
7972 
7973   // Insert a label at the end of the invoke call to mark the try range.  This
7974   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7975   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7976   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7977 
7978   // Inform MachineModuleInfo of range.
7979   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7980   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7981   // actually use outlined funclets and their LSDA info style.
7982   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7983     assert(II && "II should've been set");
7984     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7985     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7986   } else if (!isScopedEHPersonality(Pers)) {
7987     assert(EHPadBB);
7988     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7989   }
7990 
7991   return Chain;
7992 }
7993 
7994 std::pair<SDValue, SDValue>
7995 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7996                                     const BasicBlock *EHPadBB) {
7997   MCSymbol *BeginLabel = nullptr;
7998 
7999   if (EHPadBB) {
8000     // Both PendingLoads and PendingExports must be flushed here;
8001     // this call might not return.
8002     (void)getRoot();
8003     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8004     CLI.setChain(getRoot());
8005   }
8006 
8007   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8008   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8009 
8010   assert((CLI.IsTailCall || Result.second.getNode()) &&
8011          "Non-null chain expected with non-tail call!");
8012   assert((Result.second.getNode() || !Result.first.getNode()) &&
8013          "Null value expected with tail call!");
8014 
8015   if (!Result.second.getNode()) {
8016     // As a special case, a null chain means that a tail call has been emitted
8017     // and the DAG root is already updated.
8018     HasTailCall = true;
8019 
8020     // Since there's no actual continuation from this block, nothing can be
8021     // relying on us setting vregs for them.
8022     PendingExports.clear();
8023   } else {
8024     DAG.setRoot(Result.second);
8025   }
8026 
8027   if (EHPadBB) {
8028     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8029                            BeginLabel));
8030   }
8031 
8032   return Result;
8033 }
8034 
8035 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8036                                       bool isTailCall,
8037                                       bool isMustTailCall,
8038                                       const BasicBlock *EHPadBB) {
8039   auto &DL = DAG.getDataLayout();
8040   FunctionType *FTy = CB.getFunctionType();
8041   Type *RetTy = CB.getType();
8042 
8043   TargetLowering::ArgListTy Args;
8044   Args.reserve(CB.arg_size());
8045 
8046   const Value *SwiftErrorVal = nullptr;
8047   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8048 
8049   if (isTailCall) {
8050     // Avoid emitting tail calls in functions with the disable-tail-calls
8051     // attribute.
8052     auto *Caller = CB.getParent()->getParent();
8053     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8054         "true" && !isMustTailCall)
8055       isTailCall = false;
8056 
8057     // We can't tail call inside a function with a swifterror argument. Lowering
8058     // does not support this yet. It would have to move into the swifterror
8059     // register before the call.
8060     if (TLI.supportSwiftError() &&
8061         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8062       isTailCall = false;
8063   }
8064 
8065   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8066     TargetLowering::ArgListEntry Entry;
8067     const Value *V = *I;
8068 
8069     // Skip empty types
8070     if (V->getType()->isEmptyTy())
8071       continue;
8072 
8073     SDValue ArgNode = getValue(V);
8074     Entry.Node = ArgNode; Entry.Ty = V->getType();
8075 
8076     Entry.setAttributes(&CB, I - CB.arg_begin());
8077 
8078     // Use swifterror virtual register as input to the call.
8079     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8080       SwiftErrorVal = V;
8081       // We find the virtual register for the actual swifterror argument.
8082       // Instead of using the Value, we use the virtual register instead.
8083       Entry.Node =
8084           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8085                           EVT(TLI.getPointerTy(DL)));
8086     }
8087 
8088     Args.push_back(Entry);
8089 
8090     // If we have an explicit sret argument that is an Instruction, (i.e., it
8091     // might point to function-local memory), we can't meaningfully tail-call.
8092     if (Entry.IsSRet && isa<Instruction>(V))
8093       isTailCall = false;
8094   }
8095 
8096   // If call site has a cfguardtarget operand bundle, create and add an
8097   // additional ArgListEntry.
8098   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8099     TargetLowering::ArgListEntry Entry;
8100     Value *V = Bundle->Inputs[0];
8101     SDValue ArgNode = getValue(V);
8102     Entry.Node = ArgNode;
8103     Entry.Ty = V->getType();
8104     Entry.IsCFGuardTarget = true;
8105     Args.push_back(Entry);
8106   }
8107 
8108   // Check if target-independent constraints permit a tail call here.
8109   // Target-dependent constraints are checked within TLI->LowerCallTo.
8110   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8111     isTailCall = false;
8112 
8113   // Disable tail calls if there is an swifterror argument. Targets have not
8114   // been updated to support tail calls.
8115   if (TLI.supportSwiftError() && SwiftErrorVal)
8116     isTailCall = false;
8117 
8118   ConstantInt *CFIType = nullptr;
8119   if (CB.isIndirectCall()) {
8120     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8121       if (!TLI.supportKCFIBundles())
8122         report_fatal_error(
8123             "Target doesn't support calls with kcfi operand bundles.");
8124       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8125       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8126     }
8127   }
8128 
8129   TargetLowering::CallLoweringInfo CLI(DAG);
8130   CLI.setDebugLoc(getCurSDLoc())
8131       .setChain(getRoot())
8132       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8133       .setTailCall(isTailCall)
8134       .setConvergent(CB.isConvergent())
8135       .setIsPreallocated(
8136           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8137       .setCFIType(CFIType);
8138   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8139 
8140   if (Result.first.getNode()) {
8141     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8142     setValue(&CB, Result.first);
8143   }
8144 
8145   // The last element of CLI.InVals has the SDValue for swifterror return.
8146   // Here we copy it to a virtual register and update SwiftErrorMap for
8147   // book-keeping.
8148   if (SwiftErrorVal && TLI.supportSwiftError()) {
8149     // Get the last element of InVals.
8150     SDValue Src = CLI.InVals.back();
8151     Register VReg =
8152         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8153     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8154     DAG.setRoot(CopyNode);
8155   }
8156 }
8157 
8158 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8159                              SelectionDAGBuilder &Builder) {
8160   // Check to see if this load can be trivially constant folded, e.g. if the
8161   // input is from a string literal.
8162   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8163     // Cast pointer to the type we really want to load.
8164     Type *LoadTy =
8165         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8166     if (LoadVT.isVector())
8167       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8168 
8169     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8170                                          PointerType::getUnqual(LoadTy));
8171 
8172     if (const Constant *LoadCst =
8173             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8174                                          LoadTy, Builder.DAG.getDataLayout()))
8175       return Builder.getValue(LoadCst);
8176   }
8177 
8178   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8179   // still constant memory, the input chain can be the entry node.
8180   SDValue Root;
8181   bool ConstantMemory = false;
8182 
8183   // Do not serialize (non-volatile) loads of constant memory with anything.
8184   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8185     Root = Builder.DAG.getEntryNode();
8186     ConstantMemory = true;
8187   } else {
8188     // Do not serialize non-volatile loads against each other.
8189     Root = Builder.DAG.getRoot();
8190   }
8191 
8192   SDValue Ptr = Builder.getValue(PtrVal);
8193   SDValue LoadVal =
8194       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8195                           MachinePointerInfo(PtrVal), Align(1));
8196 
8197   if (!ConstantMemory)
8198     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8199   return LoadVal;
8200 }
8201 
8202 /// Record the value for an instruction that produces an integer result,
8203 /// converting the type where necessary.
8204 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8205                                                   SDValue Value,
8206                                                   bool IsSigned) {
8207   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8208                                                     I.getType(), true);
8209   if (IsSigned)
8210     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
8211   else
8212     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
8213   setValue(&I, Value);
8214 }
8215 
8216 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8217 /// true and lower it. Otherwise return false, and it will be lowered like a
8218 /// normal call.
8219 /// The caller already checked that \p I calls the appropriate LibFunc with a
8220 /// correct prototype.
8221 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8222   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8223   const Value *Size = I.getArgOperand(2);
8224   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8225   if (CSize && CSize->getZExtValue() == 0) {
8226     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8227                                                           I.getType(), true);
8228     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8229     return true;
8230   }
8231 
8232   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8233   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8234       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8235       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8236   if (Res.first.getNode()) {
8237     processIntegerCallValue(I, Res.first, true);
8238     PendingLoads.push_back(Res.second);
8239     return true;
8240   }
8241 
8242   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8243   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8244   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8245     return false;
8246 
8247   // If the target has a fast compare for the given size, it will return a
8248   // preferred load type for that size. Require that the load VT is legal and
8249   // that the target supports unaligned loads of that type. Otherwise, return
8250   // INVALID.
8251   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8252     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8253     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8254     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8255       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8256       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8257       // TODO: Check alignment of src and dest ptrs.
8258       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8259       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8260       if (!TLI.isTypeLegal(LVT) ||
8261           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8262           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8263         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8264     }
8265 
8266     return LVT;
8267   };
8268 
8269   // This turns into unaligned loads. We only do this if the target natively
8270   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8271   // we'll only produce a small number of byte loads.
8272   MVT LoadVT;
8273   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8274   switch (NumBitsToCompare) {
8275   default:
8276     return false;
8277   case 16:
8278     LoadVT = MVT::i16;
8279     break;
8280   case 32:
8281     LoadVT = MVT::i32;
8282     break;
8283   case 64:
8284   case 128:
8285   case 256:
8286     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8287     break;
8288   }
8289 
8290   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8291     return false;
8292 
8293   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8294   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8295 
8296   // Bitcast to a wide integer type if the loads are vectors.
8297   if (LoadVT.isVector()) {
8298     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8299     LoadL = DAG.getBitcast(CmpVT, LoadL);
8300     LoadR = DAG.getBitcast(CmpVT, LoadR);
8301   }
8302 
8303   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8304   processIntegerCallValue(I, Cmp, false);
8305   return true;
8306 }
8307 
8308 /// See if we can lower a memchr call into an optimized form. If so, return
8309 /// true and lower it. Otherwise return false, and it will be lowered like a
8310 /// normal call.
8311 /// The caller already checked that \p I calls the appropriate LibFunc with a
8312 /// correct prototype.
8313 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8314   const Value *Src = I.getArgOperand(0);
8315   const Value *Char = I.getArgOperand(1);
8316   const Value *Length = I.getArgOperand(2);
8317 
8318   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8319   std::pair<SDValue, SDValue> Res =
8320     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8321                                 getValue(Src), getValue(Char), getValue(Length),
8322                                 MachinePointerInfo(Src));
8323   if (Res.first.getNode()) {
8324     setValue(&I, Res.first);
8325     PendingLoads.push_back(Res.second);
8326     return true;
8327   }
8328 
8329   return false;
8330 }
8331 
8332 /// See if we can lower a mempcpy call into an optimized form. If so, return
8333 /// true and lower it. Otherwise return false, and it will be lowered like a
8334 /// normal call.
8335 /// The caller already checked that \p I calls the appropriate LibFunc with a
8336 /// correct prototype.
8337 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8338   SDValue Dst = getValue(I.getArgOperand(0));
8339   SDValue Src = getValue(I.getArgOperand(1));
8340   SDValue Size = getValue(I.getArgOperand(2));
8341 
8342   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8343   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8344   // DAG::getMemcpy needs Alignment to be defined.
8345   Align Alignment = std::min(DstAlign, SrcAlign);
8346 
8347   SDLoc sdl = getCurSDLoc();
8348 
8349   // In the mempcpy context we need to pass in a false value for isTailCall
8350   // because the return pointer needs to be adjusted by the size of
8351   // the copied memory.
8352   SDValue Root = getMemoryRoot();
8353   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false,
8354                              /*isTailCall=*/false,
8355                              MachinePointerInfo(I.getArgOperand(0)),
8356                              MachinePointerInfo(I.getArgOperand(1)),
8357                              I.getAAMetadata());
8358   assert(MC.getNode() != nullptr &&
8359          "** memcpy should not be lowered as TailCall in mempcpy context **");
8360   DAG.setRoot(MC);
8361 
8362   // Check if Size needs to be truncated or extended.
8363   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8364 
8365   // Adjust return pointer to point just past the last dst byte.
8366   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8367                                     Dst, Size);
8368   setValue(&I, DstPlusSize);
8369   return true;
8370 }
8371 
8372 /// See if we can lower a strcpy call into an optimized form.  If so, return
8373 /// true and lower it, otherwise return false and it will be lowered like a
8374 /// normal call.
8375 /// The caller already checked that \p I calls the appropriate LibFunc with a
8376 /// correct prototype.
8377 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8378   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8379 
8380   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8381   std::pair<SDValue, SDValue> Res =
8382     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8383                                 getValue(Arg0), getValue(Arg1),
8384                                 MachinePointerInfo(Arg0),
8385                                 MachinePointerInfo(Arg1), isStpcpy);
8386   if (Res.first.getNode()) {
8387     setValue(&I, Res.first);
8388     DAG.setRoot(Res.second);
8389     return true;
8390   }
8391 
8392   return false;
8393 }
8394 
8395 /// See if we can lower a strcmp call into an optimized form.  If so, return
8396 /// true and lower it, otherwise return false and it will be lowered like a
8397 /// normal call.
8398 /// The caller already checked that \p I calls the appropriate LibFunc with a
8399 /// correct prototype.
8400 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8401   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8402 
8403   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8404   std::pair<SDValue, SDValue> Res =
8405     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8406                                 getValue(Arg0), getValue(Arg1),
8407                                 MachinePointerInfo(Arg0),
8408                                 MachinePointerInfo(Arg1));
8409   if (Res.first.getNode()) {
8410     processIntegerCallValue(I, Res.first, true);
8411     PendingLoads.push_back(Res.second);
8412     return true;
8413   }
8414 
8415   return false;
8416 }
8417 
8418 /// See if we can lower a strlen call into an optimized form.  If so, return
8419 /// true and lower it, otherwise return false and it will be lowered like a
8420 /// normal call.
8421 /// The caller already checked that \p I calls the appropriate LibFunc with a
8422 /// correct prototype.
8423 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8424   const Value *Arg0 = I.getArgOperand(0);
8425 
8426   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8427   std::pair<SDValue, SDValue> Res =
8428     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8429                                 getValue(Arg0), MachinePointerInfo(Arg0));
8430   if (Res.first.getNode()) {
8431     processIntegerCallValue(I, Res.first, false);
8432     PendingLoads.push_back(Res.second);
8433     return true;
8434   }
8435 
8436   return false;
8437 }
8438 
8439 /// See if we can lower a strnlen call into an optimized form.  If so, return
8440 /// true and lower it, otherwise return false and it will be lowered like a
8441 /// normal call.
8442 /// The caller already checked that \p I calls the appropriate LibFunc with a
8443 /// correct prototype.
8444 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8445   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8446 
8447   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8448   std::pair<SDValue, SDValue> Res =
8449     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8450                                  getValue(Arg0), getValue(Arg1),
8451                                  MachinePointerInfo(Arg0));
8452   if (Res.first.getNode()) {
8453     processIntegerCallValue(I, Res.first, false);
8454     PendingLoads.push_back(Res.second);
8455     return true;
8456   }
8457 
8458   return false;
8459 }
8460 
8461 /// See if we can lower a unary floating-point operation into an SDNode with
8462 /// the specified Opcode.  If so, return true and lower it, otherwise return
8463 /// false and it will be lowered like a normal call.
8464 /// The caller already checked that \p I calls the appropriate LibFunc with a
8465 /// correct prototype.
8466 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8467                                               unsigned Opcode) {
8468   // We already checked this call's prototype; verify it doesn't modify errno.
8469   if (!I.onlyReadsMemory())
8470     return false;
8471 
8472   SDNodeFlags Flags;
8473   Flags.copyFMF(cast<FPMathOperator>(I));
8474 
8475   SDValue Tmp = getValue(I.getArgOperand(0));
8476   setValue(&I,
8477            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8478   return true;
8479 }
8480 
8481 /// See if we can lower a binary floating-point operation into an SDNode with
8482 /// the specified Opcode. If so, return true and lower it. Otherwise return
8483 /// false, and it will be lowered like a normal call.
8484 /// The caller already checked that \p I calls the appropriate LibFunc with a
8485 /// correct prototype.
8486 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8487                                                unsigned Opcode) {
8488   // We already checked this call's prototype; verify it doesn't modify errno.
8489   if (!I.onlyReadsMemory())
8490     return false;
8491 
8492   SDNodeFlags Flags;
8493   Flags.copyFMF(cast<FPMathOperator>(I));
8494 
8495   SDValue Tmp0 = getValue(I.getArgOperand(0));
8496   SDValue Tmp1 = getValue(I.getArgOperand(1));
8497   EVT VT = Tmp0.getValueType();
8498   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8499   return true;
8500 }
8501 
8502 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8503   // Handle inline assembly differently.
8504   if (I.isInlineAsm()) {
8505     visitInlineAsm(I);
8506     return;
8507   }
8508 
8509   diagnoseDontCall(I);
8510 
8511   if (Function *F = I.getCalledFunction()) {
8512     if (F->isDeclaration()) {
8513       // Is this an LLVM intrinsic or a target-specific intrinsic?
8514       unsigned IID = F->getIntrinsicID();
8515       if (!IID)
8516         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8517           IID = II->getIntrinsicID(F);
8518 
8519       if (IID) {
8520         visitIntrinsicCall(I, IID);
8521         return;
8522       }
8523     }
8524 
8525     // Check for well-known libc/libm calls.  If the function is internal, it
8526     // can't be a library call.  Don't do the check if marked as nobuiltin for
8527     // some reason or the call site requires strict floating point semantics.
8528     LibFunc Func;
8529     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8530         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8531         LibInfo->hasOptimizedCodeGen(Func)) {
8532       switch (Func) {
8533       default: break;
8534       case LibFunc_bcmp:
8535         if (visitMemCmpBCmpCall(I))
8536           return;
8537         break;
8538       case LibFunc_copysign:
8539       case LibFunc_copysignf:
8540       case LibFunc_copysignl:
8541         // We already checked this call's prototype; verify it doesn't modify
8542         // errno.
8543         if (I.onlyReadsMemory()) {
8544           SDValue LHS = getValue(I.getArgOperand(0));
8545           SDValue RHS = getValue(I.getArgOperand(1));
8546           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8547                                    LHS.getValueType(), LHS, RHS));
8548           return;
8549         }
8550         break;
8551       case LibFunc_fabs:
8552       case LibFunc_fabsf:
8553       case LibFunc_fabsl:
8554         if (visitUnaryFloatCall(I, ISD::FABS))
8555           return;
8556         break;
8557       case LibFunc_fmin:
8558       case LibFunc_fminf:
8559       case LibFunc_fminl:
8560         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8561           return;
8562         break;
8563       case LibFunc_fmax:
8564       case LibFunc_fmaxf:
8565       case LibFunc_fmaxl:
8566         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8567           return;
8568         break;
8569       case LibFunc_sin:
8570       case LibFunc_sinf:
8571       case LibFunc_sinl:
8572         if (visitUnaryFloatCall(I, ISD::FSIN))
8573           return;
8574         break;
8575       case LibFunc_cos:
8576       case LibFunc_cosf:
8577       case LibFunc_cosl:
8578         if (visitUnaryFloatCall(I, ISD::FCOS))
8579           return;
8580         break;
8581       case LibFunc_sqrt:
8582       case LibFunc_sqrtf:
8583       case LibFunc_sqrtl:
8584       case LibFunc_sqrt_finite:
8585       case LibFunc_sqrtf_finite:
8586       case LibFunc_sqrtl_finite:
8587         if (visitUnaryFloatCall(I, ISD::FSQRT))
8588           return;
8589         break;
8590       case LibFunc_floor:
8591       case LibFunc_floorf:
8592       case LibFunc_floorl:
8593         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8594           return;
8595         break;
8596       case LibFunc_nearbyint:
8597       case LibFunc_nearbyintf:
8598       case LibFunc_nearbyintl:
8599         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8600           return;
8601         break;
8602       case LibFunc_ceil:
8603       case LibFunc_ceilf:
8604       case LibFunc_ceill:
8605         if (visitUnaryFloatCall(I, ISD::FCEIL))
8606           return;
8607         break;
8608       case LibFunc_rint:
8609       case LibFunc_rintf:
8610       case LibFunc_rintl:
8611         if (visitUnaryFloatCall(I, ISD::FRINT))
8612           return;
8613         break;
8614       case LibFunc_round:
8615       case LibFunc_roundf:
8616       case LibFunc_roundl:
8617         if (visitUnaryFloatCall(I, ISD::FROUND))
8618           return;
8619         break;
8620       case LibFunc_trunc:
8621       case LibFunc_truncf:
8622       case LibFunc_truncl:
8623         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8624           return;
8625         break;
8626       case LibFunc_log2:
8627       case LibFunc_log2f:
8628       case LibFunc_log2l:
8629         if (visitUnaryFloatCall(I, ISD::FLOG2))
8630           return;
8631         break;
8632       case LibFunc_exp2:
8633       case LibFunc_exp2f:
8634       case LibFunc_exp2l:
8635         if (visitUnaryFloatCall(I, ISD::FEXP2))
8636           return;
8637         break;
8638       case LibFunc_memcmp:
8639         if (visitMemCmpBCmpCall(I))
8640           return;
8641         break;
8642       case LibFunc_mempcpy:
8643         if (visitMemPCpyCall(I))
8644           return;
8645         break;
8646       case LibFunc_memchr:
8647         if (visitMemChrCall(I))
8648           return;
8649         break;
8650       case LibFunc_strcpy:
8651         if (visitStrCpyCall(I, false))
8652           return;
8653         break;
8654       case LibFunc_stpcpy:
8655         if (visitStrCpyCall(I, true))
8656           return;
8657         break;
8658       case LibFunc_strcmp:
8659         if (visitStrCmpCall(I))
8660           return;
8661         break;
8662       case LibFunc_strlen:
8663         if (visitStrLenCall(I))
8664           return;
8665         break;
8666       case LibFunc_strnlen:
8667         if (visitStrNLenCall(I))
8668           return;
8669         break;
8670       }
8671     }
8672   }
8673 
8674   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8675   // have to do anything here to lower funclet bundles.
8676   // CFGuardTarget bundles are lowered in LowerCallTo.
8677   assert(!I.hasOperandBundlesOtherThan(
8678              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8679               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8680               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8681          "Cannot lower calls with arbitrary operand bundles!");
8682 
8683   SDValue Callee = getValue(I.getCalledOperand());
8684 
8685   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8686     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8687   else
8688     // Check if we can potentially perform a tail call. More detailed checking
8689     // is be done within LowerCallTo, after more information about the call is
8690     // known.
8691     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8692 }
8693 
8694 namespace {
8695 
8696 /// AsmOperandInfo - This contains information for each constraint that we are
8697 /// lowering.
8698 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8699 public:
8700   /// CallOperand - If this is the result output operand or a clobber
8701   /// this is null, otherwise it is the incoming operand to the CallInst.
8702   /// This gets modified as the asm is processed.
8703   SDValue CallOperand;
8704 
8705   /// AssignedRegs - If this is a register or register class operand, this
8706   /// contains the set of register corresponding to the operand.
8707   RegsForValue AssignedRegs;
8708 
8709   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8710     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8711   }
8712 
8713   /// Whether or not this operand accesses memory
8714   bool hasMemory(const TargetLowering &TLI) const {
8715     // Indirect operand accesses access memory.
8716     if (isIndirect)
8717       return true;
8718 
8719     for (const auto &Code : Codes)
8720       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8721         return true;
8722 
8723     return false;
8724   }
8725 };
8726 
8727 
8728 } // end anonymous namespace
8729 
8730 /// Make sure that the output operand \p OpInfo and its corresponding input
8731 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8732 /// out).
8733 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8734                                SDISelAsmOperandInfo &MatchingOpInfo,
8735                                SelectionDAG &DAG) {
8736   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8737     return;
8738 
8739   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8740   const auto &TLI = DAG.getTargetLoweringInfo();
8741 
8742   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8743       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8744                                        OpInfo.ConstraintVT);
8745   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8746       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8747                                        MatchingOpInfo.ConstraintVT);
8748   if ((OpInfo.ConstraintVT.isInteger() !=
8749        MatchingOpInfo.ConstraintVT.isInteger()) ||
8750       (MatchRC.second != InputRC.second)) {
8751     // FIXME: error out in a more elegant fashion
8752     report_fatal_error("Unsupported asm: input constraint"
8753                        " with a matching output constraint of"
8754                        " incompatible type!");
8755   }
8756   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8757 }
8758 
8759 /// Get a direct memory input to behave well as an indirect operand.
8760 /// This may introduce stores, hence the need for a \p Chain.
8761 /// \return The (possibly updated) chain.
8762 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8763                                         SDISelAsmOperandInfo &OpInfo,
8764                                         SelectionDAG &DAG) {
8765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8766 
8767   // If we don't have an indirect input, put it in the constpool if we can,
8768   // otherwise spill it to a stack slot.
8769   // TODO: This isn't quite right. We need to handle these according to
8770   // the addressing mode that the constraint wants. Also, this may take
8771   // an additional register for the computation and we don't want that
8772   // either.
8773 
8774   // If the operand is a float, integer, or vector constant, spill to a
8775   // constant pool entry to get its address.
8776   const Value *OpVal = OpInfo.CallOperandVal;
8777   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8778       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8779     OpInfo.CallOperand = DAG.getConstantPool(
8780         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8781     return Chain;
8782   }
8783 
8784   // Otherwise, create a stack slot and emit a store to it before the asm.
8785   Type *Ty = OpVal->getType();
8786   auto &DL = DAG.getDataLayout();
8787   uint64_t TySize = DL.getTypeAllocSize(Ty);
8788   MachineFunction &MF = DAG.getMachineFunction();
8789   int SSFI = MF.getFrameInfo().CreateStackObject(
8790       TySize, DL.getPrefTypeAlign(Ty), false);
8791   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8792   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8793                             MachinePointerInfo::getFixedStack(MF, SSFI),
8794                             TLI.getMemValueType(DL, Ty));
8795   OpInfo.CallOperand = StackSlot;
8796 
8797   return Chain;
8798 }
8799 
8800 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8801 /// specified operand.  We prefer to assign virtual registers, to allow the
8802 /// register allocator to handle the assignment process.  However, if the asm
8803 /// uses features that we can't model on machineinstrs, we have SDISel do the
8804 /// allocation.  This produces generally horrible, but correct, code.
8805 ///
8806 ///   OpInfo describes the operand
8807 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8808 static std::optional<unsigned>
8809 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8810                      SDISelAsmOperandInfo &OpInfo,
8811                      SDISelAsmOperandInfo &RefOpInfo) {
8812   LLVMContext &Context = *DAG.getContext();
8813   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8814 
8815   MachineFunction &MF = DAG.getMachineFunction();
8816   SmallVector<unsigned, 4> Regs;
8817   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8818 
8819   // No work to do for memory/address operands.
8820   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8821       OpInfo.ConstraintType == TargetLowering::C_Address)
8822     return std::nullopt;
8823 
8824   // If this is a constraint for a single physreg, or a constraint for a
8825   // register class, find it.
8826   unsigned AssignedReg;
8827   const TargetRegisterClass *RC;
8828   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8829       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8830   // RC is unset only on failure. Return immediately.
8831   if (!RC)
8832     return std::nullopt;
8833 
8834   // Get the actual register value type.  This is important, because the user
8835   // may have asked for (e.g.) the AX register in i32 type.  We need to
8836   // remember that AX is actually i16 to get the right extension.
8837   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8838 
8839   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8840     // If this is an FP operand in an integer register (or visa versa), or more
8841     // generally if the operand value disagrees with the register class we plan
8842     // to stick it in, fix the operand type.
8843     //
8844     // If this is an input value, the bitcast to the new type is done now.
8845     // Bitcast for output value is done at the end of visitInlineAsm().
8846     if ((OpInfo.Type == InlineAsm::isOutput ||
8847          OpInfo.Type == InlineAsm::isInput) &&
8848         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8849       // Try to convert to the first EVT that the reg class contains.  If the
8850       // types are identical size, use a bitcast to convert (e.g. two differing
8851       // vector types).  Note: output bitcast is done at the end of
8852       // visitInlineAsm().
8853       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8854         // Exclude indirect inputs while they are unsupported because the code
8855         // to perform the load is missing and thus OpInfo.CallOperand still
8856         // refers to the input address rather than the pointed-to value.
8857         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8858           OpInfo.CallOperand =
8859               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8860         OpInfo.ConstraintVT = RegVT;
8861         // If the operand is an FP value and we want it in integer registers,
8862         // use the corresponding integer type. This turns an f64 value into
8863         // i64, which can be passed with two i32 values on a 32-bit machine.
8864       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8865         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8866         if (OpInfo.Type == InlineAsm::isInput)
8867           OpInfo.CallOperand =
8868               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8869         OpInfo.ConstraintVT = VT;
8870       }
8871     }
8872   }
8873 
8874   // No need to allocate a matching input constraint since the constraint it's
8875   // matching to has already been allocated.
8876   if (OpInfo.isMatchingInputConstraint())
8877     return std::nullopt;
8878 
8879   EVT ValueVT = OpInfo.ConstraintVT;
8880   if (OpInfo.ConstraintVT == MVT::Other)
8881     ValueVT = RegVT;
8882 
8883   // Initialize NumRegs.
8884   unsigned NumRegs = 1;
8885   if (OpInfo.ConstraintVT != MVT::Other)
8886     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8887 
8888   // If this is a constraint for a specific physical register, like {r17},
8889   // assign it now.
8890 
8891   // If this associated to a specific register, initialize iterator to correct
8892   // place. If virtual, make sure we have enough registers
8893 
8894   // Initialize iterator if necessary
8895   TargetRegisterClass::iterator I = RC->begin();
8896   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8897 
8898   // Do not check for single registers.
8899   if (AssignedReg) {
8900     I = std::find(I, RC->end(), AssignedReg);
8901     if (I == RC->end()) {
8902       // RC does not contain the selected register, which indicates a
8903       // mismatch between the register and the required type/bitwidth.
8904       return {AssignedReg};
8905     }
8906   }
8907 
8908   for (; NumRegs; --NumRegs, ++I) {
8909     assert(I != RC->end() && "Ran out of registers to allocate!");
8910     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8911     Regs.push_back(R);
8912   }
8913 
8914   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8915   return std::nullopt;
8916 }
8917 
8918 static unsigned
8919 findMatchingInlineAsmOperand(unsigned OperandNo,
8920                              const std::vector<SDValue> &AsmNodeOperands) {
8921   // Scan until we find the definition we already emitted of this operand.
8922   unsigned CurOp = InlineAsm::Op_FirstOperand;
8923   for (; OperandNo; --OperandNo) {
8924     // Advance to the next operand.
8925     unsigned OpFlag =
8926         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8927     assert((InlineAsm::isRegDefKind(OpFlag) ||
8928             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8929             InlineAsm::isMemKind(OpFlag)) &&
8930            "Skipped past definitions?");
8931     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8932   }
8933   return CurOp;
8934 }
8935 
8936 namespace {
8937 
8938 class ExtraFlags {
8939   unsigned Flags = 0;
8940 
8941 public:
8942   explicit ExtraFlags(const CallBase &Call) {
8943     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8944     if (IA->hasSideEffects())
8945       Flags |= InlineAsm::Extra_HasSideEffects;
8946     if (IA->isAlignStack())
8947       Flags |= InlineAsm::Extra_IsAlignStack;
8948     if (Call.isConvergent())
8949       Flags |= InlineAsm::Extra_IsConvergent;
8950     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8951   }
8952 
8953   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8954     // Ideally, we would only check against memory constraints.  However, the
8955     // meaning of an Other constraint can be target-specific and we can't easily
8956     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8957     // for Other constraints as well.
8958     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8959         OpInfo.ConstraintType == TargetLowering::C_Other) {
8960       if (OpInfo.Type == InlineAsm::isInput)
8961         Flags |= InlineAsm::Extra_MayLoad;
8962       else if (OpInfo.Type == InlineAsm::isOutput)
8963         Flags |= InlineAsm::Extra_MayStore;
8964       else if (OpInfo.Type == InlineAsm::isClobber)
8965         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8966     }
8967   }
8968 
8969   unsigned get() const { return Flags; }
8970 };
8971 
8972 } // end anonymous namespace
8973 
8974 static bool isFunction(SDValue Op) {
8975   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
8976     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8977       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
8978 
8979       // In normal "call dllimport func" instruction (non-inlineasm) it force
8980       // indirect access by specifing call opcode. And usually specially print
8981       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
8982       // not do in this way now. (In fact, this is similar with "Data Access"
8983       // action). So here we ignore dllimport function.
8984       if (Fn && !Fn->hasDLLImportStorageClass())
8985         return true;
8986     }
8987   }
8988   return false;
8989 }
8990 
8991 /// visitInlineAsm - Handle a call to an InlineAsm object.
8992 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8993                                          const BasicBlock *EHPadBB) {
8994   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8995 
8996   /// ConstraintOperands - Information about all of the constraints.
8997   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8998 
8999   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9000   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9001       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9002 
9003   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9004   // AsmDialect, MayLoad, MayStore).
9005   bool HasSideEffect = IA->hasSideEffects();
9006   ExtraFlags ExtraInfo(Call);
9007 
9008   for (auto &T : TargetConstraints) {
9009     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9010     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9011 
9012     if (OpInfo.CallOperandVal)
9013       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9014 
9015     if (!HasSideEffect)
9016       HasSideEffect = OpInfo.hasMemory(TLI);
9017 
9018     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9019     // FIXME: Could we compute this on OpInfo rather than T?
9020 
9021     // Compute the constraint code and ConstraintType to use.
9022     TLI.ComputeConstraintToUse(T, SDValue());
9023 
9024     if (T.ConstraintType == TargetLowering::C_Immediate &&
9025         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9026       // We've delayed emitting a diagnostic like the "n" constraint because
9027       // inlining could cause an integer showing up.
9028       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9029                                           "' expects an integer constant "
9030                                           "expression");
9031 
9032     ExtraInfo.update(T);
9033   }
9034 
9035   // We won't need to flush pending loads if this asm doesn't touch
9036   // memory and is nonvolatile.
9037   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9038 
9039   bool EmitEHLabels = isa<InvokeInst>(Call);
9040   if (EmitEHLabels) {
9041     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9042   }
9043   bool IsCallBr = isa<CallBrInst>(Call);
9044 
9045   if (IsCallBr || EmitEHLabels) {
9046     // If this is a callbr or invoke we need to flush pending exports since
9047     // inlineasm_br and invoke are terminators.
9048     // We need to do this before nodes are glued to the inlineasm_br node.
9049     Chain = getControlRoot();
9050   }
9051 
9052   MCSymbol *BeginLabel = nullptr;
9053   if (EmitEHLabels) {
9054     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9055   }
9056 
9057   int OpNo = -1;
9058   SmallVector<StringRef> AsmStrs;
9059   IA->collectAsmStrs(AsmStrs);
9060 
9061   // Second pass over the constraints: compute which constraint option to use.
9062   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9063     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9064       OpNo++;
9065 
9066     // If this is an output operand with a matching input operand, look up the
9067     // matching input. If their types mismatch, e.g. one is an integer, the
9068     // other is floating point, or their sizes are different, flag it as an
9069     // error.
9070     if (OpInfo.hasMatchingInput()) {
9071       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9072       patchMatchingInput(OpInfo, Input, DAG);
9073     }
9074 
9075     // Compute the constraint code and ConstraintType to use.
9076     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9077 
9078     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9079          OpInfo.Type == InlineAsm::isClobber) ||
9080         OpInfo.ConstraintType == TargetLowering::C_Address)
9081       continue;
9082 
9083     // In Linux PIC model, there are 4 cases about value/label addressing:
9084     //
9085     // 1: Function call or Label jmp inside the module.
9086     // 2: Data access (such as global variable, static variable) inside module.
9087     // 3: Function call or Label jmp outside the module.
9088     // 4: Data access (such as global variable) outside the module.
9089     //
9090     // Due to current llvm inline asm architecture designed to not "recognize"
9091     // the asm code, there are quite troubles for us to treat mem addressing
9092     // differently for same value/adress used in different instuctions.
9093     // For example, in pic model, call a func may in plt way or direclty
9094     // pc-related, but lea/mov a function adress may use got.
9095     //
9096     // Here we try to "recognize" function call for the case 1 and case 3 in
9097     // inline asm. And try to adjust the constraint for them.
9098     //
9099     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9100     // label, so here we don't handle jmp function label now, but we need to
9101     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9102     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9103         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9104         TM.getCodeModel() != CodeModel::Large) {
9105       OpInfo.isIndirect = false;
9106       OpInfo.ConstraintType = TargetLowering::C_Address;
9107     }
9108 
9109     // If this is a memory input, and if the operand is not indirect, do what we
9110     // need to provide an address for the memory input.
9111     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9112         !OpInfo.isIndirect) {
9113       assert((OpInfo.isMultipleAlternative ||
9114               (OpInfo.Type == InlineAsm::isInput)) &&
9115              "Can only indirectify direct input operands!");
9116 
9117       // Memory operands really want the address of the value.
9118       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9119 
9120       // There is no longer a Value* corresponding to this operand.
9121       OpInfo.CallOperandVal = nullptr;
9122 
9123       // It is now an indirect operand.
9124       OpInfo.isIndirect = true;
9125     }
9126 
9127   }
9128 
9129   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9130   std::vector<SDValue> AsmNodeOperands;
9131   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9132   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9133       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9134 
9135   // If we have a !srcloc metadata node associated with it, we want to attach
9136   // this to the ultimately generated inline asm machineinstr.  To do this, we
9137   // pass in the third operand as this (potentially null) inline asm MDNode.
9138   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9139   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9140 
9141   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9142   // bits as operand 3.
9143   AsmNodeOperands.push_back(DAG.getTargetConstant(
9144       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9145 
9146   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9147   // this, assign virtual and physical registers for inputs and otput.
9148   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9149     // Assign Registers.
9150     SDISelAsmOperandInfo &RefOpInfo =
9151         OpInfo.isMatchingInputConstraint()
9152             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9153             : OpInfo;
9154     const auto RegError =
9155         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9156     if (RegError) {
9157       const MachineFunction &MF = DAG.getMachineFunction();
9158       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9159       const char *RegName = TRI.getName(*RegError);
9160       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9161                                    "' allocated for constraint '" +
9162                                    Twine(OpInfo.ConstraintCode) +
9163                                    "' does not match required type");
9164       return;
9165     }
9166 
9167     auto DetectWriteToReservedRegister = [&]() {
9168       const MachineFunction &MF = DAG.getMachineFunction();
9169       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9170       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9171         if (Register::isPhysicalRegister(Reg) &&
9172             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9173           const char *RegName = TRI.getName(Reg);
9174           emitInlineAsmError(Call, "write to reserved register '" +
9175                                        Twine(RegName) + "'");
9176           return true;
9177         }
9178       }
9179       return false;
9180     };
9181     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9182             (OpInfo.Type == InlineAsm::isInput &&
9183              !OpInfo.isMatchingInputConstraint())) &&
9184            "Only address as input operand is allowed.");
9185 
9186     switch (OpInfo.Type) {
9187     case InlineAsm::isOutput:
9188       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9189         unsigned ConstraintID =
9190             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9191         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9192                "Failed to convert memory constraint code to constraint id.");
9193 
9194         // Add information to the INLINEASM node to know about this output.
9195         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9196         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
9197         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9198                                                         MVT::i32));
9199         AsmNodeOperands.push_back(OpInfo.CallOperand);
9200       } else {
9201         // Otherwise, this outputs to a register (directly for C_Register /
9202         // C_RegisterClass, and a target-defined fashion for
9203         // C_Immediate/C_Other). Find a register that we can use.
9204         if (OpInfo.AssignedRegs.Regs.empty()) {
9205           emitInlineAsmError(
9206               Call, "couldn't allocate output register for constraint '" +
9207                         Twine(OpInfo.ConstraintCode) + "'");
9208           return;
9209         }
9210 
9211         if (DetectWriteToReservedRegister())
9212           return;
9213 
9214         // Add information to the INLINEASM node to know that this register is
9215         // set.
9216         OpInfo.AssignedRegs.AddInlineAsmOperands(
9217             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
9218                                   : InlineAsm::Kind_RegDef,
9219             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9220       }
9221       break;
9222 
9223     case InlineAsm::isInput:
9224     case InlineAsm::isLabel: {
9225       SDValue InOperandVal = OpInfo.CallOperand;
9226 
9227       if (OpInfo.isMatchingInputConstraint()) {
9228         // If this is required to match an output register we have already set,
9229         // just use its register.
9230         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9231                                                   AsmNodeOperands);
9232         unsigned OpFlag =
9233           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
9234         if (InlineAsm::isRegDefKind(OpFlag) ||
9235             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
9236           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
9237           if (OpInfo.isIndirect) {
9238             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9239             emitInlineAsmError(Call, "inline asm not supported yet: "
9240                                      "don't know how to handle tied "
9241                                      "indirect register inputs");
9242             return;
9243           }
9244 
9245           SmallVector<unsigned, 4> Regs;
9246           MachineFunction &MF = DAG.getMachineFunction();
9247           MachineRegisterInfo &MRI = MF.getRegInfo();
9248           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9249           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9250           Register TiedReg = R->getReg();
9251           MVT RegVT = R->getSimpleValueType(0);
9252           const TargetRegisterClass *RC =
9253               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9254               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9255                                       : TRI.getMinimalPhysRegClass(TiedReg);
9256           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
9257           for (unsigned i = 0; i != NumRegs; ++i)
9258             Regs.push_back(MRI.createVirtualRegister(RC));
9259 
9260           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9261 
9262           SDLoc dl = getCurSDLoc();
9263           // Use the produced MatchedRegs object to
9264           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9265           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
9266                                            true, OpInfo.getMatchedOperand(), dl,
9267                                            DAG, AsmNodeOperands);
9268           break;
9269         }
9270 
9271         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
9272         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
9273                "Unexpected number of operands");
9274         // Add information to the INLINEASM node to know about this input.
9275         // See InlineAsm.h isUseOperandTiedToDef.
9276         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
9277         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
9278                                                     OpInfo.getMatchedOperand());
9279         AsmNodeOperands.push_back(DAG.getTargetConstant(
9280             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9281         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9282         break;
9283       }
9284 
9285       // Treat indirect 'X' constraint as memory.
9286       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9287           OpInfo.isIndirect)
9288         OpInfo.ConstraintType = TargetLowering::C_Memory;
9289 
9290       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9291           OpInfo.ConstraintType == TargetLowering::C_Other) {
9292         std::vector<SDValue> Ops;
9293         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9294                                           Ops, DAG);
9295         if (Ops.empty()) {
9296           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9297             if (isa<ConstantSDNode>(InOperandVal)) {
9298               emitInlineAsmError(Call, "value out of range for constraint '" +
9299                                            Twine(OpInfo.ConstraintCode) + "'");
9300               return;
9301             }
9302 
9303           emitInlineAsmError(Call,
9304                              "invalid operand for inline asm constraint '" +
9305                                  Twine(OpInfo.ConstraintCode) + "'");
9306           return;
9307         }
9308 
9309         // Add information to the INLINEASM node to know about this input.
9310         unsigned ResOpType =
9311           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
9312         AsmNodeOperands.push_back(DAG.getTargetConstant(
9313             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9314         llvm::append_range(AsmNodeOperands, Ops);
9315         break;
9316       }
9317 
9318       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9319         assert((OpInfo.isIndirect ||
9320                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9321                "Operand must be indirect to be a mem!");
9322         assert(InOperandVal.getValueType() ==
9323                    TLI.getPointerTy(DAG.getDataLayout()) &&
9324                "Memory operands expect pointer values");
9325 
9326         unsigned ConstraintID =
9327             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9328         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9329                "Failed to convert memory constraint code to constraint id.");
9330 
9331         // Add information to the INLINEASM node to know about this input.
9332         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9333         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9334         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9335                                                         getCurSDLoc(),
9336                                                         MVT::i32));
9337         AsmNodeOperands.push_back(InOperandVal);
9338         break;
9339       }
9340 
9341       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9342         assert(InOperandVal.getValueType() ==
9343                    TLI.getPointerTy(DAG.getDataLayout()) &&
9344                "Address operands expect pointer values");
9345 
9346         unsigned ConstraintID =
9347             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9348         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9349                "Failed to convert memory constraint code to constraint id.");
9350 
9351         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9352 
9353         SDValue AsmOp = InOperandVal;
9354         if (isFunction(InOperandVal)) {
9355           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9356           ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1);
9357           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9358                                              InOperandVal.getValueType(),
9359                                              GA->getOffset());
9360         }
9361 
9362         // Add information to the INLINEASM node to know about this input.
9363         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9364 
9365         AsmNodeOperands.push_back(
9366             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9367 
9368         AsmNodeOperands.push_back(AsmOp);
9369         break;
9370       }
9371 
9372       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9373               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9374              "Unknown constraint type!");
9375 
9376       // TODO: Support this.
9377       if (OpInfo.isIndirect) {
9378         emitInlineAsmError(
9379             Call, "Don't know how to handle indirect register inputs yet "
9380                   "for constraint '" +
9381                       Twine(OpInfo.ConstraintCode) + "'");
9382         return;
9383       }
9384 
9385       // Copy the input into the appropriate registers.
9386       if (OpInfo.AssignedRegs.Regs.empty()) {
9387         emitInlineAsmError(Call,
9388                            "couldn't allocate input reg for constraint '" +
9389                                Twine(OpInfo.ConstraintCode) + "'");
9390         return;
9391       }
9392 
9393       if (DetectWriteToReservedRegister())
9394         return;
9395 
9396       SDLoc dl = getCurSDLoc();
9397 
9398       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
9399                                         &Call);
9400 
9401       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
9402                                                dl, DAG, AsmNodeOperands);
9403       break;
9404     }
9405     case InlineAsm::isClobber:
9406       // Add the clobbered value to the operand list, so that the register
9407       // allocator is aware that the physreg got clobbered.
9408       if (!OpInfo.AssignedRegs.Regs.empty())
9409         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
9410                                                  false, 0, getCurSDLoc(), DAG,
9411                                                  AsmNodeOperands);
9412       break;
9413     }
9414   }
9415 
9416   // Finish up input operands.  Set the input chain and add the flag last.
9417   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9418   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
9419 
9420   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9421   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9422                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9423   Glue = Chain.getValue(1);
9424 
9425   // Do additional work to generate outputs.
9426 
9427   SmallVector<EVT, 1> ResultVTs;
9428   SmallVector<SDValue, 1> ResultValues;
9429   SmallVector<SDValue, 8> OutChains;
9430 
9431   llvm::Type *CallResultType = Call.getType();
9432   ArrayRef<Type *> ResultTypes;
9433   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9434     ResultTypes = StructResult->elements();
9435   else if (!CallResultType->isVoidTy())
9436     ResultTypes = ArrayRef(CallResultType);
9437 
9438   auto CurResultType = ResultTypes.begin();
9439   auto handleRegAssign = [&](SDValue V) {
9440     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9441     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9442     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9443     ++CurResultType;
9444     // If the type of the inline asm call site return value is different but has
9445     // same size as the type of the asm output bitcast it.  One example of this
9446     // is for vectors with different width / number of elements.  This can
9447     // happen for register classes that can contain multiple different value
9448     // types.  The preg or vreg allocated may not have the same VT as was
9449     // expected.
9450     //
9451     // This can also happen for a return value that disagrees with the register
9452     // class it is put in, eg. a double in a general-purpose register on a
9453     // 32-bit machine.
9454     if (ResultVT != V.getValueType() &&
9455         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9456       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9457     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9458              V.getValueType().isInteger()) {
9459       // If a result value was tied to an input value, the computed result
9460       // may have a wider width than the expected result.  Extract the
9461       // relevant portion.
9462       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9463     }
9464     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9465     ResultVTs.push_back(ResultVT);
9466     ResultValues.push_back(V);
9467   };
9468 
9469   // Deal with output operands.
9470   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9471     if (OpInfo.Type == InlineAsm::isOutput) {
9472       SDValue Val;
9473       // Skip trivial output operands.
9474       if (OpInfo.AssignedRegs.Regs.empty())
9475         continue;
9476 
9477       switch (OpInfo.ConstraintType) {
9478       case TargetLowering::C_Register:
9479       case TargetLowering::C_RegisterClass:
9480         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9481                                                   Chain, &Glue, &Call);
9482         break;
9483       case TargetLowering::C_Immediate:
9484       case TargetLowering::C_Other:
9485         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
9486                                               OpInfo, DAG);
9487         break;
9488       case TargetLowering::C_Memory:
9489         break; // Already handled.
9490       case TargetLowering::C_Address:
9491         break; // Silence warning.
9492       case TargetLowering::C_Unknown:
9493         assert(false && "Unexpected unknown constraint");
9494       }
9495 
9496       // Indirect output manifest as stores. Record output chains.
9497       if (OpInfo.isIndirect) {
9498         const Value *Ptr = OpInfo.CallOperandVal;
9499         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9500         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9501                                      MachinePointerInfo(Ptr));
9502         OutChains.push_back(Store);
9503       } else {
9504         // generate CopyFromRegs to associated registers.
9505         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9506         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9507           for (const SDValue &V : Val->op_values())
9508             handleRegAssign(V);
9509         } else
9510           handleRegAssign(Val);
9511       }
9512     }
9513   }
9514 
9515   // Set results.
9516   if (!ResultValues.empty()) {
9517     assert(CurResultType == ResultTypes.end() &&
9518            "Mismatch in number of ResultTypes");
9519     assert(ResultValues.size() == ResultTypes.size() &&
9520            "Mismatch in number of output operands in asm result");
9521 
9522     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9523                             DAG.getVTList(ResultVTs), ResultValues);
9524     setValue(&Call, V);
9525   }
9526 
9527   // Collect store chains.
9528   if (!OutChains.empty())
9529     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9530 
9531   if (EmitEHLabels) {
9532     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9533   }
9534 
9535   // Only Update Root if inline assembly has a memory effect.
9536   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9537       EmitEHLabels)
9538     DAG.setRoot(Chain);
9539 }
9540 
9541 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9542                                              const Twine &Message) {
9543   LLVMContext &Ctx = *DAG.getContext();
9544   Ctx.emitError(&Call, Message);
9545 
9546   // Make sure we leave the DAG in a valid state
9547   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9548   SmallVector<EVT, 1> ValueVTs;
9549   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9550 
9551   if (ValueVTs.empty())
9552     return;
9553 
9554   SmallVector<SDValue, 1> Ops;
9555   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9556     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9557 
9558   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9559 }
9560 
9561 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9562   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9563                           MVT::Other, getRoot(),
9564                           getValue(I.getArgOperand(0)),
9565                           DAG.getSrcValue(I.getArgOperand(0))));
9566 }
9567 
9568 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9569   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9570   const DataLayout &DL = DAG.getDataLayout();
9571   SDValue V = DAG.getVAArg(
9572       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9573       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9574       DL.getABITypeAlign(I.getType()).value());
9575   DAG.setRoot(V.getValue(1));
9576 
9577   if (I.getType()->isPointerTy())
9578     V = DAG.getPtrExtOrTrunc(
9579         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9580   setValue(&I, V);
9581 }
9582 
9583 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9584   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9585                           MVT::Other, getRoot(),
9586                           getValue(I.getArgOperand(0)),
9587                           DAG.getSrcValue(I.getArgOperand(0))));
9588 }
9589 
9590 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9591   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9592                           MVT::Other, getRoot(),
9593                           getValue(I.getArgOperand(0)),
9594                           getValue(I.getArgOperand(1)),
9595                           DAG.getSrcValue(I.getArgOperand(0)),
9596                           DAG.getSrcValue(I.getArgOperand(1))));
9597 }
9598 
9599 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9600                                                     const Instruction &I,
9601                                                     SDValue Op) {
9602   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9603   if (!Range)
9604     return Op;
9605 
9606   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9607   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9608     return Op;
9609 
9610   APInt Lo = CR.getUnsignedMin();
9611   if (!Lo.isMinValue())
9612     return Op;
9613 
9614   APInt Hi = CR.getUnsignedMax();
9615   unsigned Bits = std::max(Hi.getActiveBits(),
9616                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9617 
9618   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9619 
9620   SDLoc SL = getCurSDLoc();
9621 
9622   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9623                              DAG.getValueType(SmallVT));
9624   unsigned NumVals = Op.getNode()->getNumValues();
9625   if (NumVals == 1)
9626     return ZExt;
9627 
9628   SmallVector<SDValue, 4> Ops;
9629 
9630   Ops.push_back(ZExt);
9631   for (unsigned I = 1; I != NumVals; ++I)
9632     Ops.push_back(Op.getValue(I));
9633 
9634   return DAG.getMergeValues(Ops, SL);
9635 }
9636 
9637 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9638 /// the call being lowered.
9639 ///
9640 /// This is a helper for lowering intrinsics that follow a target calling
9641 /// convention or require stack pointer adjustment. Only a subset of the
9642 /// intrinsic's operands need to participate in the calling convention.
9643 void SelectionDAGBuilder::populateCallLoweringInfo(
9644     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9645     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9646     bool IsPatchPoint) {
9647   TargetLowering::ArgListTy Args;
9648   Args.reserve(NumArgs);
9649 
9650   // Populate the argument list.
9651   // Attributes for args start at offset 1, after the return attribute.
9652   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9653        ArgI != ArgE; ++ArgI) {
9654     const Value *V = Call->getOperand(ArgI);
9655 
9656     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9657 
9658     TargetLowering::ArgListEntry Entry;
9659     Entry.Node = getValue(V);
9660     Entry.Ty = V->getType();
9661     Entry.setAttributes(Call, ArgI);
9662     Args.push_back(Entry);
9663   }
9664 
9665   CLI.setDebugLoc(getCurSDLoc())
9666       .setChain(getRoot())
9667       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9668       .setDiscardResult(Call->use_empty())
9669       .setIsPatchPoint(IsPatchPoint)
9670       .setIsPreallocated(
9671           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9672 }
9673 
9674 /// Add a stack map intrinsic call's live variable operands to a stackmap
9675 /// or patchpoint target node's operand list.
9676 ///
9677 /// Constants are converted to TargetConstants purely as an optimization to
9678 /// avoid constant materialization and register allocation.
9679 ///
9680 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9681 /// generate addess computation nodes, and so FinalizeISel can convert the
9682 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9683 /// address materialization and register allocation, but may also be required
9684 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9685 /// alloca in the entry block, then the runtime may assume that the alloca's
9686 /// StackMap location can be read immediately after compilation and that the
9687 /// location is valid at any point during execution (this is similar to the
9688 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9689 /// only available in a register, then the runtime would need to trap when
9690 /// execution reaches the StackMap in order to read the alloca's location.
9691 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9692                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9693                                 SelectionDAGBuilder &Builder) {
9694   SelectionDAG &DAG = Builder.DAG;
9695   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9696     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9697 
9698     // Things on the stack are pointer-typed, meaning that they are already
9699     // legal and can be emitted directly to target nodes.
9700     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9701       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9702     } else {
9703       // Otherwise emit a target independent node to be legalised.
9704       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9705     }
9706   }
9707 }
9708 
9709 /// Lower llvm.experimental.stackmap.
9710 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9711   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9712   //                                  [live variables...])
9713 
9714   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9715 
9716   SDValue Chain, InGlue, Callee;
9717   SmallVector<SDValue, 32> Ops;
9718 
9719   SDLoc DL = getCurSDLoc();
9720   Callee = getValue(CI.getCalledOperand());
9721 
9722   // The stackmap intrinsic only records the live variables (the arguments
9723   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9724   // intrinsic, this won't be lowered to a function call. This means we don't
9725   // have to worry about calling conventions and target specific lowering code.
9726   // Instead we perform the call lowering right here.
9727   //
9728   // chain, flag = CALLSEQ_START(chain, 0, 0)
9729   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9730   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9731   //
9732   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9733   InGlue = Chain.getValue(1);
9734 
9735   // Add the STACKMAP operands, starting with DAG house-keeping.
9736   Ops.push_back(Chain);
9737   Ops.push_back(InGlue);
9738 
9739   // Add the <id>, <numShadowBytes> operands.
9740   //
9741   // These do not require legalisation, and can be emitted directly to target
9742   // constant nodes.
9743   SDValue ID = getValue(CI.getArgOperand(0));
9744   assert(ID.getValueType() == MVT::i64);
9745   SDValue IDConst = DAG.getTargetConstant(
9746       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9747   Ops.push_back(IDConst);
9748 
9749   SDValue Shad = getValue(CI.getArgOperand(1));
9750   assert(Shad.getValueType() == MVT::i32);
9751   SDValue ShadConst = DAG.getTargetConstant(
9752       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9753   Ops.push_back(ShadConst);
9754 
9755   // Add the live variables.
9756   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9757 
9758   // Create the STACKMAP node.
9759   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9760   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9761   InGlue = Chain.getValue(1);
9762 
9763   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
9764 
9765   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9766 
9767   // Set the root to the target-lowered call chain.
9768   DAG.setRoot(Chain);
9769 
9770   // Inform the Frame Information that we have a stackmap in this function.
9771   FuncInfo.MF->getFrameInfo().setHasStackMap();
9772 }
9773 
9774 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9775 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9776                                           const BasicBlock *EHPadBB) {
9777   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9778   //                                                 i32 <numBytes>,
9779   //                                                 i8* <target>,
9780   //                                                 i32 <numArgs>,
9781   //                                                 [Args...],
9782   //                                                 [live variables...])
9783 
9784   CallingConv::ID CC = CB.getCallingConv();
9785   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9786   bool HasDef = !CB.getType()->isVoidTy();
9787   SDLoc dl = getCurSDLoc();
9788   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9789 
9790   // Handle immediate and symbolic callees.
9791   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9792     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9793                                    /*isTarget=*/true);
9794   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9795     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9796                                          SDLoc(SymbolicCallee),
9797                                          SymbolicCallee->getValueType(0));
9798 
9799   // Get the real number of arguments participating in the call <numArgs>
9800   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9801   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9802 
9803   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9804   // Intrinsics include all meta-operands up to but not including CC.
9805   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9806   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9807          "Not enough arguments provided to the patchpoint intrinsic");
9808 
9809   // For AnyRegCC the arguments are lowered later on manually.
9810   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9811   Type *ReturnTy =
9812       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9813 
9814   TargetLowering::CallLoweringInfo CLI(DAG);
9815   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9816                            ReturnTy, true);
9817   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9818 
9819   SDNode *CallEnd = Result.second.getNode();
9820   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9821     CallEnd = CallEnd->getOperand(0).getNode();
9822 
9823   /// Get a call instruction from the call sequence chain.
9824   /// Tail calls are not allowed.
9825   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9826          "Expected a callseq node.");
9827   SDNode *Call = CallEnd->getOperand(0).getNode();
9828   bool HasGlue = Call->getGluedNode();
9829 
9830   // Replace the target specific call node with the patchable intrinsic.
9831   SmallVector<SDValue, 8> Ops;
9832 
9833   // Push the chain.
9834   Ops.push_back(*(Call->op_begin()));
9835 
9836   // Optionally, push the glue (if any).
9837   if (HasGlue)
9838     Ops.push_back(*(Call->op_end() - 1));
9839 
9840   // Push the register mask info.
9841   if (HasGlue)
9842     Ops.push_back(*(Call->op_end() - 2));
9843   else
9844     Ops.push_back(*(Call->op_end() - 1));
9845 
9846   // Add the <id> and <numBytes> constants.
9847   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9848   Ops.push_back(DAG.getTargetConstant(
9849                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9850   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9851   Ops.push_back(DAG.getTargetConstant(
9852                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9853                   MVT::i32));
9854 
9855   // Add the callee.
9856   Ops.push_back(Callee);
9857 
9858   // Adjust <numArgs> to account for any arguments that have been passed on the
9859   // stack instead.
9860   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9861   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9862   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9863   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9864 
9865   // Add the calling convention
9866   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9867 
9868   // Add the arguments we omitted previously. The register allocator should
9869   // place these in any free register.
9870   if (IsAnyRegCC)
9871     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9872       Ops.push_back(getValue(CB.getArgOperand(i)));
9873 
9874   // Push the arguments from the call instruction.
9875   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9876   Ops.append(Call->op_begin() + 2, e);
9877 
9878   // Push live variables for the stack map.
9879   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9880 
9881   SDVTList NodeTys;
9882   if (IsAnyRegCC && HasDef) {
9883     // Create the return types based on the intrinsic definition
9884     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9885     SmallVector<EVT, 3> ValueVTs;
9886     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9887     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9888 
9889     // There is always a chain and a glue type at the end
9890     ValueVTs.push_back(MVT::Other);
9891     ValueVTs.push_back(MVT::Glue);
9892     NodeTys = DAG.getVTList(ValueVTs);
9893   } else
9894     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9895 
9896   // Replace the target specific call node with a PATCHPOINT node.
9897   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
9898 
9899   // Update the NodeMap.
9900   if (HasDef) {
9901     if (IsAnyRegCC)
9902       setValue(&CB, SDValue(PPV.getNode(), 0));
9903     else
9904       setValue(&CB, Result.first);
9905   }
9906 
9907   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9908   // call sequence. Furthermore the location of the chain and glue can change
9909   // when the AnyReg calling convention is used and the intrinsic returns a
9910   // value.
9911   if (IsAnyRegCC && HasDef) {
9912     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9913     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
9914     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9915   } else
9916     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
9917   DAG.DeleteNode(Call);
9918 
9919   // Inform the Frame Information that we have a patchpoint in this function.
9920   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9921 }
9922 
9923 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9924                                             unsigned Intrinsic) {
9925   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9926   SDValue Op1 = getValue(I.getArgOperand(0));
9927   SDValue Op2;
9928   if (I.arg_size() > 1)
9929     Op2 = getValue(I.getArgOperand(1));
9930   SDLoc dl = getCurSDLoc();
9931   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9932   SDValue Res;
9933   SDNodeFlags SDFlags;
9934   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9935     SDFlags.copyFMF(*FPMO);
9936 
9937   switch (Intrinsic) {
9938   case Intrinsic::vector_reduce_fadd:
9939     if (SDFlags.hasAllowReassociation())
9940       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9941                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9942                         SDFlags);
9943     else
9944       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9945     break;
9946   case Intrinsic::vector_reduce_fmul:
9947     if (SDFlags.hasAllowReassociation())
9948       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9949                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9950                         SDFlags);
9951     else
9952       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9953     break;
9954   case Intrinsic::vector_reduce_add:
9955     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9956     break;
9957   case Intrinsic::vector_reduce_mul:
9958     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9959     break;
9960   case Intrinsic::vector_reduce_and:
9961     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9962     break;
9963   case Intrinsic::vector_reduce_or:
9964     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9965     break;
9966   case Intrinsic::vector_reduce_xor:
9967     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9968     break;
9969   case Intrinsic::vector_reduce_smax:
9970     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9971     break;
9972   case Intrinsic::vector_reduce_smin:
9973     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9974     break;
9975   case Intrinsic::vector_reduce_umax:
9976     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9977     break;
9978   case Intrinsic::vector_reduce_umin:
9979     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9980     break;
9981   case Intrinsic::vector_reduce_fmax:
9982     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9983     break;
9984   case Intrinsic::vector_reduce_fmin:
9985     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9986     break;
9987   default:
9988     llvm_unreachable("Unhandled vector reduce intrinsic");
9989   }
9990   setValue(&I, Res);
9991 }
9992 
9993 /// Returns an AttributeList representing the attributes applied to the return
9994 /// value of the given call.
9995 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9996   SmallVector<Attribute::AttrKind, 2> Attrs;
9997   if (CLI.RetSExt)
9998     Attrs.push_back(Attribute::SExt);
9999   if (CLI.RetZExt)
10000     Attrs.push_back(Attribute::ZExt);
10001   if (CLI.IsInReg)
10002     Attrs.push_back(Attribute::InReg);
10003 
10004   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10005                             Attrs);
10006 }
10007 
10008 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10009 /// implementation, which just calls LowerCall.
10010 /// FIXME: When all targets are
10011 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10012 std::pair<SDValue, SDValue>
10013 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10014   // Handle the incoming return values from the call.
10015   CLI.Ins.clear();
10016   Type *OrigRetTy = CLI.RetTy;
10017   SmallVector<EVT, 4> RetTys;
10018   SmallVector<uint64_t, 4> Offsets;
10019   auto &DL = CLI.DAG.getDataLayout();
10020   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0);
10021 
10022   if (CLI.IsPostTypeLegalization) {
10023     // If we are lowering a libcall after legalization, split the return type.
10024     SmallVector<EVT, 4> OldRetTys;
10025     SmallVector<uint64_t, 4> OldOffsets;
10026     RetTys.swap(OldRetTys);
10027     Offsets.swap(OldOffsets);
10028 
10029     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10030       EVT RetVT = OldRetTys[i];
10031       uint64_t Offset = OldOffsets[i];
10032       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10033       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10034       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10035       RetTys.append(NumRegs, RegisterVT);
10036       for (unsigned j = 0; j != NumRegs; ++j)
10037         Offsets.push_back(Offset + j * RegisterVTByteSZ);
10038     }
10039   }
10040 
10041   SmallVector<ISD::OutputArg, 4> Outs;
10042   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10043 
10044   bool CanLowerReturn =
10045       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10046                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10047 
10048   SDValue DemoteStackSlot;
10049   int DemoteStackIdx = -100;
10050   if (!CanLowerReturn) {
10051     // FIXME: equivalent assert?
10052     // assert(!CS.hasInAllocaArgument() &&
10053     //        "sret demotion is incompatible with inalloca");
10054     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10055     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10056     MachineFunction &MF = CLI.DAG.getMachineFunction();
10057     DemoteStackIdx =
10058         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10059     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10060                                               DL.getAllocaAddrSpace());
10061 
10062     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10063     ArgListEntry Entry;
10064     Entry.Node = DemoteStackSlot;
10065     Entry.Ty = StackSlotPtrType;
10066     Entry.IsSExt = false;
10067     Entry.IsZExt = false;
10068     Entry.IsInReg = false;
10069     Entry.IsSRet = true;
10070     Entry.IsNest = false;
10071     Entry.IsByVal = false;
10072     Entry.IsByRef = false;
10073     Entry.IsReturned = false;
10074     Entry.IsSwiftSelf = false;
10075     Entry.IsSwiftAsync = false;
10076     Entry.IsSwiftError = false;
10077     Entry.IsCFGuardTarget = false;
10078     Entry.Alignment = Alignment;
10079     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10080     CLI.NumFixedArgs += 1;
10081     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10082     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10083 
10084     // sret demotion isn't compatible with tail-calls, since the sret argument
10085     // points into the callers stack frame.
10086     CLI.IsTailCall = false;
10087   } else {
10088     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10089         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10090     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10091       ISD::ArgFlagsTy Flags;
10092       if (NeedsRegBlock) {
10093         Flags.setInConsecutiveRegs();
10094         if (I == RetTys.size() - 1)
10095           Flags.setInConsecutiveRegsLast();
10096       }
10097       EVT VT = RetTys[I];
10098       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10099                                                      CLI.CallConv, VT);
10100       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10101                                                        CLI.CallConv, VT);
10102       for (unsigned i = 0; i != NumRegs; ++i) {
10103         ISD::InputArg MyFlags;
10104         MyFlags.Flags = Flags;
10105         MyFlags.VT = RegisterVT;
10106         MyFlags.ArgVT = VT;
10107         MyFlags.Used = CLI.IsReturnValueUsed;
10108         if (CLI.RetTy->isPointerTy()) {
10109           MyFlags.Flags.setPointer();
10110           MyFlags.Flags.setPointerAddrSpace(
10111               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10112         }
10113         if (CLI.RetSExt)
10114           MyFlags.Flags.setSExt();
10115         if (CLI.RetZExt)
10116           MyFlags.Flags.setZExt();
10117         if (CLI.IsInReg)
10118           MyFlags.Flags.setInReg();
10119         CLI.Ins.push_back(MyFlags);
10120       }
10121     }
10122   }
10123 
10124   // We push in swifterror return as the last element of CLI.Ins.
10125   ArgListTy &Args = CLI.getArgs();
10126   if (supportSwiftError()) {
10127     for (const ArgListEntry &Arg : Args) {
10128       if (Arg.IsSwiftError) {
10129         ISD::InputArg MyFlags;
10130         MyFlags.VT = getPointerTy(DL);
10131         MyFlags.ArgVT = EVT(getPointerTy(DL));
10132         MyFlags.Flags.setSwiftError();
10133         CLI.Ins.push_back(MyFlags);
10134       }
10135     }
10136   }
10137 
10138   // Handle all of the outgoing arguments.
10139   CLI.Outs.clear();
10140   CLI.OutVals.clear();
10141   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10142     SmallVector<EVT, 4> ValueVTs;
10143     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10144     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10145     Type *FinalType = Args[i].Ty;
10146     if (Args[i].IsByVal)
10147       FinalType = Args[i].IndirectType;
10148     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10149         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10150     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10151          ++Value) {
10152       EVT VT = ValueVTs[Value];
10153       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10154       SDValue Op = SDValue(Args[i].Node.getNode(),
10155                            Args[i].Node.getResNo() + Value);
10156       ISD::ArgFlagsTy Flags;
10157 
10158       // Certain targets (such as MIPS), may have a different ABI alignment
10159       // for a type depending on the context. Give the target a chance to
10160       // specify the alignment it wants.
10161       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10162       Flags.setOrigAlign(OriginalAlignment);
10163 
10164       if (Args[i].Ty->isPointerTy()) {
10165         Flags.setPointer();
10166         Flags.setPointerAddrSpace(
10167             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10168       }
10169       if (Args[i].IsZExt)
10170         Flags.setZExt();
10171       if (Args[i].IsSExt)
10172         Flags.setSExt();
10173       if (Args[i].IsInReg) {
10174         // If we are using vectorcall calling convention, a structure that is
10175         // passed InReg - is surely an HVA
10176         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10177             isa<StructType>(FinalType)) {
10178           // The first value of a structure is marked
10179           if (0 == Value)
10180             Flags.setHvaStart();
10181           Flags.setHva();
10182         }
10183         // Set InReg Flag
10184         Flags.setInReg();
10185       }
10186       if (Args[i].IsSRet)
10187         Flags.setSRet();
10188       if (Args[i].IsSwiftSelf)
10189         Flags.setSwiftSelf();
10190       if (Args[i].IsSwiftAsync)
10191         Flags.setSwiftAsync();
10192       if (Args[i].IsSwiftError)
10193         Flags.setSwiftError();
10194       if (Args[i].IsCFGuardTarget)
10195         Flags.setCFGuardTarget();
10196       if (Args[i].IsByVal)
10197         Flags.setByVal();
10198       if (Args[i].IsByRef)
10199         Flags.setByRef();
10200       if (Args[i].IsPreallocated) {
10201         Flags.setPreallocated();
10202         // Set the byval flag for CCAssignFn callbacks that don't know about
10203         // preallocated.  This way we can know how many bytes we should've
10204         // allocated and how many bytes a callee cleanup function will pop.  If
10205         // we port preallocated to more targets, we'll have to add custom
10206         // preallocated handling in the various CC lowering callbacks.
10207         Flags.setByVal();
10208       }
10209       if (Args[i].IsInAlloca) {
10210         Flags.setInAlloca();
10211         // Set the byval flag for CCAssignFn callbacks that don't know about
10212         // inalloca.  This way we can know how many bytes we should've allocated
10213         // and how many bytes a callee cleanup function will pop.  If we port
10214         // inalloca to more targets, we'll have to add custom inalloca handling
10215         // in the various CC lowering callbacks.
10216         Flags.setByVal();
10217       }
10218       Align MemAlign;
10219       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10220         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10221         Flags.setByValSize(FrameSize);
10222 
10223         // info is not there but there are cases it cannot get right.
10224         if (auto MA = Args[i].Alignment)
10225           MemAlign = *MA;
10226         else
10227           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10228       } else if (auto MA = Args[i].Alignment) {
10229         MemAlign = *MA;
10230       } else {
10231         MemAlign = OriginalAlignment;
10232       }
10233       Flags.setMemAlign(MemAlign);
10234       if (Args[i].IsNest)
10235         Flags.setNest();
10236       if (NeedsRegBlock)
10237         Flags.setInConsecutiveRegs();
10238 
10239       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10240                                                  CLI.CallConv, VT);
10241       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10242                                                         CLI.CallConv, VT);
10243       SmallVector<SDValue, 4> Parts(NumParts);
10244       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10245 
10246       if (Args[i].IsSExt)
10247         ExtendKind = ISD::SIGN_EXTEND;
10248       else if (Args[i].IsZExt)
10249         ExtendKind = ISD::ZERO_EXTEND;
10250 
10251       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10252       // for now.
10253       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10254           CanLowerReturn) {
10255         assert((CLI.RetTy == Args[i].Ty ||
10256                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10257                  CLI.RetTy->getPointerAddressSpace() ==
10258                      Args[i].Ty->getPointerAddressSpace())) &&
10259                RetTys.size() == NumValues && "unexpected use of 'returned'");
10260         // Before passing 'returned' to the target lowering code, ensure that
10261         // either the register MVT and the actual EVT are the same size or that
10262         // the return value and argument are extended in the same way; in these
10263         // cases it's safe to pass the argument register value unchanged as the
10264         // return register value (although it's at the target's option whether
10265         // to do so)
10266         // TODO: allow code generation to take advantage of partially preserved
10267         // registers rather than clobbering the entire register when the
10268         // parameter extension method is not compatible with the return
10269         // extension method
10270         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10271             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10272              CLI.RetZExt == Args[i].IsZExt))
10273           Flags.setReturned();
10274       }
10275 
10276       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10277                      CLI.CallConv, ExtendKind);
10278 
10279       for (unsigned j = 0; j != NumParts; ++j) {
10280         // if it isn't first piece, alignment must be 1
10281         // For scalable vectors the scalable part is currently handled
10282         // by individual targets, so we just use the known minimum size here.
10283         ISD::OutputArg MyFlags(
10284             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10285             i < CLI.NumFixedArgs, i,
10286             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10287         if (NumParts > 1 && j == 0)
10288           MyFlags.Flags.setSplit();
10289         else if (j != 0) {
10290           MyFlags.Flags.setOrigAlign(Align(1));
10291           if (j == NumParts - 1)
10292             MyFlags.Flags.setSplitEnd();
10293         }
10294 
10295         CLI.Outs.push_back(MyFlags);
10296         CLI.OutVals.push_back(Parts[j]);
10297       }
10298 
10299       if (NeedsRegBlock && Value == NumValues - 1)
10300         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10301     }
10302   }
10303 
10304   SmallVector<SDValue, 4> InVals;
10305   CLI.Chain = LowerCall(CLI, InVals);
10306 
10307   // Update CLI.InVals to use outside of this function.
10308   CLI.InVals = InVals;
10309 
10310   // Verify that the target's LowerCall behaved as expected.
10311   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10312          "LowerCall didn't return a valid chain!");
10313   assert((!CLI.IsTailCall || InVals.empty()) &&
10314          "LowerCall emitted a return value for a tail call!");
10315   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10316          "LowerCall didn't emit the correct number of values!");
10317 
10318   // For a tail call, the return value is merely live-out and there aren't
10319   // any nodes in the DAG representing it. Return a special value to
10320   // indicate that a tail call has been emitted and no more Instructions
10321   // should be processed in the current block.
10322   if (CLI.IsTailCall) {
10323     CLI.DAG.setRoot(CLI.Chain);
10324     return std::make_pair(SDValue(), SDValue());
10325   }
10326 
10327 #ifndef NDEBUG
10328   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10329     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10330     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10331            "LowerCall emitted a value with the wrong type!");
10332   }
10333 #endif
10334 
10335   SmallVector<SDValue, 4> ReturnValues;
10336   if (!CanLowerReturn) {
10337     // The instruction result is the result of loading from the
10338     // hidden sret parameter.
10339     SmallVector<EVT, 1> PVTs;
10340     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
10341 
10342     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10343     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10344     EVT PtrVT = PVTs[0];
10345 
10346     unsigned NumValues = RetTys.size();
10347     ReturnValues.resize(NumValues);
10348     SmallVector<SDValue, 4> Chains(NumValues);
10349 
10350     // An aggregate return value cannot wrap around the address space, so
10351     // offsets to its parts don't wrap either.
10352     SDNodeFlags Flags;
10353     Flags.setNoUnsignedWrap(true);
10354 
10355     MachineFunction &MF = CLI.DAG.getMachineFunction();
10356     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10357     for (unsigned i = 0; i < NumValues; ++i) {
10358       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10359                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10360                                                         PtrVT), Flags);
10361       SDValue L = CLI.DAG.getLoad(
10362           RetTys[i], CLI.DL, CLI.Chain, Add,
10363           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10364                                             DemoteStackIdx, Offsets[i]),
10365           HiddenSRetAlign);
10366       ReturnValues[i] = L;
10367       Chains[i] = L.getValue(1);
10368     }
10369 
10370     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10371   } else {
10372     // Collect the legal value parts into potentially illegal values
10373     // that correspond to the original function's return values.
10374     std::optional<ISD::NodeType> AssertOp;
10375     if (CLI.RetSExt)
10376       AssertOp = ISD::AssertSext;
10377     else if (CLI.RetZExt)
10378       AssertOp = ISD::AssertZext;
10379     unsigned CurReg = 0;
10380     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10381       EVT VT = RetTys[I];
10382       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10383                                                      CLI.CallConv, VT);
10384       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10385                                                        CLI.CallConv, VT);
10386 
10387       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10388                                               NumRegs, RegisterVT, VT, nullptr,
10389                                               CLI.CallConv, AssertOp));
10390       CurReg += NumRegs;
10391     }
10392 
10393     // For a function returning void, there is no return value. We can't create
10394     // such a node, so we just return a null return value in that case. In
10395     // that case, nothing will actually look at the value.
10396     if (ReturnValues.empty())
10397       return std::make_pair(SDValue(), CLI.Chain);
10398   }
10399 
10400   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10401                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10402   return std::make_pair(Res, CLI.Chain);
10403 }
10404 
10405 /// Places new result values for the node in Results (their number
10406 /// and types must exactly match those of the original return values of
10407 /// the node), or leaves Results empty, which indicates that the node is not
10408 /// to be custom lowered after all.
10409 void TargetLowering::LowerOperationWrapper(SDNode *N,
10410                                            SmallVectorImpl<SDValue> &Results,
10411                                            SelectionDAG &DAG) const {
10412   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10413 
10414   if (!Res.getNode())
10415     return;
10416 
10417   // If the original node has one result, take the return value from
10418   // LowerOperation as is. It might not be result number 0.
10419   if (N->getNumValues() == 1) {
10420     Results.push_back(Res);
10421     return;
10422   }
10423 
10424   // If the original node has multiple results, then the return node should
10425   // have the same number of results.
10426   assert((N->getNumValues() == Res->getNumValues()) &&
10427       "Lowering returned the wrong number of results!");
10428 
10429   // Places new result values base on N result number.
10430   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10431     Results.push_back(Res.getValue(I));
10432 }
10433 
10434 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10435   llvm_unreachable("LowerOperation not implemented for this target!");
10436 }
10437 
10438 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10439                                                      unsigned Reg,
10440                                                      ISD::NodeType ExtendType) {
10441   SDValue Op = getNonRegisterValue(V);
10442   assert((Op.getOpcode() != ISD::CopyFromReg ||
10443           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10444          "Copy from a reg to the same reg!");
10445   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10446 
10447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10448   // If this is an InlineAsm we have to match the registers required, not the
10449   // notional registers required by the type.
10450 
10451   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10452                    std::nullopt); // This is not an ABI copy.
10453   SDValue Chain = DAG.getEntryNode();
10454 
10455   if (ExtendType == ISD::ANY_EXTEND) {
10456     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10457     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10458       ExtendType = PreferredExtendIt->second;
10459   }
10460   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10461   PendingExports.push_back(Chain);
10462 }
10463 
10464 #include "llvm/CodeGen/SelectionDAGISel.h"
10465 
10466 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10467 /// entry block, return true.  This includes arguments used by switches, since
10468 /// the switch may expand into multiple basic blocks.
10469 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10470   // With FastISel active, we may be splitting blocks, so force creation
10471   // of virtual registers for all non-dead arguments.
10472   if (FastISel)
10473     return A->use_empty();
10474 
10475   const BasicBlock &Entry = A->getParent()->front();
10476   for (const User *U : A->users())
10477     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10478       return false;  // Use not in entry block.
10479 
10480   return true;
10481 }
10482 
10483 using ArgCopyElisionMapTy =
10484     DenseMap<const Argument *,
10485              std::pair<const AllocaInst *, const StoreInst *>>;
10486 
10487 /// Scan the entry block of the function in FuncInfo for arguments that look
10488 /// like copies into a local alloca. Record any copied arguments in
10489 /// ArgCopyElisionCandidates.
10490 static void
10491 findArgumentCopyElisionCandidates(const DataLayout &DL,
10492                                   FunctionLoweringInfo *FuncInfo,
10493                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10494   // Record the state of every static alloca used in the entry block. Argument
10495   // allocas are all used in the entry block, so we need approximately as many
10496   // entries as we have arguments.
10497   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10498   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10499   unsigned NumArgs = FuncInfo->Fn->arg_size();
10500   StaticAllocas.reserve(NumArgs * 2);
10501 
10502   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10503     if (!V)
10504       return nullptr;
10505     V = V->stripPointerCasts();
10506     const auto *AI = dyn_cast<AllocaInst>(V);
10507     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10508       return nullptr;
10509     auto Iter = StaticAllocas.insert({AI, Unknown});
10510     return &Iter.first->second;
10511   };
10512 
10513   // Look for stores of arguments to static allocas. Look through bitcasts and
10514   // GEPs to handle type coercions, as long as the alloca is fully initialized
10515   // by the store. Any non-store use of an alloca escapes it and any subsequent
10516   // unanalyzed store might write it.
10517   // FIXME: Handle structs initialized with multiple stores.
10518   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10519     // Look for stores, and handle non-store uses conservatively.
10520     const auto *SI = dyn_cast<StoreInst>(&I);
10521     if (!SI) {
10522       // We will look through cast uses, so ignore them completely.
10523       if (I.isCast())
10524         continue;
10525       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10526       // to allocas.
10527       if (I.isDebugOrPseudoInst())
10528         continue;
10529       // This is an unknown instruction. Assume it escapes or writes to all
10530       // static alloca operands.
10531       for (const Use &U : I.operands()) {
10532         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10533           *Info = StaticAllocaInfo::Clobbered;
10534       }
10535       continue;
10536     }
10537 
10538     // If the stored value is a static alloca, mark it as escaped.
10539     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10540       *Info = StaticAllocaInfo::Clobbered;
10541 
10542     // Check if the destination is a static alloca.
10543     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10544     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10545     if (!Info)
10546       continue;
10547     const AllocaInst *AI = cast<AllocaInst>(Dst);
10548 
10549     // Skip allocas that have been initialized or clobbered.
10550     if (*Info != StaticAllocaInfo::Unknown)
10551       continue;
10552 
10553     // Check if the stored value is an argument, and that this store fully
10554     // initializes the alloca.
10555     // If the argument type has padding bits we can't directly forward a pointer
10556     // as the upper bits may contain garbage.
10557     // Don't elide copies from the same argument twice.
10558     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10559     const auto *Arg = dyn_cast<Argument>(Val);
10560     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10561         Arg->getType()->isEmptyTy() ||
10562         DL.getTypeStoreSize(Arg->getType()) !=
10563             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10564         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10565         ArgCopyElisionCandidates.count(Arg)) {
10566       *Info = StaticAllocaInfo::Clobbered;
10567       continue;
10568     }
10569 
10570     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10571                       << '\n');
10572 
10573     // Mark this alloca and store for argument copy elision.
10574     *Info = StaticAllocaInfo::Elidable;
10575     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10576 
10577     // Stop scanning if we've seen all arguments. This will happen early in -O0
10578     // builds, which is useful, because -O0 builds have large entry blocks and
10579     // many allocas.
10580     if (ArgCopyElisionCandidates.size() == NumArgs)
10581       break;
10582   }
10583 }
10584 
10585 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10586 /// ArgVal is a load from a suitable fixed stack object.
10587 static void tryToElideArgumentCopy(
10588     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10589     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10590     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10591     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10592     SDValue ArgVal, bool &ArgHasUses) {
10593   // Check if this is a load from a fixed stack object.
10594   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10595   if (!LNode)
10596     return;
10597   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10598   if (!FINode)
10599     return;
10600 
10601   // Check that the fixed stack object is the right size and alignment.
10602   // Look at the alignment that the user wrote on the alloca instead of looking
10603   // at the stack object.
10604   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10605   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10606   const AllocaInst *AI = ArgCopyIter->second.first;
10607   int FixedIndex = FINode->getIndex();
10608   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10609   int OldIndex = AllocaIndex;
10610   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10611   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10612     LLVM_DEBUG(
10613         dbgs() << "  argument copy elision failed due to bad fixed stack "
10614                   "object size\n");
10615     return;
10616   }
10617   Align RequiredAlignment = AI->getAlign();
10618   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10619     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10620                          "greater than stack argument alignment ("
10621                       << DebugStr(RequiredAlignment) << " vs "
10622                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10623     return;
10624   }
10625 
10626   // Perform the elision. Delete the old stack object and replace its only use
10627   // in the variable info map. Mark the stack object as mutable.
10628   LLVM_DEBUG({
10629     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10630            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10631            << '\n';
10632   });
10633   MFI.RemoveStackObject(OldIndex);
10634   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10635   AllocaIndex = FixedIndex;
10636   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10637   Chains.push_back(ArgVal.getValue(1));
10638 
10639   // Avoid emitting code for the store implementing the copy.
10640   const StoreInst *SI = ArgCopyIter->second.second;
10641   ElidedArgCopyInstrs.insert(SI);
10642 
10643   // Check for uses of the argument again so that we can avoid exporting ArgVal
10644   // if it is't used by anything other than the store.
10645   for (const Value *U : Arg.users()) {
10646     if (U != SI) {
10647       ArgHasUses = true;
10648       break;
10649     }
10650   }
10651 }
10652 
10653 void SelectionDAGISel::LowerArguments(const Function &F) {
10654   SelectionDAG &DAG = SDB->DAG;
10655   SDLoc dl = SDB->getCurSDLoc();
10656   const DataLayout &DL = DAG.getDataLayout();
10657   SmallVector<ISD::InputArg, 16> Ins;
10658 
10659   // In Naked functions we aren't going to save any registers.
10660   if (F.hasFnAttribute(Attribute::Naked))
10661     return;
10662 
10663   if (!FuncInfo->CanLowerReturn) {
10664     // Put in an sret pointer parameter before all the other parameters.
10665     SmallVector<EVT, 1> ValueVTs;
10666     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10667                     F.getReturnType()->getPointerTo(
10668                         DAG.getDataLayout().getAllocaAddrSpace()),
10669                     ValueVTs);
10670 
10671     // NOTE: Assuming that a pointer will never break down to more than one VT
10672     // or one register.
10673     ISD::ArgFlagsTy Flags;
10674     Flags.setSRet();
10675     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10676     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10677                          ISD::InputArg::NoArgIndex, 0);
10678     Ins.push_back(RetArg);
10679   }
10680 
10681   // Look for stores of arguments to static allocas. Mark such arguments with a
10682   // flag to ask the target to give us the memory location of that argument if
10683   // available.
10684   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10685   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10686                                     ArgCopyElisionCandidates);
10687 
10688   // Set up the incoming argument description vector.
10689   for (const Argument &Arg : F.args()) {
10690     unsigned ArgNo = Arg.getArgNo();
10691     SmallVector<EVT, 4> ValueVTs;
10692     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10693     bool isArgValueUsed = !Arg.use_empty();
10694     unsigned PartBase = 0;
10695     Type *FinalType = Arg.getType();
10696     if (Arg.hasAttribute(Attribute::ByVal))
10697       FinalType = Arg.getParamByValType();
10698     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10699         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10700     for (unsigned Value = 0, NumValues = ValueVTs.size();
10701          Value != NumValues; ++Value) {
10702       EVT VT = ValueVTs[Value];
10703       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10704       ISD::ArgFlagsTy Flags;
10705 
10706 
10707       if (Arg.getType()->isPointerTy()) {
10708         Flags.setPointer();
10709         Flags.setPointerAddrSpace(
10710             cast<PointerType>(Arg.getType())->getAddressSpace());
10711       }
10712       if (Arg.hasAttribute(Attribute::ZExt))
10713         Flags.setZExt();
10714       if (Arg.hasAttribute(Attribute::SExt))
10715         Flags.setSExt();
10716       if (Arg.hasAttribute(Attribute::InReg)) {
10717         // If we are using vectorcall calling convention, a structure that is
10718         // passed InReg - is surely an HVA
10719         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10720             isa<StructType>(Arg.getType())) {
10721           // The first value of a structure is marked
10722           if (0 == Value)
10723             Flags.setHvaStart();
10724           Flags.setHva();
10725         }
10726         // Set InReg Flag
10727         Flags.setInReg();
10728       }
10729       if (Arg.hasAttribute(Attribute::StructRet))
10730         Flags.setSRet();
10731       if (Arg.hasAttribute(Attribute::SwiftSelf))
10732         Flags.setSwiftSelf();
10733       if (Arg.hasAttribute(Attribute::SwiftAsync))
10734         Flags.setSwiftAsync();
10735       if (Arg.hasAttribute(Attribute::SwiftError))
10736         Flags.setSwiftError();
10737       if (Arg.hasAttribute(Attribute::ByVal))
10738         Flags.setByVal();
10739       if (Arg.hasAttribute(Attribute::ByRef))
10740         Flags.setByRef();
10741       if (Arg.hasAttribute(Attribute::InAlloca)) {
10742         Flags.setInAlloca();
10743         // Set the byval flag for CCAssignFn callbacks that don't know about
10744         // inalloca.  This way we can know how many bytes we should've allocated
10745         // and how many bytes a callee cleanup function will pop.  If we port
10746         // inalloca to more targets, we'll have to add custom inalloca handling
10747         // in the various CC lowering callbacks.
10748         Flags.setByVal();
10749       }
10750       if (Arg.hasAttribute(Attribute::Preallocated)) {
10751         Flags.setPreallocated();
10752         // Set the byval flag for CCAssignFn callbacks that don't know about
10753         // preallocated.  This way we can know how many bytes we should've
10754         // allocated and how many bytes a callee cleanup function will pop.  If
10755         // we port preallocated to more targets, we'll have to add custom
10756         // preallocated handling in the various CC lowering callbacks.
10757         Flags.setByVal();
10758       }
10759 
10760       // Certain targets (such as MIPS), may have a different ABI alignment
10761       // for a type depending on the context. Give the target a chance to
10762       // specify the alignment it wants.
10763       const Align OriginalAlignment(
10764           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10765       Flags.setOrigAlign(OriginalAlignment);
10766 
10767       Align MemAlign;
10768       Type *ArgMemTy = nullptr;
10769       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10770           Flags.isByRef()) {
10771         if (!ArgMemTy)
10772           ArgMemTy = Arg.getPointeeInMemoryValueType();
10773 
10774         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10775 
10776         // For in-memory arguments, size and alignment should be passed from FE.
10777         // BE will guess if this info is not there but there are cases it cannot
10778         // get right.
10779         if (auto ParamAlign = Arg.getParamStackAlign())
10780           MemAlign = *ParamAlign;
10781         else if ((ParamAlign = Arg.getParamAlign()))
10782           MemAlign = *ParamAlign;
10783         else
10784           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10785         if (Flags.isByRef())
10786           Flags.setByRefSize(MemSize);
10787         else
10788           Flags.setByValSize(MemSize);
10789       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10790         MemAlign = *ParamAlign;
10791       } else {
10792         MemAlign = OriginalAlignment;
10793       }
10794       Flags.setMemAlign(MemAlign);
10795 
10796       if (Arg.hasAttribute(Attribute::Nest))
10797         Flags.setNest();
10798       if (NeedsRegBlock)
10799         Flags.setInConsecutiveRegs();
10800       if (ArgCopyElisionCandidates.count(&Arg))
10801         Flags.setCopyElisionCandidate();
10802       if (Arg.hasAttribute(Attribute::Returned))
10803         Flags.setReturned();
10804 
10805       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10806           *CurDAG->getContext(), F.getCallingConv(), VT);
10807       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10808           *CurDAG->getContext(), F.getCallingConv(), VT);
10809       for (unsigned i = 0; i != NumRegs; ++i) {
10810         // For scalable vectors, use the minimum size; individual targets
10811         // are responsible for handling scalable vector arguments and
10812         // return values.
10813         ISD::InputArg MyFlags(
10814             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
10815             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
10816         if (NumRegs > 1 && i == 0)
10817           MyFlags.Flags.setSplit();
10818         // if it isn't first piece, alignment must be 1
10819         else if (i > 0) {
10820           MyFlags.Flags.setOrigAlign(Align(1));
10821           if (i == NumRegs - 1)
10822             MyFlags.Flags.setSplitEnd();
10823         }
10824         Ins.push_back(MyFlags);
10825       }
10826       if (NeedsRegBlock && Value == NumValues - 1)
10827         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10828       PartBase += VT.getStoreSize().getKnownMinValue();
10829     }
10830   }
10831 
10832   // Call the target to set up the argument values.
10833   SmallVector<SDValue, 8> InVals;
10834   SDValue NewRoot = TLI->LowerFormalArguments(
10835       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10836 
10837   // Verify that the target's LowerFormalArguments behaved as expected.
10838   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10839          "LowerFormalArguments didn't return a valid chain!");
10840   assert(InVals.size() == Ins.size() &&
10841          "LowerFormalArguments didn't emit the correct number of values!");
10842   LLVM_DEBUG({
10843     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10844       assert(InVals[i].getNode() &&
10845              "LowerFormalArguments emitted a null value!");
10846       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10847              "LowerFormalArguments emitted a value with the wrong type!");
10848     }
10849   });
10850 
10851   // Update the DAG with the new chain value resulting from argument lowering.
10852   DAG.setRoot(NewRoot);
10853 
10854   // Set up the argument values.
10855   unsigned i = 0;
10856   if (!FuncInfo->CanLowerReturn) {
10857     // Create a virtual register for the sret pointer, and put in a copy
10858     // from the sret argument into it.
10859     SmallVector<EVT, 1> ValueVTs;
10860     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10861                     F.getReturnType()->getPointerTo(
10862                         DAG.getDataLayout().getAllocaAddrSpace()),
10863                     ValueVTs);
10864     MVT VT = ValueVTs[0].getSimpleVT();
10865     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10866     std::optional<ISD::NodeType> AssertOp;
10867     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10868                                         nullptr, F.getCallingConv(), AssertOp);
10869 
10870     MachineFunction& MF = SDB->DAG.getMachineFunction();
10871     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10872     Register SRetReg =
10873         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10874     FuncInfo->DemoteRegister = SRetReg;
10875     NewRoot =
10876         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10877     DAG.setRoot(NewRoot);
10878 
10879     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10880     ++i;
10881   }
10882 
10883   SmallVector<SDValue, 4> Chains;
10884   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10885   for (const Argument &Arg : F.args()) {
10886     SmallVector<SDValue, 4> ArgValues;
10887     SmallVector<EVT, 4> ValueVTs;
10888     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10889     unsigned NumValues = ValueVTs.size();
10890     if (NumValues == 0)
10891       continue;
10892 
10893     bool ArgHasUses = !Arg.use_empty();
10894 
10895     // Elide the copying store if the target loaded this argument from a
10896     // suitable fixed stack object.
10897     if (Ins[i].Flags.isCopyElisionCandidate()) {
10898       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10899                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10900                              InVals[i], ArgHasUses);
10901     }
10902 
10903     // If this argument is unused then remember its value. It is used to generate
10904     // debugging information.
10905     bool isSwiftErrorArg =
10906         TLI->supportSwiftError() &&
10907         Arg.hasAttribute(Attribute::SwiftError);
10908     if (!ArgHasUses && !isSwiftErrorArg) {
10909       SDB->setUnusedArgValue(&Arg, InVals[i]);
10910 
10911       // Also remember any frame index for use in FastISel.
10912       if (FrameIndexSDNode *FI =
10913           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10914         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10915     }
10916 
10917     for (unsigned Val = 0; Val != NumValues; ++Val) {
10918       EVT VT = ValueVTs[Val];
10919       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10920                                                       F.getCallingConv(), VT);
10921       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10922           *CurDAG->getContext(), F.getCallingConv(), VT);
10923 
10924       // Even an apparent 'unused' swifterror argument needs to be returned. So
10925       // we do generate a copy for it that can be used on return from the
10926       // function.
10927       if (ArgHasUses || isSwiftErrorArg) {
10928         std::optional<ISD::NodeType> AssertOp;
10929         if (Arg.hasAttribute(Attribute::SExt))
10930           AssertOp = ISD::AssertSext;
10931         else if (Arg.hasAttribute(Attribute::ZExt))
10932           AssertOp = ISD::AssertZext;
10933 
10934         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10935                                              PartVT, VT, nullptr,
10936                                              F.getCallingConv(), AssertOp));
10937       }
10938 
10939       i += NumParts;
10940     }
10941 
10942     // We don't need to do anything else for unused arguments.
10943     if (ArgValues.empty())
10944       continue;
10945 
10946     // Note down frame index.
10947     if (FrameIndexSDNode *FI =
10948         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10949       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10950 
10951     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
10952                                      SDB->getCurSDLoc());
10953 
10954     SDB->setValue(&Arg, Res);
10955     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10956       // We want to associate the argument with the frame index, among
10957       // involved operands, that correspond to the lowest address. The
10958       // getCopyFromParts function, called earlier, is swapping the order of
10959       // the operands to BUILD_PAIR depending on endianness. The result of
10960       // that swapping is that the least significant bits of the argument will
10961       // be in the first operand of the BUILD_PAIR node, and the most
10962       // significant bits will be in the second operand.
10963       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10964       if (LoadSDNode *LNode =
10965           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10966         if (FrameIndexSDNode *FI =
10967             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10968           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10969     }
10970 
10971     // Analyses past this point are naive and don't expect an assertion.
10972     if (Res.getOpcode() == ISD::AssertZext)
10973       Res = Res.getOperand(0);
10974 
10975     // Update the SwiftErrorVRegDefMap.
10976     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10977       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10978       if (Register::isVirtualRegister(Reg))
10979         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10980                                    Reg);
10981     }
10982 
10983     // If this argument is live outside of the entry block, insert a copy from
10984     // wherever we got it to the vreg that other BB's will reference it as.
10985     if (Res.getOpcode() == ISD::CopyFromReg) {
10986       // If we can, though, try to skip creating an unnecessary vreg.
10987       // FIXME: This isn't very clean... it would be nice to make this more
10988       // general.
10989       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10990       if (Register::isVirtualRegister(Reg)) {
10991         FuncInfo->ValueMap[&Arg] = Reg;
10992         continue;
10993       }
10994     }
10995     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10996       FuncInfo->InitializeRegForValue(&Arg);
10997       SDB->CopyToExportRegsIfNeeded(&Arg);
10998     }
10999   }
11000 
11001   if (!Chains.empty()) {
11002     Chains.push_back(NewRoot);
11003     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11004   }
11005 
11006   DAG.setRoot(NewRoot);
11007 
11008   assert(i == InVals.size() && "Argument register count mismatch!");
11009 
11010   // If any argument copy elisions occurred and we have debug info, update the
11011   // stale frame indices used in the dbg.declare variable info table.
11012   if (!ArgCopyElisionFrameIndexMap.empty()) {
11013     for (MachineFunction::VariableDbgInfo &VI :
11014          MF->getInStackSlotVariableDbgInfo()) {
11015       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11016       if (I != ArgCopyElisionFrameIndexMap.end())
11017         VI.updateStackSlot(I->second);
11018     }
11019   }
11020 
11021   // Finally, if the target has anything special to do, allow it to do so.
11022   emitFunctionEntryCode();
11023 }
11024 
11025 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11026 /// ensure constants are generated when needed.  Remember the virtual registers
11027 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11028 /// directly add them, because expansion might result in multiple MBB's for one
11029 /// BB.  As such, the start of the BB might correspond to a different MBB than
11030 /// the end.
11031 void
11032 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11033   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11034 
11035   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11036 
11037   // Check PHI nodes in successors that expect a value to be available from this
11038   // block.
11039   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11040     if (!isa<PHINode>(SuccBB->begin())) continue;
11041     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11042 
11043     // If this terminator has multiple identical successors (common for
11044     // switches), only handle each succ once.
11045     if (!SuccsHandled.insert(SuccMBB).second)
11046       continue;
11047 
11048     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11049 
11050     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11051     // nodes and Machine PHI nodes, but the incoming operands have not been
11052     // emitted yet.
11053     for (const PHINode &PN : SuccBB->phis()) {
11054       // Ignore dead phi's.
11055       if (PN.use_empty())
11056         continue;
11057 
11058       // Skip empty types
11059       if (PN.getType()->isEmptyTy())
11060         continue;
11061 
11062       unsigned Reg;
11063       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11064 
11065       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11066         unsigned &RegOut = ConstantsOut[C];
11067         if (RegOut == 0) {
11068           RegOut = FuncInfo.CreateRegs(C);
11069           // We need to zero/sign extend ConstantInt phi operands to match
11070           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11071           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11072           if (auto *CI = dyn_cast<ConstantInt>(C))
11073             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11074                                                     : ISD::ZERO_EXTEND;
11075           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11076         }
11077         Reg = RegOut;
11078       } else {
11079         DenseMap<const Value *, Register>::iterator I =
11080           FuncInfo.ValueMap.find(PHIOp);
11081         if (I != FuncInfo.ValueMap.end())
11082           Reg = I->second;
11083         else {
11084           assert(isa<AllocaInst>(PHIOp) &&
11085                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11086                  "Didn't codegen value into a register!??");
11087           Reg = FuncInfo.CreateRegs(PHIOp);
11088           CopyValueToVirtualRegister(PHIOp, Reg);
11089         }
11090       }
11091 
11092       // Remember that this register needs to added to the machine PHI node as
11093       // the input for this MBB.
11094       SmallVector<EVT, 4> ValueVTs;
11095       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11096       for (EVT VT : ValueVTs) {
11097         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11098         for (unsigned i = 0; i != NumRegisters; ++i)
11099           FuncInfo.PHINodesToUpdate.push_back(
11100               std::make_pair(&*MBBI++, Reg + i));
11101         Reg += NumRegisters;
11102       }
11103     }
11104   }
11105 
11106   ConstantsOut.clear();
11107 }
11108 
11109 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11110   MachineFunction::iterator I(MBB);
11111   if (++I == FuncInfo.MF->end())
11112     return nullptr;
11113   return &*I;
11114 }
11115 
11116 /// During lowering new call nodes can be created (such as memset, etc.).
11117 /// Those will become new roots of the current DAG, but complications arise
11118 /// when they are tail calls. In such cases, the call lowering will update
11119 /// the root, but the builder still needs to know that a tail call has been
11120 /// lowered in order to avoid generating an additional return.
11121 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11122   // If the node is null, we do have a tail call.
11123   if (MaybeTC.getNode() != nullptr)
11124     DAG.setRoot(MaybeTC);
11125   else
11126     HasTailCall = true;
11127 }
11128 
11129 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11130                                         MachineBasicBlock *SwitchMBB,
11131                                         MachineBasicBlock *DefaultMBB) {
11132   MachineFunction *CurMF = FuncInfo.MF;
11133   MachineBasicBlock *NextMBB = nullptr;
11134   MachineFunction::iterator BBI(W.MBB);
11135   if (++BBI != FuncInfo.MF->end())
11136     NextMBB = &*BBI;
11137 
11138   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11139 
11140   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11141 
11142   if (Size == 2 && W.MBB == SwitchMBB) {
11143     // If any two of the cases has the same destination, and if one value
11144     // is the same as the other, but has one bit unset that the other has set,
11145     // use bit manipulation to do two compares at once.  For example:
11146     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11147     // TODO: This could be extended to merge any 2 cases in switches with 3
11148     // cases.
11149     // TODO: Handle cases where W.CaseBB != SwitchBB.
11150     CaseCluster &Small = *W.FirstCluster;
11151     CaseCluster &Big = *W.LastCluster;
11152 
11153     if (Small.Low == Small.High && Big.Low == Big.High &&
11154         Small.MBB == Big.MBB) {
11155       const APInt &SmallValue = Small.Low->getValue();
11156       const APInt &BigValue = Big.Low->getValue();
11157 
11158       // Check that there is only one bit different.
11159       APInt CommonBit = BigValue ^ SmallValue;
11160       if (CommonBit.isPowerOf2()) {
11161         SDValue CondLHS = getValue(Cond);
11162         EVT VT = CondLHS.getValueType();
11163         SDLoc DL = getCurSDLoc();
11164 
11165         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11166                                  DAG.getConstant(CommonBit, DL, VT));
11167         SDValue Cond = DAG.getSetCC(
11168             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11169             ISD::SETEQ);
11170 
11171         // Update successor info.
11172         // Both Small and Big will jump to Small.BB, so we sum up the
11173         // probabilities.
11174         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11175         if (BPI)
11176           addSuccessorWithProb(
11177               SwitchMBB, DefaultMBB,
11178               // The default destination is the first successor in IR.
11179               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11180         else
11181           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11182 
11183         // Insert the true branch.
11184         SDValue BrCond =
11185             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11186                         DAG.getBasicBlock(Small.MBB));
11187         // Insert the false branch.
11188         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11189                              DAG.getBasicBlock(DefaultMBB));
11190 
11191         DAG.setRoot(BrCond);
11192         return;
11193       }
11194     }
11195   }
11196 
11197   if (TM.getOptLevel() != CodeGenOpt::None) {
11198     // Here, we order cases by probability so the most likely case will be
11199     // checked first. However, two clusters can have the same probability in
11200     // which case their relative ordering is non-deterministic. So we use Low
11201     // as a tie-breaker as clusters are guaranteed to never overlap.
11202     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11203                [](const CaseCluster &a, const CaseCluster &b) {
11204       return a.Prob != b.Prob ?
11205              a.Prob > b.Prob :
11206              a.Low->getValue().slt(b.Low->getValue());
11207     });
11208 
11209     // Rearrange the case blocks so that the last one falls through if possible
11210     // without changing the order of probabilities.
11211     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11212       --I;
11213       if (I->Prob > W.LastCluster->Prob)
11214         break;
11215       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11216         std::swap(*I, *W.LastCluster);
11217         break;
11218       }
11219     }
11220   }
11221 
11222   // Compute total probability.
11223   BranchProbability DefaultProb = W.DefaultProb;
11224   BranchProbability UnhandledProbs = DefaultProb;
11225   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11226     UnhandledProbs += I->Prob;
11227 
11228   MachineBasicBlock *CurMBB = W.MBB;
11229   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11230     bool FallthroughUnreachable = false;
11231     MachineBasicBlock *Fallthrough;
11232     if (I == W.LastCluster) {
11233       // For the last cluster, fall through to the default destination.
11234       Fallthrough = DefaultMBB;
11235       FallthroughUnreachable = isa<UnreachableInst>(
11236           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11237     } else {
11238       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11239       CurMF->insert(BBI, Fallthrough);
11240       // Put Cond in a virtual register to make it available from the new blocks.
11241       ExportFromCurrentBlock(Cond);
11242     }
11243     UnhandledProbs -= I->Prob;
11244 
11245     switch (I->Kind) {
11246       case CC_JumpTable: {
11247         // FIXME: Optimize away range check based on pivot comparisons.
11248         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11249         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11250 
11251         // The jump block hasn't been inserted yet; insert it here.
11252         MachineBasicBlock *JumpMBB = JT->MBB;
11253         CurMF->insert(BBI, JumpMBB);
11254 
11255         auto JumpProb = I->Prob;
11256         auto FallthroughProb = UnhandledProbs;
11257 
11258         // If the default statement is a target of the jump table, we evenly
11259         // distribute the default probability to successors of CurMBB. Also
11260         // update the probability on the edge from JumpMBB to Fallthrough.
11261         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11262                                               SE = JumpMBB->succ_end();
11263              SI != SE; ++SI) {
11264           if (*SI == DefaultMBB) {
11265             JumpProb += DefaultProb / 2;
11266             FallthroughProb -= DefaultProb / 2;
11267             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11268             JumpMBB->normalizeSuccProbs();
11269             break;
11270           }
11271         }
11272 
11273         if (FallthroughUnreachable)
11274           JTH->FallthroughUnreachable = true;
11275 
11276         if (!JTH->FallthroughUnreachable)
11277           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11278         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11279         CurMBB->normalizeSuccProbs();
11280 
11281         // The jump table header will be inserted in our current block, do the
11282         // range check, and fall through to our fallthrough block.
11283         JTH->HeaderBB = CurMBB;
11284         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11285 
11286         // If we're in the right place, emit the jump table header right now.
11287         if (CurMBB == SwitchMBB) {
11288           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11289           JTH->Emitted = true;
11290         }
11291         break;
11292       }
11293       case CC_BitTests: {
11294         // FIXME: Optimize away range check based on pivot comparisons.
11295         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11296 
11297         // The bit test blocks haven't been inserted yet; insert them here.
11298         for (BitTestCase &BTC : BTB->Cases)
11299           CurMF->insert(BBI, BTC.ThisBB);
11300 
11301         // Fill in fields of the BitTestBlock.
11302         BTB->Parent = CurMBB;
11303         BTB->Default = Fallthrough;
11304 
11305         BTB->DefaultProb = UnhandledProbs;
11306         // If the cases in bit test don't form a contiguous range, we evenly
11307         // distribute the probability on the edge to Fallthrough to two
11308         // successors of CurMBB.
11309         if (!BTB->ContiguousRange) {
11310           BTB->Prob += DefaultProb / 2;
11311           BTB->DefaultProb -= DefaultProb / 2;
11312         }
11313 
11314         if (FallthroughUnreachable)
11315           BTB->FallthroughUnreachable = true;
11316 
11317         // If we're in the right place, emit the bit test header right now.
11318         if (CurMBB == SwitchMBB) {
11319           visitBitTestHeader(*BTB, SwitchMBB);
11320           BTB->Emitted = true;
11321         }
11322         break;
11323       }
11324       case CC_Range: {
11325         const Value *RHS, *LHS, *MHS;
11326         ISD::CondCode CC;
11327         if (I->Low == I->High) {
11328           // Check Cond == I->Low.
11329           CC = ISD::SETEQ;
11330           LHS = Cond;
11331           RHS=I->Low;
11332           MHS = nullptr;
11333         } else {
11334           // Check I->Low <= Cond <= I->High.
11335           CC = ISD::SETLE;
11336           LHS = I->Low;
11337           MHS = Cond;
11338           RHS = I->High;
11339         }
11340 
11341         // If Fallthrough is unreachable, fold away the comparison.
11342         if (FallthroughUnreachable)
11343           CC = ISD::SETTRUE;
11344 
11345         // The false probability is the sum of all unhandled cases.
11346         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11347                      getCurSDLoc(), I->Prob, UnhandledProbs);
11348 
11349         if (CurMBB == SwitchMBB)
11350           visitSwitchCase(CB, SwitchMBB);
11351         else
11352           SL->SwitchCases.push_back(CB);
11353 
11354         break;
11355       }
11356     }
11357     CurMBB = Fallthrough;
11358   }
11359 }
11360 
11361 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11362                                               CaseClusterIt First,
11363                                               CaseClusterIt Last) {
11364   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11365     if (X.Prob != CC.Prob)
11366       return X.Prob > CC.Prob;
11367 
11368     // Ties are broken by comparing the case value.
11369     return X.Low->getValue().slt(CC.Low->getValue());
11370   });
11371 }
11372 
11373 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11374                                         const SwitchWorkListItem &W,
11375                                         Value *Cond,
11376                                         MachineBasicBlock *SwitchMBB) {
11377   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11378          "Clusters not sorted?");
11379 
11380   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11381 
11382   // Balance the tree based on branch probabilities to create a near-optimal (in
11383   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11384   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11385   CaseClusterIt LastLeft = W.FirstCluster;
11386   CaseClusterIt FirstRight = W.LastCluster;
11387   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11388   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11389 
11390   // Move LastLeft and FirstRight towards each other from opposite directions to
11391   // find a partitioning of the clusters which balances the probability on both
11392   // sides. If LeftProb and RightProb are equal, alternate which side is
11393   // taken to ensure 0-probability nodes are distributed evenly.
11394   unsigned I = 0;
11395   while (LastLeft + 1 < FirstRight) {
11396     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11397       LeftProb += (++LastLeft)->Prob;
11398     else
11399       RightProb += (--FirstRight)->Prob;
11400     I++;
11401   }
11402 
11403   while (true) {
11404     // Our binary search tree differs from a typical BST in that ours can have up
11405     // to three values in each leaf. The pivot selection above doesn't take that
11406     // into account, which means the tree might require more nodes and be less
11407     // efficient. We compensate for this here.
11408 
11409     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11410     unsigned NumRight = W.LastCluster - FirstRight + 1;
11411 
11412     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11413       // If one side has less than 3 clusters, and the other has more than 3,
11414       // consider taking a cluster from the other side.
11415 
11416       if (NumLeft < NumRight) {
11417         // Consider moving the first cluster on the right to the left side.
11418         CaseCluster &CC = *FirstRight;
11419         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11420         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11421         if (LeftSideRank <= RightSideRank) {
11422           // Moving the cluster to the left does not demote it.
11423           ++LastLeft;
11424           ++FirstRight;
11425           continue;
11426         }
11427       } else {
11428         assert(NumRight < NumLeft);
11429         // Consider moving the last element on the left to the right side.
11430         CaseCluster &CC = *LastLeft;
11431         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11432         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11433         if (RightSideRank <= LeftSideRank) {
11434           // Moving the cluster to the right does not demot it.
11435           --LastLeft;
11436           --FirstRight;
11437           continue;
11438         }
11439       }
11440     }
11441     break;
11442   }
11443 
11444   assert(LastLeft + 1 == FirstRight);
11445   assert(LastLeft >= W.FirstCluster);
11446   assert(FirstRight <= W.LastCluster);
11447 
11448   // Use the first element on the right as pivot since we will make less-than
11449   // comparisons against it.
11450   CaseClusterIt PivotCluster = FirstRight;
11451   assert(PivotCluster > W.FirstCluster);
11452   assert(PivotCluster <= W.LastCluster);
11453 
11454   CaseClusterIt FirstLeft = W.FirstCluster;
11455   CaseClusterIt LastRight = W.LastCluster;
11456 
11457   const ConstantInt *Pivot = PivotCluster->Low;
11458 
11459   // New blocks will be inserted immediately after the current one.
11460   MachineFunction::iterator BBI(W.MBB);
11461   ++BBI;
11462 
11463   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11464   // we can branch to its destination directly if it's squeezed exactly in
11465   // between the known lower bound and Pivot - 1.
11466   MachineBasicBlock *LeftMBB;
11467   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11468       FirstLeft->Low == W.GE &&
11469       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11470     LeftMBB = FirstLeft->MBB;
11471   } else {
11472     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11473     FuncInfo.MF->insert(BBI, LeftMBB);
11474     WorkList.push_back(
11475         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11476     // Put Cond in a virtual register to make it available from the new blocks.
11477     ExportFromCurrentBlock(Cond);
11478   }
11479 
11480   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11481   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11482   // directly if RHS.High equals the current upper bound.
11483   MachineBasicBlock *RightMBB;
11484   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11485       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11486     RightMBB = FirstRight->MBB;
11487   } else {
11488     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11489     FuncInfo.MF->insert(BBI, RightMBB);
11490     WorkList.push_back(
11491         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11492     // Put Cond in a virtual register to make it available from the new blocks.
11493     ExportFromCurrentBlock(Cond);
11494   }
11495 
11496   // Create the CaseBlock record that will be used to lower the branch.
11497   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11498                getCurSDLoc(), LeftProb, RightProb);
11499 
11500   if (W.MBB == SwitchMBB)
11501     visitSwitchCase(CB, SwitchMBB);
11502   else
11503     SL->SwitchCases.push_back(CB);
11504 }
11505 
11506 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11507 // from the swith statement.
11508 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11509                                             BranchProbability PeeledCaseProb) {
11510   if (PeeledCaseProb == BranchProbability::getOne())
11511     return BranchProbability::getZero();
11512   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11513 
11514   uint32_t Numerator = CaseProb.getNumerator();
11515   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11516   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11517 }
11518 
11519 // Try to peel the top probability case if it exceeds the threshold.
11520 // Return current MachineBasicBlock for the switch statement if the peeling
11521 // does not occur.
11522 // If the peeling is performed, return the newly created MachineBasicBlock
11523 // for the peeled switch statement. Also update Clusters to remove the peeled
11524 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11525 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11526     const SwitchInst &SI, CaseClusterVector &Clusters,
11527     BranchProbability &PeeledCaseProb) {
11528   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11529   // Don't perform if there is only one cluster or optimizing for size.
11530   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11531       TM.getOptLevel() == CodeGenOpt::None ||
11532       SwitchMBB->getParent()->getFunction().hasMinSize())
11533     return SwitchMBB;
11534 
11535   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11536   unsigned PeeledCaseIndex = 0;
11537   bool SwitchPeeled = false;
11538   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11539     CaseCluster &CC = Clusters[Index];
11540     if (CC.Prob < TopCaseProb)
11541       continue;
11542     TopCaseProb = CC.Prob;
11543     PeeledCaseIndex = Index;
11544     SwitchPeeled = true;
11545   }
11546   if (!SwitchPeeled)
11547     return SwitchMBB;
11548 
11549   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11550                     << TopCaseProb << "\n");
11551 
11552   // Record the MBB for the peeled switch statement.
11553   MachineFunction::iterator BBI(SwitchMBB);
11554   ++BBI;
11555   MachineBasicBlock *PeeledSwitchMBB =
11556       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11557   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11558 
11559   ExportFromCurrentBlock(SI.getCondition());
11560   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11561   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11562                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11563   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11564 
11565   Clusters.erase(PeeledCaseIt);
11566   for (CaseCluster &CC : Clusters) {
11567     LLVM_DEBUG(
11568         dbgs() << "Scale the probablity for one cluster, before scaling: "
11569                << CC.Prob << "\n");
11570     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11571     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11572   }
11573   PeeledCaseProb = TopCaseProb;
11574   return PeeledSwitchMBB;
11575 }
11576 
11577 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11578   // Extract cases from the switch.
11579   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11580   CaseClusterVector Clusters;
11581   Clusters.reserve(SI.getNumCases());
11582   for (auto I : SI.cases()) {
11583     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11584     const ConstantInt *CaseVal = I.getCaseValue();
11585     BranchProbability Prob =
11586         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11587             : BranchProbability(1, SI.getNumCases() + 1);
11588     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11589   }
11590 
11591   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11592 
11593   // Cluster adjacent cases with the same destination. We do this at all
11594   // optimization levels because it's cheap to do and will make codegen faster
11595   // if there are many clusters.
11596   sortAndRangeify(Clusters);
11597 
11598   // The branch probablity of the peeled case.
11599   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11600   MachineBasicBlock *PeeledSwitchMBB =
11601       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11602 
11603   // If there is only the default destination, jump there directly.
11604   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11605   if (Clusters.empty()) {
11606     assert(PeeledSwitchMBB == SwitchMBB);
11607     SwitchMBB->addSuccessor(DefaultMBB);
11608     if (DefaultMBB != NextBlock(SwitchMBB)) {
11609       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11610                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11611     }
11612     return;
11613   }
11614 
11615   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11616   SL->findBitTestClusters(Clusters, &SI);
11617 
11618   LLVM_DEBUG({
11619     dbgs() << "Case clusters: ";
11620     for (const CaseCluster &C : Clusters) {
11621       if (C.Kind == CC_JumpTable)
11622         dbgs() << "JT:";
11623       if (C.Kind == CC_BitTests)
11624         dbgs() << "BT:";
11625 
11626       C.Low->getValue().print(dbgs(), true);
11627       if (C.Low != C.High) {
11628         dbgs() << '-';
11629         C.High->getValue().print(dbgs(), true);
11630       }
11631       dbgs() << ' ';
11632     }
11633     dbgs() << '\n';
11634   });
11635 
11636   assert(!Clusters.empty());
11637   SwitchWorkList WorkList;
11638   CaseClusterIt First = Clusters.begin();
11639   CaseClusterIt Last = Clusters.end() - 1;
11640   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11641   // Scale the branchprobability for DefaultMBB if the peel occurs and
11642   // DefaultMBB is not replaced.
11643   if (PeeledCaseProb != BranchProbability::getZero() &&
11644       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11645     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11646   WorkList.push_back(
11647       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11648 
11649   while (!WorkList.empty()) {
11650     SwitchWorkListItem W = WorkList.pop_back_val();
11651     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11652 
11653     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11654         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11655       // For optimized builds, lower large range as a balanced binary tree.
11656       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11657       continue;
11658     }
11659 
11660     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11661   }
11662 }
11663 
11664 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11665   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11666   auto DL = getCurSDLoc();
11667   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11668   setValue(&I, DAG.getStepVector(DL, ResultVT));
11669 }
11670 
11671 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11672   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11673   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11674 
11675   SDLoc DL = getCurSDLoc();
11676   SDValue V = getValue(I.getOperand(0));
11677   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11678 
11679   if (VT.isScalableVector()) {
11680     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11681     return;
11682   }
11683 
11684   // Use VECTOR_SHUFFLE for the fixed-length vector
11685   // to maintain existing behavior.
11686   SmallVector<int, 8> Mask;
11687   unsigned NumElts = VT.getVectorMinNumElements();
11688   for (unsigned i = 0; i != NumElts; ++i)
11689     Mask.push_back(NumElts - 1 - i);
11690 
11691   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11692 }
11693 
11694 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
11695   auto DL = getCurSDLoc();
11696   SDValue InVec = getValue(I.getOperand(0));
11697   EVT OutVT =
11698       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
11699 
11700   unsigned OutNumElts = OutVT.getVectorMinNumElements();
11701 
11702   // ISD Node needs the input vectors split into two equal parts
11703   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11704                            DAG.getVectorIdxConstant(0, DL));
11705   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11706                            DAG.getVectorIdxConstant(OutNumElts, DL));
11707 
11708   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11709   // legalisation and combines.
11710   if (OutVT.isFixedLengthVector()) {
11711     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11712                                         createStrideMask(0, 2, OutNumElts));
11713     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11714                                        createStrideMask(1, 2, OutNumElts));
11715     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
11716     setValue(&I, Res);
11717     return;
11718   }
11719 
11720   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
11721                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
11722   setValue(&I, Res);
11723 }
11724 
11725 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
11726   auto DL = getCurSDLoc();
11727   EVT InVT = getValue(I.getOperand(0)).getValueType();
11728   SDValue InVec0 = getValue(I.getOperand(0));
11729   SDValue InVec1 = getValue(I.getOperand(1));
11730   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11731   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11732 
11733   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11734   // legalisation and combines.
11735   if (OutVT.isFixedLengthVector()) {
11736     unsigned NumElts = InVT.getVectorMinNumElements();
11737     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
11738     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
11739                                       createInterleaveMask(NumElts, 2)));
11740     return;
11741   }
11742 
11743   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
11744                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
11745   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
11746                     Res.getValue(1));
11747   setValue(&I, Res);
11748 }
11749 
11750 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11751   SmallVector<EVT, 4> ValueVTs;
11752   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11753                   ValueVTs);
11754   unsigned NumValues = ValueVTs.size();
11755   if (NumValues == 0) return;
11756 
11757   SmallVector<SDValue, 4> Values(NumValues);
11758   SDValue Op = getValue(I.getOperand(0));
11759 
11760   for (unsigned i = 0; i != NumValues; ++i)
11761     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11762                             SDValue(Op.getNode(), Op.getResNo() + i));
11763 
11764   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11765                            DAG.getVTList(ValueVTs), Values));
11766 }
11767 
11768 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11769   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11770   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11771 
11772   SDLoc DL = getCurSDLoc();
11773   SDValue V1 = getValue(I.getOperand(0));
11774   SDValue V2 = getValue(I.getOperand(1));
11775   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11776 
11777   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11778   if (VT.isScalableVector()) {
11779     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11780     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11781                              DAG.getConstant(Imm, DL, IdxVT)));
11782     return;
11783   }
11784 
11785   unsigned NumElts = VT.getVectorNumElements();
11786 
11787   uint64_t Idx = (NumElts + Imm) % NumElts;
11788 
11789   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11790   SmallVector<int, 8> Mask;
11791   for (unsigned i = 0; i < NumElts; ++i)
11792     Mask.push_back(Idx + i);
11793   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11794 }
11795 
11796 // Consider the following MIR after SelectionDAG, which produces output in
11797 // phyregs in the first case or virtregs in the second case.
11798 //
11799 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
11800 // %5:gr32 = COPY $ebx
11801 // %6:gr32 = COPY $edx
11802 // %1:gr32 = COPY %6:gr32
11803 // %0:gr32 = COPY %5:gr32
11804 //
11805 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
11806 // %1:gr32 = COPY %6:gr32
11807 // %0:gr32 = COPY %5:gr32
11808 //
11809 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
11810 // Given %1, we'd like to return $edx in the first case and %6 in the second.
11811 //
11812 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
11813 // to a single virtreg (such as %0). The remaining outputs monotonically
11814 // increase in virtreg number from there. If a callbr has no outputs, then it
11815 // should not have a corresponding callbr landingpad; in fact, the callbr
11816 // landingpad would not even be able to refer to such a callbr.
11817 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
11818   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
11819   // There is definitely at least one copy.
11820   assert(MI->getOpcode() == TargetOpcode::COPY &&
11821          "start of copy chain MUST be COPY");
11822   Reg = MI->getOperand(1).getReg();
11823   MI = MRI.def_begin(Reg)->getParent();
11824   // There may be an optional second copy.
11825   if (MI->getOpcode() == TargetOpcode::COPY) {
11826     assert(Reg.isVirtual() && "expected COPY of virtual register");
11827     Reg = MI->getOperand(1).getReg();
11828     assert(Reg.isPhysical() && "expected COPY of physical register");
11829     MI = MRI.def_begin(Reg)->getParent();
11830   }
11831   // The start of the chain must be an INLINEASM_BR.
11832   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
11833          "end of copy chain MUST be INLINEASM_BR");
11834   return Reg;
11835 }
11836 
11837 // We must do this walk rather than the simpler
11838 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
11839 // otherwise we will end up with copies of virtregs only valid along direct
11840 // edges.
11841 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
11842   SmallVector<EVT, 8> ResultVTs;
11843   SmallVector<SDValue, 8> ResultValues;
11844   const auto *CBR =
11845       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
11846 
11847   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11848   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
11849   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11850 
11851   unsigned InitialDef = FuncInfo.ValueMap[CBR];
11852   SDValue Chain = DAG.getRoot();
11853 
11854   // Re-parse the asm constraints string.
11855   TargetLowering::AsmOperandInfoVector TargetConstraints =
11856       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
11857   for (auto &T : TargetConstraints) {
11858     SDISelAsmOperandInfo OpInfo(T);
11859     if (OpInfo.Type != InlineAsm::isOutput)
11860       continue;
11861 
11862     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
11863     // individual constraint.
11864     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
11865 
11866     switch (OpInfo.ConstraintType) {
11867     case TargetLowering::C_Register:
11868     case TargetLowering::C_RegisterClass: {
11869       // Fill in OpInfo.AssignedRegs.Regs.
11870       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
11871 
11872       // getRegistersForValue may produce 1 to many registers based on whether
11873       // the OpInfo.ConstraintVT is legal on the target or not.
11874       for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) {
11875         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
11876         if (Register::isPhysicalRegister(OriginalDef))
11877           FuncInfo.MBB->addLiveIn(OriginalDef);
11878         // Update the assigned registers to use the original defs.
11879         OpInfo.AssignedRegs.Regs[i] = OriginalDef;
11880       }
11881 
11882       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
11883           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
11884       ResultValues.push_back(V);
11885       ResultVTs.push_back(OpInfo.ConstraintVT);
11886       break;
11887     }
11888     case TargetLowering::C_Other: {
11889       SDValue Flag;
11890       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
11891                                                   OpInfo, DAG);
11892       ++InitialDef;
11893       ResultValues.push_back(V);
11894       ResultVTs.push_back(OpInfo.ConstraintVT);
11895       break;
11896     }
11897     default:
11898       break;
11899     }
11900   }
11901   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11902                           DAG.getVTList(ResultVTs), ResultValues);
11903   setValue(&I, V);
11904 }
11905