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