xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision ea32197daa8517ff67c0691ad24d25eb5cf905f4)
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/TargetTransformInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Analysis/VectorUtils.h"
32 #include "llvm/CodeGen/Analysis.h"
33 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
34 #include "llvm/CodeGen/CodeGenCommonISel.h"
35 #include "llvm/CodeGen/FunctionLoweringInfo.h"
36 #include "llvm/CodeGen/GCMetadata.h"
37 #include "llvm/CodeGen/ISDOpcodes.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
43 #include "llvm/CodeGen/MachineMemOperand.h"
44 #include "llvm/CodeGen/MachineModuleInfo.h"
45 #include "llvm/CodeGen/MachineOperand.h"
46 #include "llvm/CodeGen/MachineRegisterInfo.h"
47 #include "llvm/CodeGen/RuntimeLibcalls.h"
48 #include "llvm/CodeGen/SelectionDAG.h"
49 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
50 #include "llvm/CodeGen/StackMaps.h"
51 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
52 #include "llvm/CodeGen/TargetFrameLowering.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetOpcodes.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/TargetSubtargetInfo.h"
57 #include "llvm/CodeGen/WinEHFuncInfo.h"
58 #include "llvm/IR/Argument.h"
59 #include "llvm/IR/Attributes.h"
60 #include "llvm/IR/BasicBlock.h"
61 #include "llvm/IR/CFG.h"
62 #include "llvm/IR/CallingConv.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/ConstantRange.h"
65 #include "llvm/IR/Constants.h"
66 #include "llvm/IR/DataLayout.h"
67 #include "llvm/IR/DebugInfo.h"
68 #include "llvm/IR/DebugInfoMetadata.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/DiagnosticInfo.h"
71 #include "llvm/IR/EHPersonalities.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/GetElementPtrTypeIterator.h"
74 #include "llvm/IR/InlineAsm.h"
75 #include "llvm/IR/InstrTypes.h"
76 #include "llvm/IR/Instructions.h"
77 #include "llvm/IR/IntrinsicInst.h"
78 #include "llvm/IR/Intrinsics.h"
79 #include "llvm/IR/IntrinsicsAArch64.h"
80 #include "llvm/IR/IntrinsicsAMDGPU.h"
81 #include "llvm/IR/IntrinsicsWebAssembly.h"
82 #include "llvm/IR/LLVMContext.h"
83 #include "llvm/IR/MemoryModelRelaxationAnnotations.h"
84 #include "llvm/IR/Metadata.h"
85 #include "llvm/IR/Module.h"
86 #include "llvm/IR/Operator.h"
87 #include "llvm/IR/PatternMatch.h"
88 #include "llvm/IR/Statepoint.h"
89 #include "llvm/IR/Type.h"
90 #include "llvm/IR/User.h"
91 #include "llvm/IR/Value.h"
92 #include "llvm/MC/MCContext.h"
93 #include "llvm/Support/AtomicOrdering.h"
94 #include "llvm/Support/Casting.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/InstructionCost.h"
99 #include "llvm/Support/MathExtras.h"
100 #include "llvm/Support/raw_ostream.h"
101 #include "llvm/Target/TargetIntrinsicInfo.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.h"
104 #include "llvm/TargetParser/Triple.h"
105 #include "llvm/Transforms/Utils/Local.h"
106 #include <cstddef>
107 #include <iterator>
108 #include <limits>
109 #include <optional>
110 #include <tuple>
111 
112 using namespace llvm;
113 using namespace PatternMatch;
114 using namespace SwitchCG;
115 
116 #define DEBUG_TYPE "isel"
117 
118 /// LimitFloatPrecision - Generate low-precision inline sequences for
119 /// some float libcalls (6, 8 or 12 bits).
120 static unsigned LimitFloatPrecision;
121 
122 static cl::opt<bool>
123     InsertAssertAlign("insert-assert-align", cl::init(true),
124                       cl::desc("Insert the experimental `assertalign` node."),
125                       cl::ReallyHidden);
126 
127 static cl::opt<unsigned, true>
128     LimitFPPrecision("limit-float-precision",
129                      cl::desc("Generate low-precision inline sequences "
130                               "for some float libcalls"),
131                      cl::location(LimitFloatPrecision), cl::Hidden,
132                      cl::init(0));
133 
134 static cl::opt<unsigned> SwitchPeelThreshold(
135     "switch-peel-threshold", cl::Hidden, cl::init(66),
136     cl::desc("Set the case probability threshold for peeling the case from a "
137              "switch statement. A value greater than 100 will void this "
138              "optimization"));
139 
140 // Limit the width of DAG chains. This is important in general to prevent
141 // DAG-based analysis from blowing up. For example, alias analysis and
142 // load clustering may not complete in reasonable time. It is difficult to
143 // recognize and avoid this situation within each individual analysis, and
144 // future analyses are likely to have the same behavior. Limiting DAG width is
145 // the safe approach and will be especially important with global DAGs.
146 //
147 // MaxParallelChains default is arbitrarily high to avoid affecting
148 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
149 // sequence over this should have been converted to llvm.memcpy by the
150 // frontend. It is easy to induce this behavior with .ll code such as:
151 // %buffer = alloca [4096 x i8]
152 // %data = load [4096 x i8]* %argPtr
153 // store [4096 x i8] %data, [4096 x i8]* %buffer
154 static const unsigned MaxParallelChains = 64;
155 
156 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
157                                       const SDValue *Parts, unsigned NumParts,
158                                       MVT PartVT, EVT ValueVT, const Value *V,
159                                       SDValue InChain,
160                                       std::optional<CallingConv::ID> CC);
161 
162 /// getCopyFromParts - Create a value that contains the specified legal parts
163 /// combined into the value they represent.  If the parts combine to a type
164 /// larger than ValueVT then AssertOp can be used to specify whether the extra
165 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
166 /// (ISD::AssertSext).
167 static SDValue
168 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
169                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
170                  SDValue InChain,
171                  std::optional<CallingConv::ID> CC = std::nullopt,
172                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
173   // Let the target assemble the parts if it wants to
174   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
175   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
176                                                    PartVT, ValueVT, CC))
177     return Val;
178 
179   if (ValueVT.isVector())
180     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
181                                   InChain, CC);
182 
183   assert(NumParts > 0 && "No parts to assemble!");
184   SDValue Val = Parts[0];
185 
186   if (NumParts > 1) {
187     // Assemble the value from multiple parts.
188     if (ValueVT.isInteger()) {
189       unsigned PartBits = PartVT.getSizeInBits();
190       unsigned ValueBits = ValueVT.getSizeInBits();
191 
192       // Assemble the power of 2 part.
193       unsigned RoundParts = llvm::bit_floor(NumParts);
194       unsigned RoundBits = PartBits * RoundParts;
195       EVT RoundVT = RoundBits == ValueBits ?
196         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
197       SDValue Lo, Hi;
198 
199       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
200 
201       if (RoundParts > 2) {
202         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
203                               InChain);
204         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
205                               PartVT, HalfVT, V, InChain);
206       } else {
207         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
208         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
209       }
210 
211       if (DAG.getDataLayout().isBigEndian())
212         std::swap(Lo, Hi);
213 
214       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
215 
216       if (RoundParts < NumParts) {
217         // Assemble the trailing non-power-of-2 part.
218         unsigned OddParts = NumParts - RoundParts;
219         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
220         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
221                               OddVT, V, InChain, CC);
222 
223         // Combine the round and odd parts.
224         Lo = Val;
225         if (DAG.getDataLayout().isBigEndian())
226           std::swap(Lo, Hi);
227         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
228         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
229         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
230                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
231                                          TLI.getShiftAmountTy(
232                                              TotalVT, DAG.getDataLayout())));
233         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
234         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
235       }
236     } else if (PartVT.isFloatingPoint()) {
237       // FP split into multiple FP parts (for ppcf128)
238       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
239              "Unexpected split");
240       SDValue Lo, Hi;
241       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
242       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
243       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
244         std::swap(Lo, Hi);
245       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
246     } else {
247       // FP split into integer parts (soft fp)
248       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
249              !PartVT.isVector() && "Unexpected split");
250       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
251       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
252                              InChain, CC);
253     }
254   }
255 
256   // There is now one part, held in Val.  Correct it to match ValueVT.
257   // PartEVT is the type of the register class that holds the value.
258   // ValueVT is the type of the inline asm operation.
259   EVT PartEVT = Val.getValueType();
260 
261   if (PartEVT == ValueVT)
262     return Val;
263 
264   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
265       ValueVT.bitsLT(PartEVT)) {
266     // For an FP value in an integer part, we need to truncate to the right
267     // width first.
268     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
269     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
270   }
271 
272   // Handle types that have the same size.
273   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
274     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
275 
276   // Handle types with different sizes.
277   if (PartEVT.isInteger() && ValueVT.isInteger()) {
278     if (ValueVT.bitsLT(PartEVT)) {
279       // For a truncate, see if we have any information to
280       // indicate whether the truncated bits will always be
281       // zero or sign-extension.
282       if (AssertOp)
283         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
284                           DAG.getValueType(ValueVT));
285       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
286     }
287     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
288   }
289 
290   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
291     // FP_ROUND's are always exact here.
292     if (ValueVT.bitsLT(Val.getValueType())) {
293 
294       SDValue NoChange =
295           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
296 
297       if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
298               llvm::Attribute::StrictFP)) {
299         return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
300                            DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
301                            NoChange);
302       }
303 
304       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
305     }
306 
307     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
308   }
309 
310   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
311   // then truncating.
312   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
313       ValueVT.bitsLT(PartEVT)) {
314     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
315     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
316   }
317 
318   report_fatal_error("Unknown mismatch in getCopyFromParts!");
319 }
320 
321 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
322                                               const Twine &ErrMsg) {
323   const Instruction *I = dyn_cast_or_null<Instruction>(V);
324   if (!V)
325     return Ctx.emitError(ErrMsg);
326 
327   const char *AsmError = ", possible invalid constraint for vector type";
328   if (const CallInst *CI = dyn_cast<CallInst>(I))
329     if (CI->isInlineAsm())
330       return Ctx.emitError(I, ErrMsg + AsmError);
331 
332   return Ctx.emitError(I, ErrMsg);
333 }
334 
335 /// getCopyFromPartsVector - Create a value that contains the specified legal
336 /// parts combined into the value they represent.  If the parts combine to a
337 /// type larger than ValueVT then AssertOp can be used to specify whether the
338 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
339 /// ValueVT (ISD::AssertSext).
340 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
341                                       const SDValue *Parts, unsigned NumParts,
342                                       MVT PartVT, EVT ValueVT, const Value *V,
343                                       SDValue InChain,
344                                       std::optional<CallingConv::ID> CallConv) {
345   assert(ValueVT.isVector() && "Not a vector value");
346   assert(NumParts > 0 && "No parts to assemble!");
347   const bool IsABIRegCopy = CallConv.has_value();
348 
349   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
350   SDValue Val = Parts[0];
351 
352   // Handle a multi-element vector.
353   if (NumParts > 1) {
354     EVT IntermediateVT;
355     MVT RegisterVT;
356     unsigned NumIntermediates;
357     unsigned NumRegs;
358 
359     if (IsABIRegCopy) {
360       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
361           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
362           NumIntermediates, RegisterVT);
363     } else {
364       NumRegs =
365           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
366                                      NumIntermediates, RegisterVT);
367     }
368 
369     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
370     NumParts = NumRegs; // Silence a compiler warning.
371     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
372     assert(RegisterVT.getSizeInBits() ==
373            Parts[0].getSimpleValueType().getSizeInBits() &&
374            "Part type sizes don't match!");
375 
376     // Assemble the parts into intermediate operands.
377     SmallVector<SDValue, 8> Ops(NumIntermediates);
378     if (NumIntermediates == NumParts) {
379       // If the register was not expanded, truncate or copy the value,
380       // as appropriate.
381       for (unsigned i = 0; i != NumParts; ++i)
382         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
383                                   V, InChain, CallConv);
384     } else if (NumParts > 0) {
385       // If the intermediate type was expanded, build the intermediate
386       // operands from the parts.
387       assert(NumParts % NumIntermediates == 0 &&
388              "Must expand into a divisible number of parts!");
389       unsigned Factor = NumParts / NumIntermediates;
390       for (unsigned i = 0; i != NumIntermediates; ++i)
391         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
392                                   IntermediateVT, V, InChain, CallConv);
393     }
394 
395     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
396     // intermediate operands.
397     EVT BuiltVectorTy =
398         IntermediateVT.isVector()
399             ? EVT::getVectorVT(
400                   *DAG.getContext(), IntermediateVT.getScalarType(),
401                   IntermediateVT.getVectorElementCount() * NumParts)
402             : EVT::getVectorVT(*DAG.getContext(),
403                                IntermediateVT.getScalarType(),
404                                NumIntermediates);
405     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
406                                                 : ISD::BUILD_VECTOR,
407                       DL, BuiltVectorTy, Ops);
408   }
409 
410   // There is now one part, held in Val.  Correct it to match ValueVT.
411   EVT PartEVT = Val.getValueType();
412 
413   if (PartEVT == ValueVT)
414     return Val;
415 
416   if (PartEVT.isVector()) {
417     // Vector/Vector bitcast.
418     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
419       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
420 
421     // If the parts vector has more elements than the value vector, then we
422     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
423     // Extract the elements we want.
424     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
425       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
426               ValueVT.getVectorElementCount().getKnownMinValue()) &&
427              (PartEVT.getVectorElementCount().isScalable() ==
428               ValueVT.getVectorElementCount().isScalable()) &&
429              "Cannot narrow, it would be a lossy transformation");
430       PartEVT =
431           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
432                            ValueVT.getVectorElementCount());
433       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
434                         DAG.getVectorIdxConstant(0, DL));
435       if (PartEVT == ValueVT)
436         return Val;
437       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
438         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
439 
440       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
441       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
442         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
443     }
444 
445     // Promoted vector extract
446     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
447   }
448 
449   // Trivial bitcast if the types are the same size and the destination
450   // vector type is legal.
451   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
452       TLI.isTypeLegal(ValueVT))
453     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
454 
455   if (ValueVT.getVectorNumElements() != 1) {
456      // Certain ABIs require that vectors are passed as integers. For vectors
457      // are the same size, this is an obvious bitcast.
458      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
459        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
460      } else if (ValueVT.bitsLT(PartEVT)) {
461        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
462        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
463        // Drop the extra bits.
464        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
465        return DAG.getBitcast(ValueVT, Val);
466      }
467 
468      diagnosePossiblyInvalidConstraint(
469          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
470      return DAG.getUNDEF(ValueVT);
471   }
472 
473   // Handle cases such as i8 -> <1 x i1>
474   EVT ValueSVT = ValueVT.getVectorElementType();
475   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
476     unsigned ValueSize = ValueSVT.getSizeInBits();
477     if (ValueSize == PartEVT.getSizeInBits()) {
478       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
479     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
480       // It's possible a scalar floating point type gets softened to integer and
481       // then promoted to a larger integer. If PartEVT is the larger integer
482       // we need to truncate it and then bitcast to the FP type.
483       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
484       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
485       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
486       Val = DAG.getBitcast(ValueSVT, Val);
487     } else {
488       Val = ValueVT.isFloatingPoint()
489                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
490                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
491     }
492   }
493 
494   return DAG.getBuildVector(ValueVT, DL, Val);
495 }
496 
497 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
498                                  SDValue Val, SDValue *Parts, unsigned NumParts,
499                                  MVT PartVT, const Value *V,
500                                  std::optional<CallingConv::ID> CallConv);
501 
502 /// getCopyToParts - Create a series of nodes that contain the specified value
503 /// split into legal parts.  If the parts contain more bits than Val, then, for
504 /// integers, ExtendKind can be used to specify how to generate the extra bits.
505 static void
506 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
507                unsigned NumParts, MVT PartVT, const Value *V,
508                std::optional<CallingConv::ID> CallConv = std::nullopt,
509                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
510   // Let the target split the parts if it wants to
511   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
512   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
513                                       CallConv))
514     return;
515   EVT ValueVT = Val.getValueType();
516 
517   // Handle the vector case separately.
518   if (ValueVT.isVector())
519     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
520                                 CallConv);
521 
522   unsigned OrigNumParts = NumParts;
523   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
524          "Copying to an illegal type!");
525 
526   if (NumParts == 0)
527     return;
528 
529   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
530   EVT PartEVT = PartVT;
531   if (PartEVT == ValueVT) {
532     assert(NumParts == 1 && "No-op copy with multiple parts!");
533     Parts[0] = Val;
534     return;
535   }
536 
537   unsigned PartBits = PartVT.getSizeInBits();
538   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
539     // If the parts cover more bits than the value has, promote the value.
540     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
541       assert(NumParts == 1 && "Do not know what to promote to!");
542       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
543     } else {
544       if (ValueVT.isFloatingPoint()) {
545         // FP values need to be bitcast, then extended if they are being put
546         // into a larger container.
547         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
548         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
549       }
550       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
551              ValueVT.isInteger() &&
552              "Unknown mismatch!");
553       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
554       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
555       if (PartVT == MVT::x86mmx)
556         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
557     }
558   } else if (PartBits == ValueVT.getSizeInBits()) {
559     // Different types of the same size.
560     assert(NumParts == 1 && PartEVT != ValueVT);
561     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
562   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
563     // If the parts cover less bits than value has, truncate the value.
564     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
565            ValueVT.isInteger() &&
566            "Unknown mismatch!");
567     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
568     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
569     if (PartVT == MVT::x86mmx)
570       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
571   }
572 
573   // The value may have changed - recompute ValueVT.
574   ValueVT = Val.getValueType();
575   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
576          "Failed to tile the value with PartVT!");
577 
578   if (NumParts == 1) {
579     if (PartEVT != ValueVT) {
580       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
581                                         "scalar-to-vector conversion failed");
582       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
583     }
584 
585     Parts[0] = Val;
586     return;
587   }
588 
589   // Expand the value into multiple parts.
590   if (NumParts & (NumParts - 1)) {
591     // The number of parts is not a power of 2.  Split off and copy the tail.
592     assert(PartVT.isInteger() && ValueVT.isInteger() &&
593            "Do not know what to expand to!");
594     unsigned RoundParts = llvm::bit_floor(NumParts);
595     unsigned RoundBits = RoundParts * PartBits;
596     unsigned OddParts = NumParts - RoundParts;
597     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
598       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
599 
600     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
601                    CallConv);
602 
603     if (DAG.getDataLayout().isBigEndian())
604       // The odd parts were reversed by getCopyToParts - unreverse them.
605       std::reverse(Parts + RoundParts, Parts + NumParts);
606 
607     NumParts = RoundParts;
608     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
609     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
610   }
611 
612   // The number of parts is a power of 2.  Repeatedly bisect the value using
613   // EXTRACT_ELEMENT.
614   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
615                          EVT::getIntegerVT(*DAG.getContext(),
616                                            ValueVT.getSizeInBits()),
617                          Val);
618 
619   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
620     for (unsigned i = 0; i < NumParts; i += StepSize) {
621       unsigned ThisBits = StepSize * PartBits / 2;
622       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
623       SDValue &Part0 = Parts[i];
624       SDValue &Part1 = Parts[i+StepSize/2];
625 
626       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
627                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
628       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
629                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
630 
631       if (ThisBits == PartBits && ThisVT != PartVT) {
632         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
633         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
634       }
635     }
636   }
637 
638   if (DAG.getDataLayout().isBigEndian())
639     std::reverse(Parts, Parts + OrigNumParts);
640 }
641 
642 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
643                                      const SDLoc &DL, EVT PartVT) {
644   if (!PartVT.isVector())
645     return SDValue();
646 
647   EVT ValueVT = Val.getValueType();
648   EVT PartEVT = PartVT.getVectorElementType();
649   EVT ValueEVT = ValueVT.getVectorElementType();
650   ElementCount PartNumElts = PartVT.getVectorElementCount();
651   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
652 
653   // We only support widening vectors with equivalent element types and
654   // fixed/scalable properties. If a target needs to widen a fixed-length type
655   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
656   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
657       PartNumElts.isScalable() != ValueNumElts.isScalable())
658     return SDValue();
659 
660   // Have a try for bf16 because some targets share its ABI with fp16.
661   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
662     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
663            "Cannot widen to illegal type");
664     Val = DAG.getNode(ISD::BITCAST, DL,
665                       ValueVT.changeVectorElementType(MVT::f16), Val);
666   } else if (PartEVT != ValueEVT) {
667     return SDValue();
668   }
669 
670   // Widening a scalable vector to another scalable vector is done by inserting
671   // the vector into a larger undef one.
672   if (PartNumElts.isScalable())
673     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
674                        Val, DAG.getVectorIdxConstant(0, DL));
675 
676   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
677   // undef elements.
678   SmallVector<SDValue, 16> Ops;
679   DAG.ExtractVectorElements(Val, Ops);
680   SDValue EltUndef = DAG.getUNDEF(PartEVT);
681   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
682 
683   // FIXME: Use CONCAT for 2x -> 4x.
684   return DAG.getBuildVector(PartVT, DL, Ops);
685 }
686 
687 /// getCopyToPartsVector - Create a series of nodes that contain the specified
688 /// value split into legal parts.
689 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
690                                  SDValue Val, SDValue *Parts, unsigned NumParts,
691                                  MVT PartVT, const Value *V,
692                                  std::optional<CallingConv::ID> CallConv) {
693   EVT ValueVT = Val.getValueType();
694   assert(ValueVT.isVector() && "Not a vector");
695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
696   const bool IsABIRegCopy = CallConv.has_value();
697 
698   if (NumParts == 1) {
699     EVT PartEVT = PartVT;
700     if (PartEVT == ValueVT) {
701       // Nothing to do.
702     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
703       // Bitconvert vector->vector case.
704       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
705     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
706       Val = Widened;
707     } else if (PartVT.isVector() &&
708                PartEVT.getVectorElementType().bitsGE(
709                    ValueVT.getVectorElementType()) &&
710                PartEVT.getVectorElementCount() ==
711                    ValueVT.getVectorElementCount()) {
712 
713       // Promoted vector extract
714       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
715     } else if (PartEVT.isVector() &&
716                PartEVT.getVectorElementType() !=
717                    ValueVT.getVectorElementType() &&
718                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
719                    TargetLowering::TypeWidenVector) {
720       // Combination of widening and promotion.
721       EVT WidenVT =
722           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
723                            PartVT.getVectorElementCount());
724       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
725       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
726     } else {
727       // Don't extract an integer from a float vector. This can happen if the
728       // FP type gets softened to integer and then promoted. The promotion
729       // prevents it from being picked up by the earlier bitcast case.
730       if (ValueVT.getVectorElementCount().isScalar() &&
731           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
732         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
733                           DAG.getVectorIdxConstant(0, DL));
734       } else {
735         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
736         assert(PartVT.getFixedSizeInBits() > ValueSize &&
737                "lossy conversion of vector to scalar type");
738         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
739         Val = DAG.getBitcast(IntermediateType, Val);
740         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
741       }
742     }
743 
744     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
745     Parts[0] = Val;
746     return;
747   }
748 
749   // Handle a multi-element vector.
750   EVT IntermediateVT;
751   MVT RegisterVT;
752   unsigned NumIntermediates;
753   unsigned NumRegs;
754   if (IsABIRegCopy) {
755     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
756         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
757         RegisterVT);
758   } else {
759     NumRegs =
760         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
761                                    NumIntermediates, RegisterVT);
762   }
763 
764   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
765   NumParts = NumRegs; // Silence a compiler warning.
766   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
767 
768   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
769          "Mixing scalable and fixed vectors when copying in parts");
770 
771   std::optional<ElementCount> DestEltCnt;
772 
773   if (IntermediateVT.isVector())
774     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
775   else
776     DestEltCnt = ElementCount::getFixed(NumIntermediates);
777 
778   EVT BuiltVectorTy = EVT::getVectorVT(
779       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
780 
781   if (ValueVT == BuiltVectorTy) {
782     // Nothing to do.
783   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
784     // Bitconvert vector->vector case.
785     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
786   } else {
787     if (BuiltVectorTy.getVectorElementType().bitsGT(
788             ValueVT.getVectorElementType())) {
789       // Integer promotion.
790       ValueVT = EVT::getVectorVT(*DAG.getContext(),
791                                  BuiltVectorTy.getVectorElementType(),
792                                  ValueVT.getVectorElementCount());
793       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
794     }
795 
796     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
797       Val = Widened;
798     }
799   }
800 
801   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
802 
803   // Split the vector into intermediate operands.
804   SmallVector<SDValue, 8> Ops(NumIntermediates);
805   for (unsigned i = 0; i != NumIntermediates; ++i) {
806     if (IntermediateVT.isVector()) {
807       // This does something sensible for scalable vectors - see the
808       // definition of EXTRACT_SUBVECTOR for further details.
809       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
810       Ops[i] =
811           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
812                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
813     } else {
814       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
815                            DAG.getVectorIdxConstant(i, DL));
816     }
817   }
818 
819   // Split the intermediate operands into legal parts.
820   if (NumParts == NumIntermediates) {
821     // If the register was not expanded, promote or copy the value,
822     // as appropriate.
823     for (unsigned i = 0; i != NumParts; ++i)
824       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
825   } else if (NumParts > 0) {
826     // If the intermediate type was expanded, split each the value into
827     // legal parts.
828     assert(NumIntermediates != 0 && "division by zero");
829     assert(NumParts % NumIntermediates == 0 &&
830            "Must expand into a divisible number of parts!");
831     unsigned Factor = NumParts / NumIntermediates;
832     for (unsigned i = 0; i != NumIntermediates; ++i)
833       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
834                      CallConv);
835   }
836 }
837 
838 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
839                            EVT valuevt, std::optional<CallingConv::ID> CC)
840     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
841       RegCount(1, regs.size()), CallConv(CC) {}
842 
843 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
844                            const DataLayout &DL, unsigned Reg, Type *Ty,
845                            std::optional<CallingConv::ID> CC) {
846   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
847 
848   CallConv = CC;
849 
850   for (EVT ValueVT : ValueVTs) {
851     unsigned NumRegs =
852         isABIMangled()
853             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
854             : TLI.getNumRegisters(Context, ValueVT);
855     MVT RegisterVT =
856         isABIMangled()
857             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
858             : TLI.getRegisterType(Context, ValueVT);
859     for (unsigned i = 0; i != NumRegs; ++i)
860       Regs.push_back(Reg + i);
861     RegVTs.push_back(RegisterVT);
862     RegCount.push_back(NumRegs);
863     Reg += NumRegs;
864   }
865 }
866 
867 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
868                                       FunctionLoweringInfo &FuncInfo,
869                                       const SDLoc &dl, SDValue &Chain,
870                                       SDValue *Glue, const Value *V) const {
871   // A Value with type {} or [0 x %t] needs no registers.
872   if (ValueVTs.empty())
873     return SDValue();
874 
875   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
876 
877   // Assemble the legal parts into the final values.
878   SmallVector<SDValue, 4> Values(ValueVTs.size());
879   SmallVector<SDValue, 8> Parts;
880   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
881     // Copy the legal parts from the registers.
882     EVT ValueVT = ValueVTs[Value];
883     unsigned NumRegs = RegCount[Value];
884     MVT RegisterVT = isABIMangled()
885                          ? TLI.getRegisterTypeForCallingConv(
886                                *DAG.getContext(), *CallConv, RegVTs[Value])
887                          : RegVTs[Value];
888 
889     Parts.resize(NumRegs);
890     for (unsigned i = 0; i != NumRegs; ++i) {
891       SDValue P;
892       if (!Glue) {
893         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
894       } else {
895         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
896         *Glue = P.getValue(2);
897       }
898 
899       Chain = P.getValue(1);
900       Parts[i] = P;
901 
902       // If the source register was virtual and if we know something about it,
903       // add an assert node.
904       if (!Register::isVirtualRegister(Regs[Part + i]) ||
905           !RegisterVT.isInteger())
906         continue;
907 
908       const FunctionLoweringInfo::LiveOutInfo *LOI =
909         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
910       if (!LOI)
911         continue;
912 
913       unsigned RegSize = RegisterVT.getScalarSizeInBits();
914       unsigned NumSignBits = LOI->NumSignBits;
915       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
916 
917       if (NumZeroBits == RegSize) {
918         // The current value is a zero.
919         // Explicitly express that as it would be easier for
920         // optimizations to kick in.
921         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
922         continue;
923       }
924 
925       // FIXME: We capture more information than the dag can represent.  For
926       // now, just use the tightest assertzext/assertsext possible.
927       bool isSExt;
928       EVT FromVT(MVT::Other);
929       if (NumZeroBits) {
930         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
931         isSExt = false;
932       } else if (NumSignBits > 1) {
933         FromVT =
934             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
935         isSExt = true;
936       } else {
937         continue;
938       }
939       // Add an assertion node.
940       assert(FromVT != MVT::Other);
941       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
942                              RegisterVT, P, DAG.getValueType(FromVT));
943     }
944 
945     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
946                                      RegisterVT, ValueVT, V, Chain, CallConv);
947     Part += NumRegs;
948     Parts.clear();
949   }
950 
951   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
952 }
953 
954 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
955                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
956                                  const Value *V,
957                                  ISD::NodeType PreferredExtendType) const {
958   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
959   ISD::NodeType ExtendKind = PreferredExtendType;
960 
961   // Get the list of the values's legal parts.
962   unsigned NumRegs = Regs.size();
963   SmallVector<SDValue, 8> Parts(NumRegs);
964   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
965     unsigned NumParts = RegCount[Value];
966 
967     MVT RegisterVT = isABIMangled()
968                          ? TLI.getRegisterTypeForCallingConv(
969                                *DAG.getContext(), *CallConv, RegVTs[Value])
970                          : RegVTs[Value];
971 
972     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
973       ExtendKind = ISD::ZERO_EXTEND;
974 
975     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
976                    NumParts, RegisterVT, V, CallConv, ExtendKind);
977     Part += NumParts;
978   }
979 
980   // Copy the parts into the registers.
981   SmallVector<SDValue, 8> Chains(NumRegs);
982   for (unsigned i = 0; i != NumRegs; ++i) {
983     SDValue Part;
984     if (!Glue) {
985       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
986     } else {
987       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
988       *Glue = Part.getValue(1);
989     }
990 
991     Chains[i] = Part.getValue(0);
992   }
993 
994   if (NumRegs == 1 || Glue)
995     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
996     // flagged to it. That is the CopyToReg nodes and the user are considered
997     // a single scheduling unit. If we create a TokenFactor and return it as
998     // chain, then the TokenFactor is both a predecessor (operand) of the
999     // user as well as a successor (the TF operands are flagged to the user).
1000     // c1, f1 = CopyToReg
1001     // c2, f2 = CopyToReg
1002     // c3     = TokenFactor c1, c2
1003     // ...
1004     //        = op c3, ..., f2
1005     Chain = Chains[NumRegs-1];
1006   else
1007     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1008 }
1009 
1010 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1011                                         unsigned MatchingIdx, const SDLoc &dl,
1012                                         SelectionDAG &DAG,
1013                                         std::vector<SDValue> &Ops) const {
1014   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1015 
1016   InlineAsm::Flag Flag(Code, Regs.size());
1017   if (HasMatching)
1018     Flag.setMatchingOp(MatchingIdx);
1019   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1020     // Put the register class of the virtual registers in the flag word.  That
1021     // way, later passes can recompute register class constraints for inline
1022     // assembly as well as normal instructions.
1023     // Don't do this for tied operands that can use the regclass information
1024     // from the def.
1025     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1026     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1027     Flag.setRegClass(RC->getID());
1028   }
1029 
1030   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1031   Ops.push_back(Res);
1032 
1033   if (Code == InlineAsm::Kind::Clobber) {
1034     // Clobbers should always have a 1:1 mapping with registers, and may
1035     // reference registers that have illegal (e.g. vector) types. Hence, we
1036     // shouldn't try to apply any sort of splitting logic to them.
1037     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1038            "No 1:1 mapping from clobbers to regs?");
1039     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1040     (void)SP;
1041     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1042       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1043       assert(
1044           (Regs[I] != SP ||
1045            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1046           "If we clobbered the stack pointer, MFI should know about it.");
1047     }
1048     return;
1049   }
1050 
1051   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1052     MVT RegisterVT = RegVTs[Value];
1053     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1054                                            RegisterVT);
1055     for (unsigned i = 0; i != NumRegs; ++i) {
1056       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1057       unsigned TheReg = Regs[Reg++];
1058       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1059     }
1060   }
1061 }
1062 
1063 SmallVector<std::pair<unsigned, TypeSize>, 4>
1064 RegsForValue::getRegsAndSizes() const {
1065   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1066   unsigned I = 0;
1067   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1068     unsigned RegCount = std::get<0>(CountAndVT);
1069     MVT RegisterVT = std::get<1>(CountAndVT);
1070     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1071     for (unsigned E = I + RegCount; I != E; ++I)
1072       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1073   }
1074   return OutVec;
1075 }
1076 
1077 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1078                                AssumptionCache *ac,
1079                                const TargetLibraryInfo *li) {
1080   AA = aa;
1081   AC = ac;
1082   GFI = gfi;
1083   LibInfo = li;
1084   Context = DAG.getContext();
1085   LPadToCallSiteMap.clear();
1086   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1087   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1088       *DAG.getMachineFunction().getFunction().getParent());
1089 }
1090 
1091 void SelectionDAGBuilder::clear() {
1092   NodeMap.clear();
1093   UnusedArgNodeMap.clear();
1094   PendingLoads.clear();
1095   PendingExports.clear();
1096   PendingConstrainedFP.clear();
1097   PendingConstrainedFPStrict.clear();
1098   CurInst = nullptr;
1099   HasTailCall = false;
1100   SDNodeOrder = LowestSDNodeOrder;
1101   StatepointLowering.clear();
1102 }
1103 
1104 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1105   DanglingDebugInfoMap.clear();
1106 }
1107 
1108 // Update DAG root to include dependencies on Pending chains.
1109 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1110   SDValue Root = DAG.getRoot();
1111 
1112   if (Pending.empty())
1113     return Root;
1114 
1115   // Add current root to PendingChains, unless we already indirectly
1116   // depend on it.
1117   if (Root.getOpcode() != ISD::EntryToken) {
1118     unsigned i = 0, e = Pending.size();
1119     for (; i != e; ++i) {
1120       assert(Pending[i].getNode()->getNumOperands() > 1);
1121       if (Pending[i].getNode()->getOperand(0) == Root)
1122         break;  // Don't add the root if we already indirectly depend on it.
1123     }
1124 
1125     if (i == e)
1126       Pending.push_back(Root);
1127   }
1128 
1129   if (Pending.size() == 1)
1130     Root = Pending[0];
1131   else
1132     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1133 
1134   DAG.setRoot(Root);
1135   Pending.clear();
1136   return Root;
1137 }
1138 
1139 SDValue SelectionDAGBuilder::getMemoryRoot() {
1140   return updateRoot(PendingLoads);
1141 }
1142 
1143 SDValue SelectionDAGBuilder::getRoot() {
1144   // Chain up all pending constrained intrinsics together with all
1145   // pending loads, by simply appending them to PendingLoads and
1146   // then calling getMemoryRoot().
1147   PendingLoads.reserve(PendingLoads.size() +
1148                        PendingConstrainedFP.size() +
1149                        PendingConstrainedFPStrict.size());
1150   PendingLoads.append(PendingConstrainedFP.begin(),
1151                       PendingConstrainedFP.end());
1152   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1153                       PendingConstrainedFPStrict.end());
1154   PendingConstrainedFP.clear();
1155   PendingConstrainedFPStrict.clear();
1156   return getMemoryRoot();
1157 }
1158 
1159 SDValue SelectionDAGBuilder::getControlRoot() {
1160   // We need to emit pending fpexcept.strict constrained intrinsics,
1161   // so append them to the PendingExports list.
1162   PendingExports.append(PendingConstrainedFPStrict.begin(),
1163                         PendingConstrainedFPStrict.end());
1164   PendingConstrainedFPStrict.clear();
1165   return updateRoot(PendingExports);
1166 }
1167 
1168 void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1169                                              DILocalVariable *Variable,
1170                                              DIExpression *Expression,
1171                                              DebugLoc DL) {
1172   assert(Variable && "Missing variable");
1173 
1174   // Check if address has undef value.
1175   if (!Address || isa<UndefValue>(Address) ||
1176       (Address->use_empty() && !isa<Argument>(Address))) {
1177     LLVM_DEBUG(
1178         dbgs()
1179         << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1180     return;
1181   }
1182 
1183   bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1184 
1185   SDValue &N = NodeMap[Address];
1186   if (!N.getNode() && isa<Argument>(Address))
1187     // Check unused arguments map.
1188     N = UnusedArgNodeMap[Address];
1189   SDDbgValue *SDV;
1190   if (N.getNode()) {
1191     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1192       Address = BCI->getOperand(0);
1193     // Parameters are handled specially.
1194     auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1195     if (IsParameter && FINode) {
1196       // Byval parameter. We have a frame index at this point.
1197       SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1198                                       /*IsIndirect*/ true, DL, SDNodeOrder);
1199     } else if (isa<Argument>(Address)) {
1200       // Address is an argument, so try to emit its dbg value using
1201       // virtual register info from the FuncInfo.ValueMap.
1202       EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1203                                FuncArgumentDbgValueKind::Declare, N);
1204       return;
1205     } else {
1206       SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1207                             true, DL, SDNodeOrder);
1208     }
1209     DAG.AddDbgValue(SDV, IsParameter);
1210   } else {
1211     // If Address is an argument then try to emit its dbg value using
1212     // virtual register info from the FuncInfo.ValueMap.
1213     if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1214                                   FuncArgumentDbgValueKind::Declare, N)) {
1215       LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1216                         << " (could not emit func-arg dbg_value)\n");
1217     }
1218   }
1219   return;
1220 }
1221 
1222 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1223   // Add SDDbgValue nodes for any var locs here. Do so before updating
1224   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1225   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1226     // Add SDDbgValue nodes for any var locs here. Do so before updating
1227     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1228     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1229          It != End; ++It) {
1230       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1231       dropDanglingDebugInfo(Var, It->Expr);
1232       if (It->Values.isKillLocation(It->Expr)) {
1233         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1234         continue;
1235       }
1236       SmallVector<Value *> Values(It->Values.location_ops());
1237       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1238                             It->Values.hasArgList())) {
1239         SmallVector<Value *, 4> Vals;
1240         for (Value *V : It->Values.location_ops())
1241           Vals.push_back(V);
1242         addDanglingDebugInfo(Vals,
1243                              FnVarLocs->getDILocalVariable(It->VariableID),
1244                              It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1245       }
1246     }
1247   }
1248 
1249   // We must skip DbgVariableRecords if they've already been processed above as
1250   // we have just emitted the debug values resulting from assignment tracking
1251   // analysis, making any existing DbgVariableRecords redundant (and probably
1252   // less correct). We still need to process DbgLabelRecords. This does sink
1253   // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1254   // be important as it does so deterministcally and ordering between
1255   // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1256   // printing).
1257   bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1258   // Is there is any debug-info attached to this instruction, in the form of
1259   // DbgRecord non-instruction debug-info records.
1260   for (DbgRecord &DR : I.getDbgRecordRange()) {
1261     if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1262       assert(DLR->getLabel() && "Missing label");
1263       SDDbgLabel *SDV =
1264           DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1265       DAG.AddDbgLabel(SDV);
1266       continue;
1267     }
1268 
1269     if (SkipDbgVariableRecords)
1270       continue;
1271     DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
1272     DILocalVariable *Variable = DVR.getVariable();
1273     DIExpression *Expression = DVR.getExpression();
1274     dropDanglingDebugInfo(Variable, Expression);
1275 
1276     if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1277       if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1278         continue;
1279       LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1280                         << "\n");
1281       handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression,
1282                          DVR.getDebugLoc());
1283       continue;
1284     }
1285 
1286     // A DbgVariableRecord with no locations is a kill location.
1287     SmallVector<Value *, 4> Values(DVR.location_ops());
1288     if (Values.empty()) {
1289       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1290                            SDNodeOrder);
1291       continue;
1292     }
1293 
1294     // A DbgVariableRecord with an undef or absent location is also a kill
1295     // location.
1296     if (llvm::any_of(Values,
1297                      [](Value *V) { return !V || isa<UndefValue>(V); })) {
1298       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1299                            SDNodeOrder);
1300       continue;
1301     }
1302 
1303     bool IsVariadic = DVR.hasArgList();
1304     if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1305                           SDNodeOrder, IsVariadic)) {
1306       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1307                            DVR.getDebugLoc(), SDNodeOrder);
1308     }
1309   }
1310 }
1311 
1312 void SelectionDAGBuilder::visit(const Instruction &I) {
1313   visitDbgInfo(I);
1314 
1315   // Set up outgoing PHI node register values before emitting the terminator.
1316   if (I.isTerminator()) {
1317     HandlePHINodesInSuccessorBlocks(I.getParent());
1318   }
1319 
1320   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1321   if (!isa<DbgInfoIntrinsic>(I))
1322     ++SDNodeOrder;
1323 
1324   CurInst = &I;
1325 
1326   // Set inserted listener only if required.
1327   bool NodeInserted = false;
1328   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1329   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1330   MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1331   if (PCSectionsMD || MMRA) {
1332     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1333         DAG, [&](SDNode *) { NodeInserted = true; });
1334   }
1335 
1336   visit(I.getOpcode(), I);
1337 
1338   if (!I.isTerminator() && !HasTailCall &&
1339       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1340     CopyToExportRegsIfNeeded(&I);
1341 
1342   // Handle metadata.
1343   if (PCSectionsMD || MMRA) {
1344     auto It = NodeMap.find(&I);
1345     if (It != NodeMap.end()) {
1346       if (PCSectionsMD)
1347         DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1348       if (MMRA)
1349         DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1350     } else if (NodeInserted) {
1351       // This should not happen; if it does, don't let it go unnoticed so we can
1352       // fix it. Relevant visit*() function is probably missing a setValue().
1353       errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1354              << I.getModule()->getName() << "]\n";
1355       LLVM_DEBUG(I.dump());
1356       assert(false);
1357     }
1358   }
1359 
1360   CurInst = nullptr;
1361 }
1362 
1363 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1364   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1365 }
1366 
1367 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1368   // Note: this doesn't use InstVisitor, because it has to work with
1369   // ConstantExpr's in addition to instructions.
1370   switch (Opcode) {
1371   default: llvm_unreachable("Unknown instruction type encountered!");
1372     // Build the switch statement using the Instruction.def file.
1373 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1374     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1375 #include "llvm/IR/Instruction.def"
1376   }
1377 }
1378 
1379 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1380                                             DILocalVariable *Variable,
1381                                             DebugLoc DL, unsigned Order,
1382                                             SmallVectorImpl<Value *> &Values,
1383                                             DIExpression *Expression) {
1384   // For variadic dbg_values we will now insert an undef.
1385   // FIXME: We can potentially recover these!
1386   SmallVector<SDDbgOperand, 2> Locs;
1387   for (const Value *V : Values) {
1388     auto *Undef = UndefValue::get(V->getType());
1389     Locs.push_back(SDDbgOperand::fromConst(Undef));
1390   }
1391   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1392                                         /*IsIndirect=*/false, DL, Order,
1393                                         /*IsVariadic=*/true);
1394   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1395   return true;
1396 }
1397 
1398 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1399                                                DILocalVariable *Var,
1400                                                DIExpression *Expr,
1401                                                bool IsVariadic, DebugLoc DL,
1402                                                unsigned Order) {
1403   if (IsVariadic) {
1404     handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1405     return;
1406   }
1407   // TODO: Dangling debug info will eventually either be resolved or produce
1408   // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1409   // between the original dbg.value location and its resolved DBG_VALUE,
1410   // which we should ideally fill with an extra Undef DBG_VALUE.
1411   assert(Values.size() == 1);
1412   DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1413 }
1414 
1415 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1416                                                 const DIExpression *Expr) {
1417   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1418     DIVariable *DanglingVariable = DDI.getVariable();
1419     DIExpression *DanglingExpr = DDI.getExpression();
1420     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1421       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1422                         << printDDI(nullptr, DDI) << "\n");
1423       return true;
1424     }
1425     return false;
1426   };
1427 
1428   for (auto &DDIMI : DanglingDebugInfoMap) {
1429     DanglingDebugInfoVector &DDIV = DDIMI.second;
1430 
1431     // If debug info is to be dropped, run it through final checks to see
1432     // whether it can be salvaged.
1433     for (auto &DDI : DDIV)
1434       if (isMatchingDbgValue(DDI))
1435         salvageUnresolvedDbgValue(DDIMI.first, DDI);
1436 
1437     erase_if(DDIV, isMatchingDbgValue);
1438   }
1439 }
1440 
1441 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1442 // generate the debug data structures now that we've seen its definition.
1443 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1444                                                    SDValue Val) {
1445   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1446   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1447     return;
1448 
1449   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1450   for (auto &DDI : DDIV) {
1451     DebugLoc DL = DDI.getDebugLoc();
1452     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1453     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1454     DILocalVariable *Variable = DDI.getVariable();
1455     DIExpression *Expr = DDI.getExpression();
1456     assert(Variable->isValidLocationForIntrinsic(DL) &&
1457            "Expected inlined-at fields to agree");
1458     SDDbgValue *SDV;
1459     if (Val.getNode()) {
1460       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1461       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1462       // we couldn't resolve it directly when examining the DbgValue intrinsic
1463       // in the first place we should not be more successful here). Unless we
1464       // have some test case that prove this to be correct we should avoid
1465       // calling EmitFuncArgumentDbgValue here.
1466       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1467                                     FuncArgumentDbgValueKind::Value, Val)) {
1468         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1469                           << printDDI(V, DDI) << "\n");
1470         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1471         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1472         // inserted after the definition of Val when emitting the instructions
1473         // after ISel. An alternative could be to teach
1474         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1475         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1476                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1477                    << ValSDNodeOrder << "\n");
1478         SDV = getDbgValue(Val, Variable, Expr, DL,
1479                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1480         DAG.AddDbgValue(SDV, false);
1481       } else
1482         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1483                           << printDDI(V, DDI)
1484                           << " in EmitFuncArgumentDbgValue\n");
1485     } else {
1486       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1487                         << "\n");
1488       auto Undef = UndefValue::get(V->getType());
1489       auto SDV =
1490           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1491       DAG.AddDbgValue(SDV, false);
1492     }
1493   }
1494   DDIV.clear();
1495 }
1496 
1497 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1498                                                     DanglingDebugInfo &DDI) {
1499   // TODO: For the variadic implementation, instead of only checking the fail
1500   // state of `handleDebugValue`, we need know specifically which values were
1501   // invalid, so that we attempt to salvage only those values when processing
1502   // a DIArgList.
1503   const Value *OrigV = V;
1504   DILocalVariable *Var = DDI.getVariable();
1505   DIExpression *Expr = DDI.getExpression();
1506   DebugLoc DL = DDI.getDebugLoc();
1507   unsigned SDOrder = DDI.getSDNodeOrder();
1508 
1509   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1510   // that DW_OP_stack_value is desired.
1511   bool StackValue = true;
1512 
1513   // Can this Value can be encoded without any further work?
1514   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1515     return;
1516 
1517   // Attempt to salvage back through as many instructions as possible. Bail if
1518   // a non-instruction is seen, such as a constant expression or global
1519   // variable. FIXME: Further work could recover those too.
1520   while (isa<Instruction>(V)) {
1521     const Instruction &VAsInst = *cast<const Instruction>(V);
1522     // Temporary "0", awaiting real implementation.
1523     SmallVector<uint64_t, 16> Ops;
1524     SmallVector<Value *, 4> AdditionalValues;
1525     V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1526                              Expr->getNumLocationOperands(), Ops,
1527                              AdditionalValues);
1528     // If we cannot salvage any further, and haven't yet found a suitable debug
1529     // expression, bail out.
1530     if (!V)
1531       break;
1532 
1533     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1534     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1535     // here for variadic dbg_values, remove that condition.
1536     if (!AdditionalValues.empty())
1537       break;
1538 
1539     // New value and expr now represent this debuginfo.
1540     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1541 
1542     // Some kind of simplification occurred: check whether the operand of the
1543     // salvaged debug expression can be encoded in this DAG.
1544     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1545       LLVM_DEBUG(
1546           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1547                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1548       return;
1549     }
1550   }
1551 
1552   // This was the final opportunity to salvage this debug information, and it
1553   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1554   // any earlier variable location.
1555   assert(OrigV && "V shouldn't be null");
1556   auto *Undef = UndefValue::get(OrigV->getType());
1557   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1558   DAG.AddDbgValue(SDV, false);
1559   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  "
1560                     << printDDI(OrigV, DDI) << "\n");
1561 }
1562 
1563 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1564                                                DIExpression *Expr,
1565                                                DebugLoc DbgLoc,
1566                                                unsigned Order) {
1567   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1568   DIExpression *NewExpr =
1569       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1570   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1571                    /*IsVariadic*/ false);
1572 }
1573 
1574 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1575                                            DILocalVariable *Var,
1576                                            DIExpression *Expr, DebugLoc DbgLoc,
1577                                            unsigned Order, bool IsVariadic) {
1578   if (Values.empty())
1579     return true;
1580 
1581   // Filter EntryValue locations out early.
1582   if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1583     return true;
1584 
1585   SmallVector<SDDbgOperand> LocationOps;
1586   SmallVector<SDNode *> Dependencies;
1587   for (const Value *V : Values) {
1588     // Constant value.
1589     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1590         isa<ConstantPointerNull>(V)) {
1591       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1592       continue;
1593     }
1594 
1595     // Look through IntToPtr constants.
1596     if (auto *CE = dyn_cast<ConstantExpr>(V))
1597       if (CE->getOpcode() == Instruction::IntToPtr) {
1598         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1599         continue;
1600       }
1601 
1602     // If the Value is a frame index, we can create a FrameIndex debug value
1603     // without relying on the DAG at all.
1604     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1605       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1606       if (SI != FuncInfo.StaticAllocaMap.end()) {
1607         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1608         continue;
1609       }
1610     }
1611 
1612     // Do not use getValue() in here; we don't want to generate code at
1613     // this point if it hasn't been done yet.
1614     SDValue N = NodeMap[V];
1615     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1616       N = UnusedArgNodeMap[V];
1617     if (N.getNode()) {
1618       // Only emit func arg dbg value for non-variadic dbg.values for now.
1619       if (!IsVariadic &&
1620           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1621                                    FuncArgumentDbgValueKind::Value, N))
1622         return true;
1623       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1624         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1625         // describe stack slot locations.
1626         //
1627         // Consider "int x = 0; int *px = &x;". There are two kinds of
1628         // interesting debug values here after optimization:
1629         //
1630         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1631         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1632         //
1633         // Both describe the direct values of their associated variables.
1634         Dependencies.push_back(N.getNode());
1635         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1636         continue;
1637       }
1638       LocationOps.emplace_back(
1639           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1640       continue;
1641     }
1642 
1643     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1644     // Special rules apply for the first dbg.values of parameter variables in a
1645     // function. Identify them by the fact they reference Argument Values, that
1646     // they're parameters, and they are parameters of the current function. We
1647     // need to let them dangle until they get an SDNode.
1648     bool IsParamOfFunc =
1649         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1650     if (IsParamOfFunc)
1651       return false;
1652 
1653     // The value is not used in this block yet (or it would have an SDNode).
1654     // We still want the value to appear for the user if possible -- if it has
1655     // an associated VReg, we can refer to that instead.
1656     auto VMI = FuncInfo.ValueMap.find(V);
1657     if (VMI != FuncInfo.ValueMap.end()) {
1658       unsigned Reg = VMI->second;
1659       // If this is a PHI node, it may be split up into several MI PHI nodes
1660       // (in FunctionLoweringInfo::set).
1661       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1662                        V->getType(), std::nullopt);
1663       if (RFV.occupiesMultipleRegs()) {
1664         // FIXME: We could potentially support variadic dbg_values here.
1665         if (IsVariadic)
1666           return false;
1667         unsigned Offset = 0;
1668         unsigned BitsToDescribe = 0;
1669         if (auto VarSize = Var->getSizeInBits())
1670           BitsToDescribe = *VarSize;
1671         if (auto Fragment = Expr->getFragmentInfo())
1672           BitsToDescribe = Fragment->SizeInBits;
1673         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1674           // Bail out if all bits are described already.
1675           if (Offset >= BitsToDescribe)
1676             break;
1677           // TODO: handle scalable vectors.
1678           unsigned RegisterSize = RegAndSize.second;
1679           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1680                                       ? BitsToDescribe - Offset
1681                                       : RegisterSize;
1682           auto FragmentExpr = DIExpression::createFragmentExpression(
1683               Expr, Offset, FragmentSize);
1684           if (!FragmentExpr)
1685             continue;
1686           SDDbgValue *SDV = DAG.getVRegDbgValue(
1687               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1688           DAG.AddDbgValue(SDV, false);
1689           Offset += RegisterSize;
1690         }
1691         return true;
1692       }
1693       // We can use simple vreg locations for variadic dbg_values as well.
1694       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1695       continue;
1696     }
1697     // We failed to create a SDDbgOperand for V.
1698     return false;
1699   }
1700 
1701   // We have created a SDDbgOperand for each Value in Values.
1702   assert(!LocationOps.empty());
1703   SDDbgValue *SDV =
1704       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1705                           /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1706   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1707   return true;
1708 }
1709 
1710 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1711   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1712   for (auto &Pair : DanglingDebugInfoMap)
1713     for (auto &DDI : Pair.second)
1714       salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1715   clearDanglingDebugInfo();
1716 }
1717 
1718 /// getCopyFromRegs - If there was virtual register allocated for the value V
1719 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1720 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1721   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1722   SDValue Result;
1723 
1724   if (It != FuncInfo.ValueMap.end()) {
1725     Register InReg = It->second;
1726 
1727     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1728                      DAG.getDataLayout(), InReg, Ty,
1729                      std::nullopt); // This is not an ABI copy.
1730     SDValue Chain = DAG.getEntryNode();
1731     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1732                                  V);
1733     resolveDanglingDebugInfo(V, Result);
1734   }
1735 
1736   return Result;
1737 }
1738 
1739 /// getValue - Return an SDValue for the given Value.
1740 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1741   // If we already have an SDValue for this value, use it. It's important
1742   // to do this first, so that we don't create a CopyFromReg if we already
1743   // have a regular SDValue.
1744   SDValue &N = NodeMap[V];
1745   if (N.getNode()) return N;
1746 
1747   // If there's a virtual register allocated and initialized for this
1748   // value, use it.
1749   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1750     return copyFromReg;
1751 
1752   // Otherwise create a new SDValue and remember it.
1753   SDValue Val = getValueImpl(V);
1754   NodeMap[V] = Val;
1755   resolveDanglingDebugInfo(V, Val);
1756   return Val;
1757 }
1758 
1759 /// getNonRegisterValue - Return an SDValue for the given Value, but
1760 /// don't look in FuncInfo.ValueMap for a virtual register.
1761 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1762   // If we already have an SDValue for this value, use it.
1763   SDValue &N = NodeMap[V];
1764   if (N.getNode()) {
1765     if (isIntOrFPConstant(N)) {
1766       // Remove the debug location from the node as the node is about to be used
1767       // in a location which may differ from the original debug location.  This
1768       // is relevant to Constant and ConstantFP nodes because they can appear
1769       // as constant expressions inside PHI nodes.
1770       N->setDebugLoc(DebugLoc());
1771     }
1772     return N;
1773   }
1774 
1775   // Otherwise create a new SDValue and remember it.
1776   SDValue Val = getValueImpl(V);
1777   NodeMap[V] = Val;
1778   resolveDanglingDebugInfo(V, Val);
1779   return Val;
1780 }
1781 
1782 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1783 /// Create an SDValue for the given value.
1784 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1785   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1786 
1787   if (const Constant *C = dyn_cast<Constant>(V)) {
1788     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1789 
1790     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1791       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1792 
1793     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1794       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1795 
1796     if (isa<ConstantPointerNull>(C)) {
1797       unsigned AS = V->getType()->getPointerAddressSpace();
1798       return DAG.getConstant(0, getCurSDLoc(),
1799                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1800     }
1801 
1802     if (match(C, m_VScale()))
1803       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1804 
1805     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1806       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1807 
1808     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1809       return DAG.getUNDEF(VT);
1810 
1811     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1812       visit(CE->getOpcode(), *CE);
1813       SDValue N1 = NodeMap[V];
1814       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1815       return N1;
1816     }
1817 
1818     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1819       SmallVector<SDValue, 4> Constants;
1820       for (const Use &U : C->operands()) {
1821         SDNode *Val = getValue(U).getNode();
1822         // If the operand is an empty aggregate, there are no values.
1823         if (!Val) continue;
1824         // Add each leaf value from the operand to the Constants list
1825         // to form a flattened list of all the values.
1826         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1827           Constants.push_back(SDValue(Val, i));
1828       }
1829 
1830       return DAG.getMergeValues(Constants, getCurSDLoc());
1831     }
1832 
1833     if (const ConstantDataSequential *CDS =
1834           dyn_cast<ConstantDataSequential>(C)) {
1835       SmallVector<SDValue, 4> Ops;
1836       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1837         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1838         // Add each leaf value from the operand to the Constants list
1839         // to form a flattened list of all the values.
1840         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1841           Ops.push_back(SDValue(Val, i));
1842       }
1843 
1844       if (isa<ArrayType>(CDS->getType()))
1845         return DAG.getMergeValues(Ops, getCurSDLoc());
1846       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1847     }
1848 
1849     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1850       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1851              "Unknown struct or array constant!");
1852 
1853       SmallVector<EVT, 4> ValueVTs;
1854       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1855       unsigned NumElts = ValueVTs.size();
1856       if (NumElts == 0)
1857         return SDValue(); // empty struct
1858       SmallVector<SDValue, 4> Constants(NumElts);
1859       for (unsigned i = 0; i != NumElts; ++i) {
1860         EVT EltVT = ValueVTs[i];
1861         if (isa<UndefValue>(C))
1862           Constants[i] = DAG.getUNDEF(EltVT);
1863         else if (EltVT.isFloatingPoint())
1864           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1865         else
1866           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1867       }
1868 
1869       return DAG.getMergeValues(Constants, getCurSDLoc());
1870     }
1871 
1872     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1873       return DAG.getBlockAddress(BA, VT);
1874 
1875     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1876       return getValue(Equiv->getGlobalValue());
1877 
1878     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1879       return getValue(NC->getGlobalValue());
1880 
1881     if (VT == MVT::aarch64svcount) {
1882       assert(C->isNullValue() && "Can only zero this target type!");
1883       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1884                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1885     }
1886 
1887     VectorType *VecTy = cast<VectorType>(V->getType());
1888 
1889     // Now that we know the number and type of the elements, get that number of
1890     // elements into the Ops array based on what kind of constant it is.
1891     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1892       SmallVector<SDValue, 16> Ops;
1893       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1894       for (unsigned i = 0; i != NumElements; ++i)
1895         Ops.push_back(getValue(CV->getOperand(i)));
1896 
1897       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1898     }
1899 
1900     if (isa<ConstantAggregateZero>(C)) {
1901       EVT EltVT =
1902           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1903 
1904       SDValue Op;
1905       if (EltVT.isFloatingPoint())
1906         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1907       else
1908         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1909 
1910       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1911     }
1912 
1913     llvm_unreachable("Unknown vector constant");
1914   }
1915 
1916   // If this is a static alloca, generate it as the frameindex instead of
1917   // computation.
1918   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1919     DenseMap<const AllocaInst*, int>::iterator SI =
1920       FuncInfo.StaticAllocaMap.find(AI);
1921     if (SI != FuncInfo.StaticAllocaMap.end())
1922       return DAG.getFrameIndex(
1923           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1924   }
1925 
1926   // If this is an instruction which fast-isel has deferred, select it now.
1927   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1928     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1929 
1930     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1931                      Inst->getType(), std::nullopt);
1932     SDValue Chain = DAG.getEntryNode();
1933     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1934   }
1935 
1936   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1937     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1938 
1939   if (const auto *BB = dyn_cast<BasicBlock>(V))
1940     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1941 
1942   llvm_unreachable("Can't get register for value!");
1943 }
1944 
1945 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1946   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1947   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1948   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1949   bool IsSEH = isAsynchronousEHPersonality(Pers);
1950   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1951   if (!IsSEH)
1952     CatchPadMBB->setIsEHScopeEntry();
1953   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1954   if (IsMSVCCXX || IsCoreCLR)
1955     CatchPadMBB->setIsEHFuncletEntry();
1956 }
1957 
1958 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1959   // Update machine-CFG edge.
1960   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1961   FuncInfo.MBB->addSuccessor(TargetMBB);
1962   TargetMBB->setIsEHCatchretTarget(true);
1963   DAG.getMachineFunction().setHasEHCatchret(true);
1964 
1965   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1966   bool IsSEH = isAsynchronousEHPersonality(Pers);
1967   if (IsSEH) {
1968     // If this is not a fall-through branch or optimizations are switched off,
1969     // emit the branch.
1970     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1971         TM.getOptLevel() == CodeGenOptLevel::None)
1972       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1973                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1974     return;
1975   }
1976 
1977   // Figure out the funclet membership for the catchret's successor.
1978   // This will be used by the FuncletLayout pass to determine how to order the
1979   // BB's.
1980   // A 'catchret' returns to the outer scope's color.
1981   Value *ParentPad = I.getCatchSwitchParentPad();
1982   const BasicBlock *SuccessorColor;
1983   if (isa<ConstantTokenNone>(ParentPad))
1984     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1985   else
1986     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1987   assert(SuccessorColor && "No parent funclet for catchret!");
1988   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1989   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1990 
1991   // Create the terminator node.
1992   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1993                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1994                             DAG.getBasicBlock(SuccessorColorMBB));
1995   DAG.setRoot(Ret);
1996 }
1997 
1998 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1999   // Don't emit any special code for the cleanuppad instruction. It just marks
2000   // the start of an EH scope/funclet.
2001   FuncInfo.MBB->setIsEHScopeEntry();
2002   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2003   if (Pers != EHPersonality::Wasm_CXX) {
2004     FuncInfo.MBB->setIsEHFuncletEntry();
2005     FuncInfo.MBB->setIsCleanupFuncletEntry();
2006   }
2007 }
2008 
2009 // In wasm EH, even though a catchpad may not catch an exception if a tag does
2010 // not match, it is OK to add only the first unwind destination catchpad to the
2011 // successors, because there will be at least one invoke instruction within the
2012 // catch scope that points to the next unwind destination, if one exists, so
2013 // CFGSort cannot mess up with BB sorting order.
2014 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
2015 // call within them, and catchpads only consisting of 'catch (...)' have a
2016 // '__cxa_end_catch' call within them, both of which generate invokes in case
2017 // the next unwind destination exists, i.e., the next unwind destination is not
2018 // the caller.)
2019 //
2020 // Having at most one EH pad successor is also simpler and helps later
2021 // transformations.
2022 //
2023 // For example,
2024 // current:
2025 //   invoke void @foo to ... unwind label %catch.dispatch
2026 // catch.dispatch:
2027 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
2028 // catch.start:
2029 //   ...
2030 //   ... in this BB or some other child BB dominated by this BB there will be an
2031 //   invoke that points to 'next' BB as an unwind destination
2032 //
2033 // next: ; We don't need to add this to 'current' BB's successor
2034 //   ...
2035 static void findWasmUnwindDestinations(
2036     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2037     BranchProbability Prob,
2038     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2039         &UnwindDests) {
2040   while (EHPadBB) {
2041     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2042     if (isa<CleanupPadInst>(Pad)) {
2043       // Stop on cleanup pads.
2044       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2045       UnwindDests.back().first->setIsEHScopeEntry();
2046       break;
2047     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2048       // Add the catchpad handlers to the possible destinations. We don't
2049       // continue to the unwind destination of the catchswitch for wasm.
2050       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2051         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2052         UnwindDests.back().first->setIsEHScopeEntry();
2053       }
2054       break;
2055     } else {
2056       continue;
2057     }
2058   }
2059 }
2060 
2061 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
2062 /// many places it could ultimately go. In the IR, we have a single unwind
2063 /// destination, but in the machine CFG, we enumerate all the possible blocks.
2064 /// This function skips over imaginary basic blocks that hold catchswitch
2065 /// instructions, and finds all the "real" machine
2066 /// basic block destinations. As those destinations may not be successors of
2067 /// EHPadBB, here we also calculate the edge probability to those destinations.
2068 /// The passed-in Prob is the edge probability to EHPadBB.
2069 static void findUnwindDestinations(
2070     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2071     BranchProbability Prob,
2072     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2073         &UnwindDests) {
2074   EHPersonality Personality =
2075     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2076   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2077   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2078   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2079   bool IsSEH = isAsynchronousEHPersonality(Personality);
2080 
2081   if (IsWasmCXX) {
2082     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
2083     assert(UnwindDests.size() <= 1 &&
2084            "There should be at most one unwind destination for wasm");
2085     return;
2086   }
2087 
2088   while (EHPadBB) {
2089     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2090     BasicBlock *NewEHPadBB = nullptr;
2091     if (isa<LandingPadInst>(Pad)) {
2092       // Stop on landingpads. They are not funclets.
2093       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2094       break;
2095     } else if (isa<CleanupPadInst>(Pad)) {
2096       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2097       // personalities.
2098       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2099       UnwindDests.back().first->setIsEHScopeEntry();
2100       UnwindDests.back().first->setIsEHFuncletEntry();
2101       break;
2102     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2103       // Add the catchpad handlers to the possible destinations.
2104       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2105         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2106         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2107         if (IsMSVCCXX || IsCoreCLR)
2108           UnwindDests.back().first->setIsEHFuncletEntry();
2109         if (!IsSEH)
2110           UnwindDests.back().first->setIsEHScopeEntry();
2111       }
2112       NewEHPadBB = CatchSwitch->getUnwindDest();
2113     } else {
2114       continue;
2115     }
2116 
2117     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2118     if (BPI && NewEHPadBB)
2119       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2120     EHPadBB = NewEHPadBB;
2121   }
2122 }
2123 
2124 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2125   // Update successor info.
2126   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2127   auto UnwindDest = I.getUnwindDest();
2128   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2129   BranchProbability UnwindDestProb =
2130       (BPI && UnwindDest)
2131           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2132           : BranchProbability::getZero();
2133   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2134   for (auto &UnwindDest : UnwindDests) {
2135     UnwindDest.first->setIsEHPad();
2136     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2137   }
2138   FuncInfo.MBB->normalizeSuccProbs();
2139 
2140   // Create the terminator node.
2141   SDValue Ret =
2142       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
2143   DAG.setRoot(Ret);
2144 }
2145 
2146 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2147   report_fatal_error("visitCatchSwitch not yet implemented!");
2148 }
2149 
2150 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2151   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2152   auto &DL = DAG.getDataLayout();
2153   SDValue Chain = getControlRoot();
2154   SmallVector<ISD::OutputArg, 8> Outs;
2155   SmallVector<SDValue, 8> OutVals;
2156 
2157   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2158   // lower
2159   //
2160   //   %val = call <ty> @llvm.experimental.deoptimize()
2161   //   ret <ty> %val
2162   //
2163   // differently.
2164   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2165     LowerDeoptimizingReturn();
2166     return;
2167   }
2168 
2169   if (!FuncInfo.CanLowerReturn) {
2170     unsigned DemoteReg = FuncInfo.DemoteRegister;
2171     const Function *F = I.getParent()->getParent();
2172 
2173     // Emit a store of the return value through the virtual register.
2174     // Leave Outs empty so that LowerReturn won't try to load return
2175     // registers the usual way.
2176     SmallVector<EVT, 1> PtrValueVTs;
2177     ComputeValueVTs(TLI, DL,
2178                     PointerType::get(F->getContext(),
2179                                      DAG.getDataLayout().getAllocaAddrSpace()),
2180                     PtrValueVTs);
2181 
2182     SDValue RetPtr =
2183         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2184     SDValue RetOp = getValue(I.getOperand(0));
2185 
2186     SmallVector<EVT, 4> ValueVTs, MemVTs;
2187     SmallVector<uint64_t, 4> Offsets;
2188     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2189                     &Offsets, 0);
2190     unsigned NumValues = ValueVTs.size();
2191 
2192     SmallVector<SDValue, 4> Chains(NumValues);
2193     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2194     for (unsigned i = 0; i != NumValues; ++i) {
2195       // An aggregate return value cannot wrap around the address space, so
2196       // offsets to its parts don't wrap either.
2197       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2198                                            TypeSize::getFixed(Offsets[i]));
2199 
2200       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2201       if (MemVTs[i] != ValueVTs[i])
2202         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2203       Chains[i] = DAG.getStore(
2204           Chain, getCurSDLoc(), Val,
2205           // FIXME: better loc info would be nice.
2206           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2207           commonAlignment(BaseAlign, Offsets[i]));
2208     }
2209 
2210     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2211                         MVT::Other, Chains);
2212   } else if (I.getNumOperands() != 0) {
2213     SmallVector<EVT, 4> ValueVTs;
2214     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2215     unsigned NumValues = ValueVTs.size();
2216     if (NumValues) {
2217       SDValue RetOp = getValue(I.getOperand(0));
2218 
2219       const Function *F = I.getParent()->getParent();
2220 
2221       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2222           I.getOperand(0)->getType(), F->getCallingConv(),
2223           /*IsVarArg*/ false, DL);
2224 
2225       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2226       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2227         ExtendKind = ISD::SIGN_EXTEND;
2228       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2229         ExtendKind = ISD::ZERO_EXTEND;
2230 
2231       LLVMContext &Context = F->getContext();
2232       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2233 
2234       for (unsigned j = 0; j != NumValues; ++j) {
2235         EVT VT = ValueVTs[j];
2236 
2237         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2238           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2239 
2240         CallingConv::ID CC = F->getCallingConv();
2241 
2242         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2243         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2244         SmallVector<SDValue, 4> Parts(NumParts);
2245         getCopyToParts(DAG, getCurSDLoc(),
2246                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2247                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2248 
2249         // 'inreg' on function refers to return value
2250         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2251         if (RetInReg)
2252           Flags.setInReg();
2253 
2254         if (I.getOperand(0)->getType()->isPointerTy()) {
2255           Flags.setPointer();
2256           Flags.setPointerAddrSpace(
2257               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2258         }
2259 
2260         if (NeedsRegBlock) {
2261           Flags.setInConsecutiveRegs();
2262           if (j == NumValues - 1)
2263             Flags.setInConsecutiveRegsLast();
2264         }
2265 
2266         // Propagate extension type if any
2267         if (ExtendKind == ISD::SIGN_EXTEND)
2268           Flags.setSExt();
2269         else if (ExtendKind == ISD::ZERO_EXTEND)
2270           Flags.setZExt();
2271 
2272         for (unsigned i = 0; i < NumParts; ++i) {
2273           Outs.push_back(ISD::OutputArg(Flags,
2274                                         Parts[i].getValueType().getSimpleVT(),
2275                                         VT, /*isfixed=*/true, 0, 0));
2276           OutVals.push_back(Parts[i]);
2277         }
2278       }
2279     }
2280   }
2281 
2282   // Push in swifterror virtual register as the last element of Outs. This makes
2283   // sure swifterror virtual register will be returned in the swifterror
2284   // physical register.
2285   const Function *F = I.getParent()->getParent();
2286   if (TLI.supportSwiftError() &&
2287       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2288     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2289     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2290     Flags.setSwiftError();
2291     Outs.push_back(ISD::OutputArg(
2292         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2293         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2294     // Create SDNode for the swifterror virtual register.
2295     OutVals.push_back(
2296         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2297                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2298                         EVT(TLI.getPointerTy(DL))));
2299   }
2300 
2301   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2302   CallingConv::ID CallConv =
2303     DAG.getMachineFunction().getFunction().getCallingConv();
2304   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2305       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2306 
2307   // Verify that the target's LowerReturn behaved as expected.
2308   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2309          "LowerReturn didn't return a valid chain!");
2310 
2311   // Update the DAG with the new chain value resulting from return lowering.
2312   DAG.setRoot(Chain);
2313 }
2314 
2315 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2316 /// created for it, emit nodes to copy the value into the virtual
2317 /// registers.
2318 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2319   // Skip empty types
2320   if (V->getType()->isEmptyTy())
2321     return;
2322 
2323   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2324   if (VMI != FuncInfo.ValueMap.end()) {
2325     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2326            "Unused value assigned virtual registers!");
2327     CopyValueToVirtualRegister(V, VMI->second);
2328   }
2329 }
2330 
2331 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2332 /// the current basic block, add it to ValueMap now so that we'll get a
2333 /// CopyTo/FromReg.
2334 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2335   // No need to export constants.
2336   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2337 
2338   // Already exported?
2339   if (FuncInfo.isExportedInst(V)) return;
2340 
2341   Register Reg = FuncInfo.InitializeRegForValue(V);
2342   CopyValueToVirtualRegister(V, Reg);
2343 }
2344 
2345 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2346                                                      const BasicBlock *FromBB) {
2347   // The operands of the setcc have to be in this block.  We don't know
2348   // how to export them from some other block.
2349   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2350     // Can export from current BB.
2351     if (VI->getParent() == FromBB)
2352       return true;
2353 
2354     // Is already exported, noop.
2355     return FuncInfo.isExportedInst(V);
2356   }
2357 
2358   // If this is an argument, we can export it if the BB is the entry block or
2359   // if it is already exported.
2360   if (isa<Argument>(V)) {
2361     if (FromBB->isEntryBlock())
2362       return true;
2363 
2364     // Otherwise, can only export this if it is already exported.
2365     return FuncInfo.isExportedInst(V);
2366   }
2367 
2368   // Otherwise, constants can always be exported.
2369   return true;
2370 }
2371 
2372 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2373 BranchProbability
2374 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2375                                         const MachineBasicBlock *Dst) const {
2376   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2377   const BasicBlock *SrcBB = Src->getBasicBlock();
2378   const BasicBlock *DstBB = Dst->getBasicBlock();
2379   if (!BPI) {
2380     // If BPI is not available, set the default probability as 1 / N, where N is
2381     // the number of successors.
2382     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2383     return BranchProbability(1, SuccSize);
2384   }
2385   return BPI->getEdgeProbability(SrcBB, DstBB);
2386 }
2387 
2388 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2389                                                MachineBasicBlock *Dst,
2390                                                BranchProbability Prob) {
2391   if (!FuncInfo.BPI)
2392     Src->addSuccessorWithoutProb(Dst);
2393   else {
2394     if (Prob.isUnknown())
2395       Prob = getEdgeProbability(Src, Dst);
2396     Src->addSuccessor(Dst, Prob);
2397   }
2398 }
2399 
2400 static bool InBlock(const Value *V, const BasicBlock *BB) {
2401   if (const Instruction *I = dyn_cast<Instruction>(V))
2402     return I->getParent() == BB;
2403   return true;
2404 }
2405 
2406 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2407 /// This function emits a branch and is used at the leaves of an OR or an
2408 /// AND operator tree.
2409 void
2410 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2411                                                   MachineBasicBlock *TBB,
2412                                                   MachineBasicBlock *FBB,
2413                                                   MachineBasicBlock *CurBB,
2414                                                   MachineBasicBlock *SwitchBB,
2415                                                   BranchProbability TProb,
2416                                                   BranchProbability FProb,
2417                                                   bool InvertCond) {
2418   const BasicBlock *BB = CurBB->getBasicBlock();
2419 
2420   // If the leaf of the tree is a comparison, merge the condition into
2421   // the caseblock.
2422   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2423     // The operands of the cmp have to be in this block.  We don't know
2424     // how to export them from some other block.  If this is the first block
2425     // of the sequence, no exporting is needed.
2426     if (CurBB == SwitchBB ||
2427         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2428          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2429       ISD::CondCode Condition;
2430       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2431         ICmpInst::Predicate Pred =
2432             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2433         Condition = getICmpCondCode(Pred);
2434       } else {
2435         const FCmpInst *FC = cast<FCmpInst>(Cond);
2436         FCmpInst::Predicate Pred =
2437             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2438         Condition = getFCmpCondCode(Pred);
2439         if (TM.Options.NoNaNsFPMath)
2440           Condition = getFCmpCodeWithoutNaN(Condition);
2441       }
2442 
2443       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2444                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2445       SL->SwitchCases.push_back(CB);
2446       return;
2447     }
2448   }
2449 
2450   // Create a CaseBlock record representing this branch.
2451   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2452   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2453                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2454   SL->SwitchCases.push_back(CB);
2455 }
2456 
2457 // Collect dependencies on V recursively. This is used for the cost analysis in
2458 // `shouldKeepJumpConditionsTogether`.
2459 static bool collectInstructionDeps(
2460     SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2461     SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2462     unsigned Depth = 0) {
2463   // Return false if we have an incomplete count.
2464   if (Depth >= SelectionDAG::MaxRecursionDepth)
2465     return false;
2466 
2467   auto *I = dyn_cast<Instruction>(V);
2468   if (I == nullptr)
2469     return true;
2470 
2471   if (Necessary != nullptr) {
2472     // This instruction is necessary for the other side of the condition so
2473     // don't count it.
2474     if (Necessary->contains(I))
2475       return true;
2476   }
2477 
2478   // Already added this dep.
2479   if (!Deps->try_emplace(I, false).second)
2480     return true;
2481 
2482   for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2483     if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2484                                 Depth + 1))
2485       return false;
2486   return true;
2487 }
2488 
2489 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2490     const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2491     Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2492     TargetLoweringBase::CondMergingParams Params) const {
2493   if (I.getNumSuccessors() != 2)
2494     return false;
2495 
2496   if (!I.isConditional())
2497     return false;
2498 
2499   if (Params.BaseCost < 0)
2500     return false;
2501 
2502   // Baseline cost.
2503   InstructionCost CostThresh = Params.BaseCost;
2504 
2505   BranchProbabilityInfo *BPI = nullptr;
2506   if (Params.LikelyBias || Params.UnlikelyBias)
2507     BPI = FuncInfo.BPI;
2508   if (BPI != nullptr) {
2509     // See if we are either likely to get an early out or compute both lhs/rhs
2510     // of the condition.
2511     BasicBlock *IfFalse = I.getSuccessor(0);
2512     BasicBlock *IfTrue = I.getSuccessor(1);
2513 
2514     std::optional<bool> Likely;
2515     if (BPI->isEdgeHot(I.getParent(), IfTrue))
2516       Likely = true;
2517     else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2518       Likely = false;
2519 
2520     if (Likely) {
2521       if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2522         // Its likely we will have to compute both lhs and rhs of condition
2523         CostThresh += Params.LikelyBias;
2524       else {
2525         if (Params.UnlikelyBias < 0)
2526           return false;
2527         // Its likely we will get an early out.
2528         CostThresh -= Params.UnlikelyBias;
2529       }
2530     }
2531   }
2532 
2533   if (CostThresh <= 0)
2534     return false;
2535 
2536   // Collect "all" instructions that lhs condition is dependent on.
2537   // Use map for stable iteration (to avoid non-determanism of iteration of
2538   // SmallPtrSet). The `bool` value is just a dummy.
2539   SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2540   collectInstructionDeps(&LhsDeps, Lhs);
2541   // Collect "all" instructions that rhs condition is dependent on AND are
2542   // dependencies of lhs. This gives us an estimate on which instructions we
2543   // stand to save by splitting the condition.
2544   if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2545     return false;
2546   // Add the compare instruction itself unless its a dependency on the LHS.
2547   if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2548     if (!LhsDeps.contains(RhsI))
2549       RhsDeps.try_emplace(RhsI, false);
2550 
2551   const auto &TLI = DAG.getTargetLoweringInfo();
2552   const auto &TTI =
2553       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
2554 
2555   InstructionCost CostOfIncluding = 0;
2556   // See if this instruction will need to computed independently of whether RHS
2557   // is.
2558   Value *BrCond = I.getCondition();
2559   auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2560     for (const auto *U : Ins->users()) {
2561       // If user is independent of RHS calculation we don't need to count it.
2562       if (auto *UIns = dyn_cast<Instruction>(U))
2563         if (UIns != BrCond && !RhsDeps.contains(UIns))
2564           return false;
2565     }
2566     return true;
2567   };
2568 
2569   // Prune instructions from RHS Deps that are dependencies of unrelated
2570   // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2571   // arbitrary and just meant to cap the how much time we spend in the pruning
2572   // loop. Its highly unlikely to come into affect.
2573   const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2574   // Stop after a certain point. No incorrectness from including too many
2575   // instructions.
2576   for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2577     const Instruction *ToDrop = nullptr;
2578     for (const auto &InsPair : RhsDeps) {
2579       if (!ShouldCountInsn(InsPair.first)) {
2580         ToDrop = InsPair.first;
2581         break;
2582       }
2583     }
2584     if (ToDrop == nullptr)
2585       break;
2586     RhsDeps.erase(ToDrop);
2587   }
2588 
2589   for (const auto &InsPair : RhsDeps) {
2590     // Finally accumulate latency that we can only attribute to computing the
2591     // RHS condition. Use latency because we are essentially trying to calculate
2592     // the cost of the dependency chain.
2593     // Possible TODO: We could try to estimate ILP and make this more precise.
2594     CostOfIncluding +=
2595         TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency);
2596 
2597     if (CostOfIncluding > CostThresh)
2598       return false;
2599   }
2600   return true;
2601 }
2602 
2603 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2604                                                MachineBasicBlock *TBB,
2605                                                MachineBasicBlock *FBB,
2606                                                MachineBasicBlock *CurBB,
2607                                                MachineBasicBlock *SwitchBB,
2608                                                Instruction::BinaryOps Opc,
2609                                                BranchProbability TProb,
2610                                                BranchProbability FProb,
2611                                                bool InvertCond) {
2612   // Skip over not part of the tree and remember to invert op and operands at
2613   // next level.
2614   Value *NotCond;
2615   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2616       InBlock(NotCond, CurBB->getBasicBlock())) {
2617     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2618                          !InvertCond);
2619     return;
2620   }
2621 
2622   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2623   const Value *BOpOp0, *BOpOp1;
2624   // Compute the effective opcode for Cond, taking into account whether it needs
2625   // to be inverted, e.g.
2626   //   and (not (or A, B)), C
2627   // gets lowered as
2628   //   and (and (not A, not B), C)
2629   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2630   if (BOp) {
2631     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2632                ? Instruction::And
2633                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2634                       ? Instruction::Or
2635                       : (Instruction::BinaryOps)0);
2636     if (InvertCond) {
2637       if (BOpc == Instruction::And)
2638         BOpc = Instruction::Or;
2639       else if (BOpc == Instruction::Or)
2640         BOpc = Instruction::And;
2641     }
2642   }
2643 
2644   // If this node is not part of the or/and tree, emit it as a branch.
2645   // Note that all nodes in the tree should have same opcode.
2646   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2647   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2648       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2649       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2650     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2651                                  TProb, FProb, InvertCond);
2652     return;
2653   }
2654 
2655   //  Create TmpBB after CurBB.
2656   MachineFunction::iterator BBI(CurBB);
2657   MachineFunction &MF = DAG.getMachineFunction();
2658   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2659   CurBB->getParent()->insert(++BBI, TmpBB);
2660 
2661   if (Opc == Instruction::Or) {
2662     // Codegen X | Y as:
2663     // BB1:
2664     //   jmp_if_X TBB
2665     //   jmp TmpBB
2666     // TmpBB:
2667     //   jmp_if_Y TBB
2668     //   jmp FBB
2669     //
2670 
2671     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2672     // The requirement is that
2673     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2674     //     = TrueProb for original BB.
2675     // Assuming the original probabilities are A and B, one choice is to set
2676     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2677     // A/(1+B) and 2B/(1+B). This choice assumes that
2678     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2679     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2680     // TmpBB, but the math is more complicated.
2681 
2682     auto NewTrueProb = TProb / 2;
2683     auto NewFalseProb = TProb / 2 + FProb;
2684     // Emit the LHS condition.
2685     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2686                          NewFalseProb, InvertCond);
2687 
2688     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2689     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2690     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2691     // Emit the RHS condition into TmpBB.
2692     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2693                          Probs[1], InvertCond);
2694   } else {
2695     assert(Opc == Instruction::And && "Unknown merge op!");
2696     // Codegen X & Y as:
2697     // BB1:
2698     //   jmp_if_X TmpBB
2699     //   jmp FBB
2700     // TmpBB:
2701     //   jmp_if_Y TBB
2702     //   jmp FBB
2703     //
2704     //  This requires creation of TmpBB after CurBB.
2705 
2706     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2707     // The requirement is that
2708     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2709     //     = FalseProb for original BB.
2710     // Assuming the original probabilities are A and B, one choice is to set
2711     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2712     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2713     // TrueProb for BB1 * FalseProb for TmpBB.
2714 
2715     auto NewTrueProb = TProb + FProb / 2;
2716     auto NewFalseProb = FProb / 2;
2717     // Emit the LHS condition.
2718     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2719                          NewFalseProb, InvertCond);
2720 
2721     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2722     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2723     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2724     // Emit the RHS condition into TmpBB.
2725     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2726                          Probs[1], InvertCond);
2727   }
2728 }
2729 
2730 /// If the set of cases should be emitted as a series of branches, return true.
2731 /// If we should emit this as a bunch of and/or'd together conditions, return
2732 /// false.
2733 bool
2734 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2735   if (Cases.size() != 2) return true;
2736 
2737   // If this is two comparisons of the same values or'd or and'd together, they
2738   // will get folded into a single comparison, so don't emit two blocks.
2739   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2740        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2741       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2742        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2743     return false;
2744   }
2745 
2746   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2747   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2748   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2749       Cases[0].CC == Cases[1].CC &&
2750       isa<Constant>(Cases[0].CmpRHS) &&
2751       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2752     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2753       return false;
2754     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2755       return false;
2756   }
2757 
2758   return true;
2759 }
2760 
2761 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2762   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2763 
2764   // Update machine-CFG edges.
2765   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2766 
2767   if (I.isUnconditional()) {
2768     // Update machine-CFG edges.
2769     BrMBB->addSuccessor(Succ0MBB);
2770 
2771     // If this is not a fall-through branch or optimizations are switched off,
2772     // emit the branch.
2773     if (Succ0MBB != NextBlock(BrMBB) ||
2774         TM.getOptLevel() == CodeGenOptLevel::None) {
2775       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2776                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2777       setValue(&I, Br);
2778       DAG.setRoot(Br);
2779     }
2780 
2781     return;
2782   }
2783 
2784   // If this condition is one of the special cases we handle, do special stuff
2785   // now.
2786   const Value *CondVal = I.getCondition();
2787   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2788 
2789   // If this is a series of conditions that are or'd or and'd together, emit
2790   // this as a sequence of branches instead of setcc's with and/or operations.
2791   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2792   // unpredictable branches, and vector extracts because those jumps are likely
2793   // expensive for any target), this should improve performance.
2794   // For example, instead of something like:
2795   //     cmp A, B
2796   //     C = seteq
2797   //     cmp D, E
2798   //     F = setle
2799   //     or C, F
2800   //     jnz foo
2801   // Emit:
2802   //     cmp A, B
2803   //     je foo
2804   //     cmp D, E
2805   //     jle foo
2806   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2807   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2808       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2809     Value *Vec;
2810     const Value *BOp0, *BOp1;
2811     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2812     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2813       Opcode = Instruction::And;
2814     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2815       Opcode = Instruction::Or;
2816 
2817     if (Opcode &&
2818         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2819           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2820         !shouldKeepJumpConditionsTogether(
2821             FuncInfo, I, Opcode, BOp0, BOp1,
2822             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2823                 Opcode, BOp0, BOp1))) {
2824       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2825                            getEdgeProbability(BrMBB, Succ0MBB),
2826                            getEdgeProbability(BrMBB, Succ1MBB),
2827                            /*InvertCond=*/false);
2828       // If the compares in later blocks need to use values not currently
2829       // exported from this block, export them now.  This block should always
2830       // be the first entry.
2831       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2832 
2833       // Allow some cases to be rejected.
2834       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2835         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2836           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2837           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2838         }
2839 
2840         // Emit the branch for this block.
2841         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2842         SL->SwitchCases.erase(SL->SwitchCases.begin());
2843         return;
2844       }
2845 
2846       // Okay, we decided not to do this, remove any inserted MBB's and clear
2847       // SwitchCases.
2848       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2849         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2850 
2851       SL->SwitchCases.clear();
2852     }
2853   }
2854 
2855   // Create a CaseBlock record representing this branch.
2856   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2857                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2858 
2859   // Use visitSwitchCase to actually insert the fast branch sequence for this
2860   // cond branch.
2861   visitSwitchCase(CB, BrMBB);
2862 }
2863 
2864 /// visitSwitchCase - Emits the necessary code to represent a single node in
2865 /// the binary search tree resulting from lowering a switch instruction.
2866 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2867                                           MachineBasicBlock *SwitchBB) {
2868   SDValue Cond;
2869   SDValue CondLHS = getValue(CB.CmpLHS);
2870   SDLoc dl = CB.DL;
2871 
2872   if (CB.CC == ISD::SETTRUE) {
2873     // Branch or fall through to TrueBB.
2874     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2875     SwitchBB->normalizeSuccProbs();
2876     if (CB.TrueBB != NextBlock(SwitchBB)) {
2877       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2878                               DAG.getBasicBlock(CB.TrueBB)));
2879     }
2880     return;
2881   }
2882 
2883   auto &TLI = DAG.getTargetLoweringInfo();
2884   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2885 
2886   // Build the setcc now.
2887   if (!CB.CmpMHS) {
2888     // Fold "(X == true)" to X and "(X == false)" to !X to
2889     // handle common cases produced by branch lowering.
2890     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2891         CB.CC == ISD::SETEQ)
2892       Cond = CondLHS;
2893     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2894              CB.CC == ISD::SETEQ) {
2895       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2896       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2897     } else {
2898       SDValue CondRHS = getValue(CB.CmpRHS);
2899 
2900       // If a pointer's DAG type is larger than its memory type then the DAG
2901       // values are zero-extended. This breaks signed comparisons so truncate
2902       // back to the underlying type before doing the compare.
2903       if (CondLHS.getValueType() != MemVT) {
2904         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2905         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2906       }
2907       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2908     }
2909   } else {
2910     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2911 
2912     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2913     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2914 
2915     SDValue CmpOp = getValue(CB.CmpMHS);
2916     EVT VT = CmpOp.getValueType();
2917 
2918     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2919       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2920                           ISD::SETLE);
2921     } else {
2922       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2923                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2924       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2925                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2926     }
2927   }
2928 
2929   // Update successor info
2930   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2931   // TrueBB and FalseBB are always different unless the incoming IR is
2932   // degenerate. This only happens when running llc on weird IR.
2933   if (CB.TrueBB != CB.FalseBB)
2934     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2935   SwitchBB->normalizeSuccProbs();
2936 
2937   // If the lhs block is the next block, invert the condition so that we can
2938   // fall through to the lhs instead of the rhs block.
2939   if (CB.TrueBB == NextBlock(SwitchBB)) {
2940     std::swap(CB.TrueBB, CB.FalseBB);
2941     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2942     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2943   }
2944 
2945   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2946                                MVT::Other, getControlRoot(), Cond,
2947                                DAG.getBasicBlock(CB.TrueBB));
2948 
2949   setValue(CurInst, BrCond);
2950 
2951   // Insert the false branch. Do this even if it's a fall through branch,
2952   // this makes it easier to do DAG optimizations which require inverting
2953   // the branch condition.
2954   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2955                        DAG.getBasicBlock(CB.FalseBB));
2956 
2957   DAG.setRoot(BrCond);
2958 }
2959 
2960 /// visitJumpTable - Emit JumpTable node in the current MBB
2961 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2962   // Emit the code for the jump table
2963   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2964   assert(JT.Reg != -1U && "Should lower JT Header first!");
2965   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2966   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2967   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2968   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2969                                     Index.getValue(1), Table, Index);
2970   DAG.setRoot(BrJumpTable);
2971 }
2972 
2973 /// visitJumpTableHeader - This function emits necessary code to produce index
2974 /// in the JumpTable from switch case.
2975 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2976                                                JumpTableHeader &JTH,
2977                                                MachineBasicBlock *SwitchBB) {
2978   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2979   const SDLoc &dl = *JT.SL;
2980 
2981   // Subtract the lowest switch case value from the value being switched on.
2982   SDValue SwitchOp = getValue(JTH.SValue);
2983   EVT VT = SwitchOp.getValueType();
2984   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2985                             DAG.getConstant(JTH.First, dl, VT));
2986 
2987   // The SDNode we just created, which holds the value being switched on minus
2988   // the smallest case value, needs to be copied to a virtual register so it
2989   // can be used as an index into the jump table in a subsequent basic block.
2990   // This value may be smaller or larger than the target's pointer type, and
2991   // therefore require extension or truncating.
2992   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2993   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2994 
2995   unsigned JumpTableReg =
2996       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2997   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2998                                     JumpTableReg, SwitchOp);
2999   JT.Reg = JumpTableReg;
3000 
3001   if (!JTH.FallthroughUnreachable) {
3002     // Emit the range check for the jump table, and branch to the default block
3003     // for the switch statement if the value being switched on exceeds the
3004     // largest case in the switch.
3005     SDValue CMP = DAG.getSetCC(
3006         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3007                                    Sub.getValueType()),
3008         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3009 
3010     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3011                                  MVT::Other, CopyTo, CMP,
3012                                  DAG.getBasicBlock(JT.Default));
3013 
3014     // Avoid emitting unnecessary branches to the next block.
3015     if (JT.MBB != NextBlock(SwitchBB))
3016       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3017                            DAG.getBasicBlock(JT.MBB));
3018 
3019     DAG.setRoot(BrCond);
3020   } else {
3021     // Avoid emitting unnecessary branches to the next block.
3022     if (JT.MBB != NextBlock(SwitchBB))
3023       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3024                               DAG.getBasicBlock(JT.MBB)));
3025     else
3026       DAG.setRoot(CopyTo);
3027   }
3028 }
3029 
3030 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3031 /// variable if there exists one.
3032 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3033                                  SDValue &Chain) {
3034   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3035   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3036   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3037   MachineFunction &MF = DAG.getMachineFunction();
3038   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3039   MachineSDNode *Node =
3040       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3041   if (Global) {
3042     MachinePointerInfo MPInfo(Global);
3043     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3044                  MachineMemOperand::MODereferenceable;
3045     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3046         MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8),
3047         DAG.getEVTAlign(PtrTy));
3048     DAG.setNodeMemRefs(Node, {MemRef});
3049   }
3050   if (PtrTy != PtrMemTy)
3051     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3052   return SDValue(Node, 0);
3053 }
3054 
3055 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3056 /// tail spliced into a stack protector check success bb.
3057 ///
3058 /// For a high level explanation of how this fits into the stack protector
3059 /// generation see the comment on the declaration of class
3060 /// StackProtectorDescriptor.
3061 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3062                                                   MachineBasicBlock *ParentBB) {
3063 
3064   // First create the loads to the guard/stack slot for the comparison.
3065   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3066   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3067   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3068 
3069   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3070   int FI = MFI.getStackProtectorIndex();
3071 
3072   SDValue Guard;
3073   SDLoc dl = getCurSDLoc();
3074   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3075   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3076   Align Align =
3077       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3078 
3079   // Generate code to load the content of the guard slot.
3080   SDValue GuardVal = DAG.getLoad(
3081       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3082       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3083       MachineMemOperand::MOVolatile);
3084 
3085   if (TLI.useStackGuardXorFP())
3086     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3087 
3088   // Retrieve guard check function, nullptr if instrumentation is inlined.
3089   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3090     // The target provides a guard check function to validate the guard value.
3091     // Generate a call to that function with the content of the guard slot as
3092     // argument.
3093     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3094     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3095 
3096     TargetLowering::ArgListTy Args;
3097     TargetLowering::ArgListEntry Entry;
3098     Entry.Node = GuardVal;
3099     Entry.Ty = FnTy->getParamType(0);
3100     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3101       Entry.IsInReg = true;
3102     Args.push_back(Entry);
3103 
3104     TargetLowering::CallLoweringInfo CLI(DAG);
3105     CLI.setDebugLoc(getCurSDLoc())
3106         .setChain(DAG.getEntryNode())
3107         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3108                    getValue(GuardCheckFn), std::move(Args));
3109 
3110     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3111     DAG.setRoot(Result.second);
3112     return;
3113   }
3114 
3115   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3116   // Otherwise, emit a volatile load to retrieve the stack guard value.
3117   SDValue Chain = DAG.getEntryNode();
3118   if (TLI.useLoadStackGuardNode()) {
3119     Guard = getLoadStackGuard(DAG, dl, Chain);
3120   } else {
3121     const Value *IRGuard = TLI.getSDagStackGuard(M);
3122     SDValue GuardPtr = getValue(IRGuard);
3123 
3124     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3125                         MachinePointerInfo(IRGuard, 0), Align,
3126                         MachineMemOperand::MOVolatile);
3127   }
3128 
3129   // Perform the comparison via a getsetcc.
3130   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3131                                                         *DAG.getContext(),
3132                                                         Guard.getValueType()),
3133                              Guard, GuardVal, ISD::SETNE);
3134 
3135   // If the guard/stackslot do not equal, branch to failure MBB.
3136   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3137                                MVT::Other, GuardVal.getOperand(0),
3138                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3139   // Otherwise branch to success MBB.
3140   SDValue Br = DAG.getNode(ISD::BR, dl,
3141                            MVT::Other, BrCond,
3142                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3143 
3144   DAG.setRoot(Br);
3145 }
3146 
3147 /// Codegen the failure basic block for a stack protector check.
3148 ///
3149 /// A failure stack protector machine basic block consists simply of a call to
3150 /// __stack_chk_fail().
3151 ///
3152 /// For a high level explanation of how this fits into the stack protector
3153 /// generation see the comment on the declaration of class
3154 /// StackProtectorDescriptor.
3155 void
3156 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3157   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3158   TargetLowering::MakeLibCallOptions CallOptions;
3159   CallOptions.setDiscardResult(true);
3160   SDValue Chain =
3161       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3162                       std::nullopt, CallOptions, getCurSDLoc())
3163           .second;
3164   // On PS4/PS5, the "return address" must still be within the calling
3165   // function, even if it's at the very end, so emit an explicit TRAP here.
3166   // Passing 'true' for doesNotReturn above won't generate the trap for us.
3167   if (TM.getTargetTriple().isPS())
3168     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3169   // WebAssembly needs an unreachable instruction after a non-returning call,
3170   // because the function return type can be different from __stack_chk_fail's
3171   // return type (void).
3172   if (TM.getTargetTriple().isWasm())
3173     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3174 
3175   DAG.setRoot(Chain);
3176 }
3177 
3178 /// visitBitTestHeader - This function emits necessary code to produce value
3179 /// suitable for "bit tests"
3180 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3181                                              MachineBasicBlock *SwitchBB) {
3182   SDLoc dl = getCurSDLoc();
3183 
3184   // Subtract the minimum value.
3185   SDValue SwitchOp = getValue(B.SValue);
3186   EVT VT = SwitchOp.getValueType();
3187   SDValue RangeSub =
3188       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3189 
3190   // Determine the type of the test operands.
3191   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3192   bool UsePtrType = false;
3193   if (!TLI.isTypeLegal(VT)) {
3194     UsePtrType = true;
3195   } else {
3196     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3197       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3198         // Switch table case range are encoded into series of masks.
3199         // Just use pointer type, it's guaranteed to fit.
3200         UsePtrType = true;
3201         break;
3202       }
3203   }
3204   SDValue Sub = RangeSub;
3205   if (UsePtrType) {
3206     VT = TLI.getPointerTy(DAG.getDataLayout());
3207     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3208   }
3209 
3210   B.RegVT = VT.getSimpleVT();
3211   B.Reg = FuncInfo.CreateReg(B.RegVT);
3212   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3213 
3214   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3215 
3216   if (!B.FallthroughUnreachable)
3217     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3218   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3219   SwitchBB->normalizeSuccProbs();
3220 
3221   SDValue Root = CopyTo;
3222   if (!B.FallthroughUnreachable) {
3223     // Conditional branch to the default block.
3224     SDValue RangeCmp = DAG.getSetCC(dl,
3225         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3226                                RangeSub.getValueType()),
3227         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3228         ISD::SETUGT);
3229 
3230     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3231                        DAG.getBasicBlock(B.Default));
3232   }
3233 
3234   // Avoid emitting unnecessary branches to the next block.
3235   if (MBB != NextBlock(SwitchBB))
3236     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3237 
3238   DAG.setRoot(Root);
3239 }
3240 
3241 /// visitBitTestCase - this function produces one "bit test"
3242 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3243                                            MachineBasicBlock* NextMBB,
3244                                            BranchProbability BranchProbToNext,
3245                                            unsigned Reg,
3246                                            BitTestCase &B,
3247                                            MachineBasicBlock *SwitchBB) {
3248   SDLoc dl = getCurSDLoc();
3249   MVT VT = BB.RegVT;
3250   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3251   SDValue Cmp;
3252   unsigned PopCount = llvm::popcount(B.Mask);
3253   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3254   if (PopCount == 1) {
3255     // Testing for a single bit; just compare the shift count with what it
3256     // would need to be to shift a 1 bit in that position.
3257     Cmp = DAG.getSetCC(
3258         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3259         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3260         ISD::SETEQ);
3261   } else if (PopCount == BB.Range) {
3262     // There is only one zero bit in the range, test for it directly.
3263     Cmp = DAG.getSetCC(
3264         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3265         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3266   } else {
3267     // Make desired shift
3268     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3269                                     DAG.getConstant(1, dl, VT), ShiftOp);
3270 
3271     // Emit bit tests and jumps
3272     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3273                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3274     Cmp = DAG.getSetCC(
3275         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3276         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3277   }
3278 
3279   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3280   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3281   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3282   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3283   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3284   // one as they are relative probabilities (and thus work more like weights),
3285   // and hence we need to normalize them to let the sum of them become one.
3286   SwitchBB->normalizeSuccProbs();
3287 
3288   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3289                               MVT::Other, getControlRoot(),
3290                               Cmp, DAG.getBasicBlock(B.TargetBB));
3291 
3292   // Avoid emitting unnecessary branches to the next block.
3293   if (NextMBB != NextBlock(SwitchBB))
3294     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3295                         DAG.getBasicBlock(NextMBB));
3296 
3297   DAG.setRoot(BrAnd);
3298 }
3299 
3300 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3301   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3302 
3303   // Retrieve successors. Look through artificial IR level blocks like
3304   // catchswitch for successors.
3305   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
3306   const BasicBlock *EHPadBB = I.getSuccessor(1);
3307   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
3308 
3309   // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3310   // have to do anything here to lower funclet bundles.
3311   assert(!I.hasOperandBundlesOtherThan(
3312              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3313               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3314               LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3315               LLVMContext::OB_clang_arc_attachedcall}) &&
3316          "Cannot lower invokes with arbitrary operand bundles yet!");
3317 
3318   const Value *Callee(I.getCalledOperand());
3319   const Function *Fn = dyn_cast<Function>(Callee);
3320   if (isa<InlineAsm>(Callee))
3321     visitInlineAsm(I, EHPadBB);
3322   else if (Fn && Fn->isIntrinsic()) {
3323     switch (Fn->getIntrinsicID()) {
3324     default:
3325       llvm_unreachable("Cannot invoke this intrinsic");
3326     case Intrinsic::donothing:
3327       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3328     case Intrinsic::seh_try_begin:
3329     case Intrinsic::seh_scope_begin:
3330     case Intrinsic::seh_try_end:
3331     case Intrinsic::seh_scope_end:
3332       if (EHPadMBB)
3333           // a block referenced by EH table
3334           // so dtor-funclet not removed by opts
3335           EHPadMBB->setMachineBlockAddressTaken();
3336       break;
3337     case Intrinsic::experimental_patchpoint_void:
3338     case Intrinsic::experimental_patchpoint:
3339       visitPatchpoint(I, EHPadBB);
3340       break;
3341     case Intrinsic::experimental_gc_statepoint:
3342       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3343       break;
3344     case Intrinsic::wasm_rethrow: {
3345       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3346       // special because it can be invoked, so we manually lower it to a DAG
3347       // node here.
3348       SmallVector<SDValue, 8> Ops;
3349       Ops.push_back(getRoot()); // inchain
3350       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3351       Ops.push_back(
3352           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3353                                 TLI.getPointerTy(DAG.getDataLayout())));
3354       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3355       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3356       break;
3357     }
3358     }
3359   } else if (I.hasDeoptState()) {
3360     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3361     // Eventually we will support lowering the @llvm.experimental.deoptimize
3362     // intrinsic, and right now there are no plans to support other intrinsics
3363     // with deopt state.
3364     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3365   } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3366     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB);
3367   } else {
3368     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3369   }
3370 
3371   // If the value of the invoke is used outside of its defining block, make it
3372   // available as a virtual register.
3373   // We already took care of the exported value for the statepoint instruction
3374   // during call to the LowerStatepoint.
3375   if (!isa<GCStatepointInst>(I)) {
3376     CopyToExportRegsIfNeeded(&I);
3377   }
3378 
3379   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3380   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3381   BranchProbability EHPadBBProb =
3382       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3383           : BranchProbability::getZero();
3384   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3385 
3386   // Update successor info.
3387   addSuccessorWithProb(InvokeMBB, Return);
3388   for (auto &UnwindDest : UnwindDests) {
3389     UnwindDest.first->setIsEHPad();
3390     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3391   }
3392   InvokeMBB->normalizeSuccProbs();
3393 
3394   // Drop into normal successor.
3395   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3396                           DAG.getBasicBlock(Return)));
3397 }
3398 
3399 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3400   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3401 
3402   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3403   // have to do anything here to lower funclet bundles.
3404   assert(!I.hasOperandBundlesOtherThan(
3405              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3406          "Cannot lower callbrs with arbitrary operand bundles yet!");
3407 
3408   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3409   visitInlineAsm(I);
3410   CopyToExportRegsIfNeeded(&I);
3411 
3412   // Retrieve successors.
3413   SmallPtrSet<BasicBlock *, 8> Dests;
3414   Dests.insert(I.getDefaultDest());
3415   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3416 
3417   // Update successor info.
3418   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3419   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3420     BasicBlock *Dest = I.getIndirectDest(i);
3421     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3422     Target->setIsInlineAsmBrIndirectTarget();
3423     Target->setMachineBlockAddressTaken();
3424     Target->setLabelMustBeEmitted();
3425     // Don't add duplicate machine successors.
3426     if (Dests.insert(Dest).second)
3427       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3428   }
3429   CallBrMBB->normalizeSuccProbs();
3430 
3431   // Drop into default successor.
3432   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3433                           MVT::Other, getControlRoot(),
3434                           DAG.getBasicBlock(Return)));
3435 }
3436 
3437 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3438   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3439 }
3440 
3441 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3442   assert(FuncInfo.MBB->isEHPad() &&
3443          "Call to landingpad not in landing pad!");
3444 
3445   // If there aren't registers to copy the values into (e.g., during SjLj
3446   // exceptions), then don't bother to create these DAG nodes.
3447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3448   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3449   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3450       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3451     return;
3452 
3453   // If landingpad's return type is token type, we don't create DAG nodes
3454   // for its exception pointer and selector value. The extraction of exception
3455   // pointer or selector value from token type landingpads is not currently
3456   // supported.
3457   if (LP.getType()->isTokenTy())
3458     return;
3459 
3460   SmallVector<EVT, 2> ValueVTs;
3461   SDLoc dl = getCurSDLoc();
3462   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3463   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3464 
3465   // Get the two live-in registers as SDValues. The physregs have already been
3466   // copied into virtual registers.
3467   SDValue Ops[2];
3468   if (FuncInfo.ExceptionPointerVirtReg) {
3469     Ops[0] = DAG.getZExtOrTrunc(
3470         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3471                            FuncInfo.ExceptionPointerVirtReg,
3472                            TLI.getPointerTy(DAG.getDataLayout())),
3473         dl, ValueVTs[0]);
3474   } else {
3475     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3476   }
3477   Ops[1] = DAG.getZExtOrTrunc(
3478       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3479                          FuncInfo.ExceptionSelectorVirtReg,
3480                          TLI.getPointerTy(DAG.getDataLayout())),
3481       dl, ValueVTs[1]);
3482 
3483   // Merge into one.
3484   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3485                             DAG.getVTList(ValueVTs), Ops);
3486   setValue(&LP, Res);
3487 }
3488 
3489 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3490                                            MachineBasicBlock *Last) {
3491   // Update JTCases.
3492   for (JumpTableBlock &JTB : SL->JTCases)
3493     if (JTB.first.HeaderBB == First)
3494       JTB.first.HeaderBB = Last;
3495 
3496   // Update BitTestCases.
3497   for (BitTestBlock &BTB : SL->BitTestCases)
3498     if (BTB.Parent == First)
3499       BTB.Parent = Last;
3500 }
3501 
3502 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3503   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3504 
3505   // Update machine-CFG edges with unique successors.
3506   SmallSet<BasicBlock*, 32> Done;
3507   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3508     BasicBlock *BB = I.getSuccessor(i);
3509     bool Inserted = Done.insert(BB).second;
3510     if (!Inserted)
3511         continue;
3512 
3513     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3514     addSuccessorWithProb(IndirectBrMBB, Succ);
3515   }
3516   IndirectBrMBB->normalizeSuccProbs();
3517 
3518   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3519                           MVT::Other, getControlRoot(),
3520                           getValue(I.getAddress())));
3521 }
3522 
3523 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3524   if (!DAG.getTarget().Options.TrapUnreachable)
3525     return;
3526 
3527   // We may be able to ignore unreachable behind a noreturn call.
3528   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3529     if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) {
3530       if (Call->doesNotReturn())
3531         return;
3532     }
3533   }
3534 
3535   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3536 }
3537 
3538 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3539   SDNodeFlags Flags;
3540   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3541     Flags.copyFMF(*FPOp);
3542 
3543   SDValue Op = getValue(I.getOperand(0));
3544   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3545                                     Op, Flags);
3546   setValue(&I, UnNodeValue);
3547 }
3548 
3549 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3550   SDNodeFlags Flags;
3551   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3552     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3553     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3554   }
3555   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3556     Flags.setExact(ExactOp->isExact());
3557   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3558     Flags.setDisjoint(DisjointOp->isDisjoint());
3559   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3560     Flags.copyFMF(*FPOp);
3561 
3562   SDValue Op1 = getValue(I.getOperand(0));
3563   SDValue Op2 = getValue(I.getOperand(1));
3564   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3565                                      Op1, Op2, Flags);
3566   setValue(&I, BinNodeValue);
3567 }
3568 
3569 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3570   SDValue Op1 = getValue(I.getOperand(0));
3571   SDValue Op2 = getValue(I.getOperand(1));
3572 
3573   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3574       Op1.getValueType(), DAG.getDataLayout());
3575 
3576   // Coerce the shift amount to the right type if we can. This exposes the
3577   // truncate or zext to optimization early.
3578   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3579     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3580            "Unexpected shift type");
3581     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3582   }
3583 
3584   bool nuw = false;
3585   bool nsw = false;
3586   bool exact = false;
3587 
3588   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3589 
3590     if (const OverflowingBinaryOperator *OFBinOp =
3591             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3592       nuw = OFBinOp->hasNoUnsignedWrap();
3593       nsw = OFBinOp->hasNoSignedWrap();
3594     }
3595     if (const PossiblyExactOperator *ExactOp =
3596             dyn_cast<const PossiblyExactOperator>(&I))
3597       exact = ExactOp->isExact();
3598   }
3599   SDNodeFlags Flags;
3600   Flags.setExact(exact);
3601   Flags.setNoSignedWrap(nsw);
3602   Flags.setNoUnsignedWrap(nuw);
3603   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3604                             Flags);
3605   setValue(&I, Res);
3606 }
3607 
3608 void SelectionDAGBuilder::visitSDiv(const User &I) {
3609   SDValue Op1 = getValue(I.getOperand(0));
3610   SDValue Op2 = getValue(I.getOperand(1));
3611 
3612   SDNodeFlags Flags;
3613   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3614                  cast<PossiblyExactOperator>(&I)->isExact());
3615   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3616                            Op2, Flags));
3617 }
3618 
3619 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3620   ICmpInst::Predicate predicate = I.getPredicate();
3621   SDValue Op1 = getValue(I.getOperand(0));
3622   SDValue Op2 = getValue(I.getOperand(1));
3623   ISD::CondCode Opcode = getICmpCondCode(predicate);
3624 
3625   auto &TLI = DAG.getTargetLoweringInfo();
3626   EVT MemVT =
3627       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3628 
3629   // If a pointer's DAG type is larger than its memory type then the DAG values
3630   // are zero-extended. This breaks signed comparisons so truncate back to the
3631   // underlying type before doing the compare.
3632   if (Op1.getValueType() != MemVT) {
3633     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3634     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3635   }
3636 
3637   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3638                                                         I.getType());
3639   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3640 }
3641 
3642 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3643   FCmpInst::Predicate predicate = I.getPredicate();
3644   SDValue Op1 = getValue(I.getOperand(0));
3645   SDValue Op2 = getValue(I.getOperand(1));
3646 
3647   ISD::CondCode Condition = getFCmpCondCode(predicate);
3648   auto *FPMO = cast<FPMathOperator>(&I);
3649   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3650     Condition = getFCmpCodeWithoutNaN(Condition);
3651 
3652   SDNodeFlags Flags;
3653   Flags.copyFMF(*FPMO);
3654   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3655 
3656   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3657                                                         I.getType());
3658   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3659 }
3660 
3661 // Check if the condition of the select has one use or two users that are both
3662 // selects with the same condition.
3663 static bool hasOnlySelectUsers(const Value *Cond) {
3664   return llvm::all_of(Cond->users(), [](const Value *V) {
3665     return isa<SelectInst>(V);
3666   });
3667 }
3668 
3669 void SelectionDAGBuilder::visitSelect(const User &I) {
3670   SmallVector<EVT, 4> ValueVTs;
3671   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3672                   ValueVTs);
3673   unsigned NumValues = ValueVTs.size();
3674   if (NumValues == 0) return;
3675 
3676   SmallVector<SDValue, 4> Values(NumValues);
3677   SDValue Cond     = getValue(I.getOperand(0));
3678   SDValue LHSVal   = getValue(I.getOperand(1));
3679   SDValue RHSVal   = getValue(I.getOperand(2));
3680   SmallVector<SDValue, 1> BaseOps(1, Cond);
3681   ISD::NodeType OpCode =
3682       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3683 
3684   bool IsUnaryAbs = false;
3685   bool Negate = false;
3686 
3687   SDNodeFlags Flags;
3688   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3689     Flags.copyFMF(*FPOp);
3690 
3691   Flags.setUnpredictable(
3692       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3693 
3694   // Min/max matching is only viable if all output VTs are the same.
3695   if (all_equal(ValueVTs)) {
3696     EVT VT = ValueVTs[0];
3697     LLVMContext &Ctx = *DAG.getContext();
3698     auto &TLI = DAG.getTargetLoweringInfo();
3699 
3700     // We care about the legality of the operation after it has been type
3701     // legalized.
3702     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3703       VT = TLI.getTypeToTransformTo(Ctx, VT);
3704 
3705     // If the vselect is legal, assume we want to leave this as a vector setcc +
3706     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3707     // min/max is legal on the scalar type.
3708     bool UseScalarMinMax = VT.isVector() &&
3709       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3710 
3711     // ValueTracking's select pattern matching does not account for -0.0,
3712     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3713     // -0.0 is less than +0.0.
3714     Value *LHS, *RHS;
3715     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3716     ISD::NodeType Opc = ISD::DELETED_NODE;
3717     switch (SPR.Flavor) {
3718     case SPF_UMAX:    Opc = ISD::UMAX; break;
3719     case SPF_UMIN:    Opc = ISD::UMIN; break;
3720     case SPF_SMAX:    Opc = ISD::SMAX; break;
3721     case SPF_SMIN:    Opc = ISD::SMIN; break;
3722     case SPF_FMINNUM:
3723       switch (SPR.NaNBehavior) {
3724       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3725       case SPNB_RETURNS_NAN: break;
3726       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3727       case SPNB_RETURNS_ANY:
3728         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3729             (UseScalarMinMax &&
3730              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3731           Opc = ISD::FMINNUM;
3732         break;
3733       }
3734       break;
3735     case SPF_FMAXNUM:
3736       switch (SPR.NaNBehavior) {
3737       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3738       case SPNB_RETURNS_NAN: break;
3739       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3740       case SPNB_RETURNS_ANY:
3741         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3742             (UseScalarMinMax &&
3743              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3744           Opc = ISD::FMAXNUM;
3745         break;
3746       }
3747       break;
3748     case SPF_NABS:
3749       Negate = true;
3750       [[fallthrough]];
3751     case SPF_ABS:
3752       IsUnaryAbs = true;
3753       Opc = ISD::ABS;
3754       break;
3755     default: break;
3756     }
3757 
3758     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3759         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3760          (UseScalarMinMax &&
3761           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3762         // If the underlying comparison instruction is used by any other
3763         // instruction, the consumed instructions won't be destroyed, so it is
3764         // not profitable to convert to a min/max.
3765         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3766       OpCode = Opc;
3767       LHSVal = getValue(LHS);
3768       RHSVal = getValue(RHS);
3769       BaseOps.clear();
3770     }
3771 
3772     if (IsUnaryAbs) {
3773       OpCode = Opc;
3774       LHSVal = getValue(LHS);
3775       BaseOps.clear();
3776     }
3777   }
3778 
3779   if (IsUnaryAbs) {
3780     for (unsigned i = 0; i != NumValues; ++i) {
3781       SDLoc dl = getCurSDLoc();
3782       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3783       Values[i] =
3784           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3785       if (Negate)
3786         Values[i] = DAG.getNegative(Values[i], dl, VT);
3787     }
3788   } else {
3789     for (unsigned i = 0; i != NumValues; ++i) {
3790       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3791       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3792       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3793       Values[i] = DAG.getNode(
3794           OpCode, getCurSDLoc(),
3795           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3796     }
3797   }
3798 
3799   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3800                            DAG.getVTList(ValueVTs), Values));
3801 }
3802 
3803 void SelectionDAGBuilder::visitTrunc(const User &I) {
3804   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3805   SDValue N = getValue(I.getOperand(0));
3806   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3807                                                         I.getType());
3808   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3809 }
3810 
3811 void SelectionDAGBuilder::visitZExt(const User &I) {
3812   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3813   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3814   SDValue N = getValue(I.getOperand(0));
3815   auto &TLI = DAG.getTargetLoweringInfo();
3816   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3817 
3818   SDNodeFlags Flags;
3819   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3820     Flags.setNonNeg(PNI->hasNonNeg());
3821 
3822   // Eagerly use nonneg information to canonicalize towards sign_extend if
3823   // that is the target's preference.
3824   // TODO: Let the target do this later.
3825   if (Flags.hasNonNeg() &&
3826       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3827     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3828     return;
3829   }
3830 
3831   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3832 }
3833 
3834 void SelectionDAGBuilder::visitSExt(const User &I) {
3835   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3836   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3837   SDValue N = getValue(I.getOperand(0));
3838   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3839                                                         I.getType());
3840   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3841 }
3842 
3843 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3844   // FPTrunc is never a no-op cast, no need to check
3845   SDValue N = getValue(I.getOperand(0));
3846   SDLoc dl = getCurSDLoc();
3847   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3848   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3849   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3850                            DAG.getTargetConstant(
3851                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3852 }
3853 
3854 void SelectionDAGBuilder::visitFPExt(const User &I) {
3855   // FPExt is never a no-op cast, no need to check
3856   SDValue N = getValue(I.getOperand(0));
3857   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3858                                                         I.getType());
3859   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3860 }
3861 
3862 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3863   // FPToUI is never a no-op cast, no need to check
3864   SDValue N = getValue(I.getOperand(0));
3865   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3866                                                         I.getType());
3867   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3868 }
3869 
3870 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3871   // FPToSI is never a no-op cast, no need to check
3872   SDValue N = getValue(I.getOperand(0));
3873   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3874                                                         I.getType());
3875   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3876 }
3877 
3878 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3879   // UIToFP is never a no-op cast, no need to check
3880   SDValue N = getValue(I.getOperand(0));
3881   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3882                                                         I.getType());
3883   SDNodeFlags Flags;
3884   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3885     Flags.setNonNeg(PNI->hasNonNeg());
3886 
3887   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
3888 }
3889 
3890 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3891   // SIToFP is never a no-op cast, no need to check
3892   SDValue N = getValue(I.getOperand(0));
3893   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3894                                                         I.getType());
3895   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3896 }
3897 
3898 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3899   // What to do depends on the size of the integer and the size of the pointer.
3900   // We can either truncate, zero extend, or no-op, accordingly.
3901   SDValue N = getValue(I.getOperand(0));
3902   auto &TLI = DAG.getTargetLoweringInfo();
3903   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3904                                                         I.getType());
3905   EVT PtrMemVT =
3906       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3907   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3908   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3909   setValue(&I, N);
3910 }
3911 
3912 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3913   // What to do depends on the size of the integer and the size of the pointer.
3914   // We can either truncate, zero extend, or no-op, accordingly.
3915   SDValue N = getValue(I.getOperand(0));
3916   auto &TLI = DAG.getTargetLoweringInfo();
3917   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3918   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3919   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3920   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3921   setValue(&I, N);
3922 }
3923 
3924 void SelectionDAGBuilder::visitBitCast(const User &I) {
3925   SDValue N = getValue(I.getOperand(0));
3926   SDLoc dl = getCurSDLoc();
3927   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3928                                                         I.getType());
3929 
3930   // BitCast assures us that source and destination are the same size so this is
3931   // either a BITCAST or a no-op.
3932   if (DestVT != N.getValueType())
3933     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3934                              DestVT, N)); // convert types.
3935   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3936   // might fold any kind of constant expression to an integer constant and that
3937   // is not what we are looking for. Only recognize a bitcast of a genuine
3938   // constant integer as an opaque constant.
3939   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3940     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3941                                  /*isOpaque*/true));
3942   else
3943     setValue(&I, N);            // noop cast.
3944 }
3945 
3946 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3947   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3948   const Value *SV = I.getOperand(0);
3949   SDValue N = getValue(SV);
3950   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3951 
3952   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3953   unsigned DestAS = I.getType()->getPointerAddressSpace();
3954 
3955   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3956     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3957 
3958   setValue(&I, N);
3959 }
3960 
3961 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3962   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3963   SDValue InVec = getValue(I.getOperand(0));
3964   SDValue InVal = getValue(I.getOperand(1));
3965   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3966                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3967   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3968                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3969                            InVec, InVal, InIdx));
3970 }
3971 
3972 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3973   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3974   SDValue InVec = getValue(I.getOperand(0));
3975   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3976                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3977   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3978                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3979                            InVec, InIdx));
3980 }
3981 
3982 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3983   SDValue Src1 = getValue(I.getOperand(0));
3984   SDValue Src2 = getValue(I.getOperand(1));
3985   ArrayRef<int> Mask;
3986   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3987     Mask = SVI->getShuffleMask();
3988   else
3989     Mask = cast<ConstantExpr>(I).getShuffleMask();
3990   SDLoc DL = getCurSDLoc();
3991   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3992   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3993   EVT SrcVT = Src1.getValueType();
3994 
3995   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3996       VT.isScalableVector()) {
3997     // Canonical splat form of first element of first input vector.
3998     SDValue FirstElt =
3999         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4000                     DAG.getVectorIdxConstant(0, DL));
4001     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4002     return;
4003   }
4004 
4005   // For now, we only handle splats for scalable vectors.
4006   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4007   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4008   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4009 
4010   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4011   unsigned MaskNumElts = Mask.size();
4012 
4013   if (SrcNumElts == MaskNumElts) {
4014     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4015     return;
4016   }
4017 
4018   // Normalize the shuffle vector since mask and vector length don't match.
4019   if (SrcNumElts < MaskNumElts) {
4020     // Mask is longer than the source vectors. We can use concatenate vector to
4021     // make the mask and vectors lengths match.
4022 
4023     if (MaskNumElts % SrcNumElts == 0) {
4024       // Mask length is a multiple of the source vector length.
4025       // Check if the shuffle is some kind of concatenation of the input
4026       // vectors.
4027       unsigned NumConcat = MaskNumElts / SrcNumElts;
4028       bool IsConcat = true;
4029       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4030       for (unsigned i = 0; i != MaskNumElts; ++i) {
4031         int Idx = Mask[i];
4032         if (Idx < 0)
4033           continue;
4034         // Ensure the indices in each SrcVT sized piece are sequential and that
4035         // the same source is used for the whole piece.
4036         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4037             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4038              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4039           IsConcat = false;
4040           break;
4041         }
4042         // Remember which source this index came from.
4043         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4044       }
4045 
4046       // The shuffle is concatenating multiple vectors together. Just emit
4047       // a CONCAT_VECTORS operation.
4048       if (IsConcat) {
4049         SmallVector<SDValue, 8> ConcatOps;
4050         for (auto Src : ConcatSrcs) {
4051           if (Src < 0)
4052             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4053           else if (Src == 0)
4054             ConcatOps.push_back(Src1);
4055           else
4056             ConcatOps.push_back(Src2);
4057         }
4058         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4059         return;
4060       }
4061     }
4062 
4063     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4064     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4065     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4066                                     PaddedMaskNumElts);
4067 
4068     // Pad both vectors with undefs to make them the same length as the mask.
4069     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4070 
4071     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4072     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4073     MOps1[0] = Src1;
4074     MOps2[0] = Src2;
4075 
4076     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4077     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4078 
4079     // Readjust mask for new input vector length.
4080     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4081     for (unsigned i = 0; i != MaskNumElts; ++i) {
4082       int Idx = Mask[i];
4083       if (Idx >= (int)SrcNumElts)
4084         Idx -= SrcNumElts - PaddedMaskNumElts;
4085       MappedOps[i] = Idx;
4086     }
4087 
4088     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4089 
4090     // If the concatenated vector was padded, extract a subvector with the
4091     // correct number of elements.
4092     if (MaskNumElts != PaddedMaskNumElts)
4093       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4094                            DAG.getVectorIdxConstant(0, DL));
4095 
4096     setValue(&I, Result);
4097     return;
4098   }
4099 
4100   if (SrcNumElts > MaskNumElts) {
4101     // Analyze the access pattern of the vector to see if we can extract
4102     // two subvectors and do the shuffle.
4103     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
4104     bool CanExtract = true;
4105     for (int Idx : Mask) {
4106       unsigned Input = 0;
4107       if (Idx < 0)
4108         continue;
4109 
4110       if (Idx >= (int)SrcNumElts) {
4111         Input = 1;
4112         Idx -= SrcNumElts;
4113       }
4114 
4115       // If all the indices come from the same MaskNumElts sized portion of
4116       // the sources we can use extract. Also make sure the extract wouldn't
4117       // extract past the end of the source.
4118       int NewStartIdx = alignDown(Idx, MaskNumElts);
4119       if (NewStartIdx + MaskNumElts > SrcNumElts ||
4120           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4121         CanExtract = false;
4122       // Make sure we always update StartIdx as we use it to track if all
4123       // elements are undef.
4124       StartIdx[Input] = NewStartIdx;
4125     }
4126 
4127     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4128       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4129       return;
4130     }
4131     if (CanExtract) {
4132       // Extract appropriate subvector and generate a vector shuffle
4133       for (unsigned Input = 0; Input < 2; ++Input) {
4134         SDValue &Src = Input == 0 ? Src1 : Src2;
4135         if (StartIdx[Input] < 0)
4136           Src = DAG.getUNDEF(VT);
4137         else {
4138           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4139                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
4140         }
4141       }
4142 
4143       // Calculate new mask.
4144       SmallVector<int, 8> MappedOps(Mask);
4145       for (int &Idx : MappedOps) {
4146         if (Idx >= (int)SrcNumElts)
4147           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4148         else if (Idx >= 0)
4149           Idx -= StartIdx[0];
4150       }
4151 
4152       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4153       return;
4154     }
4155   }
4156 
4157   // We can't use either concat vectors or extract subvectors so fall back to
4158   // replacing the shuffle with extract and build vector.
4159   // to insert and build vector.
4160   EVT EltVT = VT.getVectorElementType();
4161   SmallVector<SDValue,8> Ops;
4162   for (int Idx : Mask) {
4163     SDValue Res;
4164 
4165     if (Idx < 0) {
4166       Res = DAG.getUNDEF(EltVT);
4167     } else {
4168       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4169       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4170 
4171       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4172                         DAG.getVectorIdxConstant(Idx, DL));
4173     }
4174 
4175     Ops.push_back(Res);
4176   }
4177 
4178   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4179 }
4180 
4181 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4182   ArrayRef<unsigned> Indices = I.getIndices();
4183   const Value *Op0 = I.getOperand(0);
4184   const Value *Op1 = I.getOperand(1);
4185   Type *AggTy = I.getType();
4186   Type *ValTy = Op1->getType();
4187   bool IntoUndef = isa<UndefValue>(Op0);
4188   bool FromUndef = isa<UndefValue>(Op1);
4189 
4190   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4191 
4192   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4193   SmallVector<EVT, 4> AggValueVTs;
4194   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4195   SmallVector<EVT, 4> ValValueVTs;
4196   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4197 
4198   unsigned NumAggValues = AggValueVTs.size();
4199   unsigned NumValValues = ValValueVTs.size();
4200   SmallVector<SDValue, 4> Values(NumAggValues);
4201 
4202   // Ignore an insertvalue that produces an empty object
4203   if (!NumAggValues) {
4204     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4205     return;
4206   }
4207 
4208   SDValue Agg = getValue(Op0);
4209   unsigned i = 0;
4210   // Copy the beginning value(s) from the original aggregate.
4211   for (; i != LinearIndex; ++i)
4212     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4213                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4214   // Copy values from the inserted value(s).
4215   if (NumValValues) {
4216     SDValue Val = getValue(Op1);
4217     for (; i != LinearIndex + NumValValues; ++i)
4218       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4219                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4220   }
4221   // Copy remaining value(s) from the original aggregate.
4222   for (; i != NumAggValues; ++i)
4223     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4224                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4225 
4226   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4227                            DAG.getVTList(AggValueVTs), Values));
4228 }
4229 
4230 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4231   ArrayRef<unsigned> Indices = I.getIndices();
4232   const Value *Op0 = I.getOperand(0);
4233   Type *AggTy = Op0->getType();
4234   Type *ValTy = I.getType();
4235   bool OutOfUndef = isa<UndefValue>(Op0);
4236 
4237   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4238 
4239   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4240   SmallVector<EVT, 4> ValValueVTs;
4241   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4242 
4243   unsigned NumValValues = ValValueVTs.size();
4244 
4245   // Ignore a extractvalue that produces an empty object
4246   if (!NumValValues) {
4247     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4248     return;
4249   }
4250 
4251   SmallVector<SDValue, 4> Values(NumValValues);
4252 
4253   SDValue Agg = getValue(Op0);
4254   // Copy out the selected value(s).
4255   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4256     Values[i - LinearIndex] =
4257       OutOfUndef ?
4258         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4259         SDValue(Agg.getNode(), Agg.getResNo() + i);
4260 
4261   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4262                            DAG.getVTList(ValValueVTs), Values));
4263 }
4264 
4265 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4266   Value *Op0 = I.getOperand(0);
4267   // Note that the pointer operand may be a vector of pointers. Take the scalar
4268   // element which holds a pointer.
4269   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4270   SDValue N = getValue(Op0);
4271   SDLoc dl = getCurSDLoc();
4272   auto &TLI = DAG.getTargetLoweringInfo();
4273 
4274   // Normalize Vector GEP - all scalar operands should be converted to the
4275   // splat vector.
4276   bool IsVectorGEP = I.getType()->isVectorTy();
4277   ElementCount VectorElementCount =
4278       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4279                   : ElementCount::getFixed(0);
4280 
4281   if (IsVectorGEP && !N.getValueType().isVector()) {
4282     LLVMContext &Context = *DAG.getContext();
4283     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4284     N = DAG.getSplat(VT, dl, N);
4285   }
4286 
4287   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4288        GTI != E; ++GTI) {
4289     const Value *Idx = GTI.getOperand();
4290     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4291       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4292       if (Field) {
4293         // N = N + Offset
4294         uint64_t Offset =
4295             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4296 
4297         // In an inbounds GEP with an offset that is nonnegative even when
4298         // interpreted as signed, assume there is no unsigned overflow.
4299         SDNodeFlags Flags;
4300         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
4301           Flags.setNoUnsignedWrap(true);
4302 
4303         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4304                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4305       }
4306     } else {
4307       // IdxSize is the width of the arithmetic according to IR semantics.
4308       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4309       // (and fix up the result later).
4310       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4311       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4312       TypeSize ElementSize =
4313           GTI.getSequentialElementStride(DAG.getDataLayout());
4314       // We intentionally mask away the high bits here; ElementSize may not
4315       // fit in IdxTy.
4316       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4317       bool ElementScalable = ElementSize.isScalable();
4318 
4319       // If this is a scalar constant or a splat vector of constants,
4320       // handle it quickly.
4321       const auto *C = dyn_cast<Constant>(Idx);
4322       if (C && isa<VectorType>(C->getType()))
4323         C = C->getSplatValue();
4324 
4325       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4326       if (CI && CI->isZero())
4327         continue;
4328       if (CI && !ElementScalable) {
4329         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4330         LLVMContext &Context = *DAG.getContext();
4331         SDValue OffsVal;
4332         if (IsVectorGEP)
4333           OffsVal = DAG.getConstant(
4334               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4335         else
4336           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4337 
4338         // In an inbounds GEP with an offset that is nonnegative even when
4339         // interpreted as signed, assume there is no unsigned overflow.
4340         SDNodeFlags Flags;
4341         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4342           Flags.setNoUnsignedWrap(true);
4343 
4344         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4345 
4346         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4347         continue;
4348       }
4349 
4350       // N = N + Idx * ElementMul;
4351       SDValue IdxN = getValue(Idx);
4352 
4353       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4354         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4355                                   VectorElementCount);
4356         IdxN = DAG.getSplat(VT, dl, IdxN);
4357       }
4358 
4359       // If the index is smaller or larger than intptr_t, truncate or extend
4360       // it.
4361       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4362 
4363       if (ElementScalable) {
4364         EVT VScaleTy = N.getValueType().getScalarType();
4365         SDValue VScale = DAG.getNode(
4366             ISD::VSCALE, dl, VScaleTy,
4367             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4368         if (IsVectorGEP)
4369           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4370         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4371       } else {
4372         // If this is a multiply by a power of two, turn it into a shl
4373         // immediately.  This is a very common case.
4374         if (ElementMul != 1) {
4375           if (ElementMul.isPowerOf2()) {
4376             unsigned Amt = ElementMul.logBase2();
4377             IdxN = DAG.getNode(ISD::SHL, dl,
4378                                N.getValueType(), IdxN,
4379                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4380           } else {
4381             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4382                                             IdxN.getValueType());
4383             IdxN = DAG.getNode(ISD::MUL, dl,
4384                                N.getValueType(), IdxN, Scale);
4385           }
4386         }
4387       }
4388 
4389       N = DAG.getNode(ISD::ADD, dl,
4390                       N.getValueType(), N, IdxN);
4391     }
4392   }
4393 
4394   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4395   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4396   if (IsVectorGEP) {
4397     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4398     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4399   }
4400 
4401   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4402     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4403 
4404   setValue(&I, N);
4405 }
4406 
4407 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4408   // If this is a fixed sized alloca in the entry block of the function,
4409   // allocate it statically on the stack.
4410   if (FuncInfo.StaticAllocaMap.count(&I))
4411     return;   // getValue will auto-populate this.
4412 
4413   SDLoc dl = getCurSDLoc();
4414   Type *Ty = I.getAllocatedType();
4415   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4416   auto &DL = DAG.getDataLayout();
4417   TypeSize TySize = DL.getTypeAllocSize(Ty);
4418   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4419 
4420   SDValue AllocSize = getValue(I.getArraySize());
4421 
4422   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4423   if (AllocSize.getValueType() != IntPtr)
4424     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4425 
4426   if (TySize.isScalable())
4427     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4428                             DAG.getVScale(dl, IntPtr,
4429                                           APInt(IntPtr.getScalarSizeInBits(),
4430                                                 TySize.getKnownMinValue())));
4431   else {
4432     SDValue TySizeValue =
4433         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4434     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4435                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4436   }
4437 
4438   // Handle alignment.  If the requested alignment is less than or equal to
4439   // the stack alignment, ignore it.  If the size is greater than or equal to
4440   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4441   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4442   if (*Alignment <= StackAlign)
4443     Alignment = std::nullopt;
4444 
4445   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4446   // Round the size of the allocation up to the stack alignment size
4447   // by add SA-1 to the size. This doesn't overflow because we're computing
4448   // an address inside an alloca.
4449   SDNodeFlags Flags;
4450   Flags.setNoUnsignedWrap(true);
4451   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4452                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4453 
4454   // Mask out the low bits for alignment purposes.
4455   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4456                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4457 
4458   SDValue Ops[] = {
4459       getRoot(), AllocSize,
4460       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4461   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4462   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4463   setValue(&I, DSA);
4464   DAG.setRoot(DSA.getValue(1));
4465 
4466   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4467 }
4468 
4469 static const MDNode *getRangeMetadata(const Instruction &I) {
4470   // If !noundef is not present, then !range violation results in a poison
4471   // value rather than immediate undefined behavior. In theory, transferring
4472   // these annotations to SDAG is fine, but in practice there are key SDAG
4473   // transforms that are known not to be poison-safe, such as folding logical
4474   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4475   // also present.
4476   if (!I.hasMetadata(LLVMContext::MD_noundef))
4477     return nullptr;
4478   return I.getMetadata(LLVMContext::MD_range);
4479 }
4480 
4481 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4482   if (I.isAtomic())
4483     return visitAtomicLoad(I);
4484 
4485   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4486   const Value *SV = I.getOperand(0);
4487   if (TLI.supportSwiftError()) {
4488     // Swifterror values can come from either a function parameter with
4489     // swifterror attribute or an alloca with swifterror attribute.
4490     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4491       if (Arg->hasSwiftErrorAttr())
4492         return visitLoadFromSwiftError(I);
4493     }
4494 
4495     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4496       if (Alloca->isSwiftError())
4497         return visitLoadFromSwiftError(I);
4498     }
4499   }
4500 
4501   SDValue Ptr = getValue(SV);
4502 
4503   Type *Ty = I.getType();
4504   SmallVector<EVT, 4> ValueVTs, MemVTs;
4505   SmallVector<TypeSize, 4> Offsets;
4506   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4507   unsigned NumValues = ValueVTs.size();
4508   if (NumValues == 0)
4509     return;
4510 
4511   Align Alignment = I.getAlign();
4512   AAMDNodes AAInfo = I.getAAMetadata();
4513   const MDNode *Ranges = getRangeMetadata(I);
4514   bool isVolatile = I.isVolatile();
4515   MachineMemOperand::Flags MMOFlags =
4516       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4517 
4518   SDValue Root;
4519   bool ConstantMemory = false;
4520   if (isVolatile)
4521     // Serialize volatile loads with other side effects.
4522     Root = getRoot();
4523   else if (NumValues > MaxParallelChains)
4524     Root = getMemoryRoot();
4525   else if (AA &&
4526            AA->pointsToConstantMemory(MemoryLocation(
4527                SV,
4528                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4529                AAInfo))) {
4530     // Do not serialize (non-volatile) loads of constant memory with anything.
4531     Root = DAG.getEntryNode();
4532     ConstantMemory = true;
4533     MMOFlags |= MachineMemOperand::MOInvariant;
4534   } else {
4535     // Do not serialize non-volatile loads against each other.
4536     Root = DAG.getRoot();
4537   }
4538 
4539   SDLoc dl = getCurSDLoc();
4540 
4541   if (isVolatile)
4542     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4543 
4544   SmallVector<SDValue, 4> Values(NumValues);
4545   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4546 
4547   unsigned ChainI = 0;
4548   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4549     // Serializing loads here may result in excessive register pressure, and
4550     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4551     // could recover a bit by hoisting nodes upward in the chain by recognizing
4552     // they are side-effect free or do not alias. The optimizer should really
4553     // avoid this case by converting large object/array copies to llvm.memcpy
4554     // (MaxParallelChains should always remain as failsafe).
4555     if (ChainI == MaxParallelChains) {
4556       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4557       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4558                                   ArrayRef(Chains.data(), ChainI));
4559       Root = Chain;
4560       ChainI = 0;
4561     }
4562 
4563     // TODO: MachinePointerInfo only supports a fixed length offset.
4564     MachinePointerInfo PtrInfo =
4565         !Offsets[i].isScalable() || Offsets[i].isZero()
4566             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4567             : MachinePointerInfo();
4568 
4569     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4570     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4571                             MMOFlags, AAInfo, Ranges);
4572     Chains[ChainI] = L.getValue(1);
4573 
4574     if (MemVTs[i] != ValueVTs[i])
4575       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4576 
4577     Values[i] = L;
4578   }
4579 
4580   if (!ConstantMemory) {
4581     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4582                                 ArrayRef(Chains.data(), ChainI));
4583     if (isVolatile)
4584       DAG.setRoot(Chain);
4585     else
4586       PendingLoads.push_back(Chain);
4587   }
4588 
4589   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4590                            DAG.getVTList(ValueVTs), Values));
4591 }
4592 
4593 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4594   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4595          "call visitStoreToSwiftError when backend supports swifterror");
4596 
4597   SmallVector<EVT, 4> ValueVTs;
4598   SmallVector<uint64_t, 4> Offsets;
4599   const Value *SrcV = I.getOperand(0);
4600   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4601                   SrcV->getType(), ValueVTs, &Offsets, 0);
4602   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4603          "expect a single EVT for swifterror");
4604 
4605   SDValue Src = getValue(SrcV);
4606   // Create a virtual register, then update the virtual register.
4607   Register VReg =
4608       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4609   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4610   // Chain can be getRoot or getControlRoot.
4611   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4612                                       SDValue(Src.getNode(), Src.getResNo()));
4613   DAG.setRoot(CopyNode);
4614 }
4615 
4616 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4617   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4618          "call visitLoadFromSwiftError when backend supports swifterror");
4619 
4620   assert(!I.isVolatile() &&
4621          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4622          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4623          "Support volatile, non temporal, invariant for load_from_swift_error");
4624 
4625   const Value *SV = I.getOperand(0);
4626   Type *Ty = I.getType();
4627   assert(
4628       (!AA ||
4629        !AA->pointsToConstantMemory(MemoryLocation(
4630            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4631            I.getAAMetadata()))) &&
4632       "load_from_swift_error should not be constant memory");
4633 
4634   SmallVector<EVT, 4> ValueVTs;
4635   SmallVector<uint64_t, 4> Offsets;
4636   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4637                   ValueVTs, &Offsets, 0);
4638   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4639          "expect a single EVT for swifterror");
4640 
4641   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4642   SDValue L = DAG.getCopyFromReg(
4643       getRoot(), getCurSDLoc(),
4644       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4645 
4646   setValue(&I, L);
4647 }
4648 
4649 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4650   if (I.isAtomic())
4651     return visitAtomicStore(I);
4652 
4653   const Value *SrcV = I.getOperand(0);
4654   const Value *PtrV = I.getOperand(1);
4655 
4656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4657   if (TLI.supportSwiftError()) {
4658     // Swifterror values can come from either a function parameter with
4659     // swifterror attribute or an alloca with swifterror attribute.
4660     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4661       if (Arg->hasSwiftErrorAttr())
4662         return visitStoreToSwiftError(I);
4663     }
4664 
4665     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4666       if (Alloca->isSwiftError())
4667         return visitStoreToSwiftError(I);
4668     }
4669   }
4670 
4671   SmallVector<EVT, 4> ValueVTs, MemVTs;
4672   SmallVector<TypeSize, 4> Offsets;
4673   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4674                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4675   unsigned NumValues = ValueVTs.size();
4676   if (NumValues == 0)
4677     return;
4678 
4679   // Get the lowered operands. Note that we do this after
4680   // checking if NumResults is zero, because with zero results
4681   // the operands won't have values in the map.
4682   SDValue Src = getValue(SrcV);
4683   SDValue Ptr = getValue(PtrV);
4684 
4685   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4686   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4687   SDLoc dl = getCurSDLoc();
4688   Align Alignment = I.getAlign();
4689   AAMDNodes AAInfo = I.getAAMetadata();
4690 
4691   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4692 
4693   unsigned ChainI = 0;
4694   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4695     // See visitLoad comments.
4696     if (ChainI == MaxParallelChains) {
4697       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4698                                   ArrayRef(Chains.data(), ChainI));
4699       Root = Chain;
4700       ChainI = 0;
4701     }
4702 
4703     // TODO: MachinePointerInfo only supports a fixed length offset.
4704     MachinePointerInfo PtrInfo =
4705         !Offsets[i].isScalable() || Offsets[i].isZero()
4706             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4707             : MachinePointerInfo();
4708 
4709     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4710     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4711     if (MemVTs[i] != ValueVTs[i])
4712       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4713     SDValue St =
4714         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4715     Chains[ChainI] = St;
4716   }
4717 
4718   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4719                                   ArrayRef(Chains.data(), ChainI));
4720   setValue(&I, StoreNode);
4721   DAG.setRoot(StoreNode);
4722 }
4723 
4724 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4725                                            bool IsCompressing) {
4726   SDLoc sdl = getCurSDLoc();
4727 
4728   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4729                                Align &Alignment) {
4730     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4731     Src0 = I.getArgOperand(0);
4732     Ptr = I.getArgOperand(1);
4733     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue();
4734     Mask = I.getArgOperand(3);
4735   };
4736   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4737                                     Align &Alignment) {
4738     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4739     Src0 = I.getArgOperand(0);
4740     Ptr = I.getArgOperand(1);
4741     Mask = I.getArgOperand(2);
4742     Alignment = I.getParamAlign(1).valueOrOne();
4743   };
4744 
4745   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4746   Align Alignment;
4747   if (IsCompressing)
4748     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4749   else
4750     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4751 
4752   SDValue Ptr = getValue(PtrOperand);
4753   SDValue Src0 = getValue(Src0Operand);
4754   SDValue Mask = getValue(MaskOperand);
4755   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4756 
4757   EVT VT = Src0.getValueType();
4758 
4759   auto MMOFlags = MachineMemOperand::MOStore;
4760   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4761     MMOFlags |= MachineMemOperand::MONonTemporal;
4762 
4763   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4764       MachinePointerInfo(PtrOperand), MMOFlags,
4765       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4766   SDValue StoreNode =
4767       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4768                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4769   DAG.setRoot(StoreNode);
4770   setValue(&I, StoreNode);
4771 }
4772 
4773 // Get a uniform base for the Gather/Scatter intrinsic.
4774 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4775 // We try to represent it as a base pointer + vector of indices.
4776 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4777 // The first operand of the GEP may be a single pointer or a vector of pointers
4778 // Example:
4779 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4780 //  or
4781 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4782 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4783 //
4784 // When the first GEP operand is a single pointer - it is the uniform base we
4785 // are looking for. If first operand of the GEP is a splat vector - we
4786 // extract the splat value and use it as a uniform base.
4787 // In all other cases the function returns 'false'.
4788 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4789                            ISD::MemIndexType &IndexType, SDValue &Scale,
4790                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4791                            uint64_t ElemSize) {
4792   SelectionDAG& DAG = SDB->DAG;
4793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4794   const DataLayout &DL = DAG.getDataLayout();
4795 
4796   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4797 
4798   // Handle splat constant pointer.
4799   if (auto *C = dyn_cast<Constant>(Ptr)) {
4800     C = C->getSplatValue();
4801     if (!C)
4802       return false;
4803 
4804     Base = SDB->getValue(C);
4805 
4806     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4807     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4808     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4809     IndexType = ISD::SIGNED_SCALED;
4810     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4811     return true;
4812   }
4813 
4814   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4815   if (!GEP || GEP->getParent() != CurBB)
4816     return false;
4817 
4818   if (GEP->getNumOperands() != 2)
4819     return false;
4820 
4821   const Value *BasePtr = GEP->getPointerOperand();
4822   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4823 
4824   // Make sure the base is scalar and the index is a vector.
4825   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4826     return false;
4827 
4828   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4829   if (ScaleVal.isScalable())
4830     return false;
4831 
4832   // Target may not support the required addressing mode.
4833   if (ScaleVal != 1 &&
4834       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4835     return false;
4836 
4837   Base = SDB->getValue(BasePtr);
4838   Index = SDB->getValue(IndexVal);
4839   IndexType = ISD::SIGNED_SCALED;
4840 
4841   Scale =
4842       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4843   return true;
4844 }
4845 
4846 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4847   SDLoc sdl = getCurSDLoc();
4848 
4849   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4850   const Value *Ptr = I.getArgOperand(1);
4851   SDValue Src0 = getValue(I.getArgOperand(0));
4852   SDValue Mask = getValue(I.getArgOperand(3));
4853   EVT VT = Src0.getValueType();
4854   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4855                         ->getMaybeAlignValue()
4856                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4857   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4858 
4859   SDValue Base;
4860   SDValue Index;
4861   ISD::MemIndexType IndexType;
4862   SDValue Scale;
4863   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4864                                     I.getParent(), VT.getScalarStoreSize());
4865 
4866   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4867   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4868       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4869       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4870   if (!UniformBase) {
4871     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4872     Index = getValue(Ptr);
4873     IndexType = ISD::SIGNED_SCALED;
4874     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4875   }
4876 
4877   EVT IdxVT = Index.getValueType();
4878   EVT EltTy = IdxVT.getVectorElementType();
4879   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4880     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4881     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4882   }
4883 
4884   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4885   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4886                                          Ops, MMO, IndexType, false);
4887   DAG.setRoot(Scatter);
4888   setValue(&I, Scatter);
4889 }
4890 
4891 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4892   SDLoc sdl = getCurSDLoc();
4893 
4894   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4895                               Align &Alignment) {
4896     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4897     Ptr = I.getArgOperand(0);
4898     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue();
4899     Mask = I.getArgOperand(2);
4900     Src0 = I.getArgOperand(3);
4901   };
4902   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4903                                  Align &Alignment) {
4904     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4905     Ptr = I.getArgOperand(0);
4906     Alignment = I.getParamAlign(0).valueOrOne();
4907     Mask = I.getArgOperand(1);
4908     Src0 = I.getArgOperand(2);
4909   };
4910 
4911   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4912   Align Alignment;
4913   if (IsExpanding)
4914     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4915   else
4916     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4917 
4918   SDValue Ptr = getValue(PtrOperand);
4919   SDValue Src0 = getValue(Src0Operand);
4920   SDValue Mask = getValue(MaskOperand);
4921   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4922 
4923   EVT VT = Src0.getValueType();
4924   AAMDNodes AAInfo = I.getAAMetadata();
4925   const MDNode *Ranges = getRangeMetadata(I);
4926 
4927   // Do not serialize masked loads of constant memory with anything.
4928   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4929   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4930 
4931   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4932 
4933   auto MMOFlags = MachineMemOperand::MOLoad;
4934   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4935     MMOFlags |= MachineMemOperand::MONonTemporal;
4936 
4937   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4938       MachinePointerInfo(PtrOperand), MMOFlags,
4939       LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges);
4940 
4941   SDValue Load =
4942       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4943                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4944   if (AddToChain)
4945     PendingLoads.push_back(Load.getValue(1));
4946   setValue(&I, Load);
4947 }
4948 
4949 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4950   SDLoc sdl = getCurSDLoc();
4951 
4952   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4953   const Value *Ptr = I.getArgOperand(0);
4954   SDValue Src0 = getValue(I.getArgOperand(3));
4955   SDValue Mask = getValue(I.getArgOperand(2));
4956 
4957   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4958   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4959   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4960                         ->getMaybeAlignValue()
4961                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4962 
4963   const MDNode *Ranges = getRangeMetadata(I);
4964 
4965   SDValue Root = DAG.getRoot();
4966   SDValue Base;
4967   SDValue Index;
4968   ISD::MemIndexType IndexType;
4969   SDValue Scale;
4970   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4971                                     I.getParent(), VT.getScalarStoreSize());
4972   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4973   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4974       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4975       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(),
4976       Ranges);
4977 
4978   if (!UniformBase) {
4979     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4980     Index = getValue(Ptr);
4981     IndexType = ISD::SIGNED_SCALED;
4982     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4983   }
4984 
4985   EVT IdxVT = Index.getValueType();
4986   EVT EltTy = IdxVT.getVectorElementType();
4987   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4988     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4989     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4990   }
4991 
4992   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4993   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4994                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4995 
4996   PendingLoads.push_back(Gather.getValue(1));
4997   setValue(&I, Gather);
4998 }
4999 
5000 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5001   SDLoc dl = getCurSDLoc();
5002   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5003   AtomicOrdering FailureOrdering = I.getFailureOrdering();
5004   SyncScope::ID SSID = I.getSyncScopeID();
5005 
5006   SDValue InChain = getRoot();
5007 
5008   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5009   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5010 
5011   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5012   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5013 
5014   MachineFunction &MF = DAG.getMachineFunction();
5015   MachineMemOperand *MMO = MF.getMachineMemOperand(
5016       MachinePointerInfo(I.getPointerOperand()), Flags,
5017       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5018       AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering);
5019 
5020   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5021                                    dl, MemVT, VTs, InChain,
5022                                    getValue(I.getPointerOperand()),
5023                                    getValue(I.getCompareOperand()),
5024                                    getValue(I.getNewValOperand()), MMO);
5025 
5026   SDValue OutChain = L.getValue(2);
5027 
5028   setValue(&I, L);
5029   DAG.setRoot(OutChain);
5030 }
5031 
5032 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5033   SDLoc dl = getCurSDLoc();
5034   ISD::NodeType NT;
5035   switch (I.getOperation()) {
5036   default: llvm_unreachable("Unknown atomicrmw operation");
5037   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5038   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5039   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5040   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5041   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5042   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5043   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5044   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5045   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5046   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5047   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5048   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5049   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5050   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5051   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5052   case AtomicRMWInst::UIncWrap:
5053     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5054     break;
5055   case AtomicRMWInst::UDecWrap:
5056     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5057     break;
5058   }
5059   AtomicOrdering Ordering = I.getOrdering();
5060   SyncScope::ID SSID = I.getSyncScopeID();
5061 
5062   SDValue InChain = getRoot();
5063 
5064   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5065   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5066   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5067 
5068   MachineFunction &MF = DAG.getMachineFunction();
5069   MachineMemOperand *MMO = MF.getMachineMemOperand(
5070       MachinePointerInfo(I.getPointerOperand()), Flags,
5071       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5072       AAMDNodes(), nullptr, SSID, Ordering);
5073 
5074   SDValue L =
5075     DAG.getAtomic(NT, dl, MemVT, InChain,
5076                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5077                   MMO);
5078 
5079   SDValue OutChain = L.getValue(1);
5080 
5081   setValue(&I, L);
5082   DAG.setRoot(OutChain);
5083 }
5084 
5085 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5086   SDLoc dl = getCurSDLoc();
5087   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5088   SDValue Ops[3];
5089   Ops[0] = getRoot();
5090   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5091                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5092   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5093                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5094   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5095   setValue(&I, N);
5096   DAG.setRoot(N);
5097 }
5098 
5099 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5100   SDLoc dl = getCurSDLoc();
5101   AtomicOrdering Order = I.getOrdering();
5102   SyncScope::ID SSID = I.getSyncScopeID();
5103 
5104   SDValue InChain = getRoot();
5105 
5106   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5107   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5108   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5109 
5110   if (!TLI.supportsUnalignedAtomics() &&
5111       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5112     report_fatal_error("Cannot generate unaligned atomic load");
5113 
5114   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5115 
5116   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5117       MachinePointerInfo(I.getPointerOperand()), Flags,
5118       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5119       nullptr, SSID, Order);
5120 
5121   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5122 
5123   SDValue Ptr = getValue(I.getPointerOperand());
5124   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5125                             Ptr, MMO);
5126 
5127   SDValue OutChain = L.getValue(1);
5128   if (MemVT != VT)
5129     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5130 
5131   setValue(&I, L);
5132   DAG.setRoot(OutChain);
5133 }
5134 
5135 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5136   SDLoc dl = getCurSDLoc();
5137 
5138   AtomicOrdering Ordering = I.getOrdering();
5139   SyncScope::ID SSID = I.getSyncScopeID();
5140 
5141   SDValue InChain = getRoot();
5142 
5143   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5144   EVT MemVT =
5145       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5146 
5147   if (!TLI.supportsUnalignedAtomics() &&
5148       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5149     report_fatal_error("Cannot generate unaligned atomic store");
5150 
5151   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5152 
5153   MachineFunction &MF = DAG.getMachineFunction();
5154   MachineMemOperand *MMO = MF.getMachineMemOperand(
5155       MachinePointerInfo(I.getPointerOperand()), Flags,
5156       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5157       nullptr, SSID, Ordering);
5158 
5159   SDValue Val = getValue(I.getValueOperand());
5160   if (Val.getValueType() != MemVT)
5161     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5162   SDValue Ptr = getValue(I.getPointerOperand());
5163 
5164   SDValue OutChain =
5165       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5166 
5167   setValue(&I, OutChain);
5168   DAG.setRoot(OutChain);
5169 }
5170 
5171 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5172 /// node.
5173 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5174                                                unsigned Intrinsic) {
5175   // Ignore the callsite's attributes. A specific call site may be marked with
5176   // readnone, but the lowering code will expect the chain based on the
5177   // definition.
5178   const Function *F = I.getCalledFunction();
5179   bool HasChain = !F->doesNotAccessMemory();
5180   bool OnlyLoad = HasChain && F->onlyReadsMemory();
5181 
5182   // Build the operand list.
5183   SmallVector<SDValue, 8> Ops;
5184   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5185     if (OnlyLoad) {
5186       // We don't need to serialize loads against other loads.
5187       Ops.push_back(DAG.getRoot());
5188     } else {
5189       Ops.push_back(getRoot());
5190     }
5191   }
5192 
5193   // Info is set by getTgtMemIntrinsic
5194   TargetLowering::IntrinsicInfo Info;
5195   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5196   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5197                                                DAG.getMachineFunction(),
5198                                                Intrinsic);
5199 
5200   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5201   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5202       Info.opc == ISD::INTRINSIC_W_CHAIN)
5203     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5204                                         TLI.getPointerTy(DAG.getDataLayout())));
5205 
5206   // Add all operands of the call to the operand list.
5207   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5208     const Value *Arg = I.getArgOperand(i);
5209     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5210       Ops.push_back(getValue(Arg));
5211       continue;
5212     }
5213 
5214     // Use TargetConstant instead of a regular constant for immarg.
5215     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5216     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5217       assert(CI->getBitWidth() <= 64 &&
5218              "large intrinsic immediates not handled");
5219       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5220     } else {
5221       Ops.push_back(
5222           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5223     }
5224   }
5225 
5226   SmallVector<EVT, 4> ValueVTs;
5227   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5228 
5229   if (HasChain)
5230     ValueVTs.push_back(MVT::Other);
5231 
5232   SDVTList VTs = DAG.getVTList(ValueVTs);
5233 
5234   // Propagate fast-math-flags from IR to node(s).
5235   SDNodeFlags Flags;
5236   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5237     Flags.copyFMF(*FPMO);
5238   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5239 
5240   // Create the node.
5241   SDValue Result;
5242 
5243   if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5244     auto *Token = Bundle->Inputs[0].get();
5245     SDValue ConvControlToken = getValue(Token);
5246     assert(Ops.back().getValueType() != MVT::Glue &&
5247            "Did not expected another glue node here.");
5248     ConvControlToken =
5249         DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5250     Ops.push_back(ConvControlToken);
5251   }
5252 
5253   // In some cases, custom collection of operands from CallInst I may be needed.
5254   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5255   if (IsTgtIntrinsic) {
5256     // This is target intrinsic that touches memory
5257     //
5258     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5259     //       didn't yield anything useful.
5260     MachinePointerInfo MPI;
5261     if (Info.ptrVal)
5262       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5263     else if (Info.fallbackAddressSpace)
5264       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5265     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5266                                      Info.memVT, MPI, Info.align, Info.flags,
5267                                      Info.size, I.getAAMetadata());
5268   } else if (!HasChain) {
5269     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5270   } else if (!I.getType()->isVoidTy()) {
5271     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5272   } else {
5273     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5274   }
5275 
5276   if (HasChain) {
5277     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5278     if (OnlyLoad)
5279       PendingLoads.push_back(Chain);
5280     else
5281       DAG.setRoot(Chain);
5282   }
5283 
5284   if (!I.getType()->isVoidTy()) {
5285     if (!isa<VectorType>(I.getType()))
5286       Result = lowerRangeToAssertZExt(DAG, I, Result);
5287 
5288     MaybeAlign Alignment = I.getRetAlign();
5289 
5290     // Insert `assertalign` node if there's an alignment.
5291     if (InsertAssertAlign && Alignment) {
5292       Result =
5293           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5294     }
5295   }
5296 
5297   setValue(&I, Result);
5298 }
5299 
5300 /// GetSignificand - Get the significand and build it into a floating-point
5301 /// number with exponent of 1:
5302 ///
5303 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5304 ///
5305 /// where Op is the hexadecimal representation of floating point value.
5306 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5307   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5308                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5309   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5310                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5311   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5312 }
5313 
5314 /// GetExponent - Get the exponent:
5315 ///
5316 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5317 ///
5318 /// where Op is the hexadecimal representation of floating point value.
5319 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5320                            const TargetLowering &TLI, const SDLoc &dl) {
5321   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5322                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5323   SDValue t1 = DAG.getNode(
5324       ISD::SRL, dl, MVT::i32, t0,
5325       DAG.getConstant(23, dl,
5326                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5327   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5328                            DAG.getConstant(127, dl, MVT::i32));
5329   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5330 }
5331 
5332 /// getF32Constant - Get 32-bit floating point constant.
5333 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5334                               const SDLoc &dl) {
5335   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5336                            MVT::f32);
5337 }
5338 
5339 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5340                                        SelectionDAG &DAG) {
5341   // TODO: What fast-math-flags should be set on the floating-point nodes?
5342 
5343   //   IntegerPartOfX = ((int32_t)(t0);
5344   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5345 
5346   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5347   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5348   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5349 
5350   //   IntegerPartOfX <<= 23;
5351   IntegerPartOfX =
5352       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5353                   DAG.getConstant(23, dl,
5354                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5355                                       MVT::i32, DAG.getDataLayout())));
5356 
5357   SDValue TwoToFractionalPartOfX;
5358   if (LimitFloatPrecision <= 6) {
5359     // For floating-point precision of 6:
5360     //
5361     //   TwoToFractionalPartOfX =
5362     //     0.997535578f +
5363     //       (0.735607626f + 0.252464424f * x) * x;
5364     //
5365     // error 0.0144103317, which is 6 bits
5366     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5367                              getF32Constant(DAG, 0x3e814304, dl));
5368     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5369                              getF32Constant(DAG, 0x3f3c50c8, dl));
5370     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5371     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5372                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5373   } else if (LimitFloatPrecision <= 12) {
5374     // For floating-point precision of 12:
5375     //
5376     //   TwoToFractionalPartOfX =
5377     //     0.999892986f +
5378     //       (0.696457318f +
5379     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5380     //
5381     // error 0.000107046256, which is 13 to 14 bits
5382     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5383                              getF32Constant(DAG, 0x3da235e3, dl));
5384     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5385                              getF32Constant(DAG, 0x3e65b8f3, dl));
5386     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5387     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5388                              getF32Constant(DAG, 0x3f324b07, dl));
5389     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5390     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5391                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5392   } else { // LimitFloatPrecision <= 18
5393     // For floating-point precision of 18:
5394     //
5395     //   TwoToFractionalPartOfX =
5396     //     0.999999982f +
5397     //       (0.693148872f +
5398     //         (0.240227044f +
5399     //           (0.554906021e-1f +
5400     //             (0.961591928e-2f +
5401     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5402     // error 2.47208000*10^(-7), which is better than 18 bits
5403     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5404                              getF32Constant(DAG, 0x3924b03e, dl));
5405     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5406                              getF32Constant(DAG, 0x3ab24b87, dl));
5407     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5408     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5409                              getF32Constant(DAG, 0x3c1d8c17, dl));
5410     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5411     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5412                              getF32Constant(DAG, 0x3d634a1d, dl));
5413     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5414     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5415                              getF32Constant(DAG, 0x3e75fe14, dl));
5416     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5417     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5418                               getF32Constant(DAG, 0x3f317234, dl));
5419     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5420     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5421                                          getF32Constant(DAG, 0x3f800000, dl));
5422   }
5423 
5424   // Add the exponent into the result in integer domain.
5425   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5426   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5427                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5428 }
5429 
5430 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5431 /// limited-precision mode.
5432 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5433                          const TargetLowering &TLI, SDNodeFlags Flags) {
5434   if (Op.getValueType() == MVT::f32 &&
5435       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5436 
5437     // Put the exponent in the right bit position for later addition to the
5438     // final result:
5439     //
5440     // t0 = Op * log2(e)
5441 
5442     // TODO: What fast-math-flags should be set here?
5443     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5444                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5445     return getLimitedPrecisionExp2(t0, dl, DAG);
5446   }
5447 
5448   // No special expansion.
5449   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5450 }
5451 
5452 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5453 /// limited-precision mode.
5454 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5455                          const TargetLowering &TLI, SDNodeFlags Flags) {
5456   // TODO: What fast-math-flags should be set on the floating-point nodes?
5457 
5458   if (Op.getValueType() == MVT::f32 &&
5459       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5460     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5461 
5462     // Scale the exponent by log(2).
5463     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5464     SDValue LogOfExponent =
5465         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5466                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5467 
5468     // Get the significand and build it into a floating-point number with
5469     // exponent of 1.
5470     SDValue X = GetSignificand(DAG, Op1, dl);
5471 
5472     SDValue LogOfMantissa;
5473     if (LimitFloatPrecision <= 6) {
5474       // For floating-point precision of 6:
5475       //
5476       //   LogofMantissa =
5477       //     -1.1609546f +
5478       //       (1.4034025f - 0.23903021f * x) * x;
5479       //
5480       // error 0.0034276066, which is better than 8 bits
5481       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5482                                getF32Constant(DAG, 0xbe74c456, dl));
5483       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5484                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5485       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5486       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5487                                   getF32Constant(DAG, 0x3f949a29, dl));
5488     } else if (LimitFloatPrecision <= 12) {
5489       // For floating-point precision of 12:
5490       //
5491       //   LogOfMantissa =
5492       //     -1.7417939f +
5493       //       (2.8212026f +
5494       //         (-1.4699568f +
5495       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5496       //
5497       // error 0.000061011436, which is 14 bits
5498       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5499                                getF32Constant(DAG, 0xbd67b6d6, dl));
5500       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5501                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5502       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5503       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5504                                getF32Constant(DAG, 0x3fbc278b, dl));
5505       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5506       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5507                                getF32Constant(DAG, 0x40348e95, dl));
5508       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5509       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5510                                   getF32Constant(DAG, 0x3fdef31a, dl));
5511     } else { // LimitFloatPrecision <= 18
5512       // For floating-point precision of 18:
5513       //
5514       //   LogOfMantissa =
5515       //     -2.1072184f +
5516       //       (4.2372794f +
5517       //         (-3.7029485f +
5518       //           (2.2781945f +
5519       //             (-0.87823314f +
5520       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5521       //
5522       // error 0.0000023660568, which is better than 18 bits
5523       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5524                                getF32Constant(DAG, 0xbc91e5ac, dl));
5525       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5526                                getF32Constant(DAG, 0x3e4350aa, dl));
5527       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5528       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5529                                getF32Constant(DAG, 0x3f60d3e3, dl));
5530       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5531       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5532                                getF32Constant(DAG, 0x4011cdf0, dl));
5533       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5534       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5535                                getF32Constant(DAG, 0x406cfd1c, dl));
5536       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5537       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5538                                getF32Constant(DAG, 0x408797cb, dl));
5539       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5540       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5541                                   getF32Constant(DAG, 0x4006dcab, dl));
5542     }
5543 
5544     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5545   }
5546 
5547   // No special expansion.
5548   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5549 }
5550 
5551 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5552 /// limited-precision mode.
5553 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5554                           const TargetLowering &TLI, SDNodeFlags Flags) {
5555   // TODO: What fast-math-flags should be set on the floating-point nodes?
5556 
5557   if (Op.getValueType() == MVT::f32 &&
5558       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5559     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5560 
5561     // Get the exponent.
5562     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5563 
5564     // Get the significand and build it into a floating-point number with
5565     // exponent of 1.
5566     SDValue X = GetSignificand(DAG, Op1, dl);
5567 
5568     // Different possible minimax approximations of significand in
5569     // floating-point for various degrees of accuracy over [1,2].
5570     SDValue Log2ofMantissa;
5571     if (LimitFloatPrecision <= 6) {
5572       // For floating-point precision of 6:
5573       //
5574       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5575       //
5576       // error 0.0049451742, which is more than 7 bits
5577       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5578                                getF32Constant(DAG, 0xbeb08fe0, dl));
5579       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5580                                getF32Constant(DAG, 0x40019463, dl));
5581       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5582       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5583                                    getF32Constant(DAG, 0x3fd6633d, dl));
5584     } else if (LimitFloatPrecision <= 12) {
5585       // For floating-point precision of 12:
5586       //
5587       //   Log2ofMantissa =
5588       //     -2.51285454f +
5589       //       (4.07009056f +
5590       //         (-2.12067489f +
5591       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5592       //
5593       // error 0.0000876136000, which is better than 13 bits
5594       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5595                                getF32Constant(DAG, 0xbda7262e, dl));
5596       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5597                                getF32Constant(DAG, 0x3f25280b, dl));
5598       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5599       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5600                                getF32Constant(DAG, 0x4007b923, dl));
5601       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5602       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5603                                getF32Constant(DAG, 0x40823e2f, dl));
5604       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5605       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5606                                    getF32Constant(DAG, 0x4020d29c, dl));
5607     } else { // LimitFloatPrecision <= 18
5608       // For floating-point precision of 18:
5609       //
5610       //   Log2ofMantissa =
5611       //     -3.0400495f +
5612       //       (6.1129976f +
5613       //         (-5.3420409f +
5614       //           (3.2865683f +
5615       //             (-1.2669343f +
5616       //               (0.27515199f -
5617       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5618       //
5619       // error 0.0000018516, which is better than 18 bits
5620       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5621                                getF32Constant(DAG, 0xbcd2769e, dl));
5622       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5623                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5624       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5625       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5626                                getF32Constant(DAG, 0x3fa22ae7, dl));
5627       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5628       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5629                                getF32Constant(DAG, 0x40525723, dl));
5630       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5631       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5632                                getF32Constant(DAG, 0x40aaf200, dl));
5633       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5634       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5635                                getF32Constant(DAG, 0x40c39dad, dl));
5636       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5637       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5638                                    getF32Constant(DAG, 0x4042902c, dl));
5639     }
5640 
5641     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5642   }
5643 
5644   // No special expansion.
5645   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5646 }
5647 
5648 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5649 /// limited-precision mode.
5650 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5651                            const TargetLowering &TLI, SDNodeFlags Flags) {
5652   // TODO: What fast-math-flags should be set on the floating-point nodes?
5653 
5654   if (Op.getValueType() == MVT::f32 &&
5655       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5656     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5657 
5658     // Scale the exponent by log10(2) [0.30102999f].
5659     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5660     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5661                                         getF32Constant(DAG, 0x3e9a209a, dl));
5662 
5663     // Get the significand and build it into a floating-point number with
5664     // exponent of 1.
5665     SDValue X = GetSignificand(DAG, Op1, dl);
5666 
5667     SDValue Log10ofMantissa;
5668     if (LimitFloatPrecision <= 6) {
5669       // For floating-point precision of 6:
5670       //
5671       //   Log10ofMantissa =
5672       //     -0.50419619f +
5673       //       (0.60948995f - 0.10380950f * x) * x;
5674       //
5675       // error 0.0014886165, which is 6 bits
5676       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5677                                getF32Constant(DAG, 0xbdd49a13, dl));
5678       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5679                                getF32Constant(DAG, 0x3f1c0789, dl));
5680       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5681       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5682                                     getF32Constant(DAG, 0x3f011300, dl));
5683     } else if (LimitFloatPrecision <= 12) {
5684       // For floating-point precision of 12:
5685       //
5686       //   Log10ofMantissa =
5687       //     -0.64831180f +
5688       //       (0.91751397f +
5689       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5690       //
5691       // error 0.00019228036, which is better than 12 bits
5692       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5693                                getF32Constant(DAG, 0x3d431f31, dl));
5694       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5695                                getF32Constant(DAG, 0x3ea21fb2, dl));
5696       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5697       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5698                                getF32Constant(DAG, 0x3f6ae232, dl));
5699       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5700       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5701                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5702     } else { // LimitFloatPrecision <= 18
5703       // For floating-point precision of 18:
5704       //
5705       //   Log10ofMantissa =
5706       //     -0.84299375f +
5707       //       (1.5327582f +
5708       //         (-1.0688956f +
5709       //           (0.49102474f +
5710       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5711       //
5712       // error 0.0000037995730, which is better than 18 bits
5713       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5714                                getF32Constant(DAG, 0x3c5d51ce, dl));
5715       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5716                                getF32Constant(DAG, 0x3e00685a, dl));
5717       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5718       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5719                                getF32Constant(DAG, 0x3efb6798, dl));
5720       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5721       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5722                                getF32Constant(DAG, 0x3f88d192, dl));
5723       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5724       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5725                                getF32Constant(DAG, 0x3fc4316c, dl));
5726       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5727       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5728                                     getF32Constant(DAG, 0x3f57ce70, dl));
5729     }
5730 
5731     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5732   }
5733 
5734   // No special expansion.
5735   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5736 }
5737 
5738 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5739 /// limited-precision mode.
5740 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5741                           const TargetLowering &TLI, SDNodeFlags Flags) {
5742   if (Op.getValueType() == MVT::f32 &&
5743       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5744     return getLimitedPrecisionExp2(Op, dl, DAG);
5745 
5746   // No special expansion.
5747   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5748 }
5749 
5750 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5751 /// limited-precision mode with x == 10.0f.
5752 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5753                          SelectionDAG &DAG, const TargetLowering &TLI,
5754                          SDNodeFlags Flags) {
5755   bool IsExp10 = false;
5756   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5757       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5758     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5759       APFloat Ten(10.0f);
5760       IsExp10 = LHSC->isExactlyValue(Ten);
5761     }
5762   }
5763 
5764   // TODO: What fast-math-flags should be set on the FMUL node?
5765   if (IsExp10) {
5766     // Put the exponent in the right bit position for later addition to the
5767     // final result:
5768     //
5769     //   #define LOG2OF10 3.3219281f
5770     //   t0 = Op * LOG2OF10;
5771     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5772                              getF32Constant(DAG, 0x40549a78, dl));
5773     return getLimitedPrecisionExp2(t0, dl, DAG);
5774   }
5775 
5776   // No special expansion.
5777   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5778 }
5779 
5780 /// ExpandPowI - Expand a llvm.powi intrinsic.
5781 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5782                           SelectionDAG &DAG) {
5783   // If RHS is a constant, we can expand this out to a multiplication tree if
5784   // it's beneficial on the target, otherwise we end up lowering to a call to
5785   // __powidf2 (for example).
5786   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5787     unsigned Val = RHSC->getSExtValue();
5788 
5789     // powi(x, 0) -> 1.0
5790     if (Val == 0)
5791       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5792 
5793     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5794             Val, DAG.shouldOptForSize())) {
5795       // Get the exponent as a positive value.
5796       if ((int)Val < 0)
5797         Val = -Val;
5798       // We use the simple binary decomposition method to generate the multiply
5799       // sequence.  There are more optimal ways to do this (for example,
5800       // powi(x,15) generates one more multiply than it should), but this has
5801       // the benefit of being both really simple and much better than a libcall.
5802       SDValue Res; // Logically starts equal to 1.0
5803       SDValue CurSquare = LHS;
5804       // TODO: Intrinsics should have fast-math-flags that propagate to these
5805       // nodes.
5806       while (Val) {
5807         if (Val & 1) {
5808           if (Res.getNode())
5809             Res =
5810                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5811           else
5812             Res = CurSquare; // 1.0*CurSquare.
5813         }
5814 
5815         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5816                                 CurSquare, CurSquare);
5817         Val >>= 1;
5818       }
5819 
5820       // If the original was negative, invert the result, producing 1/(x*x*x).
5821       if (RHSC->getSExtValue() < 0)
5822         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5823                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5824       return Res;
5825     }
5826   }
5827 
5828   // Otherwise, expand to a libcall.
5829   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5830 }
5831 
5832 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5833                             SDValue LHS, SDValue RHS, SDValue Scale,
5834                             SelectionDAG &DAG, const TargetLowering &TLI) {
5835   EVT VT = LHS.getValueType();
5836   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5837   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5838   LLVMContext &Ctx = *DAG.getContext();
5839 
5840   // If the type is legal but the operation isn't, this node might survive all
5841   // the way to operation legalization. If we end up there and we do not have
5842   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5843   // node.
5844 
5845   // Coax the legalizer into expanding the node during type legalization instead
5846   // by bumping the size by one bit. This will force it to Promote, enabling the
5847   // early expansion and avoiding the need to expand later.
5848 
5849   // We don't have to do this if Scale is 0; that can always be expanded, unless
5850   // it's a saturating signed operation. Those can experience true integer
5851   // division overflow, a case which we must avoid.
5852 
5853   // FIXME: We wouldn't have to do this (or any of the early
5854   // expansion/promotion) if it was possible to expand a libcall of an
5855   // illegal type during operation legalization. But it's not, so things
5856   // get a bit hacky.
5857   unsigned ScaleInt = Scale->getAsZExtVal();
5858   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5859       (TLI.isTypeLegal(VT) ||
5860        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5861     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5862         Opcode, VT, ScaleInt);
5863     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5864       EVT PromVT;
5865       if (VT.isScalarInteger())
5866         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5867       else if (VT.isVector()) {
5868         PromVT = VT.getVectorElementType();
5869         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5870         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5871       } else
5872         llvm_unreachable("Wrong VT for DIVFIX?");
5873       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5874       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5875       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5876       // For saturating operations, we need to shift up the LHS to get the
5877       // proper saturation width, and then shift down again afterwards.
5878       if (Saturating)
5879         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5880                           DAG.getConstant(1, DL, ShiftTy));
5881       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5882       if (Saturating)
5883         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5884                           DAG.getConstant(1, DL, ShiftTy));
5885       return DAG.getZExtOrTrunc(Res, DL, VT);
5886     }
5887   }
5888 
5889   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5890 }
5891 
5892 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5893 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5894 static void
5895 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5896                      const SDValue &N) {
5897   switch (N.getOpcode()) {
5898   case ISD::CopyFromReg: {
5899     SDValue Op = N.getOperand(1);
5900     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5901                       Op.getValueType().getSizeInBits());
5902     return;
5903   }
5904   case ISD::BITCAST:
5905   case ISD::AssertZext:
5906   case ISD::AssertSext:
5907   case ISD::TRUNCATE:
5908     getUnderlyingArgRegs(Regs, N.getOperand(0));
5909     return;
5910   case ISD::BUILD_PAIR:
5911   case ISD::BUILD_VECTOR:
5912   case ISD::CONCAT_VECTORS:
5913     for (SDValue Op : N->op_values())
5914       getUnderlyingArgRegs(Regs, Op);
5915     return;
5916   default:
5917     return;
5918   }
5919 }
5920 
5921 /// If the DbgValueInst is a dbg_value of a function argument, create the
5922 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5923 /// instruction selection, they will be inserted to the entry BB.
5924 /// We don't currently support this for variadic dbg_values, as they shouldn't
5925 /// appear for function arguments or in the prologue.
5926 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5927     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5928     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5929   const Argument *Arg = dyn_cast<Argument>(V);
5930   if (!Arg)
5931     return false;
5932 
5933   MachineFunction &MF = DAG.getMachineFunction();
5934   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5935 
5936   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5937   // we've been asked to pursue.
5938   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5939                               bool Indirect) {
5940     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5941       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5942       // pointing at the VReg, which will be patched up later.
5943       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5944       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5945           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5946           /* isKill */ false, /* isDead */ false,
5947           /* isUndef */ false, /* isEarlyClobber */ false,
5948           /* SubReg */ 0, /* isDebug */ true)});
5949 
5950       auto *NewDIExpr = FragExpr;
5951       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5952       // the DIExpression.
5953       if (Indirect)
5954         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5955       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5956       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5957       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5958     } else {
5959       // Create a completely standard DBG_VALUE.
5960       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5961       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5962     }
5963   };
5964 
5965   if (Kind == FuncArgumentDbgValueKind::Value) {
5966     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5967     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5968     // the entry block.
5969     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5970     if (!IsInEntryBlock)
5971       return false;
5972 
5973     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5974     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5975     // variable that also is a param.
5976     //
5977     // Although, if we are at the top of the entry block already, we can still
5978     // emit using ArgDbgValue. This might catch some situations when the
5979     // dbg.value refers to an argument that isn't used in the entry block, so
5980     // any CopyToReg node would be optimized out and the only way to express
5981     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5982     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5983     // we should only emit as ArgDbgValue if the Variable is an argument to the
5984     // current function, and the dbg.value intrinsic is found in the entry
5985     // block.
5986     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5987         !DL->getInlinedAt();
5988     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5989     if (!IsInPrologue && !VariableIsFunctionInputArg)
5990       return false;
5991 
5992     // Here we assume that a function argument on IR level only can be used to
5993     // describe one input parameter on source level. If we for example have
5994     // source code like this
5995     //
5996     //    struct A { long x, y; };
5997     //    void foo(struct A a, long b) {
5998     //      ...
5999     //      b = a.x;
6000     //      ...
6001     //    }
6002     //
6003     // and IR like this
6004     //
6005     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
6006     //  entry:
6007     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6008     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6009     //    call void @llvm.dbg.value(metadata i32 %b, "b",
6010     //    ...
6011     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
6012     //    ...
6013     //
6014     // then the last dbg.value is describing a parameter "b" using a value that
6015     // is an argument. But since we already has used %a1 to describe a parameter
6016     // we should not handle that last dbg.value here (that would result in an
6017     // incorrect hoisting of the DBG_VALUE to the function entry).
6018     // Notice that we allow one dbg.value per IR level argument, to accommodate
6019     // for the situation with fragments above.
6020     // If there is no node for the value being handled, we return true to skip
6021     // the normal generation of debug info, as it would kill existing debug
6022     // info for the parameter in case of duplicates.
6023     if (VariableIsFunctionInputArg) {
6024       unsigned ArgNo = Arg->getArgNo();
6025       if (ArgNo >= FuncInfo.DescribedArgs.size())
6026         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6027       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6028         return !NodeMap[V].getNode();
6029       FuncInfo.DescribedArgs.set(ArgNo);
6030     }
6031   }
6032 
6033   bool IsIndirect = false;
6034   std::optional<MachineOperand> Op;
6035   // Some arguments' frame index is recorded during argument lowering.
6036   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6037   if (FI != std::numeric_limits<int>::max())
6038     Op = MachineOperand::CreateFI(FI);
6039 
6040   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
6041   if (!Op && N.getNode()) {
6042     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6043     Register Reg;
6044     if (ArgRegsAndSizes.size() == 1)
6045       Reg = ArgRegsAndSizes.front().first;
6046 
6047     if (Reg && Reg.isVirtual()) {
6048       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6049       Register PR = RegInfo.getLiveInPhysReg(Reg);
6050       if (PR)
6051         Reg = PR;
6052     }
6053     if (Reg) {
6054       Op = MachineOperand::CreateReg(Reg, false);
6055       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6056     }
6057   }
6058 
6059   if (!Op && N.getNode()) {
6060     // Check if frame index is available.
6061     SDValue LCandidate = peekThroughBitcasts(N);
6062     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6063       if (FrameIndexSDNode *FINode =
6064           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6065         Op = MachineOperand::CreateFI(FINode->getIndex());
6066   }
6067 
6068   if (!Op) {
6069     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6070     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
6071                                          SplitRegs) {
6072       unsigned Offset = 0;
6073       for (const auto &RegAndSize : SplitRegs) {
6074         // If the expression is already a fragment, the current register
6075         // offset+size might extend beyond the fragment. In this case, only
6076         // the register bits that are inside the fragment are relevant.
6077         int RegFragmentSizeInBits = RegAndSize.second;
6078         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6079           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6080           // The register is entirely outside the expression fragment,
6081           // so is irrelevant for debug info.
6082           if (Offset >= ExprFragmentSizeInBits)
6083             break;
6084           // The register is partially outside the expression fragment, only
6085           // the low bits within the fragment are relevant for debug info.
6086           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6087             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6088           }
6089         }
6090 
6091         auto FragmentExpr = DIExpression::createFragmentExpression(
6092             Expr, Offset, RegFragmentSizeInBits);
6093         Offset += RegAndSize.second;
6094         // If a valid fragment expression cannot be created, the variable's
6095         // correct value cannot be determined and so it is set as Undef.
6096         if (!FragmentExpr) {
6097           SDDbgValue *SDV = DAG.getConstantDbgValue(
6098               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6099           DAG.AddDbgValue(SDV, false);
6100           continue;
6101         }
6102         MachineInstr *NewMI =
6103             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6104                              Kind != FuncArgumentDbgValueKind::Value);
6105         FuncInfo.ArgDbgValues.push_back(NewMI);
6106       }
6107     };
6108 
6109     // Check if ValueMap has reg number.
6110     DenseMap<const Value *, Register>::const_iterator
6111       VMI = FuncInfo.ValueMap.find(V);
6112     if (VMI != FuncInfo.ValueMap.end()) {
6113       const auto &TLI = DAG.getTargetLoweringInfo();
6114       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6115                        V->getType(), std::nullopt);
6116       if (RFV.occupiesMultipleRegs()) {
6117         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6118         return true;
6119       }
6120 
6121       Op = MachineOperand::CreateReg(VMI->second, false);
6122       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6123     } else if (ArgRegsAndSizes.size() > 1) {
6124       // This was split due to the calling convention, and no virtual register
6125       // mapping exists for the value.
6126       splitMultiRegDbgValue(ArgRegsAndSizes);
6127       return true;
6128     }
6129   }
6130 
6131   if (!Op)
6132     return false;
6133 
6134   assert(Variable->isValidLocationForIntrinsic(DL) &&
6135          "Expected inlined-at fields to agree");
6136   MachineInstr *NewMI = nullptr;
6137 
6138   if (Op->isReg())
6139     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6140   else
6141     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6142                     Variable, Expr);
6143 
6144   // Otherwise, use ArgDbgValues.
6145   FuncInfo.ArgDbgValues.push_back(NewMI);
6146   return true;
6147 }
6148 
6149 /// Return the appropriate SDDbgValue based on N.
6150 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6151                                              DILocalVariable *Variable,
6152                                              DIExpression *Expr,
6153                                              const DebugLoc &dl,
6154                                              unsigned DbgSDNodeOrder) {
6155   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6156     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6157     // stack slot locations.
6158     //
6159     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6160     // debug values here after optimization:
6161     //
6162     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6163     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6164     //
6165     // Both describe the direct values of their associated variables.
6166     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6167                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6168   }
6169   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6170                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6171 }
6172 
6173 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6174   switch (Intrinsic) {
6175   case Intrinsic::smul_fix:
6176     return ISD::SMULFIX;
6177   case Intrinsic::umul_fix:
6178     return ISD::UMULFIX;
6179   case Intrinsic::smul_fix_sat:
6180     return ISD::SMULFIXSAT;
6181   case Intrinsic::umul_fix_sat:
6182     return ISD::UMULFIXSAT;
6183   case Intrinsic::sdiv_fix:
6184     return ISD::SDIVFIX;
6185   case Intrinsic::udiv_fix:
6186     return ISD::UDIVFIX;
6187   case Intrinsic::sdiv_fix_sat:
6188     return ISD::SDIVFIXSAT;
6189   case Intrinsic::udiv_fix_sat:
6190     return ISD::UDIVFIXSAT;
6191   default:
6192     llvm_unreachable("Unhandled fixed point intrinsic");
6193   }
6194 }
6195 
6196 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6197                                            const char *FunctionName) {
6198   assert(FunctionName && "FunctionName must not be nullptr");
6199   SDValue Callee = DAG.getExternalSymbol(
6200       FunctionName,
6201       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6202   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6203 }
6204 
6205 /// Given a @llvm.call.preallocated.setup, return the corresponding
6206 /// preallocated call.
6207 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6208   assert(cast<CallBase>(PreallocatedSetup)
6209                  ->getCalledFunction()
6210                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6211          "expected call_preallocated_setup Value");
6212   for (const auto *U : PreallocatedSetup->users()) {
6213     auto *UseCall = cast<CallBase>(U);
6214     const Function *Fn = UseCall->getCalledFunction();
6215     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6216       return UseCall;
6217     }
6218   }
6219   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6220 }
6221 
6222 /// If DI is a debug value with an EntryValue expression, lower it using the
6223 /// corresponding physical register of the associated Argument value
6224 /// (guaranteed to exist by the verifier).
6225 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6226     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6227     DIExpression *Expr, DebugLoc DbgLoc) {
6228   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6229     return false;
6230 
6231   // These properties are guaranteed by the verifier.
6232   const Argument *Arg = cast<Argument>(Values[0]);
6233   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6234 
6235   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6236   if (ArgIt == FuncInfo.ValueMap.end()) {
6237     LLVM_DEBUG(
6238         dbgs() << "Dropping dbg.value: expression is entry_value but "
6239                   "couldn't find an associated register for the Argument\n");
6240     return true;
6241   }
6242   Register ArgVReg = ArgIt->getSecond();
6243 
6244   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6245     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6246       SDDbgValue *SDV = DAG.getVRegDbgValue(
6247           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6248       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6249       return true;
6250     }
6251   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6252                        "couldn't find a physical register\n");
6253   return true;
6254 }
6255 
6256 /// Lower the call to the specified intrinsic function.
6257 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6258                                                   unsigned Intrinsic) {
6259   SDLoc sdl = getCurSDLoc();
6260   switch (Intrinsic) {
6261   case Intrinsic::experimental_convergence_anchor:
6262     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6263     break;
6264   case Intrinsic::experimental_convergence_entry:
6265     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6266     break;
6267   case Intrinsic::experimental_convergence_loop: {
6268     auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6269     auto *Token = Bundle->Inputs[0].get();
6270     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6271                              getValue(Token)));
6272     break;
6273   }
6274   }
6275 }
6276 
6277 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6278                                                unsigned IntrinsicID) {
6279   // For now, we're only lowering an 'add' histogram.
6280   // We can add others later, e.g. saturating adds, min/max.
6281   assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6282          "Tried to lower unsupported histogram type");
6283   SDLoc sdl = getCurSDLoc();
6284   Value *Ptr = I.getOperand(0);
6285   SDValue Inc = getValue(I.getOperand(1));
6286   SDValue Mask = getValue(I.getOperand(2));
6287 
6288   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6289   DataLayout TargetDL = DAG.getDataLayout();
6290   EVT VT = Inc.getValueType();
6291   Align Alignment = DAG.getEVTAlign(VT);
6292 
6293   const MDNode *Ranges = getRangeMetadata(I);
6294 
6295   SDValue Root = DAG.getRoot();
6296   SDValue Base;
6297   SDValue Index;
6298   ISD::MemIndexType IndexType;
6299   SDValue Scale;
6300   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
6301                                     I.getParent(), VT.getScalarStoreSize());
6302 
6303   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6304 
6305   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6306       MachinePointerInfo(AS),
6307       MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6308       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
6309 
6310   if (!UniformBase) {
6311     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6312     Index = getValue(Ptr);
6313     IndexType = ISD::SIGNED_SCALED;
6314     Scale =
6315         DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6316   }
6317 
6318   EVT IdxVT = Index.getValueType();
6319   EVT EltTy = IdxVT.getVectorElementType();
6320   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6321     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
6322     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6323   }
6324 
6325   SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6326 
6327   SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6328   SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6329                                              Ops, MMO, IndexType);
6330 
6331   setValue(&I, Histogram);
6332   DAG.setRoot(Histogram);
6333 }
6334 
6335 /// Lower the call to the specified intrinsic function.
6336 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6337                                              unsigned Intrinsic) {
6338   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6339   SDLoc sdl = getCurSDLoc();
6340   DebugLoc dl = getCurDebugLoc();
6341   SDValue Res;
6342 
6343   SDNodeFlags Flags;
6344   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6345     Flags.copyFMF(*FPOp);
6346 
6347   switch (Intrinsic) {
6348   default:
6349     // By default, turn this into a target intrinsic node.
6350     visitTargetIntrinsic(I, Intrinsic);
6351     return;
6352   case Intrinsic::vscale: {
6353     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6354     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6355     return;
6356   }
6357   case Intrinsic::vastart:  visitVAStart(I); return;
6358   case Intrinsic::vaend:    visitVAEnd(I); return;
6359   case Intrinsic::vacopy:   visitVACopy(I); return;
6360   case Intrinsic::returnaddress:
6361     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6362                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6363                              getValue(I.getArgOperand(0))));
6364     return;
6365   case Intrinsic::addressofreturnaddress:
6366     setValue(&I,
6367              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6368                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6369     return;
6370   case Intrinsic::sponentry:
6371     setValue(&I,
6372              DAG.getNode(ISD::SPONENTRY, sdl,
6373                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6374     return;
6375   case Intrinsic::frameaddress:
6376     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6377                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6378                              getValue(I.getArgOperand(0))));
6379     return;
6380   case Intrinsic::read_volatile_register:
6381   case Intrinsic::read_register: {
6382     Value *Reg = I.getArgOperand(0);
6383     SDValue Chain = getRoot();
6384     SDValue RegName =
6385         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6386     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6387     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6388       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6389     setValue(&I, Res);
6390     DAG.setRoot(Res.getValue(1));
6391     return;
6392   }
6393   case Intrinsic::write_register: {
6394     Value *Reg = I.getArgOperand(0);
6395     Value *RegValue = I.getArgOperand(1);
6396     SDValue Chain = getRoot();
6397     SDValue RegName =
6398         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6399     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6400                             RegName, getValue(RegValue)));
6401     return;
6402   }
6403   case Intrinsic::memcpy: {
6404     const auto &MCI = cast<MemCpyInst>(I);
6405     SDValue Op1 = getValue(I.getArgOperand(0));
6406     SDValue Op2 = getValue(I.getArgOperand(1));
6407     SDValue Op3 = getValue(I.getArgOperand(2));
6408     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6409     Align DstAlign = MCI.getDestAlign().valueOrOne();
6410     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6411     Align Alignment = std::min(DstAlign, SrcAlign);
6412     bool isVol = MCI.isVolatile();
6413     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6414     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6415     // node.
6416     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6417     SDValue MC = DAG.getMemcpy(
6418         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6419         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
6420         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6421     updateDAGForMaybeTailCall(MC);
6422     return;
6423   }
6424   case Intrinsic::memcpy_inline: {
6425     const auto &MCI = cast<MemCpyInlineInst>(I);
6426     SDValue Dst = getValue(I.getArgOperand(0));
6427     SDValue Src = getValue(I.getArgOperand(1));
6428     SDValue Size = getValue(I.getArgOperand(2));
6429     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6430     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6431     Align DstAlign = MCI.getDestAlign().valueOrOne();
6432     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6433     Align Alignment = std::min(DstAlign, SrcAlign);
6434     bool isVol = MCI.isVolatile();
6435     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6436     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6437     // node.
6438     SDValue MC = DAG.getMemcpy(
6439         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6440         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6441         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6442     updateDAGForMaybeTailCall(MC);
6443     return;
6444   }
6445   case Intrinsic::memset: {
6446     const auto &MSI = cast<MemSetInst>(I);
6447     SDValue Op1 = getValue(I.getArgOperand(0));
6448     SDValue Op2 = getValue(I.getArgOperand(1));
6449     SDValue Op3 = getValue(I.getArgOperand(2));
6450     // @llvm.memset defines 0 and 1 to both mean no alignment.
6451     Align Alignment = MSI.getDestAlign().valueOrOne();
6452     bool isVol = MSI.isVolatile();
6453     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6454     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6455     SDValue MS = DAG.getMemset(
6456         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6457         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6458     updateDAGForMaybeTailCall(MS);
6459     return;
6460   }
6461   case Intrinsic::memset_inline: {
6462     const auto &MSII = cast<MemSetInlineInst>(I);
6463     SDValue Dst = getValue(I.getArgOperand(0));
6464     SDValue Value = getValue(I.getArgOperand(1));
6465     SDValue Size = getValue(I.getArgOperand(2));
6466     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6467     // @llvm.memset defines 0 and 1 to both mean no alignment.
6468     Align DstAlign = MSII.getDestAlign().valueOrOne();
6469     bool isVol = MSII.isVolatile();
6470     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6471     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6472     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6473                                /* AlwaysInline */ true, isTC,
6474                                MachinePointerInfo(I.getArgOperand(0)),
6475                                I.getAAMetadata());
6476     updateDAGForMaybeTailCall(MC);
6477     return;
6478   }
6479   case Intrinsic::memmove: {
6480     const auto &MMI = cast<MemMoveInst>(I);
6481     SDValue Op1 = getValue(I.getArgOperand(0));
6482     SDValue Op2 = getValue(I.getArgOperand(1));
6483     SDValue Op3 = getValue(I.getArgOperand(2));
6484     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6485     Align DstAlign = MMI.getDestAlign().valueOrOne();
6486     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6487     Align Alignment = std::min(DstAlign, SrcAlign);
6488     bool isVol = MMI.isVolatile();
6489     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6490     // FIXME: Support passing different dest/src alignments to the memmove DAG
6491     // node.
6492     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6493     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6494                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6495                                 MachinePointerInfo(I.getArgOperand(1)),
6496                                 I.getAAMetadata(), AA);
6497     updateDAGForMaybeTailCall(MM);
6498     return;
6499   }
6500   case Intrinsic::memcpy_element_unordered_atomic: {
6501     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6502     SDValue Dst = getValue(MI.getRawDest());
6503     SDValue Src = getValue(MI.getRawSource());
6504     SDValue Length = getValue(MI.getLength());
6505 
6506     Type *LengthTy = MI.getLength()->getType();
6507     unsigned ElemSz = MI.getElementSizeInBytes();
6508     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6509     SDValue MC =
6510         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6511                             isTC, MachinePointerInfo(MI.getRawDest()),
6512                             MachinePointerInfo(MI.getRawSource()));
6513     updateDAGForMaybeTailCall(MC);
6514     return;
6515   }
6516   case Intrinsic::memmove_element_unordered_atomic: {
6517     auto &MI = cast<AtomicMemMoveInst>(I);
6518     SDValue Dst = getValue(MI.getRawDest());
6519     SDValue Src = getValue(MI.getRawSource());
6520     SDValue Length = getValue(MI.getLength());
6521 
6522     Type *LengthTy = MI.getLength()->getType();
6523     unsigned ElemSz = MI.getElementSizeInBytes();
6524     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6525     SDValue MC =
6526         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6527                              isTC, MachinePointerInfo(MI.getRawDest()),
6528                              MachinePointerInfo(MI.getRawSource()));
6529     updateDAGForMaybeTailCall(MC);
6530     return;
6531   }
6532   case Intrinsic::memset_element_unordered_atomic: {
6533     auto &MI = cast<AtomicMemSetInst>(I);
6534     SDValue Dst = getValue(MI.getRawDest());
6535     SDValue Val = getValue(MI.getValue());
6536     SDValue Length = getValue(MI.getLength());
6537 
6538     Type *LengthTy = MI.getLength()->getType();
6539     unsigned ElemSz = MI.getElementSizeInBytes();
6540     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6541     SDValue MC =
6542         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6543                             isTC, MachinePointerInfo(MI.getRawDest()));
6544     updateDAGForMaybeTailCall(MC);
6545     return;
6546   }
6547   case Intrinsic::call_preallocated_setup: {
6548     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6549     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6550     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6551                               getRoot(), SrcValue);
6552     setValue(&I, Res);
6553     DAG.setRoot(Res);
6554     return;
6555   }
6556   case Intrinsic::call_preallocated_arg: {
6557     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6558     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6559     SDValue Ops[3];
6560     Ops[0] = getRoot();
6561     Ops[1] = SrcValue;
6562     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6563                                    MVT::i32); // arg index
6564     SDValue Res = DAG.getNode(
6565         ISD::PREALLOCATED_ARG, sdl,
6566         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6567     setValue(&I, Res);
6568     DAG.setRoot(Res.getValue(1));
6569     return;
6570   }
6571   case Intrinsic::dbg_declare: {
6572     const auto &DI = cast<DbgDeclareInst>(I);
6573     // Debug intrinsics are handled separately in assignment tracking mode.
6574     // Some intrinsics are handled right after Argument lowering.
6575     if (AssignmentTrackingEnabled ||
6576         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6577       return;
6578     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6579     DILocalVariable *Variable = DI.getVariable();
6580     DIExpression *Expression = DI.getExpression();
6581     dropDanglingDebugInfo(Variable, Expression);
6582     // Assume dbg.declare can not currently use DIArgList, i.e.
6583     // it is non-variadic.
6584     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6585     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6586                        DI.getDebugLoc());
6587     return;
6588   }
6589   case Intrinsic::dbg_label: {
6590     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6591     DILabel *Label = DI.getLabel();
6592     assert(Label && "Missing label");
6593 
6594     SDDbgLabel *SDV;
6595     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6596     DAG.AddDbgLabel(SDV);
6597     return;
6598   }
6599   case Intrinsic::dbg_assign: {
6600     // Debug intrinsics are handled seperately in assignment tracking mode.
6601     if (AssignmentTrackingEnabled)
6602       return;
6603     // If assignment tracking hasn't been enabled then fall through and treat
6604     // the dbg.assign as a dbg.value.
6605     [[fallthrough]];
6606   }
6607   case Intrinsic::dbg_value: {
6608     // Debug intrinsics are handled seperately in assignment tracking mode.
6609     if (AssignmentTrackingEnabled)
6610       return;
6611     const DbgValueInst &DI = cast<DbgValueInst>(I);
6612     assert(DI.getVariable() && "Missing variable");
6613 
6614     DILocalVariable *Variable = DI.getVariable();
6615     DIExpression *Expression = DI.getExpression();
6616     dropDanglingDebugInfo(Variable, Expression);
6617 
6618     if (DI.isKillLocation()) {
6619       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6620       return;
6621     }
6622 
6623     SmallVector<Value *, 4> Values(DI.getValues());
6624     if (Values.empty())
6625       return;
6626 
6627     bool IsVariadic = DI.hasArgList();
6628     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6629                           SDNodeOrder, IsVariadic))
6630       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6631                            DI.getDebugLoc(), SDNodeOrder);
6632     return;
6633   }
6634 
6635   case Intrinsic::eh_typeid_for: {
6636     // Find the type id for the given typeinfo.
6637     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6638     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6639     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6640     setValue(&I, Res);
6641     return;
6642   }
6643 
6644   case Intrinsic::eh_return_i32:
6645   case Intrinsic::eh_return_i64:
6646     DAG.getMachineFunction().setCallsEHReturn(true);
6647     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6648                             MVT::Other,
6649                             getControlRoot(),
6650                             getValue(I.getArgOperand(0)),
6651                             getValue(I.getArgOperand(1))));
6652     return;
6653   case Intrinsic::eh_unwind_init:
6654     DAG.getMachineFunction().setCallsUnwindInit(true);
6655     return;
6656   case Intrinsic::eh_dwarf_cfa:
6657     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6658                              TLI.getPointerTy(DAG.getDataLayout()),
6659                              getValue(I.getArgOperand(0))));
6660     return;
6661   case Intrinsic::eh_sjlj_callsite: {
6662     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6663     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6664     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6665 
6666     MMI.setCurrentCallSite(CI->getZExtValue());
6667     return;
6668   }
6669   case Intrinsic::eh_sjlj_functioncontext: {
6670     // Get and store the index of the function context.
6671     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6672     AllocaInst *FnCtx =
6673       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6674     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6675     MFI.setFunctionContextIndex(FI);
6676     return;
6677   }
6678   case Intrinsic::eh_sjlj_setjmp: {
6679     SDValue Ops[2];
6680     Ops[0] = getRoot();
6681     Ops[1] = getValue(I.getArgOperand(0));
6682     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6683                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6684     setValue(&I, Op.getValue(0));
6685     DAG.setRoot(Op.getValue(1));
6686     return;
6687   }
6688   case Intrinsic::eh_sjlj_longjmp:
6689     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6690                             getRoot(), getValue(I.getArgOperand(0))));
6691     return;
6692   case Intrinsic::eh_sjlj_setup_dispatch:
6693     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6694                             getRoot()));
6695     return;
6696   case Intrinsic::masked_gather:
6697     visitMaskedGather(I);
6698     return;
6699   case Intrinsic::masked_load:
6700     visitMaskedLoad(I);
6701     return;
6702   case Intrinsic::masked_scatter:
6703     visitMaskedScatter(I);
6704     return;
6705   case Intrinsic::masked_store:
6706     visitMaskedStore(I);
6707     return;
6708   case Intrinsic::masked_expandload:
6709     visitMaskedLoad(I, true /* IsExpanding */);
6710     return;
6711   case Intrinsic::masked_compressstore:
6712     visitMaskedStore(I, true /* IsCompressing */);
6713     return;
6714   case Intrinsic::powi:
6715     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6716                             getValue(I.getArgOperand(1)), DAG));
6717     return;
6718   case Intrinsic::log:
6719     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6720     return;
6721   case Intrinsic::log2:
6722     setValue(&I,
6723              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6724     return;
6725   case Intrinsic::log10:
6726     setValue(&I,
6727              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6728     return;
6729   case Intrinsic::exp:
6730     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6731     return;
6732   case Intrinsic::exp2:
6733     setValue(&I,
6734              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6735     return;
6736   case Intrinsic::pow:
6737     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6738                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6739     return;
6740   case Intrinsic::sqrt:
6741   case Intrinsic::fabs:
6742   case Intrinsic::sin:
6743   case Intrinsic::cos:
6744   case Intrinsic::tan:
6745   case Intrinsic::exp10:
6746   case Intrinsic::floor:
6747   case Intrinsic::ceil:
6748   case Intrinsic::trunc:
6749   case Intrinsic::rint:
6750   case Intrinsic::nearbyint:
6751   case Intrinsic::round:
6752   case Intrinsic::roundeven:
6753   case Intrinsic::canonicalize: {
6754     unsigned Opcode;
6755     // clang-format off
6756     switch (Intrinsic) {
6757     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6758     case Intrinsic::sqrt:         Opcode = ISD::FSQRT;         break;
6759     case Intrinsic::fabs:         Opcode = ISD::FABS;          break;
6760     case Intrinsic::sin:          Opcode = ISD::FSIN;          break;
6761     case Intrinsic::cos:          Opcode = ISD::FCOS;          break;
6762     case Intrinsic::tan:          Opcode = ISD::FTAN;          break;
6763     case Intrinsic::exp10:        Opcode = ISD::FEXP10;        break;
6764     case Intrinsic::floor:        Opcode = ISD::FFLOOR;        break;
6765     case Intrinsic::ceil:         Opcode = ISD::FCEIL;         break;
6766     case Intrinsic::trunc:        Opcode = ISD::FTRUNC;        break;
6767     case Intrinsic::rint:         Opcode = ISD::FRINT;         break;
6768     case Intrinsic::nearbyint:    Opcode = ISD::FNEARBYINT;    break;
6769     case Intrinsic::round:        Opcode = ISD::FROUND;        break;
6770     case Intrinsic::roundeven:    Opcode = ISD::FROUNDEVEN;    break;
6771     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6772     }
6773     // clang-format on
6774 
6775     setValue(&I, DAG.getNode(Opcode, sdl,
6776                              getValue(I.getArgOperand(0)).getValueType(),
6777                              getValue(I.getArgOperand(0)), Flags));
6778     return;
6779   }
6780   case Intrinsic::lround:
6781   case Intrinsic::llround:
6782   case Intrinsic::lrint:
6783   case Intrinsic::llrint: {
6784     unsigned Opcode;
6785     // clang-format off
6786     switch (Intrinsic) {
6787     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6788     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6789     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6790     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6791     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6792     }
6793     // clang-format on
6794 
6795     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6796     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6797                              getValue(I.getArgOperand(0))));
6798     return;
6799   }
6800   case Intrinsic::minnum:
6801     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6802                              getValue(I.getArgOperand(0)).getValueType(),
6803                              getValue(I.getArgOperand(0)),
6804                              getValue(I.getArgOperand(1)), Flags));
6805     return;
6806   case Intrinsic::maxnum:
6807     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6808                              getValue(I.getArgOperand(0)).getValueType(),
6809                              getValue(I.getArgOperand(0)),
6810                              getValue(I.getArgOperand(1)), Flags));
6811     return;
6812   case Intrinsic::minimum:
6813     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6814                              getValue(I.getArgOperand(0)).getValueType(),
6815                              getValue(I.getArgOperand(0)),
6816                              getValue(I.getArgOperand(1)), Flags));
6817     return;
6818   case Intrinsic::maximum:
6819     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6820                              getValue(I.getArgOperand(0)).getValueType(),
6821                              getValue(I.getArgOperand(0)),
6822                              getValue(I.getArgOperand(1)), Flags));
6823     return;
6824   case Intrinsic::copysign:
6825     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6826                              getValue(I.getArgOperand(0)).getValueType(),
6827                              getValue(I.getArgOperand(0)),
6828                              getValue(I.getArgOperand(1)), Flags));
6829     return;
6830   case Intrinsic::ldexp:
6831     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6832                              getValue(I.getArgOperand(0)).getValueType(),
6833                              getValue(I.getArgOperand(0)),
6834                              getValue(I.getArgOperand(1)), Flags));
6835     return;
6836   case Intrinsic::frexp: {
6837     SmallVector<EVT, 2> ValueVTs;
6838     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6839     SDVTList VTs = DAG.getVTList(ValueVTs);
6840     setValue(&I,
6841              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6842     return;
6843   }
6844   case Intrinsic::arithmetic_fence: {
6845     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6846                              getValue(I.getArgOperand(0)).getValueType(),
6847                              getValue(I.getArgOperand(0)), Flags));
6848     return;
6849   }
6850   case Intrinsic::fma:
6851     setValue(&I, DAG.getNode(
6852                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6853                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6854                      getValue(I.getArgOperand(2)), Flags));
6855     return;
6856 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6857   case Intrinsic::INTRINSIC:
6858 #include "llvm/IR/ConstrainedOps.def"
6859     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6860     return;
6861 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6862 #include "llvm/IR/VPIntrinsics.def"
6863     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6864     return;
6865   case Intrinsic::fptrunc_round: {
6866     // Get the last argument, the metadata and convert it to an integer in the
6867     // call
6868     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6869     std::optional<RoundingMode> RoundMode =
6870         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6871 
6872     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6873 
6874     // Propagate fast-math-flags from IR to node(s).
6875     SDNodeFlags Flags;
6876     Flags.copyFMF(*cast<FPMathOperator>(&I));
6877     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6878 
6879     SDValue Result;
6880     Result = DAG.getNode(
6881         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6882         DAG.getTargetConstant((int)*RoundMode, sdl,
6883                               TLI.getPointerTy(DAG.getDataLayout())));
6884     setValue(&I, Result);
6885 
6886     return;
6887   }
6888   case Intrinsic::fmuladd: {
6889     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6890     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6891         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6892       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6893                                getValue(I.getArgOperand(0)).getValueType(),
6894                                getValue(I.getArgOperand(0)),
6895                                getValue(I.getArgOperand(1)),
6896                                getValue(I.getArgOperand(2)), Flags));
6897     } else {
6898       // TODO: Intrinsic calls should have fast-math-flags.
6899       SDValue Mul = DAG.getNode(
6900           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6901           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6902       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6903                                 getValue(I.getArgOperand(0)).getValueType(),
6904                                 Mul, getValue(I.getArgOperand(2)), Flags);
6905       setValue(&I, Add);
6906     }
6907     return;
6908   }
6909   case Intrinsic::convert_to_fp16:
6910     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6911                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6912                                          getValue(I.getArgOperand(0)),
6913                                          DAG.getTargetConstant(0, sdl,
6914                                                                MVT::i32))));
6915     return;
6916   case Intrinsic::convert_from_fp16:
6917     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6918                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6919                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6920                                          getValue(I.getArgOperand(0)))));
6921     return;
6922   case Intrinsic::fptosi_sat: {
6923     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6924     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6925                              getValue(I.getArgOperand(0)),
6926                              DAG.getValueType(VT.getScalarType())));
6927     return;
6928   }
6929   case Intrinsic::fptoui_sat: {
6930     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6931     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6932                              getValue(I.getArgOperand(0)),
6933                              DAG.getValueType(VT.getScalarType())));
6934     return;
6935   }
6936   case Intrinsic::set_rounding:
6937     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6938                       {getRoot(), getValue(I.getArgOperand(0))});
6939     setValue(&I, Res);
6940     DAG.setRoot(Res.getValue(0));
6941     return;
6942   case Intrinsic::is_fpclass: {
6943     const DataLayout DLayout = DAG.getDataLayout();
6944     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6945     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6946     FPClassTest Test = static_cast<FPClassTest>(
6947         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6948     MachineFunction &MF = DAG.getMachineFunction();
6949     const Function &F = MF.getFunction();
6950     SDValue Op = getValue(I.getArgOperand(0));
6951     SDNodeFlags Flags;
6952     Flags.setNoFPExcept(
6953         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6954     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6955     // expansion can use illegal types. Making expansion early allows
6956     // legalizing these types prior to selection.
6957     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6958       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6959       setValue(&I, Result);
6960       return;
6961     }
6962 
6963     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6964     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6965     setValue(&I, V);
6966     return;
6967   }
6968   case Intrinsic::get_fpenv: {
6969     const DataLayout DLayout = DAG.getDataLayout();
6970     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
6971     Align TempAlign = DAG.getEVTAlign(EnvVT);
6972     SDValue Chain = getRoot();
6973     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
6974     // and temporary storage in stack.
6975     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
6976       Res = DAG.getNode(
6977           ISD::GET_FPENV, sdl,
6978           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6979                         MVT::Other),
6980           Chain);
6981     } else {
6982       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6983       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6984       auto MPI =
6985           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6986       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6987           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
6988           TempAlign);
6989       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6990       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
6991     }
6992     setValue(&I, Res);
6993     DAG.setRoot(Res.getValue(1));
6994     return;
6995   }
6996   case Intrinsic::set_fpenv: {
6997     const DataLayout DLayout = DAG.getDataLayout();
6998     SDValue Env = getValue(I.getArgOperand(0));
6999     EVT EnvVT = Env.getValueType();
7000     Align TempAlign = DAG.getEVTAlign(EnvVT);
7001     SDValue Chain = getRoot();
7002     // If SET_FPENV is custom or legal, use it. Otherwise use loading
7003     // environment from memory.
7004     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7005       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7006     } else {
7007       // Allocate space in stack, copy environment bits into it and use this
7008       // memory in SET_FPENV_MEM.
7009       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7010       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7011       auto MPI =
7012           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7013       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7014                            MachineMemOperand::MOStore);
7015       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7016           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
7017           TempAlign);
7018       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7019     }
7020     DAG.setRoot(Chain);
7021     return;
7022   }
7023   case Intrinsic::reset_fpenv:
7024     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7025     return;
7026   case Intrinsic::get_fpmode:
7027     Res = DAG.getNode(
7028         ISD::GET_FPMODE, sdl,
7029         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7030                       MVT::Other),
7031         DAG.getRoot());
7032     setValue(&I, Res);
7033     DAG.setRoot(Res.getValue(1));
7034     return;
7035   case Intrinsic::set_fpmode:
7036     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7037                       getValue(I.getArgOperand(0)));
7038     DAG.setRoot(Res);
7039     return;
7040   case Intrinsic::reset_fpmode: {
7041     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7042     DAG.setRoot(Res);
7043     return;
7044   }
7045   case Intrinsic::pcmarker: {
7046     SDValue Tmp = getValue(I.getArgOperand(0));
7047     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7048     return;
7049   }
7050   case Intrinsic::readcyclecounter: {
7051     SDValue Op = getRoot();
7052     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7053                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7054     setValue(&I, Res);
7055     DAG.setRoot(Res.getValue(1));
7056     return;
7057   }
7058   case Intrinsic::readsteadycounter: {
7059     SDValue Op = getRoot();
7060     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7061                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7062     setValue(&I, Res);
7063     DAG.setRoot(Res.getValue(1));
7064     return;
7065   }
7066   case Intrinsic::bitreverse:
7067     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7068                              getValue(I.getArgOperand(0)).getValueType(),
7069                              getValue(I.getArgOperand(0))));
7070     return;
7071   case Intrinsic::bswap:
7072     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7073                              getValue(I.getArgOperand(0)).getValueType(),
7074                              getValue(I.getArgOperand(0))));
7075     return;
7076   case Intrinsic::cttz: {
7077     SDValue Arg = getValue(I.getArgOperand(0));
7078     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7079     EVT Ty = Arg.getValueType();
7080     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7081                              sdl, Ty, Arg));
7082     return;
7083   }
7084   case Intrinsic::ctlz: {
7085     SDValue Arg = getValue(I.getArgOperand(0));
7086     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7087     EVT Ty = Arg.getValueType();
7088     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7089                              sdl, Ty, Arg));
7090     return;
7091   }
7092   case Intrinsic::ctpop: {
7093     SDValue Arg = getValue(I.getArgOperand(0));
7094     EVT Ty = Arg.getValueType();
7095     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7096     return;
7097   }
7098   case Intrinsic::fshl:
7099   case Intrinsic::fshr: {
7100     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7101     SDValue X = getValue(I.getArgOperand(0));
7102     SDValue Y = getValue(I.getArgOperand(1));
7103     SDValue Z = getValue(I.getArgOperand(2));
7104     EVT VT = X.getValueType();
7105 
7106     if (X == Y) {
7107       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7108       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7109     } else {
7110       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7111       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7112     }
7113     return;
7114   }
7115   case Intrinsic::sadd_sat: {
7116     SDValue Op1 = getValue(I.getArgOperand(0));
7117     SDValue Op2 = getValue(I.getArgOperand(1));
7118     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7119     return;
7120   }
7121   case Intrinsic::uadd_sat: {
7122     SDValue Op1 = getValue(I.getArgOperand(0));
7123     SDValue Op2 = getValue(I.getArgOperand(1));
7124     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7125     return;
7126   }
7127   case Intrinsic::ssub_sat: {
7128     SDValue Op1 = getValue(I.getArgOperand(0));
7129     SDValue Op2 = getValue(I.getArgOperand(1));
7130     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7131     return;
7132   }
7133   case Intrinsic::usub_sat: {
7134     SDValue Op1 = getValue(I.getArgOperand(0));
7135     SDValue Op2 = getValue(I.getArgOperand(1));
7136     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7137     return;
7138   }
7139   case Intrinsic::sshl_sat: {
7140     SDValue Op1 = getValue(I.getArgOperand(0));
7141     SDValue Op2 = getValue(I.getArgOperand(1));
7142     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7143     return;
7144   }
7145   case Intrinsic::ushl_sat: {
7146     SDValue Op1 = getValue(I.getArgOperand(0));
7147     SDValue Op2 = getValue(I.getArgOperand(1));
7148     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7149     return;
7150   }
7151   case Intrinsic::smul_fix:
7152   case Intrinsic::umul_fix:
7153   case Intrinsic::smul_fix_sat:
7154   case Intrinsic::umul_fix_sat: {
7155     SDValue Op1 = getValue(I.getArgOperand(0));
7156     SDValue Op2 = getValue(I.getArgOperand(1));
7157     SDValue Op3 = getValue(I.getArgOperand(2));
7158     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7159                              Op1.getValueType(), Op1, Op2, Op3));
7160     return;
7161   }
7162   case Intrinsic::sdiv_fix:
7163   case Intrinsic::udiv_fix:
7164   case Intrinsic::sdiv_fix_sat:
7165   case Intrinsic::udiv_fix_sat: {
7166     SDValue Op1 = getValue(I.getArgOperand(0));
7167     SDValue Op2 = getValue(I.getArgOperand(1));
7168     SDValue Op3 = getValue(I.getArgOperand(2));
7169     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7170                               Op1, Op2, Op3, DAG, TLI));
7171     return;
7172   }
7173   case Intrinsic::smax: {
7174     SDValue Op1 = getValue(I.getArgOperand(0));
7175     SDValue Op2 = getValue(I.getArgOperand(1));
7176     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7177     return;
7178   }
7179   case Intrinsic::smin: {
7180     SDValue Op1 = getValue(I.getArgOperand(0));
7181     SDValue Op2 = getValue(I.getArgOperand(1));
7182     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7183     return;
7184   }
7185   case Intrinsic::umax: {
7186     SDValue Op1 = getValue(I.getArgOperand(0));
7187     SDValue Op2 = getValue(I.getArgOperand(1));
7188     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7189     return;
7190   }
7191   case Intrinsic::umin: {
7192     SDValue Op1 = getValue(I.getArgOperand(0));
7193     SDValue Op2 = getValue(I.getArgOperand(1));
7194     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7195     return;
7196   }
7197   case Intrinsic::abs: {
7198     // TODO: Preserve "int min is poison" arg in SDAG?
7199     SDValue Op1 = getValue(I.getArgOperand(0));
7200     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7201     return;
7202   }
7203   case Intrinsic::stacksave: {
7204     SDValue Op = getRoot();
7205     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7206     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7207     setValue(&I, Res);
7208     DAG.setRoot(Res.getValue(1));
7209     return;
7210   }
7211   case Intrinsic::stackrestore:
7212     Res = getValue(I.getArgOperand(0));
7213     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7214     return;
7215   case Intrinsic::get_dynamic_area_offset: {
7216     SDValue Op = getRoot();
7217     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7218     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7219     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7220     // target.
7221     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7222       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7223                          " intrinsic!");
7224     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7225                       Op);
7226     DAG.setRoot(Op);
7227     setValue(&I, Res);
7228     return;
7229   }
7230   case Intrinsic::stackguard: {
7231     MachineFunction &MF = DAG.getMachineFunction();
7232     const Module &M = *MF.getFunction().getParent();
7233     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7234     SDValue Chain = getRoot();
7235     if (TLI.useLoadStackGuardNode()) {
7236       Res = getLoadStackGuard(DAG, sdl, Chain);
7237       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7238     } else {
7239       const Value *Global = TLI.getSDagStackGuard(M);
7240       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7241       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7242                         MachinePointerInfo(Global, 0), Align,
7243                         MachineMemOperand::MOVolatile);
7244     }
7245     if (TLI.useStackGuardXorFP())
7246       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7247     DAG.setRoot(Chain);
7248     setValue(&I, Res);
7249     return;
7250   }
7251   case Intrinsic::stackprotector: {
7252     // Emit code into the DAG to store the stack guard onto the stack.
7253     MachineFunction &MF = DAG.getMachineFunction();
7254     MachineFrameInfo &MFI = MF.getFrameInfo();
7255     SDValue Src, Chain = getRoot();
7256 
7257     if (TLI.useLoadStackGuardNode())
7258       Src = getLoadStackGuard(DAG, sdl, Chain);
7259     else
7260       Src = getValue(I.getArgOperand(0));   // The guard's value.
7261 
7262     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7263 
7264     int FI = FuncInfo.StaticAllocaMap[Slot];
7265     MFI.setStackProtectorIndex(FI);
7266     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7267 
7268     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7269 
7270     // Store the stack protector onto the stack.
7271     Res = DAG.getStore(
7272         Chain, sdl, Src, FIN,
7273         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7274         MaybeAlign(), MachineMemOperand::MOVolatile);
7275     setValue(&I, Res);
7276     DAG.setRoot(Res);
7277     return;
7278   }
7279   case Intrinsic::objectsize:
7280     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7281 
7282   case Intrinsic::is_constant:
7283     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7284 
7285   case Intrinsic::annotation:
7286   case Intrinsic::ptr_annotation:
7287   case Intrinsic::launder_invariant_group:
7288   case Intrinsic::strip_invariant_group:
7289     // Drop the intrinsic, but forward the value
7290     setValue(&I, getValue(I.getOperand(0)));
7291     return;
7292 
7293   case Intrinsic::assume:
7294   case Intrinsic::experimental_noalias_scope_decl:
7295   case Intrinsic::var_annotation:
7296   case Intrinsic::sideeffect:
7297     // Discard annotate attributes, noalias scope declarations, assumptions, and
7298     // artificial side-effects.
7299     return;
7300 
7301   case Intrinsic::codeview_annotation: {
7302     // Emit a label associated with this metadata.
7303     MachineFunction &MF = DAG.getMachineFunction();
7304     MCSymbol *Label =
7305         MF.getMMI().getContext().createTempSymbol("annotation", true);
7306     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7307     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7308     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7309     DAG.setRoot(Res);
7310     return;
7311   }
7312 
7313   case Intrinsic::init_trampoline: {
7314     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7315 
7316     SDValue Ops[6];
7317     Ops[0] = getRoot();
7318     Ops[1] = getValue(I.getArgOperand(0));
7319     Ops[2] = getValue(I.getArgOperand(1));
7320     Ops[3] = getValue(I.getArgOperand(2));
7321     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7322     Ops[5] = DAG.getSrcValue(F);
7323 
7324     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7325 
7326     DAG.setRoot(Res);
7327     return;
7328   }
7329   case Intrinsic::adjust_trampoline:
7330     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7331                              TLI.getPointerTy(DAG.getDataLayout()),
7332                              getValue(I.getArgOperand(0))));
7333     return;
7334   case Intrinsic::gcroot: {
7335     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7336            "only valid in functions with gc specified, enforced by Verifier");
7337     assert(GFI && "implied by previous");
7338     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7339     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7340 
7341     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7342     GFI->addStackRoot(FI->getIndex(), TypeMap);
7343     return;
7344   }
7345   case Intrinsic::gcread:
7346   case Intrinsic::gcwrite:
7347     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7348   case Intrinsic::get_rounding:
7349     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7350     setValue(&I, Res);
7351     DAG.setRoot(Res.getValue(1));
7352     return;
7353 
7354   case Intrinsic::expect:
7355     // Just replace __builtin_expect(exp, c) with EXP.
7356     setValue(&I, getValue(I.getArgOperand(0)));
7357     return;
7358 
7359   case Intrinsic::ubsantrap:
7360   case Intrinsic::debugtrap:
7361   case Intrinsic::trap: {
7362     StringRef TrapFuncName =
7363         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7364     if (TrapFuncName.empty()) {
7365       switch (Intrinsic) {
7366       case Intrinsic::trap:
7367         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7368         break;
7369       case Intrinsic::debugtrap:
7370         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7371         break;
7372       case Intrinsic::ubsantrap:
7373         DAG.setRoot(DAG.getNode(
7374             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7375             DAG.getTargetConstant(
7376                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7377                 MVT::i32)));
7378         break;
7379       default: llvm_unreachable("unknown trap intrinsic");
7380       }
7381       return;
7382     }
7383     TargetLowering::ArgListTy Args;
7384     if (Intrinsic == Intrinsic::ubsantrap) {
7385       Args.push_back(TargetLoweringBase::ArgListEntry());
7386       Args[0].Val = I.getArgOperand(0);
7387       Args[0].Node = getValue(Args[0].Val);
7388       Args[0].Ty = Args[0].Val->getType();
7389     }
7390 
7391     TargetLowering::CallLoweringInfo CLI(DAG);
7392     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7393         CallingConv::C, I.getType(),
7394         DAG.getExternalSymbol(TrapFuncName.data(),
7395                               TLI.getPointerTy(DAG.getDataLayout())),
7396         std::move(Args));
7397 
7398     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7399     DAG.setRoot(Result.second);
7400     return;
7401   }
7402 
7403   case Intrinsic::allow_runtime_check:
7404   case Intrinsic::allow_ubsan_check:
7405     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7406     return;
7407 
7408   case Intrinsic::uadd_with_overflow:
7409   case Intrinsic::sadd_with_overflow:
7410   case Intrinsic::usub_with_overflow:
7411   case Intrinsic::ssub_with_overflow:
7412   case Intrinsic::umul_with_overflow:
7413   case Intrinsic::smul_with_overflow: {
7414     ISD::NodeType Op;
7415     switch (Intrinsic) {
7416     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7417     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7418     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7419     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7420     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7421     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7422     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7423     }
7424     SDValue Op1 = getValue(I.getArgOperand(0));
7425     SDValue Op2 = getValue(I.getArgOperand(1));
7426 
7427     EVT ResultVT = Op1.getValueType();
7428     EVT OverflowVT = MVT::i1;
7429     if (ResultVT.isVector())
7430       OverflowVT = EVT::getVectorVT(
7431           *Context, OverflowVT, ResultVT.getVectorElementCount());
7432 
7433     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7434     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7435     return;
7436   }
7437   case Intrinsic::prefetch: {
7438     SDValue Ops[5];
7439     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7440     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7441     Ops[0] = DAG.getRoot();
7442     Ops[1] = getValue(I.getArgOperand(0));
7443     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7444                                    MVT::i32);
7445     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7446                                    MVT::i32);
7447     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7448                                    MVT::i32);
7449     SDValue Result = DAG.getMemIntrinsicNode(
7450         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7451         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7452         /* align */ std::nullopt, Flags);
7453 
7454     // Chain the prefetch in parallel with any pending loads, to stay out of
7455     // the way of later optimizations.
7456     PendingLoads.push_back(Result);
7457     Result = getRoot();
7458     DAG.setRoot(Result);
7459     return;
7460   }
7461   case Intrinsic::lifetime_start:
7462   case Intrinsic::lifetime_end: {
7463     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7464     // Stack coloring is not enabled in O0, discard region information.
7465     if (TM.getOptLevel() == CodeGenOptLevel::None)
7466       return;
7467 
7468     const int64_t ObjectSize =
7469         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7470     Value *const ObjectPtr = I.getArgOperand(1);
7471     SmallVector<const Value *, 4> Allocas;
7472     getUnderlyingObjects(ObjectPtr, Allocas);
7473 
7474     for (const Value *Alloca : Allocas) {
7475       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7476 
7477       // Could not find an Alloca.
7478       if (!LifetimeObject)
7479         continue;
7480 
7481       // First check that the Alloca is static, otherwise it won't have a
7482       // valid frame index.
7483       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7484       if (SI == FuncInfo.StaticAllocaMap.end())
7485         return;
7486 
7487       const int FrameIndex = SI->second;
7488       int64_t Offset;
7489       if (GetPointerBaseWithConstantOffset(
7490               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7491         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7492       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7493                                 Offset);
7494       DAG.setRoot(Res);
7495     }
7496     return;
7497   }
7498   case Intrinsic::pseudoprobe: {
7499     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7500     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7501     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7502     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7503     DAG.setRoot(Res);
7504     return;
7505   }
7506   case Intrinsic::invariant_start:
7507     // Discard region information.
7508     setValue(&I,
7509              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7510     return;
7511   case Intrinsic::invariant_end:
7512     // Discard region information.
7513     return;
7514   case Intrinsic::clear_cache: {
7515     SDValue InputChain = DAG.getRoot();
7516     SDValue StartVal = getValue(I.getArgOperand(0));
7517     SDValue EndVal = getValue(I.getArgOperand(1));
7518     Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7519                       {InputChain, StartVal, EndVal});
7520     setValue(&I, Res);
7521     DAG.setRoot(Res);
7522     return;
7523   }
7524   case Intrinsic::donothing:
7525   case Intrinsic::seh_try_begin:
7526   case Intrinsic::seh_scope_begin:
7527   case Intrinsic::seh_try_end:
7528   case Intrinsic::seh_scope_end:
7529     // ignore
7530     return;
7531   case Intrinsic::experimental_stackmap:
7532     visitStackmap(I);
7533     return;
7534   case Intrinsic::experimental_patchpoint_void:
7535   case Intrinsic::experimental_patchpoint:
7536     visitPatchpoint(I);
7537     return;
7538   case Intrinsic::experimental_gc_statepoint:
7539     LowerStatepoint(cast<GCStatepointInst>(I));
7540     return;
7541   case Intrinsic::experimental_gc_result:
7542     visitGCResult(cast<GCResultInst>(I));
7543     return;
7544   case Intrinsic::experimental_gc_relocate:
7545     visitGCRelocate(cast<GCRelocateInst>(I));
7546     return;
7547   case Intrinsic::instrprof_cover:
7548     llvm_unreachable("instrprof failed to lower a cover");
7549   case Intrinsic::instrprof_increment:
7550     llvm_unreachable("instrprof failed to lower an increment");
7551   case Intrinsic::instrprof_timestamp:
7552     llvm_unreachable("instrprof failed to lower a timestamp");
7553   case Intrinsic::instrprof_value_profile:
7554     llvm_unreachable("instrprof failed to lower a value profiling call");
7555   case Intrinsic::instrprof_mcdc_parameters:
7556     llvm_unreachable("instrprof failed to lower mcdc parameters");
7557   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7558     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7559   case Intrinsic::instrprof_mcdc_condbitmap_update:
7560     llvm_unreachable("instrprof failed to lower an mcdc condbitmap update");
7561   case Intrinsic::localescape: {
7562     MachineFunction &MF = DAG.getMachineFunction();
7563     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7564 
7565     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7566     // is the same on all targets.
7567     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7568       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7569       if (isa<ConstantPointerNull>(Arg))
7570         continue; // Skip null pointers. They represent a hole in index space.
7571       AllocaInst *Slot = cast<AllocaInst>(Arg);
7572       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7573              "can only escape static allocas");
7574       int FI = FuncInfo.StaticAllocaMap[Slot];
7575       MCSymbol *FrameAllocSym =
7576           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7577               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7578       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7579               TII->get(TargetOpcode::LOCAL_ESCAPE))
7580           .addSym(FrameAllocSym)
7581           .addFrameIndex(FI);
7582     }
7583 
7584     return;
7585   }
7586 
7587   case Intrinsic::localrecover: {
7588     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7589     MachineFunction &MF = DAG.getMachineFunction();
7590 
7591     // Get the symbol that defines the frame offset.
7592     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7593     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7594     unsigned IdxVal =
7595         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7596     MCSymbol *FrameAllocSym =
7597         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7598             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7599 
7600     Value *FP = I.getArgOperand(1);
7601     SDValue FPVal = getValue(FP);
7602     EVT PtrVT = FPVal.getValueType();
7603 
7604     // Create a MCSymbol for the label to avoid any target lowering
7605     // that would make this PC relative.
7606     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7607     SDValue OffsetVal =
7608         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7609 
7610     // Add the offset to the FP.
7611     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7612     setValue(&I, Add);
7613 
7614     return;
7615   }
7616 
7617   case Intrinsic::eh_exceptionpointer:
7618   case Intrinsic::eh_exceptioncode: {
7619     // Get the exception pointer vreg, copy from it, and resize it to fit.
7620     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7621     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7622     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7623     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7624     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7625     if (Intrinsic == Intrinsic::eh_exceptioncode)
7626       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7627     setValue(&I, N);
7628     return;
7629   }
7630   case Intrinsic::xray_customevent: {
7631     // Here we want to make sure that the intrinsic behaves as if it has a
7632     // specific calling convention.
7633     const auto &Triple = DAG.getTarget().getTargetTriple();
7634     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7635       return;
7636 
7637     SmallVector<SDValue, 8> Ops;
7638 
7639     // We want to say that we always want the arguments in registers.
7640     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7641     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7642     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7643     SDValue Chain = getRoot();
7644     Ops.push_back(LogEntryVal);
7645     Ops.push_back(StrSizeVal);
7646     Ops.push_back(Chain);
7647 
7648     // We need to enforce the calling convention for the callsite, so that
7649     // argument ordering is enforced correctly, and that register allocation can
7650     // see that some registers may be assumed clobbered and have to preserve
7651     // them across calls to the intrinsic.
7652     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7653                                            sdl, NodeTys, Ops);
7654     SDValue patchableNode = SDValue(MN, 0);
7655     DAG.setRoot(patchableNode);
7656     setValue(&I, patchableNode);
7657     return;
7658   }
7659   case Intrinsic::xray_typedevent: {
7660     // Here we want to make sure that the intrinsic behaves as if it has a
7661     // specific calling convention.
7662     const auto &Triple = DAG.getTarget().getTargetTriple();
7663     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7664       return;
7665 
7666     SmallVector<SDValue, 8> Ops;
7667 
7668     // We want to say that we always want the arguments in registers.
7669     // It's unclear to me how manipulating the selection DAG here forces callers
7670     // to provide arguments in registers instead of on the stack.
7671     SDValue LogTypeId = getValue(I.getArgOperand(0));
7672     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7673     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7674     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7675     SDValue Chain = getRoot();
7676     Ops.push_back(LogTypeId);
7677     Ops.push_back(LogEntryVal);
7678     Ops.push_back(StrSizeVal);
7679     Ops.push_back(Chain);
7680 
7681     // We need to enforce the calling convention for the callsite, so that
7682     // argument ordering is enforced correctly, and that register allocation can
7683     // see that some registers may be assumed clobbered and have to preserve
7684     // them across calls to the intrinsic.
7685     MachineSDNode *MN = DAG.getMachineNode(
7686         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7687     SDValue patchableNode = SDValue(MN, 0);
7688     DAG.setRoot(patchableNode);
7689     setValue(&I, patchableNode);
7690     return;
7691   }
7692   case Intrinsic::experimental_deoptimize:
7693     LowerDeoptimizeCall(&I);
7694     return;
7695   case Intrinsic::experimental_stepvector:
7696     visitStepVector(I);
7697     return;
7698   case Intrinsic::vector_reduce_fadd:
7699   case Intrinsic::vector_reduce_fmul:
7700   case Intrinsic::vector_reduce_add:
7701   case Intrinsic::vector_reduce_mul:
7702   case Intrinsic::vector_reduce_and:
7703   case Intrinsic::vector_reduce_or:
7704   case Intrinsic::vector_reduce_xor:
7705   case Intrinsic::vector_reduce_smax:
7706   case Intrinsic::vector_reduce_smin:
7707   case Intrinsic::vector_reduce_umax:
7708   case Intrinsic::vector_reduce_umin:
7709   case Intrinsic::vector_reduce_fmax:
7710   case Intrinsic::vector_reduce_fmin:
7711   case Intrinsic::vector_reduce_fmaximum:
7712   case Intrinsic::vector_reduce_fminimum:
7713     visitVectorReduce(I, Intrinsic);
7714     return;
7715 
7716   case Intrinsic::icall_branch_funnel: {
7717     SmallVector<SDValue, 16> Ops;
7718     Ops.push_back(getValue(I.getArgOperand(0)));
7719 
7720     int64_t Offset;
7721     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7722         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7723     if (!Base)
7724       report_fatal_error(
7725           "llvm.icall.branch.funnel operand must be a GlobalValue");
7726     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7727 
7728     struct BranchFunnelTarget {
7729       int64_t Offset;
7730       SDValue Target;
7731     };
7732     SmallVector<BranchFunnelTarget, 8> Targets;
7733 
7734     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7735       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7736           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7737       if (ElemBase != Base)
7738         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7739                            "to the same GlobalValue");
7740 
7741       SDValue Val = getValue(I.getArgOperand(Op + 1));
7742       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7743       if (!GA)
7744         report_fatal_error(
7745             "llvm.icall.branch.funnel operand must be a GlobalValue");
7746       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7747                                      GA->getGlobal(), sdl, Val.getValueType(),
7748                                      GA->getOffset())});
7749     }
7750     llvm::sort(Targets,
7751                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7752                  return T1.Offset < T2.Offset;
7753                });
7754 
7755     for (auto &T : Targets) {
7756       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7757       Ops.push_back(T.Target);
7758     }
7759 
7760     Ops.push_back(DAG.getRoot()); // Chain
7761     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7762                                  MVT::Other, Ops),
7763               0);
7764     DAG.setRoot(N);
7765     setValue(&I, N);
7766     HasTailCall = true;
7767     return;
7768   }
7769 
7770   case Intrinsic::wasm_landingpad_index:
7771     // Information this intrinsic contained has been transferred to
7772     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7773     // delete it now.
7774     return;
7775 
7776   case Intrinsic::aarch64_settag:
7777   case Intrinsic::aarch64_settag_zero: {
7778     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7779     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7780     SDValue Val = TSI.EmitTargetCodeForSetTag(
7781         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7782         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7783         ZeroMemory);
7784     DAG.setRoot(Val);
7785     setValue(&I, Val);
7786     return;
7787   }
7788   case Intrinsic::amdgcn_cs_chain: {
7789     assert(I.arg_size() == 5 && "Additional args not supported yet");
7790     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7791            "Non-zero flags not supported yet");
7792 
7793     // At this point we don't care if it's amdgpu_cs_chain or
7794     // amdgpu_cs_chain_preserve.
7795     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7796 
7797     Type *RetTy = I.getType();
7798     assert(RetTy->isVoidTy() && "Should not return");
7799 
7800     SDValue Callee = getValue(I.getOperand(0));
7801 
7802     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7803     // We'll also tack the value of the EXEC mask at the end.
7804     TargetLowering::ArgListTy Args;
7805     Args.reserve(3);
7806 
7807     for (unsigned Idx : {2, 3, 1}) {
7808       TargetLowering::ArgListEntry Arg;
7809       Arg.Node = getValue(I.getOperand(Idx));
7810       Arg.Ty = I.getOperand(Idx)->getType();
7811       Arg.setAttributes(&I, Idx);
7812       Args.push_back(Arg);
7813     }
7814 
7815     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7816     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7817     Args[2].IsInReg = true; // EXEC should be inreg
7818 
7819     TargetLowering::CallLoweringInfo CLI(DAG);
7820     CLI.setDebugLoc(getCurSDLoc())
7821         .setChain(getRoot())
7822         .setCallee(CC, RetTy, Callee, std::move(Args))
7823         .setNoReturn(true)
7824         .setTailCall(true)
7825         .setConvergent(I.isConvergent());
7826     CLI.CB = &I;
7827     std::pair<SDValue, SDValue> Result =
7828         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7829     (void)Result;
7830     assert(!Result.first.getNode() && !Result.second.getNode() &&
7831            "Should've lowered as tail call");
7832 
7833     HasTailCall = true;
7834     return;
7835   }
7836   case Intrinsic::ptrmask: {
7837     SDValue Ptr = getValue(I.getOperand(0));
7838     SDValue Mask = getValue(I.getOperand(1));
7839 
7840     // On arm64_32, pointers are 32 bits when stored in memory, but
7841     // zero-extended to 64 bits when in registers.  Thus the mask is 32 bits to
7842     // match the index type, but the pointer is 64 bits, so the the mask must be
7843     // zero-extended up to 64 bits to match the pointer.
7844     EVT PtrVT =
7845         TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7846     EVT MemVT =
7847         TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7848     assert(PtrVT == Ptr.getValueType());
7849     assert(MemVT == Mask.getValueType());
7850     if (MemVT != PtrVT)
7851       Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
7852 
7853     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7854     return;
7855   }
7856   case Intrinsic::threadlocal_address: {
7857     setValue(&I, getValue(I.getOperand(0)));
7858     return;
7859   }
7860   case Intrinsic::get_active_lane_mask: {
7861     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7862     SDValue Index = getValue(I.getOperand(0));
7863     EVT ElementVT = Index.getValueType();
7864 
7865     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7866       visitTargetIntrinsic(I, Intrinsic);
7867       return;
7868     }
7869 
7870     SDValue TripCount = getValue(I.getOperand(1));
7871     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7872                                  CCVT.getVectorElementCount());
7873 
7874     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7875     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7876     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7877     SDValue VectorInduction = DAG.getNode(
7878         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7879     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7880                                  VectorTripCount, ISD::CondCode::SETULT);
7881     setValue(&I, SetCC);
7882     return;
7883   }
7884   case Intrinsic::experimental_get_vector_length: {
7885     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7886            "Expected positive VF");
7887     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7888     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7889 
7890     SDValue Count = getValue(I.getOperand(0));
7891     EVT CountVT = Count.getValueType();
7892 
7893     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7894       visitTargetIntrinsic(I, Intrinsic);
7895       return;
7896     }
7897 
7898     // Expand to a umin between the trip count and the maximum elements the type
7899     // can hold.
7900     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7901 
7902     // Extend the trip count to at least the result VT.
7903     if (CountVT.bitsLT(VT)) {
7904       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7905       CountVT = VT;
7906     }
7907 
7908     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7909                                          ElementCount::get(VF, IsScalable));
7910 
7911     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7912     // Clip to the result type if needed.
7913     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7914 
7915     setValue(&I, Trunc);
7916     return;
7917   }
7918   case Intrinsic::experimental_cttz_elts: {
7919     auto DL = getCurSDLoc();
7920     SDValue Op = getValue(I.getOperand(0));
7921     EVT OpVT = Op.getValueType();
7922 
7923     if (!TLI.shouldExpandCttzElements(OpVT)) {
7924       visitTargetIntrinsic(I, Intrinsic);
7925       return;
7926     }
7927 
7928     if (OpVT.getScalarType() != MVT::i1) {
7929       // Compare the input vector elements to zero & use to count trailing zeros
7930       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
7931       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
7932                               OpVT.getVectorElementCount());
7933       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
7934     }
7935 
7936     // If the zero-is-poison flag is set, we can assume the upper limit
7937     // of the result is VF-1.
7938     bool ZeroIsPoison =
7939         !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
7940     ConstantRange VScaleRange(1, true); // Dummy value.
7941     if (isa<ScalableVectorType>(I.getOperand(0)->getType()))
7942       VScaleRange = getVScaleRange(I.getCaller(), 64);
7943     unsigned EltWidth = TLI.getBitWidthForCttzElements(
7944         I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
7945 
7946     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
7947 
7948     // Create the new vector type & get the vector length
7949     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
7950                                  OpVT.getVectorElementCount());
7951 
7952     SDValue VL =
7953         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
7954 
7955     SDValue StepVec = DAG.getStepVector(DL, NewVT);
7956     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
7957     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
7958     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
7959     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
7960     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
7961     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
7962 
7963     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7964     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
7965 
7966     setValue(&I, Ret);
7967     return;
7968   }
7969   case Intrinsic::vector_insert: {
7970     SDValue Vec = getValue(I.getOperand(0));
7971     SDValue SubVec = getValue(I.getOperand(1));
7972     SDValue Index = getValue(I.getOperand(2));
7973 
7974     // The intrinsic's index type is i64, but the SDNode requires an index type
7975     // suitable for the target. Convert the index as required.
7976     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7977     if (Index.getValueType() != VectorIdxTy)
7978       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
7979 
7980     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7981     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7982                              Index));
7983     return;
7984   }
7985   case Intrinsic::vector_extract: {
7986     SDValue Vec = getValue(I.getOperand(0));
7987     SDValue Index = getValue(I.getOperand(1));
7988     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7989 
7990     // The intrinsic's index type is i64, but the SDNode requires an index type
7991     // suitable for the target. Convert the index as required.
7992     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7993     if (Index.getValueType() != VectorIdxTy)
7994       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
7995 
7996     setValue(&I,
7997              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7998     return;
7999   }
8000   case Intrinsic::vector_reverse:
8001     visitVectorReverse(I);
8002     return;
8003   case Intrinsic::vector_splice:
8004     visitVectorSplice(I);
8005     return;
8006   case Intrinsic::callbr_landingpad:
8007     visitCallBrLandingPad(I);
8008     return;
8009   case Intrinsic::vector_interleave2:
8010     visitVectorInterleave(I);
8011     return;
8012   case Intrinsic::vector_deinterleave2:
8013     visitVectorDeinterleave(I);
8014     return;
8015   case Intrinsic::experimental_convergence_anchor:
8016   case Intrinsic::experimental_convergence_entry:
8017   case Intrinsic::experimental_convergence_loop:
8018     visitConvergenceControl(I, Intrinsic);
8019     return;
8020   case Intrinsic::experimental_vector_histogram_add: {
8021     visitVectorHistogram(I, Intrinsic);
8022     return;
8023   }
8024   }
8025 }
8026 
8027 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8028     const ConstrainedFPIntrinsic &FPI) {
8029   SDLoc sdl = getCurSDLoc();
8030 
8031   // We do not need to serialize constrained FP intrinsics against
8032   // each other or against (nonvolatile) loads, so they can be
8033   // chained like loads.
8034   SDValue Chain = DAG.getRoot();
8035   SmallVector<SDValue, 4> Opers;
8036   Opers.push_back(Chain);
8037   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8038     Opers.push_back(getValue(FPI.getArgOperand(I)));
8039 
8040   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
8041     assert(Result.getNode()->getNumValues() == 2);
8042 
8043     // Push node to the appropriate list so that future instructions can be
8044     // chained up correctly.
8045     SDValue OutChain = Result.getValue(1);
8046     switch (EB) {
8047     case fp::ExceptionBehavior::ebIgnore:
8048       // The only reason why ebIgnore nodes still need to be chained is that
8049       // they might depend on the current rounding mode, and therefore must
8050       // not be moved across instruction that may change that mode.
8051       [[fallthrough]];
8052     case fp::ExceptionBehavior::ebMayTrap:
8053       // These must not be moved across calls or instructions that may change
8054       // floating-point exception masks.
8055       PendingConstrainedFP.push_back(OutChain);
8056       break;
8057     case fp::ExceptionBehavior::ebStrict:
8058       // These must not be moved across calls or instructions that may change
8059       // floating-point exception masks or read floating-point exception flags.
8060       // In addition, they cannot be optimized out even if unused.
8061       PendingConstrainedFPStrict.push_back(OutChain);
8062       break;
8063     }
8064   };
8065 
8066   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8067   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8068   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8069   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8070 
8071   SDNodeFlags Flags;
8072   if (EB == fp::ExceptionBehavior::ebIgnore)
8073     Flags.setNoFPExcept(true);
8074 
8075   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8076     Flags.copyFMF(*FPOp);
8077 
8078   unsigned Opcode;
8079   switch (FPI.getIntrinsicID()) {
8080   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8081 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8082   case Intrinsic::INTRINSIC:                                                   \
8083     Opcode = ISD::STRICT_##DAGN;                                               \
8084     break;
8085 #include "llvm/IR/ConstrainedOps.def"
8086   case Intrinsic::experimental_constrained_fmuladd: {
8087     Opcode = ISD::STRICT_FMA;
8088     // Break fmuladd into fmul and fadd.
8089     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8090         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8091       Opers.pop_back();
8092       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8093       pushOutChain(Mul, EB);
8094       Opcode = ISD::STRICT_FADD;
8095       Opers.clear();
8096       Opers.push_back(Mul.getValue(1));
8097       Opers.push_back(Mul.getValue(0));
8098       Opers.push_back(getValue(FPI.getArgOperand(2)));
8099     }
8100     break;
8101   }
8102   }
8103 
8104   // A few strict DAG nodes carry additional operands that are not
8105   // set up by the default code above.
8106   switch (Opcode) {
8107   default: break;
8108   case ISD::STRICT_FP_ROUND:
8109     Opers.push_back(
8110         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8111     break;
8112   case ISD::STRICT_FSETCC:
8113   case ISD::STRICT_FSETCCS: {
8114     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8115     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8116     if (TM.Options.NoNaNsFPMath)
8117       Condition = getFCmpCodeWithoutNaN(Condition);
8118     Opers.push_back(DAG.getCondCode(Condition));
8119     break;
8120   }
8121   }
8122 
8123   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8124   pushOutChain(Result, EB);
8125 
8126   SDValue FPResult = Result.getValue(0);
8127   setValue(&FPI, FPResult);
8128 }
8129 
8130 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8131   std::optional<unsigned> ResOPC;
8132   switch (VPIntrin.getIntrinsicID()) {
8133   case Intrinsic::vp_ctlz: {
8134     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8135     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8136     break;
8137   }
8138   case Intrinsic::vp_cttz: {
8139     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8140     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8141     break;
8142   }
8143   case Intrinsic::vp_cttz_elts: {
8144     bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8145     ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8146     break;
8147   }
8148 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8149   case Intrinsic::VPID:                                                        \
8150     ResOPC = ISD::VPSD;                                                        \
8151     break;
8152 #include "llvm/IR/VPIntrinsics.def"
8153   }
8154 
8155   if (!ResOPC)
8156     llvm_unreachable(
8157         "Inconsistency: no SDNode available for this VPIntrinsic!");
8158 
8159   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8160       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8161     if (VPIntrin.getFastMathFlags().allowReassoc())
8162       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8163                                                 : ISD::VP_REDUCE_FMUL;
8164   }
8165 
8166   return *ResOPC;
8167 }
8168 
8169 void SelectionDAGBuilder::visitVPLoad(
8170     const VPIntrinsic &VPIntrin, EVT VT,
8171     const SmallVectorImpl<SDValue> &OpValues) {
8172   SDLoc DL = getCurSDLoc();
8173   Value *PtrOperand = VPIntrin.getArgOperand(0);
8174   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8175   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8176   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8177   SDValue LD;
8178   // Do not serialize variable-length loads of constant memory with
8179   // anything.
8180   if (!Alignment)
8181     Alignment = DAG.getEVTAlign(VT);
8182   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8183   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8184   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8185   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8186       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8187       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8188   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8189                      MMO, false /*IsExpanding */);
8190   if (AddToChain)
8191     PendingLoads.push_back(LD.getValue(1));
8192   setValue(&VPIntrin, LD);
8193 }
8194 
8195 void SelectionDAGBuilder::visitVPGather(
8196     const VPIntrinsic &VPIntrin, EVT VT,
8197     const SmallVectorImpl<SDValue> &OpValues) {
8198   SDLoc DL = getCurSDLoc();
8199   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8200   Value *PtrOperand = VPIntrin.getArgOperand(0);
8201   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8202   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8203   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8204   SDValue LD;
8205   if (!Alignment)
8206     Alignment = DAG.getEVTAlign(VT.getScalarType());
8207   unsigned AS =
8208     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8209   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8210       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8211       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8212   SDValue Base, Index, Scale;
8213   ISD::MemIndexType IndexType;
8214   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8215                                     this, VPIntrin.getParent(),
8216                                     VT.getScalarStoreSize());
8217   if (!UniformBase) {
8218     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8219     Index = getValue(PtrOperand);
8220     IndexType = ISD::SIGNED_SCALED;
8221     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8222   }
8223   EVT IdxVT = Index.getValueType();
8224   EVT EltTy = IdxVT.getVectorElementType();
8225   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8226     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8227     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8228   }
8229   LD = DAG.getGatherVP(
8230       DAG.getVTList(VT, MVT::Other), VT, DL,
8231       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8232       IndexType);
8233   PendingLoads.push_back(LD.getValue(1));
8234   setValue(&VPIntrin, LD);
8235 }
8236 
8237 void SelectionDAGBuilder::visitVPStore(
8238     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8239   SDLoc DL = getCurSDLoc();
8240   Value *PtrOperand = VPIntrin.getArgOperand(1);
8241   EVT VT = OpValues[0].getValueType();
8242   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8243   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8244   SDValue ST;
8245   if (!Alignment)
8246     Alignment = DAG.getEVTAlign(VT);
8247   SDValue Ptr = OpValues[1];
8248   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8249   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8250       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8251       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8252   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8253                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8254                       /* IsTruncating */ false, /*IsCompressing*/ false);
8255   DAG.setRoot(ST);
8256   setValue(&VPIntrin, ST);
8257 }
8258 
8259 void SelectionDAGBuilder::visitVPScatter(
8260     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8261   SDLoc DL = getCurSDLoc();
8262   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8263   Value *PtrOperand = VPIntrin.getArgOperand(1);
8264   EVT VT = OpValues[0].getValueType();
8265   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8266   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8267   SDValue ST;
8268   if (!Alignment)
8269     Alignment = DAG.getEVTAlign(VT.getScalarType());
8270   unsigned AS =
8271       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8272   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8273       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8274       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8275   SDValue Base, Index, Scale;
8276   ISD::MemIndexType IndexType;
8277   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8278                                     this, VPIntrin.getParent(),
8279                                     VT.getScalarStoreSize());
8280   if (!UniformBase) {
8281     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8282     Index = getValue(PtrOperand);
8283     IndexType = ISD::SIGNED_SCALED;
8284     Scale =
8285       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8286   }
8287   EVT IdxVT = Index.getValueType();
8288   EVT EltTy = IdxVT.getVectorElementType();
8289   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8290     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8291     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8292   }
8293   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8294                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8295                          OpValues[2], OpValues[3]},
8296                         MMO, IndexType);
8297   DAG.setRoot(ST);
8298   setValue(&VPIntrin, ST);
8299 }
8300 
8301 void SelectionDAGBuilder::visitVPStridedLoad(
8302     const VPIntrinsic &VPIntrin, EVT VT,
8303     const SmallVectorImpl<SDValue> &OpValues) {
8304   SDLoc DL = getCurSDLoc();
8305   Value *PtrOperand = VPIntrin.getArgOperand(0);
8306   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8307   if (!Alignment)
8308     Alignment = DAG.getEVTAlign(VT.getScalarType());
8309   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8310   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8311   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8312   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8313   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8314   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8315   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8316       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8317       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8318 
8319   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8320                                     OpValues[2], OpValues[3], MMO,
8321                                     false /*IsExpanding*/);
8322 
8323   if (AddToChain)
8324     PendingLoads.push_back(LD.getValue(1));
8325   setValue(&VPIntrin, LD);
8326 }
8327 
8328 void SelectionDAGBuilder::visitVPStridedStore(
8329     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8330   SDLoc DL = getCurSDLoc();
8331   Value *PtrOperand = VPIntrin.getArgOperand(1);
8332   EVT VT = OpValues[0].getValueType();
8333   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8334   if (!Alignment)
8335     Alignment = DAG.getEVTAlign(VT.getScalarType());
8336   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8337   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8338   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8339       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8340       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8341 
8342   SDValue ST = DAG.getStridedStoreVP(
8343       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8344       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8345       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8346       /*IsCompressing*/ false);
8347 
8348   DAG.setRoot(ST);
8349   setValue(&VPIntrin, ST);
8350 }
8351 
8352 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8353   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8354   SDLoc DL = getCurSDLoc();
8355 
8356   ISD::CondCode Condition;
8357   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8358   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8359   if (IsFP) {
8360     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8361     // flags, but calls that don't return floating-point types can't be
8362     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8363     Condition = getFCmpCondCode(CondCode);
8364     if (TM.Options.NoNaNsFPMath)
8365       Condition = getFCmpCodeWithoutNaN(Condition);
8366   } else {
8367     Condition = getICmpCondCode(CondCode);
8368   }
8369 
8370   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8371   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8372   // #2 is the condition code
8373   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8374   SDValue EVL = getValue(VPIntrin.getOperand(4));
8375   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8376   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8377          "Unexpected target EVL type");
8378   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8379 
8380   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8381                                                         VPIntrin.getType());
8382   setValue(&VPIntrin,
8383            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8384 }
8385 
8386 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8387     const VPIntrinsic &VPIntrin) {
8388   SDLoc DL = getCurSDLoc();
8389   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8390 
8391   auto IID = VPIntrin.getIntrinsicID();
8392 
8393   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8394     return visitVPCmp(*CmpI);
8395 
8396   SmallVector<EVT, 4> ValueVTs;
8397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8398   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8399   SDVTList VTs = DAG.getVTList(ValueVTs);
8400 
8401   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8402 
8403   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8404   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8405          "Unexpected target EVL type");
8406 
8407   // Request operands.
8408   SmallVector<SDValue, 7> OpValues;
8409   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8410     auto Op = getValue(VPIntrin.getArgOperand(I));
8411     if (I == EVLParamPos)
8412       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8413     OpValues.push_back(Op);
8414   }
8415 
8416   switch (Opcode) {
8417   default: {
8418     SDNodeFlags SDFlags;
8419     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8420       SDFlags.copyFMF(*FPMO);
8421     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8422     setValue(&VPIntrin, Result);
8423     break;
8424   }
8425   case ISD::VP_LOAD:
8426     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8427     break;
8428   case ISD::VP_GATHER:
8429     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8430     break;
8431   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8432     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8433     break;
8434   case ISD::VP_STORE:
8435     visitVPStore(VPIntrin, OpValues);
8436     break;
8437   case ISD::VP_SCATTER:
8438     visitVPScatter(VPIntrin, OpValues);
8439     break;
8440   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8441     visitVPStridedStore(VPIntrin, OpValues);
8442     break;
8443   case ISD::VP_FMULADD: {
8444     assert(OpValues.size() == 5 && "Unexpected number of operands");
8445     SDNodeFlags SDFlags;
8446     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8447       SDFlags.copyFMF(*FPMO);
8448     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8449         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8450       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8451     } else {
8452       SDValue Mul = DAG.getNode(
8453           ISD::VP_FMUL, DL, VTs,
8454           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8455       SDValue Add =
8456           DAG.getNode(ISD::VP_FADD, DL, VTs,
8457                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8458       setValue(&VPIntrin, Add);
8459     }
8460     break;
8461   }
8462   case ISD::VP_IS_FPCLASS: {
8463     const DataLayout DLayout = DAG.getDataLayout();
8464     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8465     auto Constant = OpValues[1]->getAsZExtVal();
8466     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8467     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8468                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8469     setValue(&VPIntrin, V);
8470     return;
8471   }
8472   case ISD::VP_INTTOPTR: {
8473     SDValue N = OpValues[0];
8474     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8475     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8476     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8477                                OpValues[2]);
8478     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8479                              OpValues[2]);
8480     setValue(&VPIntrin, N);
8481     break;
8482   }
8483   case ISD::VP_PTRTOINT: {
8484     SDValue N = OpValues[0];
8485     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8486                                                           VPIntrin.getType());
8487     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8488                                        VPIntrin.getOperand(0)->getType());
8489     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8490                                OpValues[2]);
8491     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8492                              OpValues[2]);
8493     setValue(&VPIntrin, N);
8494     break;
8495   }
8496   case ISD::VP_ABS:
8497   case ISD::VP_CTLZ:
8498   case ISD::VP_CTLZ_ZERO_UNDEF:
8499   case ISD::VP_CTTZ:
8500   case ISD::VP_CTTZ_ZERO_UNDEF:
8501   case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8502   case ISD::VP_CTTZ_ELTS: {
8503     SDValue Result =
8504         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8505     setValue(&VPIntrin, Result);
8506     break;
8507   }
8508   }
8509 }
8510 
8511 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8512                                           const BasicBlock *EHPadBB,
8513                                           MCSymbol *&BeginLabel) {
8514   MachineFunction &MF = DAG.getMachineFunction();
8515   MachineModuleInfo &MMI = MF.getMMI();
8516 
8517   // Insert a label before the invoke call to mark the try range.  This can be
8518   // used to detect deletion of the invoke via the MachineModuleInfo.
8519   BeginLabel = MMI.getContext().createTempSymbol();
8520 
8521   // For SjLj, keep track of which landing pads go with which invokes
8522   // so as to maintain the ordering of pads in the LSDA.
8523   unsigned CallSiteIndex = MMI.getCurrentCallSite();
8524   if (CallSiteIndex) {
8525     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8526     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
8527 
8528     // Now that the call site is handled, stop tracking it.
8529     MMI.setCurrentCallSite(0);
8530   }
8531 
8532   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8533 }
8534 
8535 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8536                                         const BasicBlock *EHPadBB,
8537                                         MCSymbol *BeginLabel) {
8538   assert(BeginLabel && "BeginLabel should've been set");
8539 
8540   MachineFunction &MF = DAG.getMachineFunction();
8541   MachineModuleInfo &MMI = MF.getMMI();
8542 
8543   // Insert a label at the end of the invoke call to mark the try range.  This
8544   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8545   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
8546   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8547 
8548   // Inform MachineModuleInfo of range.
8549   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8550   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8551   // actually use outlined funclets and their LSDA info style.
8552   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8553     assert(II && "II should've been set");
8554     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8555     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8556   } else if (!isScopedEHPersonality(Pers)) {
8557     assert(EHPadBB);
8558     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
8559   }
8560 
8561   return Chain;
8562 }
8563 
8564 std::pair<SDValue, SDValue>
8565 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8566                                     const BasicBlock *EHPadBB) {
8567   MCSymbol *BeginLabel = nullptr;
8568 
8569   if (EHPadBB) {
8570     // Both PendingLoads and PendingExports must be flushed here;
8571     // this call might not return.
8572     (void)getRoot();
8573     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8574     CLI.setChain(getRoot());
8575   }
8576 
8577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8578   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8579 
8580   assert((CLI.IsTailCall || Result.second.getNode()) &&
8581          "Non-null chain expected with non-tail call!");
8582   assert((Result.second.getNode() || !Result.first.getNode()) &&
8583          "Null value expected with tail call!");
8584 
8585   if (!Result.second.getNode()) {
8586     // As a special case, a null chain means that a tail call has been emitted
8587     // and the DAG root is already updated.
8588     HasTailCall = true;
8589 
8590     // Since there's no actual continuation from this block, nothing can be
8591     // relying on us setting vregs for them.
8592     PendingExports.clear();
8593   } else {
8594     DAG.setRoot(Result.second);
8595   }
8596 
8597   if (EHPadBB) {
8598     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8599                            BeginLabel));
8600   }
8601 
8602   return Result;
8603 }
8604 
8605 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8606                                       bool isTailCall, bool isMustTailCall,
8607                                       const BasicBlock *EHPadBB,
8608                                       const TargetLowering::PtrAuthInfo *PAI) {
8609   auto &DL = DAG.getDataLayout();
8610   FunctionType *FTy = CB.getFunctionType();
8611   Type *RetTy = CB.getType();
8612 
8613   TargetLowering::ArgListTy Args;
8614   Args.reserve(CB.arg_size());
8615 
8616   const Value *SwiftErrorVal = nullptr;
8617   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8618 
8619   if (isTailCall) {
8620     // Avoid emitting tail calls in functions with the disable-tail-calls
8621     // attribute.
8622     auto *Caller = CB.getParent()->getParent();
8623     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8624         "true" && !isMustTailCall)
8625       isTailCall = false;
8626 
8627     // We can't tail call inside a function with a swifterror argument. Lowering
8628     // does not support this yet. It would have to move into the swifterror
8629     // register before the call.
8630     if (TLI.supportSwiftError() &&
8631         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8632       isTailCall = false;
8633   }
8634 
8635   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8636     TargetLowering::ArgListEntry Entry;
8637     const Value *V = *I;
8638 
8639     // Skip empty types
8640     if (V->getType()->isEmptyTy())
8641       continue;
8642 
8643     SDValue ArgNode = getValue(V);
8644     Entry.Node = ArgNode; Entry.Ty = V->getType();
8645 
8646     Entry.setAttributes(&CB, I - CB.arg_begin());
8647 
8648     // Use swifterror virtual register as input to the call.
8649     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8650       SwiftErrorVal = V;
8651       // We find the virtual register for the actual swifterror argument.
8652       // Instead of using the Value, we use the virtual register instead.
8653       Entry.Node =
8654           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8655                           EVT(TLI.getPointerTy(DL)));
8656     }
8657 
8658     Args.push_back(Entry);
8659 
8660     // If we have an explicit sret argument that is an Instruction, (i.e., it
8661     // might point to function-local memory), we can't meaningfully tail-call.
8662     if (Entry.IsSRet && isa<Instruction>(V))
8663       isTailCall = false;
8664   }
8665 
8666   // If call site has a cfguardtarget operand bundle, create and add an
8667   // additional ArgListEntry.
8668   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8669     TargetLowering::ArgListEntry Entry;
8670     Value *V = Bundle->Inputs[0];
8671     SDValue ArgNode = getValue(V);
8672     Entry.Node = ArgNode;
8673     Entry.Ty = V->getType();
8674     Entry.IsCFGuardTarget = true;
8675     Args.push_back(Entry);
8676   }
8677 
8678   // Check if target-independent constraints permit a tail call here.
8679   // Target-dependent constraints are checked within TLI->LowerCallTo.
8680   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8681     isTailCall = false;
8682 
8683   // Disable tail calls if there is an swifterror argument. Targets have not
8684   // been updated to support tail calls.
8685   if (TLI.supportSwiftError() && SwiftErrorVal)
8686     isTailCall = false;
8687 
8688   ConstantInt *CFIType = nullptr;
8689   if (CB.isIndirectCall()) {
8690     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8691       if (!TLI.supportKCFIBundles())
8692         report_fatal_error(
8693             "Target doesn't support calls with kcfi operand bundles.");
8694       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8695       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8696     }
8697   }
8698 
8699   SDValue ConvControlToken;
8700   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8701     auto *Token = Bundle->Inputs[0].get();
8702     ConvControlToken = getValue(Token);
8703   }
8704 
8705   TargetLowering::CallLoweringInfo CLI(DAG);
8706   CLI.setDebugLoc(getCurSDLoc())
8707       .setChain(getRoot())
8708       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8709       .setTailCall(isTailCall)
8710       .setConvergent(CB.isConvergent())
8711       .setIsPreallocated(
8712           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8713       .setCFIType(CFIType)
8714       .setConvergenceControlToken(ConvControlToken);
8715 
8716   // Set the pointer authentication info if we have it.
8717   if (PAI) {
8718     if (!TLI.supportPtrAuthBundles())
8719       report_fatal_error(
8720           "This target doesn't support calls with ptrauth operand bundles.");
8721     CLI.setPtrAuth(*PAI);
8722   }
8723 
8724   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8725 
8726   if (Result.first.getNode()) {
8727     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8728     setValue(&CB, Result.first);
8729   }
8730 
8731   // The last element of CLI.InVals has the SDValue for swifterror return.
8732   // Here we copy it to a virtual register and update SwiftErrorMap for
8733   // book-keeping.
8734   if (SwiftErrorVal && TLI.supportSwiftError()) {
8735     // Get the last element of InVals.
8736     SDValue Src = CLI.InVals.back();
8737     Register VReg =
8738         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8739     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8740     DAG.setRoot(CopyNode);
8741   }
8742 }
8743 
8744 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8745                              SelectionDAGBuilder &Builder) {
8746   // Check to see if this load can be trivially constant folded, e.g. if the
8747   // input is from a string literal.
8748   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8749     // Cast pointer to the type we really want to load.
8750     Type *LoadTy =
8751         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8752     if (LoadVT.isVector())
8753       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8754 
8755     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8756                                          PointerType::getUnqual(LoadTy));
8757 
8758     if (const Constant *LoadCst =
8759             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8760                                          LoadTy, Builder.DAG.getDataLayout()))
8761       return Builder.getValue(LoadCst);
8762   }
8763 
8764   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8765   // still constant memory, the input chain can be the entry node.
8766   SDValue Root;
8767   bool ConstantMemory = false;
8768 
8769   // Do not serialize (non-volatile) loads of constant memory with anything.
8770   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8771     Root = Builder.DAG.getEntryNode();
8772     ConstantMemory = true;
8773   } else {
8774     // Do not serialize non-volatile loads against each other.
8775     Root = Builder.DAG.getRoot();
8776   }
8777 
8778   SDValue Ptr = Builder.getValue(PtrVal);
8779   SDValue LoadVal =
8780       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8781                           MachinePointerInfo(PtrVal), Align(1));
8782 
8783   if (!ConstantMemory)
8784     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8785   return LoadVal;
8786 }
8787 
8788 /// Record the value for an instruction that produces an integer result,
8789 /// converting the type where necessary.
8790 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8791                                                   SDValue Value,
8792                                                   bool IsSigned) {
8793   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8794                                                     I.getType(), true);
8795   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8796   setValue(&I, Value);
8797 }
8798 
8799 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8800 /// true and lower it. Otherwise return false, and it will be lowered like a
8801 /// normal call.
8802 /// The caller already checked that \p I calls the appropriate LibFunc with a
8803 /// correct prototype.
8804 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8805   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8806   const Value *Size = I.getArgOperand(2);
8807   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8808   if (CSize && CSize->getZExtValue() == 0) {
8809     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8810                                                           I.getType(), true);
8811     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8812     return true;
8813   }
8814 
8815   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8816   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8817       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8818       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8819   if (Res.first.getNode()) {
8820     processIntegerCallValue(I, Res.first, true);
8821     PendingLoads.push_back(Res.second);
8822     return true;
8823   }
8824 
8825   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8826   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8827   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8828     return false;
8829 
8830   // If the target has a fast compare for the given size, it will return a
8831   // preferred load type for that size. Require that the load VT is legal and
8832   // that the target supports unaligned loads of that type. Otherwise, return
8833   // INVALID.
8834   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8835     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8836     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8837     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8838       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8839       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8840       // TODO: Check alignment of src and dest ptrs.
8841       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8842       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8843       if (!TLI.isTypeLegal(LVT) ||
8844           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8845           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8846         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8847     }
8848 
8849     return LVT;
8850   };
8851 
8852   // This turns into unaligned loads. We only do this if the target natively
8853   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8854   // we'll only produce a small number of byte loads.
8855   MVT LoadVT;
8856   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8857   switch (NumBitsToCompare) {
8858   default:
8859     return false;
8860   case 16:
8861     LoadVT = MVT::i16;
8862     break;
8863   case 32:
8864     LoadVT = MVT::i32;
8865     break;
8866   case 64:
8867   case 128:
8868   case 256:
8869     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8870     break;
8871   }
8872 
8873   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8874     return false;
8875 
8876   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8877   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8878 
8879   // Bitcast to a wide integer type if the loads are vectors.
8880   if (LoadVT.isVector()) {
8881     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8882     LoadL = DAG.getBitcast(CmpVT, LoadL);
8883     LoadR = DAG.getBitcast(CmpVT, LoadR);
8884   }
8885 
8886   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8887   processIntegerCallValue(I, Cmp, false);
8888   return true;
8889 }
8890 
8891 /// See if we can lower a memchr call into an optimized form. If so, return
8892 /// true and lower it. Otherwise return false, and it will be lowered like a
8893 /// normal call.
8894 /// The caller already checked that \p I calls the appropriate LibFunc with a
8895 /// correct prototype.
8896 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8897   const Value *Src = I.getArgOperand(0);
8898   const Value *Char = I.getArgOperand(1);
8899   const Value *Length = I.getArgOperand(2);
8900 
8901   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8902   std::pair<SDValue, SDValue> Res =
8903     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8904                                 getValue(Src), getValue(Char), getValue(Length),
8905                                 MachinePointerInfo(Src));
8906   if (Res.first.getNode()) {
8907     setValue(&I, Res.first);
8908     PendingLoads.push_back(Res.second);
8909     return true;
8910   }
8911 
8912   return false;
8913 }
8914 
8915 /// See if we can lower a mempcpy call into an optimized form. If so, return
8916 /// true and lower it. Otherwise return false, and it will be lowered like a
8917 /// normal call.
8918 /// The caller already checked that \p I calls the appropriate LibFunc with a
8919 /// correct prototype.
8920 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8921   SDValue Dst = getValue(I.getArgOperand(0));
8922   SDValue Src = getValue(I.getArgOperand(1));
8923   SDValue Size = getValue(I.getArgOperand(2));
8924 
8925   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8926   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8927   // DAG::getMemcpy needs Alignment to be defined.
8928   Align Alignment = std::min(DstAlign, SrcAlign);
8929 
8930   SDLoc sdl = getCurSDLoc();
8931 
8932   // In the mempcpy context we need to pass in a false value for isTailCall
8933   // because the return pointer needs to be adjusted by the size of
8934   // the copied memory.
8935   SDValue Root = getMemoryRoot();
8936   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false,
8937                              /*isTailCall=*/false,
8938                              MachinePointerInfo(I.getArgOperand(0)),
8939                              MachinePointerInfo(I.getArgOperand(1)),
8940                              I.getAAMetadata());
8941   assert(MC.getNode() != nullptr &&
8942          "** memcpy should not be lowered as TailCall in mempcpy context **");
8943   DAG.setRoot(MC);
8944 
8945   // Check if Size needs to be truncated or extended.
8946   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8947 
8948   // Adjust return pointer to point just past the last dst byte.
8949   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8950                                     Dst, Size);
8951   setValue(&I, DstPlusSize);
8952   return true;
8953 }
8954 
8955 /// See if we can lower a strcpy call into an optimized form.  If so, return
8956 /// true and lower it, otherwise return false and it will be lowered like a
8957 /// normal call.
8958 /// The caller already checked that \p I calls the appropriate LibFunc with a
8959 /// correct prototype.
8960 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8961   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8962 
8963   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8964   std::pair<SDValue, SDValue> Res =
8965     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8966                                 getValue(Arg0), getValue(Arg1),
8967                                 MachinePointerInfo(Arg0),
8968                                 MachinePointerInfo(Arg1), isStpcpy);
8969   if (Res.first.getNode()) {
8970     setValue(&I, Res.first);
8971     DAG.setRoot(Res.second);
8972     return true;
8973   }
8974 
8975   return false;
8976 }
8977 
8978 /// See if we can lower a strcmp call into an optimized form.  If so, return
8979 /// true and lower it, otherwise return false and it will be lowered like a
8980 /// normal call.
8981 /// The caller already checked that \p I calls the appropriate LibFunc with a
8982 /// correct prototype.
8983 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8984   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8985 
8986   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8987   std::pair<SDValue, SDValue> Res =
8988     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8989                                 getValue(Arg0), getValue(Arg1),
8990                                 MachinePointerInfo(Arg0),
8991                                 MachinePointerInfo(Arg1));
8992   if (Res.first.getNode()) {
8993     processIntegerCallValue(I, Res.first, true);
8994     PendingLoads.push_back(Res.second);
8995     return true;
8996   }
8997 
8998   return false;
8999 }
9000 
9001 /// See if we can lower a strlen call into an optimized form.  If so, return
9002 /// true and lower it, otherwise return false and it will be lowered like a
9003 /// normal call.
9004 /// The caller already checked that \p I calls the appropriate LibFunc with a
9005 /// correct prototype.
9006 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9007   const Value *Arg0 = I.getArgOperand(0);
9008 
9009   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9010   std::pair<SDValue, SDValue> Res =
9011     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
9012                                 getValue(Arg0), MachinePointerInfo(Arg0));
9013   if (Res.first.getNode()) {
9014     processIntegerCallValue(I, Res.first, false);
9015     PendingLoads.push_back(Res.second);
9016     return true;
9017   }
9018 
9019   return false;
9020 }
9021 
9022 /// See if we can lower a strnlen call into an optimized form.  If so, return
9023 /// true and lower it, otherwise return false and it will be lowered like a
9024 /// normal call.
9025 /// The caller already checked that \p I calls the appropriate LibFunc with a
9026 /// correct prototype.
9027 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9028   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9029 
9030   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9031   std::pair<SDValue, SDValue> Res =
9032     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9033                                  getValue(Arg0), getValue(Arg1),
9034                                  MachinePointerInfo(Arg0));
9035   if (Res.first.getNode()) {
9036     processIntegerCallValue(I, Res.first, false);
9037     PendingLoads.push_back(Res.second);
9038     return true;
9039   }
9040 
9041   return false;
9042 }
9043 
9044 /// See if we can lower a unary floating-point operation into an SDNode with
9045 /// the specified Opcode.  If so, return true and lower it, otherwise return
9046 /// false and it will be lowered like a normal call.
9047 /// The caller already checked that \p I calls the appropriate LibFunc with a
9048 /// correct prototype.
9049 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9050                                               unsigned Opcode) {
9051   // We already checked this call's prototype; verify it doesn't modify errno.
9052   if (!I.onlyReadsMemory())
9053     return false;
9054 
9055   SDNodeFlags Flags;
9056   Flags.copyFMF(cast<FPMathOperator>(I));
9057 
9058   SDValue Tmp = getValue(I.getArgOperand(0));
9059   setValue(&I,
9060            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9061   return true;
9062 }
9063 
9064 /// See if we can lower a binary floating-point operation into an SDNode with
9065 /// the specified Opcode. If so, return true and lower it. Otherwise return
9066 /// false, and it will be lowered like a normal call.
9067 /// The caller already checked that \p I calls the appropriate LibFunc with a
9068 /// correct prototype.
9069 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9070                                                unsigned Opcode) {
9071   // We already checked this call's prototype; verify it doesn't modify errno.
9072   if (!I.onlyReadsMemory())
9073     return false;
9074 
9075   SDNodeFlags Flags;
9076   Flags.copyFMF(cast<FPMathOperator>(I));
9077 
9078   SDValue Tmp0 = getValue(I.getArgOperand(0));
9079   SDValue Tmp1 = getValue(I.getArgOperand(1));
9080   EVT VT = Tmp0.getValueType();
9081   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9082   return true;
9083 }
9084 
9085 void SelectionDAGBuilder::visitCall(const CallInst &I) {
9086   // Handle inline assembly differently.
9087   if (I.isInlineAsm()) {
9088     visitInlineAsm(I);
9089     return;
9090   }
9091 
9092   diagnoseDontCall(I);
9093 
9094   if (Function *F = I.getCalledFunction()) {
9095     if (F->isDeclaration()) {
9096       // Is this an LLVM intrinsic or a target-specific intrinsic?
9097       unsigned IID = F->getIntrinsicID();
9098       if (!IID)
9099         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9100           IID = II->getIntrinsicID(F);
9101 
9102       if (IID) {
9103         visitIntrinsicCall(I, IID);
9104         return;
9105       }
9106     }
9107 
9108     // Check for well-known libc/libm calls.  If the function is internal, it
9109     // can't be a library call.  Don't do the check if marked as nobuiltin for
9110     // some reason or the call site requires strict floating point semantics.
9111     LibFunc Func;
9112     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9113         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9114         LibInfo->hasOptimizedCodeGen(Func)) {
9115       switch (Func) {
9116       default: break;
9117       case LibFunc_bcmp:
9118         if (visitMemCmpBCmpCall(I))
9119           return;
9120         break;
9121       case LibFunc_copysign:
9122       case LibFunc_copysignf:
9123       case LibFunc_copysignl:
9124         // We already checked this call's prototype; verify it doesn't modify
9125         // errno.
9126         if (I.onlyReadsMemory()) {
9127           SDValue LHS = getValue(I.getArgOperand(0));
9128           SDValue RHS = getValue(I.getArgOperand(1));
9129           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9130                                    LHS.getValueType(), LHS, RHS));
9131           return;
9132         }
9133         break;
9134       case LibFunc_fabs:
9135       case LibFunc_fabsf:
9136       case LibFunc_fabsl:
9137         if (visitUnaryFloatCall(I, ISD::FABS))
9138           return;
9139         break;
9140       case LibFunc_fmin:
9141       case LibFunc_fminf:
9142       case LibFunc_fminl:
9143         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9144           return;
9145         break;
9146       case LibFunc_fmax:
9147       case LibFunc_fmaxf:
9148       case LibFunc_fmaxl:
9149         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9150           return;
9151         break;
9152       case LibFunc_sin:
9153       case LibFunc_sinf:
9154       case LibFunc_sinl:
9155         if (visitUnaryFloatCall(I, ISD::FSIN))
9156           return;
9157         break;
9158       case LibFunc_cos:
9159       case LibFunc_cosf:
9160       case LibFunc_cosl:
9161         if (visitUnaryFloatCall(I, ISD::FCOS))
9162           return;
9163         break;
9164       case LibFunc_tan:
9165       case LibFunc_tanf:
9166       case LibFunc_tanl:
9167         if (visitUnaryFloatCall(I, ISD::FTAN))
9168           return;
9169         break;
9170       case LibFunc_sqrt:
9171       case LibFunc_sqrtf:
9172       case LibFunc_sqrtl:
9173       case LibFunc_sqrt_finite:
9174       case LibFunc_sqrtf_finite:
9175       case LibFunc_sqrtl_finite:
9176         if (visitUnaryFloatCall(I, ISD::FSQRT))
9177           return;
9178         break;
9179       case LibFunc_floor:
9180       case LibFunc_floorf:
9181       case LibFunc_floorl:
9182         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9183           return;
9184         break;
9185       case LibFunc_nearbyint:
9186       case LibFunc_nearbyintf:
9187       case LibFunc_nearbyintl:
9188         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9189           return;
9190         break;
9191       case LibFunc_ceil:
9192       case LibFunc_ceilf:
9193       case LibFunc_ceill:
9194         if (visitUnaryFloatCall(I, ISD::FCEIL))
9195           return;
9196         break;
9197       case LibFunc_rint:
9198       case LibFunc_rintf:
9199       case LibFunc_rintl:
9200         if (visitUnaryFloatCall(I, ISD::FRINT))
9201           return;
9202         break;
9203       case LibFunc_round:
9204       case LibFunc_roundf:
9205       case LibFunc_roundl:
9206         if (visitUnaryFloatCall(I, ISD::FROUND))
9207           return;
9208         break;
9209       case LibFunc_trunc:
9210       case LibFunc_truncf:
9211       case LibFunc_truncl:
9212         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9213           return;
9214         break;
9215       case LibFunc_log2:
9216       case LibFunc_log2f:
9217       case LibFunc_log2l:
9218         if (visitUnaryFloatCall(I, ISD::FLOG2))
9219           return;
9220         break;
9221       case LibFunc_exp2:
9222       case LibFunc_exp2f:
9223       case LibFunc_exp2l:
9224         if (visitUnaryFloatCall(I, ISD::FEXP2))
9225           return;
9226         break;
9227       case LibFunc_exp10:
9228       case LibFunc_exp10f:
9229       case LibFunc_exp10l:
9230         if (visitUnaryFloatCall(I, ISD::FEXP10))
9231           return;
9232         break;
9233       case LibFunc_ldexp:
9234       case LibFunc_ldexpf:
9235       case LibFunc_ldexpl:
9236         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9237           return;
9238         break;
9239       case LibFunc_memcmp:
9240         if (visitMemCmpBCmpCall(I))
9241           return;
9242         break;
9243       case LibFunc_mempcpy:
9244         if (visitMemPCpyCall(I))
9245           return;
9246         break;
9247       case LibFunc_memchr:
9248         if (visitMemChrCall(I))
9249           return;
9250         break;
9251       case LibFunc_strcpy:
9252         if (visitStrCpyCall(I, false))
9253           return;
9254         break;
9255       case LibFunc_stpcpy:
9256         if (visitStrCpyCall(I, true))
9257           return;
9258         break;
9259       case LibFunc_strcmp:
9260         if (visitStrCmpCall(I))
9261           return;
9262         break;
9263       case LibFunc_strlen:
9264         if (visitStrLenCall(I))
9265           return;
9266         break;
9267       case LibFunc_strnlen:
9268         if (visitStrNLenCall(I))
9269           return;
9270         break;
9271       }
9272     }
9273   }
9274 
9275   if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9276     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9277     return;
9278   }
9279 
9280   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9281   // have to do anything here to lower funclet bundles.
9282   // CFGuardTarget bundles are lowered in LowerCallTo.
9283   assert(!I.hasOperandBundlesOtherThan(
9284              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9285               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9286               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9287               LLVMContext::OB_convergencectrl}) &&
9288          "Cannot lower calls with arbitrary operand bundles!");
9289 
9290   SDValue Callee = getValue(I.getCalledOperand());
9291 
9292   if (I.hasDeoptState())
9293     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9294   else
9295     // Check if we can potentially perform a tail call. More detailed checking
9296     // is be done within LowerCallTo, after more information about the call is
9297     // known.
9298     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9299 }
9300 
9301 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9302     const CallBase &CB, const BasicBlock *EHPadBB) {
9303   auto PAB = CB.getOperandBundle("ptrauth");
9304   const Value *CalleeV = CB.getCalledOperand();
9305 
9306   // Gather the call ptrauth data from the operand bundle:
9307   //   [ i32 <key>, i64 <discriminator> ]
9308   const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9309   const Value *Discriminator = PAB->Inputs[1];
9310 
9311   assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9312   assert(Discriminator->getType()->isIntegerTy(64) &&
9313          "Invalid ptrauth discriminator");
9314 
9315   // Functions should never be ptrauth-called directly.
9316   assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9317 
9318   // Otherwise, do an authenticated indirect call.
9319   TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9320                                      getValue(Discriminator)};
9321 
9322   LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9323               EHPadBB, &PAI);
9324 }
9325 
9326 namespace {
9327 
9328 /// AsmOperandInfo - This contains information for each constraint that we are
9329 /// lowering.
9330 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9331 public:
9332   /// CallOperand - If this is the result output operand or a clobber
9333   /// this is null, otherwise it is the incoming operand to the CallInst.
9334   /// This gets modified as the asm is processed.
9335   SDValue CallOperand;
9336 
9337   /// AssignedRegs - If this is a register or register class operand, this
9338   /// contains the set of register corresponding to the operand.
9339   RegsForValue AssignedRegs;
9340 
9341   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9342     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9343   }
9344 
9345   /// Whether or not this operand accesses memory
9346   bool hasMemory(const TargetLowering &TLI) const {
9347     // Indirect operand accesses access memory.
9348     if (isIndirect)
9349       return true;
9350 
9351     for (const auto &Code : Codes)
9352       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9353         return true;
9354 
9355     return false;
9356   }
9357 };
9358 
9359 
9360 } // end anonymous namespace
9361 
9362 /// Make sure that the output operand \p OpInfo and its corresponding input
9363 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9364 /// out).
9365 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9366                                SDISelAsmOperandInfo &MatchingOpInfo,
9367                                SelectionDAG &DAG) {
9368   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9369     return;
9370 
9371   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9372   const auto &TLI = DAG.getTargetLoweringInfo();
9373 
9374   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9375       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9376                                        OpInfo.ConstraintVT);
9377   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9378       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9379                                        MatchingOpInfo.ConstraintVT);
9380   if ((OpInfo.ConstraintVT.isInteger() !=
9381        MatchingOpInfo.ConstraintVT.isInteger()) ||
9382       (MatchRC.second != InputRC.second)) {
9383     // FIXME: error out in a more elegant fashion
9384     report_fatal_error("Unsupported asm: input constraint"
9385                        " with a matching output constraint of"
9386                        " incompatible type!");
9387   }
9388   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9389 }
9390 
9391 /// Get a direct memory input to behave well as an indirect operand.
9392 /// This may introduce stores, hence the need for a \p Chain.
9393 /// \return The (possibly updated) chain.
9394 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9395                                         SDISelAsmOperandInfo &OpInfo,
9396                                         SelectionDAG &DAG) {
9397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9398 
9399   // If we don't have an indirect input, put it in the constpool if we can,
9400   // otherwise spill it to a stack slot.
9401   // TODO: This isn't quite right. We need to handle these according to
9402   // the addressing mode that the constraint wants. Also, this may take
9403   // an additional register for the computation and we don't want that
9404   // either.
9405 
9406   // If the operand is a float, integer, or vector constant, spill to a
9407   // constant pool entry to get its address.
9408   const Value *OpVal = OpInfo.CallOperandVal;
9409   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9410       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9411     OpInfo.CallOperand = DAG.getConstantPool(
9412         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9413     return Chain;
9414   }
9415 
9416   // Otherwise, create a stack slot and emit a store to it before the asm.
9417   Type *Ty = OpVal->getType();
9418   auto &DL = DAG.getDataLayout();
9419   uint64_t TySize = DL.getTypeAllocSize(Ty);
9420   MachineFunction &MF = DAG.getMachineFunction();
9421   int SSFI = MF.getFrameInfo().CreateStackObject(
9422       TySize, DL.getPrefTypeAlign(Ty), false);
9423   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9424   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9425                             MachinePointerInfo::getFixedStack(MF, SSFI),
9426                             TLI.getMemValueType(DL, Ty));
9427   OpInfo.CallOperand = StackSlot;
9428 
9429   return Chain;
9430 }
9431 
9432 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9433 /// specified operand.  We prefer to assign virtual registers, to allow the
9434 /// register allocator to handle the assignment process.  However, if the asm
9435 /// uses features that we can't model on machineinstrs, we have SDISel do the
9436 /// allocation.  This produces generally horrible, but correct, code.
9437 ///
9438 ///   OpInfo describes the operand
9439 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9440 static std::optional<unsigned>
9441 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9442                      SDISelAsmOperandInfo &OpInfo,
9443                      SDISelAsmOperandInfo &RefOpInfo) {
9444   LLVMContext &Context = *DAG.getContext();
9445   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9446 
9447   MachineFunction &MF = DAG.getMachineFunction();
9448   SmallVector<unsigned, 4> Regs;
9449   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9450 
9451   // No work to do for memory/address operands.
9452   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9453       OpInfo.ConstraintType == TargetLowering::C_Address)
9454     return std::nullopt;
9455 
9456   // If this is a constraint for a single physreg, or a constraint for a
9457   // register class, find it.
9458   unsigned AssignedReg;
9459   const TargetRegisterClass *RC;
9460   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9461       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9462   // RC is unset only on failure. Return immediately.
9463   if (!RC)
9464     return std::nullopt;
9465 
9466   // Get the actual register value type.  This is important, because the user
9467   // may have asked for (e.g.) the AX register in i32 type.  We need to
9468   // remember that AX is actually i16 to get the right extension.
9469   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9470 
9471   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9472     // If this is an FP operand in an integer register (or visa versa), or more
9473     // generally if the operand value disagrees with the register class we plan
9474     // to stick it in, fix the operand type.
9475     //
9476     // If this is an input value, the bitcast to the new type is done now.
9477     // Bitcast for output value is done at the end of visitInlineAsm().
9478     if ((OpInfo.Type == InlineAsm::isOutput ||
9479          OpInfo.Type == InlineAsm::isInput) &&
9480         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9481       // Try to convert to the first EVT that the reg class contains.  If the
9482       // types are identical size, use a bitcast to convert (e.g. two differing
9483       // vector types).  Note: output bitcast is done at the end of
9484       // visitInlineAsm().
9485       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9486         // Exclude indirect inputs while they are unsupported because the code
9487         // to perform the load is missing and thus OpInfo.CallOperand still
9488         // refers to the input address rather than the pointed-to value.
9489         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9490           OpInfo.CallOperand =
9491               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9492         OpInfo.ConstraintVT = RegVT;
9493         // If the operand is an FP value and we want it in integer registers,
9494         // use the corresponding integer type. This turns an f64 value into
9495         // i64, which can be passed with two i32 values on a 32-bit machine.
9496       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9497         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9498         if (OpInfo.Type == InlineAsm::isInput)
9499           OpInfo.CallOperand =
9500               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9501         OpInfo.ConstraintVT = VT;
9502       }
9503     }
9504   }
9505 
9506   // No need to allocate a matching input constraint since the constraint it's
9507   // matching to has already been allocated.
9508   if (OpInfo.isMatchingInputConstraint())
9509     return std::nullopt;
9510 
9511   EVT ValueVT = OpInfo.ConstraintVT;
9512   if (OpInfo.ConstraintVT == MVT::Other)
9513     ValueVT = RegVT;
9514 
9515   // Initialize NumRegs.
9516   unsigned NumRegs = 1;
9517   if (OpInfo.ConstraintVT != MVT::Other)
9518     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9519 
9520   // If this is a constraint for a specific physical register, like {r17},
9521   // assign it now.
9522 
9523   // If this associated to a specific register, initialize iterator to correct
9524   // place. If virtual, make sure we have enough registers
9525 
9526   // Initialize iterator if necessary
9527   TargetRegisterClass::iterator I = RC->begin();
9528   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9529 
9530   // Do not check for single registers.
9531   if (AssignedReg) {
9532     I = std::find(I, RC->end(), AssignedReg);
9533     if (I == RC->end()) {
9534       // RC does not contain the selected register, which indicates a
9535       // mismatch between the register and the required type/bitwidth.
9536       return {AssignedReg};
9537     }
9538   }
9539 
9540   for (; NumRegs; --NumRegs, ++I) {
9541     assert(I != RC->end() && "Ran out of registers to allocate!");
9542     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9543     Regs.push_back(R);
9544   }
9545 
9546   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9547   return std::nullopt;
9548 }
9549 
9550 static unsigned
9551 findMatchingInlineAsmOperand(unsigned OperandNo,
9552                              const std::vector<SDValue> &AsmNodeOperands) {
9553   // Scan until we find the definition we already emitted of this operand.
9554   unsigned CurOp = InlineAsm::Op_FirstOperand;
9555   for (; OperandNo; --OperandNo) {
9556     // Advance to the next operand.
9557     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9558     const InlineAsm::Flag F(OpFlag);
9559     assert(
9560         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9561         "Skipped past definitions?");
9562     CurOp += F.getNumOperandRegisters() + 1;
9563   }
9564   return CurOp;
9565 }
9566 
9567 namespace {
9568 
9569 class ExtraFlags {
9570   unsigned Flags = 0;
9571 
9572 public:
9573   explicit ExtraFlags(const CallBase &Call) {
9574     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9575     if (IA->hasSideEffects())
9576       Flags |= InlineAsm::Extra_HasSideEffects;
9577     if (IA->isAlignStack())
9578       Flags |= InlineAsm::Extra_IsAlignStack;
9579     if (Call.isConvergent())
9580       Flags |= InlineAsm::Extra_IsConvergent;
9581     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9582   }
9583 
9584   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9585     // Ideally, we would only check against memory constraints.  However, the
9586     // meaning of an Other constraint can be target-specific and we can't easily
9587     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9588     // for Other constraints as well.
9589     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9590         OpInfo.ConstraintType == TargetLowering::C_Other) {
9591       if (OpInfo.Type == InlineAsm::isInput)
9592         Flags |= InlineAsm::Extra_MayLoad;
9593       else if (OpInfo.Type == InlineAsm::isOutput)
9594         Flags |= InlineAsm::Extra_MayStore;
9595       else if (OpInfo.Type == InlineAsm::isClobber)
9596         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9597     }
9598   }
9599 
9600   unsigned get() const { return Flags; }
9601 };
9602 
9603 } // end anonymous namespace
9604 
9605 static bool isFunction(SDValue Op) {
9606   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9607     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9608       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9609 
9610       // In normal "call dllimport func" instruction (non-inlineasm) it force
9611       // indirect access by specifing call opcode. And usually specially print
9612       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9613       // not do in this way now. (In fact, this is similar with "Data Access"
9614       // action). So here we ignore dllimport function.
9615       if (Fn && !Fn->hasDLLImportStorageClass())
9616         return true;
9617     }
9618   }
9619   return false;
9620 }
9621 
9622 /// visitInlineAsm - Handle a call to an InlineAsm object.
9623 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9624                                          const BasicBlock *EHPadBB) {
9625   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9626 
9627   /// ConstraintOperands - Information about all of the constraints.
9628   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9629 
9630   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9631   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9632       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9633 
9634   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9635   // AsmDialect, MayLoad, MayStore).
9636   bool HasSideEffect = IA->hasSideEffects();
9637   ExtraFlags ExtraInfo(Call);
9638 
9639   for (auto &T : TargetConstraints) {
9640     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9641     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9642 
9643     if (OpInfo.CallOperandVal)
9644       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9645 
9646     if (!HasSideEffect)
9647       HasSideEffect = OpInfo.hasMemory(TLI);
9648 
9649     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9650     // FIXME: Could we compute this on OpInfo rather than T?
9651 
9652     // Compute the constraint code and ConstraintType to use.
9653     TLI.ComputeConstraintToUse(T, SDValue());
9654 
9655     if (T.ConstraintType == TargetLowering::C_Immediate &&
9656         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9657       // We've delayed emitting a diagnostic like the "n" constraint because
9658       // inlining could cause an integer showing up.
9659       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9660                                           "' expects an integer constant "
9661                                           "expression");
9662 
9663     ExtraInfo.update(T);
9664   }
9665 
9666   // We won't need to flush pending loads if this asm doesn't touch
9667   // memory and is nonvolatile.
9668   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9669 
9670   bool EmitEHLabels = isa<InvokeInst>(Call);
9671   if (EmitEHLabels) {
9672     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9673   }
9674   bool IsCallBr = isa<CallBrInst>(Call);
9675 
9676   if (IsCallBr || EmitEHLabels) {
9677     // If this is a callbr or invoke we need to flush pending exports since
9678     // inlineasm_br and invoke are terminators.
9679     // We need to do this before nodes are glued to the inlineasm_br node.
9680     Chain = getControlRoot();
9681   }
9682 
9683   MCSymbol *BeginLabel = nullptr;
9684   if (EmitEHLabels) {
9685     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9686   }
9687 
9688   int OpNo = -1;
9689   SmallVector<StringRef> AsmStrs;
9690   IA->collectAsmStrs(AsmStrs);
9691 
9692   // Second pass over the constraints: compute which constraint option to use.
9693   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9694     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9695       OpNo++;
9696 
9697     // If this is an output operand with a matching input operand, look up the
9698     // matching input. If their types mismatch, e.g. one is an integer, the
9699     // other is floating point, or their sizes are different, flag it as an
9700     // error.
9701     if (OpInfo.hasMatchingInput()) {
9702       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9703       patchMatchingInput(OpInfo, Input, DAG);
9704     }
9705 
9706     // Compute the constraint code and ConstraintType to use.
9707     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9708 
9709     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9710          OpInfo.Type == InlineAsm::isClobber) ||
9711         OpInfo.ConstraintType == TargetLowering::C_Address)
9712       continue;
9713 
9714     // In Linux PIC model, there are 4 cases about value/label addressing:
9715     //
9716     // 1: Function call or Label jmp inside the module.
9717     // 2: Data access (such as global variable, static variable) inside module.
9718     // 3: Function call or Label jmp outside the module.
9719     // 4: Data access (such as global variable) outside the module.
9720     //
9721     // Due to current llvm inline asm architecture designed to not "recognize"
9722     // the asm code, there are quite troubles for us to treat mem addressing
9723     // differently for same value/adress used in different instuctions.
9724     // For example, in pic model, call a func may in plt way or direclty
9725     // pc-related, but lea/mov a function adress may use got.
9726     //
9727     // Here we try to "recognize" function call for the case 1 and case 3 in
9728     // inline asm. And try to adjust the constraint for them.
9729     //
9730     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9731     // label, so here we don't handle jmp function label now, but we need to
9732     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9733     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9734         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9735         TM.getCodeModel() != CodeModel::Large) {
9736       OpInfo.isIndirect = false;
9737       OpInfo.ConstraintType = TargetLowering::C_Address;
9738     }
9739 
9740     // If this is a memory input, and if the operand is not indirect, do what we
9741     // need to provide an address for the memory input.
9742     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9743         !OpInfo.isIndirect) {
9744       assert((OpInfo.isMultipleAlternative ||
9745               (OpInfo.Type == InlineAsm::isInput)) &&
9746              "Can only indirectify direct input operands!");
9747 
9748       // Memory operands really want the address of the value.
9749       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9750 
9751       // There is no longer a Value* corresponding to this operand.
9752       OpInfo.CallOperandVal = nullptr;
9753 
9754       // It is now an indirect operand.
9755       OpInfo.isIndirect = true;
9756     }
9757 
9758   }
9759 
9760   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9761   std::vector<SDValue> AsmNodeOperands;
9762   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9763   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9764       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9765 
9766   // If we have a !srcloc metadata node associated with it, we want to attach
9767   // this to the ultimately generated inline asm machineinstr.  To do this, we
9768   // pass in the third operand as this (potentially null) inline asm MDNode.
9769   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9770   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9771 
9772   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9773   // bits as operand 3.
9774   AsmNodeOperands.push_back(DAG.getTargetConstant(
9775       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9776 
9777   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9778   // this, assign virtual and physical registers for inputs and otput.
9779   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9780     // Assign Registers.
9781     SDISelAsmOperandInfo &RefOpInfo =
9782         OpInfo.isMatchingInputConstraint()
9783             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9784             : OpInfo;
9785     const auto RegError =
9786         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9787     if (RegError) {
9788       const MachineFunction &MF = DAG.getMachineFunction();
9789       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9790       const char *RegName = TRI.getName(*RegError);
9791       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9792                                    "' allocated for constraint '" +
9793                                    Twine(OpInfo.ConstraintCode) +
9794                                    "' does not match required type");
9795       return;
9796     }
9797 
9798     auto DetectWriteToReservedRegister = [&]() {
9799       const MachineFunction &MF = DAG.getMachineFunction();
9800       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9801       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9802         if (Register::isPhysicalRegister(Reg) &&
9803             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9804           const char *RegName = TRI.getName(Reg);
9805           emitInlineAsmError(Call, "write to reserved register '" +
9806                                        Twine(RegName) + "'");
9807           return true;
9808         }
9809       }
9810       return false;
9811     };
9812     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9813             (OpInfo.Type == InlineAsm::isInput &&
9814              !OpInfo.isMatchingInputConstraint())) &&
9815            "Only address as input operand is allowed.");
9816 
9817     switch (OpInfo.Type) {
9818     case InlineAsm::isOutput:
9819       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9820         const InlineAsm::ConstraintCode ConstraintID =
9821             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9822         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9823                "Failed to convert memory constraint code to constraint id.");
9824 
9825         // Add information to the INLINEASM node to know about this output.
9826         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
9827         OpFlags.setMemConstraint(ConstraintID);
9828         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9829                                                         MVT::i32));
9830         AsmNodeOperands.push_back(OpInfo.CallOperand);
9831       } else {
9832         // Otherwise, this outputs to a register (directly for C_Register /
9833         // C_RegisterClass, and a target-defined fashion for
9834         // C_Immediate/C_Other). Find a register that we can use.
9835         if (OpInfo.AssignedRegs.Regs.empty()) {
9836           emitInlineAsmError(
9837               Call, "couldn't allocate output register for constraint '" +
9838                         Twine(OpInfo.ConstraintCode) + "'");
9839           return;
9840         }
9841 
9842         if (DetectWriteToReservedRegister())
9843           return;
9844 
9845         // Add information to the INLINEASM node to know that this register is
9846         // set.
9847         OpInfo.AssignedRegs.AddInlineAsmOperands(
9848             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
9849                                   : InlineAsm::Kind::RegDef,
9850             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9851       }
9852       break;
9853 
9854     case InlineAsm::isInput:
9855     case InlineAsm::isLabel: {
9856       SDValue InOperandVal = OpInfo.CallOperand;
9857 
9858       if (OpInfo.isMatchingInputConstraint()) {
9859         // If this is required to match an output register we have already set,
9860         // just use its register.
9861         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9862                                                   AsmNodeOperands);
9863         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
9864         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
9865           if (OpInfo.isIndirect) {
9866             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9867             emitInlineAsmError(Call, "inline asm not supported yet: "
9868                                      "don't know how to handle tied "
9869                                      "indirect register inputs");
9870             return;
9871           }
9872 
9873           SmallVector<unsigned, 4> Regs;
9874           MachineFunction &MF = DAG.getMachineFunction();
9875           MachineRegisterInfo &MRI = MF.getRegInfo();
9876           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9877           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9878           Register TiedReg = R->getReg();
9879           MVT RegVT = R->getSimpleValueType(0);
9880           const TargetRegisterClass *RC =
9881               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9882               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9883                                       : TRI.getMinimalPhysRegClass(TiedReg);
9884           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
9885             Regs.push_back(MRI.createVirtualRegister(RC));
9886 
9887           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9888 
9889           SDLoc dl = getCurSDLoc();
9890           // Use the produced MatchedRegs object to
9891           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9892           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
9893                                            OpInfo.getMatchedOperand(), dl, DAG,
9894                                            AsmNodeOperands);
9895           break;
9896         }
9897 
9898         assert(Flag.isMemKind() && "Unknown matching constraint!");
9899         assert(Flag.getNumOperandRegisters() == 1 &&
9900                "Unexpected number of operands");
9901         // Add information to the INLINEASM node to know about this input.
9902         // See InlineAsm.h isUseOperandTiedToDef.
9903         Flag.clearMemConstraint();
9904         Flag.setMatchingOp(OpInfo.getMatchedOperand());
9905         AsmNodeOperands.push_back(DAG.getTargetConstant(
9906             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9907         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9908         break;
9909       }
9910 
9911       // Treat indirect 'X' constraint as memory.
9912       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9913           OpInfo.isIndirect)
9914         OpInfo.ConstraintType = TargetLowering::C_Memory;
9915 
9916       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9917           OpInfo.ConstraintType == TargetLowering::C_Other) {
9918         std::vector<SDValue> Ops;
9919         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9920                                           Ops, DAG);
9921         if (Ops.empty()) {
9922           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9923             if (isa<ConstantSDNode>(InOperandVal)) {
9924               emitInlineAsmError(Call, "value out of range for constraint '" +
9925                                            Twine(OpInfo.ConstraintCode) + "'");
9926               return;
9927             }
9928 
9929           emitInlineAsmError(Call,
9930                              "invalid operand for inline asm constraint '" +
9931                                  Twine(OpInfo.ConstraintCode) + "'");
9932           return;
9933         }
9934 
9935         // Add information to the INLINEASM node to know about this input.
9936         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
9937         AsmNodeOperands.push_back(DAG.getTargetConstant(
9938             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9939         llvm::append_range(AsmNodeOperands, Ops);
9940         break;
9941       }
9942 
9943       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9944         assert((OpInfo.isIndirect ||
9945                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9946                "Operand must be indirect to be a mem!");
9947         assert(InOperandVal.getValueType() ==
9948                    TLI.getPointerTy(DAG.getDataLayout()) &&
9949                "Memory operands expect pointer values");
9950 
9951         const InlineAsm::ConstraintCode ConstraintID =
9952             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9953         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9954                "Failed to convert memory constraint code to constraint id.");
9955 
9956         // Add information to the INLINEASM node to know about this input.
9957         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9958         ResOpType.setMemConstraint(ConstraintID);
9959         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9960                                                         getCurSDLoc(),
9961                                                         MVT::i32));
9962         AsmNodeOperands.push_back(InOperandVal);
9963         break;
9964       }
9965 
9966       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9967         const InlineAsm::ConstraintCode ConstraintID =
9968             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9969         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9970                "Failed to convert memory constraint code to constraint id.");
9971 
9972         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9973 
9974         SDValue AsmOp = InOperandVal;
9975         if (isFunction(InOperandVal)) {
9976           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9977           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
9978           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9979                                              InOperandVal.getValueType(),
9980                                              GA->getOffset());
9981         }
9982 
9983         // Add information to the INLINEASM node to know about this input.
9984         ResOpType.setMemConstraint(ConstraintID);
9985 
9986         AsmNodeOperands.push_back(
9987             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9988 
9989         AsmNodeOperands.push_back(AsmOp);
9990         break;
9991       }
9992 
9993       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9994               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9995              "Unknown constraint type!");
9996 
9997       // TODO: Support this.
9998       if (OpInfo.isIndirect) {
9999         emitInlineAsmError(
10000             Call, "Don't know how to handle indirect register inputs yet "
10001                   "for constraint '" +
10002                       Twine(OpInfo.ConstraintCode) + "'");
10003         return;
10004       }
10005 
10006       // Copy the input into the appropriate registers.
10007       if (OpInfo.AssignedRegs.Regs.empty()) {
10008         emitInlineAsmError(Call,
10009                            "couldn't allocate input reg for constraint '" +
10010                                Twine(OpInfo.ConstraintCode) + "'");
10011         return;
10012       }
10013 
10014       if (DetectWriteToReservedRegister())
10015         return;
10016 
10017       SDLoc dl = getCurSDLoc();
10018 
10019       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
10020                                         &Call);
10021 
10022       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
10023                                                0, dl, DAG, AsmNodeOperands);
10024       break;
10025     }
10026     case InlineAsm::isClobber:
10027       // Add the clobbered value to the operand list, so that the register
10028       // allocator is aware that the physreg got clobbered.
10029       if (!OpInfo.AssignedRegs.Regs.empty())
10030         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
10031                                                  false, 0, getCurSDLoc(), DAG,
10032                                                  AsmNodeOperands);
10033       break;
10034     }
10035   }
10036 
10037   // Finish up input operands.  Set the input chain and add the flag last.
10038   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10039   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
10040 
10041   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10042   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
10043                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
10044   Glue = Chain.getValue(1);
10045 
10046   // Do additional work to generate outputs.
10047 
10048   SmallVector<EVT, 1> ResultVTs;
10049   SmallVector<SDValue, 1> ResultValues;
10050   SmallVector<SDValue, 8> OutChains;
10051 
10052   llvm::Type *CallResultType = Call.getType();
10053   ArrayRef<Type *> ResultTypes;
10054   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10055     ResultTypes = StructResult->elements();
10056   else if (!CallResultType->isVoidTy())
10057     ResultTypes = ArrayRef(CallResultType);
10058 
10059   auto CurResultType = ResultTypes.begin();
10060   auto handleRegAssign = [&](SDValue V) {
10061     assert(CurResultType != ResultTypes.end() && "Unexpected value");
10062     assert((*CurResultType)->isSized() && "Unexpected unsized type");
10063     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10064     ++CurResultType;
10065     // If the type of the inline asm call site return value is different but has
10066     // same size as the type of the asm output bitcast it.  One example of this
10067     // is for vectors with different width / number of elements.  This can
10068     // happen for register classes that can contain multiple different value
10069     // types.  The preg or vreg allocated may not have the same VT as was
10070     // expected.
10071     //
10072     // This can also happen for a return value that disagrees with the register
10073     // class it is put in, eg. a double in a general-purpose register on a
10074     // 32-bit machine.
10075     if (ResultVT != V.getValueType() &&
10076         ResultVT.getSizeInBits() == V.getValueSizeInBits())
10077       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10078     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10079              V.getValueType().isInteger()) {
10080       // If a result value was tied to an input value, the computed result
10081       // may have a wider width than the expected result.  Extract the
10082       // relevant portion.
10083       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10084     }
10085     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10086     ResultVTs.push_back(ResultVT);
10087     ResultValues.push_back(V);
10088   };
10089 
10090   // Deal with output operands.
10091   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10092     if (OpInfo.Type == InlineAsm::isOutput) {
10093       SDValue Val;
10094       // Skip trivial output operands.
10095       if (OpInfo.AssignedRegs.Regs.empty())
10096         continue;
10097 
10098       switch (OpInfo.ConstraintType) {
10099       case TargetLowering::C_Register:
10100       case TargetLowering::C_RegisterClass:
10101         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10102                                                   Chain, &Glue, &Call);
10103         break;
10104       case TargetLowering::C_Immediate:
10105       case TargetLowering::C_Other:
10106         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10107                                               OpInfo, DAG);
10108         break;
10109       case TargetLowering::C_Memory:
10110         break; // Already handled.
10111       case TargetLowering::C_Address:
10112         break; // Silence warning.
10113       case TargetLowering::C_Unknown:
10114         assert(false && "Unexpected unknown constraint");
10115       }
10116 
10117       // Indirect output manifest as stores. Record output chains.
10118       if (OpInfo.isIndirect) {
10119         const Value *Ptr = OpInfo.CallOperandVal;
10120         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10121         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10122                                      MachinePointerInfo(Ptr));
10123         OutChains.push_back(Store);
10124       } else {
10125         // generate CopyFromRegs to associated registers.
10126         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10127         if (Val.getOpcode() == ISD::MERGE_VALUES) {
10128           for (const SDValue &V : Val->op_values())
10129             handleRegAssign(V);
10130         } else
10131           handleRegAssign(Val);
10132       }
10133     }
10134   }
10135 
10136   // Set results.
10137   if (!ResultValues.empty()) {
10138     assert(CurResultType == ResultTypes.end() &&
10139            "Mismatch in number of ResultTypes");
10140     assert(ResultValues.size() == ResultTypes.size() &&
10141            "Mismatch in number of output operands in asm result");
10142 
10143     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10144                             DAG.getVTList(ResultVTs), ResultValues);
10145     setValue(&Call, V);
10146   }
10147 
10148   // Collect store chains.
10149   if (!OutChains.empty())
10150     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10151 
10152   if (EmitEHLabels) {
10153     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10154   }
10155 
10156   // Only Update Root if inline assembly has a memory effect.
10157   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10158       EmitEHLabels)
10159     DAG.setRoot(Chain);
10160 }
10161 
10162 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10163                                              const Twine &Message) {
10164   LLVMContext &Ctx = *DAG.getContext();
10165   Ctx.emitError(&Call, Message);
10166 
10167   // Make sure we leave the DAG in a valid state
10168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10169   SmallVector<EVT, 1> ValueVTs;
10170   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10171 
10172   if (ValueVTs.empty())
10173     return;
10174 
10175   SmallVector<SDValue, 1> Ops;
10176   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
10177     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
10178 
10179   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10180 }
10181 
10182 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10183   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10184                           MVT::Other, getRoot(),
10185                           getValue(I.getArgOperand(0)),
10186                           DAG.getSrcValue(I.getArgOperand(0))));
10187 }
10188 
10189 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10190   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10191   const DataLayout &DL = DAG.getDataLayout();
10192   SDValue V = DAG.getVAArg(
10193       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10194       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10195       DL.getABITypeAlign(I.getType()).value());
10196   DAG.setRoot(V.getValue(1));
10197 
10198   if (I.getType()->isPointerTy())
10199     V = DAG.getPtrExtOrTrunc(
10200         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10201   setValue(&I, V);
10202 }
10203 
10204 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10205   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10206                           MVT::Other, getRoot(),
10207                           getValue(I.getArgOperand(0)),
10208                           DAG.getSrcValue(I.getArgOperand(0))));
10209 }
10210 
10211 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10212   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10213                           MVT::Other, getRoot(),
10214                           getValue(I.getArgOperand(0)),
10215                           getValue(I.getArgOperand(1)),
10216                           DAG.getSrcValue(I.getArgOperand(0)),
10217                           DAG.getSrcValue(I.getArgOperand(1))));
10218 }
10219 
10220 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10221                                                     const Instruction &I,
10222                                                     SDValue Op) {
10223   const MDNode *Range = getRangeMetadata(I);
10224   if (!Range)
10225     return Op;
10226 
10227   ConstantRange CR = getConstantRangeFromMetadata(*Range);
10228   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
10229     return Op;
10230 
10231   APInt Lo = CR.getUnsignedMin();
10232   if (!Lo.isMinValue())
10233     return Op;
10234 
10235   APInt Hi = CR.getUnsignedMax();
10236   unsigned Bits = std::max(Hi.getActiveBits(),
10237                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10238 
10239   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10240 
10241   SDLoc SL = getCurSDLoc();
10242 
10243   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10244                              DAG.getValueType(SmallVT));
10245   unsigned NumVals = Op.getNode()->getNumValues();
10246   if (NumVals == 1)
10247     return ZExt;
10248 
10249   SmallVector<SDValue, 4> Ops;
10250 
10251   Ops.push_back(ZExt);
10252   for (unsigned I = 1; I != NumVals; ++I)
10253     Ops.push_back(Op.getValue(I));
10254 
10255   return DAG.getMergeValues(Ops, SL);
10256 }
10257 
10258 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10259 /// the call being lowered.
10260 ///
10261 /// This is a helper for lowering intrinsics that follow a target calling
10262 /// convention or require stack pointer adjustment. Only a subset of the
10263 /// intrinsic's operands need to participate in the calling convention.
10264 void SelectionDAGBuilder::populateCallLoweringInfo(
10265     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10266     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10267     AttributeSet RetAttrs, bool IsPatchPoint) {
10268   TargetLowering::ArgListTy Args;
10269   Args.reserve(NumArgs);
10270 
10271   // Populate the argument list.
10272   // Attributes for args start at offset 1, after the return attribute.
10273   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10274        ArgI != ArgE; ++ArgI) {
10275     const Value *V = Call->getOperand(ArgI);
10276 
10277     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10278 
10279     TargetLowering::ArgListEntry Entry;
10280     Entry.Node = getValue(V);
10281     Entry.Ty = V->getType();
10282     Entry.setAttributes(Call, ArgI);
10283     Args.push_back(Entry);
10284   }
10285 
10286   CLI.setDebugLoc(getCurSDLoc())
10287       .setChain(getRoot())
10288       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10289                  RetAttrs)
10290       .setDiscardResult(Call->use_empty())
10291       .setIsPatchPoint(IsPatchPoint)
10292       .setIsPreallocated(
10293           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10294 }
10295 
10296 /// Add a stack map intrinsic call's live variable operands to a stackmap
10297 /// or patchpoint target node's operand list.
10298 ///
10299 /// Constants are converted to TargetConstants purely as an optimization to
10300 /// avoid constant materialization and register allocation.
10301 ///
10302 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10303 /// generate addess computation nodes, and so FinalizeISel can convert the
10304 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10305 /// address materialization and register allocation, but may also be required
10306 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10307 /// alloca in the entry block, then the runtime may assume that the alloca's
10308 /// StackMap location can be read immediately after compilation and that the
10309 /// location is valid at any point during execution (this is similar to the
10310 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10311 /// only available in a register, then the runtime would need to trap when
10312 /// execution reaches the StackMap in order to read the alloca's location.
10313 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10314                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10315                                 SelectionDAGBuilder &Builder) {
10316   SelectionDAG &DAG = Builder.DAG;
10317   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10318     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10319 
10320     // Things on the stack are pointer-typed, meaning that they are already
10321     // legal and can be emitted directly to target nodes.
10322     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10323       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10324     } else {
10325       // Otherwise emit a target independent node to be legalised.
10326       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10327     }
10328   }
10329 }
10330 
10331 /// Lower llvm.experimental.stackmap.
10332 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10333   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10334   //                                  [live variables...])
10335 
10336   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10337 
10338   SDValue Chain, InGlue, Callee;
10339   SmallVector<SDValue, 32> Ops;
10340 
10341   SDLoc DL = getCurSDLoc();
10342   Callee = getValue(CI.getCalledOperand());
10343 
10344   // The stackmap intrinsic only records the live variables (the arguments
10345   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10346   // intrinsic, this won't be lowered to a function call. This means we don't
10347   // have to worry about calling conventions and target specific lowering code.
10348   // Instead we perform the call lowering right here.
10349   //
10350   // chain, flag = CALLSEQ_START(chain, 0, 0)
10351   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10352   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10353   //
10354   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10355   InGlue = Chain.getValue(1);
10356 
10357   // Add the STACKMAP operands, starting with DAG house-keeping.
10358   Ops.push_back(Chain);
10359   Ops.push_back(InGlue);
10360 
10361   // Add the <id>, <numShadowBytes> operands.
10362   //
10363   // These do not require legalisation, and can be emitted directly to target
10364   // constant nodes.
10365   SDValue ID = getValue(CI.getArgOperand(0));
10366   assert(ID.getValueType() == MVT::i64);
10367   SDValue IDConst =
10368       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10369   Ops.push_back(IDConst);
10370 
10371   SDValue Shad = getValue(CI.getArgOperand(1));
10372   assert(Shad.getValueType() == MVT::i32);
10373   SDValue ShadConst =
10374       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10375   Ops.push_back(ShadConst);
10376 
10377   // Add the live variables.
10378   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10379 
10380   // Create the STACKMAP node.
10381   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10382   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10383   InGlue = Chain.getValue(1);
10384 
10385   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10386 
10387   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10388 
10389   // Set the root to the target-lowered call chain.
10390   DAG.setRoot(Chain);
10391 
10392   // Inform the Frame Information that we have a stackmap in this function.
10393   FuncInfo.MF->getFrameInfo().setHasStackMap();
10394 }
10395 
10396 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10397 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10398                                           const BasicBlock *EHPadBB) {
10399   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10400   //                                         i32 <numBytes>,
10401   //                                         i8* <target>,
10402   //                                         i32 <numArgs>,
10403   //                                         [Args...],
10404   //                                         [live variables...])
10405 
10406   CallingConv::ID CC = CB.getCallingConv();
10407   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10408   bool HasDef = !CB.getType()->isVoidTy();
10409   SDLoc dl = getCurSDLoc();
10410   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10411 
10412   // Handle immediate and symbolic callees.
10413   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10414     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10415                                    /*isTarget=*/true);
10416   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10417     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10418                                          SDLoc(SymbolicCallee),
10419                                          SymbolicCallee->getValueType(0));
10420 
10421   // Get the real number of arguments participating in the call <numArgs>
10422   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10423   unsigned NumArgs = NArgVal->getAsZExtVal();
10424 
10425   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10426   // Intrinsics include all meta-operands up to but not including CC.
10427   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10428   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10429          "Not enough arguments provided to the patchpoint intrinsic");
10430 
10431   // For AnyRegCC the arguments are lowered later on manually.
10432   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10433   Type *ReturnTy =
10434       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10435 
10436   TargetLowering::CallLoweringInfo CLI(DAG);
10437   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10438                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10439   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10440 
10441   SDNode *CallEnd = Result.second.getNode();
10442   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10443     CallEnd = CallEnd->getOperand(0).getNode();
10444 
10445   /// Get a call instruction from the call sequence chain.
10446   /// Tail calls are not allowed.
10447   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10448          "Expected a callseq node.");
10449   SDNode *Call = CallEnd->getOperand(0).getNode();
10450   bool HasGlue = Call->getGluedNode();
10451 
10452   // Replace the target specific call node with the patchable intrinsic.
10453   SmallVector<SDValue, 8> Ops;
10454 
10455   // Push the chain.
10456   Ops.push_back(*(Call->op_begin()));
10457 
10458   // Optionally, push the glue (if any).
10459   if (HasGlue)
10460     Ops.push_back(*(Call->op_end() - 1));
10461 
10462   // Push the register mask info.
10463   if (HasGlue)
10464     Ops.push_back(*(Call->op_end() - 2));
10465   else
10466     Ops.push_back(*(Call->op_end() - 1));
10467 
10468   // Add the <id> and <numBytes> constants.
10469   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10470   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10471   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10472   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10473 
10474   // Add the callee.
10475   Ops.push_back(Callee);
10476 
10477   // Adjust <numArgs> to account for any arguments that have been passed on the
10478   // stack instead.
10479   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10480   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10481   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10482   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10483 
10484   // Add the calling convention
10485   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10486 
10487   // Add the arguments we omitted previously. The register allocator should
10488   // place these in any free register.
10489   if (IsAnyRegCC)
10490     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10491       Ops.push_back(getValue(CB.getArgOperand(i)));
10492 
10493   // Push the arguments from the call instruction.
10494   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10495   Ops.append(Call->op_begin() + 2, e);
10496 
10497   // Push live variables for the stack map.
10498   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10499 
10500   SDVTList NodeTys;
10501   if (IsAnyRegCC && HasDef) {
10502     // Create the return types based on the intrinsic definition
10503     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10504     SmallVector<EVT, 3> ValueVTs;
10505     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10506     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10507 
10508     // There is always a chain and a glue type at the end
10509     ValueVTs.push_back(MVT::Other);
10510     ValueVTs.push_back(MVT::Glue);
10511     NodeTys = DAG.getVTList(ValueVTs);
10512   } else
10513     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10514 
10515   // Replace the target specific call node with a PATCHPOINT node.
10516   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10517 
10518   // Update the NodeMap.
10519   if (HasDef) {
10520     if (IsAnyRegCC)
10521       setValue(&CB, SDValue(PPV.getNode(), 0));
10522     else
10523       setValue(&CB, Result.first);
10524   }
10525 
10526   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10527   // call sequence. Furthermore the location of the chain and glue can change
10528   // when the AnyReg calling convention is used and the intrinsic returns a
10529   // value.
10530   if (IsAnyRegCC && HasDef) {
10531     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10532     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10533     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10534   } else
10535     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10536   DAG.DeleteNode(Call);
10537 
10538   // Inform the Frame Information that we have a patchpoint in this function.
10539   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10540 }
10541 
10542 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10543                                             unsigned Intrinsic) {
10544   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10545   SDValue Op1 = getValue(I.getArgOperand(0));
10546   SDValue Op2;
10547   if (I.arg_size() > 1)
10548     Op2 = getValue(I.getArgOperand(1));
10549   SDLoc dl = getCurSDLoc();
10550   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10551   SDValue Res;
10552   SDNodeFlags SDFlags;
10553   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10554     SDFlags.copyFMF(*FPMO);
10555 
10556   switch (Intrinsic) {
10557   case Intrinsic::vector_reduce_fadd:
10558     if (SDFlags.hasAllowReassociation())
10559       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10560                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10561                         SDFlags);
10562     else
10563       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10564     break;
10565   case Intrinsic::vector_reduce_fmul:
10566     if (SDFlags.hasAllowReassociation())
10567       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10568                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10569                         SDFlags);
10570     else
10571       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10572     break;
10573   case Intrinsic::vector_reduce_add:
10574     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10575     break;
10576   case Intrinsic::vector_reduce_mul:
10577     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10578     break;
10579   case Intrinsic::vector_reduce_and:
10580     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10581     break;
10582   case Intrinsic::vector_reduce_or:
10583     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10584     break;
10585   case Intrinsic::vector_reduce_xor:
10586     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10587     break;
10588   case Intrinsic::vector_reduce_smax:
10589     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10590     break;
10591   case Intrinsic::vector_reduce_smin:
10592     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10593     break;
10594   case Intrinsic::vector_reduce_umax:
10595     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10596     break;
10597   case Intrinsic::vector_reduce_umin:
10598     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10599     break;
10600   case Intrinsic::vector_reduce_fmax:
10601     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10602     break;
10603   case Intrinsic::vector_reduce_fmin:
10604     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10605     break;
10606   case Intrinsic::vector_reduce_fmaximum:
10607     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10608     break;
10609   case Intrinsic::vector_reduce_fminimum:
10610     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10611     break;
10612   default:
10613     llvm_unreachable("Unhandled vector reduce intrinsic");
10614   }
10615   setValue(&I, Res);
10616 }
10617 
10618 /// Returns an AttributeList representing the attributes applied to the return
10619 /// value of the given call.
10620 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10621   SmallVector<Attribute::AttrKind, 2> Attrs;
10622   if (CLI.RetSExt)
10623     Attrs.push_back(Attribute::SExt);
10624   if (CLI.RetZExt)
10625     Attrs.push_back(Attribute::ZExt);
10626   if (CLI.IsInReg)
10627     Attrs.push_back(Attribute::InReg);
10628 
10629   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10630                             Attrs);
10631 }
10632 
10633 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10634 /// implementation, which just calls LowerCall.
10635 /// FIXME: When all targets are
10636 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10637 std::pair<SDValue, SDValue>
10638 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10639   // Handle the incoming return values from the call.
10640   CLI.Ins.clear();
10641   Type *OrigRetTy = CLI.RetTy;
10642   SmallVector<EVT, 4> RetTys;
10643   SmallVector<TypeSize, 4> Offsets;
10644   auto &DL = CLI.DAG.getDataLayout();
10645   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10646 
10647   if (CLI.IsPostTypeLegalization) {
10648     // If we are lowering a libcall after legalization, split the return type.
10649     SmallVector<EVT, 4> OldRetTys;
10650     SmallVector<TypeSize, 4> OldOffsets;
10651     RetTys.swap(OldRetTys);
10652     Offsets.swap(OldOffsets);
10653 
10654     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10655       EVT RetVT = OldRetTys[i];
10656       uint64_t Offset = OldOffsets[i];
10657       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10658       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10659       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10660       RetTys.append(NumRegs, RegisterVT);
10661       for (unsigned j = 0; j != NumRegs; ++j)
10662         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
10663     }
10664   }
10665 
10666   SmallVector<ISD::OutputArg, 4> Outs;
10667   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10668 
10669   bool CanLowerReturn =
10670       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10671                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10672 
10673   SDValue DemoteStackSlot;
10674   int DemoteStackIdx = -100;
10675   if (!CanLowerReturn) {
10676     // FIXME: equivalent assert?
10677     // assert(!CS.hasInAllocaArgument() &&
10678     //        "sret demotion is incompatible with inalloca");
10679     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10680     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10681     MachineFunction &MF = CLI.DAG.getMachineFunction();
10682     DemoteStackIdx =
10683         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10684     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10685                                               DL.getAllocaAddrSpace());
10686 
10687     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10688     ArgListEntry Entry;
10689     Entry.Node = DemoteStackSlot;
10690     Entry.Ty = StackSlotPtrType;
10691     Entry.IsSExt = false;
10692     Entry.IsZExt = false;
10693     Entry.IsInReg = false;
10694     Entry.IsSRet = true;
10695     Entry.IsNest = false;
10696     Entry.IsByVal = false;
10697     Entry.IsByRef = false;
10698     Entry.IsReturned = false;
10699     Entry.IsSwiftSelf = false;
10700     Entry.IsSwiftAsync = false;
10701     Entry.IsSwiftError = false;
10702     Entry.IsCFGuardTarget = false;
10703     Entry.Alignment = Alignment;
10704     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10705     CLI.NumFixedArgs += 1;
10706     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10707     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10708 
10709     // sret demotion isn't compatible with tail-calls, since the sret argument
10710     // points into the callers stack frame.
10711     CLI.IsTailCall = false;
10712   } else {
10713     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10714         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10715     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10716       ISD::ArgFlagsTy Flags;
10717       if (NeedsRegBlock) {
10718         Flags.setInConsecutiveRegs();
10719         if (I == RetTys.size() - 1)
10720           Flags.setInConsecutiveRegsLast();
10721       }
10722       EVT VT = RetTys[I];
10723       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10724                                                      CLI.CallConv, VT);
10725       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10726                                                        CLI.CallConv, VT);
10727       for (unsigned i = 0; i != NumRegs; ++i) {
10728         ISD::InputArg MyFlags;
10729         MyFlags.Flags = Flags;
10730         MyFlags.VT = RegisterVT;
10731         MyFlags.ArgVT = VT;
10732         MyFlags.Used = CLI.IsReturnValueUsed;
10733         if (CLI.RetTy->isPointerTy()) {
10734           MyFlags.Flags.setPointer();
10735           MyFlags.Flags.setPointerAddrSpace(
10736               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10737         }
10738         if (CLI.RetSExt)
10739           MyFlags.Flags.setSExt();
10740         if (CLI.RetZExt)
10741           MyFlags.Flags.setZExt();
10742         if (CLI.IsInReg)
10743           MyFlags.Flags.setInReg();
10744         CLI.Ins.push_back(MyFlags);
10745       }
10746     }
10747   }
10748 
10749   // We push in swifterror return as the last element of CLI.Ins.
10750   ArgListTy &Args = CLI.getArgs();
10751   if (supportSwiftError()) {
10752     for (const ArgListEntry &Arg : Args) {
10753       if (Arg.IsSwiftError) {
10754         ISD::InputArg MyFlags;
10755         MyFlags.VT = getPointerTy(DL);
10756         MyFlags.ArgVT = EVT(getPointerTy(DL));
10757         MyFlags.Flags.setSwiftError();
10758         CLI.Ins.push_back(MyFlags);
10759       }
10760     }
10761   }
10762 
10763   // Handle all of the outgoing arguments.
10764   CLI.Outs.clear();
10765   CLI.OutVals.clear();
10766   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10767     SmallVector<EVT, 4> ValueVTs;
10768     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10769     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10770     Type *FinalType = Args[i].Ty;
10771     if (Args[i].IsByVal)
10772       FinalType = Args[i].IndirectType;
10773     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10774         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10775     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10776          ++Value) {
10777       EVT VT = ValueVTs[Value];
10778       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10779       SDValue Op = SDValue(Args[i].Node.getNode(),
10780                            Args[i].Node.getResNo() + Value);
10781       ISD::ArgFlagsTy Flags;
10782 
10783       // Certain targets (such as MIPS), may have a different ABI alignment
10784       // for a type depending on the context. Give the target a chance to
10785       // specify the alignment it wants.
10786       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10787       Flags.setOrigAlign(OriginalAlignment);
10788 
10789       if (Args[i].Ty->isPointerTy()) {
10790         Flags.setPointer();
10791         Flags.setPointerAddrSpace(
10792             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10793       }
10794       if (Args[i].IsZExt)
10795         Flags.setZExt();
10796       if (Args[i].IsSExt)
10797         Flags.setSExt();
10798       if (Args[i].IsInReg) {
10799         // If we are using vectorcall calling convention, a structure that is
10800         // passed InReg - is surely an HVA
10801         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10802             isa<StructType>(FinalType)) {
10803           // The first value of a structure is marked
10804           if (0 == Value)
10805             Flags.setHvaStart();
10806           Flags.setHva();
10807         }
10808         // Set InReg Flag
10809         Flags.setInReg();
10810       }
10811       if (Args[i].IsSRet)
10812         Flags.setSRet();
10813       if (Args[i].IsSwiftSelf)
10814         Flags.setSwiftSelf();
10815       if (Args[i].IsSwiftAsync)
10816         Flags.setSwiftAsync();
10817       if (Args[i].IsSwiftError)
10818         Flags.setSwiftError();
10819       if (Args[i].IsCFGuardTarget)
10820         Flags.setCFGuardTarget();
10821       if (Args[i].IsByVal)
10822         Flags.setByVal();
10823       if (Args[i].IsByRef)
10824         Flags.setByRef();
10825       if (Args[i].IsPreallocated) {
10826         Flags.setPreallocated();
10827         // Set the byval flag for CCAssignFn callbacks that don't know about
10828         // preallocated.  This way we can know how many bytes we should've
10829         // allocated and how many bytes a callee cleanup function will pop.  If
10830         // we port preallocated to more targets, we'll have to add custom
10831         // preallocated handling in the various CC lowering callbacks.
10832         Flags.setByVal();
10833       }
10834       if (Args[i].IsInAlloca) {
10835         Flags.setInAlloca();
10836         // Set the byval flag for CCAssignFn callbacks that don't know about
10837         // inalloca.  This way we can know how many bytes we should've allocated
10838         // and how many bytes a callee cleanup function will pop.  If we port
10839         // inalloca to more targets, we'll have to add custom inalloca handling
10840         // in the various CC lowering callbacks.
10841         Flags.setByVal();
10842       }
10843       Align MemAlign;
10844       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10845         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10846         Flags.setByValSize(FrameSize);
10847 
10848         // info is not there but there are cases it cannot get right.
10849         if (auto MA = Args[i].Alignment)
10850           MemAlign = *MA;
10851         else
10852           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10853       } else if (auto MA = Args[i].Alignment) {
10854         MemAlign = *MA;
10855       } else {
10856         MemAlign = OriginalAlignment;
10857       }
10858       Flags.setMemAlign(MemAlign);
10859       if (Args[i].IsNest)
10860         Flags.setNest();
10861       if (NeedsRegBlock)
10862         Flags.setInConsecutiveRegs();
10863 
10864       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10865                                                  CLI.CallConv, VT);
10866       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10867                                                         CLI.CallConv, VT);
10868       SmallVector<SDValue, 4> Parts(NumParts);
10869       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10870 
10871       if (Args[i].IsSExt)
10872         ExtendKind = ISD::SIGN_EXTEND;
10873       else if (Args[i].IsZExt)
10874         ExtendKind = ISD::ZERO_EXTEND;
10875 
10876       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10877       // for now.
10878       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10879           CanLowerReturn) {
10880         assert((CLI.RetTy == Args[i].Ty ||
10881                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10882                  CLI.RetTy->getPointerAddressSpace() ==
10883                      Args[i].Ty->getPointerAddressSpace())) &&
10884                RetTys.size() == NumValues && "unexpected use of 'returned'");
10885         // Before passing 'returned' to the target lowering code, ensure that
10886         // either the register MVT and the actual EVT are the same size or that
10887         // the return value and argument are extended in the same way; in these
10888         // cases it's safe to pass the argument register value unchanged as the
10889         // return register value (although it's at the target's option whether
10890         // to do so)
10891         // TODO: allow code generation to take advantage of partially preserved
10892         // registers rather than clobbering the entire register when the
10893         // parameter extension method is not compatible with the return
10894         // extension method
10895         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10896             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10897              CLI.RetZExt == Args[i].IsZExt))
10898           Flags.setReturned();
10899       }
10900 
10901       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10902                      CLI.CallConv, ExtendKind);
10903 
10904       for (unsigned j = 0; j != NumParts; ++j) {
10905         // if it isn't first piece, alignment must be 1
10906         // For scalable vectors the scalable part is currently handled
10907         // by individual targets, so we just use the known minimum size here.
10908         ISD::OutputArg MyFlags(
10909             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10910             i < CLI.NumFixedArgs, i,
10911             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10912         if (NumParts > 1 && j == 0)
10913           MyFlags.Flags.setSplit();
10914         else if (j != 0) {
10915           MyFlags.Flags.setOrigAlign(Align(1));
10916           if (j == NumParts - 1)
10917             MyFlags.Flags.setSplitEnd();
10918         }
10919 
10920         CLI.Outs.push_back(MyFlags);
10921         CLI.OutVals.push_back(Parts[j]);
10922       }
10923 
10924       if (NeedsRegBlock && Value == NumValues - 1)
10925         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10926     }
10927   }
10928 
10929   SmallVector<SDValue, 4> InVals;
10930   CLI.Chain = LowerCall(CLI, InVals);
10931 
10932   // Update CLI.InVals to use outside of this function.
10933   CLI.InVals = InVals;
10934 
10935   // Verify that the target's LowerCall behaved as expected.
10936   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10937          "LowerCall didn't return a valid chain!");
10938   assert((!CLI.IsTailCall || InVals.empty()) &&
10939          "LowerCall emitted a return value for a tail call!");
10940   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10941          "LowerCall didn't emit the correct number of values!");
10942 
10943   // For a tail call, the return value is merely live-out and there aren't
10944   // any nodes in the DAG representing it. Return a special value to
10945   // indicate that a tail call has been emitted and no more Instructions
10946   // should be processed in the current block.
10947   if (CLI.IsTailCall) {
10948     CLI.DAG.setRoot(CLI.Chain);
10949     return std::make_pair(SDValue(), SDValue());
10950   }
10951 
10952 #ifndef NDEBUG
10953   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10954     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10955     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10956            "LowerCall emitted a value with the wrong type!");
10957   }
10958 #endif
10959 
10960   SmallVector<SDValue, 4> ReturnValues;
10961   if (!CanLowerReturn) {
10962     // The instruction result is the result of loading from the
10963     // hidden sret parameter.
10964     SmallVector<EVT, 1> PVTs;
10965     Type *PtrRetTy =
10966         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
10967 
10968     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10969     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10970     EVT PtrVT = PVTs[0];
10971 
10972     unsigned NumValues = RetTys.size();
10973     ReturnValues.resize(NumValues);
10974     SmallVector<SDValue, 4> Chains(NumValues);
10975 
10976     // An aggregate return value cannot wrap around the address space, so
10977     // offsets to its parts don't wrap either.
10978     SDNodeFlags Flags;
10979     Flags.setNoUnsignedWrap(true);
10980 
10981     MachineFunction &MF = CLI.DAG.getMachineFunction();
10982     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10983     for (unsigned i = 0; i < NumValues; ++i) {
10984       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10985                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10986                                                         PtrVT), Flags);
10987       SDValue L = CLI.DAG.getLoad(
10988           RetTys[i], CLI.DL, CLI.Chain, Add,
10989           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10990                                             DemoteStackIdx, Offsets[i]),
10991           HiddenSRetAlign);
10992       ReturnValues[i] = L;
10993       Chains[i] = L.getValue(1);
10994     }
10995 
10996     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10997   } else {
10998     // Collect the legal value parts into potentially illegal values
10999     // that correspond to the original function's return values.
11000     std::optional<ISD::NodeType> AssertOp;
11001     if (CLI.RetSExt)
11002       AssertOp = ISD::AssertSext;
11003     else if (CLI.RetZExt)
11004       AssertOp = ISD::AssertZext;
11005     unsigned CurReg = 0;
11006     for (EVT VT : RetTys) {
11007       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11008                                                      CLI.CallConv, VT);
11009       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11010                                                        CLI.CallConv, VT);
11011 
11012       ReturnValues.push_back(getCopyFromParts(
11013           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11014           CLI.Chain, CLI.CallConv, AssertOp));
11015       CurReg += NumRegs;
11016     }
11017 
11018     // For a function returning void, there is no return value. We can't create
11019     // such a node, so we just return a null return value in that case. In
11020     // that case, nothing will actually look at the value.
11021     if (ReturnValues.empty())
11022       return std::make_pair(SDValue(), CLI.Chain);
11023   }
11024 
11025   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11026                                 CLI.DAG.getVTList(RetTys), ReturnValues);
11027   return std::make_pair(Res, CLI.Chain);
11028 }
11029 
11030 /// Places new result values for the node in Results (their number
11031 /// and types must exactly match those of the original return values of
11032 /// the node), or leaves Results empty, which indicates that the node is not
11033 /// to be custom lowered after all.
11034 void TargetLowering::LowerOperationWrapper(SDNode *N,
11035                                            SmallVectorImpl<SDValue> &Results,
11036                                            SelectionDAG &DAG) const {
11037   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11038 
11039   if (!Res.getNode())
11040     return;
11041 
11042   // If the original node has one result, take the return value from
11043   // LowerOperation as is. It might not be result number 0.
11044   if (N->getNumValues() == 1) {
11045     Results.push_back(Res);
11046     return;
11047   }
11048 
11049   // If the original node has multiple results, then the return node should
11050   // have the same number of results.
11051   assert((N->getNumValues() == Res->getNumValues()) &&
11052       "Lowering returned the wrong number of results!");
11053 
11054   // Places new result values base on N result number.
11055   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11056     Results.push_back(Res.getValue(I));
11057 }
11058 
11059 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11060   llvm_unreachable("LowerOperation not implemented for this target!");
11061 }
11062 
11063 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11064                                                      unsigned Reg,
11065                                                      ISD::NodeType ExtendType) {
11066   SDValue Op = getNonRegisterValue(V);
11067   assert((Op.getOpcode() != ISD::CopyFromReg ||
11068           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11069          "Copy from a reg to the same reg!");
11070   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
11071 
11072   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11073   // If this is an InlineAsm we have to match the registers required, not the
11074   // notional registers required by the type.
11075 
11076   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11077                    std::nullopt); // This is not an ABI copy.
11078   SDValue Chain = DAG.getEntryNode();
11079 
11080   if (ExtendType == ISD::ANY_EXTEND) {
11081     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11082     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11083       ExtendType = PreferredExtendIt->second;
11084   }
11085   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11086   PendingExports.push_back(Chain);
11087 }
11088 
11089 #include "llvm/CodeGen/SelectionDAGISel.h"
11090 
11091 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11092 /// entry block, return true.  This includes arguments used by switches, since
11093 /// the switch may expand into multiple basic blocks.
11094 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11095   // With FastISel active, we may be splitting blocks, so force creation
11096   // of virtual registers for all non-dead arguments.
11097   if (FastISel)
11098     return A->use_empty();
11099 
11100   const BasicBlock &Entry = A->getParent()->front();
11101   for (const User *U : A->users())
11102     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11103       return false;  // Use not in entry block.
11104 
11105   return true;
11106 }
11107 
11108 using ArgCopyElisionMapTy =
11109     DenseMap<const Argument *,
11110              std::pair<const AllocaInst *, const StoreInst *>>;
11111 
11112 /// Scan the entry block of the function in FuncInfo for arguments that look
11113 /// like copies into a local alloca. Record any copied arguments in
11114 /// ArgCopyElisionCandidates.
11115 static void
11116 findArgumentCopyElisionCandidates(const DataLayout &DL,
11117                                   FunctionLoweringInfo *FuncInfo,
11118                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11119   // Record the state of every static alloca used in the entry block. Argument
11120   // allocas are all used in the entry block, so we need approximately as many
11121   // entries as we have arguments.
11122   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11123   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11124   unsigned NumArgs = FuncInfo->Fn->arg_size();
11125   StaticAllocas.reserve(NumArgs * 2);
11126 
11127   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11128     if (!V)
11129       return nullptr;
11130     V = V->stripPointerCasts();
11131     const auto *AI = dyn_cast<AllocaInst>(V);
11132     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11133       return nullptr;
11134     auto Iter = StaticAllocas.insert({AI, Unknown});
11135     return &Iter.first->second;
11136   };
11137 
11138   // Look for stores of arguments to static allocas. Look through bitcasts and
11139   // GEPs to handle type coercions, as long as the alloca is fully initialized
11140   // by the store. Any non-store use of an alloca escapes it and any subsequent
11141   // unanalyzed store might write it.
11142   // FIXME: Handle structs initialized with multiple stores.
11143   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11144     // Look for stores, and handle non-store uses conservatively.
11145     const auto *SI = dyn_cast<StoreInst>(&I);
11146     if (!SI) {
11147       // We will look through cast uses, so ignore them completely.
11148       if (I.isCast())
11149         continue;
11150       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11151       // to allocas.
11152       if (I.isDebugOrPseudoInst())
11153         continue;
11154       // This is an unknown instruction. Assume it escapes or writes to all
11155       // static alloca operands.
11156       for (const Use &U : I.operands()) {
11157         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11158           *Info = StaticAllocaInfo::Clobbered;
11159       }
11160       continue;
11161     }
11162 
11163     // If the stored value is a static alloca, mark it as escaped.
11164     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11165       *Info = StaticAllocaInfo::Clobbered;
11166 
11167     // Check if the destination is a static alloca.
11168     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11169     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11170     if (!Info)
11171       continue;
11172     const AllocaInst *AI = cast<AllocaInst>(Dst);
11173 
11174     // Skip allocas that have been initialized or clobbered.
11175     if (*Info != StaticAllocaInfo::Unknown)
11176       continue;
11177 
11178     // Check if the stored value is an argument, and that this store fully
11179     // initializes the alloca.
11180     // If the argument type has padding bits we can't directly forward a pointer
11181     // as the upper bits may contain garbage.
11182     // Don't elide copies from the same argument twice.
11183     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11184     const auto *Arg = dyn_cast<Argument>(Val);
11185     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11186         Arg->getType()->isEmptyTy() ||
11187         DL.getTypeStoreSize(Arg->getType()) !=
11188             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11189         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11190         ArgCopyElisionCandidates.count(Arg)) {
11191       *Info = StaticAllocaInfo::Clobbered;
11192       continue;
11193     }
11194 
11195     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11196                       << '\n');
11197 
11198     // Mark this alloca and store for argument copy elision.
11199     *Info = StaticAllocaInfo::Elidable;
11200     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11201 
11202     // Stop scanning if we've seen all arguments. This will happen early in -O0
11203     // builds, which is useful, because -O0 builds have large entry blocks and
11204     // many allocas.
11205     if (ArgCopyElisionCandidates.size() == NumArgs)
11206       break;
11207   }
11208 }
11209 
11210 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11211 /// ArgVal is a load from a suitable fixed stack object.
11212 static void tryToElideArgumentCopy(
11213     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11214     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11215     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11216     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11217     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11218   // Check if this is a load from a fixed stack object.
11219   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11220   if (!LNode)
11221     return;
11222   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11223   if (!FINode)
11224     return;
11225 
11226   // Check that the fixed stack object is the right size and alignment.
11227   // Look at the alignment that the user wrote on the alloca instead of looking
11228   // at the stack object.
11229   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11230   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11231   const AllocaInst *AI = ArgCopyIter->second.first;
11232   int FixedIndex = FINode->getIndex();
11233   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11234   int OldIndex = AllocaIndex;
11235   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11236   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11237     LLVM_DEBUG(
11238         dbgs() << "  argument copy elision failed due to bad fixed stack "
11239                   "object size\n");
11240     return;
11241   }
11242   Align RequiredAlignment = AI->getAlign();
11243   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11244     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11245                          "greater than stack argument alignment ("
11246                       << DebugStr(RequiredAlignment) << " vs "
11247                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11248     return;
11249   }
11250 
11251   // Perform the elision. Delete the old stack object and replace its only use
11252   // in the variable info map. Mark the stack object as mutable and aliased.
11253   LLVM_DEBUG({
11254     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11255            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11256            << '\n';
11257   });
11258   MFI.RemoveStackObject(OldIndex);
11259   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11260   MFI.setIsAliasedObjectIndex(FixedIndex, true);
11261   AllocaIndex = FixedIndex;
11262   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11263   for (SDValue ArgVal : ArgVals)
11264     Chains.push_back(ArgVal.getValue(1));
11265 
11266   // Avoid emitting code for the store implementing the copy.
11267   const StoreInst *SI = ArgCopyIter->second.second;
11268   ElidedArgCopyInstrs.insert(SI);
11269 
11270   // Check for uses of the argument again so that we can avoid exporting ArgVal
11271   // if it is't used by anything other than the store.
11272   for (const Value *U : Arg.users()) {
11273     if (U != SI) {
11274       ArgHasUses = true;
11275       break;
11276     }
11277   }
11278 }
11279 
11280 void SelectionDAGISel::LowerArguments(const Function &F) {
11281   SelectionDAG &DAG = SDB->DAG;
11282   SDLoc dl = SDB->getCurSDLoc();
11283   const DataLayout &DL = DAG.getDataLayout();
11284   SmallVector<ISD::InputArg, 16> Ins;
11285 
11286   // In Naked functions we aren't going to save any registers.
11287   if (F.hasFnAttribute(Attribute::Naked))
11288     return;
11289 
11290   if (!FuncInfo->CanLowerReturn) {
11291     // Put in an sret pointer parameter before all the other parameters.
11292     SmallVector<EVT, 1> ValueVTs;
11293     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11294                     PointerType::get(F.getContext(),
11295                                      DAG.getDataLayout().getAllocaAddrSpace()),
11296                     ValueVTs);
11297 
11298     // NOTE: Assuming that a pointer will never break down to more than one VT
11299     // or one register.
11300     ISD::ArgFlagsTy Flags;
11301     Flags.setSRet();
11302     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
11303     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
11304                          ISD::InputArg::NoArgIndex, 0);
11305     Ins.push_back(RetArg);
11306   }
11307 
11308   // Look for stores of arguments to static allocas. Mark such arguments with a
11309   // flag to ask the target to give us the memory location of that argument if
11310   // available.
11311   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11312   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11313                                     ArgCopyElisionCandidates);
11314 
11315   // Set up the incoming argument description vector.
11316   for (const Argument &Arg : F.args()) {
11317     unsigned ArgNo = Arg.getArgNo();
11318     SmallVector<EVT, 4> ValueVTs;
11319     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11320     bool isArgValueUsed = !Arg.use_empty();
11321     unsigned PartBase = 0;
11322     Type *FinalType = Arg.getType();
11323     if (Arg.hasAttribute(Attribute::ByVal))
11324       FinalType = Arg.getParamByValType();
11325     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11326         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11327     for (unsigned Value = 0, NumValues = ValueVTs.size();
11328          Value != NumValues; ++Value) {
11329       EVT VT = ValueVTs[Value];
11330       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11331       ISD::ArgFlagsTy Flags;
11332 
11333 
11334       if (Arg.getType()->isPointerTy()) {
11335         Flags.setPointer();
11336         Flags.setPointerAddrSpace(
11337             cast<PointerType>(Arg.getType())->getAddressSpace());
11338       }
11339       if (Arg.hasAttribute(Attribute::ZExt))
11340         Flags.setZExt();
11341       if (Arg.hasAttribute(Attribute::SExt))
11342         Flags.setSExt();
11343       if (Arg.hasAttribute(Attribute::InReg)) {
11344         // If we are using vectorcall calling convention, a structure that is
11345         // passed InReg - is surely an HVA
11346         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11347             isa<StructType>(Arg.getType())) {
11348           // The first value of a structure is marked
11349           if (0 == Value)
11350             Flags.setHvaStart();
11351           Flags.setHva();
11352         }
11353         // Set InReg Flag
11354         Flags.setInReg();
11355       }
11356       if (Arg.hasAttribute(Attribute::StructRet))
11357         Flags.setSRet();
11358       if (Arg.hasAttribute(Attribute::SwiftSelf))
11359         Flags.setSwiftSelf();
11360       if (Arg.hasAttribute(Attribute::SwiftAsync))
11361         Flags.setSwiftAsync();
11362       if (Arg.hasAttribute(Attribute::SwiftError))
11363         Flags.setSwiftError();
11364       if (Arg.hasAttribute(Attribute::ByVal))
11365         Flags.setByVal();
11366       if (Arg.hasAttribute(Attribute::ByRef))
11367         Flags.setByRef();
11368       if (Arg.hasAttribute(Attribute::InAlloca)) {
11369         Flags.setInAlloca();
11370         // Set the byval flag for CCAssignFn callbacks that don't know about
11371         // inalloca.  This way we can know how many bytes we should've allocated
11372         // and how many bytes a callee cleanup function will pop.  If we port
11373         // inalloca to more targets, we'll have to add custom inalloca handling
11374         // in the various CC lowering callbacks.
11375         Flags.setByVal();
11376       }
11377       if (Arg.hasAttribute(Attribute::Preallocated)) {
11378         Flags.setPreallocated();
11379         // Set the byval flag for CCAssignFn callbacks that don't know about
11380         // preallocated.  This way we can know how many bytes we should've
11381         // allocated and how many bytes a callee cleanup function will pop.  If
11382         // we port preallocated to more targets, we'll have to add custom
11383         // preallocated handling in the various CC lowering callbacks.
11384         Flags.setByVal();
11385       }
11386 
11387       // Certain targets (such as MIPS), may have a different ABI alignment
11388       // for a type depending on the context. Give the target a chance to
11389       // specify the alignment it wants.
11390       const Align OriginalAlignment(
11391           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11392       Flags.setOrigAlign(OriginalAlignment);
11393 
11394       Align MemAlign;
11395       Type *ArgMemTy = nullptr;
11396       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11397           Flags.isByRef()) {
11398         if (!ArgMemTy)
11399           ArgMemTy = Arg.getPointeeInMemoryValueType();
11400 
11401         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11402 
11403         // For in-memory arguments, size and alignment should be passed from FE.
11404         // BE will guess if this info is not there but there are cases it cannot
11405         // get right.
11406         if (auto ParamAlign = Arg.getParamStackAlign())
11407           MemAlign = *ParamAlign;
11408         else if ((ParamAlign = Arg.getParamAlign()))
11409           MemAlign = *ParamAlign;
11410         else
11411           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11412         if (Flags.isByRef())
11413           Flags.setByRefSize(MemSize);
11414         else
11415           Flags.setByValSize(MemSize);
11416       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11417         MemAlign = *ParamAlign;
11418       } else {
11419         MemAlign = OriginalAlignment;
11420       }
11421       Flags.setMemAlign(MemAlign);
11422 
11423       if (Arg.hasAttribute(Attribute::Nest))
11424         Flags.setNest();
11425       if (NeedsRegBlock)
11426         Flags.setInConsecutiveRegs();
11427       if (ArgCopyElisionCandidates.count(&Arg))
11428         Flags.setCopyElisionCandidate();
11429       if (Arg.hasAttribute(Attribute::Returned))
11430         Flags.setReturned();
11431 
11432       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11433           *CurDAG->getContext(), F.getCallingConv(), VT);
11434       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11435           *CurDAG->getContext(), F.getCallingConv(), VT);
11436       for (unsigned i = 0; i != NumRegs; ++i) {
11437         // For scalable vectors, use the minimum size; individual targets
11438         // are responsible for handling scalable vector arguments and
11439         // return values.
11440         ISD::InputArg MyFlags(
11441             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11442             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11443         if (NumRegs > 1 && i == 0)
11444           MyFlags.Flags.setSplit();
11445         // if it isn't first piece, alignment must be 1
11446         else if (i > 0) {
11447           MyFlags.Flags.setOrigAlign(Align(1));
11448           if (i == NumRegs - 1)
11449             MyFlags.Flags.setSplitEnd();
11450         }
11451         Ins.push_back(MyFlags);
11452       }
11453       if (NeedsRegBlock && Value == NumValues - 1)
11454         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11455       PartBase += VT.getStoreSize().getKnownMinValue();
11456     }
11457   }
11458 
11459   // Call the target to set up the argument values.
11460   SmallVector<SDValue, 8> InVals;
11461   SDValue NewRoot = TLI->LowerFormalArguments(
11462       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11463 
11464   // Verify that the target's LowerFormalArguments behaved as expected.
11465   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11466          "LowerFormalArguments didn't return a valid chain!");
11467   assert(InVals.size() == Ins.size() &&
11468          "LowerFormalArguments didn't emit the correct number of values!");
11469   LLVM_DEBUG({
11470     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11471       assert(InVals[i].getNode() &&
11472              "LowerFormalArguments emitted a null value!");
11473       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11474              "LowerFormalArguments emitted a value with the wrong type!");
11475     }
11476   });
11477 
11478   // Update the DAG with the new chain value resulting from argument lowering.
11479   DAG.setRoot(NewRoot);
11480 
11481   // Set up the argument values.
11482   unsigned i = 0;
11483   if (!FuncInfo->CanLowerReturn) {
11484     // Create a virtual register for the sret pointer, and put in a copy
11485     // from the sret argument into it.
11486     SmallVector<EVT, 1> ValueVTs;
11487     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11488                     PointerType::get(F.getContext(),
11489                                      DAG.getDataLayout().getAllocaAddrSpace()),
11490                     ValueVTs);
11491     MVT VT = ValueVTs[0].getSimpleVT();
11492     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11493     std::optional<ISD::NodeType> AssertOp;
11494     SDValue ArgValue =
11495         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11496                          F.getCallingConv(), AssertOp);
11497 
11498     MachineFunction& MF = SDB->DAG.getMachineFunction();
11499     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11500     Register SRetReg =
11501         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11502     FuncInfo->DemoteRegister = SRetReg;
11503     NewRoot =
11504         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11505     DAG.setRoot(NewRoot);
11506 
11507     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11508     ++i;
11509   }
11510 
11511   SmallVector<SDValue, 4> Chains;
11512   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11513   for (const Argument &Arg : F.args()) {
11514     SmallVector<SDValue, 4> ArgValues;
11515     SmallVector<EVT, 4> ValueVTs;
11516     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11517     unsigned NumValues = ValueVTs.size();
11518     if (NumValues == 0)
11519       continue;
11520 
11521     bool ArgHasUses = !Arg.use_empty();
11522 
11523     // Elide the copying store if the target loaded this argument from a
11524     // suitable fixed stack object.
11525     if (Ins[i].Flags.isCopyElisionCandidate()) {
11526       unsigned NumParts = 0;
11527       for (EVT VT : ValueVTs)
11528         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11529                                                        F.getCallingConv(), VT);
11530 
11531       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11532                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11533                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11534     }
11535 
11536     // If this argument is unused then remember its value. It is used to generate
11537     // debugging information.
11538     bool isSwiftErrorArg =
11539         TLI->supportSwiftError() &&
11540         Arg.hasAttribute(Attribute::SwiftError);
11541     if (!ArgHasUses && !isSwiftErrorArg) {
11542       SDB->setUnusedArgValue(&Arg, InVals[i]);
11543 
11544       // Also remember any frame index for use in FastISel.
11545       if (FrameIndexSDNode *FI =
11546           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11547         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11548     }
11549 
11550     for (unsigned Val = 0; Val != NumValues; ++Val) {
11551       EVT VT = ValueVTs[Val];
11552       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11553                                                       F.getCallingConv(), VT);
11554       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11555           *CurDAG->getContext(), F.getCallingConv(), VT);
11556 
11557       // Even an apparent 'unused' swifterror argument needs to be returned. So
11558       // we do generate a copy for it that can be used on return from the
11559       // function.
11560       if (ArgHasUses || isSwiftErrorArg) {
11561         std::optional<ISD::NodeType> AssertOp;
11562         if (Arg.hasAttribute(Attribute::SExt))
11563           AssertOp = ISD::AssertSext;
11564         else if (Arg.hasAttribute(Attribute::ZExt))
11565           AssertOp = ISD::AssertZext;
11566 
11567         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11568                                              PartVT, VT, nullptr, NewRoot,
11569                                              F.getCallingConv(), AssertOp));
11570       }
11571 
11572       i += NumParts;
11573     }
11574 
11575     // We don't need to do anything else for unused arguments.
11576     if (ArgValues.empty())
11577       continue;
11578 
11579     // Note down frame index.
11580     if (FrameIndexSDNode *FI =
11581         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11582       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11583 
11584     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11585                                      SDB->getCurSDLoc());
11586 
11587     SDB->setValue(&Arg, Res);
11588     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11589       // We want to associate the argument with the frame index, among
11590       // involved operands, that correspond to the lowest address. The
11591       // getCopyFromParts function, called earlier, is swapping the order of
11592       // the operands to BUILD_PAIR depending on endianness. The result of
11593       // that swapping is that the least significant bits of the argument will
11594       // be in the first operand of the BUILD_PAIR node, and the most
11595       // significant bits will be in the second operand.
11596       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11597       if (LoadSDNode *LNode =
11598           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11599         if (FrameIndexSDNode *FI =
11600             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11601           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11602     }
11603 
11604     // Analyses past this point are naive and don't expect an assertion.
11605     if (Res.getOpcode() == ISD::AssertZext)
11606       Res = Res.getOperand(0);
11607 
11608     // Update the SwiftErrorVRegDefMap.
11609     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11610       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11611       if (Register::isVirtualRegister(Reg))
11612         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11613                                    Reg);
11614     }
11615 
11616     // If this argument is live outside of the entry block, insert a copy from
11617     // wherever we got it to the vreg that other BB's will reference it as.
11618     if (Res.getOpcode() == ISD::CopyFromReg) {
11619       // If we can, though, try to skip creating an unnecessary vreg.
11620       // FIXME: This isn't very clean... it would be nice to make this more
11621       // general.
11622       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11623       if (Register::isVirtualRegister(Reg)) {
11624         FuncInfo->ValueMap[&Arg] = Reg;
11625         continue;
11626       }
11627     }
11628     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11629       FuncInfo->InitializeRegForValue(&Arg);
11630       SDB->CopyToExportRegsIfNeeded(&Arg);
11631     }
11632   }
11633 
11634   if (!Chains.empty()) {
11635     Chains.push_back(NewRoot);
11636     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11637   }
11638 
11639   DAG.setRoot(NewRoot);
11640 
11641   assert(i == InVals.size() && "Argument register count mismatch!");
11642 
11643   // If any argument copy elisions occurred and we have debug info, update the
11644   // stale frame indices used in the dbg.declare variable info table.
11645   if (!ArgCopyElisionFrameIndexMap.empty()) {
11646     for (MachineFunction::VariableDbgInfo &VI :
11647          MF->getInStackSlotVariableDbgInfo()) {
11648       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11649       if (I != ArgCopyElisionFrameIndexMap.end())
11650         VI.updateStackSlot(I->second);
11651     }
11652   }
11653 
11654   // Finally, if the target has anything special to do, allow it to do so.
11655   emitFunctionEntryCode();
11656 }
11657 
11658 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11659 /// ensure constants are generated when needed.  Remember the virtual registers
11660 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11661 /// directly add them, because expansion might result in multiple MBB's for one
11662 /// BB.  As such, the start of the BB might correspond to a different MBB than
11663 /// the end.
11664 void
11665 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11666   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11667 
11668   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11669 
11670   // Check PHI nodes in successors that expect a value to be available from this
11671   // block.
11672   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11673     if (!isa<PHINode>(SuccBB->begin())) continue;
11674     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11675 
11676     // If this terminator has multiple identical successors (common for
11677     // switches), only handle each succ once.
11678     if (!SuccsHandled.insert(SuccMBB).second)
11679       continue;
11680 
11681     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11682 
11683     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11684     // nodes and Machine PHI nodes, but the incoming operands have not been
11685     // emitted yet.
11686     for (const PHINode &PN : SuccBB->phis()) {
11687       // Ignore dead phi's.
11688       if (PN.use_empty())
11689         continue;
11690 
11691       // Skip empty types
11692       if (PN.getType()->isEmptyTy())
11693         continue;
11694 
11695       unsigned Reg;
11696       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11697 
11698       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11699         unsigned &RegOut = ConstantsOut[C];
11700         if (RegOut == 0) {
11701           RegOut = FuncInfo.CreateRegs(C);
11702           // We need to zero/sign extend ConstantInt phi operands to match
11703           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11704           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11705           if (auto *CI = dyn_cast<ConstantInt>(C))
11706             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11707                                                     : ISD::ZERO_EXTEND;
11708           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11709         }
11710         Reg = RegOut;
11711       } else {
11712         DenseMap<const Value *, Register>::iterator I =
11713           FuncInfo.ValueMap.find(PHIOp);
11714         if (I != FuncInfo.ValueMap.end())
11715           Reg = I->second;
11716         else {
11717           assert(isa<AllocaInst>(PHIOp) &&
11718                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11719                  "Didn't codegen value into a register!??");
11720           Reg = FuncInfo.CreateRegs(PHIOp);
11721           CopyValueToVirtualRegister(PHIOp, Reg);
11722         }
11723       }
11724 
11725       // Remember that this register needs to added to the machine PHI node as
11726       // the input for this MBB.
11727       SmallVector<EVT, 4> ValueVTs;
11728       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11729       for (EVT VT : ValueVTs) {
11730         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11731         for (unsigned i = 0; i != NumRegisters; ++i)
11732           FuncInfo.PHINodesToUpdate.push_back(
11733               std::make_pair(&*MBBI++, Reg + i));
11734         Reg += NumRegisters;
11735       }
11736     }
11737   }
11738 
11739   ConstantsOut.clear();
11740 }
11741 
11742 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11743   MachineFunction::iterator I(MBB);
11744   if (++I == FuncInfo.MF->end())
11745     return nullptr;
11746   return &*I;
11747 }
11748 
11749 /// During lowering new call nodes can be created (such as memset, etc.).
11750 /// Those will become new roots of the current DAG, but complications arise
11751 /// when they are tail calls. In such cases, the call lowering will update
11752 /// the root, but the builder still needs to know that a tail call has been
11753 /// lowered in order to avoid generating an additional return.
11754 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11755   // If the node is null, we do have a tail call.
11756   if (MaybeTC.getNode() != nullptr)
11757     DAG.setRoot(MaybeTC);
11758   else
11759     HasTailCall = true;
11760 }
11761 
11762 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11763                                         MachineBasicBlock *SwitchMBB,
11764                                         MachineBasicBlock *DefaultMBB) {
11765   MachineFunction *CurMF = FuncInfo.MF;
11766   MachineBasicBlock *NextMBB = nullptr;
11767   MachineFunction::iterator BBI(W.MBB);
11768   if (++BBI != FuncInfo.MF->end())
11769     NextMBB = &*BBI;
11770 
11771   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11772 
11773   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11774 
11775   if (Size == 2 && W.MBB == SwitchMBB) {
11776     // If any two of the cases has the same destination, and if one value
11777     // is the same as the other, but has one bit unset that the other has set,
11778     // use bit manipulation to do two compares at once.  For example:
11779     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11780     // TODO: This could be extended to merge any 2 cases in switches with 3
11781     // cases.
11782     // TODO: Handle cases where W.CaseBB != SwitchBB.
11783     CaseCluster &Small = *W.FirstCluster;
11784     CaseCluster &Big = *W.LastCluster;
11785 
11786     if (Small.Low == Small.High && Big.Low == Big.High &&
11787         Small.MBB == Big.MBB) {
11788       const APInt &SmallValue = Small.Low->getValue();
11789       const APInt &BigValue = Big.Low->getValue();
11790 
11791       // Check that there is only one bit different.
11792       APInt CommonBit = BigValue ^ SmallValue;
11793       if (CommonBit.isPowerOf2()) {
11794         SDValue CondLHS = getValue(Cond);
11795         EVT VT = CondLHS.getValueType();
11796         SDLoc DL = getCurSDLoc();
11797 
11798         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11799                                  DAG.getConstant(CommonBit, DL, VT));
11800         SDValue Cond = DAG.getSetCC(
11801             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11802             ISD::SETEQ);
11803 
11804         // Update successor info.
11805         // Both Small and Big will jump to Small.BB, so we sum up the
11806         // probabilities.
11807         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11808         if (BPI)
11809           addSuccessorWithProb(
11810               SwitchMBB, DefaultMBB,
11811               // The default destination is the first successor in IR.
11812               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11813         else
11814           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11815 
11816         // Insert the true branch.
11817         SDValue BrCond =
11818             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11819                         DAG.getBasicBlock(Small.MBB));
11820         // Insert the false branch.
11821         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11822                              DAG.getBasicBlock(DefaultMBB));
11823 
11824         DAG.setRoot(BrCond);
11825         return;
11826       }
11827     }
11828   }
11829 
11830   if (TM.getOptLevel() != CodeGenOptLevel::None) {
11831     // Here, we order cases by probability so the most likely case will be
11832     // checked first. However, two clusters can have the same probability in
11833     // which case their relative ordering is non-deterministic. So we use Low
11834     // as a tie-breaker as clusters are guaranteed to never overlap.
11835     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11836                [](const CaseCluster &a, const CaseCluster &b) {
11837       return a.Prob != b.Prob ?
11838              a.Prob > b.Prob :
11839              a.Low->getValue().slt(b.Low->getValue());
11840     });
11841 
11842     // Rearrange the case blocks so that the last one falls through if possible
11843     // without changing the order of probabilities.
11844     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11845       --I;
11846       if (I->Prob > W.LastCluster->Prob)
11847         break;
11848       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11849         std::swap(*I, *W.LastCluster);
11850         break;
11851       }
11852     }
11853   }
11854 
11855   // Compute total probability.
11856   BranchProbability DefaultProb = W.DefaultProb;
11857   BranchProbability UnhandledProbs = DefaultProb;
11858   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11859     UnhandledProbs += I->Prob;
11860 
11861   MachineBasicBlock *CurMBB = W.MBB;
11862   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11863     bool FallthroughUnreachable = false;
11864     MachineBasicBlock *Fallthrough;
11865     if (I == W.LastCluster) {
11866       // For the last cluster, fall through to the default destination.
11867       Fallthrough = DefaultMBB;
11868       FallthroughUnreachable = isa<UnreachableInst>(
11869           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11870     } else {
11871       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11872       CurMF->insert(BBI, Fallthrough);
11873       // Put Cond in a virtual register to make it available from the new blocks.
11874       ExportFromCurrentBlock(Cond);
11875     }
11876     UnhandledProbs -= I->Prob;
11877 
11878     switch (I->Kind) {
11879       case CC_JumpTable: {
11880         // FIXME: Optimize away range check based on pivot comparisons.
11881         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11882         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11883 
11884         // The jump block hasn't been inserted yet; insert it here.
11885         MachineBasicBlock *JumpMBB = JT->MBB;
11886         CurMF->insert(BBI, JumpMBB);
11887 
11888         auto JumpProb = I->Prob;
11889         auto FallthroughProb = UnhandledProbs;
11890 
11891         // If the default statement is a target of the jump table, we evenly
11892         // distribute the default probability to successors of CurMBB. Also
11893         // update the probability on the edge from JumpMBB to Fallthrough.
11894         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11895                                               SE = JumpMBB->succ_end();
11896              SI != SE; ++SI) {
11897           if (*SI == DefaultMBB) {
11898             JumpProb += DefaultProb / 2;
11899             FallthroughProb -= DefaultProb / 2;
11900             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11901             JumpMBB->normalizeSuccProbs();
11902             break;
11903           }
11904         }
11905 
11906         // If the default clause is unreachable, propagate that knowledge into
11907         // JTH->FallthroughUnreachable which will use it to suppress the range
11908         // check.
11909         //
11910         // However, don't do this if we're doing branch target enforcement,
11911         // because a table branch _without_ a range check can be a tempting JOP
11912         // gadget - out-of-bounds inputs that are impossible in correct
11913         // execution become possible again if an attacker can influence the
11914         // control flow. So if an attacker doesn't already have a BTI bypass
11915         // available, we don't want them to be able to get one out of this
11916         // table branch.
11917         if (FallthroughUnreachable) {
11918           Function &CurFunc = CurMF->getFunction();
11919           bool HasBranchTargetEnforcement = false;
11920           if (CurFunc.hasFnAttribute("branch-target-enforcement")) {
11921             HasBranchTargetEnforcement =
11922                 CurFunc.getFnAttribute("branch-target-enforcement")
11923                     .getValueAsBool();
11924           } else {
11925             HasBranchTargetEnforcement =
11926                 CurMF->getMMI().getModule()->getModuleFlag(
11927                     "branch-target-enforcement");
11928           }
11929           if (!HasBranchTargetEnforcement)
11930             JTH->FallthroughUnreachable = true;
11931         }
11932 
11933         if (!JTH->FallthroughUnreachable)
11934           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11935         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11936         CurMBB->normalizeSuccProbs();
11937 
11938         // The jump table header will be inserted in our current block, do the
11939         // range check, and fall through to our fallthrough block.
11940         JTH->HeaderBB = CurMBB;
11941         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11942 
11943         // If we're in the right place, emit the jump table header right now.
11944         if (CurMBB == SwitchMBB) {
11945           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11946           JTH->Emitted = true;
11947         }
11948         break;
11949       }
11950       case CC_BitTests: {
11951         // FIXME: Optimize away range check based on pivot comparisons.
11952         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11953 
11954         // The bit test blocks haven't been inserted yet; insert them here.
11955         for (BitTestCase &BTC : BTB->Cases)
11956           CurMF->insert(BBI, BTC.ThisBB);
11957 
11958         // Fill in fields of the BitTestBlock.
11959         BTB->Parent = CurMBB;
11960         BTB->Default = Fallthrough;
11961 
11962         BTB->DefaultProb = UnhandledProbs;
11963         // If the cases in bit test don't form a contiguous range, we evenly
11964         // distribute the probability on the edge to Fallthrough to two
11965         // successors of CurMBB.
11966         if (!BTB->ContiguousRange) {
11967           BTB->Prob += DefaultProb / 2;
11968           BTB->DefaultProb -= DefaultProb / 2;
11969         }
11970 
11971         if (FallthroughUnreachable)
11972           BTB->FallthroughUnreachable = true;
11973 
11974         // If we're in the right place, emit the bit test header right now.
11975         if (CurMBB == SwitchMBB) {
11976           visitBitTestHeader(*BTB, SwitchMBB);
11977           BTB->Emitted = true;
11978         }
11979         break;
11980       }
11981       case CC_Range: {
11982         const Value *RHS, *LHS, *MHS;
11983         ISD::CondCode CC;
11984         if (I->Low == I->High) {
11985           // Check Cond == I->Low.
11986           CC = ISD::SETEQ;
11987           LHS = Cond;
11988           RHS=I->Low;
11989           MHS = nullptr;
11990         } else {
11991           // Check I->Low <= Cond <= I->High.
11992           CC = ISD::SETLE;
11993           LHS = I->Low;
11994           MHS = Cond;
11995           RHS = I->High;
11996         }
11997 
11998         // If Fallthrough is unreachable, fold away the comparison.
11999         if (FallthroughUnreachable)
12000           CC = ISD::SETTRUE;
12001 
12002         // The false probability is the sum of all unhandled cases.
12003         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12004                      getCurSDLoc(), I->Prob, UnhandledProbs);
12005 
12006         if (CurMBB == SwitchMBB)
12007           visitSwitchCase(CB, SwitchMBB);
12008         else
12009           SL->SwitchCases.push_back(CB);
12010 
12011         break;
12012       }
12013     }
12014     CurMBB = Fallthrough;
12015   }
12016 }
12017 
12018 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12019                                         const SwitchWorkListItem &W,
12020                                         Value *Cond,
12021                                         MachineBasicBlock *SwitchMBB) {
12022   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12023          "Clusters not sorted?");
12024   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12025 
12026   auto [LastLeft, FirstRight, LeftProb, RightProb] =
12027       SL->computeSplitWorkItemInfo(W);
12028 
12029   // Use the first element on the right as pivot since we will make less-than
12030   // comparisons against it.
12031   CaseClusterIt PivotCluster = FirstRight;
12032   assert(PivotCluster > W.FirstCluster);
12033   assert(PivotCluster <= W.LastCluster);
12034 
12035   CaseClusterIt FirstLeft = W.FirstCluster;
12036   CaseClusterIt LastRight = W.LastCluster;
12037 
12038   const ConstantInt *Pivot = PivotCluster->Low;
12039 
12040   // New blocks will be inserted immediately after the current one.
12041   MachineFunction::iterator BBI(W.MBB);
12042   ++BBI;
12043 
12044   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12045   // we can branch to its destination directly if it's squeezed exactly in
12046   // between the known lower bound and Pivot - 1.
12047   MachineBasicBlock *LeftMBB;
12048   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12049       FirstLeft->Low == W.GE &&
12050       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12051     LeftMBB = FirstLeft->MBB;
12052   } else {
12053     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12054     FuncInfo.MF->insert(BBI, LeftMBB);
12055     WorkList.push_back(
12056         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12057     // Put Cond in a virtual register to make it available from the new blocks.
12058     ExportFromCurrentBlock(Cond);
12059   }
12060 
12061   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12062   // single cluster, RHS.Low == Pivot, and we can branch to its destination
12063   // directly if RHS.High equals the current upper bound.
12064   MachineBasicBlock *RightMBB;
12065   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12066       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12067     RightMBB = FirstRight->MBB;
12068   } else {
12069     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12070     FuncInfo.MF->insert(BBI, RightMBB);
12071     WorkList.push_back(
12072         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12073     // Put Cond in a virtual register to make it available from the new blocks.
12074     ExportFromCurrentBlock(Cond);
12075   }
12076 
12077   // Create the CaseBlock record that will be used to lower the branch.
12078   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12079                getCurSDLoc(), LeftProb, RightProb);
12080 
12081   if (W.MBB == SwitchMBB)
12082     visitSwitchCase(CB, SwitchMBB);
12083   else
12084     SL->SwitchCases.push_back(CB);
12085 }
12086 
12087 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12088 // from the swith statement.
12089 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12090                                             BranchProbability PeeledCaseProb) {
12091   if (PeeledCaseProb == BranchProbability::getOne())
12092     return BranchProbability::getZero();
12093   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12094 
12095   uint32_t Numerator = CaseProb.getNumerator();
12096   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12097   return BranchProbability(Numerator, std::max(Numerator, Denominator));
12098 }
12099 
12100 // Try to peel the top probability case if it exceeds the threshold.
12101 // Return current MachineBasicBlock for the switch statement if the peeling
12102 // does not occur.
12103 // If the peeling is performed, return the newly created MachineBasicBlock
12104 // for the peeled switch statement. Also update Clusters to remove the peeled
12105 // case. PeeledCaseProb is the BranchProbability for the peeled case.
12106 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12107     const SwitchInst &SI, CaseClusterVector &Clusters,
12108     BranchProbability &PeeledCaseProb) {
12109   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12110   // Don't perform if there is only one cluster or optimizing for size.
12111   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12112       TM.getOptLevel() == CodeGenOptLevel::None ||
12113       SwitchMBB->getParent()->getFunction().hasMinSize())
12114     return SwitchMBB;
12115 
12116   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12117   unsigned PeeledCaseIndex = 0;
12118   bool SwitchPeeled = false;
12119   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12120     CaseCluster &CC = Clusters[Index];
12121     if (CC.Prob < TopCaseProb)
12122       continue;
12123     TopCaseProb = CC.Prob;
12124     PeeledCaseIndex = Index;
12125     SwitchPeeled = true;
12126   }
12127   if (!SwitchPeeled)
12128     return SwitchMBB;
12129 
12130   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12131                     << TopCaseProb << "\n");
12132 
12133   // Record the MBB for the peeled switch statement.
12134   MachineFunction::iterator BBI(SwitchMBB);
12135   ++BBI;
12136   MachineBasicBlock *PeeledSwitchMBB =
12137       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12138   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12139 
12140   ExportFromCurrentBlock(SI.getCondition());
12141   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12142   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12143                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12144   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12145 
12146   Clusters.erase(PeeledCaseIt);
12147   for (CaseCluster &CC : Clusters) {
12148     LLVM_DEBUG(
12149         dbgs() << "Scale the probablity for one cluster, before scaling: "
12150                << CC.Prob << "\n");
12151     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12152     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12153   }
12154   PeeledCaseProb = TopCaseProb;
12155   return PeeledSwitchMBB;
12156 }
12157 
12158 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12159   // Extract cases from the switch.
12160   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12161   CaseClusterVector Clusters;
12162   Clusters.reserve(SI.getNumCases());
12163   for (auto I : SI.cases()) {
12164     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
12165     const ConstantInt *CaseVal = I.getCaseValue();
12166     BranchProbability Prob =
12167         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12168             : BranchProbability(1, SI.getNumCases() + 1);
12169     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12170   }
12171 
12172   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
12173 
12174   // Cluster adjacent cases with the same destination. We do this at all
12175   // optimization levels because it's cheap to do and will make codegen faster
12176   // if there are many clusters.
12177   sortAndRangeify(Clusters);
12178 
12179   // The branch probablity of the peeled case.
12180   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12181   MachineBasicBlock *PeeledSwitchMBB =
12182       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12183 
12184   // If there is only the default destination, jump there directly.
12185   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12186   if (Clusters.empty()) {
12187     assert(PeeledSwitchMBB == SwitchMBB);
12188     SwitchMBB->addSuccessor(DefaultMBB);
12189     if (DefaultMBB != NextBlock(SwitchMBB)) {
12190       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12191                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12192     }
12193     return;
12194   }
12195 
12196   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12197                      DAG.getBFI());
12198   SL->findBitTestClusters(Clusters, &SI);
12199 
12200   LLVM_DEBUG({
12201     dbgs() << "Case clusters: ";
12202     for (const CaseCluster &C : Clusters) {
12203       if (C.Kind == CC_JumpTable)
12204         dbgs() << "JT:";
12205       if (C.Kind == CC_BitTests)
12206         dbgs() << "BT:";
12207 
12208       C.Low->getValue().print(dbgs(), true);
12209       if (C.Low != C.High) {
12210         dbgs() << '-';
12211         C.High->getValue().print(dbgs(), true);
12212       }
12213       dbgs() << ' ';
12214     }
12215     dbgs() << '\n';
12216   });
12217 
12218   assert(!Clusters.empty());
12219   SwitchWorkList WorkList;
12220   CaseClusterIt First = Clusters.begin();
12221   CaseClusterIt Last = Clusters.end() - 1;
12222   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12223   // Scale the branchprobability for DefaultMBB if the peel occurs and
12224   // DefaultMBB is not replaced.
12225   if (PeeledCaseProb != BranchProbability::getZero() &&
12226       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
12227     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12228   WorkList.push_back(
12229       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12230 
12231   while (!WorkList.empty()) {
12232     SwitchWorkListItem W = WorkList.pop_back_val();
12233     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12234 
12235     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12236         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12237       // For optimized builds, lower large range as a balanced binary tree.
12238       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12239       continue;
12240     }
12241 
12242     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12243   }
12244 }
12245 
12246 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12247   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12248   auto DL = getCurSDLoc();
12249   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12250   setValue(&I, DAG.getStepVector(DL, ResultVT));
12251 }
12252 
12253 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12254   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12255   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12256 
12257   SDLoc DL = getCurSDLoc();
12258   SDValue V = getValue(I.getOperand(0));
12259   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12260 
12261   if (VT.isScalableVector()) {
12262     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12263     return;
12264   }
12265 
12266   // Use VECTOR_SHUFFLE for the fixed-length vector
12267   // to maintain existing behavior.
12268   SmallVector<int, 8> Mask;
12269   unsigned NumElts = VT.getVectorMinNumElements();
12270   for (unsigned i = 0; i != NumElts; ++i)
12271     Mask.push_back(NumElts - 1 - i);
12272 
12273   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12274 }
12275 
12276 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12277   auto DL = getCurSDLoc();
12278   SDValue InVec = getValue(I.getOperand(0));
12279   EVT OutVT =
12280       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12281 
12282   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12283 
12284   // ISD Node needs the input vectors split into two equal parts
12285   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12286                            DAG.getVectorIdxConstant(0, DL));
12287   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12288                            DAG.getVectorIdxConstant(OutNumElts, DL));
12289 
12290   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12291   // legalisation and combines.
12292   if (OutVT.isFixedLengthVector()) {
12293     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12294                                         createStrideMask(0, 2, OutNumElts));
12295     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12296                                        createStrideMask(1, 2, OutNumElts));
12297     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12298     setValue(&I, Res);
12299     return;
12300   }
12301 
12302   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12303                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12304   setValue(&I, Res);
12305 }
12306 
12307 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12308   auto DL = getCurSDLoc();
12309   EVT InVT = getValue(I.getOperand(0)).getValueType();
12310   SDValue InVec0 = getValue(I.getOperand(0));
12311   SDValue InVec1 = getValue(I.getOperand(1));
12312   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12313   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12314 
12315   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12316   // legalisation and combines.
12317   if (OutVT.isFixedLengthVector()) {
12318     unsigned NumElts = InVT.getVectorMinNumElements();
12319     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12320     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12321                                       createInterleaveMask(NumElts, 2)));
12322     return;
12323   }
12324 
12325   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12326                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12327   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12328                     Res.getValue(1));
12329   setValue(&I, Res);
12330 }
12331 
12332 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12333   SmallVector<EVT, 4> ValueVTs;
12334   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12335                   ValueVTs);
12336   unsigned NumValues = ValueVTs.size();
12337   if (NumValues == 0) return;
12338 
12339   SmallVector<SDValue, 4> Values(NumValues);
12340   SDValue Op = getValue(I.getOperand(0));
12341 
12342   for (unsigned i = 0; i != NumValues; ++i)
12343     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12344                             SDValue(Op.getNode(), Op.getResNo() + i));
12345 
12346   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12347                            DAG.getVTList(ValueVTs), Values));
12348 }
12349 
12350 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12351   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12352   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12353 
12354   SDLoc DL = getCurSDLoc();
12355   SDValue V1 = getValue(I.getOperand(0));
12356   SDValue V2 = getValue(I.getOperand(1));
12357   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12358 
12359   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12360   if (VT.isScalableVector()) {
12361     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12362                              DAG.getVectorIdxConstant(Imm, DL)));
12363     return;
12364   }
12365 
12366   unsigned NumElts = VT.getVectorNumElements();
12367 
12368   uint64_t Idx = (NumElts + Imm) % NumElts;
12369 
12370   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12371   SmallVector<int, 8> Mask;
12372   for (unsigned i = 0; i < NumElts; ++i)
12373     Mask.push_back(Idx + i);
12374   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12375 }
12376 
12377 // Consider the following MIR after SelectionDAG, which produces output in
12378 // phyregs in the first case or virtregs in the second case.
12379 //
12380 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12381 // %5:gr32 = COPY $ebx
12382 // %6:gr32 = COPY $edx
12383 // %1:gr32 = COPY %6:gr32
12384 // %0:gr32 = COPY %5:gr32
12385 //
12386 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12387 // %1:gr32 = COPY %6:gr32
12388 // %0:gr32 = COPY %5:gr32
12389 //
12390 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12391 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12392 //
12393 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12394 // to a single virtreg (such as %0). The remaining outputs monotonically
12395 // increase in virtreg number from there. If a callbr has no outputs, then it
12396 // should not have a corresponding callbr landingpad; in fact, the callbr
12397 // landingpad would not even be able to refer to such a callbr.
12398 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12399   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12400   // There is definitely at least one copy.
12401   assert(MI->getOpcode() == TargetOpcode::COPY &&
12402          "start of copy chain MUST be COPY");
12403   Reg = MI->getOperand(1).getReg();
12404   MI = MRI.def_begin(Reg)->getParent();
12405   // There may be an optional second copy.
12406   if (MI->getOpcode() == TargetOpcode::COPY) {
12407     assert(Reg.isVirtual() && "expected COPY of virtual register");
12408     Reg = MI->getOperand(1).getReg();
12409     assert(Reg.isPhysical() && "expected COPY of physical register");
12410     MI = MRI.def_begin(Reg)->getParent();
12411   }
12412   // The start of the chain must be an INLINEASM_BR.
12413   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12414          "end of copy chain MUST be INLINEASM_BR");
12415   return Reg;
12416 }
12417 
12418 // We must do this walk rather than the simpler
12419 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12420 // otherwise we will end up with copies of virtregs only valid along direct
12421 // edges.
12422 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12423   SmallVector<EVT, 8> ResultVTs;
12424   SmallVector<SDValue, 8> ResultValues;
12425   const auto *CBR =
12426       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12427 
12428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12429   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12430   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12431 
12432   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12433   SDValue Chain = DAG.getRoot();
12434 
12435   // Re-parse the asm constraints string.
12436   TargetLowering::AsmOperandInfoVector TargetConstraints =
12437       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12438   for (auto &T : TargetConstraints) {
12439     SDISelAsmOperandInfo OpInfo(T);
12440     if (OpInfo.Type != InlineAsm::isOutput)
12441       continue;
12442 
12443     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12444     // individual constraint.
12445     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12446 
12447     switch (OpInfo.ConstraintType) {
12448     case TargetLowering::C_Register:
12449     case TargetLowering::C_RegisterClass: {
12450       // Fill in OpInfo.AssignedRegs.Regs.
12451       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12452 
12453       // getRegistersForValue may produce 1 to many registers based on whether
12454       // the OpInfo.ConstraintVT is legal on the target or not.
12455       for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) {
12456         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12457         if (Register::isPhysicalRegister(OriginalDef))
12458           FuncInfo.MBB->addLiveIn(OriginalDef);
12459         // Update the assigned registers to use the original defs.
12460         OpInfo.AssignedRegs.Regs[i] = OriginalDef;
12461       }
12462 
12463       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12464           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12465       ResultValues.push_back(V);
12466       ResultVTs.push_back(OpInfo.ConstraintVT);
12467       break;
12468     }
12469     case TargetLowering::C_Other: {
12470       SDValue Flag;
12471       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12472                                                   OpInfo, DAG);
12473       ++InitialDef;
12474       ResultValues.push_back(V);
12475       ResultVTs.push_back(OpInfo.ConstraintVT);
12476       break;
12477     }
12478     default:
12479       break;
12480     }
12481   }
12482   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12483                           DAG.getVTList(ResultVTs), ResultValues);
12484   setValue(&I, V);
12485 }
12486