xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 972983539b28ccc941d4a10cad6d436278e55c6f)
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       SmallVector<Value *> Values(It->Values.location_ops());
1151       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1152                             It->Values.hasArgList()))
1153         addDanglingDebugInfo(It, SDNodeOrder);
1154     }
1155   }
1156 
1157   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1158   if (!isa<DbgInfoIntrinsic>(I))
1159     ++SDNodeOrder;
1160 
1161   CurInst = &I;
1162 
1163   // Set inserted listener only if required.
1164   bool NodeInserted = false;
1165   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1166   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1167   if (PCSectionsMD) {
1168     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1169         DAG, [&](SDNode *) { NodeInserted = true; });
1170   }
1171 
1172   visit(I.getOpcode(), I);
1173 
1174   if (!I.isTerminator() && !HasTailCall &&
1175       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1176     CopyToExportRegsIfNeeded(&I);
1177 
1178   // Handle metadata.
1179   if (PCSectionsMD) {
1180     auto It = NodeMap.find(&I);
1181     if (It != NodeMap.end()) {
1182       DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1183     } else if (NodeInserted) {
1184       // This should not happen; if it does, don't let it go unnoticed so we can
1185       // fix it. Relevant visit*() function is probably missing a setValue().
1186       errs() << "warning: loosing !pcsections metadata ["
1187              << I.getModule()->getName() << "]\n";
1188       LLVM_DEBUG(I.dump());
1189       assert(false);
1190     }
1191   }
1192 
1193   CurInst = nullptr;
1194 }
1195 
1196 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1197   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1198 }
1199 
1200 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1201   // Note: this doesn't use InstVisitor, because it has to work with
1202   // ConstantExpr's in addition to instructions.
1203   switch (Opcode) {
1204   default: llvm_unreachable("Unknown instruction type encountered!");
1205     // Build the switch statement using the Instruction.def file.
1206 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1207     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1208 #include "llvm/IR/Instruction.def"
1209   }
1210 }
1211 
1212 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1213                                             DILocalVariable *Variable,
1214                                             DebugLoc DL, unsigned Order,
1215                                             RawLocationWrapper Values,
1216                                             DIExpression *Expression) {
1217   if (!Values.hasArgList())
1218     return false;
1219   // For variadic dbg_values we will now insert an undef.
1220   // FIXME: We can potentially recover these!
1221   SmallVector<SDDbgOperand, 2> Locs;
1222   for (const Value *V : Values.location_ops()) {
1223     auto *Undef = UndefValue::get(V->getType());
1224     Locs.push_back(SDDbgOperand::fromConst(Undef));
1225   }
1226   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1227                                         /*IsIndirect=*/false, DL, Order,
1228                                         /*IsVariadic=*/true);
1229   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1230   return true;
1231 }
1232 
1233 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc,
1234                                                unsigned Order) {
1235   if (!handleDanglingVariadicDebugInfo(
1236           DAG,
1237           const_cast<DILocalVariable *>(DAG.getFunctionVarLocs()
1238                                             ->getVariable(VarLoc->VariableID)
1239                                             .getVariable()),
1240           VarLoc->DL, Order, VarLoc->Values, VarLoc->Expr)) {
1241     DanglingDebugInfoMap[VarLoc->Values.getVariableLocationOp(0)].emplace_back(
1242         VarLoc, Order);
1243   }
1244 }
1245 
1246 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1247                                                unsigned Order) {
1248   // We treat variadic dbg_values differently at this stage.
1249   if (!handleDanglingVariadicDebugInfo(
1250           DAG, DI->getVariable(), DI->getDebugLoc(), Order,
1251           DI->getWrappedLocation(), DI->getExpression())) {
1252     // TODO: Dangling debug info will eventually either be resolved or produce
1253     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1254     // between the original dbg.value location and its resolved DBG_VALUE,
1255     // which we should ideally fill with an extra Undef DBG_VALUE.
1256     assert(DI->getNumVariableLocationOps() == 1 &&
1257            "DbgValueInst without an ArgList should have a single location "
1258            "operand.");
1259     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order);
1260   }
1261 }
1262 
1263 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1264                                                 const DIExpression *Expr) {
1265   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1266     DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs());
1267     DIExpression *DanglingExpr = DDI.getExpression();
1268     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1269       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI)
1270                         << "\n");
1271       return true;
1272     }
1273     return false;
1274   };
1275 
1276   for (auto &DDIMI : DanglingDebugInfoMap) {
1277     DanglingDebugInfoVector &DDIV = DDIMI.second;
1278 
1279     // If debug info is to be dropped, run it through final checks to see
1280     // whether it can be salvaged.
1281     for (auto &DDI : DDIV)
1282       if (isMatchingDbgValue(DDI))
1283         salvageUnresolvedDbgValue(DDI);
1284 
1285     erase_if(DDIV, isMatchingDbgValue);
1286   }
1287 }
1288 
1289 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1290 // generate the debug data structures now that we've seen its definition.
1291 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1292                                                    SDValue Val) {
1293   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1294   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1295     return;
1296 
1297   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1298   for (auto &DDI : DDIV) {
1299     DebugLoc DL = DDI.getDebugLoc();
1300     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1301     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1302     DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs());
1303     DIExpression *Expr = DDI.getExpression();
1304     assert(Variable->isValidLocationForIntrinsic(DL) &&
1305            "Expected inlined-at fields to agree");
1306     SDDbgValue *SDV;
1307     if (Val.getNode()) {
1308       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1309       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1310       // we couldn't resolve it directly when examining the DbgValue intrinsic
1311       // in the first place we should not be more successful here). Unless we
1312       // have some test case that prove this to be correct we should avoid
1313       // calling EmitFuncArgumentDbgValue here.
1314       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1315                                     FuncArgumentDbgValueKind::Value, Val)) {
1316         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI)
1317                           << "\n");
1318         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1319         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1320         // inserted after the definition of Val when emitting the instructions
1321         // after ISel. An alternative could be to teach
1322         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1323         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1324                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1325                    << ValSDNodeOrder << "\n");
1326         SDV = getDbgValue(Val, Variable, Expr, DL,
1327                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1328         DAG.AddDbgValue(SDV, false);
1329       } else
1330         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1331                           << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n");
1332     } else {
1333       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n");
1334       auto Undef = UndefValue::get(V->getType());
1335       auto SDV =
1336           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1337       DAG.AddDbgValue(SDV, false);
1338     }
1339   }
1340   DDIV.clear();
1341 }
1342 
1343 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1344   // TODO: For the variadic implementation, instead of only checking the fail
1345   // state of `handleDebugValue`, we need know specifically which values were
1346   // invalid, so that we attempt to salvage only those values when processing
1347   // a DIArgList.
1348   Value *V = DDI.getVariableLocationOp(0);
1349   Value *OrigV = V;
1350   DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs());
1351   DIExpression *Expr = DDI.getExpression();
1352   DebugLoc DL = DDI.getDebugLoc();
1353   unsigned SDOrder = DDI.getSDNodeOrder();
1354 
1355   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1356   // that DW_OP_stack_value is desired.
1357   bool StackValue = true;
1358 
1359   // Can this Value can be encoded without any further work?
1360   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1361     return;
1362 
1363   // Attempt to salvage back through as many instructions as possible. Bail if
1364   // a non-instruction is seen, such as a constant expression or global
1365   // variable. FIXME: Further work could recover those too.
1366   while (isa<Instruction>(V)) {
1367     Instruction &VAsInst = *cast<Instruction>(V);
1368     // Temporary "0", awaiting real implementation.
1369     SmallVector<uint64_t, 16> Ops;
1370     SmallVector<Value *, 4> AdditionalValues;
1371     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1372                              AdditionalValues);
1373     // If we cannot salvage any further, and haven't yet found a suitable debug
1374     // expression, bail out.
1375     if (!V)
1376       break;
1377 
1378     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1379     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1380     // here for variadic dbg_values, remove that condition.
1381     if (!AdditionalValues.empty())
1382       break;
1383 
1384     // New value and expr now represent this debuginfo.
1385     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1386 
1387     // Some kind of simplification occurred: check whether the operand of the
1388     // salvaged debug expression can be encoded in this DAG.
1389     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1390       LLVM_DEBUG(
1391           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1392                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1393       return;
1394     }
1395   }
1396 
1397   // This was the final opportunity to salvage this debug information, and it
1398   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1399   // any earlier variable location.
1400   assert(OrigV && "V shouldn't be null");
1401   auto *Undef = UndefValue::get(OrigV->getType());
1402   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1403   DAG.AddDbgValue(SDV, false);
1404   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << printDDI(DDI)
1405                     << "\n");
1406 }
1407 
1408 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1409                                            DILocalVariable *Var,
1410                                            DIExpression *Expr, DebugLoc DbgLoc,
1411                                            unsigned Order, bool IsVariadic) {
1412   if (Values.empty())
1413     return true;
1414   SmallVector<SDDbgOperand> LocationOps;
1415   SmallVector<SDNode *> Dependencies;
1416   for (const Value *V : Values) {
1417     // Constant value.
1418     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1419         isa<ConstantPointerNull>(V)) {
1420       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1421       continue;
1422     }
1423 
1424     // Look through IntToPtr constants.
1425     if (auto *CE = dyn_cast<ConstantExpr>(V))
1426       if (CE->getOpcode() == Instruction::IntToPtr) {
1427         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1428         continue;
1429       }
1430 
1431     // If the Value is a frame index, we can create a FrameIndex debug value
1432     // without relying on the DAG at all.
1433     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1434       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1435       if (SI != FuncInfo.StaticAllocaMap.end()) {
1436         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1437         continue;
1438       }
1439     }
1440 
1441     // Do not use getValue() in here; we don't want to generate code at
1442     // this point if it hasn't been done yet.
1443     SDValue N = NodeMap[V];
1444     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1445       N = UnusedArgNodeMap[V];
1446     if (N.getNode()) {
1447       // Only emit func arg dbg value for non-variadic dbg.values for now.
1448       if (!IsVariadic &&
1449           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1450                                    FuncArgumentDbgValueKind::Value, N))
1451         return true;
1452       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1453         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1454         // describe stack slot locations.
1455         //
1456         // Consider "int x = 0; int *px = &x;". There are two kinds of
1457         // interesting debug values here after optimization:
1458         //
1459         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1460         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1461         //
1462         // Both describe the direct values of their associated variables.
1463         Dependencies.push_back(N.getNode());
1464         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1465         continue;
1466       }
1467       LocationOps.emplace_back(
1468           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1469       continue;
1470     }
1471 
1472     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1473     // Special rules apply for the first dbg.values of parameter variables in a
1474     // function. Identify them by the fact they reference Argument Values, that
1475     // they're parameters, and they are parameters of the current function. We
1476     // need to let them dangle until they get an SDNode.
1477     bool IsParamOfFunc =
1478         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1479     if (IsParamOfFunc)
1480       return false;
1481 
1482     // The value is not used in this block yet (or it would have an SDNode).
1483     // We still want the value to appear for the user if possible -- if it has
1484     // an associated VReg, we can refer to that instead.
1485     auto VMI = FuncInfo.ValueMap.find(V);
1486     if (VMI != FuncInfo.ValueMap.end()) {
1487       unsigned Reg = VMI->second;
1488       // If this is a PHI node, it may be split up into several MI PHI nodes
1489       // (in FunctionLoweringInfo::set).
1490       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1491                        V->getType(), std::nullopt);
1492       if (RFV.occupiesMultipleRegs()) {
1493         // FIXME: We could potentially support variadic dbg_values here.
1494         if (IsVariadic)
1495           return false;
1496         unsigned Offset = 0;
1497         unsigned BitsToDescribe = 0;
1498         if (auto VarSize = Var->getSizeInBits())
1499           BitsToDescribe = *VarSize;
1500         if (auto Fragment = Expr->getFragmentInfo())
1501           BitsToDescribe = Fragment->SizeInBits;
1502         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1503           // Bail out if all bits are described already.
1504           if (Offset >= BitsToDescribe)
1505             break;
1506           // TODO: handle scalable vectors.
1507           unsigned RegisterSize = RegAndSize.second;
1508           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1509                                       ? BitsToDescribe - Offset
1510                                       : RegisterSize;
1511           auto FragmentExpr = DIExpression::createFragmentExpression(
1512               Expr, Offset, FragmentSize);
1513           if (!FragmentExpr)
1514             continue;
1515           SDDbgValue *SDV = DAG.getVRegDbgValue(
1516               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1517           DAG.AddDbgValue(SDV, false);
1518           Offset += RegisterSize;
1519         }
1520         return true;
1521       }
1522       // We can use simple vreg locations for variadic dbg_values as well.
1523       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1524       continue;
1525     }
1526     // We failed to create a SDDbgOperand for V.
1527     return false;
1528   }
1529 
1530   // We have created a SDDbgOperand for each Value in Values.
1531   // Should use Order instead of SDNodeOrder?
1532   assert(!LocationOps.empty());
1533   SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1534                                         /*IsIndirect=*/false, DbgLoc,
1535                                         SDNodeOrder, IsVariadic);
1536   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1537   return true;
1538 }
1539 
1540 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1541   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1542   for (auto &Pair : DanglingDebugInfoMap)
1543     for (auto &DDI : Pair.second)
1544       salvageUnresolvedDbgValue(DDI);
1545   clearDanglingDebugInfo();
1546 }
1547 
1548 /// getCopyFromRegs - If there was virtual register allocated for the value V
1549 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1550 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1551   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1552   SDValue Result;
1553 
1554   if (It != FuncInfo.ValueMap.end()) {
1555     Register InReg = It->second;
1556 
1557     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1558                      DAG.getDataLayout(), InReg, Ty,
1559                      std::nullopt); // This is not an ABI copy.
1560     SDValue Chain = DAG.getEntryNode();
1561     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1562                                  V);
1563     resolveDanglingDebugInfo(V, Result);
1564   }
1565 
1566   return Result;
1567 }
1568 
1569 /// getValue - Return an SDValue for the given Value.
1570 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1571   // If we already have an SDValue for this value, use it. It's important
1572   // to do this first, so that we don't create a CopyFromReg if we already
1573   // have a regular SDValue.
1574   SDValue &N = NodeMap[V];
1575   if (N.getNode()) return N;
1576 
1577   // If there's a virtual register allocated and initialized for this
1578   // value, use it.
1579   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1580     return copyFromReg;
1581 
1582   // Otherwise create a new SDValue and remember it.
1583   SDValue Val = getValueImpl(V);
1584   NodeMap[V] = Val;
1585   resolveDanglingDebugInfo(V, Val);
1586   return Val;
1587 }
1588 
1589 /// getNonRegisterValue - Return an SDValue for the given Value, but
1590 /// don't look in FuncInfo.ValueMap for a virtual register.
1591 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1592   // If we already have an SDValue for this value, use it.
1593   SDValue &N = NodeMap[V];
1594   if (N.getNode()) {
1595     if (isIntOrFPConstant(N)) {
1596       // Remove the debug location from the node as the node is about to be used
1597       // in a location which may differ from the original debug location.  This
1598       // is relevant to Constant and ConstantFP nodes because they can appear
1599       // as constant expressions inside PHI nodes.
1600       N->setDebugLoc(DebugLoc());
1601     }
1602     return N;
1603   }
1604 
1605   // Otherwise create a new SDValue and remember it.
1606   SDValue Val = getValueImpl(V);
1607   NodeMap[V] = Val;
1608   resolveDanglingDebugInfo(V, Val);
1609   return Val;
1610 }
1611 
1612 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1613 /// Create an SDValue for the given value.
1614 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1615   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1616 
1617   if (const Constant *C = dyn_cast<Constant>(V)) {
1618     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1619 
1620     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1621       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1622 
1623     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1624       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1625 
1626     if (isa<ConstantPointerNull>(C)) {
1627       unsigned AS = V->getType()->getPointerAddressSpace();
1628       return DAG.getConstant(0, getCurSDLoc(),
1629                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1630     }
1631 
1632     if (match(C, m_VScale()))
1633       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1634 
1635     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1636       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1637 
1638     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1639       return DAG.getUNDEF(VT);
1640 
1641     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1642       visit(CE->getOpcode(), *CE);
1643       SDValue N1 = NodeMap[V];
1644       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1645       return N1;
1646     }
1647 
1648     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1649       SmallVector<SDValue, 4> Constants;
1650       for (const Use &U : C->operands()) {
1651         SDNode *Val = getValue(U).getNode();
1652         // If the operand is an empty aggregate, there are no values.
1653         if (!Val) continue;
1654         // Add each leaf value from the operand to the Constants list
1655         // to form a flattened list of all the values.
1656         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1657           Constants.push_back(SDValue(Val, i));
1658       }
1659 
1660       return DAG.getMergeValues(Constants, getCurSDLoc());
1661     }
1662 
1663     if (const ConstantDataSequential *CDS =
1664           dyn_cast<ConstantDataSequential>(C)) {
1665       SmallVector<SDValue, 4> Ops;
1666       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1667         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1668         // Add each leaf value from the operand to the Constants list
1669         // to form a flattened list of all the values.
1670         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1671           Ops.push_back(SDValue(Val, i));
1672       }
1673 
1674       if (isa<ArrayType>(CDS->getType()))
1675         return DAG.getMergeValues(Ops, getCurSDLoc());
1676       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1677     }
1678 
1679     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1680       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1681              "Unknown struct or array constant!");
1682 
1683       SmallVector<EVT, 4> ValueVTs;
1684       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1685       unsigned NumElts = ValueVTs.size();
1686       if (NumElts == 0)
1687         return SDValue(); // empty struct
1688       SmallVector<SDValue, 4> Constants(NumElts);
1689       for (unsigned i = 0; i != NumElts; ++i) {
1690         EVT EltVT = ValueVTs[i];
1691         if (isa<UndefValue>(C))
1692           Constants[i] = DAG.getUNDEF(EltVT);
1693         else if (EltVT.isFloatingPoint())
1694           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1695         else
1696           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1697       }
1698 
1699       return DAG.getMergeValues(Constants, getCurSDLoc());
1700     }
1701 
1702     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1703       return DAG.getBlockAddress(BA, VT);
1704 
1705     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1706       return getValue(Equiv->getGlobalValue());
1707 
1708     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1709       return getValue(NC->getGlobalValue());
1710 
1711     VectorType *VecTy = cast<VectorType>(V->getType());
1712 
1713     // Now that we know the number and type of the elements, get that number of
1714     // elements into the Ops array based on what kind of constant it is.
1715     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1716       SmallVector<SDValue, 16> Ops;
1717       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1718       for (unsigned i = 0; i != NumElements; ++i)
1719         Ops.push_back(getValue(CV->getOperand(i)));
1720 
1721       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1722     }
1723 
1724     if (isa<ConstantAggregateZero>(C)) {
1725       EVT EltVT =
1726           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1727 
1728       SDValue Op;
1729       if (EltVT.isFloatingPoint())
1730         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1731       else
1732         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1733 
1734       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1735     }
1736 
1737     llvm_unreachable("Unknown vector constant");
1738   }
1739 
1740   // If this is a static alloca, generate it as the frameindex instead of
1741   // computation.
1742   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1743     DenseMap<const AllocaInst*, int>::iterator SI =
1744       FuncInfo.StaticAllocaMap.find(AI);
1745     if (SI != FuncInfo.StaticAllocaMap.end())
1746       return DAG.getFrameIndex(
1747           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1748   }
1749 
1750   // If this is an instruction which fast-isel has deferred, select it now.
1751   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1752     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1753 
1754     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1755                      Inst->getType(), std::nullopt);
1756     SDValue Chain = DAG.getEntryNode();
1757     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1758   }
1759 
1760   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1761     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1762 
1763   if (const auto *BB = dyn_cast<BasicBlock>(V))
1764     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1765 
1766   llvm_unreachable("Can't get register for value!");
1767 }
1768 
1769 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1770   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1771   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1772   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1773   bool IsSEH = isAsynchronousEHPersonality(Pers);
1774   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1775   if (!IsSEH)
1776     CatchPadMBB->setIsEHScopeEntry();
1777   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1778   if (IsMSVCCXX || IsCoreCLR)
1779     CatchPadMBB->setIsEHFuncletEntry();
1780 }
1781 
1782 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1783   // Update machine-CFG edge.
1784   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1785   FuncInfo.MBB->addSuccessor(TargetMBB);
1786   TargetMBB->setIsEHCatchretTarget(true);
1787   DAG.getMachineFunction().setHasEHCatchret(true);
1788 
1789   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1790   bool IsSEH = isAsynchronousEHPersonality(Pers);
1791   if (IsSEH) {
1792     // If this is not a fall-through branch or optimizations are switched off,
1793     // emit the branch.
1794     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1795         TM.getOptLevel() == CodeGenOpt::None)
1796       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1797                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1798     return;
1799   }
1800 
1801   // Figure out the funclet membership for the catchret's successor.
1802   // This will be used by the FuncletLayout pass to determine how to order the
1803   // BB's.
1804   // A 'catchret' returns to the outer scope's color.
1805   Value *ParentPad = I.getCatchSwitchParentPad();
1806   const BasicBlock *SuccessorColor;
1807   if (isa<ConstantTokenNone>(ParentPad))
1808     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1809   else
1810     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1811   assert(SuccessorColor && "No parent funclet for catchret!");
1812   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1813   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1814 
1815   // Create the terminator node.
1816   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1817                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1818                             DAG.getBasicBlock(SuccessorColorMBB));
1819   DAG.setRoot(Ret);
1820 }
1821 
1822 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1823   // Don't emit any special code for the cleanuppad instruction. It just marks
1824   // the start of an EH scope/funclet.
1825   FuncInfo.MBB->setIsEHScopeEntry();
1826   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1827   if (Pers != EHPersonality::Wasm_CXX) {
1828     FuncInfo.MBB->setIsEHFuncletEntry();
1829     FuncInfo.MBB->setIsCleanupFuncletEntry();
1830   }
1831 }
1832 
1833 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1834 // not match, it is OK to add only the first unwind destination catchpad to the
1835 // successors, because there will be at least one invoke instruction within the
1836 // catch scope that points to the next unwind destination, if one exists, so
1837 // CFGSort cannot mess up with BB sorting order.
1838 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1839 // call within them, and catchpads only consisting of 'catch (...)' have a
1840 // '__cxa_end_catch' call within them, both of which generate invokes in case
1841 // the next unwind destination exists, i.e., the next unwind destination is not
1842 // the caller.)
1843 //
1844 // Having at most one EH pad successor is also simpler and helps later
1845 // transformations.
1846 //
1847 // For example,
1848 // current:
1849 //   invoke void @foo to ... unwind label %catch.dispatch
1850 // catch.dispatch:
1851 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1852 // catch.start:
1853 //   ...
1854 //   ... in this BB or some other child BB dominated by this BB there will be an
1855 //   invoke that points to 'next' BB as an unwind destination
1856 //
1857 // next: ; We don't need to add this to 'current' BB's successor
1858 //   ...
1859 static void findWasmUnwindDestinations(
1860     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1861     BranchProbability Prob,
1862     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1863         &UnwindDests) {
1864   while (EHPadBB) {
1865     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1866     if (isa<CleanupPadInst>(Pad)) {
1867       // Stop on cleanup pads.
1868       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1869       UnwindDests.back().first->setIsEHScopeEntry();
1870       break;
1871     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1872       // Add the catchpad handlers to the possible destinations. We don't
1873       // continue to the unwind destination of the catchswitch for wasm.
1874       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1875         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1876         UnwindDests.back().first->setIsEHScopeEntry();
1877       }
1878       break;
1879     } else {
1880       continue;
1881     }
1882   }
1883 }
1884 
1885 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1886 /// many places it could ultimately go. In the IR, we have a single unwind
1887 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1888 /// This function skips over imaginary basic blocks that hold catchswitch
1889 /// instructions, and finds all the "real" machine
1890 /// basic block destinations. As those destinations may not be successors of
1891 /// EHPadBB, here we also calculate the edge probability to those destinations.
1892 /// The passed-in Prob is the edge probability to EHPadBB.
1893 static void findUnwindDestinations(
1894     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1895     BranchProbability Prob,
1896     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1897         &UnwindDests) {
1898   EHPersonality Personality =
1899     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1900   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1901   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1902   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1903   bool IsSEH = isAsynchronousEHPersonality(Personality);
1904 
1905   if (IsWasmCXX) {
1906     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1907     assert(UnwindDests.size() <= 1 &&
1908            "There should be at most one unwind destination for wasm");
1909     return;
1910   }
1911 
1912   while (EHPadBB) {
1913     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1914     BasicBlock *NewEHPadBB = nullptr;
1915     if (isa<LandingPadInst>(Pad)) {
1916       // Stop on landingpads. They are not funclets.
1917       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1918       break;
1919     } else if (isa<CleanupPadInst>(Pad)) {
1920       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1921       // personalities.
1922       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1923       UnwindDests.back().first->setIsEHScopeEntry();
1924       UnwindDests.back().first->setIsEHFuncletEntry();
1925       break;
1926     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1927       // Add the catchpad handlers to the possible destinations.
1928       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1929         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1930         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1931         if (IsMSVCCXX || IsCoreCLR)
1932           UnwindDests.back().first->setIsEHFuncletEntry();
1933         if (!IsSEH)
1934           UnwindDests.back().first->setIsEHScopeEntry();
1935       }
1936       NewEHPadBB = CatchSwitch->getUnwindDest();
1937     } else {
1938       continue;
1939     }
1940 
1941     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1942     if (BPI && NewEHPadBB)
1943       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1944     EHPadBB = NewEHPadBB;
1945   }
1946 }
1947 
1948 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1949   // Update successor info.
1950   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1951   auto UnwindDest = I.getUnwindDest();
1952   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1953   BranchProbability UnwindDestProb =
1954       (BPI && UnwindDest)
1955           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1956           : BranchProbability::getZero();
1957   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1958   for (auto &UnwindDest : UnwindDests) {
1959     UnwindDest.first->setIsEHPad();
1960     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1961   }
1962   FuncInfo.MBB->normalizeSuccProbs();
1963 
1964   // Create the terminator node.
1965   SDValue Ret =
1966       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1967   DAG.setRoot(Ret);
1968 }
1969 
1970 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1971   report_fatal_error("visitCatchSwitch not yet implemented!");
1972 }
1973 
1974 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1975   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1976   auto &DL = DAG.getDataLayout();
1977   SDValue Chain = getControlRoot();
1978   SmallVector<ISD::OutputArg, 8> Outs;
1979   SmallVector<SDValue, 8> OutVals;
1980 
1981   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1982   // lower
1983   //
1984   //   %val = call <ty> @llvm.experimental.deoptimize()
1985   //   ret <ty> %val
1986   //
1987   // differently.
1988   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1989     LowerDeoptimizingReturn();
1990     return;
1991   }
1992 
1993   if (!FuncInfo.CanLowerReturn) {
1994     unsigned DemoteReg = FuncInfo.DemoteRegister;
1995     const Function *F = I.getParent()->getParent();
1996 
1997     // Emit a store of the return value through the virtual register.
1998     // Leave Outs empty so that LowerReturn won't try to load return
1999     // registers the usual way.
2000     SmallVector<EVT, 1> PtrValueVTs;
2001     ComputeValueVTs(TLI, DL,
2002                     F->getReturnType()->getPointerTo(
2003                         DAG.getDataLayout().getAllocaAddrSpace()),
2004                     PtrValueVTs);
2005 
2006     SDValue RetPtr =
2007         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2008     SDValue RetOp = getValue(I.getOperand(0));
2009 
2010     SmallVector<EVT, 4> ValueVTs, MemVTs;
2011     SmallVector<uint64_t, 4> Offsets;
2012     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2013                     &Offsets);
2014     unsigned NumValues = ValueVTs.size();
2015 
2016     SmallVector<SDValue, 4> Chains(NumValues);
2017     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2018     for (unsigned i = 0; i != NumValues; ++i) {
2019       // An aggregate return value cannot wrap around the address space, so
2020       // offsets to its parts don't wrap either.
2021       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2022                                            TypeSize::Fixed(Offsets[i]));
2023 
2024       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2025       if (MemVTs[i] != ValueVTs[i])
2026         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2027       Chains[i] = DAG.getStore(
2028           Chain, getCurSDLoc(), Val,
2029           // FIXME: better loc info would be nice.
2030           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2031           commonAlignment(BaseAlign, Offsets[i]));
2032     }
2033 
2034     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2035                         MVT::Other, Chains);
2036   } else if (I.getNumOperands() != 0) {
2037     SmallVector<EVT, 4> ValueVTs;
2038     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2039     unsigned NumValues = ValueVTs.size();
2040     if (NumValues) {
2041       SDValue RetOp = getValue(I.getOperand(0));
2042 
2043       const Function *F = I.getParent()->getParent();
2044 
2045       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2046           I.getOperand(0)->getType(), F->getCallingConv(),
2047           /*IsVarArg*/ false, DL);
2048 
2049       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2050       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2051         ExtendKind = ISD::SIGN_EXTEND;
2052       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2053         ExtendKind = ISD::ZERO_EXTEND;
2054 
2055       LLVMContext &Context = F->getContext();
2056       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2057 
2058       for (unsigned j = 0; j != NumValues; ++j) {
2059         EVT VT = ValueVTs[j];
2060 
2061         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2062           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2063 
2064         CallingConv::ID CC = F->getCallingConv();
2065 
2066         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2067         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2068         SmallVector<SDValue, 4> Parts(NumParts);
2069         getCopyToParts(DAG, getCurSDLoc(),
2070                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2071                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2072 
2073         // 'inreg' on function refers to return value
2074         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2075         if (RetInReg)
2076           Flags.setInReg();
2077 
2078         if (I.getOperand(0)->getType()->isPointerTy()) {
2079           Flags.setPointer();
2080           Flags.setPointerAddrSpace(
2081               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2082         }
2083 
2084         if (NeedsRegBlock) {
2085           Flags.setInConsecutiveRegs();
2086           if (j == NumValues - 1)
2087             Flags.setInConsecutiveRegsLast();
2088         }
2089 
2090         // Propagate extension type if any
2091         if (ExtendKind == ISD::SIGN_EXTEND)
2092           Flags.setSExt();
2093         else if (ExtendKind == ISD::ZERO_EXTEND)
2094           Flags.setZExt();
2095 
2096         for (unsigned i = 0; i < NumParts; ++i) {
2097           Outs.push_back(ISD::OutputArg(Flags,
2098                                         Parts[i].getValueType().getSimpleVT(),
2099                                         VT, /*isfixed=*/true, 0, 0));
2100           OutVals.push_back(Parts[i]);
2101         }
2102       }
2103     }
2104   }
2105 
2106   // Push in swifterror virtual register as the last element of Outs. This makes
2107   // sure swifterror virtual register will be returned in the swifterror
2108   // physical register.
2109   const Function *F = I.getParent()->getParent();
2110   if (TLI.supportSwiftError() &&
2111       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2112     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2113     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2114     Flags.setSwiftError();
2115     Outs.push_back(ISD::OutputArg(
2116         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2117         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2118     // Create SDNode for the swifterror virtual register.
2119     OutVals.push_back(
2120         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2121                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2122                         EVT(TLI.getPointerTy(DL))));
2123   }
2124 
2125   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2126   CallingConv::ID CallConv =
2127     DAG.getMachineFunction().getFunction().getCallingConv();
2128   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2129       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2130 
2131   // Verify that the target's LowerReturn behaved as expected.
2132   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2133          "LowerReturn didn't return a valid chain!");
2134 
2135   // Update the DAG with the new chain value resulting from return lowering.
2136   DAG.setRoot(Chain);
2137 }
2138 
2139 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2140 /// created for it, emit nodes to copy the value into the virtual
2141 /// registers.
2142 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2143   // Skip empty types
2144   if (V->getType()->isEmptyTy())
2145     return;
2146 
2147   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2148   if (VMI != FuncInfo.ValueMap.end()) {
2149     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2150            "Unused value assigned virtual registers!");
2151     CopyValueToVirtualRegister(V, VMI->second);
2152   }
2153 }
2154 
2155 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2156 /// the current basic block, add it to ValueMap now so that we'll get a
2157 /// CopyTo/FromReg.
2158 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2159   // No need to export constants.
2160   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2161 
2162   // Already exported?
2163   if (FuncInfo.isExportedInst(V)) return;
2164 
2165   Register Reg = FuncInfo.InitializeRegForValue(V);
2166   CopyValueToVirtualRegister(V, Reg);
2167 }
2168 
2169 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2170                                                      const BasicBlock *FromBB) {
2171   // The operands of the setcc have to be in this block.  We don't know
2172   // how to export them from some other block.
2173   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2174     // Can export from current BB.
2175     if (VI->getParent() == FromBB)
2176       return true;
2177 
2178     // Is already exported, noop.
2179     return FuncInfo.isExportedInst(V);
2180   }
2181 
2182   // If this is an argument, we can export it if the BB is the entry block or
2183   // if it is already exported.
2184   if (isa<Argument>(V)) {
2185     if (FromBB->isEntryBlock())
2186       return true;
2187 
2188     // Otherwise, can only export this if it is already exported.
2189     return FuncInfo.isExportedInst(V);
2190   }
2191 
2192   // Otherwise, constants can always be exported.
2193   return true;
2194 }
2195 
2196 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2197 BranchProbability
2198 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2199                                         const MachineBasicBlock *Dst) const {
2200   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2201   const BasicBlock *SrcBB = Src->getBasicBlock();
2202   const BasicBlock *DstBB = Dst->getBasicBlock();
2203   if (!BPI) {
2204     // If BPI is not available, set the default probability as 1 / N, where N is
2205     // the number of successors.
2206     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2207     return BranchProbability(1, SuccSize);
2208   }
2209   return BPI->getEdgeProbability(SrcBB, DstBB);
2210 }
2211 
2212 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2213                                                MachineBasicBlock *Dst,
2214                                                BranchProbability Prob) {
2215   if (!FuncInfo.BPI)
2216     Src->addSuccessorWithoutProb(Dst);
2217   else {
2218     if (Prob.isUnknown())
2219       Prob = getEdgeProbability(Src, Dst);
2220     Src->addSuccessor(Dst, Prob);
2221   }
2222 }
2223 
2224 static bool InBlock(const Value *V, const BasicBlock *BB) {
2225   if (const Instruction *I = dyn_cast<Instruction>(V))
2226     return I->getParent() == BB;
2227   return true;
2228 }
2229 
2230 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2231 /// This function emits a branch and is used at the leaves of an OR or an
2232 /// AND operator tree.
2233 void
2234 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2235                                                   MachineBasicBlock *TBB,
2236                                                   MachineBasicBlock *FBB,
2237                                                   MachineBasicBlock *CurBB,
2238                                                   MachineBasicBlock *SwitchBB,
2239                                                   BranchProbability TProb,
2240                                                   BranchProbability FProb,
2241                                                   bool InvertCond) {
2242   const BasicBlock *BB = CurBB->getBasicBlock();
2243 
2244   // If the leaf of the tree is a comparison, merge the condition into
2245   // the caseblock.
2246   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2247     // The operands of the cmp have to be in this block.  We don't know
2248     // how to export them from some other block.  If this is the first block
2249     // of the sequence, no exporting is needed.
2250     if (CurBB == SwitchBB ||
2251         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2252          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2253       ISD::CondCode Condition;
2254       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2255         ICmpInst::Predicate Pred =
2256             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2257         Condition = getICmpCondCode(Pred);
2258       } else {
2259         const FCmpInst *FC = cast<FCmpInst>(Cond);
2260         FCmpInst::Predicate Pred =
2261             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2262         Condition = getFCmpCondCode(Pred);
2263         if (TM.Options.NoNaNsFPMath)
2264           Condition = getFCmpCodeWithoutNaN(Condition);
2265       }
2266 
2267       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2268                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2269       SL->SwitchCases.push_back(CB);
2270       return;
2271     }
2272   }
2273 
2274   // Create a CaseBlock record representing this branch.
2275   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2276   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2277                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2278   SL->SwitchCases.push_back(CB);
2279 }
2280 
2281 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2282                                                MachineBasicBlock *TBB,
2283                                                MachineBasicBlock *FBB,
2284                                                MachineBasicBlock *CurBB,
2285                                                MachineBasicBlock *SwitchBB,
2286                                                Instruction::BinaryOps Opc,
2287                                                BranchProbability TProb,
2288                                                BranchProbability FProb,
2289                                                bool InvertCond) {
2290   // Skip over not part of the tree and remember to invert op and operands at
2291   // next level.
2292   Value *NotCond;
2293   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2294       InBlock(NotCond, CurBB->getBasicBlock())) {
2295     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2296                          !InvertCond);
2297     return;
2298   }
2299 
2300   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2301   const Value *BOpOp0, *BOpOp1;
2302   // Compute the effective opcode for Cond, taking into account whether it needs
2303   // to be inverted, e.g.
2304   //   and (not (or A, B)), C
2305   // gets lowered as
2306   //   and (and (not A, not B), C)
2307   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2308   if (BOp) {
2309     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2310                ? Instruction::And
2311                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2312                       ? Instruction::Or
2313                       : (Instruction::BinaryOps)0);
2314     if (InvertCond) {
2315       if (BOpc == Instruction::And)
2316         BOpc = Instruction::Or;
2317       else if (BOpc == Instruction::Or)
2318         BOpc = Instruction::And;
2319     }
2320   }
2321 
2322   // If this node is not part of the or/and tree, emit it as a branch.
2323   // Note that all nodes in the tree should have same opcode.
2324   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2325   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2326       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2327       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2328     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2329                                  TProb, FProb, InvertCond);
2330     return;
2331   }
2332 
2333   //  Create TmpBB after CurBB.
2334   MachineFunction::iterator BBI(CurBB);
2335   MachineFunction &MF = DAG.getMachineFunction();
2336   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2337   CurBB->getParent()->insert(++BBI, TmpBB);
2338 
2339   if (Opc == Instruction::Or) {
2340     // Codegen X | Y as:
2341     // BB1:
2342     //   jmp_if_X TBB
2343     //   jmp TmpBB
2344     // TmpBB:
2345     //   jmp_if_Y TBB
2346     //   jmp FBB
2347     //
2348 
2349     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2350     // The requirement is that
2351     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2352     //     = TrueProb for original BB.
2353     // Assuming the original probabilities are A and B, one choice is to set
2354     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2355     // A/(1+B) and 2B/(1+B). This choice assumes that
2356     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2357     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2358     // TmpBB, but the math is more complicated.
2359 
2360     auto NewTrueProb = TProb / 2;
2361     auto NewFalseProb = TProb / 2 + FProb;
2362     // Emit the LHS condition.
2363     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2364                          NewFalseProb, InvertCond);
2365 
2366     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2367     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2368     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2369     // Emit the RHS condition into TmpBB.
2370     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2371                          Probs[1], InvertCond);
2372   } else {
2373     assert(Opc == Instruction::And && "Unknown merge op!");
2374     // Codegen X & Y as:
2375     // BB1:
2376     //   jmp_if_X TmpBB
2377     //   jmp FBB
2378     // TmpBB:
2379     //   jmp_if_Y TBB
2380     //   jmp FBB
2381     //
2382     //  This requires creation of TmpBB after CurBB.
2383 
2384     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2385     // The requirement is that
2386     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2387     //     = FalseProb for original BB.
2388     // Assuming the original probabilities are A and B, one choice is to set
2389     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2390     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2391     // TrueProb for BB1 * FalseProb for TmpBB.
2392 
2393     auto NewTrueProb = TProb + FProb / 2;
2394     auto NewFalseProb = FProb / 2;
2395     // Emit the LHS condition.
2396     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2397                          NewFalseProb, InvertCond);
2398 
2399     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2400     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2401     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2402     // Emit the RHS condition into TmpBB.
2403     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2404                          Probs[1], InvertCond);
2405   }
2406 }
2407 
2408 /// If the set of cases should be emitted as a series of branches, return true.
2409 /// If we should emit this as a bunch of and/or'd together conditions, return
2410 /// false.
2411 bool
2412 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2413   if (Cases.size() != 2) return true;
2414 
2415   // If this is two comparisons of the same values or'd or and'd together, they
2416   // will get folded into a single comparison, so don't emit two blocks.
2417   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2418        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2419       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2420        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2421     return false;
2422   }
2423 
2424   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2425   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2426   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2427       Cases[0].CC == Cases[1].CC &&
2428       isa<Constant>(Cases[0].CmpRHS) &&
2429       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2430     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2431       return false;
2432     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2433       return false;
2434   }
2435 
2436   return true;
2437 }
2438 
2439 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2440   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2441 
2442   // Update machine-CFG edges.
2443   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2444 
2445   if (I.isUnconditional()) {
2446     // Update machine-CFG edges.
2447     BrMBB->addSuccessor(Succ0MBB);
2448 
2449     // If this is not a fall-through branch or optimizations are switched off,
2450     // emit the branch.
2451     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2452       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2453                               MVT::Other, getControlRoot(),
2454                               DAG.getBasicBlock(Succ0MBB)));
2455 
2456     return;
2457   }
2458 
2459   // If this condition is one of the special cases we handle, do special stuff
2460   // now.
2461   const Value *CondVal = I.getCondition();
2462   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2463 
2464   // If this is a series of conditions that are or'd or and'd together, emit
2465   // this as a sequence of branches instead of setcc's with and/or operations.
2466   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2467   // unpredictable branches, and vector extracts because those jumps are likely
2468   // expensive for any target), this should improve performance.
2469   // For example, instead of something like:
2470   //     cmp A, B
2471   //     C = seteq
2472   //     cmp D, E
2473   //     F = setle
2474   //     or C, F
2475   //     jnz foo
2476   // Emit:
2477   //     cmp A, B
2478   //     je foo
2479   //     cmp D, E
2480   //     jle foo
2481   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2482   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2483       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2484     Value *Vec;
2485     const Value *BOp0, *BOp1;
2486     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2487     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2488       Opcode = Instruction::And;
2489     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2490       Opcode = Instruction::Or;
2491 
2492     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2493                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2494       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2495                            getEdgeProbability(BrMBB, Succ0MBB),
2496                            getEdgeProbability(BrMBB, Succ1MBB),
2497                            /*InvertCond=*/false);
2498       // If the compares in later blocks need to use values not currently
2499       // exported from this block, export them now.  This block should always
2500       // be the first entry.
2501       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2502 
2503       // Allow some cases to be rejected.
2504       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2505         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2506           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2507           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2508         }
2509 
2510         // Emit the branch for this block.
2511         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2512         SL->SwitchCases.erase(SL->SwitchCases.begin());
2513         return;
2514       }
2515 
2516       // Okay, we decided not to do this, remove any inserted MBB's and clear
2517       // SwitchCases.
2518       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2519         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2520 
2521       SL->SwitchCases.clear();
2522     }
2523   }
2524 
2525   // Create a CaseBlock record representing this branch.
2526   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2527                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2528 
2529   // Use visitSwitchCase to actually insert the fast branch sequence for this
2530   // cond branch.
2531   visitSwitchCase(CB, BrMBB);
2532 }
2533 
2534 /// visitSwitchCase - Emits the necessary code to represent a single node in
2535 /// the binary search tree resulting from lowering a switch instruction.
2536 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2537                                           MachineBasicBlock *SwitchBB) {
2538   SDValue Cond;
2539   SDValue CondLHS = getValue(CB.CmpLHS);
2540   SDLoc dl = CB.DL;
2541 
2542   if (CB.CC == ISD::SETTRUE) {
2543     // Branch or fall through to TrueBB.
2544     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2545     SwitchBB->normalizeSuccProbs();
2546     if (CB.TrueBB != NextBlock(SwitchBB)) {
2547       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2548                               DAG.getBasicBlock(CB.TrueBB)));
2549     }
2550     return;
2551   }
2552 
2553   auto &TLI = DAG.getTargetLoweringInfo();
2554   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2555 
2556   // Build the setcc now.
2557   if (!CB.CmpMHS) {
2558     // Fold "(X == true)" to X and "(X == false)" to !X to
2559     // handle common cases produced by branch lowering.
2560     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2561         CB.CC == ISD::SETEQ)
2562       Cond = CondLHS;
2563     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2564              CB.CC == ISD::SETEQ) {
2565       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2566       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2567     } else {
2568       SDValue CondRHS = getValue(CB.CmpRHS);
2569 
2570       // If a pointer's DAG type is larger than its memory type then the DAG
2571       // values are zero-extended. This breaks signed comparisons so truncate
2572       // back to the underlying type before doing the compare.
2573       if (CondLHS.getValueType() != MemVT) {
2574         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2575         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2576       }
2577       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2578     }
2579   } else {
2580     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2581 
2582     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2583     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2584 
2585     SDValue CmpOp = getValue(CB.CmpMHS);
2586     EVT VT = CmpOp.getValueType();
2587 
2588     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2589       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2590                           ISD::SETLE);
2591     } else {
2592       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2593                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2594       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2595                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2596     }
2597   }
2598 
2599   // Update successor info
2600   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2601   // TrueBB and FalseBB are always different unless the incoming IR is
2602   // degenerate. This only happens when running llc on weird IR.
2603   if (CB.TrueBB != CB.FalseBB)
2604     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2605   SwitchBB->normalizeSuccProbs();
2606 
2607   // If the lhs block is the next block, invert the condition so that we can
2608   // fall through to the lhs instead of the rhs block.
2609   if (CB.TrueBB == NextBlock(SwitchBB)) {
2610     std::swap(CB.TrueBB, CB.FalseBB);
2611     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2612     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2613   }
2614 
2615   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2616                                MVT::Other, getControlRoot(), Cond,
2617                                DAG.getBasicBlock(CB.TrueBB));
2618 
2619   setValue(CurInst, BrCond);
2620 
2621   // Insert the false branch. Do this even if it's a fall through branch,
2622   // this makes it easier to do DAG optimizations which require inverting
2623   // the branch condition.
2624   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2625                        DAG.getBasicBlock(CB.FalseBB));
2626 
2627   DAG.setRoot(BrCond);
2628 }
2629 
2630 /// visitJumpTable - Emit JumpTable node in the current MBB
2631 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2632   // Emit the code for the jump table
2633   assert(JT.Reg != -1U && "Should lower JT Header first!");
2634   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2635   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2636                                      JT.Reg, PTy);
2637   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2638   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2639                                     MVT::Other, Index.getValue(1),
2640                                     Table, Index);
2641   DAG.setRoot(BrJumpTable);
2642 }
2643 
2644 /// visitJumpTableHeader - This function emits necessary code to produce index
2645 /// in the JumpTable from switch case.
2646 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2647                                                JumpTableHeader &JTH,
2648                                                MachineBasicBlock *SwitchBB) {
2649   SDLoc dl = getCurSDLoc();
2650 
2651   // Subtract the lowest switch case value from the value being switched on.
2652   SDValue SwitchOp = getValue(JTH.SValue);
2653   EVT VT = SwitchOp.getValueType();
2654   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2655                             DAG.getConstant(JTH.First, dl, VT));
2656 
2657   // The SDNode we just created, which holds the value being switched on minus
2658   // the smallest case value, needs to be copied to a virtual register so it
2659   // can be used as an index into the jump table in a subsequent basic block.
2660   // This value may be smaller or larger than the target's pointer type, and
2661   // therefore require extension or truncating.
2662   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2663   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2664 
2665   unsigned JumpTableReg =
2666       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2667   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2668                                     JumpTableReg, SwitchOp);
2669   JT.Reg = JumpTableReg;
2670 
2671   if (!JTH.FallthroughUnreachable) {
2672     // Emit the range check for the jump table, and branch to the default block
2673     // for the switch statement if the value being switched on exceeds the
2674     // largest case in the switch.
2675     SDValue CMP = DAG.getSetCC(
2676         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2677                                    Sub.getValueType()),
2678         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2679 
2680     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2681                                  MVT::Other, CopyTo, CMP,
2682                                  DAG.getBasicBlock(JT.Default));
2683 
2684     // Avoid emitting unnecessary branches to the next block.
2685     if (JT.MBB != NextBlock(SwitchBB))
2686       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2687                            DAG.getBasicBlock(JT.MBB));
2688 
2689     DAG.setRoot(BrCond);
2690   } else {
2691     // Avoid emitting unnecessary branches to the next block.
2692     if (JT.MBB != NextBlock(SwitchBB))
2693       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2694                               DAG.getBasicBlock(JT.MBB)));
2695     else
2696       DAG.setRoot(CopyTo);
2697   }
2698 }
2699 
2700 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2701 /// variable if there exists one.
2702 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2703                                  SDValue &Chain) {
2704   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2705   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2706   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2707   MachineFunction &MF = DAG.getMachineFunction();
2708   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2709   MachineSDNode *Node =
2710       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2711   if (Global) {
2712     MachinePointerInfo MPInfo(Global);
2713     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2714                  MachineMemOperand::MODereferenceable;
2715     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2716         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2717     DAG.setNodeMemRefs(Node, {MemRef});
2718   }
2719   if (PtrTy != PtrMemTy)
2720     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2721   return SDValue(Node, 0);
2722 }
2723 
2724 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2725 /// tail spliced into a stack protector check success bb.
2726 ///
2727 /// For a high level explanation of how this fits into the stack protector
2728 /// generation see the comment on the declaration of class
2729 /// StackProtectorDescriptor.
2730 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2731                                                   MachineBasicBlock *ParentBB) {
2732 
2733   // First create the loads to the guard/stack slot for the comparison.
2734   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2735   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2736   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2737 
2738   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2739   int FI = MFI.getStackProtectorIndex();
2740 
2741   SDValue Guard;
2742   SDLoc dl = getCurSDLoc();
2743   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2744   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2745   Align Align =
2746       DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2747 
2748   // Generate code to load the content of the guard slot.
2749   SDValue GuardVal = DAG.getLoad(
2750       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2751       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2752       MachineMemOperand::MOVolatile);
2753 
2754   if (TLI.useStackGuardXorFP())
2755     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2756 
2757   // Retrieve guard check function, nullptr if instrumentation is inlined.
2758   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2759     // The target provides a guard check function to validate the guard value.
2760     // Generate a call to that function with the content of the guard slot as
2761     // argument.
2762     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2763     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2764 
2765     TargetLowering::ArgListTy Args;
2766     TargetLowering::ArgListEntry Entry;
2767     Entry.Node = GuardVal;
2768     Entry.Ty = FnTy->getParamType(0);
2769     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2770       Entry.IsInReg = true;
2771     Args.push_back(Entry);
2772 
2773     TargetLowering::CallLoweringInfo CLI(DAG);
2774     CLI.setDebugLoc(getCurSDLoc())
2775         .setChain(DAG.getEntryNode())
2776         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2777                    getValue(GuardCheckFn), std::move(Args));
2778 
2779     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2780     DAG.setRoot(Result.second);
2781     return;
2782   }
2783 
2784   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2785   // Otherwise, emit a volatile load to retrieve the stack guard value.
2786   SDValue Chain = DAG.getEntryNode();
2787   if (TLI.useLoadStackGuardNode()) {
2788     Guard = getLoadStackGuard(DAG, dl, Chain);
2789   } else {
2790     const Value *IRGuard = TLI.getSDagStackGuard(M);
2791     SDValue GuardPtr = getValue(IRGuard);
2792 
2793     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2794                         MachinePointerInfo(IRGuard, 0), Align,
2795                         MachineMemOperand::MOVolatile);
2796   }
2797 
2798   // Perform the comparison via a getsetcc.
2799   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2800                                                         *DAG.getContext(),
2801                                                         Guard.getValueType()),
2802                              Guard, GuardVal, ISD::SETNE);
2803 
2804   // If the guard/stackslot do not equal, branch to failure MBB.
2805   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2806                                MVT::Other, GuardVal.getOperand(0),
2807                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2808   // Otherwise branch to success MBB.
2809   SDValue Br = DAG.getNode(ISD::BR, dl,
2810                            MVT::Other, BrCond,
2811                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2812 
2813   DAG.setRoot(Br);
2814 }
2815 
2816 /// Codegen the failure basic block for a stack protector check.
2817 ///
2818 /// A failure stack protector machine basic block consists simply of a call to
2819 /// __stack_chk_fail().
2820 ///
2821 /// For a high level explanation of how this fits into the stack protector
2822 /// generation see the comment on the declaration of class
2823 /// StackProtectorDescriptor.
2824 void
2825 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2826   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2827   TargetLowering::MakeLibCallOptions CallOptions;
2828   CallOptions.setDiscardResult(true);
2829   SDValue Chain =
2830       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2831                       std::nullopt, CallOptions, getCurSDLoc())
2832           .second;
2833   // On PS4/PS5, the "return address" must still be within the calling
2834   // function, even if it's at the very end, so emit an explicit TRAP here.
2835   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2836   if (TM.getTargetTriple().isPS())
2837     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2838   // WebAssembly needs an unreachable instruction after a non-returning call,
2839   // because the function return type can be different from __stack_chk_fail's
2840   // return type (void).
2841   if (TM.getTargetTriple().isWasm())
2842     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2843 
2844   DAG.setRoot(Chain);
2845 }
2846 
2847 /// visitBitTestHeader - This function emits necessary code to produce value
2848 /// suitable for "bit tests"
2849 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2850                                              MachineBasicBlock *SwitchBB) {
2851   SDLoc dl = getCurSDLoc();
2852 
2853   // Subtract the minimum value.
2854   SDValue SwitchOp = getValue(B.SValue);
2855   EVT VT = SwitchOp.getValueType();
2856   SDValue RangeSub =
2857       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2858 
2859   // Determine the type of the test operands.
2860   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2861   bool UsePtrType = false;
2862   if (!TLI.isTypeLegal(VT)) {
2863     UsePtrType = true;
2864   } else {
2865     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2866       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2867         // Switch table case range are encoded into series of masks.
2868         // Just use pointer type, it's guaranteed to fit.
2869         UsePtrType = true;
2870         break;
2871       }
2872   }
2873   SDValue Sub = RangeSub;
2874   if (UsePtrType) {
2875     VT = TLI.getPointerTy(DAG.getDataLayout());
2876     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2877   }
2878 
2879   B.RegVT = VT.getSimpleVT();
2880   B.Reg = FuncInfo.CreateReg(B.RegVT);
2881   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2882 
2883   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2884 
2885   if (!B.FallthroughUnreachable)
2886     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2887   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2888   SwitchBB->normalizeSuccProbs();
2889 
2890   SDValue Root = CopyTo;
2891   if (!B.FallthroughUnreachable) {
2892     // Conditional branch to the default block.
2893     SDValue RangeCmp = DAG.getSetCC(dl,
2894         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2895                                RangeSub.getValueType()),
2896         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2897         ISD::SETUGT);
2898 
2899     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2900                        DAG.getBasicBlock(B.Default));
2901   }
2902 
2903   // Avoid emitting unnecessary branches to the next block.
2904   if (MBB != NextBlock(SwitchBB))
2905     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2906 
2907   DAG.setRoot(Root);
2908 }
2909 
2910 /// visitBitTestCase - this function produces one "bit test"
2911 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2912                                            MachineBasicBlock* NextMBB,
2913                                            BranchProbability BranchProbToNext,
2914                                            unsigned Reg,
2915                                            BitTestCase &B,
2916                                            MachineBasicBlock *SwitchBB) {
2917   SDLoc dl = getCurSDLoc();
2918   MVT VT = BB.RegVT;
2919   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2920   SDValue Cmp;
2921   unsigned PopCount = llvm::popcount(B.Mask);
2922   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2923   if (PopCount == 1) {
2924     // Testing for a single bit; just compare the shift count with what it
2925     // would need to be to shift a 1 bit in that position.
2926     Cmp = DAG.getSetCC(
2927         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2928         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
2929         ISD::SETEQ);
2930   } else if (PopCount == BB.Range) {
2931     // There is only one zero bit in the range, test for it directly.
2932     Cmp = DAG.getSetCC(
2933         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2934         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
2935   } else {
2936     // Make desired shift
2937     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2938                                     DAG.getConstant(1, dl, VT), ShiftOp);
2939 
2940     // Emit bit tests and jumps
2941     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2942                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2943     Cmp = DAG.getSetCC(
2944         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2945         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2946   }
2947 
2948   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2949   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2950   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2951   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2952   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2953   // one as they are relative probabilities (and thus work more like weights),
2954   // and hence we need to normalize them to let the sum of them become one.
2955   SwitchBB->normalizeSuccProbs();
2956 
2957   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2958                               MVT::Other, getControlRoot(),
2959                               Cmp, DAG.getBasicBlock(B.TargetBB));
2960 
2961   // Avoid emitting unnecessary branches to the next block.
2962   if (NextMBB != NextBlock(SwitchBB))
2963     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2964                         DAG.getBasicBlock(NextMBB));
2965 
2966   DAG.setRoot(BrAnd);
2967 }
2968 
2969 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2970   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2971 
2972   // Retrieve successors. Look through artificial IR level blocks like
2973   // catchswitch for successors.
2974   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2975   const BasicBlock *EHPadBB = I.getSuccessor(1);
2976   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
2977 
2978   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2979   // have to do anything here to lower funclet bundles.
2980   assert(!I.hasOperandBundlesOtherThan(
2981              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2982               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2983               LLVMContext::OB_cfguardtarget,
2984               LLVMContext::OB_clang_arc_attachedcall}) &&
2985          "Cannot lower invokes with arbitrary operand bundles yet!");
2986 
2987   const Value *Callee(I.getCalledOperand());
2988   const Function *Fn = dyn_cast<Function>(Callee);
2989   if (isa<InlineAsm>(Callee))
2990     visitInlineAsm(I, EHPadBB);
2991   else if (Fn && Fn->isIntrinsic()) {
2992     switch (Fn->getIntrinsicID()) {
2993     default:
2994       llvm_unreachable("Cannot invoke this intrinsic");
2995     case Intrinsic::donothing:
2996       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2997     case Intrinsic::seh_try_begin:
2998     case Intrinsic::seh_scope_begin:
2999     case Intrinsic::seh_try_end:
3000     case Intrinsic::seh_scope_end:
3001       if (EHPadMBB)
3002           // a block referenced by EH table
3003           // so dtor-funclet not removed by opts
3004           EHPadMBB->setMachineBlockAddressTaken();
3005       break;
3006     case Intrinsic::experimental_patchpoint_void:
3007     case Intrinsic::experimental_patchpoint_i64:
3008       visitPatchpoint(I, EHPadBB);
3009       break;
3010     case Intrinsic::experimental_gc_statepoint:
3011       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3012       break;
3013     case Intrinsic::wasm_rethrow: {
3014       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3015       // special because it can be invoked, so we manually lower it to a DAG
3016       // node here.
3017       SmallVector<SDValue, 8> Ops;
3018       Ops.push_back(getRoot()); // inchain
3019       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3020       Ops.push_back(
3021           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3022                                 TLI.getPointerTy(DAG.getDataLayout())));
3023       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3024       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3025       break;
3026     }
3027     }
3028   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
3029     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3030     // Eventually we will support lowering the @llvm.experimental.deoptimize
3031     // intrinsic, and right now there are no plans to support other intrinsics
3032     // with deopt state.
3033     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3034   } else {
3035     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3036   }
3037 
3038   // If the value of the invoke is used outside of its defining block, make it
3039   // available as a virtual register.
3040   // We already took care of the exported value for the statepoint instruction
3041   // during call to the LowerStatepoint.
3042   if (!isa<GCStatepointInst>(I)) {
3043     CopyToExportRegsIfNeeded(&I);
3044   }
3045 
3046   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3047   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3048   BranchProbability EHPadBBProb =
3049       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3050           : BranchProbability::getZero();
3051   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3052 
3053   // Update successor info.
3054   addSuccessorWithProb(InvokeMBB, Return);
3055   for (auto &UnwindDest : UnwindDests) {
3056     UnwindDest.first->setIsEHPad();
3057     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3058   }
3059   InvokeMBB->normalizeSuccProbs();
3060 
3061   // Drop into normal successor.
3062   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3063                           DAG.getBasicBlock(Return)));
3064 }
3065 
3066 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3067   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3068 
3069   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3070   // have to do anything here to lower funclet bundles.
3071   assert(!I.hasOperandBundlesOtherThan(
3072              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3073          "Cannot lower callbrs with arbitrary operand bundles yet!");
3074 
3075   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3076   visitInlineAsm(I);
3077   CopyToExportRegsIfNeeded(&I);
3078 
3079   // Retrieve successors.
3080   SmallPtrSet<BasicBlock *, 8> Dests;
3081   Dests.insert(I.getDefaultDest());
3082   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3083 
3084   // Update successor info.
3085   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3086   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3087     BasicBlock *Dest = I.getIndirectDest(i);
3088     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3089     Target->setIsInlineAsmBrIndirectTarget();
3090     Target->setMachineBlockAddressTaken();
3091     Target->setLabelMustBeEmitted();
3092     // Don't add duplicate machine successors.
3093     if (Dests.insert(Dest).second)
3094       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3095   }
3096   CallBrMBB->normalizeSuccProbs();
3097 
3098   // Drop into default successor.
3099   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3100                           MVT::Other, getControlRoot(),
3101                           DAG.getBasicBlock(Return)));
3102 }
3103 
3104 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3105   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3106 }
3107 
3108 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3109   assert(FuncInfo.MBB->isEHPad() &&
3110          "Call to landingpad not in landing pad!");
3111 
3112   // If there aren't registers to copy the values into (e.g., during SjLj
3113   // exceptions), then don't bother to create these DAG nodes.
3114   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3115   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3116   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3117       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3118     return;
3119 
3120   // If landingpad's return type is token type, we don't create DAG nodes
3121   // for its exception pointer and selector value. The extraction of exception
3122   // pointer or selector value from token type landingpads is not currently
3123   // supported.
3124   if (LP.getType()->isTokenTy())
3125     return;
3126 
3127   SmallVector<EVT, 2> ValueVTs;
3128   SDLoc dl = getCurSDLoc();
3129   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3130   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3131 
3132   // Get the two live-in registers as SDValues. The physregs have already been
3133   // copied into virtual registers.
3134   SDValue Ops[2];
3135   if (FuncInfo.ExceptionPointerVirtReg) {
3136     Ops[0] = DAG.getZExtOrTrunc(
3137         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3138                            FuncInfo.ExceptionPointerVirtReg,
3139                            TLI.getPointerTy(DAG.getDataLayout())),
3140         dl, ValueVTs[0]);
3141   } else {
3142     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3143   }
3144   Ops[1] = DAG.getZExtOrTrunc(
3145       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3146                          FuncInfo.ExceptionSelectorVirtReg,
3147                          TLI.getPointerTy(DAG.getDataLayout())),
3148       dl, ValueVTs[1]);
3149 
3150   // Merge into one.
3151   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3152                             DAG.getVTList(ValueVTs), Ops);
3153   setValue(&LP, Res);
3154 }
3155 
3156 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3157                                            MachineBasicBlock *Last) {
3158   // Update JTCases.
3159   for (JumpTableBlock &JTB : SL->JTCases)
3160     if (JTB.first.HeaderBB == First)
3161       JTB.first.HeaderBB = Last;
3162 
3163   // Update BitTestCases.
3164   for (BitTestBlock &BTB : SL->BitTestCases)
3165     if (BTB.Parent == First)
3166       BTB.Parent = Last;
3167 }
3168 
3169 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3170   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3171 
3172   // Update machine-CFG edges with unique successors.
3173   SmallSet<BasicBlock*, 32> Done;
3174   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3175     BasicBlock *BB = I.getSuccessor(i);
3176     bool Inserted = Done.insert(BB).second;
3177     if (!Inserted)
3178         continue;
3179 
3180     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3181     addSuccessorWithProb(IndirectBrMBB, Succ);
3182   }
3183   IndirectBrMBB->normalizeSuccProbs();
3184 
3185   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3186                           MVT::Other, getControlRoot(),
3187                           getValue(I.getAddress())));
3188 }
3189 
3190 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3191   if (!DAG.getTarget().Options.TrapUnreachable)
3192     return;
3193 
3194   // We may be able to ignore unreachable behind a noreturn call.
3195   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3196     const BasicBlock &BB = *I.getParent();
3197     if (&I != &BB.front()) {
3198       BasicBlock::const_iterator PredI =
3199         std::prev(BasicBlock::const_iterator(&I));
3200       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3201         if (Call->doesNotReturn())
3202           return;
3203       }
3204     }
3205   }
3206 
3207   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3208 }
3209 
3210 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3211   SDNodeFlags Flags;
3212   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3213     Flags.copyFMF(*FPOp);
3214 
3215   SDValue Op = getValue(I.getOperand(0));
3216   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3217                                     Op, Flags);
3218   setValue(&I, UnNodeValue);
3219 }
3220 
3221 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3222   SDNodeFlags Flags;
3223   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3224     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3225     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3226   }
3227   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3228     Flags.setExact(ExactOp->isExact());
3229   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3230     Flags.copyFMF(*FPOp);
3231 
3232   SDValue Op1 = getValue(I.getOperand(0));
3233   SDValue Op2 = getValue(I.getOperand(1));
3234   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3235                                      Op1, Op2, Flags);
3236   setValue(&I, BinNodeValue);
3237 }
3238 
3239 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3240   SDValue Op1 = getValue(I.getOperand(0));
3241   SDValue Op2 = getValue(I.getOperand(1));
3242 
3243   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3244       Op1.getValueType(), DAG.getDataLayout());
3245 
3246   // Coerce the shift amount to the right type if we can. This exposes the
3247   // truncate or zext to optimization early.
3248   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3249     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3250            "Unexpected shift type");
3251     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3252   }
3253 
3254   bool nuw = false;
3255   bool nsw = false;
3256   bool exact = false;
3257 
3258   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3259 
3260     if (const OverflowingBinaryOperator *OFBinOp =
3261             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3262       nuw = OFBinOp->hasNoUnsignedWrap();
3263       nsw = OFBinOp->hasNoSignedWrap();
3264     }
3265     if (const PossiblyExactOperator *ExactOp =
3266             dyn_cast<const PossiblyExactOperator>(&I))
3267       exact = ExactOp->isExact();
3268   }
3269   SDNodeFlags Flags;
3270   Flags.setExact(exact);
3271   Flags.setNoSignedWrap(nsw);
3272   Flags.setNoUnsignedWrap(nuw);
3273   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3274                             Flags);
3275   setValue(&I, Res);
3276 }
3277 
3278 void SelectionDAGBuilder::visitSDiv(const User &I) {
3279   SDValue Op1 = getValue(I.getOperand(0));
3280   SDValue Op2 = getValue(I.getOperand(1));
3281 
3282   SDNodeFlags Flags;
3283   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3284                  cast<PossiblyExactOperator>(&I)->isExact());
3285   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3286                            Op2, Flags));
3287 }
3288 
3289 void SelectionDAGBuilder::visitICmp(const User &I) {
3290   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3291   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3292     predicate = IC->getPredicate();
3293   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3294     predicate = ICmpInst::Predicate(IC->getPredicate());
3295   SDValue Op1 = getValue(I.getOperand(0));
3296   SDValue Op2 = getValue(I.getOperand(1));
3297   ISD::CondCode Opcode = getICmpCondCode(predicate);
3298 
3299   auto &TLI = DAG.getTargetLoweringInfo();
3300   EVT MemVT =
3301       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3302 
3303   // If a pointer's DAG type is larger than its memory type then the DAG values
3304   // are zero-extended. This breaks signed comparisons so truncate back to the
3305   // underlying type before doing the compare.
3306   if (Op1.getValueType() != MemVT) {
3307     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3308     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3309   }
3310 
3311   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3312                                                         I.getType());
3313   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3314 }
3315 
3316 void SelectionDAGBuilder::visitFCmp(const User &I) {
3317   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3318   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3319     predicate = FC->getPredicate();
3320   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3321     predicate = FCmpInst::Predicate(FC->getPredicate());
3322   SDValue Op1 = getValue(I.getOperand(0));
3323   SDValue Op2 = getValue(I.getOperand(1));
3324 
3325   ISD::CondCode Condition = getFCmpCondCode(predicate);
3326   auto *FPMO = cast<FPMathOperator>(&I);
3327   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3328     Condition = getFCmpCodeWithoutNaN(Condition);
3329 
3330   SDNodeFlags Flags;
3331   Flags.copyFMF(*FPMO);
3332   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3333 
3334   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3335                                                         I.getType());
3336   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3337 }
3338 
3339 // Check if the condition of the select has one use or two users that are both
3340 // selects with the same condition.
3341 static bool hasOnlySelectUsers(const Value *Cond) {
3342   return llvm::all_of(Cond->users(), [](const Value *V) {
3343     return isa<SelectInst>(V);
3344   });
3345 }
3346 
3347 void SelectionDAGBuilder::visitSelect(const User &I) {
3348   SmallVector<EVT, 4> ValueVTs;
3349   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3350                   ValueVTs);
3351   unsigned NumValues = ValueVTs.size();
3352   if (NumValues == 0) return;
3353 
3354   SmallVector<SDValue, 4> Values(NumValues);
3355   SDValue Cond     = getValue(I.getOperand(0));
3356   SDValue LHSVal   = getValue(I.getOperand(1));
3357   SDValue RHSVal   = getValue(I.getOperand(2));
3358   SmallVector<SDValue, 1> BaseOps(1, Cond);
3359   ISD::NodeType OpCode =
3360       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3361 
3362   bool IsUnaryAbs = false;
3363   bool Negate = false;
3364 
3365   SDNodeFlags Flags;
3366   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3367     Flags.copyFMF(*FPOp);
3368 
3369   // Min/max matching is only viable if all output VTs are the same.
3370   if (all_equal(ValueVTs)) {
3371     EVT VT = ValueVTs[0];
3372     LLVMContext &Ctx = *DAG.getContext();
3373     auto &TLI = DAG.getTargetLoweringInfo();
3374 
3375     // We care about the legality of the operation after it has been type
3376     // legalized.
3377     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3378       VT = TLI.getTypeToTransformTo(Ctx, VT);
3379 
3380     // If the vselect is legal, assume we want to leave this as a vector setcc +
3381     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3382     // min/max is legal on the scalar type.
3383     bool UseScalarMinMax = VT.isVector() &&
3384       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3385 
3386     // ValueTracking's select pattern matching does not account for -0.0,
3387     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3388     // -0.0 is less than +0.0.
3389     Value *LHS, *RHS;
3390     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3391     ISD::NodeType Opc = ISD::DELETED_NODE;
3392     switch (SPR.Flavor) {
3393     case SPF_UMAX:    Opc = ISD::UMAX; break;
3394     case SPF_UMIN:    Opc = ISD::UMIN; break;
3395     case SPF_SMAX:    Opc = ISD::SMAX; break;
3396     case SPF_SMIN:    Opc = ISD::SMIN; break;
3397     case SPF_FMINNUM:
3398       switch (SPR.NaNBehavior) {
3399       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3400       case SPNB_RETURNS_NAN: break;
3401       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3402       case SPNB_RETURNS_ANY:
3403         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3404             (UseScalarMinMax &&
3405              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3406           Opc = ISD::FMINNUM;
3407         break;
3408       }
3409       break;
3410     case SPF_FMAXNUM:
3411       switch (SPR.NaNBehavior) {
3412       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3413       case SPNB_RETURNS_NAN: break;
3414       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3415       case SPNB_RETURNS_ANY:
3416         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3417             (UseScalarMinMax &&
3418              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3419           Opc = ISD::FMAXNUM;
3420         break;
3421       }
3422       break;
3423     case SPF_NABS:
3424       Negate = true;
3425       [[fallthrough]];
3426     case SPF_ABS:
3427       IsUnaryAbs = true;
3428       Opc = ISD::ABS;
3429       break;
3430     default: break;
3431     }
3432 
3433     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3434         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3435          (UseScalarMinMax &&
3436           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3437         // If the underlying comparison instruction is used by any other
3438         // instruction, the consumed instructions won't be destroyed, so it is
3439         // not profitable to convert to a min/max.
3440         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3441       OpCode = Opc;
3442       LHSVal = getValue(LHS);
3443       RHSVal = getValue(RHS);
3444       BaseOps.clear();
3445     }
3446 
3447     if (IsUnaryAbs) {
3448       OpCode = Opc;
3449       LHSVal = getValue(LHS);
3450       BaseOps.clear();
3451     }
3452   }
3453 
3454   if (IsUnaryAbs) {
3455     for (unsigned i = 0; i != NumValues; ++i) {
3456       SDLoc dl = getCurSDLoc();
3457       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3458       Values[i] =
3459           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3460       if (Negate)
3461         Values[i] = DAG.getNegative(Values[i], dl, VT);
3462     }
3463   } else {
3464     for (unsigned i = 0; i != NumValues; ++i) {
3465       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3466       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3467       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3468       Values[i] = DAG.getNode(
3469           OpCode, getCurSDLoc(),
3470           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3471     }
3472   }
3473 
3474   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3475                            DAG.getVTList(ValueVTs), Values));
3476 }
3477 
3478 void SelectionDAGBuilder::visitTrunc(const User &I) {
3479   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3480   SDValue N = getValue(I.getOperand(0));
3481   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3482                                                         I.getType());
3483   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3484 }
3485 
3486 void SelectionDAGBuilder::visitZExt(const User &I) {
3487   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3488   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3489   SDValue N = getValue(I.getOperand(0));
3490   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3491                                                         I.getType());
3492   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3493 }
3494 
3495 void SelectionDAGBuilder::visitSExt(const User &I) {
3496   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3497   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3498   SDValue N = getValue(I.getOperand(0));
3499   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3500                                                         I.getType());
3501   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3502 }
3503 
3504 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3505   // FPTrunc is never a no-op cast, no need to check
3506   SDValue N = getValue(I.getOperand(0));
3507   SDLoc dl = getCurSDLoc();
3508   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3509   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3510   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3511                            DAG.getTargetConstant(
3512                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3513 }
3514 
3515 void SelectionDAGBuilder::visitFPExt(const User &I) {
3516   // FPExt is never a no-op cast, no need to check
3517   SDValue N = getValue(I.getOperand(0));
3518   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3519                                                         I.getType());
3520   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3521 }
3522 
3523 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3524   // FPToUI is never a no-op cast, no need to check
3525   SDValue N = getValue(I.getOperand(0));
3526   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3527                                                         I.getType());
3528   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3529 }
3530 
3531 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3532   // FPToSI is never a no-op cast, no need to check
3533   SDValue N = getValue(I.getOperand(0));
3534   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3535                                                         I.getType());
3536   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3537 }
3538 
3539 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3540   // UIToFP is never a no-op cast, no need to check
3541   SDValue N = getValue(I.getOperand(0));
3542   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3543                                                         I.getType());
3544   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3545 }
3546 
3547 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3548   // SIToFP is never a no-op cast, no need to check
3549   SDValue N = getValue(I.getOperand(0));
3550   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3551                                                         I.getType());
3552   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3553 }
3554 
3555 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3556   // What to do depends on the size of the integer and the size of the pointer.
3557   // We can either truncate, zero extend, or no-op, accordingly.
3558   SDValue N = getValue(I.getOperand(0));
3559   auto &TLI = DAG.getTargetLoweringInfo();
3560   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3561                                                         I.getType());
3562   EVT PtrMemVT =
3563       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3564   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3565   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3566   setValue(&I, N);
3567 }
3568 
3569 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3570   // What to do depends on the size of the integer and the size of the pointer.
3571   // We can either truncate, zero extend, or no-op, accordingly.
3572   SDValue N = getValue(I.getOperand(0));
3573   auto &TLI = DAG.getTargetLoweringInfo();
3574   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3575   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3576   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3577   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3578   setValue(&I, N);
3579 }
3580 
3581 void SelectionDAGBuilder::visitBitCast(const User &I) {
3582   SDValue N = getValue(I.getOperand(0));
3583   SDLoc dl = getCurSDLoc();
3584   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3585                                                         I.getType());
3586 
3587   // BitCast assures us that source and destination are the same size so this is
3588   // either a BITCAST or a no-op.
3589   if (DestVT != N.getValueType())
3590     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3591                              DestVT, N)); // convert types.
3592   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3593   // might fold any kind of constant expression to an integer constant and that
3594   // is not what we are looking for. Only recognize a bitcast of a genuine
3595   // constant integer as an opaque constant.
3596   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3597     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3598                                  /*isOpaque*/true));
3599   else
3600     setValue(&I, N);            // noop cast.
3601 }
3602 
3603 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3604   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3605   const Value *SV = I.getOperand(0);
3606   SDValue N = getValue(SV);
3607   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3608 
3609   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3610   unsigned DestAS = I.getType()->getPointerAddressSpace();
3611 
3612   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3613     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3614 
3615   setValue(&I, N);
3616 }
3617 
3618 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3619   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3620   SDValue InVec = getValue(I.getOperand(0));
3621   SDValue InVal = getValue(I.getOperand(1));
3622   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3623                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3624   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3625                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3626                            InVec, InVal, InIdx));
3627 }
3628 
3629 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3630   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3631   SDValue InVec = getValue(I.getOperand(0));
3632   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3633                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3634   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3635                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3636                            InVec, InIdx));
3637 }
3638 
3639 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3640   SDValue Src1 = getValue(I.getOperand(0));
3641   SDValue Src2 = getValue(I.getOperand(1));
3642   ArrayRef<int> Mask;
3643   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3644     Mask = SVI->getShuffleMask();
3645   else
3646     Mask = cast<ConstantExpr>(I).getShuffleMask();
3647   SDLoc DL = getCurSDLoc();
3648   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3649   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3650   EVT SrcVT = Src1.getValueType();
3651 
3652   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3653       VT.isScalableVector()) {
3654     // Canonical splat form of first element of first input vector.
3655     SDValue FirstElt =
3656         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3657                     DAG.getVectorIdxConstant(0, DL));
3658     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3659     return;
3660   }
3661 
3662   // For now, we only handle splats for scalable vectors.
3663   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3664   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3665   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3666 
3667   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3668   unsigned MaskNumElts = Mask.size();
3669 
3670   if (SrcNumElts == MaskNumElts) {
3671     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3672     return;
3673   }
3674 
3675   // Normalize the shuffle vector since mask and vector length don't match.
3676   if (SrcNumElts < MaskNumElts) {
3677     // Mask is longer than the source vectors. We can use concatenate vector to
3678     // make the mask and vectors lengths match.
3679 
3680     if (MaskNumElts % SrcNumElts == 0) {
3681       // Mask length is a multiple of the source vector length.
3682       // Check if the shuffle is some kind of concatenation of the input
3683       // vectors.
3684       unsigned NumConcat = MaskNumElts / SrcNumElts;
3685       bool IsConcat = true;
3686       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3687       for (unsigned i = 0; i != MaskNumElts; ++i) {
3688         int Idx = Mask[i];
3689         if (Idx < 0)
3690           continue;
3691         // Ensure the indices in each SrcVT sized piece are sequential and that
3692         // the same source is used for the whole piece.
3693         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3694             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3695              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3696           IsConcat = false;
3697           break;
3698         }
3699         // Remember which source this index came from.
3700         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3701       }
3702 
3703       // The shuffle is concatenating multiple vectors together. Just emit
3704       // a CONCAT_VECTORS operation.
3705       if (IsConcat) {
3706         SmallVector<SDValue, 8> ConcatOps;
3707         for (auto Src : ConcatSrcs) {
3708           if (Src < 0)
3709             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3710           else if (Src == 0)
3711             ConcatOps.push_back(Src1);
3712           else
3713             ConcatOps.push_back(Src2);
3714         }
3715         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3716         return;
3717       }
3718     }
3719 
3720     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3721     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3722     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3723                                     PaddedMaskNumElts);
3724 
3725     // Pad both vectors with undefs to make them the same length as the mask.
3726     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3727 
3728     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3729     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3730     MOps1[0] = Src1;
3731     MOps2[0] = Src2;
3732 
3733     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3734     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3735 
3736     // Readjust mask for new input vector length.
3737     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3738     for (unsigned i = 0; i != MaskNumElts; ++i) {
3739       int Idx = Mask[i];
3740       if (Idx >= (int)SrcNumElts)
3741         Idx -= SrcNumElts - PaddedMaskNumElts;
3742       MappedOps[i] = Idx;
3743     }
3744 
3745     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3746 
3747     // If the concatenated vector was padded, extract a subvector with the
3748     // correct number of elements.
3749     if (MaskNumElts != PaddedMaskNumElts)
3750       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3751                            DAG.getVectorIdxConstant(0, DL));
3752 
3753     setValue(&I, Result);
3754     return;
3755   }
3756 
3757   if (SrcNumElts > MaskNumElts) {
3758     // Analyze the access pattern of the vector to see if we can extract
3759     // two subvectors and do the shuffle.
3760     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3761     bool CanExtract = true;
3762     for (int Idx : Mask) {
3763       unsigned Input = 0;
3764       if (Idx < 0)
3765         continue;
3766 
3767       if (Idx >= (int)SrcNumElts) {
3768         Input = 1;
3769         Idx -= SrcNumElts;
3770       }
3771 
3772       // If all the indices come from the same MaskNumElts sized portion of
3773       // the sources we can use extract. Also make sure the extract wouldn't
3774       // extract past the end of the source.
3775       int NewStartIdx = alignDown(Idx, MaskNumElts);
3776       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3777           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3778         CanExtract = false;
3779       // Make sure we always update StartIdx as we use it to track if all
3780       // elements are undef.
3781       StartIdx[Input] = NewStartIdx;
3782     }
3783 
3784     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3785       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3786       return;
3787     }
3788     if (CanExtract) {
3789       // Extract appropriate subvector and generate a vector shuffle
3790       for (unsigned Input = 0; Input < 2; ++Input) {
3791         SDValue &Src = Input == 0 ? Src1 : Src2;
3792         if (StartIdx[Input] < 0)
3793           Src = DAG.getUNDEF(VT);
3794         else {
3795           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3796                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3797         }
3798       }
3799 
3800       // Calculate new mask.
3801       SmallVector<int, 8> MappedOps(Mask);
3802       for (int &Idx : MappedOps) {
3803         if (Idx >= (int)SrcNumElts)
3804           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3805         else if (Idx >= 0)
3806           Idx -= StartIdx[0];
3807       }
3808 
3809       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3810       return;
3811     }
3812   }
3813 
3814   // We can't use either concat vectors or extract subvectors so fall back to
3815   // replacing the shuffle with extract and build vector.
3816   // to insert and build vector.
3817   EVT EltVT = VT.getVectorElementType();
3818   SmallVector<SDValue,8> Ops;
3819   for (int Idx : Mask) {
3820     SDValue Res;
3821 
3822     if (Idx < 0) {
3823       Res = DAG.getUNDEF(EltVT);
3824     } else {
3825       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3826       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3827 
3828       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3829                         DAG.getVectorIdxConstant(Idx, DL));
3830     }
3831 
3832     Ops.push_back(Res);
3833   }
3834 
3835   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3836 }
3837 
3838 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3839   ArrayRef<unsigned> Indices = I.getIndices();
3840   const Value *Op0 = I.getOperand(0);
3841   const Value *Op1 = I.getOperand(1);
3842   Type *AggTy = I.getType();
3843   Type *ValTy = Op1->getType();
3844   bool IntoUndef = isa<UndefValue>(Op0);
3845   bool FromUndef = isa<UndefValue>(Op1);
3846 
3847   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3848 
3849   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3850   SmallVector<EVT, 4> AggValueVTs;
3851   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3852   SmallVector<EVT, 4> ValValueVTs;
3853   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3854 
3855   unsigned NumAggValues = AggValueVTs.size();
3856   unsigned NumValValues = ValValueVTs.size();
3857   SmallVector<SDValue, 4> Values(NumAggValues);
3858 
3859   // Ignore an insertvalue that produces an empty object
3860   if (!NumAggValues) {
3861     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3862     return;
3863   }
3864 
3865   SDValue Agg = getValue(Op0);
3866   unsigned i = 0;
3867   // Copy the beginning value(s) from the original aggregate.
3868   for (; i != LinearIndex; ++i)
3869     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3870                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3871   // Copy values from the inserted value(s).
3872   if (NumValValues) {
3873     SDValue Val = getValue(Op1);
3874     for (; i != LinearIndex + NumValValues; ++i)
3875       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3876                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3877   }
3878   // Copy remaining value(s) from the original aggregate.
3879   for (; i != NumAggValues; ++i)
3880     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3881                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3882 
3883   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3884                            DAG.getVTList(AggValueVTs), Values));
3885 }
3886 
3887 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3888   ArrayRef<unsigned> Indices = I.getIndices();
3889   const Value *Op0 = I.getOperand(0);
3890   Type *AggTy = Op0->getType();
3891   Type *ValTy = I.getType();
3892   bool OutOfUndef = isa<UndefValue>(Op0);
3893 
3894   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3895 
3896   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3897   SmallVector<EVT, 4> ValValueVTs;
3898   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3899 
3900   unsigned NumValValues = ValValueVTs.size();
3901 
3902   // Ignore a extractvalue that produces an empty object
3903   if (!NumValValues) {
3904     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3905     return;
3906   }
3907 
3908   SmallVector<SDValue, 4> Values(NumValValues);
3909 
3910   SDValue Agg = getValue(Op0);
3911   // Copy out the selected value(s).
3912   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3913     Values[i - LinearIndex] =
3914       OutOfUndef ?
3915         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3916         SDValue(Agg.getNode(), Agg.getResNo() + i);
3917 
3918   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3919                            DAG.getVTList(ValValueVTs), Values));
3920 }
3921 
3922 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3923   Value *Op0 = I.getOperand(0);
3924   // Note that the pointer operand may be a vector of pointers. Take the scalar
3925   // element which holds a pointer.
3926   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3927   SDValue N = getValue(Op0);
3928   SDLoc dl = getCurSDLoc();
3929   auto &TLI = DAG.getTargetLoweringInfo();
3930 
3931   // Normalize Vector GEP - all scalar operands should be converted to the
3932   // splat vector.
3933   bool IsVectorGEP = I.getType()->isVectorTy();
3934   ElementCount VectorElementCount =
3935       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3936                   : ElementCount::getFixed(0);
3937 
3938   if (IsVectorGEP && !N.getValueType().isVector()) {
3939     LLVMContext &Context = *DAG.getContext();
3940     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3941     N = DAG.getSplat(VT, dl, N);
3942   }
3943 
3944   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3945        GTI != E; ++GTI) {
3946     const Value *Idx = GTI.getOperand();
3947     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3948       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3949       if (Field) {
3950         // N = N + Offset
3951         uint64_t Offset =
3952             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3953 
3954         // In an inbounds GEP with an offset that is nonnegative even when
3955         // interpreted as signed, assume there is no unsigned overflow.
3956         SDNodeFlags Flags;
3957         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3958           Flags.setNoUnsignedWrap(true);
3959 
3960         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3961                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3962       }
3963     } else {
3964       // IdxSize is the width of the arithmetic according to IR semantics.
3965       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3966       // (and fix up the result later).
3967       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3968       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3969       TypeSize ElementSize =
3970           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3971       // We intentionally mask away the high bits here; ElementSize may not
3972       // fit in IdxTy.
3973       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
3974       bool ElementScalable = ElementSize.isScalable();
3975 
3976       // If this is a scalar constant or a splat vector of constants,
3977       // handle it quickly.
3978       const auto *C = dyn_cast<Constant>(Idx);
3979       if (C && isa<VectorType>(C->getType()))
3980         C = C->getSplatValue();
3981 
3982       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3983       if (CI && CI->isZero())
3984         continue;
3985       if (CI && !ElementScalable) {
3986         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3987         LLVMContext &Context = *DAG.getContext();
3988         SDValue OffsVal;
3989         if (IsVectorGEP)
3990           OffsVal = DAG.getConstant(
3991               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3992         else
3993           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3994 
3995         // In an inbounds GEP with an offset that is nonnegative even when
3996         // interpreted as signed, assume there is no unsigned overflow.
3997         SDNodeFlags Flags;
3998         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3999           Flags.setNoUnsignedWrap(true);
4000 
4001         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4002 
4003         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4004         continue;
4005       }
4006 
4007       // N = N + Idx * ElementMul;
4008       SDValue IdxN = getValue(Idx);
4009 
4010       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4011         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4012                                   VectorElementCount);
4013         IdxN = DAG.getSplat(VT, dl, IdxN);
4014       }
4015 
4016       // If the index is smaller or larger than intptr_t, truncate or extend
4017       // it.
4018       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4019 
4020       if (ElementScalable) {
4021         EVT VScaleTy = N.getValueType().getScalarType();
4022         SDValue VScale = DAG.getNode(
4023             ISD::VSCALE, dl, VScaleTy,
4024             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4025         if (IsVectorGEP)
4026           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4027         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4028       } else {
4029         // If this is a multiply by a power of two, turn it into a shl
4030         // immediately.  This is a very common case.
4031         if (ElementMul != 1) {
4032           if (ElementMul.isPowerOf2()) {
4033             unsigned Amt = ElementMul.logBase2();
4034             IdxN = DAG.getNode(ISD::SHL, dl,
4035                                N.getValueType(), IdxN,
4036                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4037           } else {
4038             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4039                                             IdxN.getValueType());
4040             IdxN = DAG.getNode(ISD::MUL, dl,
4041                                N.getValueType(), IdxN, Scale);
4042           }
4043         }
4044       }
4045 
4046       N = DAG.getNode(ISD::ADD, dl,
4047                       N.getValueType(), N, IdxN);
4048     }
4049   }
4050 
4051   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4052   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4053   if (IsVectorGEP) {
4054     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4055     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4056   }
4057 
4058   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4059     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4060 
4061   setValue(&I, N);
4062 }
4063 
4064 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4065   // If this is a fixed sized alloca in the entry block of the function,
4066   // allocate it statically on the stack.
4067   if (FuncInfo.StaticAllocaMap.count(&I))
4068     return;   // getValue will auto-populate this.
4069 
4070   SDLoc dl = getCurSDLoc();
4071   Type *Ty = I.getAllocatedType();
4072   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4073   auto &DL = DAG.getDataLayout();
4074   TypeSize TySize = DL.getTypeAllocSize(Ty);
4075   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4076 
4077   SDValue AllocSize = getValue(I.getArraySize());
4078 
4079   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace());
4080   if (AllocSize.getValueType() != IntPtr)
4081     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4082 
4083   if (TySize.isScalable())
4084     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4085                             DAG.getVScale(dl, IntPtr,
4086                                           APInt(IntPtr.getScalarSizeInBits(),
4087                                                 TySize.getKnownMinValue())));
4088   else
4089     AllocSize =
4090         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4091                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4092 
4093   // Handle alignment.  If the requested alignment is less than or equal to
4094   // the stack alignment, ignore it.  If the size is greater than or equal to
4095   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4096   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4097   if (*Alignment <= StackAlign)
4098     Alignment = std::nullopt;
4099 
4100   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4101   // Round the size of the allocation up to the stack alignment size
4102   // by add SA-1 to the size. This doesn't overflow because we're computing
4103   // an address inside an alloca.
4104   SDNodeFlags Flags;
4105   Flags.setNoUnsignedWrap(true);
4106   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4107                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4108 
4109   // Mask out the low bits for alignment purposes.
4110   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4111                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4112 
4113   SDValue Ops[] = {
4114       getRoot(), AllocSize,
4115       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4116   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4117   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4118   setValue(&I, DSA);
4119   DAG.setRoot(DSA.getValue(1));
4120 
4121   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4122 }
4123 
4124 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4125   if (I.isAtomic())
4126     return visitAtomicLoad(I);
4127 
4128   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4129   const Value *SV = I.getOperand(0);
4130   if (TLI.supportSwiftError()) {
4131     // Swifterror values can come from either a function parameter with
4132     // swifterror attribute or an alloca with swifterror attribute.
4133     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4134       if (Arg->hasSwiftErrorAttr())
4135         return visitLoadFromSwiftError(I);
4136     }
4137 
4138     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4139       if (Alloca->isSwiftError())
4140         return visitLoadFromSwiftError(I);
4141     }
4142   }
4143 
4144   SDValue Ptr = getValue(SV);
4145 
4146   Type *Ty = I.getType();
4147   SmallVector<EVT, 4> ValueVTs, MemVTs;
4148   SmallVector<uint64_t, 4> Offsets;
4149   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4150   unsigned NumValues = ValueVTs.size();
4151   if (NumValues == 0)
4152     return;
4153 
4154   Align Alignment = I.getAlign();
4155   AAMDNodes AAInfo = I.getAAMetadata();
4156   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4157   bool isVolatile = I.isVolatile();
4158   MachineMemOperand::Flags MMOFlags =
4159       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4160 
4161   SDValue Root;
4162   bool ConstantMemory = false;
4163   if (isVolatile)
4164     // Serialize volatile loads with other side effects.
4165     Root = getRoot();
4166   else if (NumValues > MaxParallelChains)
4167     Root = getMemoryRoot();
4168   else if (AA &&
4169            AA->pointsToConstantMemory(MemoryLocation(
4170                SV,
4171                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4172                AAInfo))) {
4173     // Do not serialize (non-volatile) loads of constant memory with anything.
4174     Root = DAG.getEntryNode();
4175     ConstantMemory = true;
4176     MMOFlags |= MachineMemOperand::MOInvariant;
4177   } else {
4178     // Do not serialize non-volatile loads against each other.
4179     Root = DAG.getRoot();
4180   }
4181 
4182   SDLoc dl = getCurSDLoc();
4183 
4184   if (isVolatile)
4185     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4186 
4187   // An aggregate load cannot wrap around the address space, so offsets to its
4188   // parts don't wrap either.
4189   SDNodeFlags Flags;
4190   Flags.setNoUnsignedWrap(true);
4191 
4192   SmallVector<SDValue, 4> Values(NumValues);
4193   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4194   EVT PtrVT = Ptr.getValueType();
4195 
4196   unsigned ChainI = 0;
4197   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4198     // Serializing loads here may result in excessive register pressure, and
4199     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4200     // could recover a bit by hoisting nodes upward in the chain by recognizing
4201     // they are side-effect free or do not alias. The optimizer should really
4202     // avoid this case by converting large object/array copies to llvm.memcpy
4203     // (MaxParallelChains should always remain as failsafe).
4204     if (ChainI == MaxParallelChains) {
4205       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4206       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4207                                   ArrayRef(Chains.data(), ChainI));
4208       Root = Chain;
4209       ChainI = 0;
4210     }
4211     SDValue A = DAG.getNode(ISD::ADD, dl,
4212                             PtrVT, Ptr,
4213                             DAG.getConstant(Offsets[i], dl, PtrVT),
4214                             Flags);
4215 
4216     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4217                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4218                             MMOFlags, AAInfo, Ranges);
4219     Chains[ChainI] = L.getValue(1);
4220 
4221     if (MemVTs[i] != ValueVTs[i])
4222       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4223 
4224     Values[i] = L;
4225   }
4226 
4227   if (!ConstantMemory) {
4228     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4229                                 ArrayRef(Chains.data(), ChainI));
4230     if (isVolatile)
4231       DAG.setRoot(Chain);
4232     else
4233       PendingLoads.push_back(Chain);
4234   }
4235 
4236   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4237                            DAG.getVTList(ValueVTs), Values));
4238 }
4239 
4240 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4241   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4242          "call visitStoreToSwiftError when backend supports swifterror");
4243 
4244   SmallVector<EVT, 4> ValueVTs;
4245   SmallVector<uint64_t, 4> Offsets;
4246   const Value *SrcV = I.getOperand(0);
4247   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4248                   SrcV->getType(), ValueVTs, &Offsets);
4249   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4250          "expect a single EVT for swifterror");
4251 
4252   SDValue Src = getValue(SrcV);
4253   // Create a virtual register, then update the virtual register.
4254   Register VReg =
4255       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4256   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4257   // Chain can be getRoot or getControlRoot.
4258   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4259                                       SDValue(Src.getNode(), Src.getResNo()));
4260   DAG.setRoot(CopyNode);
4261 }
4262 
4263 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4264   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4265          "call visitLoadFromSwiftError when backend supports swifterror");
4266 
4267   assert(!I.isVolatile() &&
4268          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4269          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4270          "Support volatile, non temporal, invariant for load_from_swift_error");
4271 
4272   const Value *SV = I.getOperand(0);
4273   Type *Ty = I.getType();
4274   assert(
4275       (!AA ||
4276        !AA->pointsToConstantMemory(MemoryLocation(
4277            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4278            I.getAAMetadata()))) &&
4279       "load_from_swift_error should not be constant memory");
4280 
4281   SmallVector<EVT, 4> ValueVTs;
4282   SmallVector<uint64_t, 4> Offsets;
4283   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4284                   ValueVTs, &Offsets);
4285   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4286          "expect a single EVT for swifterror");
4287 
4288   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4289   SDValue L = DAG.getCopyFromReg(
4290       getRoot(), getCurSDLoc(),
4291       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4292 
4293   setValue(&I, L);
4294 }
4295 
4296 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4297   if (I.isAtomic())
4298     return visitAtomicStore(I);
4299 
4300   const Value *SrcV = I.getOperand(0);
4301   const Value *PtrV = I.getOperand(1);
4302 
4303   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4304   if (TLI.supportSwiftError()) {
4305     // Swifterror values can come from either a function parameter with
4306     // swifterror attribute or an alloca with swifterror attribute.
4307     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4308       if (Arg->hasSwiftErrorAttr())
4309         return visitStoreToSwiftError(I);
4310     }
4311 
4312     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4313       if (Alloca->isSwiftError())
4314         return visitStoreToSwiftError(I);
4315     }
4316   }
4317 
4318   SmallVector<EVT, 4> ValueVTs, MemVTs;
4319   SmallVector<uint64_t, 4> Offsets;
4320   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4321                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4322   unsigned NumValues = ValueVTs.size();
4323   if (NumValues == 0)
4324     return;
4325 
4326   // Get the lowered operands. Note that we do this after
4327   // checking if NumResults is zero, because with zero results
4328   // the operands won't have values in the map.
4329   SDValue Src = getValue(SrcV);
4330   SDValue Ptr = getValue(PtrV);
4331 
4332   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4333   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4334   SDLoc dl = getCurSDLoc();
4335   Align Alignment = I.getAlign();
4336   AAMDNodes AAInfo = I.getAAMetadata();
4337 
4338   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4339 
4340   // An aggregate load cannot wrap around the address space, so offsets to its
4341   // parts don't wrap either.
4342   SDNodeFlags Flags;
4343   Flags.setNoUnsignedWrap(true);
4344 
4345   unsigned ChainI = 0;
4346   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4347     // See visitLoad comments.
4348     if (ChainI == MaxParallelChains) {
4349       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4350                                   ArrayRef(Chains.data(), ChainI));
4351       Root = Chain;
4352       ChainI = 0;
4353     }
4354     SDValue Add =
4355         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4356     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4357     if (MemVTs[i] != ValueVTs[i])
4358       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4359     SDValue St =
4360         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4361                      Alignment, MMOFlags, AAInfo);
4362     Chains[ChainI] = St;
4363   }
4364 
4365   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4366                                   ArrayRef(Chains.data(), ChainI));
4367   setValue(&I, StoreNode);
4368   DAG.setRoot(StoreNode);
4369 }
4370 
4371 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4372                                            bool IsCompressing) {
4373   SDLoc sdl = getCurSDLoc();
4374 
4375   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4376                                MaybeAlign &Alignment) {
4377     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4378     Src0 = I.getArgOperand(0);
4379     Ptr = I.getArgOperand(1);
4380     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4381     Mask = I.getArgOperand(3);
4382   };
4383   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4384                                     MaybeAlign &Alignment) {
4385     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4386     Src0 = I.getArgOperand(0);
4387     Ptr = I.getArgOperand(1);
4388     Mask = I.getArgOperand(2);
4389     Alignment = std::nullopt;
4390   };
4391 
4392   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4393   MaybeAlign Alignment;
4394   if (IsCompressing)
4395     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4396   else
4397     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4398 
4399   SDValue Ptr = getValue(PtrOperand);
4400   SDValue Src0 = getValue(Src0Operand);
4401   SDValue Mask = getValue(MaskOperand);
4402   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4403 
4404   EVT VT = Src0.getValueType();
4405   if (!Alignment)
4406     Alignment = DAG.getEVTAlign(VT);
4407 
4408   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4409       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4410       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4411   SDValue StoreNode =
4412       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4413                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4414   DAG.setRoot(StoreNode);
4415   setValue(&I, StoreNode);
4416 }
4417 
4418 // Get a uniform base for the Gather/Scatter intrinsic.
4419 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4420 // We try to represent it as a base pointer + vector of indices.
4421 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4422 // The first operand of the GEP may be a single pointer or a vector of pointers
4423 // Example:
4424 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4425 //  or
4426 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4427 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4428 //
4429 // When the first GEP operand is a single pointer - it is the uniform base we
4430 // are looking for. If first operand of the GEP is a splat vector - we
4431 // extract the splat value and use it as a uniform base.
4432 // In all other cases the function returns 'false'.
4433 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4434                            ISD::MemIndexType &IndexType, SDValue &Scale,
4435                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4436                            uint64_t ElemSize) {
4437   SelectionDAG& DAG = SDB->DAG;
4438   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4439   const DataLayout &DL = DAG.getDataLayout();
4440 
4441   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4442 
4443   // Handle splat constant pointer.
4444   if (auto *C = dyn_cast<Constant>(Ptr)) {
4445     C = C->getSplatValue();
4446     if (!C)
4447       return false;
4448 
4449     Base = SDB->getValue(C);
4450 
4451     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4452     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4453     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4454     IndexType = ISD::SIGNED_SCALED;
4455     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4456     return true;
4457   }
4458 
4459   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4460   if (!GEP || GEP->getParent() != CurBB)
4461     return false;
4462 
4463   if (GEP->getNumOperands() != 2)
4464     return false;
4465 
4466   const Value *BasePtr = GEP->getPointerOperand();
4467   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4468 
4469   // Make sure the base is scalar and the index is a vector.
4470   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4471     return false;
4472 
4473   uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4474 
4475   // Target may not support the required addressing mode.
4476   if (ScaleVal != 1 &&
4477       !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize))
4478     return false;
4479 
4480   Base = SDB->getValue(BasePtr);
4481   Index = SDB->getValue(IndexVal);
4482   IndexType = ISD::SIGNED_SCALED;
4483 
4484   Scale =
4485       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4486   return true;
4487 }
4488 
4489 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4490   SDLoc sdl = getCurSDLoc();
4491 
4492   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4493   const Value *Ptr = I.getArgOperand(1);
4494   SDValue Src0 = getValue(I.getArgOperand(0));
4495   SDValue Mask = getValue(I.getArgOperand(3));
4496   EVT VT = Src0.getValueType();
4497   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4498                         ->getMaybeAlignValue()
4499                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4500   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4501 
4502   SDValue Base;
4503   SDValue Index;
4504   ISD::MemIndexType IndexType;
4505   SDValue Scale;
4506   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4507                                     I.getParent(), VT.getScalarStoreSize());
4508 
4509   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4510   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4511       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4512       // TODO: Make MachineMemOperands aware of scalable
4513       // vectors.
4514       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4515   if (!UniformBase) {
4516     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4517     Index = getValue(Ptr);
4518     IndexType = ISD::SIGNED_SCALED;
4519     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4520   }
4521 
4522   EVT IdxVT = Index.getValueType();
4523   EVT EltTy = IdxVT.getVectorElementType();
4524   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4525     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4526     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4527   }
4528 
4529   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4530   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4531                                          Ops, MMO, IndexType, false);
4532   DAG.setRoot(Scatter);
4533   setValue(&I, Scatter);
4534 }
4535 
4536 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4537   SDLoc sdl = getCurSDLoc();
4538 
4539   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4540                               MaybeAlign &Alignment) {
4541     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4542     Ptr = I.getArgOperand(0);
4543     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4544     Mask = I.getArgOperand(2);
4545     Src0 = I.getArgOperand(3);
4546   };
4547   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4548                                  MaybeAlign &Alignment) {
4549     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4550     Ptr = I.getArgOperand(0);
4551     Alignment = std::nullopt;
4552     Mask = I.getArgOperand(1);
4553     Src0 = I.getArgOperand(2);
4554   };
4555 
4556   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4557   MaybeAlign Alignment;
4558   if (IsExpanding)
4559     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4560   else
4561     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4562 
4563   SDValue Ptr = getValue(PtrOperand);
4564   SDValue Src0 = getValue(Src0Operand);
4565   SDValue Mask = getValue(MaskOperand);
4566   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4567 
4568   EVT VT = Src0.getValueType();
4569   if (!Alignment)
4570     Alignment = DAG.getEVTAlign(VT);
4571 
4572   AAMDNodes AAInfo = I.getAAMetadata();
4573   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4574 
4575   // Do not serialize masked loads of constant memory with anything.
4576   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4577   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4578 
4579   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4580 
4581   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4582       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4583       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4584 
4585   SDValue Load =
4586       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4587                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4588   if (AddToChain)
4589     PendingLoads.push_back(Load.getValue(1));
4590   setValue(&I, Load);
4591 }
4592 
4593 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4594   SDLoc sdl = getCurSDLoc();
4595 
4596   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4597   const Value *Ptr = I.getArgOperand(0);
4598   SDValue Src0 = getValue(I.getArgOperand(3));
4599   SDValue Mask = getValue(I.getArgOperand(2));
4600 
4601   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4602   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4603   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4604                         ->getMaybeAlignValue()
4605                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4606 
4607   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4608 
4609   SDValue Root = DAG.getRoot();
4610   SDValue Base;
4611   SDValue Index;
4612   ISD::MemIndexType IndexType;
4613   SDValue Scale;
4614   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4615                                     I.getParent(), VT.getScalarStoreSize());
4616   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4617   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4618       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4619       // TODO: Make MachineMemOperands aware of scalable
4620       // vectors.
4621       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4622 
4623   if (!UniformBase) {
4624     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4625     Index = getValue(Ptr);
4626     IndexType = ISD::SIGNED_SCALED;
4627     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4628   }
4629 
4630   EVT IdxVT = Index.getValueType();
4631   EVT EltTy = IdxVT.getVectorElementType();
4632   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4633     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4634     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4635   }
4636 
4637   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4638   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4639                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4640 
4641   PendingLoads.push_back(Gather.getValue(1));
4642   setValue(&I, Gather);
4643 }
4644 
4645 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4646   SDLoc dl = getCurSDLoc();
4647   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4648   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4649   SyncScope::ID SSID = I.getSyncScopeID();
4650 
4651   SDValue InChain = getRoot();
4652 
4653   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4654   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4655 
4656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4657   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4658 
4659   MachineFunction &MF = DAG.getMachineFunction();
4660   MachineMemOperand *MMO = MF.getMachineMemOperand(
4661       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4662       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4663       FailureOrdering);
4664 
4665   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4666                                    dl, MemVT, VTs, InChain,
4667                                    getValue(I.getPointerOperand()),
4668                                    getValue(I.getCompareOperand()),
4669                                    getValue(I.getNewValOperand()), MMO);
4670 
4671   SDValue OutChain = L.getValue(2);
4672 
4673   setValue(&I, L);
4674   DAG.setRoot(OutChain);
4675 }
4676 
4677 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4678   SDLoc dl = getCurSDLoc();
4679   ISD::NodeType NT;
4680   switch (I.getOperation()) {
4681   default: llvm_unreachable("Unknown atomicrmw operation");
4682   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4683   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4684   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4685   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4686   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4687   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4688   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4689   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4690   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4691   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4692   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4693   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4694   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4695   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4696   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4697   case AtomicRMWInst::UIncWrap:
4698     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
4699     break;
4700   case AtomicRMWInst::UDecWrap:
4701     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
4702     break;
4703   }
4704   AtomicOrdering Ordering = I.getOrdering();
4705   SyncScope::ID SSID = I.getSyncScopeID();
4706 
4707   SDValue InChain = getRoot();
4708 
4709   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4710   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4711   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4712 
4713   MachineFunction &MF = DAG.getMachineFunction();
4714   MachineMemOperand *MMO = MF.getMachineMemOperand(
4715       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4716       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4717 
4718   SDValue L =
4719     DAG.getAtomic(NT, dl, MemVT, InChain,
4720                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4721                   MMO);
4722 
4723   SDValue OutChain = L.getValue(1);
4724 
4725   setValue(&I, L);
4726   DAG.setRoot(OutChain);
4727 }
4728 
4729 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4730   SDLoc dl = getCurSDLoc();
4731   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4732   SDValue Ops[3];
4733   Ops[0] = getRoot();
4734   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4735                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4736   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4737                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4738   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4739   setValue(&I, N);
4740   DAG.setRoot(N);
4741 }
4742 
4743 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4744   SDLoc dl = getCurSDLoc();
4745   AtomicOrdering Order = I.getOrdering();
4746   SyncScope::ID SSID = I.getSyncScopeID();
4747 
4748   SDValue InChain = getRoot();
4749 
4750   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4751   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4752   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4753 
4754   if (!TLI.supportsUnalignedAtomics() &&
4755       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4756     report_fatal_error("Cannot generate unaligned atomic load");
4757 
4758   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4759 
4760   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4761       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4762       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4763 
4764   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4765 
4766   SDValue Ptr = getValue(I.getPointerOperand());
4767 
4768   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4769     // TODO: Once this is better exercised by tests, it should be merged with
4770     // the normal path for loads to prevent future divergence.
4771     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4772     if (MemVT != VT)
4773       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4774 
4775     setValue(&I, L);
4776     SDValue OutChain = L.getValue(1);
4777     if (!I.isUnordered())
4778       DAG.setRoot(OutChain);
4779     else
4780       PendingLoads.push_back(OutChain);
4781     return;
4782   }
4783 
4784   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4785                             Ptr, MMO);
4786 
4787   SDValue OutChain = L.getValue(1);
4788   if (MemVT != VT)
4789     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4790 
4791   setValue(&I, L);
4792   DAG.setRoot(OutChain);
4793 }
4794 
4795 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4796   SDLoc dl = getCurSDLoc();
4797 
4798   AtomicOrdering Ordering = I.getOrdering();
4799   SyncScope::ID SSID = I.getSyncScopeID();
4800 
4801   SDValue InChain = getRoot();
4802 
4803   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4804   EVT MemVT =
4805       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4806 
4807   if (!TLI.supportsUnalignedAtomics() &&
4808       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4809     report_fatal_error("Cannot generate unaligned atomic store");
4810 
4811   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4812 
4813   MachineFunction &MF = DAG.getMachineFunction();
4814   MachineMemOperand *MMO = MF.getMachineMemOperand(
4815       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4816       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4817 
4818   SDValue Val = getValue(I.getValueOperand());
4819   if (Val.getValueType() != MemVT)
4820     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4821   SDValue Ptr = getValue(I.getPointerOperand());
4822 
4823   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4824     // TODO: Once this is better exercised by tests, it should be merged with
4825     // the normal path for stores to prevent future divergence.
4826     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4827     setValue(&I, S);
4828     DAG.setRoot(S);
4829     return;
4830   }
4831   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4832                                    Ptr, Val, MMO);
4833 
4834   setValue(&I, OutChain);
4835   DAG.setRoot(OutChain);
4836 }
4837 
4838 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4839 /// node.
4840 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4841                                                unsigned Intrinsic) {
4842   // Ignore the callsite's attributes. A specific call site may be marked with
4843   // readnone, but the lowering code will expect the chain based on the
4844   // definition.
4845   const Function *F = I.getCalledFunction();
4846   bool HasChain = !F->doesNotAccessMemory();
4847   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4848 
4849   // Build the operand list.
4850   SmallVector<SDValue, 8> Ops;
4851   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4852     if (OnlyLoad) {
4853       // We don't need to serialize loads against other loads.
4854       Ops.push_back(DAG.getRoot());
4855     } else {
4856       Ops.push_back(getRoot());
4857     }
4858   }
4859 
4860   // Info is set by getTgtMemIntrinsic
4861   TargetLowering::IntrinsicInfo Info;
4862   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4863   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4864                                                DAG.getMachineFunction(),
4865                                                Intrinsic);
4866 
4867   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4868   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4869       Info.opc == ISD::INTRINSIC_W_CHAIN)
4870     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4871                                         TLI.getPointerTy(DAG.getDataLayout())));
4872 
4873   // Add all operands of the call to the operand list.
4874   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4875     const Value *Arg = I.getArgOperand(i);
4876     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4877       Ops.push_back(getValue(Arg));
4878       continue;
4879     }
4880 
4881     // Use TargetConstant instead of a regular constant for immarg.
4882     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4883     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4884       assert(CI->getBitWidth() <= 64 &&
4885              "large intrinsic immediates not handled");
4886       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4887     } else {
4888       Ops.push_back(
4889           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4890     }
4891   }
4892 
4893   SmallVector<EVT, 4> ValueVTs;
4894   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4895 
4896   if (HasChain)
4897     ValueVTs.push_back(MVT::Other);
4898 
4899   SDVTList VTs = DAG.getVTList(ValueVTs);
4900 
4901   // Propagate fast-math-flags from IR to node(s).
4902   SDNodeFlags Flags;
4903   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4904     Flags.copyFMF(*FPMO);
4905   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4906 
4907   // Create the node.
4908   SDValue Result;
4909   // In some cases, custom collection of operands from CallInst I may be needed.
4910   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4911   if (IsTgtIntrinsic) {
4912     // This is target intrinsic that touches memory
4913     //
4914     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
4915     //       didn't yield anything useful.
4916     MachinePointerInfo MPI;
4917     if (Info.ptrVal)
4918       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
4919     else if (Info.fallbackAddressSpace)
4920       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
4921     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
4922                                      Info.memVT, MPI, Info.align, Info.flags,
4923                                      Info.size, I.getAAMetadata());
4924   } else if (!HasChain) {
4925     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4926   } else if (!I.getType()->isVoidTy()) {
4927     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4928   } else {
4929     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4930   }
4931 
4932   if (HasChain) {
4933     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4934     if (OnlyLoad)
4935       PendingLoads.push_back(Chain);
4936     else
4937       DAG.setRoot(Chain);
4938   }
4939 
4940   if (!I.getType()->isVoidTy()) {
4941     if (!isa<VectorType>(I.getType()))
4942       Result = lowerRangeToAssertZExt(DAG, I, Result);
4943 
4944     MaybeAlign Alignment = I.getRetAlign();
4945 
4946     // Insert `assertalign` node if there's an alignment.
4947     if (InsertAssertAlign && Alignment) {
4948       Result =
4949           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4950     }
4951 
4952     setValue(&I, Result);
4953   }
4954 }
4955 
4956 /// GetSignificand - Get the significand and build it into a floating-point
4957 /// number with exponent of 1:
4958 ///
4959 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4960 ///
4961 /// where Op is the hexadecimal representation of floating point value.
4962 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4963   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4964                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4965   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4966                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4967   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4968 }
4969 
4970 /// GetExponent - Get the exponent:
4971 ///
4972 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4973 ///
4974 /// where Op is the hexadecimal representation of floating point value.
4975 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4976                            const TargetLowering &TLI, const SDLoc &dl) {
4977   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4978                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4979   SDValue t1 = DAG.getNode(
4980       ISD::SRL, dl, MVT::i32, t0,
4981       DAG.getConstant(23, dl,
4982                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
4983   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4984                            DAG.getConstant(127, dl, MVT::i32));
4985   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4986 }
4987 
4988 /// getF32Constant - Get 32-bit floating point constant.
4989 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4990                               const SDLoc &dl) {
4991   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4992                            MVT::f32);
4993 }
4994 
4995 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4996                                        SelectionDAG &DAG) {
4997   // TODO: What fast-math-flags should be set on the floating-point nodes?
4998 
4999   //   IntegerPartOfX = ((int32_t)(t0);
5000   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5001 
5002   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5003   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5004   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5005 
5006   //   IntegerPartOfX <<= 23;
5007   IntegerPartOfX =
5008       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5009                   DAG.getConstant(23, dl,
5010                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5011                                       MVT::i32, DAG.getDataLayout())));
5012 
5013   SDValue TwoToFractionalPartOfX;
5014   if (LimitFloatPrecision <= 6) {
5015     // For floating-point precision of 6:
5016     //
5017     //   TwoToFractionalPartOfX =
5018     //     0.997535578f +
5019     //       (0.735607626f + 0.252464424f * x) * x;
5020     //
5021     // error 0.0144103317, which is 6 bits
5022     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5023                              getF32Constant(DAG, 0x3e814304, dl));
5024     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5025                              getF32Constant(DAG, 0x3f3c50c8, dl));
5026     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5027     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5028                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5029   } else if (LimitFloatPrecision <= 12) {
5030     // For floating-point precision of 12:
5031     //
5032     //   TwoToFractionalPartOfX =
5033     //     0.999892986f +
5034     //       (0.696457318f +
5035     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5036     //
5037     // error 0.000107046256, which is 13 to 14 bits
5038     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5039                              getF32Constant(DAG, 0x3da235e3, dl));
5040     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5041                              getF32Constant(DAG, 0x3e65b8f3, dl));
5042     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5043     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5044                              getF32Constant(DAG, 0x3f324b07, dl));
5045     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5046     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5047                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5048   } else { // LimitFloatPrecision <= 18
5049     // For floating-point precision of 18:
5050     //
5051     //   TwoToFractionalPartOfX =
5052     //     0.999999982f +
5053     //       (0.693148872f +
5054     //         (0.240227044f +
5055     //           (0.554906021e-1f +
5056     //             (0.961591928e-2f +
5057     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5058     // error 2.47208000*10^(-7), which is better than 18 bits
5059     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5060                              getF32Constant(DAG, 0x3924b03e, dl));
5061     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5062                              getF32Constant(DAG, 0x3ab24b87, dl));
5063     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5064     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5065                              getF32Constant(DAG, 0x3c1d8c17, dl));
5066     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5067     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5068                              getF32Constant(DAG, 0x3d634a1d, dl));
5069     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5070     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5071                              getF32Constant(DAG, 0x3e75fe14, dl));
5072     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5073     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5074                               getF32Constant(DAG, 0x3f317234, dl));
5075     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5076     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5077                                          getF32Constant(DAG, 0x3f800000, dl));
5078   }
5079 
5080   // Add the exponent into the result in integer domain.
5081   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5082   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5083                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5084 }
5085 
5086 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5087 /// limited-precision mode.
5088 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5089                          const TargetLowering &TLI, SDNodeFlags Flags) {
5090   if (Op.getValueType() == MVT::f32 &&
5091       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5092 
5093     // Put the exponent in the right bit position for later addition to the
5094     // final result:
5095     //
5096     // t0 = Op * log2(e)
5097 
5098     // TODO: What fast-math-flags should be set here?
5099     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5100                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5101     return getLimitedPrecisionExp2(t0, dl, DAG);
5102   }
5103 
5104   // No special expansion.
5105   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5106 }
5107 
5108 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5109 /// limited-precision mode.
5110 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5111                          const TargetLowering &TLI, SDNodeFlags Flags) {
5112   // TODO: What fast-math-flags should be set on the floating-point nodes?
5113 
5114   if (Op.getValueType() == MVT::f32 &&
5115       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5116     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5117 
5118     // Scale the exponent by log(2).
5119     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5120     SDValue LogOfExponent =
5121         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5122                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5123 
5124     // Get the significand and build it into a floating-point number with
5125     // exponent of 1.
5126     SDValue X = GetSignificand(DAG, Op1, dl);
5127 
5128     SDValue LogOfMantissa;
5129     if (LimitFloatPrecision <= 6) {
5130       // For floating-point precision of 6:
5131       //
5132       //   LogofMantissa =
5133       //     -1.1609546f +
5134       //       (1.4034025f - 0.23903021f * x) * x;
5135       //
5136       // error 0.0034276066, which is better than 8 bits
5137       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5138                                getF32Constant(DAG, 0xbe74c456, dl));
5139       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5140                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5141       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5142       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5143                                   getF32Constant(DAG, 0x3f949a29, dl));
5144     } else if (LimitFloatPrecision <= 12) {
5145       // For floating-point precision of 12:
5146       //
5147       //   LogOfMantissa =
5148       //     -1.7417939f +
5149       //       (2.8212026f +
5150       //         (-1.4699568f +
5151       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5152       //
5153       // error 0.000061011436, which is 14 bits
5154       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5155                                getF32Constant(DAG, 0xbd67b6d6, dl));
5156       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5157                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5158       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5159       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5160                                getF32Constant(DAG, 0x3fbc278b, dl));
5161       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5162       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5163                                getF32Constant(DAG, 0x40348e95, dl));
5164       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5165       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5166                                   getF32Constant(DAG, 0x3fdef31a, dl));
5167     } else { // LimitFloatPrecision <= 18
5168       // For floating-point precision of 18:
5169       //
5170       //   LogOfMantissa =
5171       //     -2.1072184f +
5172       //       (4.2372794f +
5173       //         (-3.7029485f +
5174       //           (2.2781945f +
5175       //             (-0.87823314f +
5176       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5177       //
5178       // error 0.0000023660568, which is better than 18 bits
5179       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5180                                getF32Constant(DAG, 0xbc91e5ac, dl));
5181       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5182                                getF32Constant(DAG, 0x3e4350aa, dl));
5183       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5184       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5185                                getF32Constant(DAG, 0x3f60d3e3, dl));
5186       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5187       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5188                                getF32Constant(DAG, 0x4011cdf0, dl));
5189       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5190       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5191                                getF32Constant(DAG, 0x406cfd1c, dl));
5192       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5193       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5194                                getF32Constant(DAG, 0x408797cb, dl));
5195       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5196       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5197                                   getF32Constant(DAG, 0x4006dcab, dl));
5198     }
5199 
5200     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5201   }
5202 
5203   // No special expansion.
5204   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5205 }
5206 
5207 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5208 /// limited-precision mode.
5209 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5210                           const TargetLowering &TLI, SDNodeFlags Flags) {
5211   // TODO: What fast-math-flags should be set on the floating-point nodes?
5212 
5213   if (Op.getValueType() == MVT::f32 &&
5214       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5215     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5216 
5217     // Get the exponent.
5218     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5219 
5220     // Get the significand and build it into a floating-point number with
5221     // exponent of 1.
5222     SDValue X = GetSignificand(DAG, Op1, dl);
5223 
5224     // Different possible minimax approximations of significand in
5225     // floating-point for various degrees of accuracy over [1,2].
5226     SDValue Log2ofMantissa;
5227     if (LimitFloatPrecision <= 6) {
5228       // For floating-point precision of 6:
5229       //
5230       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5231       //
5232       // error 0.0049451742, which is more than 7 bits
5233       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5234                                getF32Constant(DAG, 0xbeb08fe0, dl));
5235       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5236                                getF32Constant(DAG, 0x40019463, dl));
5237       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5238       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5239                                    getF32Constant(DAG, 0x3fd6633d, dl));
5240     } else if (LimitFloatPrecision <= 12) {
5241       // For floating-point precision of 12:
5242       //
5243       //   Log2ofMantissa =
5244       //     -2.51285454f +
5245       //       (4.07009056f +
5246       //         (-2.12067489f +
5247       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5248       //
5249       // error 0.0000876136000, which is better than 13 bits
5250       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5251                                getF32Constant(DAG, 0xbda7262e, dl));
5252       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5253                                getF32Constant(DAG, 0x3f25280b, dl));
5254       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5255       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5256                                getF32Constant(DAG, 0x4007b923, dl));
5257       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5258       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5259                                getF32Constant(DAG, 0x40823e2f, dl));
5260       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5261       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5262                                    getF32Constant(DAG, 0x4020d29c, dl));
5263     } else { // LimitFloatPrecision <= 18
5264       // For floating-point precision of 18:
5265       //
5266       //   Log2ofMantissa =
5267       //     -3.0400495f +
5268       //       (6.1129976f +
5269       //         (-5.3420409f +
5270       //           (3.2865683f +
5271       //             (-1.2669343f +
5272       //               (0.27515199f -
5273       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5274       //
5275       // error 0.0000018516, which is better than 18 bits
5276       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5277                                getF32Constant(DAG, 0xbcd2769e, dl));
5278       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5279                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5280       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5281       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5282                                getF32Constant(DAG, 0x3fa22ae7, dl));
5283       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5284       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5285                                getF32Constant(DAG, 0x40525723, dl));
5286       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5287       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5288                                getF32Constant(DAG, 0x40aaf200, dl));
5289       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5290       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5291                                getF32Constant(DAG, 0x40c39dad, dl));
5292       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5293       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5294                                    getF32Constant(DAG, 0x4042902c, dl));
5295     }
5296 
5297     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5298   }
5299 
5300   // No special expansion.
5301   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5302 }
5303 
5304 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5305 /// limited-precision mode.
5306 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5307                            const TargetLowering &TLI, SDNodeFlags Flags) {
5308   // TODO: What fast-math-flags should be set on the floating-point nodes?
5309 
5310   if (Op.getValueType() == MVT::f32 &&
5311       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5312     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5313 
5314     // Scale the exponent by log10(2) [0.30102999f].
5315     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5316     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5317                                         getF32Constant(DAG, 0x3e9a209a, dl));
5318 
5319     // Get the significand and build it into a floating-point number with
5320     // exponent of 1.
5321     SDValue X = GetSignificand(DAG, Op1, dl);
5322 
5323     SDValue Log10ofMantissa;
5324     if (LimitFloatPrecision <= 6) {
5325       // For floating-point precision of 6:
5326       //
5327       //   Log10ofMantissa =
5328       //     -0.50419619f +
5329       //       (0.60948995f - 0.10380950f * x) * x;
5330       //
5331       // error 0.0014886165, which is 6 bits
5332       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5333                                getF32Constant(DAG, 0xbdd49a13, dl));
5334       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5335                                getF32Constant(DAG, 0x3f1c0789, dl));
5336       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5337       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5338                                     getF32Constant(DAG, 0x3f011300, dl));
5339     } else if (LimitFloatPrecision <= 12) {
5340       // For floating-point precision of 12:
5341       //
5342       //   Log10ofMantissa =
5343       //     -0.64831180f +
5344       //       (0.91751397f +
5345       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5346       //
5347       // error 0.00019228036, which is better than 12 bits
5348       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5349                                getF32Constant(DAG, 0x3d431f31, dl));
5350       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5351                                getF32Constant(DAG, 0x3ea21fb2, dl));
5352       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5353       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5354                                getF32Constant(DAG, 0x3f6ae232, dl));
5355       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5356       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5357                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5358     } else { // LimitFloatPrecision <= 18
5359       // For floating-point precision of 18:
5360       //
5361       //   Log10ofMantissa =
5362       //     -0.84299375f +
5363       //       (1.5327582f +
5364       //         (-1.0688956f +
5365       //           (0.49102474f +
5366       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5367       //
5368       // error 0.0000037995730, which is better than 18 bits
5369       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5370                                getF32Constant(DAG, 0x3c5d51ce, dl));
5371       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5372                                getF32Constant(DAG, 0x3e00685a, dl));
5373       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5374       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5375                                getF32Constant(DAG, 0x3efb6798, dl));
5376       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5377       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5378                                getF32Constant(DAG, 0x3f88d192, dl));
5379       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5380       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5381                                getF32Constant(DAG, 0x3fc4316c, dl));
5382       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5383       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5384                                     getF32Constant(DAG, 0x3f57ce70, dl));
5385     }
5386 
5387     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5388   }
5389 
5390   // No special expansion.
5391   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5392 }
5393 
5394 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5395 /// limited-precision mode.
5396 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5397                           const TargetLowering &TLI, SDNodeFlags Flags) {
5398   if (Op.getValueType() == MVT::f32 &&
5399       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5400     return getLimitedPrecisionExp2(Op, dl, DAG);
5401 
5402   // No special expansion.
5403   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5404 }
5405 
5406 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5407 /// limited-precision mode with x == 10.0f.
5408 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5409                          SelectionDAG &DAG, const TargetLowering &TLI,
5410                          SDNodeFlags Flags) {
5411   bool IsExp10 = false;
5412   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5413       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5414     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5415       APFloat Ten(10.0f);
5416       IsExp10 = LHSC->isExactlyValue(Ten);
5417     }
5418   }
5419 
5420   // TODO: What fast-math-flags should be set on the FMUL node?
5421   if (IsExp10) {
5422     // Put the exponent in the right bit position for later addition to the
5423     // final result:
5424     //
5425     //   #define LOG2OF10 3.3219281f
5426     //   t0 = Op * LOG2OF10;
5427     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5428                              getF32Constant(DAG, 0x40549a78, dl));
5429     return getLimitedPrecisionExp2(t0, dl, DAG);
5430   }
5431 
5432   // No special expansion.
5433   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5434 }
5435 
5436 /// ExpandPowI - Expand a llvm.powi intrinsic.
5437 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5438                           SelectionDAG &DAG) {
5439   // If RHS is a constant, we can expand this out to a multiplication tree if
5440   // it's beneficial on the target, otherwise we end up lowering to a call to
5441   // __powidf2 (for example).
5442   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5443     unsigned Val = RHSC->getSExtValue();
5444 
5445     // powi(x, 0) -> 1.0
5446     if (Val == 0)
5447       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5448 
5449     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5450             Val, DAG.shouldOptForSize())) {
5451       // Get the exponent as a positive value.
5452       if ((int)Val < 0)
5453         Val = -Val;
5454       // We use the simple binary decomposition method to generate the multiply
5455       // sequence.  There are more optimal ways to do this (for example,
5456       // powi(x,15) generates one more multiply than it should), but this has
5457       // the benefit of being both really simple and much better than a libcall.
5458       SDValue Res; // Logically starts equal to 1.0
5459       SDValue CurSquare = LHS;
5460       // TODO: Intrinsics should have fast-math-flags that propagate to these
5461       // nodes.
5462       while (Val) {
5463         if (Val & 1) {
5464           if (Res.getNode())
5465             Res =
5466                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5467           else
5468             Res = CurSquare; // 1.0*CurSquare.
5469         }
5470 
5471         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5472                                 CurSquare, CurSquare);
5473         Val >>= 1;
5474       }
5475 
5476       // If the original was negative, invert the result, producing 1/(x*x*x).
5477       if (RHSC->getSExtValue() < 0)
5478         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5479                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5480       return Res;
5481     }
5482   }
5483 
5484   // Otherwise, expand to a libcall.
5485   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5486 }
5487 
5488 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5489                             SDValue LHS, SDValue RHS, SDValue Scale,
5490                             SelectionDAG &DAG, const TargetLowering &TLI) {
5491   EVT VT = LHS.getValueType();
5492   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5493   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5494   LLVMContext &Ctx = *DAG.getContext();
5495 
5496   // If the type is legal but the operation isn't, this node might survive all
5497   // the way to operation legalization. If we end up there and we do not have
5498   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5499   // node.
5500 
5501   // Coax the legalizer into expanding the node during type legalization instead
5502   // by bumping the size by one bit. This will force it to Promote, enabling the
5503   // early expansion and avoiding the need to expand later.
5504 
5505   // We don't have to do this if Scale is 0; that can always be expanded, unless
5506   // it's a saturating signed operation. Those can experience true integer
5507   // division overflow, a case which we must avoid.
5508 
5509   // FIXME: We wouldn't have to do this (or any of the early
5510   // expansion/promotion) if it was possible to expand a libcall of an
5511   // illegal type during operation legalization. But it's not, so things
5512   // get a bit hacky.
5513   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5514   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5515       (TLI.isTypeLegal(VT) ||
5516        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5517     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5518         Opcode, VT, ScaleInt);
5519     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5520       EVT PromVT;
5521       if (VT.isScalarInteger())
5522         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5523       else if (VT.isVector()) {
5524         PromVT = VT.getVectorElementType();
5525         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5526         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5527       } else
5528         llvm_unreachable("Wrong VT for DIVFIX?");
5529       if (Signed) {
5530         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5531         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5532       } else {
5533         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5534         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5535       }
5536       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5537       // For saturating operations, we need to shift up the LHS to get the
5538       // proper saturation width, and then shift down again afterwards.
5539       if (Saturating)
5540         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5541                           DAG.getConstant(1, DL, ShiftTy));
5542       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5543       if (Saturating)
5544         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5545                           DAG.getConstant(1, DL, ShiftTy));
5546       return DAG.getZExtOrTrunc(Res, DL, VT);
5547     }
5548   }
5549 
5550   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5551 }
5552 
5553 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5554 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5555 static void
5556 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5557                      const SDValue &N) {
5558   switch (N.getOpcode()) {
5559   case ISD::CopyFromReg: {
5560     SDValue Op = N.getOperand(1);
5561     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5562                       Op.getValueType().getSizeInBits());
5563     return;
5564   }
5565   case ISD::BITCAST:
5566   case ISD::AssertZext:
5567   case ISD::AssertSext:
5568   case ISD::TRUNCATE:
5569     getUnderlyingArgRegs(Regs, N.getOperand(0));
5570     return;
5571   case ISD::BUILD_PAIR:
5572   case ISD::BUILD_VECTOR:
5573   case ISD::CONCAT_VECTORS:
5574     for (SDValue Op : N->op_values())
5575       getUnderlyingArgRegs(Regs, Op);
5576     return;
5577   default:
5578     return;
5579   }
5580 }
5581 
5582 /// If the DbgValueInst is a dbg_value of a function argument, create the
5583 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5584 /// instruction selection, they will be inserted to the entry BB.
5585 /// We don't currently support this for variadic dbg_values, as they shouldn't
5586 /// appear for function arguments or in the prologue.
5587 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5588     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5589     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5590   const Argument *Arg = dyn_cast<Argument>(V);
5591   if (!Arg)
5592     return false;
5593 
5594   MachineFunction &MF = DAG.getMachineFunction();
5595   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5596 
5597   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5598   // we've been asked to pursue.
5599   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5600                               bool Indirect) {
5601     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5602       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5603       // pointing at the VReg, which will be patched up later.
5604       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5605       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5606           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5607           /* isKill */ false, /* isDead */ false,
5608           /* isUndef */ false, /* isEarlyClobber */ false,
5609           /* SubReg */ 0, /* isDebug */ true)});
5610 
5611       auto *NewDIExpr = FragExpr;
5612       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5613       // the DIExpression.
5614       if (Indirect)
5615         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5616       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5617       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5618       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5619     } else {
5620       // Create a completely standard DBG_VALUE.
5621       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5622       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5623     }
5624   };
5625 
5626   if (Kind == FuncArgumentDbgValueKind::Value) {
5627     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5628     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5629     // the entry block.
5630     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5631     if (!IsInEntryBlock)
5632       return false;
5633 
5634     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5635     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5636     // variable that also is a param.
5637     //
5638     // Although, if we are at the top of the entry block already, we can still
5639     // emit using ArgDbgValue. This might catch some situations when the
5640     // dbg.value refers to an argument that isn't used in the entry block, so
5641     // any CopyToReg node would be optimized out and the only way to express
5642     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5643     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5644     // we should only emit as ArgDbgValue if the Variable is an argument to the
5645     // current function, and the dbg.value intrinsic is found in the entry
5646     // block.
5647     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5648         !DL->getInlinedAt();
5649     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5650     if (!IsInPrologue && !VariableIsFunctionInputArg)
5651       return false;
5652 
5653     // Here we assume that a function argument on IR level only can be used to
5654     // describe one input parameter on source level. If we for example have
5655     // source code like this
5656     //
5657     //    struct A { long x, y; };
5658     //    void foo(struct A a, long b) {
5659     //      ...
5660     //      b = a.x;
5661     //      ...
5662     //    }
5663     //
5664     // and IR like this
5665     //
5666     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5667     //  entry:
5668     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5669     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5670     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5671     //    ...
5672     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5673     //    ...
5674     //
5675     // then the last dbg.value is describing a parameter "b" using a value that
5676     // is an argument. But since we already has used %a1 to describe a parameter
5677     // we should not handle that last dbg.value here (that would result in an
5678     // incorrect hoisting of the DBG_VALUE to the function entry).
5679     // Notice that we allow one dbg.value per IR level argument, to accommodate
5680     // for the situation with fragments above.
5681     if (VariableIsFunctionInputArg) {
5682       unsigned ArgNo = Arg->getArgNo();
5683       if (ArgNo >= FuncInfo.DescribedArgs.size())
5684         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5685       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5686         return false;
5687       FuncInfo.DescribedArgs.set(ArgNo);
5688     }
5689   }
5690 
5691   bool IsIndirect = false;
5692   std::optional<MachineOperand> Op;
5693   // Some arguments' frame index is recorded during argument lowering.
5694   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5695   if (FI != std::numeric_limits<int>::max())
5696     Op = MachineOperand::CreateFI(FI);
5697 
5698   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5699   if (!Op && N.getNode()) {
5700     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5701     Register Reg;
5702     if (ArgRegsAndSizes.size() == 1)
5703       Reg = ArgRegsAndSizes.front().first;
5704 
5705     if (Reg && Reg.isVirtual()) {
5706       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5707       Register PR = RegInfo.getLiveInPhysReg(Reg);
5708       if (PR)
5709         Reg = PR;
5710     }
5711     if (Reg) {
5712       Op = MachineOperand::CreateReg(Reg, false);
5713       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5714     }
5715   }
5716 
5717   if (!Op && N.getNode()) {
5718     // Check if frame index is available.
5719     SDValue LCandidate = peekThroughBitcasts(N);
5720     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5721       if (FrameIndexSDNode *FINode =
5722           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5723         Op = MachineOperand::CreateFI(FINode->getIndex());
5724   }
5725 
5726   if (!Op) {
5727     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5728     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5729                                          SplitRegs) {
5730       unsigned Offset = 0;
5731       for (const auto &RegAndSize : SplitRegs) {
5732         // If the expression is already a fragment, the current register
5733         // offset+size might extend beyond the fragment. In this case, only
5734         // the register bits that are inside the fragment are relevant.
5735         int RegFragmentSizeInBits = RegAndSize.second;
5736         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5737           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5738           // The register is entirely outside the expression fragment,
5739           // so is irrelevant for debug info.
5740           if (Offset >= ExprFragmentSizeInBits)
5741             break;
5742           // The register is partially outside the expression fragment, only
5743           // the low bits within the fragment are relevant for debug info.
5744           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5745             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5746           }
5747         }
5748 
5749         auto FragmentExpr = DIExpression::createFragmentExpression(
5750             Expr, Offset, RegFragmentSizeInBits);
5751         Offset += RegAndSize.second;
5752         // If a valid fragment expression cannot be created, the variable's
5753         // correct value cannot be determined and so it is set as Undef.
5754         if (!FragmentExpr) {
5755           SDDbgValue *SDV = DAG.getConstantDbgValue(
5756               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5757           DAG.AddDbgValue(SDV, false);
5758           continue;
5759         }
5760         MachineInstr *NewMI =
5761             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5762                              Kind != FuncArgumentDbgValueKind::Value);
5763         FuncInfo.ArgDbgValues.push_back(NewMI);
5764       }
5765     };
5766 
5767     // Check if ValueMap has reg number.
5768     DenseMap<const Value *, Register>::const_iterator
5769       VMI = FuncInfo.ValueMap.find(V);
5770     if (VMI != FuncInfo.ValueMap.end()) {
5771       const auto &TLI = DAG.getTargetLoweringInfo();
5772       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5773                        V->getType(), std::nullopt);
5774       if (RFV.occupiesMultipleRegs()) {
5775         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5776         return true;
5777       }
5778 
5779       Op = MachineOperand::CreateReg(VMI->second, false);
5780       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5781     } else if (ArgRegsAndSizes.size() > 1) {
5782       // This was split due to the calling convention, and no virtual register
5783       // mapping exists for the value.
5784       splitMultiRegDbgValue(ArgRegsAndSizes);
5785       return true;
5786     }
5787   }
5788 
5789   if (!Op)
5790     return false;
5791 
5792   assert(Variable->isValidLocationForIntrinsic(DL) &&
5793          "Expected inlined-at fields to agree");
5794   MachineInstr *NewMI = nullptr;
5795 
5796   if (Op->isReg())
5797     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5798   else
5799     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5800                     Variable, Expr);
5801 
5802   // Otherwise, use ArgDbgValues.
5803   FuncInfo.ArgDbgValues.push_back(NewMI);
5804   return true;
5805 }
5806 
5807 /// Return the appropriate SDDbgValue based on N.
5808 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5809                                              DILocalVariable *Variable,
5810                                              DIExpression *Expr,
5811                                              const DebugLoc &dl,
5812                                              unsigned DbgSDNodeOrder) {
5813   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5814     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5815     // stack slot locations.
5816     //
5817     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5818     // debug values here after optimization:
5819     //
5820     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5821     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5822     //
5823     // Both describe the direct values of their associated variables.
5824     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5825                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5826   }
5827   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5828                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5829 }
5830 
5831 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5832   switch (Intrinsic) {
5833   case Intrinsic::smul_fix:
5834     return ISD::SMULFIX;
5835   case Intrinsic::umul_fix:
5836     return ISD::UMULFIX;
5837   case Intrinsic::smul_fix_sat:
5838     return ISD::SMULFIXSAT;
5839   case Intrinsic::umul_fix_sat:
5840     return ISD::UMULFIXSAT;
5841   case Intrinsic::sdiv_fix:
5842     return ISD::SDIVFIX;
5843   case Intrinsic::udiv_fix:
5844     return ISD::UDIVFIX;
5845   case Intrinsic::sdiv_fix_sat:
5846     return ISD::SDIVFIXSAT;
5847   case Intrinsic::udiv_fix_sat:
5848     return ISD::UDIVFIXSAT;
5849   default:
5850     llvm_unreachable("Unhandled fixed point intrinsic");
5851   }
5852 }
5853 
5854 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5855                                            const char *FunctionName) {
5856   assert(FunctionName && "FunctionName must not be nullptr");
5857   SDValue Callee = DAG.getExternalSymbol(
5858       FunctionName,
5859       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5860   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5861 }
5862 
5863 /// Given a @llvm.call.preallocated.setup, return the corresponding
5864 /// preallocated call.
5865 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5866   assert(cast<CallBase>(PreallocatedSetup)
5867                  ->getCalledFunction()
5868                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5869          "expected call_preallocated_setup Value");
5870   for (const auto *U : PreallocatedSetup->users()) {
5871     auto *UseCall = cast<CallBase>(U);
5872     const Function *Fn = UseCall->getCalledFunction();
5873     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5874       return UseCall;
5875     }
5876   }
5877   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5878 }
5879 
5880 /// Lower the call to the specified intrinsic function.
5881 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5882                                              unsigned Intrinsic) {
5883   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5884   SDLoc sdl = getCurSDLoc();
5885   DebugLoc dl = getCurDebugLoc();
5886   SDValue Res;
5887 
5888   SDNodeFlags Flags;
5889   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5890     Flags.copyFMF(*FPOp);
5891 
5892   switch (Intrinsic) {
5893   default:
5894     // By default, turn this into a target intrinsic node.
5895     visitTargetIntrinsic(I, Intrinsic);
5896     return;
5897   case Intrinsic::vscale: {
5898     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5899     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5900     return;
5901   }
5902   case Intrinsic::vastart:  visitVAStart(I); return;
5903   case Intrinsic::vaend:    visitVAEnd(I); return;
5904   case Intrinsic::vacopy:   visitVACopy(I); return;
5905   case Intrinsic::returnaddress:
5906     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5907                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5908                              getValue(I.getArgOperand(0))));
5909     return;
5910   case Intrinsic::addressofreturnaddress:
5911     setValue(&I,
5912              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5913                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5914     return;
5915   case Intrinsic::sponentry:
5916     setValue(&I,
5917              DAG.getNode(ISD::SPONENTRY, sdl,
5918                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5919     return;
5920   case Intrinsic::frameaddress:
5921     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5922                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5923                              getValue(I.getArgOperand(0))));
5924     return;
5925   case Intrinsic::read_volatile_register:
5926   case Intrinsic::read_register: {
5927     Value *Reg = I.getArgOperand(0);
5928     SDValue Chain = getRoot();
5929     SDValue RegName =
5930         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5931     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5932     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5933       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5934     setValue(&I, Res);
5935     DAG.setRoot(Res.getValue(1));
5936     return;
5937   }
5938   case Intrinsic::write_register: {
5939     Value *Reg = I.getArgOperand(0);
5940     Value *RegValue = I.getArgOperand(1);
5941     SDValue Chain = getRoot();
5942     SDValue RegName =
5943         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5944     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5945                             RegName, getValue(RegValue)));
5946     return;
5947   }
5948   case Intrinsic::memcpy: {
5949     const auto &MCI = cast<MemCpyInst>(I);
5950     SDValue Op1 = getValue(I.getArgOperand(0));
5951     SDValue Op2 = getValue(I.getArgOperand(1));
5952     SDValue Op3 = getValue(I.getArgOperand(2));
5953     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5954     Align DstAlign = MCI.getDestAlign().valueOrOne();
5955     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5956     Align Alignment = std::min(DstAlign, SrcAlign);
5957     bool isVol = MCI.isVolatile();
5958     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5959     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5960     // node.
5961     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5962     SDValue MC = DAG.getMemcpy(
5963         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5964         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
5965         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5966     updateDAGForMaybeTailCall(MC);
5967     return;
5968   }
5969   case Intrinsic::memcpy_inline: {
5970     const auto &MCI = cast<MemCpyInlineInst>(I);
5971     SDValue Dst = getValue(I.getArgOperand(0));
5972     SDValue Src = getValue(I.getArgOperand(1));
5973     SDValue Size = getValue(I.getArgOperand(2));
5974     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5975     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5976     Align DstAlign = MCI.getDestAlign().valueOrOne();
5977     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5978     Align Alignment = std::min(DstAlign, SrcAlign);
5979     bool isVol = MCI.isVolatile();
5980     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5981     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5982     // node.
5983     SDValue MC = DAG.getMemcpy(
5984         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5985         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
5986         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5987     updateDAGForMaybeTailCall(MC);
5988     return;
5989   }
5990   case Intrinsic::memset: {
5991     const auto &MSI = cast<MemSetInst>(I);
5992     SDValue Op1 = getValue(I.getArgOperand(0));
5993     SDValue Op2 = getValue(I.getArgOperand(1));
5994     SDValue Op3 = getValue(I.getArgOperand(2));
5995     // @llvm.memset defines 0 and 1 to both mean no alignment.
5996     Align Alignment = MSI.getDestAlign().valueOrOne();
5997     bool isVol = MSI.isVolatile();
5998     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5999     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6000     SDValue MS = DAG.getMemset(
6001         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6002         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6003     updateDAGForMaybeTailCall(MS);
6004     return;
6005   }
6006   case Intrinsic::memset_inline: {
6007     const auto &MSII = cast<MemSetInlineInst>(I);
6008     SDValue Dst = getValue(I.getArgOperand(0));
6009     SDValue Value = getValue(I.getArgOperand(1));
6010     SDValue Size = getValue(I.getArgOperand(2));
6011     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6012     // @llvm.memset defines 0 and 1 to both mean no alignment.
6013     Align DstAlign = MSII.getDestAlign().valueOrOne();
6014     bool isVol = MSII.isVolatile();
6015     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6016     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6017     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6018                                /* AlwaysInline */ true, isTC,
6019                                MachinePointerInfo(I.getArgOperand(0)),
6020                                I.getAAMetadata());
6021     updateDAGForMaybeTailCall(MC);
6022     return;
6023   }
6024   case Intrinsic::memmove: {
6025     const auto &MMI = cast<MemMoveInst>(I);
6026     SDValue Op1 = getValue(I.getArgOperand(0));
6027     SDValue Op2 = getValue(I.getArgOperand(1));
6028     SDValue Op3 = getValue(I.getArgOperand(2));
6029     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6030     Align DstAlign = MMI.getDestAlign().valueOrOne();
6031     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6032     Align Alignment = std::min(DstAlign, SrcAlign);
6033     bool isVol = MMI.isVolatile();
6034     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6035     // FIXME: Support passing different dest/src alignments to the memmove DAG
6036     // node.
6037     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6038     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6039                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6040                                 MachinePointerInfo(I.getArgOperand(1)),
6041                                 I.getAAMetadata(), AA);
6042     updateDAGForMaybeTailCall(MM);
6043     return;
6044   }
6045   case Intrinsic::memcpy_element_unordered_atomic: {
6046     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6047     SDValue Dst = getValue(MI.getRawDest());
6048     SDValue Src = getValue(MI.getRawSource());
6049     SDValue Length = getValue(MI.getLength());
6050 
6051     Type *LengthTy = MI.getLength()->getType();
6052     unsigned ElemSz = MI.getElementSizeInBytes();
6053     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6054     SDValue MC =
6055         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6056                             isTC, MachinePointerInfo(MI.getRawDest()),
6057                             MachinePointerInfo(MI.getRawSource()));
6058     updateDAGForMaybeTailCall(MC);
6059     return;
6060   }
6061   case Intrinsic::memmove_element_unordered_atomic: {
6062     auto &MI = cast<AtomicMemMoveInst>(I);
6063     SDValue Dst = getValue(MI.getRawDest());
6064     SDValue Src = getValue(MI.getRawSource());
6065     SDValue Length = getValue(MI.getLength());
6066 
6067     Type *LengthTy = MI.getLength()->getType();
6068     unsigned ElemSz = MI.getElementSizeInBytes();
6069     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6070     SDValue MC =
6071         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6072                              isTC, MachinePointerInfo(MI.getRawDest()),
6073                              MachinePointerInfo(MI.getRawSource()));
6074     updateDAGForMaybeTailCall(MC);
6075     return;
6076   }
6077   case Intrinsic::memset_element_unordered_atomic: {
6078     auto &MI = cast<AtomicMemSetInst>(I);
6079     SDValue Dst = getValue(MI.getRawDest());
6080     SDValue Val = getValue(MI.getValue());
6081     SDValue Length = getValue(MI.getLength());
6082 
6083     Type *LengthTy = MI.getLength()->getType();
6084     unsigned ElemSz = MI.getElementSizeInBytes();
6085     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6086     SDValue MC =
6087         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6088                             isTC, MachinePointerInfo(MI.getRawDest()));
6089     updateDAGForMaybeTailCall(MC);
6090     return;
6091   }
6092   case Intrinsic::call_preallocated_setup: {
6093     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6094     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6095     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6096                               getRoot(), SrcValue);
6097     setValue(&I, Res);
6098     DAG.setRoot(Res);
6099     return;
6100   }
6101   case Intrinsic::call_preallocated_arg: {
6102     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6103     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6104     SDValue Ops[3];
6105     Ops[0] = getRoot();
6106     Ops[1] = SrcValue;
6107     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6108                                    MVT::i32); // arg index
6109     SDValue Res = DAG.getNode(
6110         ISD::PREALLOCATED_ARG, sdl,
6111         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6112     setValue(&I, Res);
6113     DAG.setRoot(Res.getValue(1));
6114     return;
6115   }
6116   case Intrinsic::dbg_declare: {
6117     // Debug intrinsics are handled separately in assignment tracking mode.
6118     if (AssignmentTrackingEnabled)
6119       return;
6120     // Assume dbg.declare can not currently use DIArgList, i.e.
6121     // it is non-variadic.
6122     const auto &DI = cast<DbgVariableIntrinsic>(I);
6123     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6124     DILocalVariable *Variable = DI.getVariable();
6125     DIExpression *Expression = DI.getExpression();
6126     dropDanglingDebugInfo(Variable, Expression);
6127     assert(Variable && "Missing variable");
6128     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6129                       << "\n");
6130     // Check if address has undef value.
6131     const Value *Address = DI.getVariableLocationOp(0);
6132     if (!Address || isa<UndefValue>(Address) ||
6133         (Address->use_empty() && !isa<Argument>(Address))) {
6134       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6135                         << " (bad/undef/unused-arg address)\n");
6136       return;
6137     }
6138 
6139     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6140 
6141     // Check if this variable can be described by a frame index, typically
6142     // either as a static alloca or a byval parameter.
6143     int FI = std::numeric_limits<int>::max();
6144     if (const auto *AI =
6145             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6146       if (AI->isStaticAlloca()) {
6147         auto I = FuncInfo.StaticAllocaMap.find(AI);
6148         if (I != FuncInfo.StaticAllocaMap.end())
6149           FI = I->second;
6150       }
6151     } else if (const auto *Arg = dyn_cast<Argument>(
6152                    Address->stripInBoundsConstantOffsets())) {
6153       FI = FuncInfo.getArgumentFrameIndex(Arg);
6154     }
6155 
6156     // llvm.dbg.declare is handled as a frame index in the MachineFunction
6157     // variable table.
6158     if (FI != std::numeric_limits<int>::max()) {
6159       LLVM_DEBUG(dbgs() << "Skipping " << DI
6160                         << " (variable info stashed in MF side table)\n");
6161       return;
6162     }
6163 
6164     SDValue &N = NodeMap[Address];
6165     if (!N.getNode() && isa<Argument>(Address))
6166       // Check unused arguments map.
6167       N = UnusedArgNodeMap[Address];
6168     SDDbgValue *SDV;
6169     if (N.getNode()) {
6170       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6171         Address = BCI->getOperand(0);
6172       // Parameters are handled specially.
6173       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6174       if (isParameter && FINode) {
6175         // Byval parameter. We have a frame index at this point.
6176         SDV =
6177             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6178                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6179       } else if (isa<Argument>(Address)) {
6180         // Address is an argument, so try to emit its dbg value using
6181         // virtual register info from the FuncInfo.ValueMap.
6182         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6183                                  FuncArgumentDbgValueKind::Declare, N);
6184         return;
6185       } else {
6186         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6187                               true, dl, SDNodeOrder);
6188       }
6189       DAG.AddDbgValue(SDV, isParameter);
6190     } else {
6191       // If Address is an argument then try to emit its dbg value using
6192       // virtual register info from the FuncInfo.ValueMap.
6193       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6194                                     FuncArgumentDbgValueKind::Declare, N)) {
6195         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6196                           << " (could not emit func-arg dbg_value)\n");
6197       }
6198     }
6199     return;
6200   }
6201   case Intrinsic::dbg_label: {
6202     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6203     DILabel *Label = DI.getLabel();
6204     assert(Label && "Missing label");
6205 
6206     SDDbgLabel *SDV;
6207     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6208     DAG.AddDbgLabel(SDV);
6209     return;
6210   }
6211   case Intrinsic::dbg_assign: {
6212     // Debug intrinsics are handled seperately in assignment tracking mode.
6213     assert(AssignmentTrackingEnabled &&
6214            "expected assignment tracking to be enabled");
6215     return;
6216   }
6217   case Intrinsic::dbg_value: {
6218     // Debug intrinsics are handled seperately in assignment tracking mode.
6219     if (AssignmentTrackingEnabled)
6220       return;
6221     const DbgValueInst &DI = cast<DbgValueInst>(I);
6222     assert(DI.getVariable() && "Missing variable");
6223 
6224     DILocalVariable *Variable = DI.getVariable();
6225     DIExpression *Expression = DI.getExpression();
6226     dropDanglingDebugInfo(Variable, Expression);
6227     SmallVector<Value *, 4> Values(DI.getValues());
6228     if (Values.empty())
6229       return;
6230 
6231     if (llvm::is_contained(Values, nullptr))
6232       return;
6233 
6234     bool IsVariadic = DI.hasArgList();
6235     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6236                           SDNodeOrder, IsVariadic))
6237       addDanglingDebugInfo(&DI, SDNodeOrder);
6238     return;
6239   }
6240 
6241   case Intrinsic::eh_typeid_for: {
6242     // Find the type id for the given typeinfo.
6243     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6244     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6245     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6246     setValue(&I, Res);
6247     return;
6248   }
6249 
6250   case Intrinsic::eh_return_i32:
6251   case Intrinsic::eh_return_i64:
6252     DAG.getMachineFunction().setCallsEHReturn(true);
6253     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6254                             MVT::Other,
6255                             getControlRoot(),
6256                             getValue(I.getArgOperand(0)),
6257                             getValue(I.getArgOperand(1))));
6258     return;
6259   case Intrinsic::eh_unwind_init:
6260     DAG.getMachineFunction().setCallsUnwindInit(true);
6261     return;
6262   case Intrinsic::eh_dwarf_cfa:
6263     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6264                              TLI.getPointerTy(DAG.getDataLayout()),
6265                              getValue(I.getArgOperand(0))));
6266     return;
6267   case Intrinsic::eh_sjlj_callsite: {
6268     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6269     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6270     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6271 
6272     MMI.setCurrentCallSite(CI->getZExtValue());
6273     return;
6274   }
6275   case Intrinsic::eh_sjlj_functioncontext: {
6276     // Get and store the index of the function context.
6277     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6278     AllocaInst *FnCtx =
6279       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6280     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6281     MFI.setFunctionContextIndex(FI);
6282     return;
6283   }
6284   case Intrinsic::eh_sjlj_setjmp: {
6285     SDValue Ops[2];
6286     Ops[0] = getRoot();
6287     Ops[1] = getValue(I.getArgOperand(0));
6288     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6289                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6290     setValue(&I, Op.getValue(0));
6291     DAG.setRoot(Op.getValue(1));
6292     return;
6293   }
6294   case Intrinsic::eh_sjlj_longjmp:
6295     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6296                             getRoot(), getValue(I.getArgOperand(0))));
6297     return;
6298   case Intrinsic::eh_sjlj_setup_dispatch:
6299     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6300                             getRoot()));
6301     return;
6302   case Intrinsic::masked_gather:
6303     visitMaskedGather(I);
6304     return;
6305   case Intrinsic::masked_load:
6306     visitMaskedLoad(I);
6307     return;
6308   case Intrinsic::masked_scatter:
6309     visitMaskedScatter(I);
6310     return;
6311   case Intrinsic::masked_store:
6312     visitMaskedStore(I);
6313     return;
6314   case Intrinsic::masked_expandload:
6315     visitMaskedLoad(I, true /* IsExpanding */);
6316     return;
6317   case Intrinsic::masked_compressstore:
6318     visitMaskedStore(I, true /* IsCompressing */);
6319     return;
6320   case Intrinsic::powi:
6321     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6322                             getValue(I.getArgOperand(1)), DAG));
6323     return;
6324   case Intrinsic::log:
6325     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6326     return;
6327   case Intrinsic::log2:
6328     setValue(&I,
6329              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6330     return;
6331   case Intrinsic::log10:
6332     setValue(&I,
6333              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6334     return;
6335   case Intrinsic::exp:
6336     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6337     return;
6338   case Intrinsic::exp2:
6339     setValue(&I,
6340              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6341     return;
6342   case Intrinsic::pow:
6343     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6344                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6345     return;
6346   case Intrinsic::sqrt:
6347   case Intrinsic::fabs:
6348   case Intrinsic::sin:
6349   case Intrinsic::cos:
6350   case Intrinsic::floor:
6351   case Intrinsic::ceil:
6352   case Intrinsic::trunc:
6353   case Intrinsic::rint:
6354   case Intrinsic::nearbyint:
6355   case Intrinsic::round:
6356   case Intrinsic::roundeven:
6357   case Intrinsic::canonicalize: {
6358     unsigned Opcode;
6359     switch (Intrinsic) {
6360     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6361     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6362     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6363     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6364     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6365     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6366     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6367     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6368     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6369     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6370     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6371     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6372     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6373     }
6374 
6375     setValue(&I, DAG.getNode(Opcode, sdl,
6376                              getValue(I.getArgOperand(0)).getValueType(),
6377                              getValue(I.getArgOperand(0)), Flags));
6378     return;
6379   }
6380   case Intrinsic::lround:
6381   case Intrinsic::llround:
6382   case Intrinsic::lrint:
6383   case Intrinsic::llrint: {
6384     unsigned Opcode;
6385     switch (Intrinsic) {
6386     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6387     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6388     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6389     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6390     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6391     }
6392 
6393     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6394     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6395                              getValue(I.getArgOperand(0))));
6396     return;
6397   }
6398   case Intrinsic::minnum:
6399     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6400                              getValue(I.getArgOperand(0)).getValueType(),
6401                              getValue(I.getArgOperand(0)),
6402                              getValue(I.getArgOperand(1)), Flags));
6403     return;
6404   case Intrinsic::maxnum:
6405     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6406                              getValue(I.getArgOperand(0)).getValueType(),
6407                              getValue(I.getArgOperand(0)),
6408                              getValue(I.getArgOperand(1)), Flags));
6409     return;
6410   case Intrinsic::minimum:
6411     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6412                              getValue(I.getArgOperand(0)).getValueType(),
6413                              getValue(I.getArgOperand(0)),
6414                              getValue(I.getArgOperand(1)), Flags));
6415     return;
6416   case Intrinsic::maximum:
6417     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6418                              getValue(I.getArgOperand(0)).getValueType(),
6419                              getValue(I.getArgOperand(0)),
6420                              getValue(I.getArgOperand(1)), Flags));
6421     return;
6422   case Intrinsic::copysign:
6423     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6424                              getValue(I.getArgOperand(0)).getValueType(),
6425                              getValue(I.getArgOperand(0)),
6426                              getValue(I.getArgOperand(1)), Flags));
6427     return;
6428   case Intrinsic::arithmetic_fence: {
6429     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6430                              getValue(I.getArgOperand(0)).getValueType(),
6431                              getValue(I.getArgOperand(0)), Flags));
6432     return;
6433   }
6434   case Intrinsic::fma:
6435     setValue(&I, DAG.getNode(
6436                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6437                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6438                      getValue(I.getArgOperand(2)), Flags));
6439     return;
6440 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6441   case Intrinsic::INTRINSIC:
6442 #include "llvm/IR/ConstrainedOps.def"
6443     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6444     return;
6445 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6446 #include "llvm/IR/VPIntrinsics.def"
6447     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6448     return;
6449   case Intrinsic::fptrunc_round: {
6450     // Get the last argument, the metadata and convert it to an integer in the
6451     // call
6452     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6453     std::optional<RoundingMode> RoundMode =
6454         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6455 
6456     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6457 
6458     // Propagate fast-math-flags from IR to node(s).
6459     SDNodeFlags Flags;
6460     Flags.copyFMF(*cast<FPMathOperator>(&I));
6461     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6462 
6463     SDValue Result;
6464     Result = DAG.getNode(
6465         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6466         DAG.getTargetConstant((int)*RoundMode, sdl,
6467                               TLI.getPointerTy(DAG.getDataLayout())));
6468     setValue(&I, Result);
6469 
6470     return;
6471   }
6472   case Intrinsic::fmuladd: {
6473     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6474     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6475         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6476       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6477                                getValue(I.getArgOperand(0)).getValueType(),
6478                                getValue(I.getArgOperand(0)),
6479                                getValue(I.getArgOperand(1)),
6480                                getValue(I.getArgOperand(2)), Flags));
6481     } else {
6482       // TODO: Intrinsic calls should have fast-math-flags.
6483       SDValue Mul = DAG.getNode(
6484           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6485           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6486       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6487                                 getValue(I.getArgOperand(0)).getValueType(),
6488                                 Mul, getValue(I.getArgOperand(2)), Flags);
6489       setValue(&I, Add);
6490     }
6491     return;
6492   }
6493   case Intrinsic::convert_to_fp16:
6494     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6495                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6496                                          getValue(I.getArgOperand(0)),
6497                                          DAG.getTargetConstant(0, sdl,
6498                                                                MVT::i32))));
6499     return;
6500   case Intrinsic::convert_from_fp16:
6501     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6502                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6503                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6504                                          getValue(I.getArgOperand(0)))));
6505     return;
6506   case Intrinsic::fptosi_sat: {
6507     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6508     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6509                              getValue(I.getArgOperand(0)),
6510                              DAG.getValueType(VT.getScalarType())));
6511     return;
6512   }
6513   case Intrinsic::fptoui_sat: {
6514     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6515     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6516                              getValue(I.getArgOperand(0)),
6517                              DAG.getValueType(VT.getScalarType())));
6518     return;
6519   }
6520   case Intrinsic::set_rounding:
6521     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6522                       {getRoot(), getValue(I.getArgOperand(0))});
6523     setValue(&I, Res);
6524     DAG.setRoot(Res.getValue(0));
6525     return;
6526   case Intrinsic::is_fpclass: {
6527     const DataLayout DLayout = DAG.getDataLayout();
6528     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6529     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6530     FPClassTest Test = static_cast<FPClassTest>(
6531         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6532     MachineFunction &MF = DAG.getMachineFunction();
6533     const Function &F = MF.getFunction();
6534     SDValue Op = getValue(I.getArgOperand(0));
6535     SDNodeFlags Flags;
6536     Flags.setNoFPExcept(
6537         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6538     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6539     // expansion can use illegal types. Making expansion early allows
6540     // legalizing these types prior to selection.
6541     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6542       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6543       setValue(&I, Result);
6544       return;
6545     }
6546 
6547     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6548     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6549     setValue(&I, V);
6550     return;
6551   }
6552   case Intrinsic::pcmarker: {
6553     SDValue Tmp = getValue(I.getArgOperand(0));
6554     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6555     return;
6556   }
6557   case Intrinsic::readcyclecounter: {
6558     SDValue Op = getRoot();
6559     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6560                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6561     setValue(&I, Res);
6562     DAG.setRoot(Res.getValue(1));
6563     return;
6564   }
6565   case Intrinsic::bitreverse:
6566     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6567                              getValue(I.getArgOperand(0)).getValueType(),
6568                              getValue(I.getArgOperand(0))));
6569     return;
6570   case Intrinsic::bswap:
6571     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6572                              getValue(I.getArgOperand(0)).getValueType(),
6573                              getValue(I.getArgOperand(0))));
6574     return;
6575   case Intrinsic::cttz: {
6576     SDValue Arg = getValue(I.getArgOperand(0));
6577     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6578     EVT Ty = Arg.getValueType();
6579     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6580                              sdl, Ty, Arg));
6581     return;
6582   }
6583   case Intrinsic::ctlz: {
6584     SDValue Arg = getValue(I.getArgOperand(0));
6585     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6586     EVT Ty = Arg.getValueType();
6587     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6588                              sdl, Ty, Arg));
6589     return;
6590   }
6591   case Intrinsic::ctpop: {
6592     SDValue Arg = getValue(I.getArgOperand(0));
6593     EVT Ty = Arg.getValueType();
6594     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6595     return;
6596   }
6597   case Intrinsic::fshl:
6598   case Intrinsic::fshr: {
6599     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6600     SDValue X = getValue(I.getArgOperand(0));
6601     SDValue Y = getValue(I.getArgOperand(1));
6602     SDValue Z = getValue(I.getArgOperand(2));
6603     EVT VT = X.getValueType();
6604 
6605     if (X == Y) {
6606       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6607       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6608     } else {
6609       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6610       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6611     }
6612     return;
6613   }
6614   case Intrinsic::sadd_sat: {
6615     SDValue Op1 = getValue(I.getArgOperand(0));
6616     SDValue Op2 = getValue(I.getArgOperand(1));
6617     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6618     return;
6619   }
6620   case Intrinsic::uadd_sat: {
6621     SDValue Op1 = getValue(I.getArgOperand(0));
6622     SDValue Op2 = getValue(I.getArgOperand(1));
6623     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6624     return;
6625   }
6626   case Intrinsic::ssub_sat: {
6627     SDValue Op1 = getValue(I.getArgOperand(0));
6628     SDValue Op2 = getValue(I.getArgOperand(1));
6629     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6630     return;
6631   }
6632   case Intrinsic::usub_sat: {
6633     SDValue Op1 = getValue(I.getArgOperand(0));
6634     SDValue Op2 = getValue(I.getArgOperand(1));
6635     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6636     return;
6637   }
6638   case Intrinsic::sshl_sat: {
6639     SDValue Op1 = getValue(I.getArgOperand(0));
6640     SDValue Op2 = getValue(I.getArgOperand(1));
6641     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6642     return;
6643   }
6644   case Intrinsic::ushl_sat: {
6645     SDValue Op1 = getValue(I.getArgOperand(0));
6646     SDValue Op2 = getValue(I.getArgOperand(1));
6647     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6648     return;
6649   }
6650   case Intrinsic::smul_fix:
6651   case Intrinsic::umul_fix:
6652   case Intrinsic::smul_fix_sat:
6653   case Intrinsic::umul_fix_sat: {
6654     SDValue Op1 = getValue(I.getArgOperand(0));
6655     SDValue Op2 = getValue(I.getArgOperand(1));
6656     SDValue Op3 = getValue(I.getArgOperand(2));
6657     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6658                              Op1.getValueType(), Op1, Op2, Op3));
6659     return;
6660   }
6661   case Intrinsic::sdiv_fix:
6662   case Intrinsic::udiv_fix:
6663   case Intrinsic::sdiv_fix_sat:
6664   case Intrinsic::udiv_fix_sat: {
6665     SDValue Op1 = getValue(I.getArgOperand(0));
6666     SDValue Op2 = getValue(I.getArgOperand(1));
6667     SDValue Op3 = getValue(I.getArgOperand(2));
6668     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6669                               Op1, Op2, Op3, DAG, TLI));
6670     return;
6671   }
6672   case Intrinsic::smax: {
6673     SDValue Op1 = getValue(I.getArgOperand(0));
6674     SDValue Op2 = getValue(I.getArgOperand(1));
6675     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6676     return;
6677   }
6678   case Intrinsic::smin: {
6679     SDValue Op1 = getValue(I.getArgOperand(0));
6680     SDValue Op2 = getValue(I.getArgOperand(1));
6681     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6682     return;
6683   }
6684   case Intrinsic::umax: {
6685     SDValue Op1 = getValue(I.getArgOperand(0));
6686     SDValue Op2 = getValue(I.getArgOperand(1));
6687     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6688     return;
6689   }
6690   case Intrinsic::umin: {
6691     SDValue Op1 = getValue(I.getArgOperand(0));
6692     SDValue Op2 = getValue(I.getArgOperand(1));
6693     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6694     return;
6695   }
6696   case Intrinsic::abs: {
6697     // TODO: Preserve "int min is poison" arg in SDAG?
6698     SDValue Op1 = getValue(I.getArgOperand(0));
6699     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6700     return;
6701   }
6702   case Intrinsic::stacksave: {
6703     SDValue Op = getRoot();
6704     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6705     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6706     setValue(&I, Res);
6707     DAG.setRoot(Res.getValue(1));
6708     return;
6709   }
6710   case Intrinsic::stackrestore:
6711     Res = getValue(I.getArgOperand(0));
6712     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6713     return;
6714   case Intrinsic::get_dynamic_area_offset: {
6715     SDValue Op = getRoot();
6716     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6717     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6718     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6719     // target.
6720     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6721       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6722                          " intrinsic!");
6723     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6724                       Op);
6725     DAG.setRoot(Op);
6726     setValue(&I, Res);
6727     return;
6728   }
6729   case Intrinsic::stackguard: {
6730     MachineFunction &MF = DAG.getMachineFunction();
6731     const Module &M = *MF.getFunction().getParent();
6732     SDValue Chain = getRoot();
6733     if (TLI.useLoadStackGuardNode()) {
6734       Res = getLoadStackGuard(DAG, sdl, Chain);
6735     } else {
6736       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6737       const Value *Global = TLI.getSDagStackGuard(M);
6738       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6739       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6740                         MachinePointerInfo(Global, 0), Align,
6741                         MachineMemOperand::MOVolatile);
6742     }
6743     if (TLI.useStackGuardXorFP())
6744       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6745     DAG.setRoot(Chain);
6746     setValue(&I, Res);
6747     return;
6748   }
6749   case Intrinsic::stackprotector: {
6750     // Emit code into the DAG to store the stack guard onto the stack.
6751     MachineFunction &MF = DAG.getMachineFunction();
6752     MachineFrameInfo &MFI = MF.getFrameInfo();
6753     SDValue Src, Chain = getRoot();
6754 
6755     if (TLI.useLoadStackGuardNode())
6756       Src = getLoadStackGuard(DAG, sdl, Chain);
6757     else
6758       Src = getValue(I.getArgOperand(0));   // The guard's value.
6759 
6760     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6761 
6762     int FI = FuncInfo.StaticAllocaMap[Slot];
6763     MFI.setStackProtectorIndex(FI);
6764     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6765 
6766     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6767 
6768     // Store the stack protector onto the stack.
6769     Res = DAG.getStore(
6770         Chain, sdl, Src, FIN,
6771         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6772         MaybeAlign(), MachineMemOperand::MOVolatile);
6773     setValue(&I, Res);
6774     DAG.setRoot(Res);
6775     return;
6776   }
6777   case Intrinsic::objectsize:
6778     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6779 
6780   case Intrinsic::is_constant:
6781     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6782 
6783   case Intrinsic::annotation:
6784   case Intrinsic::ptr_annotation:
6785   case Intrinsic::launder_invariant_group:
6786   case Intrinsic::strip_invariant_group:
6787     // Drop the intrinsic, but forward the value
6788     setValue(&I, getValue(I.getOperand(0)));
6789     return;
6790 
6791   case Intrinsic::assume:
6792   case Intrinsic::experimental_noalias_scope_decl:
6793   case Intrinsic::var_annotation:
6794   case Intrinsic::sideeffect:
6795     // Discard annotate attributes, noalias scope declarations, assumptions, and
6796     // artificial side-effects.
6797     return;
6798 
6799   case Intrinsic::codeview_annotation: {
6800     // Emit a label associated with this metadata.
6801     MachineFunction &MF = DAG.getMachineFunction();
6802     MCSymbol *Label =
6803         MF.getMMI().getContext().createTempSymbol("annotation", true);
6804     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6805     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6806     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6807     DAG.setRoot(Res);
6808     return;
6809   }
6810 
6811   case Intrinsic::init_trampoline: {
6812     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6813 
6814     SDValue Ops[6];
6815     Ops[0] = getRoot();
6816     Ops[1] = getValue(I.getArgOperand(0));
6817     Ops[2] = getValue(I.getArgOperand(1));
6818     Ops[3] = getValue(I.getArgOperand(2));
6819     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6820     Ops[5] = DAG.getSrcValue(F);
6821 
6822     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6823 
6824     DAG.setRoot(Res);
6825     return;
6826   }
6827   case Intrinsic::adjust_trampoline:
6828     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6829                              TLI.getPointerTy(DAG.getDataLayout()),
6830                              getValue(I.getArgOperand(0))));
6831     return;
6832   case Intrinsic::gcroot: {
6833     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6834            "only valid in functions with gc specified, enforced by Verifier");
6835     assert(GFI && "implied by previous");
6836     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6837     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6838 
6839     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6840     GFI->addStackRoot(FI->getIndex(), TypeMap);
6841     return;
6842   }
6843   case Intrinsic::gcread:
6844   case Intrinsic::gcwrite:
6845     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6846   case Intrinsic::get_rounding:
6847     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
6848     setValue(&I, Res);
6849     DAG.setRoot(Res.getValue(1));
6850     return;
6851 
6852   case Intrinsic::expect:
6853     // Just replace __builtin_expect(exp, c) with EXP.
6854     setValue(&I, getValue(I.getArgOperand(0)));
6855     return;
6856 
6857   case Intrinsic::ubsantrap:
6858   case Intrinsic::debugtrap:
6859   case Intrinsic::trap: {
6860     StringRef TrapFuncName =
6861         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6862     if (TrapFuncName.empty()) {
6863       switch (Intrinsic) {
6864       case Intrinsic::trap:
6865         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6866         break;
6867       case Intrinsic::debugtrap:
6868         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6869         break;
6870       case Intrinsic::ubsantrap:
6871         DAG.setRoot(DAG.getNode(
6872             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6873             DAG.getTargetConstant(
6874                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6875                 MVT::i32)));
6876         break;
6877       default: llvm_unreachable("unknown trap intrinsic");
6878       }
6879       return;
6880     }
6881     TargetLowering::ArgListTy Args;
6882     if (Intrinsic == Intrinsic::ubsantrap) {
6883       Args.push_back(TargetLoweringBase::ArgListEntry());
6884       Args[0].Val = I.getArgOperand(0);
6885       Args[0].Node = getValue(Args[0].Val);
6886       Args[0].Ty = Args[0].Val->getType();
6887     }
6888 
6889     TargetLowering::CallLoweringInfo CLI(DAG);
6890     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6891         CallingConv::C, I.getType(),
6892         DAG.getExternalSymbol(TrapFuncName.data(),
6893                               TLI.getPointerTy(DAG.getDataLayout())),
6894         std::move(Args));
6895 
6896     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6897     DAG.setRoot(Result.second);
6898     return;
6899   }
6900 
6901   case Intrinsic::uadd_with_overflow:
6902   case Intrinsic::sadd_with_overflow:
6903   case Intrinsic::usub_with_overflow:
6904   case Intrinsic::ssub_with_overflow:
6905   case Intrinsic::umul_with_overflow:
6906   case Intrinsic::smul_with_overflow: {
6907     ISD::NodeType Op;
6908     switch (Intrinsic) {
6909     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6910     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6911     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6912     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6913     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6914     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6915     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6916     }
6917     SDValue Op1 = getValue(I.getArgOperand(0));
6918     SDValue Op2 = getValue(I.getArgOperand(1));
6919 
6920     EVT ResultVT = Op1.getValueType();
6921     EVT OverflowVT = MVT::i1;
6922     if (ResultVT.isVector())
6923       OverflowVT = EVT::getVectorVT(
6924           *Context, OverflowVT, ResultVT.getVectorElementCount());
6925 
6926     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6927     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6928     return;
6929   }
6930   case Intrinsic::prefetch: {
6931     SDValue Ops[5];
6932     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6933     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6934     Ops[0] = DAG.getRoot();
6935     Ops[1] = getValue(I.getArgOperand(0));
6936     Ops[2] = getValue(I.getArgOperand(1));
6937     Ops[3] = getValue(I.getArgOperand(2));
6938     Ops[4] = getValue(I.getArgOperand(3));
6939     SDValue Result = DAG.getMemIntrinsicNode(
6940         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6941         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6942         /* align */ std::nullopt, Flags);
6943 
6944     // Chain the prefetch in parallell with any pending loads, to stay out of
6945     // the way of later optimizations.
6946     PendingLoads.push_back(Result);
6947     Result = getRoot();
6948     DAG.setRoot(Result);
6949     return;
6950   }
6951   case Intrinsic::lifetime_start:
6952   case Intrinsic::lifetime_end: {
6953     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6954     // Stack coloring is not enabled in O0, discard region information.
6955     if (TM.getOptLevel() == CodeGenOpt::None)
6956       return;
6957 
6958     const int64_t ObjectSize =
6959         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6960     Value *const ObjectPtr = I.getArgOperand(1);
6961     SmallVector<const Value *, 4> Allocas;
6962     getUnderlyingObjects(ObjectPtr, Allocas);
6963 
6964     for (const Value *Alloca : Allocas) {
6965       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6966 
6967       // Could not find an Alloca.
6968       if (!LifetimeObject)
6969         continue;
6970 
6971       // First check that the Alloca is static, otherwise it won't have a
6972       // valid frame index.
6973       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6974       if (SI == FuncInfo.StaticAllocaMap.end())
6975         return;
6976 
6977       const int FrameIndex = SI->second;
6978       int64_t Offset;
6979       if (GetPointerBaseWithConstantOffset(
6980               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6981         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6982       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6983                                 Offset);
6984       DAG.setRoot(Res);
6985     }
6986     return;
6987   }
6988   case Intrinsic::pseudoprobe: {
6989     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6990     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6991     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6992     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6993     DAG.setRoot(Res);
6994     return;
6995   }
6996   case Intrinsic::invariant_start:
6997     // Discard region information.
6998     setValue(&I,
6999              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7000     return;
7001   case Intrinsic::invariant_end:
7002     // Discard region information.
7003     return;
7004   case Intrinsic::clear_cache:
7005     /// FunctionName may be null.
7006     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
7007       lowerCallToExternalSymbol(I, FunctionName);
7008     return;
7009   case Intrinsic::donothing:
7010   case Intrinsic::seh_try_begin:
7011   case Intrinsic::seh_scope_begin:
7012   case Intrinsic::seh_try_end:
7013   case Intrinsic::seh_scope_end:
7014     // ignore
7015     return;
7016   case Intrinsic::experimental_stackmap:
7017     visitStackmap(I);
7018     return;
7019   case Intrinsic::experimental_patchpoint_void:
7020   case Intrinsic::experimental_patchpoint_i64:
7021     visitPatchpoint(I);
7022     return;
7023   case Intrinsic::experimental_gc_statepoint:
7024     LowerStatepoint(cast<GCStatepointInst>(I));
7025     return;
7026   case Intrinsic::experimental_gc_result:
7027     visitGCResult(cast<GCResultInst>(I));
7028     return;
7029   case Intrinsic::experimental_gc_relocate:
7030     visitGCRelocate(cast<GCRelocateInst>(I));
7031     return;
7032   case Intrinsic::instrprof_cover:
7033     llvm_unreachable("instrprof failed to lower a cover");
7034   case Intrinsic::instrprof_increment:
7035     llvm_unreachable("instrprof failed to lower an increment");
7036   case Intrinsic::instrprof_timestamp:
7037     llvm_unreachable("instrprof failed to lower a timestamp");
7038   case Intrinsic::instrprof_value_profile:
7039     llvm_unreachable("instrprof failed to lower a value profiling call");
7040   case Intrinsic::localescape: {
7041     MachineFunction &MF = DAG.getMachineFunction();
7042     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7043 
7044     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7045     // is the same on all targets.
7046     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7047       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7048       if (isa<ConstantPointerNull>(Arg))
7049         continue; // Skip null pointers. They represent a hole in index space.
7050       AllocaInst *Slot = cast<AllocaInst>(Arg);
7051       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7052              "can only escape static allocas");
7053       int FI = FuncInfo.StaticAllocaMap[Slot];
7054       MCSymbol *FrameAllocSym =
7055           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7056               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7057       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7058               TII->get(TargetOpcode::LOCAL_ESCAPE))
7059           .addSym(FrameAllocSym)
7060           .addFrameIndex(FI);
7061     }
7062 
7063     return;
7064   }
7065 
7066   case Intrinsic::localrecover: {
7067     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7068     MachineFunction &MF = DAG.getMachineFunction();
7069 
7070     // Get the symbol that defines the frame offset.
7071     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7072     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7073     unsigned IdxVal =
7074         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7075     MCSymbol *FrameAllocSym =
7076         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7077             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7078 
7079     Value *FP = I.getArgOperand(1);
7080     SDValue FPVal = getValue(FP);
7081     EVT PtrVT = FPVal.getValueType();
7082 
7083     // Create a MCSymbol for the label to avoid any target lowering
7084     // that would make this PC relative.
7085     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7086     SDValue OffsetVal =
7087         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7088 
7089     // Add the offset to the FP.
7090     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7091     setValue(&I, Add);
7092 
7093     return;
7094   }
7095 
7096   case Intrinsic::eh_exceptionpointer:
7097   case Intrinsic::eh_exceptioncode: {
7098     // Get the exception pointer vreg, copy from it, and resize it to fit.
7099     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7100     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7101     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7102     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7103     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7104     if (Intrinsic == Intrinsic::eh_exceptioncode)
7105       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7106     setValue(&I, N);
7107     return;
7108   }
7109   case Intrinsic::xray_customevent: {
7110     // Here we want to make sure that the intrinsic behaves as if it has a
7111     // specific calling convention, and only for x86_64.
7112     // FIXME: Support other platforms later.
7113     const auto &Triple = DAG.getTarget().getTargetTriple();
7114     if (Triple.getArch() != Triple::x86_64)
7115       return;
7116 
7117     SmallVector<SDValue, 8> Ops;
7118 
7119     // We want to say that we always want the arguments in registers.
7120     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7121     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7122     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7123     SDValue Chain = getRoot();
7124     Ops.push_back(LogEntryVal);
7125     Ops.push_back(StrSizeVal);
7126     Ops.push_back(Chain);
7127 
7128     // We need to enforce the calling convention for the callsite, so that
7129     // argument ordering is enforced correctly, and that register allocation can
7130     // see that some registers may be assumed clobbered and have to preserve
7131     // them across calls to the intrinsic.
7132     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7133                                            sdl, NodeTys, Ops);
7134     SDValue patchableNode = SDValue(MN, 0);
7135     DAG.setRoot(patchableNode);
7136     setValue(&I, patchableNode);
7137     return;
7138   }
7139   case Intrinsic::xray_typedevent: {
7140     // Here we want to make sure that the intrinsic behaves as if it has a
7141     // specific calling convention, and only for x86_64.
7142     // FIXME: Support other platforms later.
7143     const auto &Triple = DAG.getTarget().getTargetTriple();
7144     if (Triple.getArch() != Triple::x86_64)
7145       return;
7146 
7147     SmallVector<SDValue, 8> Ops;
7148 
7149     // We want to say that we always want the arguments in registers.
7150     // It's unclear to me how manipulating the selection DAG here forces callers
7151     // to provide arguments in registers instead of on the stack.
7152     SDValue LogTypeId = getValue(I.getArgOperand(0));
7153     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7154     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7155     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7156     SDValue Chain = getRoot();
7157     Ops.push_back(LogTypeId);
7158     Ops.push_back(LogEntryVal);
7159     Ops.push_back(StrSizeVal);
7160     Ops.push_back(Chain);
7161 
7162     // We need to enforce the calling convention for the callsite, so that
7163     // argument ordering is enforced correctly, and that register allocation can
7164     // see that some registers may be assumed clobbered and have to preserve
7165     // them across calls to the intrinsic.
7166     MachineSDNode *MN = DAG.getMachineNode(
7167         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7168     SDValue patchableNode = SDValue(MN, 0);
7169     DAG.setRoot(patchableNode);
7170     setValue(&I, patchableNode);
7171     return;
7172   }
7173   case Intrinsic::experimental_deoptimize:
7174     LowerDeoptimizeCall(&I);
7175     return;
7176   case Intrinsic::experimental_stepvector:
7177     visitStepVector(I);
7178     return;
7179   case Intrinsic::vector_reduce_fadd:
7180   case Intrinsic::vector_reduce_fmul:
7181   case Intrinsic::vector_reduce_add:
7182   case Intrinsic::vector_reduce_mul:
7183   case Intrinsic::vector_reduce_and:
7184   case Intrinsic::vector_reduce_or:
7185   case Intrinsic::vector_reduce_xor:
7186   case Intrinsic::vector_reduce_smax:
7187   case Intrinsic::vector_reduce_smin:
7188   case Intrinsic::vector_reduce_umax:
7189   case Intrinsic::vector_reduce_umin:
7190   case Intrinsic::vector_reduce_fmax:
7191   case Intrinsic::vector_reduce_fmin:
7192     visitVectorReduce(I, Intrinsic);
7193     return;
7194 
7195   case Intrinsic::icall_branch_funnel: {
7196     SmallVector<SDValue, 16> Ops;
7197     Ops.push_back(getValue(I.getArgOperand(0)));
7198 
7199     int64_t Offset;
7200     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7201         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7202     if (!Base)
7203       report_fatal_error(
7204           "llvm.icall.branch.funnel operand must be a GlobalValue");
7205     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7206 
7207     struct BranchFunnelTarget {
7208       int64_t Offset;
7209       SDValue Target;
7210     };
7211     SmallVector<BranchFunnelTarget, 8> Targets;
7212 
7213     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7214       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7215           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7216       if (ElemBase != Base)
7217         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7218                            "to the same GlobalValue");
7219 
7220       SDValue Val = getValue(I.getArgOperand(Op + 1));
7221       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7222       if (!GA)
7223         report_fatal_error(
7224             "llvm.icall.branch.funnel operand must be a GlobalValue");
7225       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7226                                      GA->getGlobal(), sdl, Val.getValueType(),
7227                                      GA->getOffset())});
7228     }
7229     llvm::sort(Targets,
7230                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7231                  return T1.Offset < T2.Offset;
7232                });
7233 
7234     for (auto &T : Targets) {
7235       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7236       Ops.push_back(T.Target);
7237     }
7238 
7239     Ops.push_back(DAG.getRoot()); // Chain
7240     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7241                                  MVT::Other, Ops),
7242               0);
7243     DAG.setRoot(N);
7244     setValue(&I, N);
7245     HasTailCall = true;
7246     return;
7247   }
7248 
7249   case Intrinsic::wasm_landingpad_index:
7250     // Information this intrinsic contained has been transferred to
7251     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7252     // delete it now.
7253     return;
7254 
7255   case Intrinsic::aarch64_settag:
7256   case Intrinsic::aarch64_settag_zero: {
7257     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7258     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7259     SDValue Val = TSI.EmitTargetCodeForSetTag(
7260         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7261         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7262         ZeroMemory);
7263     DAG.setRoot(Val);
7264     setValue(&I, Val);
7265     return;
7266   }
7267   case Intrinsic::ptrmask: {
7268     SDValue Ptr = getValue(I.getOperand(0));
7269     SDValue Const = getValue(I.getOperand(1));
7270 
7271     EVT PtrVT = Ptr.getValueType();
7272     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7273                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7274     return;
7275   }
7276   case Intrinsic::threadlocal_address: {
7277     setValue(&I, getValue(I.getOperand(0)));
7278     return;
7279   }
7280   case Intrinsic::get_active_lane_mask: {
7281     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7282     SDValue Index = getValue(I.getOperand(0));
7283     EVT ElementVT = Index.getValueType();
7284 
7285     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7286       visitTargetIntrinsic(I, Intrinsic);
7287       return;
7288     }
7289 
7290     SDValue TripCount = getValue(I.getOperand(1));
7291     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7292 
7293     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7294     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7295     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7296     SDValue VectorInduction = DAG.getNode(
7297         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7298     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7299                                  VectorTripCount, ISD::CondCode::SETULT);
7300     setValue(&I, SetCC);
7301     return;
7302   }
7303   case Intrinsic::vector_insert: {
7304     SDValue Vec = getValue(I.getOperand(0));
7305     SDValue SubVec = getValue(I.getOperand(1));
7306     SDValue Index = getValue(I.getOperand(2));
7307 
7308     // The intrinsic's index type is i64, but the SDNode requires an index type
7309     // suitable for the target. Convert the index as required.
7310     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7311     if (Index.getValueType() != VectorIdxTy)
7312       Index = DAG.getVectorIdxConstant(
7313           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7314 
7315     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7316     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7317                              Index));
7318     return;
7319   }
7320   case Intrinsic::vector_extract: {
7321     SDValue Vec = getValue(I.getOperand(0));
7322     SDValue Index = getValue(I.getOperand(1));
7323     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7324 
7325     // The intrinsic's index type is i64, but the SDNode requires an index type
7326     // suitable for the target. Convert the index as required.
7327     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7328     if (Index.getValueType() != VectorIdxTy)
7329       Index = DAG.getVectorIdxConstant(
7330           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7331 
7332     setValue(&I,
7333              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7334     return;
7335   }
7336   case Intrinsic::experimental_vector_reverse:
7337     visitVectorReverse(I);
7338     return;
7339   case Intrinsic::experimental_vector_splice:
7340     visitVectorSplice(I);
7341     return;
7342   case Intrinsic::callbr_landingpad:
7343     visitCallBrLandingPad(I);
7344     return;
7345   case Intrinsic::experimental_vector_interleave2:
7346     visitVectorInterleave(I);
7347     return;
7348   case Intrinsic::experimental_vector_deinterleave2:
7349     visitVectorDeinterleave(I);
7350     return;
7351   }
7352 }
7353 
7354 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7355     const ConstrainedFPIntrinsic &FPI) {
7356   SDLoc sdl = getCurSDLoc();
7357 
7358   // We do not need to serialize constrained FP intrinsics against
7359   // each other or against (nonvolatile) loads, so they can be
7360   // chained like loads.
7361   SDValue Chain = DAG.getRoot();
7362   SmallVector<SDValue, 4> Opers;
7363   Opers.push_back(Chain);
7364   if (FPI.isUnaryOp()) {
7365     Opers.push_back(getValue(FPI.getArgOperand(0)));
7366   } else if (FPI.isTernaryOp()) {
7367     Opers.push_back(getValue(FPI.getArgOperand(0)));
7368     Opers.push_back(getValue(FPI.getArgOperand(1)));
7369     Opers.push_back(getValue(FPI.getArgOperand(2)));
7370   } else {
7371     Opers.push_back(getValue(FPI.getArgOperand(0)));
7372     Opers.push_back(getValue(FPI.getArgOperand(1)));
7373   }
7374 
7375   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7376     assert(Result.getNode()->getNumValues() == 2);
7377 
7378     // Push node to the appropriate list so that future instructions can be
7379     // chained up correctly.
7380     SDValue OutChain = Result.getValue(1);
7381     switch (EB) {
7382     case fp::ExceptionBehavior::ebIgnore:
7383       // The only reason why ebIgnore nodes still need to be chained is that
7384       // they might depend on the current rounding mode, and therefore must
7385       // not be moved across instruction that may change that mode.
7386       [[fallthrough]];
7387     case fp::ExceptionBehavior::ebMayTrap:
7388       // These must not be moved across calls or instructions that may change
7389       // floating-point exception masks.
7390       PendingConstrainedFP.push_back(OutChain);
7391       break;
7392     case fp::ExceptionBehavior::ebStrict:
7393       // These must not be moved across calls or instructions that may change
7394       // floating-point exception masks or read floating-point exception flags.
7395       // In addition, they cannot be optimized out even if unused.
7396       PendingConstrainedFPStrict.push_back(OutChain);
7397       break;
7398     }
7399   };
7400 
7401   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7402   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7403   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7404   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7405 
7406   SDNodeFlags Flags;
7407   if (EB == fp::ExceptionBehavior::ebIgnore)
7408     Flags.setNoFPExcept(true);
7409 
7410   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7411     Flags.copyFMF(*FPOp);
7412 
7413   unsigned Opcode;
7414   switch (FPI.getIntrinsicID()) {
7415   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7416 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7417   case Intrinsic::INTRINSIC:                                                   \
7418     Opcode = ISD::STRICT_##DAGN;                                               \
7419     break;
7420 #include "llvm/IR/ConstrainedOps.def"
7421   case Intrinsic::experimental_constrained_fmuladd: {
7422     Opcode = ISD::STRICT_FMA;
7423     // Break fmuladd into fmul and fadd.
7424     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7425         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7426       Opers.pop_back();
7427       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7428       pushOutChain(Mul, EB);
7429       Opcode = ISD::STRICT_FADD;
7430       Opers.clear();
7431       Opers.push_back(Mul.getValue(1));
7432       Opers.push_back(Mul.getValue(0));
7433       Opers.push_back(getValue(FPI.getArgOperand(2)));
7434     }
7435     break;
7436   }
7437   }
7438 
7439   // A few strict DAG nodes carry additional operands that are not
7440   // set up by the default code above.
7441   switch (Opcode) {
7442   default: break;
7443   case ISD::STRICT_FP_ROUND:
7444     Opers.push_back(
7445         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7446     break;
7447   case ISD::STRICT_FSETCC:
7448   case ISD::STRICT_FSETCCS: {
7449     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7450     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7451     if (TM.Options.NoNaNsFPMath)
7452       Condition = getFCmpCodeWithoutNaN(Condition);
7453     Opers.push_back(DAG.getCondCode(Condition));
7454     break;
7455   }
7456   }
7457 
7458   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7459   pushOutChain(Result, EB);
7460 
7461   SDValue FPResult = Result.getValue(0);
7462   setValue(&FPI, FPResult);
7463 }
7464 
7465 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7466   std::optional<unsigned> ResOPC;
7467   switch (VPIntrin.getIntrinsicID()) {
7468   case Intrinsic::vp_ctlz: {
7469     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7470     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
7471     break;
7472   }
7473   case Intrinsic::vp_cttz: {
7474     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7475     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
7476     break;
7477   }
7478 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7479   case Intrinsic::VPID:                                                        \
7480     ResOPC = ISD::VPSD;                                                        \
7481     break;
7482 #include "llvm/IR/VPIntrinsics.def"
7483   }
7484 
7485   if (!ResOPC)
7486     llvm_unreachable(
7487         "Inconsistency: no SDNode available for this VPIntrinsic!");
7488 
7489   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7490       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7491     if (VPIntrin.getFastMathFlags().allowReassoc())
7492       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7493                                                 : ISD::VP_REDUCE_FMUL;
7494   }
7495 
7496   return *ResOPC;
7497 }
7498 
7499 void SelectionDAGBuilder::visitVPLoad(
7500     const VPIntrinsic &VPIntrin, EVT VT,
7501     const SmallVectorImpl<SDValue> &OpValues) {
7502   SDLoc DL = getCurSDLoc();
7503   Value *PtrOperand = VPIntrin.getArgOperand(0);
7504   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7505   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7506   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7507   SDValue LD;
7508   // Do not serialize variable-length loads of constant memory with
7509   // anything.
7510   if (!Alignment)
7511     Alignment = DAG.getEVTAlign(VT);
7512   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7513   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7514   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7515   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7516       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7517       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7518   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7519                      MMO, false /*IsExpanding */);
7520   if (AddToChain)
7521     PendingLoads.push_back(LD.getValue(1));
7522   setValue(&VPIntrin, LD);
7523 }
7524 
7525 void SelectionDAGBuilder::visitVPGather(
7526     const VPIntrinsic &VPIntrin, EVT VT,
7527     const SmallVectorImpl<SDValue> &OpValues) {
7528   SDLoc DL = getCurSDLoc();
7529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7530   Value *PtrOperand = VPIntrin.getArgOperand(0);
7531   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7532   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7533   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7534   SDValue LD;
7535   if (!Alignment)
7536     Alignment = DAG.getEVTAlign(VT.getScalarType());
7537   unsigned AS =
7538     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7539   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7540      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7541      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7542   SDValue Base, Index, Scale;
7543   ISD::MemIndexType IndexType;
7544   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7545                                     this, VPIntrin.getParent(),
7546                                     VT.getScalarStoreSize());
7547   if (!UniformBase) {
7548     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7549     Index = getValue(PtrOperand);
7550     IndexType = ISD::SIGNED_SCALED;
7551     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7552   }
7553   EVT IdxVT = Index.getValueType();
7554   EVT EltTy = IdxVT.getVectorElementType();
7555   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7556     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7557     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7558   }
7559   LD = DAG.getGatherVP(
7560       DAG.getVTList(VT, MVT::Other), VT, DL,
7561       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7562       IndexType);
7563   PendingLoads.push_back(LD.getValue(1));
7564   setValue(&VPIntrin, LD);
7565 }
7566 
7567 void SelectionDAGBuilder::visitVPStore(
7568     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7569   SDLoc DL = getCurSDLoc();
7570   Value *PtrOperand = VPIntrin.getArgOperand(1);
7571   EVT VT = OpValues[0].getValueType();
7572   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7573   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7574   SDValue ST;
7575   if (!Alignment)
7576     Alignment = DAG.getEVTAlign(VT);
7577   SDValue Ptr = OpValues[1];
7578   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7579   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7580       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7581       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7582   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7583                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7584                       /* IsTruncating */ false, /*IsCompressing*/ false);
7585   DAG.setRoot(ST);
7586   setValue(&VPIntrin, ST);
7587 }
7588 
7589 void SelectionDAGBuilder::visitVPScatter(
7590     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7591   SDLoc DL = getCurSDLoc();
7592   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7593   Value *PtrOperand = VPIntrin.getArgOperand(1);
7594   EVT VT = OpValues[0].getValueType();
7595   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7596   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7597   SDValue ST;
7598   if (!Alignment)
7599     Alignment = DAG.getEVTAlign(VT.getScalarType());
7600   unsigned AS =
7601       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7602   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7603       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7604       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7605   SDValue Base, Index, Scale;
7606   ISD::MemIndexType IndexType;
7607   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7608                                     this, VPIntrin.getParent(),
7609                                     VT.getScalarStoreSize());
7610   if (!UniformBase) {
7611     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7612     Index = getValue(PtrOperand);
7613     IndexType = ISD::SIGNED_SCALED;
7614     Scale =
7615       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7616   }
7617   EVT IdxVT = Index.getValueType();
7618   EVT EltTy = IdxVT.getVectorElementType();
7619   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7620     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7621     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7622   }
7623   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7624                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7625                          OpValues[2], OpValues[3]},
7626                         MMO, IndexType);
7627   DAG.setRoot(ST);
7628   setValue(&VPIntrin, ST);
7629 }
7630 
7631 void SelectionDAGBuilder::visitVPStridedLoad(
7632     const VPIntrinsic &VPIntrin, EVT VT,
7633     const SmallVectorImpl<SDValue> &OpValues) {
7634   SDLoc DL = getCurSDLoc();
7635   Value *PtrOperand = VPIntrin.getArgOperand(0);
7636   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7637   if (!Alignment)
7638     Alignment = DAG.getEVTAlign(VT.getScalarType());
7639   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7640   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7641   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7642   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7643   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7644   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7645       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7646       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7647 
7648   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7649                                     OpValues[2], OpValues[3], MMO,
7650                                     false /*IsExpanding*/);
7651 
7652   if (AddToChain)
7653     PendingLoads.push_back(LD.getValue(1));
7654   setValue(&VPIntrin, LD);
7655 }
7656 
7657 void SelectionDAGBuilder::visitVPStridedStore(
7658     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7659   SDLoc DL = getCurSDLoc();
7660   Value *PtrOperand = VPIntrin.getArgOperand(1);
7661   EVT VT = OpValues[0].getValueType();
7662   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7663   if (!Alignment)
7664     Alignment = DAG.getEVTAlign(VT.getScalarType());
7665   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7666   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7667       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7668       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7669 
7670   SDValue ST = DAG.getStridedStoreVP(
7671       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7672       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7673       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7674       /*IsCompressing*/ false);
7675 
7676   DAG.setRoot(ST);
7677   setValue(&VPIntrin, ST);
7678 }
7679 
7680 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
7681   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7682   SDLoc DL = getCurSDLoc();
7683 
7684   ISD::CondCode Condition;
7685   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
7686   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
7687   if (IsFP) {
7688     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
7689     // flags, but calls that don't return floating-point types can't be
7690     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
7691     Condition = getFCmpCondCode(CondCode);
7692     if (TM.Options.NoNaNsFPMath)
7693       Condition = getFCmpCodeWithoutNaN(Condition);
7694   } else {
7695     Condition = getICmpCondCode(CondCode);
7696   }
7697 
7698   SDValue Op1 = getValue(VPIntrin.getOperand(0));
7699   SDValue Op2 = getValue(VPIntrin.getOperand(1));
7700   // #2 is the condition code
7701   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
7702   SDValue EVL = getValue(VPIntrin.getOperand(4));
7703   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7704   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7705          "Unexpected target EVL type");
7706   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
7707 
7708   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7709                                                         VPIntrin.getType());
7710   setValue(&VPIntrin,
7711            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
7712 }
7713 
7714 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7715     const VPIntrinsic &VPIntrin) {
7716   SDLoc DL = getCurSDLoc();
7717   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7718 
7719   auto IID = VPIntrin.getIntrinsicID();
7720 
7721   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
7722     return visitVPCmp(*CmpI);
7723 
7724   SmallVector<EVT, 4> ValueVTs;
7725   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7726   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7727   SDVTList VTs = DAG.getVTList(ValueVTs);
7728 
7729   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
7730 
7731   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7732   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7733          "Unexpected target EVL type");
7734 
7735   // Request operands.
7736   SmallVector<SDValue, 7> OpValues;
7737   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7738     auto Op = getValue(VPIntrin.getArgOperand(I));
7739     if (I == EVLParamPos)
7740       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7741     OpValues.push_back(Op);
7742   }
7743 
7744   switch (Opcode) {
7745   default: {
7746     SDNodeFlags SDFlags;
7747     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7748       SDFlags.copyFMF(*FPMO);
7749     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
7750     setValue(&VPIntrin, Result);
7751     break;
7752   }
7753   case ISD::VP_LOAD:
7754     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
7755     break;
7756   case ISD::VP_GATHER:
7757     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
7758     break;
7759   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7760     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7761     break;
7762   case ISD::VP_STORE:
7763     visitVPStore(VPIntrin, OpValues);
7764     break;
7765   case ISD::VP_SCATTER:
7766     visitVPScatter(VPIntrin, OpValues);
7767     break;
7768   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7769     visitVPStridedStore(VPIntrin, OpValues);
7770     break;
7771   case ISD::VP_FMULADD: {
7772     assert(OpValues.size() == 5 && "Unexpected number of operands");
7773     SDNodeFlags SDFlags;
7774     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7775       SDFlags.copyFMF(*FPMO);
7776     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7777         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
7778       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
7779     } else {
7780       SDValue Mul = DAG.getNode(
7781           ISD::VP_FMUL, DL, VTs,
7782           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
7783       SDValue Add =
7784           DAG.getNode(ISD::VP_FADD, DL, VTs,
7785                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
7786       setValue(&VPIntrin, Add);
7787     }
7788     break;
7789   }
7790   case ISD::VP_INTTOPTR: {
7791     SDValue N = OpValues[0];
7792     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
7793     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
7794     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7795                                OpValues[2]);
7796     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7797                              OpValues[2]);
7798     setValue(&VPIntrin, N);
7799     break;
7800   }
7801   case ISD::VP_PTRTOINT: {
7802     SDValue N = OpValues[0];
7803     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7804                                                           VPIntrin.getType());
7805     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
7806                                        VPIntrin.getOperand(0)->getType());
7807     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7808                                OpValues[2]);
7809     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7810                              OpValues[2]);
7811     setValue(&VPIntrin, N);
7812     break;
7813   }
7814   case ISD::VP_ABS:
7815   case ISD::VP_CTLZ:
7816   case ISD::VP_CTLZ_ZERO_UNDEF:
7817   case ISD::VP_CTTZ:
7818   case ISD::VP_CTTZ_ZERO_UNDEF: {
7819     SDValue Result =
7820         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
7821     setValue(&VPIntrin, Result);
7822     break;
7823   }
7824   }
7825 }
7826 
7827 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7828                                           const BasicBlock *EHPadBB,
7829                                           MCSymbol *&BeginLabel) {
7830   MachineFunction &MF = DAG.getMachineFunction();
7831   MachineModuleInfo &MMI = MF.getMMI();
7832 
7833   // Insert a label before the invoke call to mark the try range.  This can be
7834   // used to detect deletion of the invoke via the MachineModuleInfo.
7835   BeginLabel = MMI.getContext().createTempSymbol();
7836 
7837   // For SjLj, keep track of which landing pads go with which invokes
7838   // so as to maintain the ordering of pads in the LSDA.
7839   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7840   if (CallSiteIndex) {
7841     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7842     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7843 
7844     // Now that the call site is handled, stop tracking it.
7845     MMI.setCurrentCallSite(0);
7846   }
7847 
7848   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7849 }
7850 
7851 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7852                                         const BasicBlock *EHPadBB,
7853                                         MCSymbol *BeginLabel) {
7854   assert(BeginLabel && "BeginLabel should've been set");
7855 
7856   MachineFunction &MF = DAG.getMachineFunction();
7857   MachineModuleInfo &MMI = MF.getMMI();
7858 
7859   // Insert a label at the end of the invoke call to mark the try range.  This
7860   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7861   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7862   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7863 
7864   // Inform MachineModuleInfo of range.
7865   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7866   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7867   // actually use outlined funclets and their LSDA info style.
7868   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7869     assert(II && "II should've been set");
7870     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7871     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7872   } else if (!isScopedEHPersonality(Pers)) {
7873     assert(EHPadBB);
7874     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7875   }
7876 
7877   return Chain;
7878 }
7879 
7880 std::pair<SDValue, SDValue>
7881 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7882                                     const BasicBlock *EHPadBB) {
7883   MCSymbol *BeginLabel = nullptr;
7884 
7885   if (EHPadBB) {
7886     // Both PendingLoads and PendingExports must be flushed here;
7887     // this call might not return.
7888     (void)getRoot();
7889     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7890     CLI.setChain(getRoot());
7891   }
7892 
7893   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7894   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7895 
7896   assert((CLI.IsTailCall || Result.second.getNode()) &&
7897          "Non-null chain expected with non-tail call!");
7898   assert((Result.second.getNode() || !Result.first.getNode()) &&
7899          "Null value expected with tail call!");
7900 
7901   if (!Result.second.getNode()) {
7902     // As a special case, a null chain means that a tail call has been emitted
7903     // and the DAG root is already updated.
7904     HasTailCall = true;
7905 
7906     // Since there's no actual continuation from this block, nothing can be
7907     // relying on us setting vregs for them.
7908     PendingExports.clear();
7909   } else {
7910     DAG.setRoot(Result.second);
7911   }
7912 
7913   if (EHPadBB) {
7914     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7915                            BeginLabel));
7916   }
7917 
7918   return Result;
7919 }
7920 
7921 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7922                                       bool isTailCall,
7923                                       bool isMustTailCall,
7924                                       const BasicBlock *EHPadBB) {
7925   auto &DL = DAG.getDataLayout();
7926   FunctionType *FTy = CB.getFunctionType();
7927   Type *RetTy = CB.getType();
7928 
7929   TargetLowering::ArgListTy Args;
7930   Args.reserve(CB.arg_size());
7931 
7932   const Value *SwiftErrorVal = nullptr;
7933   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7934 
7935   if (isTailCall) {
7936     // Avoid emitting tail calls in functions with the disable-tail-calls
7937     // attribute.
7938     auto *Caller = CB.getParent()->getParent();
7939     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7940         "true" && !isMustTailCall)
7941       isTailCall = false;
7942 
7943     // We can't tail call inside a function with a swifterror argument. Lowering
7944     // does not support this yet. It would have to move into the swifterror
7945     // register before the call.
7946     if (TLI.supportSwiftError() &&
7947         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7948       isTailCall = false;
7949   }
7950 
7951   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7952     TargetLowering::ArgListEntry Entry;
7953     const Value *V = *I;
7954 
7955     // Skip empty types
7956     if (V->getType()->isEmptyTy())
7957       continue;
7958 
7959     SDValue ArgNode = getValue(V);
7960     Entry.Node = ArgNode; Entry.Ty = V->getType();
7961 
7962     Entry.setAttributes(&CB, I - CB.arg_begin());
7963 
7964     // Use swifterror virtual register as input to the call.
7965     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7966       SwiftErrorVal = V;
7967       // We find the virtual register for the actual swifterror argument.
7968       // Instead of using the Value, we use the virtual register instead.
7969       Entry.Node =
7970           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7971                           EVT(TLI.getPointerTy(DL)));
7972     }
7973 
7974     Args.push_back(Entry);
7975 
7976     // If we have an explicit sret argument that is an Instruction, (i.e., it
7977     // might point to function-local memory), we can't meaningfully tail-call.
7978     if (Entry.IsSRet && isa<Instruction>(V))
7979       isTailCall = false;
7980   }
7981 
7982   // If call site has a cfguardtarget operand bundle, create and add an
7983   // additional ArgListEntry.
7984   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7985     TargetLowering::ArgListEntry Entry;
7986     Value *V = Bundle->Inputs[0];
7987     SDValue ArgNode = getValue(V);
7988     Entry.Node = ArgNode;
7989     Entry.Ty = V->getType();
7990     Entry.IsCFGuardTarget = true;
7991     Args.push_back(Entry);
7992   }
7993 
7994   // Check if target-independent constraints permit a tail call here.
7995   // Target-dependent constraints are checked within TLI->LowerCallTo.
7996   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7997     isTailCall = false;
7998 
7999   // Disable tail calls if there is an swifterror argument. Targets have not
8000   // been updated to support tail calls.
8001   if (TLI.supportSwiftError() && SwiftErrorVal)
8002     isTailCall = false;
8003 
8004   ConstantInt *CFIType = nullptr;
8005   if (CB.isIndirectCall()) {
8006     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8007       if (!TLI.supportKCFIBundles())
8008         report_fatal_error(
8009             "Target doesn't support calls with kcfi operand bundles.");
8010       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8011       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8012     }
8013   }
8014 
8015   TargetLowering::CallLoweringInfo CLI(DAG);
8016   CLI.setDebugLoc(getCurSDLoc())
8017       .setChain(getRoot())
8018       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8019       .setTailCall(isTailCall)
8020       .setConvergent(CB.isConvergent())
8021       .setIsPreallocated(
8022           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8023       .setCFIType(CFIType);
8024   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8025 
8026   if (Result.first.getNode()) {
8027     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8028     setValue(&CB, Result.first);
8029   }
8030 
8031   // The last element of CLI.InVals has the SDValue for swifterror return.
8032   // Here we copy it to a virtual register and update SwiftErrorMap for
8033   // book-keeping.
8034   if (SwiftErrorVal && TLI.supportSwiftError()) {
8035     // Get the last element of InVals.
8036     SDValue Src = CLI.InVals.back();
8037     Register VReg =
8038         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8039     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8040     DAG.setRoot(CopyNode);
8041   }
8042 }
8043 
8044 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8045                              SelectionDAGBuilder &Builder) {
8046   // Check to see if this load can be trivially constant folded, e.g. if the
8047   // input is from a string literal.
8048   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8049     // Cast pointer to the type we really want to load.
8050     Type *LoadTy =
8051         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8052     if (LoadVT.isVector())
8053       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8054 
8055     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8056                                          PointerType::getUnqual(LoadTy));
8057 
8058     if (const Constant *LoadCst =
8059             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8060                                          LoadTy, Builder.DAG.getDataLayout()))
8061       return Builder.getValue(LoadCst);
8062   }
8063 
8064   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8065   // still constant memory, the input chain can be the entry node.
8066   SDValue Root;
8067   bool ConstantMemory = false;
8068 
8069   // Do not serialize (non-volatile) loads of constant memory with anything.
8070   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8071     Root = Builder.DAG.getEntryNode();
8072     ConstantMemory = true;
8073   } else {
8074     // Do not serialize non-volatile loads against each other.
8075     Root = Builder.DAG.getRoot();
8076   }
8077 
8078   SDValue Ptr = Builder.getValue(PtrVal);
8079   SDValue LoadVal =
8080       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8081                           MachinePointerInfo(PtrVal), Align(1));
8082 
8083   if (!ConstantMemory)
8084     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8085   return LoadVal;
8086 }
8087 
8088 /// Record the value for an instruction that produces an integer result,
8089 /// converting the type where necessary.
8090 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8091                                                   SDValue Value,
8092                                                   bool IsSigned) {
8093   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8094                                                     I.getType(), true);
8095   if (IsSigned)
8096     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
8097   else
8098     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
8099   setValue(&I, Value);
8100 }
8101 
8102 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8103 /// true and lower it. Otherwise return false, and it will be lowered like a
8104 /// normal call.
8105 /// The caller already checked that \p I calls the appropriate LibFunc with a
8106 /// correct prototype.
8107 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8108   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8109   const Value *Size = I.getArgOperand(2);
8110   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8111   if (CSize && CSize->getZExtValue() == 0) {
8112     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8113                                                           I.getType(), true);
8114     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8115     return true;
8116   }
8117 
8118   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8119   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8120       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8121       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8122   if (Res.first.getNode()) {
8123     processIntegerCallValue(I, Res.first, true);
8124     PendingLoads.push_back(Res.second);
8125     return true;
8126   }
8127 
8128   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8129   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8130   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8131     return false;
8132 
8133   // If the target has a fast compare for the given size, it will return a
8134   // preferred load type for that size. Require that the load VT is legal and
8135   // that the target supports unaligned loads of that type. Otherwise, return
8136   // INVALID.
8137   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8138     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8139     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8140     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8141       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8142       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8143       // TODO: Check alignment of src and dest ptrs.
8144       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8145       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8146       if (!TLI.isTypeLegal(LVT) ||
8147           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8148           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8149         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8150     }
8151 
8152     return LVT;
8153   };
8154 
8155   // This turns into unaligned loads. We only do this if the target natively
8156   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8157   // we'll only produce a small number of byte loads.
8158   MVT LoadVT;
8159   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8160   switch (NumBitsToCompare) {
8161   default:
8162     return false;
8163   case 16:
8164     LoadVT = MVT::i16;
8165     break;
8166   case 32:
8167     LoadVT = MVT::i32;
8168     break;
8169   case 64:
8170   case 128:
8171   case 256:
8172     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8173     break;
8174   }
8175 
8176   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8177     return false;
8178 
8179   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8180   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8181 
8182   // Bitcast to a wide integer type if the loads are vectors.
8183   if (LoadVT.isVector()) {
8184     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8185     LoadL = DAG.getBitcast(CmpVT, LoadL);
8186     LoadR = DAG.getBitcast(CmpVT, LoadR);
8187   }
8188 
8189   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8190   processIntegerCallValue(I, Cmp, false);
8191   return true;
8192 }
8193 
8194 /// See if we can lower a memchr call into an optimized form. If so, return
8195 /// true and lower it. Otherwise return false, and it will be lowered like a
8196 /// normal call.
8197 /// The caller already checked that \p I calls the appropriate LibFunc with a
8198 /// correct prototype.
8199 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8200   const Value *Src = I.getArgOperand(0);
8201   const Value *Char = I.getArgOperand(1);
8202   const Value *Length = I.getArgOperand(2);
8203 
8204   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8205   std::pair<SDValue, SDValue> Res =
8206     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8207                                 getValue(Src), getValue(Char), getValue(Length),
8208                                 MachinePointerInfo(Src));
8209   if (Res.first.getNode()) {
8210     setValue(&I, Res.first);
8211     PendingLoads.push_back(Res.second);
8212     return true;
8213   }
8214 
8215   return false;
8216 }
8217 
8218 /// See if we can lower a mempcpy call into an optimized form. If so, return
8219 /// true and lower it. Otherwise return false, and it will be lowered like a
8220 /// normal call.
8221 /// The caller already checked that \p I calls the appropriate LibFunc with a
8222 /// correct prototype.
8223 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8224   SDValue Dst = getValue(I.getArgOperand(0));
8225   SDValue Src = getValue(I.getArgOperand(1));
8226   SDValue Size = getValue(I.getArgOperand(2));
8227 
8228   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8229   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8230   // DAG::getMemcpy needs Alignment to be defined.
8231   Align Alignment = std::min(DstAlign, SrcAlign);
8232 
8233   bool isVol = false;
8234   SDLoc sdl = getCurSDLoc();
8235 
8236   // In the mempcpy context we need to pass in a false value for isTailCall
8237   // because the return pointer needs to be adjusted by the size of
8238   // the copied memory.
8239   SDValue Root = isVol ? getRoot() : getMemoryRoot();
8240   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
8241                              /*isTailCall=*/false,
8242                              MachinePointerInfo(I.getArgOperand(0)),
8243                              MachinePointerInfo(I.getArgOperand(1)),
8244                              I.getAAMetadata());
8245   assert(MC.getNode() != nullptr &&
8246          "** memcpy should not be lowered as TailCall in mempcpy context **");
8247   DAG.setRoot(MC);
8248 
8249   // Check if Size needs to be truncated or extended.
8250   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8251 
8252   // Adjust return pointer to point just past the last dst byte.
8253   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8254                                     Dst, Size);
8255   setValue(&I, DstPlusSize);
8256   return true;
8257 }
8258 
8259 /// See if we can lower a strcpy call into an optimized form.  If so, return
8260 /// true and lower it, otherwise return false and it will be lowered like a
8261 /// normal call.
8262 /// The caller already checked that \p I calls the appropriate LibFunc with a
8263 /// correct prototype.
8264 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8265   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8266 
8267   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8268   std::pair<SDValue, SDValue> Res =
8269     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8270                                 getValue(Arg0), getValue(Arg1),
8271                                 MachinePointerInfo(Arg0),
8272                                 MachinePointerInfo(Arg1), isStpcpy);
8273   if (Res.first.getNode()) {
8274     setValue(&I, Res.first);
8275     DAG.setRoot(Res.second);
8276     return true;
8277   }
8278 
8279   return false;
8280 }
8281 
8282 /// See if we can lower a strcmp call into an optimized form.  If so, return
8283 /// true and lower it, otherwise return false and it will be lowered like a
8284 /// normal call.
8285 /// The caller already checked that \p I calls the appropriate LibFunc with a
8286 /// correct prototype.
8287 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8288   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8289 
8290   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8291   std::pair<SDValue, SDValue> Res =
8292     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8293                                 getValue(Arg0), getValue(Arg1),
8294                                 MachinePointerInfo(Arg0),
8295                                 MachinePointerInfo(Arg1));
8296   if (Res.first.getNode()) {
8297     processIntegerCallValue(I, Res.first, true);
8298     PendingLoads.push_back(Res.second);
8299     return true;
8300   }
8301 
8302   return false;
8303 }
8304 
8305 /// See if we can lower a strlen call into an optimized form.  If so, return
8306 /// true and lower it, otherwise return false and it will be lowered like a
8307 /// normal call.
8308 /// The caller already checked that \p I calls the appropriate LibFunc with a
8309 /// correct prototype.
8310 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8311   const Value *Arg0 = I.getArgOperand(0);
8312 
8313   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8314   std::pair<SDValue, SDValue> Res =
8315     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8316                                 getValue(Arg0), MachinePointerInfo(Arg0));
8317   if (Res.first.getNode()) {
8318     processIntegerCallValue(I, Res.first, false);
8319     PendingLoads.push_back(Res.second);
8320     return true;
8321   }
8322 
8323   return false;
8324 }
8325 
8326 /// See if we can lower a strnlen call into an optimized form.  If so, return
8327 /// true and lower it, otherwise return false and it will be lowered like a
8328 /// normal call.
8329 /// The caller already checked that \p I calls the appropriate LibFunc with a
8330 /// correct prototype.
8331 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8332   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8333 
8334   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8335   std::pair<SDValue, SDValue> Res =
8336     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8337                                  getValue(Arg0), getValue(Arg1),
8338                                  MachinePointerInfo(Arg0));
8339   if (Res.first.getNode()) {
8340     processIntegerCallValue(I, Res.first, false);
8341     PendingLoads.push_back(Res.second);
8342     return true;
8343   }
8344 
8345   return false;
8346 }
8347 
8348 /// See if we can lower a unary floating-point operation into an SDNode with
8349 /// the specified Opcode.  If so, return true and lower it, otherwise return
8350 /// false and it will be lowered like a normal call.
8351 /// The caller already checked that \p I calls the appropriate LibFunc with a
8352 /// correct prototype.
8353 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8354                                               unsigned Opcode) {
8355   // We already checked this call's prototype; verify it doesn't modify errno.
8356   if (!I.onlyReadsMemory())
8357     return false;
8358 
8359   SDNodeFlags Flags;
8360   Flags.copyFMF(cast<FPMathOperator>(I));
8361 
8362   SDValue Tmp = getValue(I.getArgOperand(0));
8363   setValue(&I,
8364            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8365   return true;
8366 }
8367 
8368 /// See if we can lower a binary floating-point operation into an SDNode with
8369 /// the specified Opcode. If so, return true and lower it. Otherwise return
8370 /// false, and it will be lowered like a normal call.
8371 /// The caller already checked that \p I calls the appropriate LibFunc with a
8372 /// correct prototype.
8373 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8374                                                unsigned Opcode) {
8375   // We already checked this call's prototype; verify it doesn't modify errno.
8376   if (!I.onlyReadsMemory())
8377     return false;
8378 
8379   SDNodeFlags Flags;
8380   Flags.copyFMF(cast<FPMathOperator>(I));
8381 
8382   SDValue Tmp0 = getValue(I.getArgOperand(0));
8383   SDValue Tmp1 = getValue(I.getArgOperand(1));
8384   EVT VT = Tmp0.getValueType();
8385   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8386   return true;
8387 }
8388 
8389 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8390   // Handle inline assembly differently.
8391   if (I.isInlineAsm()) {
8392     visitInlineAsm(I);
8393     return;
8394   }
8395 
8396   diagnoseDontCall(I);
8397 
8398   if (Function *F = I.getCalledFunction()) {
8399     if (F->isDeclaration()) {
8400       // Is this an LLVM intrinsic or a target-specific intrinsic?
8401       unsigned IID = F->getIntrinsicID();
8402       if (!IID)
8403         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8404           IID = II->getIntrinsicID(F);
8405 
8406       if (IID) {
8407         visitIntrinsicCall(I, IID);
8408         return;
8409       }
8410     }
8411 
8412     // Check for well-known libc/libm calls.  If the function is internal, it
8413     // can't be a library call.  Don't do the check if marked as nobuiltin for
8414     // some reason or the call site requires strict floating point semantics.
8415     LibFunc Func;
8416     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8417         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8418         LibInfo->hasOptimizedCodeGen(Func)) {
8419       switch (Func) {
8420       default: break;
8421       case LibFunc_bcmp:
8422         if (visitMemCmpBCmpCall(I))
8423           return;
8424         break;
8425       case LibFunc_copysign:
8426       case LibFunc_copysignf:
8427       case LibFunc_copysignl:
8428         // We already checked this call's prototype; verify it doesn't modify
8429         // errno.
8430         if (I.onlyReadsMemory()) {
8431           SDValue LHS = getValue(I.getArgOperand(0));
8432           SDValue RHS = getValue(I.getArgOperand(1));
8433           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8434                                    LHS.getValueType(), LHS, RHS));
8435           return;
8436         }
8437         break;
8438       case LibFunc_fabs:
8439       case LibFunc_fabsf:
8440       case LibFunc_fabsl:
8441         if (visitUnaryFloatCall(I, ISD::FABS))
8442           return;
8443         break;
8444       case LibFunc_fmin:
8445       case LibFunc_fminf:
8446       case LibFunc_fminl:
8447         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8448           return;
8449         break;
8450       case LibFunc_fmax:
8451       case LibFunc_fmaxf:
8452       case LibFunc_fmaxl:
8453         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8454           return;
8455         break;
8456       case LibFunc_sin:
8457       case LibFunc_sinf:
8458       case LibFunc_sinl:
8459         if (visitUnaryFloatCall(I, ISD::FSIN))
8460           return;
8461         break;
8462       case LibFunc_cos:
8463       case LibFunc_cosf:
8464       case LibFunc_cosl:
8465         if (visitUnaryFloatCall(I, ISD::FCOS))
8466           return;
8467         break;
8468       case LibFunc_sqrt:
8469       case LibFunc_sqrtf:
8470       case LibFunc_sqrtl:
8471       case LibFunc_sqrt_finite:
8472       case LibFunc_sqrtf_finite:
8473       case LibFunc_sqrtl_finite:
8474         if (visitUnaryFloatCall(I, ISD::FSQRT))
8475           return;
8476         break;
8477       case LibFunc_floor:
8478       case LibFunc_floorf:
8479       case LibFunc_floorl:
8480         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8481           return;
8482         break;
8483       case LibFunc_nearbyint:
8484       case LibFunc_nearbyintf:
8485       case LibFunc_nearbyintl:
8486         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8487           return;
8488         break;
8489       case LibFunc_ceil:
8490       case LibFunc_ceilf:
8491       case LibFunc_ceill:
8492         if (visitUnaryFloatCall(I, ISD::FCEIL))
8493           return;
8494         break;
8495       case LibFunc_rint:
8496       case LibFunc_rintf:
8497       case LibFunc_rintl:
8498         if (visitUnaryFloatCall(I, ISD::FRINT))
8499           return;
8500         break;
8501       case LibFunc_round:
8502       case LibFunc_roundf:
8503       case LibFunc_roundl:
8504         if (visitUnaryFloatCall(I, ISD::FROUND))
8505           return;
8506         break;
8507       case LibFunc_trunc:
8508       case LibFunc_truncf:
8509       case LibFunc_truncl:
8510         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8511           return;
8512         break;
8513       case LibFunc_log2:
8514       case LibFunc_log2f:
8515       case LibFunc_log2l:
8516         if (visitUnaryFloatCall(I, ISD::FLOG2))
8517           return;
8518         break;
8519       case LibFunc_exp2:
8520       case LibFunc_exp2f:
8521       case LibFunc_exp2l:
8522         if (visitUnaryFloatCall(I, ISD::FEXP2))
8523           return;
8524         break;
8525       case LibFunc_memcmp:
8526         if (visitMemCmpBCmpCall(I))
8527           return;
8528         break;
8529       case LibFunc_mempcpy:
8530         if (visitMemPCpyCall(I))
8531           return;
8532         break;
8533       case LibFunc_memchr:
8534         if (visitMemChrCall(I))
8535           return;
8536         break;
8537       case LibFunc_strcpy:
8538         if (visitStrCpyCall(I, false))
8539           return;
8540         break;
8541       case LibFunc_stpcpy:
8542         if (visitStrCpyCall(I, true))
8543           return;
8544         break;
8545       case LibFunc_strcmp:
8546         if (visitStrCmpCall(I))
8547           return;
8548         break;
8549       case LibFunc_strlen:
8550         if (visitStrLenCall(I))
8551           return;
8552         break;
8553       case LibFunc_strnlen:
8554         if (visitStrNLenCall(I))
8555           return;
8556         break;
8557       }
8558     }
8559   }
8560 
8561   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8562   // have to do anything here to lower funclet bundles.
8563   // CFGuardTarget bundles are lowered in LowerCallTo.
8564   assert(!I.hasOperandBundlesOtherThan(
8565              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8566               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8567               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8568          "Cannot lower calls with arbitrary operand bundles!");
8569 
8570   SDValue Callee = getValue(I.getCalledOperand());
8571 
8572   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8573     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8574   else
8575     // Check if we can potentially perform a tail call. More detailed checking
8576     // is be done within LowerCallTo, after more information about the call is
8577     // known.
8578     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8579 }
8580 
8581 namespace {
8582 
8583 /// AsmOperandInfo - This contains information for each constraint that we are
8584 /// lowering.
8585 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8586 public:
8587   /// CallOperand - If this is the result output operand or a clobber
8588   /// this is null, otherwise it is the incoming operand to the CallInst.
8589   /// This gets modified as the asm is processed.
8590   SDValue CallOperand;
8591 
8592   /// AssignedRegs - If this is a register or register class operand, this
8593   /// contains the set of register corresponding to the operand.
8594   RegsForValue AssignedRegs;
8595 
8596   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8597     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8598   }
8599 
8600   /// Whether or not this operand accesses memory
8601   bool hasMemory(const TargetLowering &TLI) const {
8602     // Indirect operand accesses access memory.
8603     if (isIndirect)
8604       return true;
8605 
8606     for (const auto &Code : Codes)
8607       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8608         return true;
8609 
8610     return false;
8611   }
8612 };
8613 
8614 
8615 } // end anonymous namespace
8616 
8617 /// Make sure that the output operand \p OpInfo and its corresponding input
8618 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8619 /// out).
8620 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8621                                SDISelAsmOperandInfo &MatchingOpInfo,
8622                                SelectionDAG &DAG) {
8623   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8624     return;
8625 
8626   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8627   const auto &TLI = DAG.getTargetLoweringInfo();
8628 
8629   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8630       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8631                                        OpInfo.ConstraintVT);
8632   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8633       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8634                                        MatchingOpInfo.ConstraintVT);
8635   if ((OpInfo.ConstraintVT.isInteger() !=
8636        MatchingOpInfo.ConstraintVT.isInteger()) ||
8637       (MatchRC.second != InputRC.second)) {
8638     // FIXME: error out in a more elegant fashion
8639     report_fatal_error("Unsupported asm: input constraint"
8640                        " with a matching output constraint of"
8641                        " incompatible type!");
8642   }
8643   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8644 }
8645 
8646 /// Get a direct memory input to behave well as an indirect operand.
8647 /// This may introduce stores, hence the need for a \p Chain.
8648 /// \return The (possibly updated) chain.
8649 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8650                                         SDISelAsmOperandInfo &OpInfo,
8651                                         SelectionDAG &DAG) {
8652   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8653 
8654   // If we don't have an indirect input, put it in the constpool if we can,
8655   // otherwise spill it to a stack slot.
8656   // TODO: This isn't quite right. We need to handle these according to
8657   // the addressing mode that the constraint wants. Also, this may take
8658   // an additional register for the computation and we don't want that
8659   // either.
8660 
8661   // If the operand is a float, integer, or vector constant, spill to a
8662   // constant pool entry to get its address.
8663   const Value *OpVal = OpInfo.CallOperandVal;
8664   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8665       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8666     OpInfo.CallOperand = DAG.getConstantPool(
8667         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8668     return Chain;
8669   }
8670 
8671   // Otherwise, create a stack slot and emit a store to it before the asm.
8672   Type *Ty = OpVal->getType();
8673   auto &DL = DAG.getDataLayout();
8674   uint64_t TySize = DL.getTypeAllocSize(Ty);
8675   MachineFunction &MF = DAG.getMachineFunction();
8676   int SSFI = MF.getFrameInfo().CreateStackObject(
8677       TySize, DL.getPrefTypeAlign(Ty), false);
8678   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8679   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8680                             MachinePointerInfo::getFixedStack(MF, SSFI),
8681                             TLI.getMemValueType(DL, Ty));
8682   OpInfo.CallOperand = StackSlot;
8683 
8684   return Chain;
8685 }
8686 
8687 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8688 /// specified operand.  We prefer to assign virtual registers, to allow the
8689 /// register allocator to handle the assignment process.  However, if the asm
8690 /// uses features that we can't model on machineinstrs, we have SDISel do the
8691 /// allocation.  This produces generally horrible, but correct, code.
8692 ///
8693 ///   OpInfo describes the operand
8694 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8695 static std::optional<unsigned>
8696 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8697                      SDISelAsmOperandInfo &OpInfo,
8698                      SDISelAsmOperandInfo &RefOpInfo) {
8699   LLVMContext &Context = *DAG.getContext();
8700   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8701 
8702   MachineFunction &MF = DAG.getMachineFunction();
8703   SmallVector<unsigned, 4> Regs;
8704   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8705 
8706   // No work to do for memory/address operands.
8707   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8708       OpInfo.ConstraintType == TargetLowering::C_Address)
8709     return std::nullopt;
8710 
8711   // If this is a constraint for a single physreg, or a constraint for a
8712   // register class, find it.
8713   unsigned AssignedReg;
8714   const TargetRegisterClass *RC;
8715   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8716       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8717   // RC is unset only on failure. Return immediately.
8718   if (!RC)
8719     return std::nullopt;
8720 
8721   // Get the actual register value type.  This is important, because the user
8722   // may have asked for (e.g.) the AX register in i32 type.  We need to
8723   // remember that AX is actually i16 to get the right extension.
8724   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8725 
8726   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8727     // If this is an FP operand in an integer register (or visa versa), or more
8728     // generally if the operand value disagrees with the register class we plan
8729     // to stick it in, fix the operand type.
8730     //
8731     // If this is an input value, the bitcast to the new type is done now.
8732     // Bitcast for output value is done at the end of visitInlineAsm().
8733     if ((OpInfo.Type == InlineAsm::isOutput ||
8734          OpInfo.Type == InlineAsm::isInput) &&
8735         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8736       // Try to convert to the first EVT that the reg class contains.  If the
8737       // types are identical size, use a bitcast to convert (e.g. two differing
8738       // vector types).  Note: output bitcast is done at the end of
8739       // visitInlineAsm().
8740       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8741         // Exclude indirect inputs while they are unsupported because the code
8742         // to perform the load is missing and thus OpInfo.CallOperand still
8743         // refers to the input address rather than the pointed-to value.
8744         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8745           OpInfo.CallOperand =
8746               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8747         OpInfo.ConstraintVT = RegVT;
8748         // If the operand is an FP value and we want it in integer registers,
8749         // use the corresponding integer type. This turns an f64 value into
8750         // i64, which can be passed with two i32 values on a 32-bit machine.
8751       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8752         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8753         if (OpInfo.Type == InlineAsm::isInput)
8754           OpInfo.CallOperand =
8755               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8756         OpInfo.ConstraintVT = VT;
8757       }
8758     }
8759   }
8760 
8761   // No need to allocate a matching input constraint since the constraint it's
8762   // matching to has already been allocated.
8763   if (OpInfo.isMatchingInputConstraint())
8764     return std::nullopt;
8765 
8766   EVT ValueVT = OpInfo.ConstraintVT;
8767   if (OpInfo.ConstraintVT == MVT::Other)
8768     ValueVT = RegVT;
8769 
8770   // Initialize NumRegs.
8771   unsigned NumRegs = 1;
8772   if (OpInfo.ConstraintVT != MVT::Other)
8773     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8774 
8775   // If this is a constraint for a specific physical register, like {r17},
8776   // assign it now.
8777 
8778   // If this associated to a specific register, initialize iterator to correct
8779   // place. If virtual, make sure we have enough registers
8780 
8781   // Initialize iterator if necessary
8782   TargetRegisterClass::iterator I = RC->begin();
8783   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8784 
8785   // Do not check for single registers.
8786   if (AssignedReg) {
8787     I = std::find(I, RC->end(), AssignedReg);
8788     if (I == RC->end()) {
8789       // RC does not contain the selected register, which indicates a
8790       // mismatch between the register and the required type/bitwidth.
8791       return {AssignedReg};
8792     }
8793   }
8794 
8795   for (; NumRegs; --NumRegs, ++I) {
8796     assert(I != RC->end() && "Ran out of registers to allocate!");
8797     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8798     Regs.push_back(R);
8799   }
8800 
8801   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8802   return std::nullopt;
8803 }
8804 
8805 static unsigned
8806 findMatchingInlineAsmOperand(unsigned OperandNo,
8807                              const std::vector<SDValue> &AsmNodeOperands) {
8808   // Scan until we find the definition we already emitted of this operand.
8809   unsigned CurOp = InlineAsm::Op_FirstOperand;
8810   for (; OperandNo; --OperandNo) {
8811     // Advance to the next operand.
8812     unsigned OpFlag =
8813         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8814     assert((InlineAsm::isRegDefKind(OpFlag) ||
8815             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8816             InlineAsm::isMemKind(OpFlag)) &&
8817            "Skipped past definitions?");
8818     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8819   }
8820   return CurOp;
8821 }
8822 
8823 namespace {
8824 
8825 class ExtraFlags {
8826   unsigned Flags = 0;
8827 
8828 public:
8829   explicit ExtraFlags(const CallBase &Call) {
8830     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8831     if (IA->hasSideEffects())
8832       Flags |= InlineAsm::Extra_HasSideEffects;
8833     if (IA->isAlignStack())
8834       Flags |= InlineAsm::Extra_IsAlignStack;
8835     if (Call.isConvergent())
8836       Flags |= InlineAsm::Extra_IsConvergent;
8837     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8838   }
8839 
8840   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8841     // Ideally, we would only check against memory constraints.  However, the
8842     // meaning of an Other constraint can be target-specific and we can't easily
8843     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8844     // for Other constraints as well.
8845     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8846         OpInfo.ConstraintType == TargetLowering::C_Other) {
8847       if (OpInfo.Type == InlineAsm::isInput)
8848         Flags |= InlineAsm::Extra_MayLoad;
8849       else if (OpInfo.Type == InlineAsm::isOutput)
8850         Flags |= InlineAsm::Extra_MayStore;
8851       else if (OpInfo.Type == InlineAsm::isClobber)
8852         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8853     }
8854   }
8855 
8856   unsigned get() const { return Flags; }
8857 };
8858 
8859 } // end anonymous namespace
8860 
8861 static bool isFunction(SDValue Op) {
8862   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
8863     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8864       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
8865 
8866       // In normal "call dllimport func" instruction (non-inlineasm) it force
8867       // indirect access by specifing call opcode. And usually specially print
8868       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
8869       // not do in this way now. (In fact, this is similar with "Data Access"
8870       // action). So here we ignore dllimport function.
8871       if (Fn && !Fn->hasDLLImportStorageClass())
8872         return true;
8873     }
8874   }
8875   return false;
8876 }
8877 
8878 /// visitInlineAsm - Handle a call to an InlineAsm object.
8879 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8880                                          const BasicBlock *EHPadBB) {
8881   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8882 
8883   /// ConstraintOperands - Information about all of the constraints.
8884   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8885 
8886   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8887   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8888       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8889 
8890   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8891   // AsmDialect, MayLoad, MayStore).
8892   bool HasSideEffect = IA->hasSideEffects();
8893   ExtraFlags ExtraInfo(Call);
8894 
8895   for (auto &T : TargetConstraints) {
8896     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8897     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8898 
8899     if (OpInfo.CallOperandVal)
8900       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8901 
8902     if (!HasSideEffect)
8903       HasSideEffect = OpInfo.hasMemory(TLI);
8904 
8905     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8906     // FIXME: Could we compute this on OpInfo rather than T?
8907 
8908     // Compute the constraint code and ConstraintType to use.
8909     TLI.ComputeConstraintToUse(T, SDValue());
8910 
8911     if (T.ConstraintType == TargetLowering::C_Immediate &&
8912         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8913       // We've delayed emitting a diagnostic like the "n" constraint because
8914       // inlining could cause an integer showing up.
8915       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8916                                           "' expects an integer constant "
8917                                           "expression");
8918 
8919     ExtraInfo.update(T);
8920   }
8921 
8922   // We won't need to flush pending loads if this asm doesn't touch
8923   // memory and is nonvolatile.
8924   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8925 
8926   bool EmitEHLabels = isa<InvokeInst>(Call);
8927   if (EmitEHLabels) {
8928     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8929   }
8930   bool IsCallBr = isa<CallBrInst>(Call);
8931 
8932   if (IsCallBr || EmitEHLabels) {
8933     // If this is a callbr or invoke we need to flush pending exports since
8934     // inlineasm_br and invoke are terminators.
8935     // We need to do this before nodes are glued to the inlineasm_br node.
8936     Chain = getControlRoot();
8937   }
8938 
8939   MCSymbol *BeginLabel = nullptr;
8940   if (EmitEHLabels) {
8941     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8942   }
8943 
8944   int OpNo = -1;
8945   SmallVector<StringRef> AsmStrs;
8946   IA->collectAsmStrs(AsmStrs);
8947 
8948   // Second pass over the constraints: compute which constraint option to use.
8949   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8950     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
8951       OpNo++;
8952 
8953     // If this is an output operand with a matching input operand, look up the
8954     // matching input. If their types mismatch, e.g. one is an integer, the
8955     // other is floating point, or their sizes are different, flag it as an
8956     // error.
8957     if (OpInfo.hasMatchingInput()) {
8958       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8959       patchMatchingInput(OpInfo, Input, DAG);
8960     }
8961 
8962     // Compute the constraint code and ConstraintType to use.
8963     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8964 
8965     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
8966          OpInfo.Type == InlineAsm::isClobber) ||
8967         OpInfo.ConstraintType == TargetLowering::C_Address)
8968       continue;
8969 
8970     // In Linux PIC model, there are 4 cases about value/label addressing:
8971     //
8972     // 1: Function call or Label jmp inside the module.
8973     // 2: Data access (such as global variable, static variable) inside module.
8974     // 3: Function call or Label jmp outside the module.
8975     // 4: Data access (such as global variable) outside the module.
8976     //
8977     // Due to current llvm inline asm architecture designed to not "recognize"
8978     // the asm code, there are quite troubles for us to treat mem addressing
8979     // differently for same value/adress used in different instuctions.
8980     // For example, in pic model, call a func may in plt way or direclty
8981     // pc-related, but lea/mov a function adress may use got.
8982     //
8983     // Here we try to "recognize" function call for the case 1 and case 3 in
8984     // inline asm. And try to adjust the constraint for them.
8985     //
8986     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
8987     // label, so here we don't handle jmp function label now, but we need to
8988     // enhance it (especilly in PIC model) if we meet meaningful requirements.
8989     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
8990         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
8991         TM.getCodeModel() != CodeModel::Large) {
8992       OpInfo.isIndirect = false;
8993       OpInfo.ConstraintType = TargetLowering::C_Address;
8994     }
8995 
8996     // If this is a memory input, and if the operand is not indirect, do what we
8997     // need to provide an address for the memory input.
8998     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8999         !OpInfo.isIndirect) {
9000       assert((OpInfo.isMultipleAlternative ||
9001               (OpInfo.Type == InlineAsm::isInput)) &&
9002              "Can only indirectify direct input operands!");
9003 
9004       // Memory operands really want the address of the value.
9005       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9006 
9007       // There is no longer a Value* corresponding to this operand.
9008       OpInfo.CallOperandVal = nullptr;
9009 
9010       // It is now an indirect operand.
9011       OpInfo.isIndirect = true;
9012     }
9013 
9014   }
9015 
9016   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9017   std::vector<SDValue> AsmNodeOperands;
9018   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9019   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9020       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9021 
9022   // If we have a !srcloc metadata node associated with it, we want to attach
9023   // this to the ultimately generated inline asm machineinstr.  To do this, we
9024   // pass in the third operand as this (potentially null) inline asm MDNode.
9025   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9026   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9027 
9028   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9029   // bits as operand 3.
9030   AsmNodeOperands.push_back(DAG.getTargetConstant(
9031       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9032 
9033   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9034   // this, assign virtual and physical registers for inputs and otput.
9035   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9036     // Assign Registers.
9037     SDISelAsmOperandInfo &RefOpInfo =
9038         OpInfo.isMatchingInputConstraint()
9039             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9040             : OpInfo;
9041     const auto RegError =
9042         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9043     if (RegError) {
9044       const MachineFunction &MF = DAG.getMachineFunction();
9045       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9046       const char *RegName = TRI.getName(*RegError);
9047       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9048                                    "' allocated for constraint '" +
9049                                    Twine(OpInfo.ConstraintCode) +
9050                                    "' does not match required type");
9051       return;
9052     }
9053 
9054     auto DetectWriteToReservedRegister = [&]() {
9055       const MachineFunction &MF = DAG.getMachineFunction();
9056       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9057       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9058         if (Register::isPhysicalRegister(Reg) &&
9059             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9060           const char *RegName = TRI.getName(Reg);
9061           emitInlineAsmError(Call, "write to reserved register '" +
9062                                        Twine(RegName) + "'");
9063           return true;
9064         }
9065       }
9066       return false;
9067     };
9068     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9069             (OpInfo.Type == InlineAsm::isInput &&
9070              !OpInfo.isMatchingInputConstraint())) &&
9071            "Only address as input operand is allowed.");
9072 
9073     switch (OpInfo.Type) {
9074     case InlineAsm::isOutput:
9075       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9076         unsigned ConstraintID =
9077             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9078         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9079                "Failed to convert memory constraint code to constraint id.");
9080 
9081         // Add information to the INLINEASM node to know about this output.
9082         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9083         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
9084         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9085                                                         MVT::i32));
9086         AsmNodeOperands.push_back(OpInfo.CallOperand);
9087       } else {
9088         // Otherwise, this outputs to a register (directly for C_Register /
9089         // C_RegisterClass, and a target-defined fashion for
9090         // C_Immediate/C_Other). Find a register that we can use.
9091         if (OpInfo.AssignedRegs.Regs.empty()) {
9092           emitInlineAsmError(
9093               Call, "couldn't allocate output register for constraint '" +
9094                         Twine(OpInfo.ConstraintCode) + "'");
9095           return;
9096         }
9097 
9098         if (DetectWriteToReservedRegister())
9099           return;
9100 
9101         // Add information to the INLINEASM node to know that this register is
9102         // set.
9103         OpInfo.AssignedRegs.AddInlineAsmOperands(
9104             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
9105                                   : InlineAsm::Kind_RegDef,
9106             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9107       }
9108       break;
9109 
9110     case InlineAsm::isInput:
9111     case InlineAsm::isLabel: {
9112       SDValue InOperandVal = OpInfo.CallOperand;
9113 
9114       if (OpInfo.isMatchingInputConstraint()) {
9115         // If this is required to match an output register we have already set,
9116         // just use its register.
9117         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9118                                                   AsmNodeOperands);
9119         unsigned OpFlag =
9120           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
9121         if (InlineAsm::isRegDefKind(OpFlag) ||
9122             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
9123           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
9124           if (OpInfo.isIndirect) {
9125             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9126             emitInlineAsmError(Call, "inline asm not supported yet: "
9127                                      "don't know how to handle tied "
9128                                      "indirect register inputs");
9129             return;
9130           }
9131 
9132           SmallVector<unsigned, 4> Regs;
9133           MachineFunction &MF = DAG.getMachineFunction();
9134           MachineRegisterInfo &MRI = MF.getRegInfo();
9135           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9136           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9137           Register TiedReg = R->getReg();
9138           MVT RegVT = R->getSimpleValueType(0);
9139           const TargetRegisterClass *RC =
9140               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9141               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9142                                       : TRI.getMinimalPhysRegClass(TiedReg);
9143           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
9144           for (unsigned i = 0; i != NumRegs; ++i)
9145             Regs.push_back(MRI.createVirtualRegister(RC));
9146 
9147           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9148 
9149           SDLoc dl = getCurSDLoc();
9150           // Use the produced MatchedRegs object to
9151           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9152           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
9153                                            true, OpInfo.getMatchedOperand(), dl,
9154                                            DAG, AsmNodeOperands);
9155           break;
9156         }
9157 
9158         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
9159         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
9160                "Unexpected number of operands");
9161         // Add information to the INLINEASM node to know about this input.
9162         // See InlineAsm.h isUseOperandTiedToDef.
9163         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
9164         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
9165                                                     OpInfo.getMatchedOperand());
9166         AsmNodeOperands.push_back(DAG.getTargetConstant(
9167             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9168         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9169         break;
9170       }
9171 
9172       // Treat indirect 'X' constraint as memory.
9173       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9174           OpInfo.isIndirect)
9175         OpInfo.ConstraintType = TargetLowering::C_Memory;
9176 
9177       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9178           OpInfo.ConstraintType == TargetLowering::C_Other) {
9179         std::vector<SDValue> Ops;
9180         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9181                                           Ops, DAG);
9182         if (Ops.empty()) {
9183           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9184             if (isa<ConstantSDNode>(InOperandVal)) {
9185               emitInlineAsmError(Call, "value out of range for constraint '" +
9186                                            Twine(OpInfo.ConstraintCode) + "'");
9187               return;
9188             }
9189 
9190           emitInlineAsmError(Call,
9191                              "invalid operand for inline asm constraint '" +
9192                                  Twine(OpInfo.ConstraintCode) + "'");
9193           return;
9194         }
9195 
9196         // Add information to the INLINEASM node to know about this input.
9197         unsigned ResOpType =
9198           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
9199         AsmNodeOperands.push_back(DAG.getTargetConstant(
9200             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9201         llvm::append_range(AsmNodeOperands, Ops);
9202         break;
9203       }
9204 
9205       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9206         assert((OpInfo.isIndirect ||
9207                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9208                "Operand must be indirect to be a mem!");
9209         assert(InOperandVal.getValueType() ==
9210                    TLI.getPointerTy(DAG.getDataLayout()) &&
9211                "Memory operands expect pointer values");
9212 
9213         unsigned ConstraintID =
9214             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9215         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9216                "Failed to convert memory constraint code to constraint id.");
9217 
9218         // Add information to the INLINEASM node to know about this input.
9219         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9220         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9221         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9222                                                         getCurSDLoc(),
9223                                                         MVT::i32));
9224         AsmNodeOperands.push_back(InOperandVal);
9225         break;
9226       }
9227 
9228       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9229         assert(InOperandVal.getValueType() ==
9230                    TLI.getPointerTy(DAG.getDataLayout()) &&
9231                "Address operands expect pointer values");
9232 
9233         unsigned ConstraintID =
9234             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9235         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9236                "Failed to convert memory constraint code to constraint id.");
9237 
9238         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9239 
9240         SDValue AsmOp = InOperandVal;
9241         if (isFunction(InOperandVal)) {
9242           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9243           ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1);
9244           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9245                                              InOperandVal.getValueType(),
9246                                              GA->getOffset());
9247         }
9248 
9249         // Add information to the INLINEASM node to know about this input.
9250         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9251 
9252         AsmNodeOperands.push_back(
9253             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9254 
9255         AsmNodeOperands.push_back(AsmOp);
9256         break;
9257       }
9258 
9259       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9260               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9261              "Unknown constraint type!");
9262 
9263       // TODO: Support this.
9264       if (OpInfo.isIndirect) {
9265         emitInlineAsmError(
9266             Call, "Don't know how to handle indirect register inputs yet "
9267                   "for constraint '" +
9268                       Twine(OpInfo.ConstraintCode) + "'");
9269         return;
9270       }
9271 
9272       // Copy the input into the appropriate registers.
9273       if (OpInfo.AssignedRegs.Regs.empty()) {
9274         emitInlineAsmError(Call,
9275                            "couldn't allocate input reg for constraint '" +
9276                                Twine(OpInfo.ConstraintCode) + "'");
9277         return;
9278       }
9279 
9280       if (DetectWriteToReservedRegister())
9281         return;
9282 
9283       SDLoc dl = getCurSDLoc();
9284 
9285       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
9286                                         &Call);
9287 
9288       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
9289                                                dl, DAG, AsmNodeOperands);
9290       break;
9291     }
9292     case InlineAsm::isClobber:
9293       // Add the clobbered value to the operand list, so that the register
9294       // allocator is aware that the physreg got clobbered.
9295       if (!OpInfo.AssignedRegs.Regs.empty())
9296         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
9297                                                  false, 0, getCurSDLoc(), DAG,
9298                                                  AsmNodeOperands);
9299       break;
9300     }
9301   }
9302 
9303   // Finish up input operands.  Set the input chain and add the flag last.
9304   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9305   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
9306 
9307   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9308   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9309                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9310   Glue = Chain.getValue(1);
9311 
9312   // Do additional work to generate outputs.
9313 
9314   SmallVector<EVT, 1> ResultVTs;
9315   SmallVector<SDValue, 1> ResultValues;
9316   SmallVector<SDValue, 8> OutChains;
9317 
9318   llvm::Type *CallResultType = Call.getType();
9319   ArrayRef<Type *> ResultTypes;
9320   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9321     ResultTypes = StructResult->elements();
9322   else if (!CallResultType->isVoidTy())
9323     ResultTypes = ArrayRef(CallResultType);
9324 
9325   auto CurResultType = ResultTypes.begin();
9326   auto handleRegAssign = [&](SDValue V) {
9327     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9328     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9329     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9330     ++CurResultType;
9331     // If the type of the inline asm call site return value is different but has
9332     // same size as the type of the asm output bitcast it.  One example of this
9333     // is for vectors with different width / number of elements.  This can
9334     // happen for register classes that can contain multiple different value
9335     // types.  The preg or vreg allocated may not have the same VT as was
9336     // expected.
9337     //
9338     // This can also happen for a return value that disagrees with the register
9339     // class it is put in, eg. a double in a general-purpose register on a
9340     // 32-bit machine.
9341     if (ResultVT != V.getValueType() &&
9342         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9343       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9344     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9345              V.getValueType().isInteger()) {
9346       // If a result value was tied to an input value, the computed result
9347       // may have a wider width than the expected result.  Extract the
9348       // relevant portion.
9349       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9350     }
9351     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9352     ResultVTs.push_back(ResultVT);
9353     ResultValues.push_back(V);
9354   };
9355 
9356   // Deal with output operands.
9357   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9358     if (OpInfo.Type == InlineAsm::isOutput) {
9359       SDValue Val;
9360       // Skip trivial output operands.
9361       if (OpInfo.AssignedRegs.Regs.empty())
9362         continue;
9363 
9364       switch (OpInfo.ConstraintType) {
9365       case TargetLowering::C_Register:
9366       case TargetLowering::C_RegisterClass:
9367         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9368                                                   Chain, &Glue, &Call);
9369         break;
9370       case TargetLowering::C_Immediate:
9371       case TargetLowering::C_Other:
9372         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
9373                                               OpInfo, DAG);
9374         break;
9375       case TargetLowering::C_Memory:
9376         break; // Already handled.
9377       case TargetLowering::C_Address:
9378         break; // Silence warning.
9379       case TargetLowering::C_Unknown:
9380         assert(false && "Unexpected unknown constraint");
9381       }
9382 
9383       // Indirect output manifest as stores. Record output chains.
9384       if (OpInfo.isIndirect) {
9385         const Value *Ptr = OpInfo.CallOperandVal;
9386         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9387         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9388                                      MachinePointerInfo(Ptr));
9389         OutChains.push_back(Store);
9390       } else {
9391         // generate CopyFromRegs to associated registers.
9392         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9393         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9394           for (const SDValue &V : Val->op_values())
9395             handleRegAssign(V);
9396         } else
9397           handleRegAssign(Val);
9398       }
9399     }
9400   }
9401 
9402   // Set results.
9403   if (!ResultValues.empty()) {
9404     assert(CurResultType == ResultTypes.end() &&
9405            "Mismatch in number of ResultTypes");
9406     assert(ResultValues.size() == ResultTypes.size() &&
9407            "Mismatch in number of output operands in asm result");
9408 
9409     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9410                             DAG.getVTList(ResultVTs), ResultValues);
9411     setValue(&Call, V);
9412   }
9413 
9414   // Collect store chains.
9415   if (!OutChains.empty())
9416     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9417 
9418   if (EmitEHLabels) {
9419     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9420   }
9421 
9422   // Only Update Root if inline assembly has a memory effect.
9423   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9424       EmitEHLabels)
9425     DAG.setRoot(Chain);
9426 }
9427 
9428 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9429                                              const Twine &Message) {
9430   LLVMContext &Ctx = *DAG.getContext();
9431   Ctx.emitError(&Call, Message);
9432 
9433   // Make sure we leave the DAG in a valid state
9434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9435   SmallVector<EVT, 1> ValueVTs;
9436   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9437 
9438   if (ValueVTs.empty())
9439     return;
9440 
9441   SmallVector<SDValue, 1> Ops;
9442   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9443     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9444 
9445   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9446 }
9447 
9448 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9449   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9450                           MVT::Other, getRoot(),
9451                           getValue(I.getArgOperand(0)),
9452                           DAG.getSrcValue(I.getArgOperand(0))));
9453 }
9454 
9455 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9456   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9457   const DataLayout &DL = DAG.getDataLayout();
9458   SDValue V = DAG.getVAArg(
9459       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9460       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9461       DL.getABITypeAlign(I.getType()).value());
9462   DAG.setRoot(V.getValue(1));
9463 
9464   if (I.getType()->isPointerTy())
9465     V = DAG.getPtrExtOrTrunc(
9466         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9467   setValue(&I, V);
9468 }
9469 
9470 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9471   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9472                           MVT::Other, getRoot(),
9473                           getValue(I.getArgOperand(0)),
9474                           DAG.getSrcValue(I.getArgOperand(0))));
9475 }
9476 
9477 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9478   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9479                           MVT::Other, getRoot(),
9480                           getValue(I.getArgOperand(0)),
9481                           getValue(I.getArgOperand(1)),
9482                           DAG.getSrcValue(I.getArgOperand(0)),
9483                           DAG.getSrcValue(I.getArgOperand(1))));
9484 }
9485 
9486 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9487                                                     const Instruction &I,
9488                                                     SDValue Op) {
9489   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9490   if (!Range)
9491     return Op;
9492 
9493   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9494   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9495     return Op;
9496 
9497   APInt Lo = CR.getUnsignedMin();
9498   if (!Lo.isMinValue())
9499     return Op;
9500 
9501   APInt Hi = CR.getUnsignedMax();
9502   unsigned Bits = std::max(Hi.getActiveBits(),
9503                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9504 
9505   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9506 
9507   SDLoc SL = getCurSDLoc();
9508 
9509   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9510                              DAG.getValueType(SmallVT));
9511   unsigned NumVals = Op.getNode()->getNumValues();
9512   if (NumVals == 1)
9513     return ZExt;
9514 
9515   SmallVector<SDValue, 4> Ops;
9516 
9517   Ops.push_back(ZExt);
9518   for (unsigned I = 1; I != NumVals; ++I)
9519     Ops.push_back(Op.getValue(I));
9520 
9521   return DAG.getMergeValues(Ops, SL);
9522 }
9523 
9524 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9525 /// the call being lowered.
9526 ///
9527 /// This is a helper for lowering intrinsics that follow a target calling
9528 /// convention or require stack pointer adjustment. Only a subset of the
9529 /// intrinsic's operands need to participate in the calling convention.
9530 void SelectionDAGBuilder::populateCallLoweringInfo(
9531     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9532     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9533     bool IsPatchPoint) {
9534   TargetLowering::ArgListTy Args;
9535   Args.reserve(NumArgs);
9536 
9537   // Populate the argument list.
9538   // Attributes for args start at offset 1, after the return attribute.
9539   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9540        ArgI != ArgE; ++ArgI) {
9541     const Value *V = Call->getOperand(ArgI);
9542 
9543     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9544 
9545     TargetLowering::ArgListEntry Entry;
9546     Entry.Node = getValue(V);
9547     Entry.Ty = V->getType();
9548     Entry.setAttributes(Call, ArgI);
9549     Args.push_back(Entry);
9550   }
9551 
9552   CLI.setDebugLoc(getCurSDLoc())
9553       .setChain(getRoot())
9554       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9555       .setDiscardResult(Call->use_empty())
9556       .setIsPatchPoint(IsPatchPoint)
9557       .setIsPreallocated(
9558           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9559 }
9560 
9561 /// Add a stack map intrinsic call's live variable operands to a stackmap
9562 /// or patchpoint target node's operand list.
9563 ///
9564 /// Constants are converted to TargetConstants purely as an optimization to
9565 /// avoid constant materialization and register allocation.
9566 ///
9567 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9568 /// generate addess computation nodes, and so FinalizeISel can convert the
9569 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9570 /// address materialization and register allocation, but may also be required
9571 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9572 /// alloca in the entry block, then the runtime may assume that the alloca's
9573 /// StackMap location can be read immediately after compilation and that the
9574 /// location is valid at any point during execution (this is similar to the
9575 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9576 /// only available in a register, then the runtime would need to trap when
9577 /// execution reaches the StackMap in order to read the alloca's location.
9578 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9579                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9580                                 SelectionDAGBuilder &Builder) {
9581   SelectionDAG &DAG = Builder.DAG;
9582   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9583     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9584 
9585     // Things on the stack are pointer-typed, meaning that they are already
9586     // legal and can be emitted directly to target nodes.
9587     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9588       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9589     } else {
9590       // Otherwise emit a target independent node to be legalised.
9591       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9592     }
9593   }
9594 }
9595 
9596 /// Lower llvm.experimental.stackmap.
9597 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9598   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9599   //                                  [live variables...])
9600 
9601   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9602 
9603   SDValue Chain, InGlue, Callee;
9604   SmallVector<SDValue, 32> Ops;
9605 
9606   SDLoc DL = getCurSDLoc();
9607   Callee = getValue(CI.getCalledOperand());
9608 
9609   // The stackmap intrinsic only records the live variables (the arguments
9610   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9611   // intrinsic, this won't be lowered to a function call. This means we don't
9612   // have to worry about calling conventions and target specific lowering code.
9613   // Instead we perform the call lowering right here.
9614   //
9615   // chain, flag = CALLSEQ_START(chain, 0, 0)
9616   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9617   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9618   //
9619   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9620   InGlue = Chain.getValue(1);
9621 
9622   // Add the STACKMAP operands, starting with DAG house-keeping.
9623   Ops.push_back(Chain);
9624   Ops.push_back(InGlue);
9625 
9626   // Add the <id>, <numShadowBytes> operands.
9627   //
9628   // These do not require legalisation, and can be emitted directly to target
9629   // constant nodes.
9630   SDValue ID = getValue(CI.getArgOperand(0));
9631   assert(ID.getValueType() == MVT::i64);
9632   SDValue IDConst = DAG.getTargetConstant(
9633       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9634   Ops.push_back(IDConst);
9635 
9636   SDValue Shad = getValue(CI.getArgOperand(1));
9637   assert(Shad.getValueType() == MVT::i32);
9638   SDValue ShadConst = DAG.getTargetConstant(
9639       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9640   Ops.push_back(ShadConst);
9641 
9642   // Add the live variables.
9643   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9644 
9645   // Create the STACKMAP node.
9646   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9647   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9648   InGlue = Chain.getValue(1);
9649 
9650   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
9651 
9652   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9653 
9654   // Set the root to the target-lowered call chain.
9655   DAG.setRoot(Chain);
9656 
9657   // Inform the Frame Information that we have a stackmap in this function.
9658   FuncInfo.MF->getFrameInfo().setHasStackMap();
9659 }
9660 
9661 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9662 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9663                                           const BasicBlock *EHPadBB) {
9664   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9665   //                                                 i32 <numBytes>,
9666   //                                                 i8* <target>,
9667   //                                                 i32 <numArgs>,
9668   //                                                 [Args...],
9669   //                                                 [live variables...])
9670 
9671   CallingConv::ID CC = CB.getCallingConv();
9672   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9673   bool HasDef = !CB.getType()->isVoidTy();
9674   SDLoc dl = getCurSDLoc();
9675   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9676 
9677   // Handle immediate and symbolic callees.
9678   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9679     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9680                                    /*isTarget=*/true);
9681   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9682     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9683                                          SDLoc(SymbolicCallee),
9684                                          SymbolicCallee->getValueType(0));
9685 
9686   // Get the real number of arguments participating in the call <numArgs>
9687   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9688   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9689 
9690   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9691   // Intrinsics include all meta-operands up to but not including CC.
9692   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9693   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9694          "Not enough arguments provided to the patchpoint intrinsic");
9695 
9696   // For AnyRegCC the arguments are lowered later on manually.
9697   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9698   Type *ReturnTy =
9699       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9700 
9701   TargetLowering::CallLoweringInfo CLI(DAG);
9702   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9703                            ReturnTy, true);
9704   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9705 
9706   SDNode *CallEnd = Result.second.getNode();
9707   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9708     CallEnd = CallEnd->getOperand(0).getNode();
9709 
9710   /// Get a call instruction from the call sequence chain.
9711   /// Tail calls are not allowed.
9712   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9713          "Expected a callseq node.");
9714   SDNode *Call = CallEnd->getOperand(0).getNode();
9715   bool HasGlue = Call->getGluedNode();
9716 
9717   // Replace the target specific call node with the patchable intrinsic.
9718   SmallVector<SDValue, 8> Ops;
9719 
9720   // Push the chain.
9721   Ops.push_back(*(Call->op_begin()));
9722 
9723   // Optionally, push the glue (if any).
9724   if (HasGlue)
9725     Ops.push_back(*(Call->op_end() - 1));
9726 
9727   // Push the register mask info.
9728   if (HasGlue)
9729     Ops.push_back(*(Call->op_end() - 2));
9730   else
9731     Ops.push_back(*(Call->op_end() - 1));
9732 
9733   // Add the <id> and <numBytes> constants.
9734   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9735   Ops.push_back(DAG.getTargetConstant(
9736                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9737   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9738   Ops.push_back(DAG.getTargetConstant(
9739                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9740                   MVT::i32));
9741 
9742   // Add the callee.
9743   Ops.push_back(Callee);
9744 
9745   // Adjust <numArgs> to account for any arguments that have been passed on the
9746   // stack instead.
9747   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9748   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9749   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9750   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9751 
9752   // Add the calling convention
9753   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9754 
9755   // Add the arguments we omitted previously. The register allocator should
9756   // place these in any free register.
9757   if (IsAnyRegCC)
9758     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9759       Ops.push_back(getValue(CB.getArgOperand(i)));
9760 
9761   // Push the arguments from the call instruction.
9762   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9763   Ops.append(Call->op_begin() + 2, e);
9764 
9765   // Push live variables for the stack map.
9766   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9767 
9768   SDVTList NodeTys;
9769   if (IsAnyRegCC && HasDef) {
9770     // Create the return types based on the intrinsic definition
9771     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9772     SmallVector<EVT, 3> ValueVTs;
9773     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9774     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9775 
9776     // There is always a chain and a glue type at the end
9777     ValueVTs.push_back(MVT::Other);
9778     ValueVTs.push_back(MVT::Glue);
9779     NodeTys = DAG.getVTList(ValueVTs);
9780   } else
9781     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9782 
9783   // Replace the target specific call node with a PATCHPOINT node.
9784   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
9785 
9786   // Update the NodeMap.
9787   if (HasDef) {
9788     if (IsAnyRegCC)
9789       setValue(&CB, SDValue(PPV.getNode(), 0));
9790     else
9791       setValue(&CB, Result.first);
9792   }
9793 
9794   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9795   // call sequence. Furthermore the location of the chain and glue can change
9796   // when the AnyReg calling convention is used and the intrinsic returns a
9797   // value.
9798   if (IsAnyRegCC && HasDef) {
9799     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9800     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
9801     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9802   } else
9803     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
9804   DAG.DeleteNode(Call);
9805 
9806   // Inform the Frame Information that we have a patchpoint in this function.
9807   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9808 }
9809 
9810 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9811                                             unsigned Intrinsic) {
9812   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9813   SDValue Op1 = getValue(I.getArgOperand(0));
9814   SDValue Op2;
9815   if (I.arg_size() > 1)
9816     Op2 = getValue(I.getArgOperand(1));
9817   SDLoc dl = getCurSDLoc();
9818   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9819   SDValue Res;
9820   SDNodeFlags SDFlags;
9821   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9822     SDFlags.copyFMF(*FPMO);
9823 
9824   switch (Intrinsic) {
9825   case Intrinsic::vector_reduce_fadd:
9826     if (SDFlags.hasAllowReassociation())
9827       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9828                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9829                         SDFlags);
9830     else
9831       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9832     break;
9833   case Intrinsic::vector_reduce_fmul:
9834     if (SDFlags.hasAllowReassociation())
9835       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9836                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9837                         SDFlags);
9838     else
9839       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9840     break;
9841   case Intrinsic::vector_reduce_add:
9842     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9843     break;
9844   case Intrinsic::vector_reduce_mul:
9845     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9846     break;
9847   case Intrinsic::vector_reduce_and:
9848     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9849     break;
9850   case Intrinsic::vector_reduce_or:
9851     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9852     break;
9853   case Intrinsic::vector_reduce_xor:
9854     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9855     break;
9856   case Intrinsic::vector_reduce_smax:
9857     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9858     break;
9859   case Intrinsic::vector_reduce_smin:
9860     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9861     break;
9862   case Intrinsic::vector_reduce_umax:
9863     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9864     break;
9865   case Intrinsic::vector_reduce_umin:
9866     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9867     break;
9868   case Intrinsic::vector_reduce_fmax:
9869     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9870     break;
9871   case Intrinsic::vector_reduce_fmin:
9872     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9873     break;
9874   default:
9875     llvm_unreachable("Unhandled vector reduce intrinsic");
9876   }
9877   setValue(&I, Res);
9878 }
9879 
9880 /// Returns an AttributeList representing the attributes applied to the return
9881 /// value of the given call.
9882 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9883   SmallVector<Attribute::AttrKind, 2> Attrs;
9884   if (CLI.RetSExt)
9885     Attrs.push_back(Attribute::SExt);
9886   if (CLI.RetZExt)
9887     Attrs.push_back(Attribute::ZExt);
9888   if (CLI.IsInReg)
9889     Attrs.push_back(Attribute::InReg);
9890 
9891   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9892                             Attrs);
9893 }
9894 
9895 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9896 /// implementation, which just calls LowerCall.
9897 /// FIXME: When all targets are
9898 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9899 std::pair<SDValue, SDValue>
9900 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9901   // Handle the incoming return values from the call.
9902   CLI.Ins.clear();
9903   Type *OrigRetTy = CLI.RetTy;
9904   SmallVector<EVT, 4> RetTys;
9905   SmallVector<uint64_t, 4> Offsets;
9906   auto &DL = CLI.DAG.getDataLayout();
9907   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9908 
9909   if (CLI.IsPostTypeLegalization) {
9910     // If we are lowering a libcall after legalization, split the return type.
9911     SmallVector<EVT, 4> OldRetTys;
9912     SmallVector<uint64_t, 4> OldOffsets;
9913     RetTys.swap(OldRetTys);
9914     Offsets.swap(OldOffsets);
9915 
9916     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9917       EVT RetVT = OldRetTys[i];
9918       uint64_t Offset = OldOffsets[i];
9919       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9920       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9921       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9922       RetTys.append(NumRegs, RegisterVT);
9923       for (unsigned j = 0; j != NumRegs; ++j)
9924         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9925     }
9926   }
9927 
9928   SmallVector<ISD::OutputArg, 4> Outs;
9929   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9930 
9931   bool CanLowerReturn =
9932       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9933                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9934 
9935   SDValue DemoteStackSlot;
9936   int DemoteStackIdx = -100;
9937   if (!CanLowerReturn) {
9938     // FIXME: equivalent assert?
9939     // assert(!CS.hasInAllocaArgument() &&
9940     //        "sret demotion is incompatible with inalloca");
9941     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9942     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9943     MachineFunction &MF = CLI.DAG.getMachineFunction();
9944     DemoteStackIdx =
9945         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9946     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9947                                               DL.getAllocaAddrSpace());
9948 
9949     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9950     ArgListEntry Entry;
9951     Entry.Node = DemoteStackSlot;
9952     Entry.Ty = StackSlotPtrType;
9953     Entry.IsSExt = false;
9954     Entry.IsZExt = false;
9955     Entry.IsInReg = false;
9956     Entry.IsSRet = true;
9957     Entry.IsNest = false;
9958     Entry.IsByVal = false;
9959     Entry.IsByRef = false;
9960     Entry.IsReturned = false;
9961     Entry.IsSwiftSelf = false;
9962     Entry.IsSwiftAsync = false;
9963     Entry.IsSwiftError = false;
9964     Entry.IsCFGuardTarget = false;
9965     Entry.Alignment = Alignment;
9966     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9967     CLI.NumFixedArgs += 1;
9968     CLI.getArgs()[0].IndirectType = CLI.RetTy;
9969     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9970 
9971     // sret demotion isn't compatible with tail-calls, since the sret argument
9972     // points into the callers stack frame.
9973     CLI.IsTailCall = false;
9974   } else {
9975     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9976         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9977     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9978       ISD::ArgFlagsTy Flags;
9979       if (NeedsRegBlock) {
9980         Flags.setInConsecutiveRegs();
9981         if (I == RetTys.size() - 1)
9982           Flags.setInConsecutiveRegsLast();
9983       }
9984       EVT VT = RetTys[I];
9985       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9986                                                      CLI.CallConv, VT);
9987       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9988                                                        CLI.CallConv, VT);
9989       for (unsigned i = 0; i != NumRegs; ++i) {
9990         ISD::InputArg MyFlags;
9991         MyFlags.Flags = Flags;
9992         MyFlags.VT = RegisterVT;
9993         MyFlags.ArgVT = VT;
9994         MyFlags.Used = CLI.IsReturnValueUsed;
9995         if (CLI.RetTy->isPointerTy()) {
9996           MyFlags.Flags.setPointer();
9997           MyFlags.Flags.setPointerAddrSpace(
9998               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9999         }
10000         if (CLI.RetSExt)
10001           MyFlags.Flags.setSExt();
10002         if (CLI.RetZExt)
10003           MyFlags.Flags.setZExt();
10004         if (CLI.IsInReg)
10005           MyFlags.Flags.setInReg();
10006         CLI.Ins.push_back(MyFlags);
10007       }
10008     }
10009   }
10010 
10011   // We push in swifterror return as the last element of CLI.Ins.
10012   ArgListTy &Args = CLI.getArgs();
10013   if (supportSwiftError()) {
10014     for (const ArgListEntry &Arg : Args) {
10015       if (Arg.IsSwiftError) {
10016         ISD::InputArg MyFlags;
10017         MyFlags.VT = getPointerTy(DL);
10018         MyFlags.ArgVT = EVT(getPointerTy(DL));
10019         MyFlags.Flags.setSwiftError();
10020         CLI.Ins.push_back(MyFlags);
10021       }
10022     }
10023   }
10024 
10025   // Handle all of the outgoing arguments.
10026   CLI.Outs.clear();
10027   CLI.OutVals.clear();
10028   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10029     SmallVector<EVT, 4> ValueVTs;
10030     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10031     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10032     Type *FinalType = Args[i].Ty;
10033     if (Args[i].IsByVal)
10034       FinalType = Args[i].IndirectType;
10035     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10036         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10037     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10038          ++Value) {
10039       EVT VT = ValueVTs[Value];
10040       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10041       SDValue Op = SDValue(Args[i].Node.getNode(),
10042                            Args[i].Node.getResNo() + Value);
10043       ISD::ArgFlagsTy Flags;
10044 
10045       // Certain targets (such as MIPS), may have a different ABI alignment
10046       // for a type depending on the context. Give the target a chance to
10047       // specify the alignment it wants.
10048       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10049       Flags.setOrigAlign(OriginalAlignment);
10050 
10051       if (Args[i].Ty->isPointerTy()) {
10052         Flags.setPointer();
10053         Flags.setPointerAddrSpace(
10054             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10055       }
10056       if (Args[i].IsZExt)
10057         Flags.setZExt();
10058       if (Args[i].IsSExt)
10059         Flags.setSExt();
10060       if (Args[i].IsInReg) {
10061         // If we are using vectorcall calling convention, a structure that is
10062         // passed InReg - is surely an HVA
10063         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10064             isa<StructType>(FinalType)) {
10065           // The first value of a structure is marked
10066           if (0 == Value)
10067             Flags.setHvaStart();
10068           Flags.setHva();
10069         }
10070         // Set InReg Flag
10071         Flags.setInReg();
10072       }
10073       if (Args[i].IsSRet)
10074         Flags.setSRet();
10075       if (Args[i].IsSwiftSelf)
10076         Flags.setSwiftSelf();
10077       if (Args[i].IsSwiftAsync)
10078         Flags.setSwiftAsync();
10079       if (Args[i].IsSwiftError)
10080         Flags.setSwiftError();
10081       if (Args[i].IsCFGuardTarget)
10082         Flags.setCFGuardTarget();
10083       if (Args[i].IsByVal)
10084         Flags.setByVal();
10085       if (Args[i].IsByRef)
10086         Flags.setByRef();
10087       if (Args[i].IsPreallocated) {
10088         Flags.setPreallocated();
10089         // Set the byval flag for CCAssignFn callbacks that don't know about
10090         // preallocated.  This way we can know how many bytes we should've
10091         // allocated and how many bytes a callee cleanup function will pop.  If
10092         // we port preallocated to more targets, we'll have to add custom
10093         // preallocated handling in the various CC lowering callbacks.
10094         Flags.setByVal();
10095       }
10096       if (Args[i].IsInAlloca) {
10097         Flags.setInAlloca();
10098         // Set the byval flag for CCAssignFn callbacks that don't know about
10099         // inalloca.  This way we can know how many bytes we should've allocated
10100         // and how many bytes a callee cleanup function will pop.  If we port
10101         // inalloca to more targets, we'll have to add custom inalloca handling
10102         // in the various CC lowering callbacks.
10103         Flags.setByVal();
10104       }
10105       Align MemAlign;
10106       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10107         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10108         Flags.setByValSize(FrameSize);
10109 
10110         // info is not there but there are cases it cannot get right.
10111         if (auto MA = Args[i].Alignment)
10112           MemAlign = *MA;
10113         else
10114           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10115       } else if (auto MA = Args[i].Alignment) {
10116         MemAlign = *MA;
10117       } else {
10118         MemAlign = OriginalAlignment;
10119       }
10120       Flags.setMemAlign(MemAlign);
10121       if (Args[i].IsNest)
10122         Flags.setNest();
10123       if (NeedsRegBlock)
10124         Flags.setInConsecutiveRegs();
10125 
10126       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10127                                                  CLI.CallConv, VT);
10128       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10129                                                         CLI.CallConv, VT);
10130       SmallVector<SDValue, 4> Parts(NumParts);
10131       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10132 
10133       if (Args[i].IsSExt)
10134         ExtendKind = ISD::SIGN_EXTEND;
10135       else if (Args[i].IsZExt)
10136         ExtendKind = ISD::ZERO_EXTEND;
10137 
10138       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10139       // for now.
10140       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10141           CanLowerReturn) {
10142         assert((CLI.RetTy == Args[i].Ty ||
10143                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10144                  CLI.RetTy->getPointerAddressSpace() ==
10145                      Args[i].Ty->getPointerAddressSpace())) &&
10146                RetTys.size() == NumValues && "unexpected use of 'returned'");
10147         // Before passing 'returned' to the target lowering code, ensure that
10148         // either the register MVT and the actual EVT are the same size or that
10149         // the return value and argument are extended in the same way; in these
10150         // cases it's safe to pass the argument register value unchanged as the
10151         // return register value (although it's at the target's option whether
10152         // to do so)
10153         // TODO: allow code generation to take advantage of partially preserved
10154         // registers rather than clobbering the entire register when the
10155         // parameter extension method is not compatible with the return
10156         // extension method
10157         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10158             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10159              CLI.RetZExt == Args[i].IsZExt))
10160           Flags.setReturned();
10161       }
10162 
10163       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10164                      CLI.CallConv, ExtendKind);
10165 
10166       for (unsigned j = 0; j != NumParts; ++j) {
10167         // if it isn't first piece, alignment must be 1
10168         // For scalable vectors the scalable part is currently handled
10169         // by individual targets, so we just use the known minimum size here.
10170         ISD::OutputArg MyFlags(
10171             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10172             i < CLI.NumFixedArgs, i,
10173             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10174         if (NumParts > 1 && j == 0)
10175           MyFlags.Flags.setSplit();
10176         else if (j != 0) {
10177           MyFlags.Flags.setOrigAlign(Align(1));
10178           if (j == NumParts - 1)
10179             MyFlags.Flags.setSplitEnd();
10180         }
10181 
10182         CLI.Outs.push_back(MyFlags);
10183         CLI.OutVals.push_back(Parts[j]);
10184       }
10185 
10186       if (NeedsRegBlock && Value == NumValues - 1)
10187         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10188     }
10189   }
10190 
10191   SmallVector<SDValue, 4> InVals;
10192   CLI.Chain = LowerCall(CLI, InVals);
10193 
10194   // Update CLI.InVals to use outside of this function.
10195   CLI.InVals = InVals;
10196 
10197   // Verify that the target's LowerCall behaved as expected.
10198   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10199          "LowerCall didn't return a valid chain!");
10200   assert((!CLI.IsTailCall || InVals.empty()) &&
10201          "LowerCall emitted a return value for a tail call!");
10202   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10203          "LowerCall didn't emit the correct number of values!");
10204 
10205   // For a tail call, the return value is merely live-out and there aren't
10206   // any nodes in the DAG representing it. Return a special value to
10207   // indicate that a tail call has been emitted and no more Instructions
10208   // should be processed in the current block.
10209   if (CLI.IsTailCall) {
10210     CLI.DAG.setRoot(CLI.Chain);
10211     return std::make_pair(SDValue(), SDValue());
10212   }
10213 
10214 #ifndef NDEBUG
10215   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10216     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10217     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10218            "LowerCall emitted a value with the wrong type!");
10219   }
10220 #endif
10221 
10222   SmallVector<SDValue, 4> ReturnValues;
10223   if (!CanLowerReturn) {
10224     // The instruction result is the result of loading from the
10225     // hidden sret parameter.
10226     SmallVector<EVT, 1> PVTs;
10227     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
10228 
10229     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10230     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10231     EVT PtrVT = PVTs[0];
10232 
10233     unsigned NumValues = RetTys.size();
10234     ReturnValues.resize(NumValues);
10235     SmallVector<SDValue, 4> Chains(NumValues);
10236 
10237     // An aggregate return value cannot wrap around the address space, so
10238     // offsets to its parts don't wrap either.
10239     SDNodeFlags Flags;
10240     Flags.setNoUnsignedWrap(true);
10241 
10242     MachineFunction &MF = CLI.DAG.getMachineFunction();
10243     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10244     for (unsigned i = 0; i < NumValues; ++i) {
10245       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10246                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10247                                                         PtrVT), Flags);
10248       SDValue L = CLI.DAG.getLoad(
10249           RetTys[i], CLI.DL, CLI.Chain, Add,
10250           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10251                                             DemoteStackIdx, Offsets[i]),
10252           HiddenSRetAlign);
10253       ReturnValues[i] = L;
10254       Chains[i] = L.getValue(1);
10255     }
10256 
10257     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10258   } else {
10259     // Collect the legal value parts into potentially illegal values
10260     // that correspond to the original function's return values.
10261     std::optional<ISD::NodeType> AssertOp;
10262     if (CLI.RetSExt)
10263       AssertOp = ISD::AssertSext;
10264     else if (CLI.RetZExt)
10265       AssertOp = ISD::AssertZext;
10266     unsigned CurReg = 0;
10267     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10268       EVT VT = RetTys[I];
10269       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10270                                                      CLI.CallConv, VT);
10271       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10272                                                        CLI.CallConv, VT);
10273 
10274       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10275                                               NumRegs, RegisterVT, VT, nullptr,
10276                                               CLI.CallConv, AssertOp));
10277       CurReg += NumRegs;
10278     }
10279 
10280     // For a function returning void, there is no return value. We can't create
10281     // such a node, so we just return a null return value in that case. In
10282     // that case, nothing will actually look at the value.
10283     if (ReturnValues.empty())
10284       return std::make_pair(SDValue(), CLI.Chain);
10285   }
10286 
10287   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10288                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10289   return std::make_pair(Res, CLI.Chain);
10290 }
10291 
10292 /// Places new result values for the node in Results (their number
10293 /// and types must exactly match those of the original return values of
10294 /// the node), or leaves Results empty, which indicates that the node is not
10295 /// to be custom lowered after all.
10296 void TargetLowering::LowerOperationWrapper(SDNode *N,
10297                                            SmallVectorImpl<SDValue> &Results,
10298                                            SelectionDAG &DAG) const {
10299   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10300 
10301   if (!Res.getNode())
10302     return;
10303 
10304   // If the original node has one result, take the return value from
10305   // LowerOperation as is. It might not be result number 0.
10306   if (N->getNumValues() == 1) {
10307     Results.push_back(Res);
10308     return;
10309   }
10310 
10311   // If the original node has multiple results, then the return node should
10312   // have the same number of results.
10313   assert((N->getNumValues() == Res->getNumValues()) &&
10314       "Lowering returned the wrong number of results!");
10315 
10316   // Places new result values base on N result number.
10317   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10318     Results.push_back(Res.getValue(I));
10319 }
10320 
10321 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10322   llvm_unreachable("LowerOperation not implemented for this target!");
10323 }
10324 
10325 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10326                                                      unsigned Reg,
10327                                                      ISD::NodeType ExtendType) {
10328   SDValue Op = getNonRegisterValue(V);
10329   assert((Op.getOpcode() != ISD::CopyFromReg ||
10330           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10331          "Copy from a reg to the same reg!");
10332   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10333 
10334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10335   // If this is an InlineAsm we have to match the registers required, not the
10336   // notional registers required by the type.
10337 
10338   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10339                    std::nullopt); // This is not an ABI copy.
10340   SDValue Chain = DAG.getEntryNode();
10341 
10342   if (ExtendType == ISD::ANY_EXTEND) {
10343     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10344     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10345       ExtendType = PreferredExtendIt->second;
10346   }
10347   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10348   PendingExports.push_back(Chain);
10349 }
10350 
10351 #include "llvm/CodeGen/SelectionDAGISel.h"
10352 
10353 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10354 /// entry block, return true.  This includes arguments used by switches, since
10355 /// the switch may expand into multiple basic blocks.
10356 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10357   // With FastISel active, we may be splitting blocks, so force creation
10358   // of virtual registers for all non-dead arguments.
10359   if (FastISel)
10360     return A->use_empty();
10361 
10362   const BasicBlock &Entry = A->getParent()->front();
10363   for (const User *U : A->users())
10364     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10365       return false;  // Use not in entry block.
10366 
10367   return true;
10368 }
10369 
10370 using ArgCopyElisionMapTy =
10371     DenseMap<const Argument *,
10372              std::pair<const AllocaInst *, const StoreInst *>>;
10373 
10374 /// Scan the entry block of the function in FuncInfo for arguments that look
10375 /// like copies into a local alloca. Record any copied arguments in
10376 /// ArgCopyElisionCandidates.
10377 static void
10378 findArgumentCopyElisionCandidates(const DataLayout &DL,
10379                                   FunctionLoweringInfo *FuncInfo,
10380                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10381   // Record the state of every static alloca used in the entry block. Argument
10382   // allocas are all used in the entry block, so we need approximately as many
10383   // entries as we have arguments.
10384   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10385   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10386   unsigned NumArgs = FuncInfo->Fn->arg_size();
10387   StaticAllocas.reserve(NumArgs * 2);
10388 
10389   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10390     if (!V)
10391       return nullptr;
10392     V = V->stripPointerCasts();
10393     const auto *AI = dyn_cast<AllocaInst>(V);
10394     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10395       return nullptr;
10396     auto Iter = StaticAllocas.insert({AI, Unknown});
10397     return &Iter.first->second;
10398   };
10399 
10400   // Look for stores of arguments to static allocas. Look through bitcasts and
10401   // GEPs to handle type coercions, as long as the alloca is fully initialized
10402   // by the store. Any non-store use of an alloca escapes it and any subsequent
10403   // unanalyzed store might write it.
10404   // FIXME: Handle structs initialized with multiple stores.
10405   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10406     // Look for stores, and handle non-store uses conservatively.
10407     const auto *SI = dyn_cast<StoreInst>(&I);
10408     if (!SI) {
10409       // We will look through cast uses, so ignore them completely.
10410       if (I.isCast())
10411         continue;
10412       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10413       // to allocas.
10414       if (I.isDebugOrPseudoInst())
10415         continue;
10416       // This is an unknown instruction. Assume it escapes or writes to all
10417       // static alloca operands.
10418       for (const Use &U : I.operands()) {
10419         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10420           *Info = StaticAllocaInfo::Clobbered;
10421       }
10422       continue;
10423     }
10424 
10425     // If the stored value is a static alloca, mark it as escaped.
10426     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10427       *Info = StaticAllocaInfo::Clobbered;
10428 
10429     // Check if the destination is a static alloca.
10430     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10431     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10432     if (!Info)
10433       continue;
10434     const AllocaInst *AI = cast<AllocaInst>(Dst);
10435 
10436     // Skip allocas that have been initialized or clobbered.
10437     if (*Info != StaticAllocaInfo::Unknown)
10438       continue;
10439 
10440     // Check if the stored value is an argument, and that this store fully
10441     // initializes the alloca.
10442     // If the argument type has padding bits we can't directly forward a pointer
10443     // as the upper bits may contain garbage.
10444     // Don't elide copies from the same argument twice.
10445     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10446     const auto *Arg = dyn_cast<Argument>(Val);
10447     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10448         Arg->getType()->isEmptyTy() ||
10449         DL.getTypeStoreSize(Arg->getType()) !=
10450             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10451         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10452         ArgCopyElisionCandidates.count(Arg)) {
10453       *Info = StaticAllocaInfo::Clobbered;
10454       continue;
10455     }
10456 
10457     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10458                       << '\n');
10459 
10460     // Mark this alloca and store for argument copy elision.
10461     *Info = StaticAllocaInfo::Elidable;
10462     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10463 
10464     // Stop scanning if we've seen all arguments. This will happen early in -O0
10465     // builds, which is useful, because -O0 builds have large entry blocks and
10466     // many allocas.
10467     if (ArgCopyElisionCandidates.size() == NumArgs)
10468       break;
10469   }
10470 }
10471 
10472 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10473 /// ArgVal is a load from a suitable fixed stack object.
10474 static void tryToElideArgumentCopy(
10475     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10476     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10477     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10478     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10479     SDValue ArgVal, bool &ArgHasUses) {
10480   // Check if this is a load from a fixed stack object.
10481   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10482   if (!LNode)
10483     return;
10484   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10485   if (!FINode)
10486     return;
10487 
10488   // Check that the fixed stack object is the right size and alignment.
10489   // Look at the alignment that the user wrote on the alloca instead of looking
10490   // at the stack object.
10491   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10492   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10493   const AllocaInst *AI = ArgCopyIter->second.first;
10494   int FixedIndex = FINode->getIndex();
10495   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10496   int OldIndex = AllocaIndex;
10497   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10498   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10499     LLVM_DEBUG(
10500         dbgs() << "  argument copy elision failed due to bad fixed stack "
10501                   "object size\n");
10502     return;
10503   }
10504   Align RequiredAlignment = AI->getAlign();
10505   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10506     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10507                          "greater than stack argument alignment ("
10508                       << DebugStr(RequiredAlignment) << " vs "
10509                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10510     return;
10511   }
10512 
10513   // Perform the elision. Delete the old stack object and replace its only use
10514   // in the variable info map. Mark the stack object as mutable.
10515   LLVM_DEBUG({
10516     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10517            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10518            << '\n';
10519   });
10520   MFI.RemoveStackObject(OldIndex);
10521   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10522   AllocaIndex = FixedIndex;
10523   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10524   Chains.push_back(ArgVal.getValue(1));
10525 
10526   // Avoid emitting code for the store implementing the copy.
10527   const StoreInst *SI = ArgCopyIter->second.second;
10528   ElidedArgCopyInstrs.insert(SI);
10529 
10530   // Check for uses of the argument again so that we can avoid exporting ArgVal
10531   // if it is't used by anything other than the store.
10532   for (const Value *U : Arg.users()) {
10533     if (U != SI) {
10534       ArgHasUses = true;
10535       break;
10536     }
10537   }
10538 }
10539 
10540 void SelectionDAGISel::LowerArguments(const Function &F) {
10541   SelectionDAG &DAG = SDB->DAG;
10542   SDLoc dl = SDB->getCurSDLoc();
10543   const DataLayout &DL = DAG.getDataLayout();
10544   SmallVector<ISD::InputArg, 16> Ins;
10545 
10546   // In Naked functions we aren't going to save any registers.
10547   if (F.hasFnAttribute(Attribute::Naked))
10548     return;
10549 
10550   if (!FuncInfo->CanLowerReturn) {
10551     // Put in an sret pointer parameter before all the other parameters.
10552     SmallVector<EVT, 1> ValueVTs;
10553     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10554                     F.getReturnType()->getPointerTo(
10555                         DAG.getDataLayout().getAllocaAddrSpace()),
10556                     ValueVTs);
10557 
10558     // NOTE: Assuming that a pointer will never break down to more than one VT
10559     // or one register.
10560     ISD::ArgFlagsTy Flags;
10561     Flags.setSRet();
10562     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10563     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10564                          ISD::InputArg::NoArgIndex, 0);
10565     Ins.push_back(RetArg);
10566   }
10567 
10568   // Look for stores of arguments to static allocas. Mark such arguments with a
10569   // flag to ask the target to give us the memory location of that argument if
10570   // available.
10571   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10572   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10573                                     ArgCopyElisionCandidates);
10574 
10575   // Set up the incoming argument description vector.
10576   for (const Argument &Arg : F.args()) {
10577     unsigned ArgNo = Arg.getArgNo();
10578     SmallVector<EVT, 4> ValueVTs;
10579     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10580     bool isArgValueUsed = !Arg.use_empty();
10581     unsigned PartBase = 0;
10582     Type *FinalType = Arg.getType();
10583     if (Arg.hasAttribute(Attribute::ByVal))
10584       FinalType = Arg.getParamByValType();
10585     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10586         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10587     for (unsigned Value = 0, NumValues = ValueVTs.size();
10588          Value != NumValues; ++Value) {
10589       EVT VT = ValueVTs[Value];
10590       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10591       ISD::ArgFlagsTy Flags;
10592 
10593 
10594       if (Arg.getType()->isPointerTy()) {
10595         Flags.setPointer();
10596         Flags.setPointerAddrSpace(
10597             cast<PointerType>(Arg.getType())->getAddressSpace());
10598       }
10599       if (Arg.hasAttribute(Attribute::ZExt))
10600         Flags.setZExt();
10601       if (Arg.hasAttribute(Attribute::SExt))
10602         Flags.setSExt();
10603       if (Arg.hasAttribute(Attribute::InReg)) {
10604         // If we are using vectorcall calling convention, a structure that is
10605         // passed InReg - is surely an HVA
10606         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10607             isa<StructType>(Arg.getType())) {
10608           // The first value of a structure is marked
10609           if (0 == Value)
10610             Flags.setHvaStart();
10611           Flags.setHva();
10612         }
10613         // Set InReg Flag
10614         Flags.setInReg();
10615       }
10616       if (Arg.hasAttribute(Attribute::StructRet))
10617         Flags.setSRet();
10618       if (Arg.hasAttribute(Attribute::SwiftSelf))
10619         Flags.setSwiftSelf();
10620       if (Arg.hasAttribute(Attribute::SwiftAsync))
10621         Flags.setSwiftAsync();
10622       if (Arg.hasAttribute(Attribute::SwiftError))
10623         Flags.setSwiftError();
10624       if (Arg.hasAttribute(Attribute::ByVal))
10625         Flags.setByVal();
10626       if (Arg.hasAttribute(Attribute::ByRef))
10627         Flags.setByRef();
10628       if (Arg.hasAttribute(Attribute::InAlloca)) {
10629         Flags.setInAlloca();
10630         // Set the byval flag for CCAssignFn callbacks that don't know about
10631         // inalloca.  This way we can know how many bytes we should've allocated
10632         // and how many bytes a callee cleanup function will pop.  If we port
10633         // inalloca to more targets, we'll have to add custom inalloca handling
10634         // in the various CC lowering callbacks.
10635         Flags.setByVal();
10636       }
10637       if (Arg.hasAttribute(Attribute::Preallocated)) {
10638         Flags.setPreallocated();
10639         // Set the byval flag for CCAssignFn callbacks that don't know about
10640         // preallocated.  This way we can know how many bytes we should've
10641         // allocated and how many bytes a callee cleanup function will pop.  If
10642         // we port preallocated to more targets, we'll have to add custom
10643         // preallocated handling in the various CC lowering callbacks.
10644         Flags.setByVal();
10645       }
10646 
10647       // Certain targets (such as MIPS), may have a different ABI alignment
10648       // for a type depending on the context. Give the target a chance to
10649       // specify the alignment it wants.
10650       const Align OriginalAlignment(
10651           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10652       Flags.setOrigAlign(OriginalAlignment);
10653 
10654       Align MemAlign;
10655       Type *ArgMemTy = nullptr;
10656       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10657           Flags.isByRef()) {
10658         if (!ArgMemTy)
10659           ArgMemTy = Arg.getPointeeInMemoryValueType();
10660 
10661         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10662 
10663         // For in-memory arguments, size and alignment should be passed from FE.
10664         // BE will guess if this info is not there but there are cases it cannot
10665         // get right.
10666         if (auto ParamAlign = Arg.getParamStackAlign())
10667           MemAlign = *ParamAlign;
10668         else if ((ParamAlign = Arg.getParamAlign()))
10669           MemAlign = *ParamAlign;
10670         else
10671           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10672         if (Flags.isByRef())
10673           Flags.setByRefSize(MemSize);
10674         else
10675           Flags.setByValSize(MemSize);
10676       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10677         MemAlign = *ParamAlign;
10678       } else {
10679         MemAlign = OriginalAlignment;
10680       }
10681       Flags.setMemAlign(MemAlign);
10682 
10683       if (Arg.hasAttribute(Attribute::Nest))
10684         Flags.setNest();
10685       if (NeedsRegBlock)
10686         Flags.setInConsecutiveRegs();
10687       if (ArgCopyElisionCandidates.count(&Arg))
10688         Flags.setCopyElisionCandidate();
10689       if (Arg.hasAttribute(Attribute::Returned))
10690         Flags.setReturned();
10691 
10692       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10693           *CurDAG->getContext(), F.getCallingConv(), VT);
10694       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10695           *CurDAG->getContext(), F.getCallingConv(), VT);
10696       for (unsigned i = 0; i != NumRegs; ++i) {
10697         // For scalable vectors, use the minimum size; individual targets
10698         // are responsible for handling scalable vector arguments and
10699         // return values.
10700         ISD::InputArg MyFlags(
10701             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
10702             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
10703         if (NumRegs > 1 && i == 0)
10704           MyFlags.Flags.setSplit();
10705         // if it isn't first piece, alignment must be 1
10706         else if (i > 0) {
10707           MyFlags.Flags.setOrigAlign(Align(1));
10708           if (i == NumRegs - 1)
10709             MyFlags.Flags.setSplitEnd();
10710         }
10711         Ins.push_back(MyFlags);
10712       }
10713       if (NeedsRegBlock && Value == NumValues - 1)
10714         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10715       PartBase += VT.getStoreSize().getKnownMinValue();
10716     }
10717   }
10718 
10719   // Call the target to set up the argument values.
10720   SmallVector<SDValue, 8> InVals;
10721   SDValue NewRoot = TLI->LowerFormalArguments(
10722       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10723 
10724   // Verify that the target's LowerFormalArguments behaved as expected.
10725   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10726          "LowerFormalArguments didn't return a valid chain!");
10727   assert(InVals.size() == Ins.size() &&
10728          "LowerFormalArguments didn't emit the correct number of values!");
10729   LLVM_DEBUG({
10730     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10731       assert(InVals[i].getNode() &&
10732              "LowerFormalArguments emitted a null value!");
10733       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10734              "LowerFormalArguments emitted a value with the wrong type!");
10735     }
10736   });
10737 
10738   // Update the DAG with the new chain value resulting from argument lowering.
10739   DAG.setRoot(NewRoot);
10740 
10741   // Set up the argument values.
10742   unsigned i = 0;
10743   if (!FuncInfo->CanLowerReturn) {
10744     // Create a virtual register for the sret pointer, and put in a copy
10745     // from the sret argument into it.
10746     SmallVector<EVT, 1> ValueVTs;
10747     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10748                     F.getReturnType()->getPointerTo(
10749                         DAG.getDataLayout().getAllocaAddrSpace()),
10750                     ValueVTs);
10751     MVT VT = ValueVTs[0].getSimpleVT();
10752     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10753     std::optional<ISD::NodeType> AssertOp;
10754     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10755                                         nullptr, F.getCallingConv(), AssertOp);
10756 
10757     MachineFunction& MF = SDB->DAG.getMachineFunction();
10758     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10759     Register SRetReg =
10760         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10761     FuncInfo->DemoteRegister = SRetReg;
10762     NewRoot =
10763         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10764     DAG.setRoot(NewRoot);
10765 
10766     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10767     ++i;
10768   }
10769 
10770   SmallVector<SDValue, 4> Chains;
10771   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10772   for (const Argument &Arg : F.args()) {
10773     SmallVector<SDValue, 4> ArgValues;
10774     SmallVector<EVT, 4> ValueVTs;
10775     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10776     unsigned NumValues = ValueVTs.size();
10777     if (NumValues == 0)
10778       continue;
10779 
10780     bool ArgHasUses = !Arg.use_empty();
10781 
10782     // Elide the copying store if the target loaded this argument from a
10783     // suitable fixed stack object.
10784     if (Ins[i].Flags.isCopyElisionCandidate()) {
10785       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10786                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10787                              InVals[i], ArgHasUses);
10788     }
10789 
10790     // If this argument is unused then remember its value. It is used to generate
10791     // debugging information.
10792     bool isSwiftErrorArg =
10793         TLI->supportSwiftError() &&
10794         Arg.hasAttribute(Attribute::SwiftError);
10795     if (!ArgHasUses && !isSwiftErrorArg) {
10796       SDB->setUnusedArgValue(&Arg, InVals[i]);
10797 
10798       // Also remember any frame index for use in FastISel.
10799       if (FrameIndexSDNode *FI =
10800           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10801         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10802     }
10803 
10804     for (unsigned Val = 0; Val != NumValues; ++Val) {
10805       EVT VT = ValueVTs[Val];
10806       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10807                                                       F.getCallingConv(), VT);
10808       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10809           *CurDAG->getContext(), F.getCallingConv(), VT);
10810 
10811       // Even an apparent 'unused' swifterror argument needs to be returned. So
10812       // we do generate a copy for it that can be used on return from the
10813       // function.
10814       if (ArgHasUses || isSwiftErrorArg) {
10815         std::optional<ISD::NodeType> AssertOp;
10816         if (Arg.hasAttribute(Attribute::SExt))
10817           AssertOp = ISD::AssertSext;
10818         else if (Arg.hasAttribute(Attribute::ZExt))
10819           AssertOp = ISD::AssertZext;
10820 
10821         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10822                                              PartVT, VT, nullptr,
10823                                              F.getCallingConv(), AssertOp));
10824       }
10825 
10826       i += NumParts;
10827     }
10828 
10829     // We don't need to do anything else for unused arguments.
10830     if (ArgValues.empty())
10831       continue;
10832 
10833     // Note down frame index.
10834     if (FrameIndexSDNode *FI =
10835         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10836       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10837 
10838     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
10839                                      SDB->getCurSDLoc());
10840 
10841     SDB->setValue(&Arg, Res);
10842     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10843       // We want to associate the argument with the frame index, among
10844       // involved operands, that correspond to the lowest address. The
10845       // getCopyFromParts function, called earlier, is swapping the order of
10846       // the operands to BUILD_PAIR depending on endianness. The result of
10847       // that swapping is that the least significant bits of the argument will
10848       // be in the first operand of the BUILD_PAIR node, and the most
10849       // significant bits will be in the second operand.
10850       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10851       if (LoadSDNode *LNode =
10852           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10853         if (FrameIndexSDNode *FI =
10854             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10855           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10856     }
10857 
10858     // Analyses past this point are naive and don't expect an assertion.
10859     if (Res.getOpcode() == ISD::AssertZext)
10860       Res = Res.getOperand(0);
10861 
10862     // Update the SwiftErrorVRegDefMap.
10863     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10864       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10865       if (Register::isVirtualRegister(Reg))
10866         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10867                                    Reg);
10868     }
10869 
10870     // If this argument is live outside of the entry block, insert a copy from
10871     // wherever we got it to the vreg that other BB's will reference it as.
10872     if (Res.getOpcode() == ISD::CopyFromReg) {
10873       // If we can, though, try to skip creating an unnecessary vreg.
10874       // FIXME: This isn't very clean... it would be nice to make this more
10875       // general.
10876       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10877       if (Register::isVirtualRegister(Reg)) {
10878         FuncInfo->ValueMap[&Arg] = Reg;
10879         continue;
10880       }
10881     }
10882     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10883       FuncInfo->InitializeRegForValue(&Arg);
10884       SDB->CopyToExportRegsIfNeeded(&Arg);
10885     }
10886   }
10887 
10888   if (!Chains.empty()) {
10889     Chains.push_back(NewRoot);
10890     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10891   }
10892 
10893   DAG.setRoot(NewRoot);
10894 
10895   assert(i == InVals.size() && "Argument register count mismatch!");
10896 
10897   // If any argument copy elisions occurred and we have debug info, update the
10898   // stale frame indices used in the dbg.declare variable info table.
10899   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10900   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10901     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10902       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10903       if (I != ArgCopyElisionFrameIndexMap.end())
10904         VI.Slot = I->second;
10905     }
10906   }
10907 
10908   // Finally, if the target has anything special to do, allow it to do so.
10909   emitFunctionEntryCode();
10910 }
10911 
10912 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10913 /// ensure constants are generated when needed.  Remember the virtual registers
10914 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10915 /// directly add them, because expansion might result in multiple MBB's for one
10916 /// BB.  As such, the start of the BB might correspond to a different MBB than
10917 /// the end.
10918 void
10919 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10920   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10921 
10922   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10923 
10924   // Check PHI nodes in successors that expect a value to be available from this
10925   // block.
10926   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
10927     if (!isa<PHINode>(SuccBB->begin())) continue;
10928     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10929 
10930     // If this terminator has multiple identical successors (common for
10931     // switches), only handle each succ once.
10932     if (!SuccsHandled.insert(SuccMBB).second)
10933       continue;
10934 
10935     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10936 
10937     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10938     // nodes and Machine PHI nodes, but the incoming operands have not been
10939     // emitted yet.
10940     for (const PHINode &PN : SuccBB->phis()) {
10941       // Ignore dead phi's.
10942       if (PN.use_empty())
10943         continue;
10944 
10945       // Skip empty types
10946       if (PN.getType()->isEmptyTy())
10947         continue;
10948 
10949       unsigned Reg;
10950       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10951 
10952       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
10953         unsigned &RegOut = ConstantsOut[C];
10954         if (RegOut == 0) {
10955           RegOut = FuncInfo.CreateRegs(C);
10956           // We need to zero/sign extend ConstantInt phi operands to match
10957           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
10958           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
10959           if (auto *CI = dyn_cast<ConstantInt>(C))
10960             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
10961                                                     : ISD::ZERO_EXTEND;
10962           CopyValueToVirtualRegister(C, RegOut, ExtendType);
10963         }
10964         Reg = RegOut;
10965       } else {
10966         DenseMap<const Value *, Register>::iterator I =
10967           FuncInfo.ValueMap.find(PHIOp);
10968         if (I != FuncInfo.ValueMap.end())
10969           Reg = I->second;
10970         else {
10971           assert(isa<AllocaInst>(PHIOp) &&
10972                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10973                  "Didn't codegen value into a register!??");
10974           Reg = FuncInfo.CreateRegs(PHIOp);
10975           CopyValueToVirtualRegister(PHIOp, Reg);
10976         }
10977       }
10978 
10979       // Remember that this register needs to added to the machine PHI node as
10980       // the input for this MBB.
10981       SmallVector<EVT, 4> ValueVTs;
10982       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10983       for (EVT VT : ValueVTs) {
10984         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10985         for (unsigned i = 0; i != NumRegisters; ++i)
10986           FuncInfo.PHINodesToUpdate.push_back(
10987               std::make_pair(&*MBBI++, Reg + i));
10988         Reg += NumRegisters;
10989       }
10990     }
10991   }
10992 
10993   ConstantsOut.clear();
10994 }
10995 
10996 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10997   MachineFunction::iterator I(MBB);
10998   if (++I == FuncInfo.MF->end())
10999     return nullptr;
11000   return &*I;
11001 }
11002 
11003 /// During lowering new call nodes can be created (such as memset, etc.).
11004 /// Those will become new roots of the current DAG, but complications arise
11005 /// when they are tail calls. In such cases, the call lowering will update
11006 /// the root, but the builder still needs to know that a tail call has been
11007 /// lowered in order to avoid generating an additional return.
11008 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11009   // If the node is null, we do have a tail call.
11010   if (MaybeTC.getNode() != nullptr)
11011     DAG.setRoot(MaybeTC);
11012   else
11013     HasTailCall = true;
11014 }
11015 
11016 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11017                                         MachineBasicBlock *SwitchMBB,
11018                                         MachineBasicBlock *DefaultMBB) {
11019   MachineFunction *CurMF = FuncInfo.MF;
11020   MachineBasicBlock *NextMBB = nullptr;
11021   MachineFunction::iterator BBI(W.MBB);
11022   if (++BBI != FuncInfo.MF->end())
11023     NextMBB = &*BBI;
11024 
11025   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11026 
11027   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11028 
11029   if (Size == 2 && W.MBB == SwitchMBB) {
11030     // If any two of the cases has the same destination, and if one value
11031     // is the same as the other, but has one bit unset that the other has set,
11032     // use bit manipulation to do two compares at once.  For example:
11033     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11034     // TODO: This could be extended to merge any 2 cases in switches with 3
11035     // cases.
11036     // TODO: Handle cases where W.CaseBB != SwitchBB.
11037     CaseCluster &Small = *W.FirstCluster;
11038     CaseCluster &Big = *W.LastCluster;
11039 
11040     if (Small.Low == Small.High && Big.Low == Big.High &&
11041         Small.MBB == Big.MBB) {
11042       const APInt &SmallValue = Small.Low->getValue();
11043       const APInt &BigValue = Big.Low->getValue();
11044 
11045       // Check that there is only one bit different.
11046       APInt CommonBit = BigValue ^ SmallValue;
11047       if (CommonBit.isPowerOf2()) {
11048         SDValue CondLHS = getValue(Cond);
11049         EVT VT = CondLHS.getValueType();
11050         SDLoc DL = getCurSDLoc();
11051 
11052         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11053                                  DAG.getConstant(CommonBit, DL, VT));
11054         SDValue Cond = DAG.getSetCC(
11055             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11056             ISD::SETEQ);
11057 
11058         // Update successor info.
11059         // Both Small and Big will jump to Small.BB, so we sum up the
11060         // probabilities.
11061         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11062         if (BPI)
11063           addSuccessorWithProb(
11064               SwitchMBB, DefaultMBB,
11065               // The default destination is the first successor in IR.
11066               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11067         else
11068           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11069 
11070         // Insert the true branch.
11071         SDValue BrCond =
11072             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11073                         DAG.getBasicBlock(Small.MBB));
11074         // Insert the false branch.
11075         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11076                              DAG.getBasicBlock(DefaultMBB));
11077 
11078         DAG.setRoot(BrCond);
11079         return;
11080       }
11081     }
11082   }
11083 
11084   if (TM.getOptLevel() != CodeGenOpt::None) {
11085     // Here, we order cases by probability so the most likely case will be
11086     // checked first. However, two clusters can have the same probability in
11087     // which case their relative ordering is non-deterministic. So we use Low
11088     // as a tie-breaker as clusters are guaranteed to never overlap.
11089     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11090                [](const CaseCluster &a, const CaseCluster &b) {
11091       return a.Prob != b.Prob ?
11092              a.Prob > b.Prob :
11093              a.Low->getValue().slt(b.Low->getValue());
11094     });
11095 
11096     // Rearrange the case blocks so that the last one falls through if possible
11097     // without changing the order of probabilities.
11098     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11099       --I;
11100       if (I->Prob > W.LastCluster->Prob)
11101         break;
11102       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11103         std::swap(*I, *W.LastCluster);
11104         break;
11105       }
11106     }
11107   }
11108 
11109   // Compute total probability.
11110   BranchProbability DefaultProb = W.DefaultProb;
11111   BranchProbability UnhandledProbs = DefaultProb;
11112   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11113     UnhandledProbs += I->Prob;
11114 
11115   MachineBasicBlock *CurMBB = W.MBB;
11116   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11117     bool FallthroughUnreachable = false;
11118     MachineBasicBlock *Fallthrough;
11119     if (I == W.LastCluster) {
11120       // For the last cluster, fall through to the default destination.
11121       Fallthrough = DefaultMBB;
11122       FallthroughUnreachable = isa<UnreachableInst>(
11123           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11124     } else {
11125       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11126       CurMF->insert(BBI, Fallthrough);
11127       // Put Cond in a virtual register to make it available from the new blocks.
11128       ExportFromCurrentBlock(Cond);
11129     }
11130     UnhandledProbs -= I->Prob;
11131 
11132     switch (I->Kind) {
11133       case CC_JumpTable: {
11134         // FIXME: Optimize away range check based on pivot comparisons.
11135         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11136         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11137 
11138         // The jump block hasn't been inserted yet; insert it here.
11139         MachineBasicBlock *JumpMBB = JT->MBB;
11140         CurMF->insert(BBI, JumpMBB);
11141 
11142         auto JumpProb = I->Prob;
11143         auto FallthroughProb = UnhandledProbs;
11144 
11145         // If the default statement is a target of the jump table, we evenly
11146         // distribute the default probability to successors of CurMBB. Also
11147         // update the probability on the edge from JumpMBB to Fallthrough.
11148         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11149                                               SE = JumpMBB->succ_end();
11150              SI != SE; ++SI) {
11151           if (*SI == DefaultMBB) {
11152             JumpProb += DefaultProb / 2;
11153             FallthroughProb -= DefaultProb / 2;
11154             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11155             JumpMBB->normalizeSuccProbs();
11156             break;
11157           }
11158         }
11159 
11160         if (FallthroughUnreachable)
11161           JTH->FallthroughUnreachable = true;
11162 
11163         if (!JTH->FallthroughUnreachable)
11164           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11165         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11166         CurMBB->normalizeSuccProbs();
11167 
11168         // The jump table header will be inserted in our current block, do the
11169         // range check, and fall through to our fallthrough block.
11170         JTH->HeaderBB = CurMBB;
11171         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11172 
11173         // If we're in the right place, emit the jump table header right now.
11174         if (CurMBB == SwitchMBB) {
11175           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11176           JTH->Emitted = true;
11177         }
11178         break;
11179       }
11180       case CC_BitTests: {
11181         // FIXME: Optimize away range check based on pivot comparisons.
11182         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11183 
11184         // The bit test blocks haven't been inserted yet; insert them here.
11185         for (BitTestCase &BTC : BTB->Cases)
11186           CurMF->insert(BBI, BTC.ThisBB);
11187 
11188         // Fill in fields of the BitTestBlock.
11189         BTB->Parent = CurMBB;
11190         BTB->Default = Fallthrough;
11191 
11192         BTB->DefaultProb = UnhandledProbs;
11193         // If the cases in bit test don't form a contiguous range, we evenly
11194         // distribute the probability on the edge to Fallthrough to two
11195         // successors of CurMBB.
11196         if (!BTB->ContiguousRange) {
11197           BTB->Prob += DefaultProb / 2;
11198           BTB->DefaultProb -= DefaultProb / 2;
11199         }
11200 
11201         if (FallthroughUnreachable)
11202           BTB->FallthroughUnreachable = true;
11203 
11204         // If we're in the right place, emit the bit test header right now.
11205         if (CurMBB == SwitchMBB) {
11206           visitBitTestHeader(*BTB, SwitchMBB);
11207           BTB->Emitted = true;
11208         }
11209         break;
11210       }
11211       case CC_Range: {
11212         const Value *RHS, *LHS, *MHS;
11213         ISD::CondCode CC;
11214         if (I->Low == I->High) {
11215           // Check Cond == I->Low.
11216           CC = ISD::SETEQ;
11217           LHS = Cond;
11218           RHS=I->Low;
11219           MHS = nullptr;
11220         } else {
11221           // Check I->Low <= Cond <= I->High.
11222           CC = ISD::SETLE;
11223           LHS = I->Low;
11224           MHS = Cond;
11225           RHS = I->High;
11226         }
11227 
11228         // If Fallthrough is unreachable, fold away the comparison.
11229         if (FallthroughUnreachable)
11230           CC = ISD::SETTRUE;
11231 
11232         // The false probability is the sum of all unhandled cases.
11233         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11234                      getCurSDLoc(), I->Prob, UnhandledProbs);
11235 
11236         if (CurMBB == SwitchMBB)
11237           visitSwitchCase(CB, SwitchMBB);
11238         else
11239           SL->SwitchCases.push_back(CB);
11240 
11241         break;
11242       }
11243     }
11244     CurMBB = Fallthrough;
11245   }
11246 }
11247 
11248 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11249                                               CaseClusterIt First,
11250                                               CaseClusterIt Last) {
11251   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11252     if (X.Prob != CC.Prob)
11253       return X.Prob > CC.Prob;
11254 
11255     // Ties are broken by comparing the case value.
11256     return X.Low->getValue().slt(CC.Low->getValue());
11257   });
11258 }
11259 
11260 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11261                                         const SwitchWorkListItem &W,
11262                                         Value *Cond,
11263                                         MachineBasicBlock *SwitchMBB) {
11264   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11265          "Clusters not sorted?");
11266 
11267   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11268 
11269   // Balance the tree based on branch probabilities to create a near-optimal (in
11270   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11271   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11272   CaseClusterIt LastLeft = W.FirstCluster;
11273   CaseClusterIt FirstRight = W.LastCluster;
11274   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11275   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11276 
11277   // Move LastLeft and FirstRight towards each other from opposite directions to
11278   // find a partitioning of the clusters which balances the probability on both
11279   // sides. If LeftProb and RightProb are equal, alternate which side is
11280   // taken to ensure 0-probability nodes are distributed evenly.
11281   unsigned I = 0;
11282   while (LastLeft + 1 < FirstRight) {
11283     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11284       LeftProb += (++LastLeft)->Prob;
11285     else
11286       RightProb += (--FirstRight)->Prob;
11287     I++;
11288   }
11289 
11290   while (true) {
11291     // Our binary search tree differs from a typical BST in that ours can have up
11292     // to three values in each leaf. The pivot selection above doesn't take that
11293     // into account, which means the tree might require more nodes and be less
11294     // efficient. We compensate for this here.
11295 
11296     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11297     unsigned NumRight = W.LastCluster - FirstRight + 1;
11298 
11299     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11300       // If one side has less than 3 clusters, and the other has more than 3,
11301       // consider taking a cluster from the other side.
11302 
11303       if (NumLeft < NumRight) {
11304         // Consider moving the first cluster on the right to the left side.
11305         CaseCluster &CC = *FirstRight;
11306         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11307         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11308         if (LeftSideRank <= RightSideRank) {
11309           // Moving the cluster to the left does not demote it.
11310           ++LastLeft;
11311           ++FirstRight;
11312           continue;
11313         }
11314       } else {
11315         assert(NumRight < NumLeft);
11316         // Consider moving the last element on the left to the right side.
11317         CaseCluster &CC = *LastLeft;
11318         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11319         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11320         if (RightSideRank <= LeftSideRank) {
11321           // Moving the cluster to the right does not demot it.
11322           --LastLeft;
11323           --FirstRight;
11324           continue;
11325         }
11326       }
11327     }
11328     break;
11329   }
11330 
11331   assert(LastLeft + 1 == FirstRight);
11332   assert(LastLeft >= W.FirstCluster);
11333   assert(FirstRight <= W.LastCluster);
11334 
11335   // Use the first element on the right as pivot since we will make less-than
11336   // comparisons against it.
11337   CaseClusterIt PivotCluster = FirstRight;
11338   assert(PivotCluster > W.FirstCluster);
11339   assert(PivotCluster <= W.LastCluster);
11340 
11341   CaseClusterIt FirstLeft = W.FirstCluster;
11342   CaseClusterIt LastRight = W.LastCluster;
11343 
11344   const ConstantInt *Pivot = PivotCluster->Low;
11345 
11346   // New blocks will be inserted immediately after the current one.
11347   MachineFunction::iterator BBI(W.MBB);
11348   ++BBI;
11349 
11350   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11351   // we can branch to its destination directly if it's squeezed exactly in
11352   // between the known lower bound and Pivot - 1.
11353   MachineBasicBlock *LeftMBB;
11354   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11355       FirstLeft->Low == W.GE &&
11356       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11357     LeftMBB = FirstLeft->MBB;
11358   } else {
11359     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11360     FuncInfo.MF->insert(BBI, LeftMBB);
11361     WorkList.push_back(
11362         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11363     // Put Cond in a virtual register to make it available from the new blocks.
11364     ExportFromCurrentBlock(Cond);
11365   }
11366 
11367   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11368   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11369   // directly if RHS.High equals the current upper bound.
11370   MachineBasicBlock *RightMBB;
11371   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11372       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11373     RightMBB = FirstRight->MBB;
11374   } else {
11375     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11376     FuncInfo.MF->insert(BBI, RightMBB);
11377     WorkList.push_back(
11378         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11379     // Put Cond in a virtual register to make it available from the new blocks.
11380     ExportFromCurrentBlock(Cond);
11381   }
11382 
11383   // Create the CaseBlock record that will be used to lower the branch.
11384   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11385                getCurSDLoc(), LeftProb, RightProb);
11386 
11387   if (W.MBB == SwitchMBB)
11388     visitSwitchCase(CB, SwitchMBB);
11389   else
11390     SL->SwitchCases.push_back(CB);
11391 }
11392 
11393 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11394 // from the swith statement.
11395 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11396                                             BranchProbability PeeledCaseProb) {
11397   if (PeeledCaseProb == BranchProbability::getOne())
11398     return BranchProbability::getZero();
11399   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11400 
11401   uint32_t Numerator = CaseProb.getNumerator();
11402   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11403   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11404 }
11405 
11406 // Try to peel the top probability case if it exceeds the threshold.
11407 // Return current MachineBasicBlock for the switch statement if the peeling
11408 // does not occur.
11409 // If the peeling is performed, return the newly created MachineBasicBlock
11410 // for the peeled switch statement. Also update Clusters to remove the peeled
11411 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11412 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11413     const SwitchInst &SI, CaseClusterVector &Clusters,
11414     BranchProbability &PeeledCaseProb) {
11415   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11416   // Don't perform if there is only one cluster or optimizing for size.
11417   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11418       TM.getOptLevel() == CodeGenOpt::None ||
11419       SwitchMBB->getParent()->getFunction().hasMinSize())
11420     return SwitchMBB;
11421 
11422   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11423   unsigned PeeledCaseIndex = 0;
11424   bool SwitchPeeled = false;
11425   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11426     CaseCluster &CC = Clusters[Index];
11427     if (CC.Prob < TopCaseProb)
11428       continue;
11429     TopCaseProb = CC.Prob;
11430     PeeledCaseIndex = Index;
11431     SwitchPeeled = true;
11432   }
11433   if (!SwitchPeeled)
11434     return SwitchMBB;
11435 
11436   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11437                     << TopCaseProb << "\n");
11438 
11439   // Record the MBB for the peeled switch statement.
11440   MachineFunction::iterator BBI(SwitchMBB);
11441   ++BBI;
11442   MachineBasicBlock *PeeledSwitchMBB =
11443       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11444   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11445 
11446   ExportFromCurrentBlock(SI.getCondition());
11447   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11448   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11449                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11450   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11451 
11452   Clusters.erase(PeeledCaseIt);
11453   for (CaseCluster &CC : Clusters) {
11454     LLVM_DEBUG(
11455         dbgs() << "Scale the probablity for one cluster, before scaling: "
11456                << CC.Prob << "\n");
11457     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11458     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11459   }
11460   PeeledCaseProb = TopCaseProb;
11461   return PeeledSwitchMBB;
11462 }
11463 
11464 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11465   // Extract cases from the switch.
11466   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11467   CaseClusterVector Clusters;
11468   Clusters.reserve(SI.getNumCases());
11469   for (auto I : SI.cases()) {
11470     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11471     const ConstantInt *CaseVal = I.getCaseValue();
11472     BranchProbability Prob =
11473         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11474             : BranchProbability(1, SI.getNumCases() + 1);
11475     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11476   }
11477 
11478   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11479 
11480   // Cluster adjacent cases with the same destination. We do this at all
11481   // optimization levels because it's cheap to do and will make codegen faster
11482   // if there are many clusters.
11483   sortAndRangeify(Clusters);
11484 
11485   // The branch probablity of the peeled case.
11486   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11487   MachineBasicBlock *PeeledSwitchMBB =
11488       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11489 
11490   // If there is only the default destination, jump there directly.
11491   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11492   if (Clusters.empty()) {
11493     assert(PeeledSwitchMBB == SwitchMBB);
11494     SwitchMBB->addSuccessor(DefaultMBB);
11495     if (DefaultMBB != NextBlock(SwitchMBB)) {
11496       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11497                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11498     }
11499     return;
11500   }
11501 
11502   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11503   SL->findBitTestClusters(Clusters, &SI);
11504 
11505   LLVM_DEBUG({
11506     dbgs() << "Case clusters: ";
11507     for (const CaseCluster &C : Clusters) {
11508       if (C.Kind == CC_JumpTable)
11509         dbgs() << "JT:";
11510       if (C.Kind == CC_BitTests)
11511         dbgs() << "BT:";
11512 
11513       C.Low->getValue().print(dbgs(), true);
11514       if (C.Low != C.High) {
11515         dbgs() << '-';
11516         C.High->getValue().print(dbgs(), true);
11517       }
11518       dbgs() << ' ';
11519     }
11520     dbgs() << '\n';
11521   });
11522 
11523   assert(!Clusters.empty());
11524   SwitchWorkList WorkList;
11525   CaseClusterIt First = Clusters.begin();
11526   CaseClusterIt Last = Clusters.end() - 1;
11527   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11528   // Scale the branchprobability for DefaultMBB if the peel occurs and
11529   // DefaultMBB is not replaced.
11530   if (PeeledCaseProb != BranchProbability::getZero() &&
11531       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11532     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11533   WorkList.push_back(
11534       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11535 
11536   while (!WorkList.empty()) {
11537     SwitchWorkListItem W = WorkList.pop_back_val();
11538     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11539 
11540     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11541         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11542       // For optimized builds, lower large range as a balanced binary tree.
11543       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11544       continue;
11545     }
11546 
11547     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11548   }
11549 }
11550 
11551 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11552   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11553   auto DL = getCurSDLoc();
11554   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11555   setValue(&I, DAG.getStepVector(DL, ResultVT));
11556 }
11557 
11558 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11559   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11560   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11561 
11562   SDLoc DL = getCurSDLoc();
11563   SDValue V = getValue(I.getOperand(0));
11564   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11565 
11566   if (VT.isScalableVector()) {
11567     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11568     return;
11569   }
11570 
11571   // Use VECTOR_SHUFFLE for the fixed-length vector
11572   // to maintain existing behavior.
11573   SmallVector<int, 8> Mask;
11574   unsigned NumElts = VT.getVectorMinNumElements();
11575   for (unsigned i = 0; i != NumElts; ++i)
11576     Mask.push_back(NumElts - 1 - i);
11577 
11578   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11579 }
11580 
11581 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
11582   auto DL = getCurSDLoc();
11583   SDValue InVec = getValue(I.getOperand(0));
11584   EVT OutVT =
11585       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
11586 
11587   unsigned OutNumElts = OutVT.getVectorMinNumElements();
11588 
11589   // ISD Node needs the input vectors split into two equal parts
11590   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11591                            DAG.getVectorIdxConstant(0, DL));
11592   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11593                            DAG.getVectorIdxConstant(OutNumElts, DL));
11594 
11595   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11596   // legalisation and combines.
11597   if (OutVT.isFixedLengthVector()) {
11598     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11599                                         createStrideMask(0, 2, OutNumElts));
11600     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11601                                        createStrideMask(1, 2, OutNumElts));
11602     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
11603     setValue(&I, Res);
11604     return;
11605   }
11606 
11607   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
11608                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
11609   setValue(&I, Res);
11610 }
11611 
11612 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
11613   auto DL = getCurSDLoc();
11614   EVT InVT = getValue(I.getOperand(0)).getValueType();
11615   SDValue InVec0 = getValue(I.getOperand(0));
11616   SDValue InVec1 = getValue(I.getOperand(1));
11617   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11618   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11619 
11620   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11621   // legalisation and combines.
11622   if (OutVT.isFixedLengthVector()) {
11623     unsigned NumElts = InVT.getVectorMinNumElements();
11624     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
11625     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
11626                                       createInterleaveMask(NumElts, 2)));
11627     return;
11628   }
11629 
11630   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
11631                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
11632   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
11633                     Res.getValue(1));
11634   setValue(&I, Res);
11635 }
11636 
11637 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11638   SmallVector<EVT, 4> ValueVTs;
11639   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11640                   ValueVTs);
11641   unsigned NumValues = ValueVTs.size();
11642   if (NumValues == 0) return;
11643 
11644   SmallVector<SDValue, 4> Values(NumValues);
11645   SDValue Op = getValue(I.getOperand(0));
11646 
11647   for (unsigned i = 0; i != NumValues; ++i)
11648     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11649                             SDValue(Op.getNode(), Op.getResNo() + i));
11650 
11651   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11652                            DAG.getVTList(ValueVTs), Values));
11653 }
11654 
11655 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11657   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11658 
11659   SDLoc DL = getCurSDLoc();
11660   SDValue V1 = getValue(I.getOperand(0));
11661   SDValue V2 = getValue(I.getOperand(1));
11662   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11663 
11664   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11665   if (VT.isScalableVector()) {
11666     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11667     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11668                              DAG.getConstant(Imm, DL, IdxVT)));
11669     return;
11670   }
11671 
11672   unsigned NumElts = VT.getVectorNumElements();
11673 
11674   uint64_t Idx = (NumElts + Imm) % NumElts;
11675 
11676   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11677   SmallVector<int, 8> Mask;
11678   for (unsigned i = 0; i < NumElts; ++i)
11679     Mask.push_back(Idx + i);
11680   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11681 }
11682 
11683 // Consider the following MIR after SelectionDAG, which produces output in
11684 // phyregs in the first case or virtregs in the second case.
11685 //
11686 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
11687 // %5:gr32 = COPY $ebx
11688 // %6:gr32 = COPY $edx
11689 // %1:gr32 = COPY %6:gr32
11690 // %0:gr32 = COPY %5:gr32
11691 //
11692 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
11693 // %1:gr32 = COPY %6:gr32
11694 // %0:gr32 = COPY %5:gr32
11695 //
11696 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
11697 // Given %1, we'd like to return $edx in the first case and %6 in the second.
11698 //
11699 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
11700 // to a single virtreg (such as %0). The remaining outputs monotonically
11701 // increase in virtreg number from there. If a callbr has no outputs, then it
11702 // should not have a corresponding callbr landingpad; in fact, the callbr
11703 // landingpad would not even be able to refer to such a callbr.
11704 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
11705   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
11706   // There is definitely at least one copy.
11707   assert(MI->getOpcode() == TargetOpcode::COPY &&
11708          "start of copy chain MUST be COPY");
11709   Reg = MI->getOperand(1).getReg();
11710   MI = MRI.def_begin(Reg)->getParent();
11711   // There may be an optional second copy.
11712   if (MI->getOpcode() == TargetOpcode::COPY) {
11713     assert(Reg.isVirtual() && "expected COPY of virtual register");
11714     Reg = MI->getOperand(1).getReg();
11715     assert(Reg.isPhysical() && "expected COPY of physical register");
11716     MI = MRI.def_begin(Reg)->getParent();
11717   }
11718   // The start of the chain must be an INLINEASM_BR.
11719   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
11720          "end of copy chain MUST be INLINEASM_BR");
11721   return Reg;
11722 }
11723 
11724 // We must do this walk rather than the simpler
11725 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
11726 // otherwise we will end up with copies of virtregs only valid along direct
11727 // edges.
11728 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
11729   SmallVector<EVT, 8> ResultVTs;
11730   SmallVector<SDValue, 8> ResultValues;
11731   const auto *CBR =
11732       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
11733 
11734   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11735   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
11736   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11737 
11738   unsigned InitialDef = FuncInfo.ValueMap[CBR];
11739   SDValue Chain = DAG.getRoot();
11740 
11741   // Re-parse the asm constraints string.
11742   TargetLowering::AsmOperandInfoVector TargetConstraints =
11743       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
11744   for (auto &T : TargetConstraints) {
11745     SDISelAsmOperandInfo OpInfo(T);
11746     if (OpInfo.Type != InlineAsm::isOutput)
11747       continue;
11748 
11749     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
11750     // individual constraint.
11751     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
11752 
11753     switch (OpInfo.ConstraintType) {
11754     case TargetLowering::C_Register:
11755     case TargetLowering::C_RegisterClass: {
11756       // Fill in OpInfo.AssignedRegs.Regs.
11757       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
11758 
11759       // getRegistersForValue may produce 1 to many registers based on whether
11760       // the OpInfo.ConstraintVT is legal on the target or not.
11761       for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) {
11762         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
11763         if (Register::isPhysicalRegister(OriginalDef))
11764           FuncInfo.MBB->addLiveIn(OriginalDef);
11765         // Update the assigned registers to use the original defs.
11766         OpInfo.AssignedRegs.Regs[i] = OriginalDef;
11767       }
11768 
11769       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
11770           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
11771       ResultValues.push_back(V);
11772       ResultVTs.push_back(OpInfo.ConstraintVT);
11773       break;
11774     }
11775     case TargetLowering::C_Other: {
11776       SDValue Flag;
11777       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
11778                                                   OpInfo, DAG);
11779       ++InitialDef;
11780       ResultValues.push_back(V);
11781       ResultVTs.push_back(OpInfo.ConstraintVT);
11782       break;
11783     }
11784     default:
11785       break;
11786     }
11787   }
11788   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11789                           DAG.getVTList(ResultVTs), ResultValues);
11790   setValue(&I, V);
11791 }
11792