xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 415efcecd8b80f68e76376ef2b854cb6f5c84b5a)
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/RuntimeLibcallUtil.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 <deque>
108 #include <iterator>
109 #include <limits>
110 #include <optional>
111 #include <tuple>
112 
113 using namespace llvm;
114 using namespace PatternMatch;
115 using namespace SwitchCG;
116 
117 #define DEBUG_TYPE "isel"
118 
119 /// LimitFloatPrecision - Generate low-precision inline sequences for
120 /// some float libcalls (6, 8 or 12 bits).
121 static unsigned LimitFloatPrecision;
122 
123 static cl::opt<bool>
124     InsertAssertAlign("insert-assert-align", cl::init(true),
125                       cl::desc("Insert the experimental `assertalign` node."),
126                       cl::ReallyHidden);
127 
128 static cl::opt<unsigned, true>
129     LimitFPPrecision("limit-float-precision",
130                      cl::desc("Generate low-precision inline sequences "
131                               "for some float libcalls"),
132                      cl::location(LimitFloatPrecision), cl::Hidden,
133                      cl::init(0));
134 
135 static cl::opt<unsigned> SwitchPeelThreshold(
136     "switch-peel-threshold", cl::Hidden, cl::init(66),
137     cl::desc("Set the case probability threshold for peeling the case from a "
138              "switch statement. A value greater than 100 will void this "
139              "optimization"));
140 
141 // Limit the width of DAG chains. This is important in general to prevent
142 // DAG-based analysis from blowing up. For example, alias analysis and
143 // load clustering may not complete in reasonable time. It is difficult to
144 // recognize and avoid this situation within each individual analysis, and
145 // future analyses are likely to have the same behavior. Limiting DAG width is
146 // the safe approach and will be especially important with global DAGs.
147 //
148 // MaxParallelChains default is arbitrarily high to avoid affecting
149 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
150 // sequence over this should have been converted to llvm.memcpy by the
151 // frontend. It is easy to induce this behavior with .ll code such as:
152 // %buffer = alloca [4096 x i8]
153 // %data = load [4096 x i8]* %argPtr
154 // store [4096 x i8] %data, [4096 x i8]* %buffer
155 static const unsigned MaxParallelChains = 64;
156 
157 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
158                                       const SDValue *Parts, unsigned NumParts,
159                                       MVT PartVT, EVT ValueVT, const Value *V,
160                                       SDValue InChain,
161                                       std::optional<CallingConv::ID> CC);
162 
163 /// getCopyFromParts - Create a value that contains the specified legal parts
164 /// combined into the value they represent.  If the parts combine to a type
165 /// larger than ValueVT then AssertOp can be used to specify whether the extra
166 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
167 /// (ISD::AssertSext).
168 static SDValue
getCopyFromParts(SelectionDAG & DAG,const SDLoc & DL,const SDValue * Parts,unsigned NumParts,MVT PartVT,EVT ValueVT,const Value * V,SDValue InChain,std::optional<CallingConv::ID> CC=std::nullopt,std::optional<ISD::NodeType> AssertOp=std::nullopt)169 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
170                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
171                  SDValue InChain,
172                  std::optional<CallingConv::ID> CC = std::nullopt,
173                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
174   // Let the target assemble the parts if it wants to
175   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
176   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
177                                                    PartVT, ValueVT, CC))
178     return Val;
179 
180   if (ValueVT.isVector())
181     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
182                                   InChain, CC);
183 
184   assert(NumParts > 0 && "No parts to assemble!");
185   SDValue Val = Parts[0];
186 
187   if (NumParts > 1) {
188     // Assemble the value from multiple parts.
189     if (ValueVT.isInteger()) {
190       unsigned PartBits = PartVT.getSizeInBits();
191       unsigned ValueBits = ValueVT.getSizeInBits();
192 
193       // Assemble the power of 2 part.
194       unsigned RoundParts = llvm::bit_floor(NumParts);
195       unsigned RoundBits = PartBits * RoundParts;
196       EVT RoundVT = RoundBits == ValueBits ?
197         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
198       SDValue Lo, Hi;
199 
200       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
201 
202       if (RoundParts > 2) {
203         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
204                               InChain);
205         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
206                               PartVT, HalfVT, V, InChain);
207       } else {
208         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
209         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
210       }
211 
212       if (DAG.getDataLayout().isBigEndian())
213         std::swap(Lo, Hi);
214 
215       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
216 
217       if (RoundParts < NumParts) {
218         // Assemble the trailing non-power-of-2 part.
219         unsigned OddParts = NumParts - RoundParts;
220         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
221         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
222                               OddVT, V, InChain, CC);
223 
224         // Combine the round and odd parts.
225         Lo = Val;
226         if (DAG.getDataLayout().isBigEndian())
227           std::swap(Lo, Hi);
228         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
229         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
230         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
231                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
232                                          TLI.getShiftAmountTy(
233                                              TotalVT, DAG.getDataLayout())));
234         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
235         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
236       }
237     } else if (PartVT.isFloatingPoint()) {
238       // FP split into multiple FP parts (for ppcf128)
239       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
240              "Unexpected split");
241       SDValue Lo, Hi;
242       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
243       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
244       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
245         std::swap(Lo, Hi);
246       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
247     } else {
248       // FP split into integer parts (soft fp)
249       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
250              !PartVT.isVector() && "Unexpected split");
251       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
252       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
253                              InChain, CC);
254     }
255   }
256 
257   // There is now one part, held in Val.  Correct it to match ValueVT.
258   // PartEVT is the type of the register class that holds the value.
259   // ValueVT is the type of the inline asm operation.
260   EVT PartEVT = Val.getValueType();
261 
262   if (PartEVT == ValueVT)
263     return Val;
264 
265   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
266       ValueVT.bitsLT(PartEVT)) {
267     // For an FP value in an integer part, we need to truncate to the right
268     // width first.
269     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
270     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
271   }
272 
273   // Handle types that have the same size.
274   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
275     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
276 
277   // Handle types with different sizes.
278   if (PartEVT.isInteger() && ValueVT.isInteger()) {
279     if (ValueVT.bitsLT(PartEVT)) {
280       // For a truncate, see if we have any information to
281       // indicate whether the truncated bits will always be
282       // zero or sign-extension.
283       if (AssertOp)
284         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
285                           DAG.getValueType(ValueVT));
286       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
287     }
288     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
289   }
290 
291   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
292     // FP_ROUND's are always exact here.
293     if (ValueVT.bitsLT(Val.getValueType())) {
294 
295       SDValue NoChange =
296           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
297 
298       if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
299               llvm::Attribute::StrictFP)) {
300         return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
301                            DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
302                            NoChange);
303       }
304 
305       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
306     }
307 
308     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
309   }
310 
311   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
312   // then truncating.
313   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
314       ValueVT.bitsLT(PartEVT)) {
315     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
316     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
317   }
318 
319   report_fatal_error("Unknown mismatch in getCopyFromParts!");
320 }
321 
diagnosePossiblyInvalidConstraint(LLVMContext & Ctx,const Value * V,const Twine & ErrMsg)322 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
323                                               const Twine &ErrMsg) {
324   const Instruction *I = dyn_cast_or_null<Instruction>(V);
325   if (!V)
326     return Ctx.emitError(ErrMsg);
327 
328   const char *AsmError = ", possible invalid constraint for vector type";
329   if (const CallInst *CI = dyn_cast<CallInst>(I))
330     if (CI->isInlineAsm())
331       return Ctx.emitError(I, ErrMsg + AsmError);
332 
333   return Ctx.emitError(I, ErrMsg);
334 }
335 
336 /// getCopyFromPartsVector - Create a value that contains the specified legal
337 /// parts combined into the value they represent.  If the parts combine to a
338 /// type larger than ValueVT then AssertOp can be used to specify whether the
339 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
340 /// ValueVT (ISD::AssertSext).
getCopyFromPartsVector(SelectionDAG & DAG,const SDLoc & DL,const SDValue * Parts,unsigned NumParts,MVT PartVT,EVT ValueVT,const Value * V,SDValue InChain,std::optional<CallingConv::ID> CallConv)341 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
342                                       const SDValue *Parts, unsigned NumParts,
343                                       MVT PartVT, EVT ValueVT, const Value *V,
344                                       SDValue InChain,
345                                       std::optional<CallingConv::ID> CallConv) {
346   assert(ValueVT.isVector() && "Not a vector value");
347   assert(NumParts > 0 && "No parts to assemble!");
348   const bool IsABIRegCopy = CallConv.has_value();
349 
350   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
351   SDValue Val = Parts[0];
352 
353   // Handle a multi-element vector.
354   if (NumParts > 1) {
355     EVT IntermediateVT;
356     MVT RegisterVT;
357     unsigned NumIntermediates;
358     unsigned NumRegs;
359 
360     if (IsABIRegCopy) {
361       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
362           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
363           NumIntermediates, RegisterVT);
364     } else {
365       NumRegs =
366           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
367                                      NumIntermediates, RegisterVT);
368     }
369 
370     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
371     NumParts = NumRegs; // Silence a compiler warning.
372     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
373     assert(RegisterVT.getSizeInBits() ==
374            Parts[0].getSimpleValueType().getSizeInBits() &&
375            "Part type sizes don't match!");
376 
377     // Assemble the parts into intermediate operands.
378     SmallVector<SDValue, 8> Ops(NumIntermediates);
379     if (NumIntermediates == NumParts) {
380       // If the register was not expanded, truncate or copy the value,
381       // as appropriate.
382       for (unsigned i = 0; i != NumParts; ++i)
383         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
384                                   V, InChain, CallConv);
385     } else if (NumParts > 0) {
386       // If the intermediate type was expanded, build the intermediate
387       // operands from the parts.
388       assert(NumParts % NumIntermediates == 0 &&
389              "Must expand into a divisible number of parts!");
390       unsigned Factor = NumParts / NumIntermediates;
391       for (unsigned i = 0; i != NumIntermediates; ++i)
392         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
393                                   IntermediateVT, V, InChain, CallConv);
394     }
395 
396     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
397     // intermediate operands.
398     EVT BuiltVectorTy =
399         IntermediateVT.isVector()
400             ? EVT::getVectorVT(
401                   *DAG.getContext(), IntermediateVT.getScalarType(),
402                   IntermediateVT.getVectorElementCount() * NumParts)
403             : EVT::getVectorVT(*DAG.getContext(),
404                                IntermediateVT.getScalarType(),
405                                NumIntermediates);
406     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
407                                                 : ISD::BUILD_VECTOR,
408                       DL, BuiltVectorTy, Ops);
409   }
410 
411   // There is now one part, held in Val.  Correct it to match ValueVT.
412   EVT PartEVT = Val.getValueType();
413 
414   if (PartEVT == ValueVT)
415     return Val;
416 
417   if (PartEVT.isVector()) {
418     // Vector/Vector bitcast.
419     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
420       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
421 
422     // If the parts vector has more elements than the value vector, then we
423     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
424     // Extract the elements we want.
425     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
426       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
427               ValueVT.getVectorElementCount().getKnownMinValue()) &&
428              (PartEVT.getVectorElementCount().isScalable() ==
429               ValueVT.getVectorElementCount().isScalable()) &&
430              "Cannot narrow, it would be a lossy transformation");
431       PartEVT =
432           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
433                            ValueVT.getVectorElementCount());
434       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
435                         DAG.getVectorIdxConstant(0, DL));
436       if (PartEVT == ValueVT)
437         return Val;
438       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
439         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
440 
441       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
442       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
443         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
444     }
445 
446     // Promoted vector extract
447     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
448   }
449 
450   // Trivial bitcast if the types are the same size and the destination
451   // vector type is legal.
452   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
453       TLI.isTypeLegal(ValueVT))
454     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
455 
456   if (ValueVT.getVectorNumElements() != 1) {
457      // Certain ABIs require that vectors are passed as integers. For vectors
458      // are the same size, this is an obvious bitcast.
459      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
460        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
461      } else if (ValueVT.bitsLT(PartEVT)) {
462        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
463        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
464        // Drop the extra bits.
465        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
466        return DAG.getBitcast(ValueVT, Val);
467      }
468 
469      diagnosePossiblyInvalidConstraint(
470          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
471      return DAG.getUNDEF(ValueVT);
472   }
473 
474   // Handle cases such as i8 -> <1 x i1>
475   EVT ValueSVT = ValueVT.getVectorElementType();
476   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
477     unsigned ValueSize = ValueSVT.getSizeInBits();
478     if (ValueSize == PartEVT.getSizeInBits()) {
479       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
480     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
481       // It's possible a scalar floating point type gets softened to integer and
482       // then promoted to a larger integer. If PartEVT is the larger integer
483       // we need to truncate it and then bitcast to the FP type.
484       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
485       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
486       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
487       Val = DAG.getBitcast(ValueSVT, Val);
488     } else {
489       Val = ValueVT.isFloatingPoint()
490                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
491                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
492     }
493   }
494 
495   return DAG.getBuildVector(ValueVT, DL, Val);
496 }
497 
498 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
499                                  SDValue Val, SDValue *Parts, unsigned NumParts,
500                                  MVT PartVT, const Value *V,
501                                  std::optional<CallingConv::ID> CallConv);
502 
503 /// getCopyToParts - Create a series of nodes that contain the specified value
504 /// split into legal parts.  If the parts contain more bits than Val, then, for
505 /// integers, ExtendKind can be used to specify how to generate the extra bits.
506 static void
getCopyToParts(SelectionDAG & DAG,const SDLoc & DL,SDValue Val,SDValue * Parts,unsigned NumParts,MVT PartVT,const Value * V,std::optional<CallingConv::ID> CallConv=std::nullopt,ISD::NodeType ExtendKind=ISD::ANY_EXTEND)507 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
508                unsigned NumParts, MVT PartVT, const Value *V,
509                std::optional<CallingConv::ID> CallConv = std::nullopt,
510                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
511   // Let the target split the parts if it wants to
512   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
513   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
514                                       CallConv))
515     return;
516   EVT ValueVT = Val.getValueType();
517 
518   // Handle the vector case separately.
519   if (ValueVT.isVector())
520     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
521                                 CallConv);
522 
523   unsigned OrigNumParts = NumParts;
524   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
525          "Copying to an illegal type!");
526 
527   if (NumParts == 0)
528     return;
529 
530   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
531   EVT PartEVT = PartVT;
532   if (PartEVT == ValueVT) {
533     assert(NumParts == 1 && "No-op copy with multiple parts!");
534     Parts[0] = Val;
535     return;
536   }
537 
538   unsigned PartBits = PartVT.getSizeInBits();
539   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
540     // If the parts cover more bits than the value has, promote the value.
541     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
542       assert(NumParts == 1 && "Do not know what to promote to!");
543       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
544     } else {
545       if (ValueVT.isFloatingPoint()) {
546         // FP values need to be bitcast, then extended if they are being put
547         // into a larger container.
548         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
549         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
550       }
551       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
552              ValueVT.isInteger() &&
553              "Unknown mismatch!");
554       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
555       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
556       if (PartVT == MVT::x86mmx)
557         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
558     }
559   } else if (PartBits == ValueVT.getSizeInBits()) {
560     // Different types of the same size.
561     assert(NumParts == 1 && PartEVT != ValueVT);
562     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
563   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
564     // If the parts cover less bits than value has, truncate the value.
565     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
566            ValueVT.isInteger() &&
567            "Unknown mismatch!");
568     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
569     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
570     if (PartVT == MVT::x86mmx)
571       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
572   }
573 
574   // The value may have changed - recompute ValueVT.
575   ValueVT = Val.getValueType();
576   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
577          "Failed to tile the value with PartVT!");
578 
579   if (NumParts == 1) {
580     if (PartEVT != ValueVT) {
581       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
582                                         "scalar-to-vector conversion failed");
583       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
584     }
585 
586     Parts[0] = Val;
587     return;
588   }
589 
590   // Expand the value into multiple parts.
591   if (NumParts & (NumParts - 1)) {
592     // The number of parts is not a power of 2.  Split off and copy the tail.
593     assert(PartVT.isInteger() && ValueVT.isInteger() &&
594            "Do not know what to expand to!");
595     unsigned RoundParts = llvm::bit_floor(NumParts);
596     unsigned RoundBits = RoundParts * PartBits;
597     unsigned OddParts = NumParts - RoundParts;
598     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
599       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
600 
601     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
602                    CallConv);
603 
604     if (DAG.getDataLayout().isBigEndian())
605       // The odd parts were reversed by getCopyToParts - unreverse them.
606       std::reverse(Parts + RoundParts, Parts + NumParts);
607 
608     NumParts = RoundParts;
609     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
610     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
611   }
612 
613   // The number of parts is a power of 2.  Repeatedly bisect the value using
614   // EXTRACT_ELEMENT.
615   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
616                          EVT::getIntegerVT(*DAG.getContext(),
617                                            ValueVT.getSizeInBits()),
618                          Val);
619 
620   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
621     for (unsigned i = 0; i < NumParts; i += StepSize) {
622       unsigned ThisBits = StepSize * PartBits / 2;
623       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
624       SDValue &Part0 = Parts[i];
625       SDValue &Part1 = Parts[i+StepSize/2];
626 
627       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
628                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
629       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
630                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
631 
632       if (ThisBits == PartBits && ThisVT != PartVT) {
633         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
634         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
635       }
636     }
637   }
638 
639   if (DAG.getDataLayout().isBigEndian())
640     std::reverse(Parts, Parts + OrigNumParts);
641 }
642 
widenVectorToPartType(SelectionDAG & DAG,SDValue Val,const SDLoc & DL,EVT PartVT)643 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
644                                      const SDLoc &DL, EVT PartVT) {
645   if (!PartVT.isVector())
646     return SDValue();
647 
648   EVT ValueVT = Val.getValueType();
649   EVT PartEVT = PartVT.getVectorElementType();
650   EVT ValueEVT = ValueVT.getVectorElementType();
651   ElementCount PartNumElts = PartVT.getVectorElementCount();
652   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
653 
654   // We only support widening vectors with equivalent element types and
655   // fixed/scalable properties. If a target needs to widen a fixed-length type
656   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
657   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
658       PartNumElts.isScalable() != ValueNumElts.isScalable())
659     return SDValue();
660 
661   // Have a try for bf16 because some targets share its ABI with fp16.
662   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
663     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
664            "Cannot widen to illegal type");
665     Val = DAG.getNode(ISD::BITCAST, DL,
666                       ValueVT.changeVectorElementType(MVT::f16), Val);
667   } else if (PartEVT != ValueEVT) {
668     return SDValue();
669   }
670 
671   // Widening a scalable vector to another scalable vector is done by inserting
672   // the vector into a larger undef one.
673   if (PartNumElts.isScalable())
674     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
675                        Val, DAG.getVectorIdxConstant(0, DL));
676 
677   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
678   // undef elements.
679   SmallVector<SDValue, 16> Ops;
680   DAG.ExtractVectorElements(Val, Ops);
681   SDValue EltUndef = DAG.getUNDEF(PartEVT);
682   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
683 
684   // FIXME: Use CONCAT for 2x -> 4x.
685   return DAG.getBuildVector(PartVT, DL, Ops);
686 }
687 
688 /// getCopyToPartsVector - Create a series of nodes that contain the specified
689 /// value split into legal parts.
getCopyToPartsVector(SelectionDAG & DAG,const SDLoc & DL,SDValue Val,SDValue * Parts,unsigned NumParts,MVT PartVT,const Value * V,std::optional<CallingConv::ID> CallConv)690 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
691                                  SDValue Val, SDValue *Parts, unsigned NumParts,
692                                  MVT PartVT, const Value *V,
693                                  std::optional<CallingConv::ID> CallConv) {
694   EVT ValueVT = Val.getValueType();
695   assert(ValueVT.isVector() && "Not a vector");
696   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
697   const bool IsABIRegCopy = CallConv.has_value();
698 
699   if (NumParts == 1) {
700     EVT PartEVT = PartVT;
701     if (PartEVT == ValueVT) {
702       // Nothing to do.
703     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
704       // Bitconvert vector->vector case.
705       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
706     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
707       Val = Widened;
708     } else if (PartVT.isVector() &&
709                PartEVT.getVectorElementType().bitsGE(
710                    ValueVT.getVectorElementType()) &&
711                PartEVT.getVectorElementCount() ==
712                    ValueVT.getVectorElementCount()) {
713 
714       // Promoted vector extract
715       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
716     } else if (PartEVT.isVector() &&
717                PartEVT.getVectorElementType() !=
718                    ValueVT.getVectorElementType() &&
719                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
720                    TargetLowering::TypeWidenVector) {
721       // Combination of widening and promotion.
722       EVT WidenVT =
723           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
724                            PartVT.getVectorElementCount());
725       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
726       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
727     } else {
728       // Don't extract an integer from a float vector. This can happen if the
729       // FP type gets softened to integer and then promoted. The promotion
730       // prevents it from being picked up by the earlier bitcast case.
731       if (ValueVT.getVectorElementCount().isScalar() &&
732           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
733         // If we reach this condition and PartVT is FP, this means that
734         // ValueVT is also FP and both have a different size, otherwise we
735         // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
736         // would be invalid since that would mean the smaller FP type has to
737         // be extended to the larger one.
738         if (PartVT.isFloatingPoint()) {
739           Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
740           Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
741         } else
742           Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
743                             DAG.getVectorIdxConstant(0, DL));
744       } else {
745         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
746         assert(PartVT.getFixedSizeInBits() > ValueSize &&
747                "lossy conversion of vector to scalar type");
748         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
749         Val = DAG.getBitcast(IntermediateType, Val);
750         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
751       }
752     }
753 
754     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
755     Parts[0] = Val;
756     return;
757   }
758 
759   // Handle a multi-element vector.
760   EVT IntermediateVT;
761   MVT RegisterVT;
762   unsigned NumIntermediates;
763   unsigned NumRegs;
764   if (IsABIRegCopy) {
765     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
766         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
767         RegisterVT);
768   } else {
769     NumRegs =
770         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
771                                    NumIntermediates, RegisterVT);
772   }
773 
774   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
775   NumParts = NumRegs; // Silence a compiler warning.
776   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
777 
778   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
779          "Mixing scalable and fixed vectors when copying in parts");
780 
781   std::optional<ElementCount> DestEltCnt;
782 
783   if (IntermediateVT.isVector())
784     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
785   else
786     DestEltCnt = ElementCount::getFixed(NumIntermediates);
787 
788   EVT BuiltVectorTy = EVT::getVectorVT(
789       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
790 
791   if (ValueVT == BuiltVectorTy) {
792     // Nothing to do.
793   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
794     // Bitconvert vector->vector case.
795     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
796   } else {
797     if (BuiltVectorTy.getVectorElementType().bitsGT(
798             ValueVT.getVectorElementType())) {
799       // Integer promotion.
800       ValueVT = EVT::getVectorVT(*DAG.getContext(),
801                                  BuiltVectorTy.getVectorElementType(),
802                                  ValueVT.getVectorElementCount());
803       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
804     }
805 
806     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
807       Val = Widened;
808     }
809   }
810 
811   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
812 
813   // Split the vector into intermediate operands.
814   SmallVector<SDValue, 8> Ops(NumIntermediates);
815   for (unsigned i = 0; i != NumIntermediates; ++i) {
816     if (IntermediateVT.isVector()) {
817       // This does something sensible for scalable vectors - see the
818       // definition of EXTRACT_SUBVECTOR for further details.
819       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
820       Ops[i] =
821           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
822                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
823     } else {
824       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
825                            DAG.getVectorIdxConstant(i, DL));
826     }
827   }
828 
829   // Split the intermediate operands into legal parts.
830   if (NumParts == NumIntermediates) {
831     // If the register was not expanded, promote or copy the value,
832     // as appropriate.
833     for (unsigned i = 0; i != NumParts; ++i)
834       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
835   } else if (NumParts > 0) {
836     // If the intermediate type was expanded, split each the value into
837     // legal parts.
838     assert(NumIntermediates != 0 && "division by zero");
839     assert(NumParts % NumIntermediates == 0 &&
840            "Must expand into a divisible number of parts!");
841     unsigned Factor = NumParts / NumIntermediates;
842     for (unsigned i = 0; i != NumIntermediates; ++i)
843       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
844                      CallConv);
845   }
846 }
847 
RegsForValue(const SmallVector<unsigned,4> & regs,MVT regvt,EVT valuevt,std::optional<CallingConv::ID> CC)848 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
849                            EVT valuevt, std::optional<CallingConv::ID> CC)
850     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
851       RegCount(1, regs.size()), CallConv(CC) {}
852 
RegsForValue(LLVMContext & Context,const TargetLowering & TLI,const DataLayout & DL,unsigned Reg,Type * Ty,std::optional<CallingConv::ID> CC)853 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
854                            const DataLayout &DL, unsigned Reg, Type *Ty,
855                            std::optional<CallingConv::ID> CC) {
856   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
857 
858   CallConv = CC;
859 
860   for (EVT ValueVT : ValueVTs) {
861     unsigned NumRegs =
862         isABIMangled()
863             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
864             : TLI.getNumRegisters(Context, ValueVT);
865     MVT RegisterVT =
866         isABIMangled()
867             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
868             : TLI.getRegisterType(Context, ValueVT);
869     for (unsigned i = 0; i != NumRegs; ++i)
870       Regs.push_back(Reg + i);
871     RegVTs.push_back(RegisterVT);
872     RegCount.push_back(NumRegs);
873     Reg += NumRegs;
874   }
875 }
876 
getCopyFromRegs(SelectionDAG & DAG,FunctionLoweringInfo & FuncInfo,const SDLoc & dl,SDValue & Chain,SDValue * Glue,const Value * V) const877 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
878                                       FunctionLoweringInfo &FuncInfo,
879                                       const SDLoc &dl, SDValue &Chain,
880                                       SDValue *Glue, const Value *V) const {
881   // A Value with type {} or [0 x %t] needs no registers.
882   if (ValueVTs.empty())
883     return SDValue();
884 
885   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
886 
887   // Assemble the legal parts into the final values.
888   SmallVector<SDValue, 4> Values(ValueVTs.size());
889   SmallVector<SDValue, 8> Parts;
890   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
891     // Copy the legal parts from the registers.
892     EVT ValueVT = ValueVTs[Value];
893     unsigned NumRegs = RegCount[Value];
894     MVT RegisterVT = isABIMangled()
895                          ? TLI.getRegisterTypeForCallingConv(
896                                *DAG.getContext(), *CallConv, RegVTs[Value])
897                          : RegVTs[Value];
898 
899     Parts.resize(NumRegs);
900     for (unsigned i = 0; i != NumRegs; ++i) {
901       SDValue P;
902       if (!Glue) {
903         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
904       } else {
905         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
906         *Glue = P.getValue(2);
907       }
908 
909       Chain = P.getValue(1);
910       Parts[i] = P;
911 
912       // If the source register was virtual and if we know something about it,
913       // add an assert node.
914       if (!Register::isVirtualRegister(Regs[Part + i]) ||
915           !RegisterVT.isInteger())
916         continue;
917 
918       const FunctionLoweringInfo::LiveOutInfo *LOI =
919         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
920       if (!LOI)
921         continue;
922 
923       unsigned RegSize = RegisterVT.getScalarSizeInBits();
924       unsigned NumSignBits = LOI->NumSignBits;
925       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
926 
927       if (NumZeroBits == RegSize) {
928         // The current value is a zero.
929         // Explicitly express that as it would be easier for
930         // optimizations to kick in.
931         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
932         continue;
933       }
934 
935       // FIXME: We capture more information than the dag can represent.  For
936       // now, just use the tightest assertzext/assertsext possible.
937       bool isSExt;
938       EVT FromVT(MVT::Other);
939       if (NumZeroBits) {
940         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
941         isSExt = false;
942       } else if (NumSignBits > 1) {
943         FromVT =
944             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
945         isSExt = true;
946       } else {
947         continue;
948       }
949       // Add an assertion node.
950       assert(FromVT != MVT::Other);
951       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
952                              RegisterVT, P, DAG.getValueType(FromVT));
953     }
954 
955     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
956                                      RegisterVT, ValueVT, V, Chain, CallConv);
957     Part += NumRegs;
958     Parts.clear();
959   }
960 
961   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
962 }
963 
getCopyToRegs(SDValue Val,SelectionDAG & DAG,const SDLoc & dl,SDValue & Chain,SDValue * Glue,const Value * V,ISD::NodeType PreferredExtendType) const964 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
965                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
966                                  const Value *V,
967                                  ISD::NodeType PreferredExtendType) const {
968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
969   ISD::NodeType ExtendKind = PreferredExtendType;
970 
971   // Get the list of the values's legal parts.
972   unsigned NumRegs = Regs.size();
973   SmallVector<SDValue, 8> Parts(NumRegs);
974   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
975     unsigned NumParts = RegCount[Value];
976 
977     MVT RegisterVT = isABIMangled()
978                          ? TLI.getRegisterTypeForCallingConv(
979                                *DAG.getContext(), *CallConv, RegVTs[Value])
980                          : RegVTs[Value];
981 
982     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
983       ExtendKind = ISD::ZERO_EXTEND;
984 
985     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
986                    NumParts, RegisterVT, V, CallConv, ExtendKind);
987     Part += NumParts;
988   }
989 
990   // Copy the parts into the registers.
991   SmallVector<SDValue, 8> Chains(NumRegs);
992   for (unsigned i = 0; i != NumRegs; ++i) {
993     SDValue Part;
994     if (!Glue) {
995       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
996     } else {
997       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
998       *Glue = Part.getValue(1);
999     }
1000 
1001     Chains[i] = Part.getValue(0);
1002   }
1003 
1004   if (NumRegs == 1 || Glue)
1005     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1006     // flagged to it. That is the CopyToReg nodes and the user are considered
1007     // a single scheduling unit. If we create a TokenFactor and return it as
1008     // chain, then the TokenFactor is both a predecessor (operand) of the
1009     // user as well as a successor (the TF operands are flagged to the user).
1010     // c1, f1 = CopyToReg
1011     // c2, f2 = CopyToReg
1012     // c3     = TokenFactor c1, c2
1013     // ...
1014     //        = op c3, ..., f2
1015     Chain = Chains[NumRegs-1];
1016   else
1017     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1018 }
1019 
AddInlineAsmOperands(InlineAsm::Kind Code,bool HasMatching,unsigned MatchingIdx,const SDLoc & dl,SelectionDAG & DAG,std::vector<SDValue> & Ops) const1020 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1021                                         unsigned MatchingIdx, const SDLoc &dl,
1022                                         SelectionDAG &DAG,
1023                                         std::vector<SDValue> &Ops) const {
1024   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1025 
1026   InlineAsm::Flag Flag(Code, Regs.size());
1027   if (HasMatching)
1028     Flag.setMatchingOp(MatchingIdx);
1029   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1030     // Put the register class of the virtual registers in the flag word.  That
1031     // way, later passes can recompute register class constraints for inline
1032     // assembly as well as normal instructions.
1033     // Don't do this for tied operands that can use the regclass information
1034     // from the def.
1035     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1036     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1037     Flag.setRegClass(RC->getID());
1038   }
1039 
1040   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1041   Ops.push_back(Res);
1042 
1043   if (Code == InlineAsm::Kind::Clobber) {
1044     // Clobbers should always have a 1:1 mapping with registers, and may
1045     // reference registers that have illegal (e.g. vector) types. Hence, we
1046     // shouldn't try to apply any sort of splitting logic to them.
1047     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1048            "No 1:1 mapping from clobbers to regs?");
1049     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1050     (void)SP;
1051     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1052       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1053       assert(
1054           (Regs[I] != SP ||
1055            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1056           "If we clobbered the stack pointer, MFI should know about it.");
1057     }
1058     return;
1059   }
1060 
1061   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1062     MVT RegisterVT = RegVTs[Value];
1063     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1064                                            RegisterVT);
1065     for (unsigned i = 0; i != NumRegs; ++i) {
1066       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1067       unsigned TheReg = Regs[Reg++];
1068       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1069     }
1070   }
1071 }
1072 
1073 SmallVector<std::pair<unsigned, TypeSize>, 4>
getRegsAndSizes() const1074 RegsForValue::getRegsAndSizes() const {
1075   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1076   unsigned I = 0;
1077   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1078     unsigned RegCount = std::get<0>(CountAndVT);
1079     MVT RegisterVT = std::get<1>(CountAndVT);
1080     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1081     for (unsigned E = I + RegCount; I != E; ++I)
1082       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1083   }
1084   return OutVec;
1085 }
1086 
init(GCFunctionInfo * gfi,AliasAnalysis * aa,AssumptionCache * ac,const TargetLibraryInfo * li)1087 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1088                                AssumptionCache *ac,
1089                                const TargetLibraryInfo *li) {
1090   AA = aa;
1091   AC = ac;
1092   GFI = gfi;
1093   LibInfo = li;
1094   Context = DAG.getContext();
1095   LPadToCallSiteMap.clear();
1096   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1097   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1098       *DAG.getMachineFunction().getFunction().getParent());
1099 }
1100 
clear()1101 void SelectionDAGBuilder::clear() {
1102   NodeMap.clear();
1103   UnusedArgNodeMap.clear();
1104   PendingLoads.clear();
1105   PendingExports.clear();
1106   PendingConstrainedFP.clear();
1107   PendingConstrainedFPStrict.clear();
1108   CurInst = nullptr;
1109   HasTailCall = false;
1110   SDNodeOrder = LowestSDNodeOrder;
1111   StatepointLowering.clear();
1112 }
1113 
clearDanglingDebugInfo()1114 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1115   DanglingDebugInfoMap.clear();
1116 }
1117 
1118 // Update DAG root to include dependencies on Pending chains.
updateRoot(SmallVectorImpl<SDValue> & Pending)1119 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1120   SDValue Root = DAG.getRoot();
1121 
1122   if (Pending.empty())
1123     return Root;
1124 
1125   // Add current root to PendingChains, unless we already indirectly
1126   // depend on it.
1127   if (Root.getOpcode() != ISD::EntryToken) {
1128     unsigned i = 0, e = Pending.size();
1129     for (; i != e; ++i) {
1130       assert(Pending[i].getNode()->getNumOperands() > 1);
1131       if (Pending[i].getNode()->getOperand(0) == Root)
1132         break;  // Don't add the root if we already indirectly depend on it.
1133     }
1134 
1135     if (i == e)
1136       Pending.push_back(Root);
1137   }
1138 
1139   if (Pending.size() == 1)
1140     Root = Pending[0];
1141   else
1142     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1143 
1144   DAG.setRoot(Root);
1145   Pending.clear();
1146   return Root;
1147 }
1148 
getMemoryRoot()1149 SDValue SelectionDAGBuilder::getMemoryRoot() {
1150   return updateRoot(PendingLoads);
1151 }
1152 
getRoot()1153 SDValue SelectionDAGBuilder::getRoot() {
1154   // Chain up all pending constrained intrinsics together with all
1155   // pending loads, by simply appending them to PendingLoads and
1156   // then calling getMemoryRoot().
1157   PendingLoads.reserve(PendingLoads.size() +
1158                        PendingConstrainedFP.size() +
1159                        PendingConstrainedFPStrict.size());
1160   PendingLoads.append(PendingConstrainedFP.begin(),
1161                       PendingConstrainedFP.end());
1162   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1163                       PendingConstrainedFPStrict.end());
1164   PendingConstrainedFP.clear();
1165   PendingConstrainedFPStrict.clear();
1166   return getMemoryRoot();
1167 }
1168 
getControlRoot()1169 SDValue SelectionDAGBuilder::getControlRoot() {
1170   // We need to emit pending fpexcept.strict constrained intrinsics,
1171   // so append them to the PendingExports list.
1172   PendingExports.append(PendingConstrainedFPStrict.begin(),
1173                         PendingConstrainedFPStrict.end());
1174   PendingConstrainedFPStrict.clear();
1175   return updateRoot(PendingExports);
1176 }
1177 
handleDebugDeclare(Value * Address,DILocalVariable * Variable,DIExpression * Expression,DebugLoc DL)1178 void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1179                                              DILocalVariable *Variable,
1180                                              DIExpression *Expression,
1181                                              DebugLoc DL) {
1182   assert(Variable && "Missing variable");
1183 
1184   // Check if address has undef value.
1185   if (!Address || isa<UndefValue>(Address) ||
1186       (Address->use_empty() && !isa<Argument>(Address))) {
1187     LLVM_DEBUG(
1188         dbgs()
1189         << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1190     return;
1191   }
1192 
1193   bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1194 
1195   SDValue &N = NodeMap[Address];
1196   if (!N.getNode() && isa<Argument>(Address))
1197     // Check unused arguments map.
1198     N = UnusedArgNodeMap[Address];
1199   SDDbgValue *SDV;
1200   if (N.getNode()) {
1201     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1202       Address = BCI->getOperand(0);
1203     // Parameters are handled specially.
1204     auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1205     if (IsParameter && FINode) {
1206       // Byval parameter. We have a frame index at this point.
1207       SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1208                                       /*IsIndirect*/ true, DL, SDNodeOrder);
1209     } else if (isa<Argument>(Address)) {
1210       // Address is an argument, so try to emit its dbg value using
1211       // virtual register info from the FuncInfo.ValueMap.
1212       EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1213                                FuncArgumentDbgValueKind::Declare, N);
1214       return;
1215     } else {
1216       SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1217                             true, DL, SDNodeOrder);
1218     }
1219     DAG.AddDbgValue(SDV, IsParameter);
1220   } else {
1221     // If Address is an argument then try to emit its dbg value using
1222     // virtual register info from the FuncInfo.ValueMap.
1223     if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1224                                   FuncArgumentDbgValueKind::Declare, N)) {
1225       LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1226                         << " (could not emit func-arg dbg_value)\n");
1227     }
1228   }
1229   return;
1230 }
1231 
visitDbgInfo(const Instruction & I)1232 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1233   // Add SDDbgValue nodes for any var locs here. Do so before updating
1234   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1235   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1236     // Add SDDbgValue nodes for any var locs here. Do so before updating
1237     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1238     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1239          It != End; ++It) {
1240       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1241       dropDanglingDebugInfo(Var, It->Expr);
1242       if (It->Values.isKillLocation(It->Expr)) {
1243         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1244         continue;
1245       }
1246       SmallVector<Value *> Values(It->Values.location_ops());
1247       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1248                             It->Values.hasArgList())) {
1249         SmallVector<Value *, 4> Vals;
1250         for (Value *V : It->Values.location_ops())
1251           Vals.push_back(V);
1252         addDanglingDebugInfo(Vals,
1253                              FnVarLocs->getDILocalVariable(It->VariableID),
1254                              It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1255       }
1256     }
1257   }
1258 
1259   // We must skip DbgVariableRecords if they've already been processed above as
1260   // we have just emitted the debug values resulting from assignment tracking
1261   // analysis, making any existing DbgVariableRecords redundant (and probably
1262   // less correct). We still need to process DbgLabelRecords. This does sink
1263   // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1264   // be important as it does so deterministcally and ordering between
1265   // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1266   // printing).
1267   bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1268   // Is there is any debug-info attached to this instruction, in the form of
1269   // DbgRecord non-instruction debug-info records.
1270   for (DbgRecord &DR : I.getDbgRecordRange()) {
1271     if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1272       assert(DLR->getLabel() && "Missing label");
1273       SDDbgLabel *SDV =
1274           DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1275       DAG.AddDbgLabel(SDV);
1276       continue;
1277     }
1278 
1279     if (SkipDbgVariableRecords)
1280       continue;
1281     DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
1282     DILocalVariable *Variable = DVR.getVariable();
1283     DIExpression *Expression = DVR.getExpression();
1284     dropDanglingDebugInfo(Variable, Expression);
1285 
1286     if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1287       if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1288         continue;
1289       LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1290                         << "\n");
1291       handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression,
1292                          DVR.getDebugLoc());
1293       continue;
1294     }
1295 
1296     // A DbgVariableRecord with no locations is a kill location.
1297     SmallVector<Value *, 4> Values(DVR.location_ops());
1298     if (Values.empty()) {
1299       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1300                            SDNodeOrder);
1301       continue;
1302     }
1303 
1304     // A DbgVariableRecord with an undef or absent location is also a kill
1305     // location.
1306     if (llvm::any_of(Values,
1307                      [](Value *V) { return !V || isa<UndefValue>(V); })) {
1308       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1309                            SDNodeOrder);
1310       continue;
1311     }
1312 
1313     bool IsVariadic = DVR.hasArgList();
1314     if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1315                           SDNodeOrder, IsVariadic)) {
1316       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1317                            DVR.getDebugLoc(), SDNodeOrder);
1318     }
1319   }
1320 }
1321 
visit(const Instruction & I)1322 void SelectionDAGBuilder::visit(const Instruction &I) {
1323   visitDbgInfo(I);
1324 
1325   // Set up outgoing PHI node register values before emitting the terminator.
1326   if (I.isTerminator()) {
1327     HandlePHINodesInSuccessorBlocks(I.getParent());
1328   }
1329 
1330   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1331   if (!isa<DbgInfoIntrinsic>(I))
1332     ++SDNodeOrder;
1333 
1334   CurInst = &I;
1335 
1336   // Set inserted listener only if required.
1337   bool NodeInserted = false;
1338   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1339   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1340   MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1341   if (PCSectionsMD || MMRA) {
1342     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1343         DAG, [&](SDNode *) { NodeInserted = true; });
1344   }
1345 
1346   visit(I.getOpcode(), I);
1347 
1348   if (!I.isTerminator() && !HasTailCall &&
1349       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1350     CopyToExportRegsIfNeeded(&I);
1351 
1352   // Handle metadata.
1353   if (PCSectionsMD || MMRA) {
1354     auto It = NodeMap.find(&I);
1355     if (It != NodeMap.end()) {
1356       if (PCSectionsMD)
1357         DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1358       if (MMRA)
1359         DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1360     } else if (NodeInserted) {
1361       // This should not happen; if it does, don't let it go unnoticed so we can
1362       // fix it. Relevant visit*() function is probably missing a setValue().
1363       errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1364              << I.getModule()->getName() << "]\n";
1365       LLVM_DEBUG(I.dump());
1366       assert(false);
1367     }
1368   }
1369 
1370   CurInst = nullptr;
1371 }
1372 
visitPHI(const PHINode &)1373 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1374   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1375 }
1376 
visit(unsigned Opcode,const User & I)1377 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1378   // Note: this doesn't use InstVisitor, because it has to work with
1379   // ConstantExpr's in addition to instructions.
1380   switch (Opcode) {
1381   default: llvm_unreachable("Unknown instruction type encountered!");
1382     // Build the switch statement using the Instruction.def file.
1383 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1384     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1385 #include "llvm/IR/Instruction.def"
1386   }
1387 }
1388 
handleDanglingVariadicDebugInfo(SelectionDAG & DAG,DILocalVariable * Variable,DebugLoc DL,unsigned Order,SmallVectorImpl<Value * > & Values,DIExpression * Expression)1389 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1390                                             DILocalVariable *Variable,
1391                                             DebugLoc DL, unsigned Order,
1392                                             SmallVectorImpl<Value *> &Values,
1393                                             DIExpression *Expression) {
1394   // For variadic dbg_values we will now insert an undef.
1395   // FIXME: We can potentially recover these!
1396   SmallVector<SDDbgOperand, 2> Locs;
1397   for (const Value *V : Values) {
1398     auto *Undef = UndefValue::get(V->getType());
1399     Locs.push_back(SDDbgOperand::fromConst(Undef));
1400   }
1401   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1402                                         /*IsIndirect=*/false, DL, Order,
1403                                         /*IsVariadic=*/true);
1404   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1405   return true;
1406 }
1407 
addDanglingDebugInfo(SmallVectorImpl<Value * > & Values,DILocalVariable * Var,DIExpression * Expr,bool IsVariadic,DebugLoc DL,unsigned Order)1408 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1409                                                DILocalVariable *Var,
1410                                                DIExpression *Expr,
1411                                                bool IsVariadic, DebugLoc DL,
1412                                                unsigned Order) {
1413   if (IsVariadic) {
1414     handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1415     return;
1416   }
1417   // TODO: Dangling debug info will eventually either be resolved or produce
1418   // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1419   // between the original dbg.value location and its resolved DBG_VALUE,
1420   // which we should ideally fill with an extra Undef DBG_VALUE.
1421   assert(Values.size() == 1);
1422   DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1423 }
1424 
dropDanglingDebugInfo(const DILocalVariable * Variable,const DIExpression * Expr)1425 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1426                                                 const DIExpression *Expr) {
1427   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1428     DIVariable *DanglingVariable = DDI.getVariable();
1429     DIExpression *DanglingExpr = DDI.getExpression();
1430     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1431       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1432                         << printDDI(nullptr, DDI) << "\n");
1433       return true;
1434     }
1435     return false;
1436   };
1437 
1438   for (auto &DDIMI : DanglingDebugInfoMap) {
1439     DanglingDebugInfoVector &DDIV = DDIMI.second;
1440 
1441     // If debug info is to be dropped, run it through final checks to see
1442     // whether it can be salvaged.
1443     for (auto &DDI : DDIV)
1444       if (isMatchingDbgValue(DDI))
1445         salvageUnresolvedDbgValue(DDIMI.first, DDI);
1446 
1447     erase_if(DDIV, isMatchingDbgValue);
1448   }
1449 }
1450 
1451 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1452 // generate the debug data structures now that we've seen its definition.
resolveDanglingDebugInfo(const Value * V,SDValue Val)1453 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1454                                                    SDValue Val) {
1455   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1456   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1457     return;
1458 
1459   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1460   for (auto &DDI : DDIV) {
1461     DebugLoc DL = DDI.getDebugLoc();
1462     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1463     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1464     DILocalVariable *Variable = DDI.getVariable();
1465     DIExpression *Expr = DDI.getExpression();
1466     assert(Variable->isValidLocationForIntrinsic(DL) &&
1467            "Expected inlined-at fields to agree");
1468     SDDbgValue *SDV;
1469     if (Val.getNode()) {
1470       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1471       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1472       // we couldn't resolve it directly when examining the DbgValue intrinsic
1473       // in the first place we should not be more successful here). Unless we
1474       // have some test case that prove this to be correct we should avoid
1475       // calling EmitFuncArgumentDbgValue here.
1476       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1477                                     FuncArgumentDbgValueKind::Value, Val)) {
1478         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1479                           << printDDI(V, DDI) << "\n");
1480         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1481         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1482         // inserted after the definition of Val when emitting the instructions
1483         // after ISel. An alternative could be to teach
1484         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1485         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1486                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1487                    << ValSDNodeOrder << "\n");
1488         SDV = getDbgValue(Val, Variable, Expr, DL,
1489                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1490         DAG.AddDbgValue(SDV, false);
1491       } else
1492         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1493                           << printDDI(V, DDI)
1494                           << " in EmitFuncArgumentDbgValue\n");
1495     } else {
1496       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1497                         << "\n");
1498       auto Undef = UndefValue::get(V->getType());
1499       auto SDV =
1500           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1501       DAG.AddDbgValue(SDV, false);
1502     }
1503   }
1504   DDIV.clear();
1505 }
1506 
salvageUnresolvedDbgValue(const Value * V,DanglingDebugInfo & DDI)1507 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1508                                                     DanglingDebugInfo &DDI) {
1509   // TODO: For the variadic implementation, instead of only checking the fail
1510   // state of `handleDebugValue`, we need know specifically which values were
1511   // invalid, so that we attempt to salvage only those values when processing
1512   // a DIArgList.
1513   const Value *OrigV = V;
1514   DILocalVariable *Var = DDI.getVariable();
1515   DIExpression *Expr = DDI.getExpression();
1516   DebugLoc DL = DDI.getDebugLoc();
1517   unsigned SDOrder = DDI.getSDNodeOrder();
1518 
1519   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1520   // that DW_OP_stack_value is desired.
1521   bool StackValue = true;
1522 
1523   // Can this Value can be encoded without any further work?
1524   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1525     return;
1526 
1527   // Attempt to salvage back through as many instructions as possible. Bail if
1528   // a non-instruction is seen, such as a constant expression or global
1529   // variable. FIXME: Further work could recover those too.
1530   while (isa<Instruction>(V)) {
1531     const Instruction &VAsInst = *cast<const Instruction>(V);
1532     // Temporary "0", awaiting real implementation.
1533     SmallVector<uint64_t, 16> Ops;
1534     SmallVector<Value *, 4> AdditionalValues;
1535     V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1536                              Expr->getNumLocationOperands(), Ops,
1537                              AdditionalValues);
1538     // If we cannot salvage any further, and haven't yet found a suitable debug
1539     // expression, bail out.
1540     if (!V)
1541       break;
1542 
1543     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1544     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1545     // here for variadic dbg_values, remove that condition.
1546     if (!AdditionalValues.empty())
1547       break;
1548 
1549     // New value and expr now represent this debuginfo.
1550     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1551 
1552     // Some kind of simplification occurred: check whether the operand of the
1553     // salvaged debug expression can be encoded in this DAG.
1554     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1555       LLVM_DEBUG(
1556           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1557                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1558       return;
1559     }
1560   }
1561 
1562   // This was the final opportunity to salvage this debug information, and it
1563   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1564   // any earlier variable location.
1565   assert(OrigV && "V shouldn't be null");
1566   auto *Undef = UndefValue::get(OrigV->getType());
1567   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1568   DAG.AddDbgValue(SDV, false);
1569   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  "
1570                     << printDDI(OrigV, DDI) << "\n");
1571 }
1572 
handleKillDebugValue(DILocalVariable * Var,DIExpression * Expr,DebugLoc DbgLoc,unsigned Order)1573 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1574                                                DIExpression *Expr,
1575                                                DebugLoc DbgLoc,
1576                                                unsigned Order) {
1577   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1578   DIExpression *NewExpr =
1579       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1580   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1581                    /*IsVariadic*/ false);
1582 }
1583 
handleDebugValue(ArrayRef<const Value * > Values,DILocalVariable * Var,DIExpression * Expr,DebugLoc DbgLoc,unsigned Order,bool IsVariadic)1584 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1585                                            DILocalVariable *Var,
1586                                            DIExpression *Expr, DebugLoc DbgLoc,
1587                                            unsigned Order, bool IsVariadic) {
1588   if (Values.empty())
1589     return true;
1590 
1591   // Filter EntryValue locations out early.
1592   if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1593     return true;
1594 
1595   SmallVector<SDDbgOperand> LocationOps;
1596   SmallVector<SDNode *> Dependencies;
1597   for (const Value *V : Values) {
1598     // Constant value.
1599     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1600         isa<ConstantPointerNull>(V)) {
1601       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1602       continue;
1603     }
1604 
1605     // Look through IntToPtr constants.
1606     if (auto *CE = dyn_cast<ConstantExpr>(V))
1607       if (CE->getOpcode() == Instruction::IntToPtr) {
1608         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1609         continue;
1610       }
1611 
1612     // If the Value is a frame index, we can create a FrameIndex debug value
1613     // without relying on the DAG at all.
1614     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1615       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1616       if (SI != FuncInfo.StaticAllocaMap.end()) {
1617         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1618         continue;
1619       }
1620     }
1621 
1622     // Do not use getValue() in here; we don't want to generate code at
1623     // this point if it hasn't been done yet.
1624     SDValue N = NodeMap[V];
1625     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1626       N = UnusedArgNodeMap[V];
1627     if (N.getNode()) {
1628       // Only emit func arg dbg value for non-variadic dbg.values for now.
1629       if (!IsVariadic &&
1630           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1631                                    FuncArgumentDbgValueKind::Value, N))
1632         return true;
1633       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1634         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1635         // describe stack slot locations.
1636         //
1637         // Consider "int x = 0; int *px = &x;". There are two kinds of
1638         // interesting debug values here after optimization:
1639         //
1640         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1641         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1642         //
1643         // Both describe the direct values of their associated variables.
1644         Dependencies.push_back(N.getNode());
1645         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1646         continue;
1647       }
1648       LocationOps.emplace_back(
1649           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1650       continue;
1651     }
1652 
1653     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1654     // Special rules apply for the first dbg.values of parameter variables in a
1655     // function. Identify them by the fact they reference Argument Values, that
1656     // they're parameters, and they are parameters of the current function. We
1657     // need to let them dangle until they get an SDNode.
1658     bool IsParamOfFunc =
1659         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1660     if (IsParamOfFunc)
1661       return false;
1662 
1663     // The value is not used in this block yet (or it would have an SDNode).
1664     // We still want the value to appear for the user if possible -- if it has
1665     // an associated VReg, we can refer to that instead.
1666     auto VMI = FuncInfo.ValueMap.find(V);
1667     if (VMI != FuncInfo.ValueMap.end()) {
1668       unsigned Reg = VMI->second;
1669       // If this is a PHI node, it may be split up into several MI PHI nodes
1670       // (in FunctionLoweringInfo::set).
1671       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1672                        V->getType(), std::nullopt);
1673       if (RFV.occupiesMultipleRegs()) {
1674         // FIXME: We could potentially support variadic dbg_values here.
1675         if (IsVariadic)
1676           return false;
1677         unsigned Offset = 0;
1678         unsigned BitsToDescribe = 0;
1679         if (auto VarSize = Var->getSizeInBits())
1680           BitsToDescribe = *VarSize;
1681         if (auto Fragment = Expr->getFragmentInfo())
1682           BitsToDescribe = Fragment->SizeInBits;
1683         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1684           // Bail out if all bits are described already.
1685           if (Offset >= BitsToDescribe)
1686             break;
1687           // TODO: handle scalable vectors.
1688           unsigned RegisterSize = RegAndSize.second;
1689           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1690                                       ? BitsToDescribe - Offset
1691                                       : RegisterSize;
1692           auto FragmentExpr = DIExpression::createFragmentExpression(
1693               Expr, Offset, FragmentSize);
1694           if (!FragmentExpr)
1695             continue;
1696           SDDbgValue *SDV = DAG.getVRegDbgValue(
1697               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1698           DAG.AddDbgValue(SDV, false);
1699           Offset += RegisterSize;
1700         }
1701         return true;
1702       }
1703       // We can use simple vreg locations for variadic dbg_values as well.
1704       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1705       continue;
1706     }
1707     // We failed to create a SDDbgOperand for V.
1708     return false;
1709   }
1710 
1711   // We have created a SDDbgOperand for each Value in Values.
1712   assert(!LocationOps.empty());
1713   SDDbgValue *SDV =
1714       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1715                           /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1716   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1717   return true;
1718 }
1719 
resolveOrClearDbgInfo()1720 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1721   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1722   for (auto &Pair : DanglingDebugInfoMap)
1723     for (auto &DDI : Pair.second)
1724       salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1725   clearDanglingDebugInfo();
1726 }
1727 
1728 /// getCopyFromRegs - If there was virtual register allocated for the value V
1729 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
getCopyFromRegs(const Value * V,Type * Ty)1730 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1731   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1732   SDValue Result;
1733 
1734   if (It != FuncInfo.ValueMap.end()) {
1735     Register InReg = It->second;
1736 
1737     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1738                      DAG.getDataLayout(), InReg, Ty,
1739                      std::nullopt); // This is not an ABI copy.
1740     SDValue Chain = DAG.getEntryNode();
1741     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1742                                  V);
1743     resolveDanglingDebugInfo(V, Result);
1744   }
1745 
1746   return Result;
1747 }
1748 
1749 /// getValue - Return an SDValue for the given Value.
getValue(const Value * V)1750 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1751   // If we already have an SDValue for this value, use it. It's important
1752   // to do this first, so that we don't create a CopyFromReg if we already
1753   // have a regular SDValue.
1754   SDValue &N = NodeMap[V];
1755   if (N.getNode()) return N;
1756 
1757   // If there's a virtual register allocated and initialized for this
1758   // value, use it.
1759   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1760     return copyFromReg;
1761 
1762   // Otherwise create a new SDValue and remember it.
1763   SDValue Val = getValueImpl(V);
1764   NodeMap[V] = Val;
1765   resolveDanglingDebugInfo(V, Val);
1766   return Val;
1767 }
1768 
1769 /// getNonRegisterValue - Return an SDValue for the given Value, but
1770 /// don't look in FuncInfo.ValueMap for a virtual register.
getNonRegisterValue(const Value * V)1771 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1772   // If we already have an SDValue for this value, use it.
1773   SDValue &N = NodeMap[V];
1774   if (N.getNode()) {
1775     if (isIntOrFPConstant(N)) {
1776       // Remove the debug location from the node as the node is about to be used
1777       // in a location which may differ from the original debug location.  This
1778       // is relevant to Constant and ConstantFP nodes because they can appear
1779       // as constant expressions inside PHI nodes.
1780       N->setDebugLoc(DebugLoc());
1781     }
1782     return N;
1783   }
1784 
1785   // Otherwise create a new SDValue and remember it.
1786   SDValue Val = getValueImpl(V);
1787   NodeMap[V] = Val;
1788   resolveDanglingDebugInfo(V, Val);
1789   return Val;
1790 }
1791 
1792 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1793 /// Create an SDValue for the given value.
getValueImpl(const Value * V)1794 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1796 
1797   if (const Constant *C = dyn_cast<Constant>(V)) {
1798     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1799 
1800     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1801       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1802 
1803     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1804       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1805 
1806     if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) {
1807       return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT,
1808                          getValue(CPA->getPointer()), getValue(CPA->getKey()),
1809                          getValue(CPA->getAddrDiscriminator()),
1810                          getValue(CPA->getDiscriminator()));
1811     }
1812 
1813     if (isa<ConstantPointerNull>(C)) {
1814       unsigned AS = V->getType()->getPointerAddressSpace();
1815       return DAG.getConstant(0, getCurSDLoc(),
1816                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1817     }
1818 
1819     if (match(C, m_VScale()))
1820       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1821 
1822     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1823       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1824 
1825     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1826       return DAG.getUNDEF(VT);
1827 
1828     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1829       visit(CE->getOpcode(), *CE);
1830       SDValue N1 = NodeMap[V];
1831       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1832       return N1;
1833     }
1834 
1835     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1836       SmallVector<SDValue, 4> Constants;
1837       for (const Use &U : C->operands()) {
1838         SDNode *Val = getValue(U).getNode();
1839         // If the operand is an empty aggregate, there are no values.
1840         if (!Val) continue;
1841         // Add each leaf value from the operand to the Constants list
1842         // to form a flattened list of all the values.
1843         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1844           Constants.push_back(SDValue(Val, i));
1845       }
1846 
1847       return DAG.getMergeValues(Constants, getCurSDLoc());
1848     }
1849 
1850     if (const ConstantDataSequential *CDS =
1851           dyn_cast<ConstantDataSequential>(C)) {
1852       SmallVector<SDValue, 4> Ops;
1853       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1854         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1855         // Add each leaf value from the operand to the Constants list
1856         // to form a flattened list of all the values.
1857         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1858           Ops.push_back(SDValue(Val, i));
1859       }
1860 
1861       if (isa<ArrayType>(CDS->getType()))
1862         return DAG.getMergeValues(Ops, getCurSDLoc());
1863       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1864     }
1865 
1866     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1867       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1868              "Unknown struct or array constant!");
1869 
1870       SmallVector<EVT, 4> ValueVTs;
1871       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1872       unsigned NumElts = ValueVTs.size();
1873       if (NumElts == 0)
1874         return SDValue(); // empty struct
1875       SmallVector<SDValue, 4> Constants(NumElts);
1876       for (unsigned i = 0; i != NumElts; ++i) {
1877         EVT EltVT = ValueVTs[i];
1878         if (isa<UndefValue>(C))
1879           Constants[i] = DAG.getUNDEF(EltVT);
1880         else if (EltVT.isFloatingPoint())
1881           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1882         else
1883           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1884       }
1885 
1886       return DAG.getMergeValues(Constants, getCurSDLoc());
1887     }
1888 
1889     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1890       return DAG.getBlockAddress(BA, VT);
1891 
1892     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1893       return getValue(Equiv->getGlobalValue());
1894 
1895     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1896       return getValue(NC->getGlobalValue());
1897 
1898     if (VT == MVT::aarch64svcount) {
1899       assert(C->isNullValue() && "Can only zero this target type!");
1900       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1901                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1902     }
1903 
1904     VectorType *VecTy = cast<VectorType>(V->getType());
1905 
1906     // Now that we know the number and type of the elements, get that number of
1907     // elements into the Ops array based on what kind of constant it is.
1908     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1909       SmallVector<SDValue, 16> Ops;
1910       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1911       for (unsigned i = 0; i != NumElements; ++i)
1912         Ops.push_back(getValue(CV->getOperand(i)));
1913 
1914       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1915     }
1916 
1917     if (isa<ConstantAggregateZero>(C)) {
1918       EVT EltVT =
1919           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1920 
1921       SDValue Op;
1922       if (EltVT.isFloatingPoint())
1923         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1924       else
1925         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1926 
1927       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1928     }
1929 
1930     llvm_unreachable("Unknown vector constant");
1931   }
1932 
1933   // If this is a static alloca, generate it as the frameindex instead of
1934   // computation.
1935   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1936     DenseMap<const AllocaInst*, int>::iterator SI =
1937       FuncInfo.StaticAllocaMap.find(AI);
1938     if (SI != FuncInfo.StaticAllocaMap.end())
1939       return DAG.getFrameIndex(
1940           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1941   }
1942 
1943   // If this is an instruction which fast-isel has deferred, select it now.
1944   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1945     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1946 
1947     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1948                      Inst->getType(), std::nullopt);
1949     SDValue Chain = DAG.getEntryNode();
1950     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1951   }
1952 
1953   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1954     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1955 
1956   if (const auto *BB = dyn_cast<BasicBlock>(V))
1957     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1958 
1959   llvm_unreachable("Can't get register for value!");
1960 }
1961 
visitCatchPad(const CatchPadInst & I)1962 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1963   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1964   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1965   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1966   bool IsSEH = isAsynchronousEHPersonality(Pers);
1967   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1968   if (!IsSEH)
1969     CatchPadMBB->setIsEHScopeEntry();
1970   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1971   if (IsMSVCCXX || IsCoreCLR)
1972     CatchPadMBB->setIsEHFuncletEntry();
1973 }
1974 
visitCatchRet(const CatchReturnInst & I)1975 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1976   // Update machine-CFG edge.
1977   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1978   FuncInfo.MBB->addSuccessor(TargetMBB);
1979   TargetMBB->setIsEHCatchretTarget(true);
1980   DAG.getMachineFunction().setHasEHCatchret(true);
1981 
1982   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1983   bool IsSEH = isAsynchronousEHPersonality(Pers);
1984   if (IsSEH) {
1985     // If this is not a fall-through branch or optimizations are switched off,
1986     // emit the branch.
1987     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1988         TM.getOptLevel() == CodeGenOptLevel::None)
1989       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1990                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1991     return;
1992   }
1993 
1994   // Figure out the funclet membership for the catchret's successor.
1995   // This will be used by the FuncletLayout pass to determine how to order the
1996   // BB's.
1997   // A 'catchret' returns to the outer scope's color.
1998   Value *ParentPad = I.getCatchSwitchParentPad();
1999   const BasicBlock *SuccessorColor;
2000   if (isa<ConstantTokenNone>(ParentPad))
2001     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2002   else
2003     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
2004   assert(SuccessorColor && "No parent funclet for catchret!");
2005   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
2006   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2007 
2008   // Create the terminator node.
2009   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2010                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
2011                             DAG.getBasicBlock(SuccessorColorMBB));
2012   DAG.setRoot(Ret);
2013 }
2014 
visitCleanupPad(const CleanupPadInst & CPI)2015 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2016   // Don't emit any special code for the cleanuppad instruction. It just marks
2017   // the start of an EH scope/funclet.
2018   FuncInfo.MBB->setIsEHScopeEntry();
2019   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2020   if (Pers != EHPersonality::Wasm_CXX) {
2021     FuncInfo.MBB->setIsEHFuncletEntry();
2022     FuncInfo.MBB->setIsCleanupFuncletEntry();
2023   }
2024 }
2025 
2026 // In wasm EH, even though a catchpad may not catch an exception if a tag does
2027 // not match, it is OK to add only the first unwind destination catchpad to the
2028 // successors, because there will be at least one invoke instruction within the
2029 // catch scope that points to the next unwind destination, if one exists, so
2030 // CFGSort cannot mess up with BB sorting order.
2031 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
2032 // call within them, and catchpads only consisting of 'catch (...)' have a
2033 // '__cxa_end_catch' call within them, both of which generate invokes in case
2034 // the next unwind destination exists, i.e., the next unwind destination is not
2035 // the caller.)
2036 //
2037 // Having at most one EH pad successor is also simpler and helps later
2038 // transformations.
2039 //
2040 // For example,
2041 // current:
2042 //   invoke void @foo to ... unwind label %catch.dispatch
2043 // catch.dispatch:
2044 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
2045 // catch.start:
2046 //   ...
2047 //   ... in this BB or some other child BB dominated by this BB there will be an
2048 //   invoke that points to 'next' BB as an unwind destination
2049 //
2050 // next: ; We don't need to add this to 'current' BB's successor
2051 //   ...
findWasmUnwindDestinations(FunctionLoweringInfo & FuncInfo,const BasicBlock * EHPadBB,BranchProbability Prob,SmallVectorImpl<std::pair<MachineBasicBlock *,BranchProbability>> & UnwindDests)2052 static void findWasmUnwindDestinations(
2053     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2054     BranchProbability Prob,
2055     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2056         &UnwindDests) {
2057   while (EHPadBB) {
2058     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2059     if (isa<CleanupPadInst>(Pad)) {
2060       // Stop on cleanup pads.
2061       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2062       UnwindDests.back().first->setIsEHScopeEntry();
2063       break;
2064     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2065       // Add the catchpad handlers to the possible destinations. We don't
2066       // continue to the unwind destination of the catchswitch for wasm.
2067       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2068         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2069         UnwindDests.back().first->setIsEHScopeEntry();
2070       }
2071       break;
2072     } else {
2073       continue;
2074     }
2075   }
2076 }
2077 
2078 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
2079 /// many places it could ultimately go. In the IR, we have a single unwind
2080 /// destination, but in the machine CFG, we enumerate all the possible blocks.
2081 /// This function skips over imaginary basic blocks that hold catchswitch
2082 /// instructions, and finds all the "real" machine
2083 /// basic block destinations. As those destinations may not be successors of
2084 /// EHPadBB, here we also calculate the edge probability to those destinations.
2085 /// The passed-in Prob is the edge probability to EHPadBB.
findUnwindDestinations(FunctionLoweringInfo & FuncInfo,const BasicBlock * EHPadBB,BranchProbability Prob,SmallVectorImpl<std::pair<MachineBasicBlock *,BranchProbability>> & UnwindDests)2086 static void findUnwindDestinations(
2087     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2088     BranchProbability Prob,
2089     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2090         &UnwindDests) {
2091   EHPersonality Personality =
2092     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2093   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2094   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2095   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2096   bool IsSEH = isAsynchronousEHPersonality(Personality);
2097 
2098   if (IsWasmCXX) {
2099     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
2100     assert(UnwindDests.size() <= 1 &&
2101            "There should be at most one unwind destination for wasm");
2102     return;
2103   }
2104 
2105   while (EHPadBB) {
2106     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2107     BasicBlock *NewEHPadBB = nullptr;
2108     if (isa<LandingPadInst>(Pad)) {
2109       // Stop on landingpads. They are not funclets.
2110       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2111       break;
2112     } else if (isa<CleanupPadInst>(Pad)) {
2113       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2114       // personalities.
2115       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2116       UnwindDests.back().first->setIsEHScopeEntry();
2117       UnwindDests.back().first->setIsEHFuncletEntry();
2118       break;
2119     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2120       // Add the catchpad handlers to the possible destinations.
2121       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2122         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2123         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2124         if (IsMSVCCXX || IsCoreCLR)
2125           UnwindDests.back().first->setIsEHFuncletEntry();
2126         if (!IsSEH)
2127           UnwindDests.back().first->setIsEHScopeEntry();
2128       }
2129       NewEHPadBB = CatchSwitch->getUnwindDest();
2130     } else {
2131       continue;
2132     }
2133 
2134     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2135     if (BPI && NewEHPadBB)
2136       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2137     EHPadBB = NewEHPadBB;
2138   }
2139 }
2140 
visitCleanupRet(const CleanupReturnInst & I)2141 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2142   // Update successor info.
2143   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2144   auto UnwindDest = I.getUnwindDest();
2145   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2146   BranchProbability UnwindDestProb =
2147       (BPI && UnwindDest)
2148           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2149           : BranchProbability::getZero();
2150   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2151   for (auto &UnwindDest : UnwindDests) {
2152     UnwindDest.first->setIsEHPad();
2153     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2154   }
2155   FuncInfo.MBB->normalizeSuccProbs();
2156 
2157   // Create the terminator node.
2158   MachineBasicBlock *CleanupPadMBB =
2159       FuncInfo.MBBMap[I.getCleanupPad()->getParent()];
2160   SDValue Ret = DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other,
2161                             getControlRoot(), DAG.getBasicBlock(CleanupPadMBB));
2162   DAG.setRoot(Ret);
2163 }
2164 
visitCatchSwitch(const CatchSwitchInst & CSI)2165 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2166   report_fatal_error("visitCatchSwitch not yet implemented!");
2167 }
2168 
visitRet(const ReturnInst & I)2169 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2171   auto &DL = DAG.getDataLayout();
2172   SDValue Chain = getControlRoot();
2173   SmallVector<ISD::OutputArg, 8> Outs;
2174   SmallVector<SDValue, 8> OutVals;
2175 
2176   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2177   // lower
2178   //
2179   //   %val = call <ty> @llvm.experimental.deoptimize()
2180   //   ret <ty> %val
2181   //
2182   // differently.
2183   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2184     LowerDeoptimizingReturn();
2185     return;
2186   }
2187 
2188   if (!FuncInfo.CanLowerReturn) {
2189     unsigned DemoteReg = FuncInfo.DemoteRegister;
2190     const Function *F = I.getParent()->getParent();
2191 
2192     // Emit a store of the return value through the virtual register.
2193     // Leave Outs empty so that LowerReturn won't try to load return
2194     // registers the usual way.
2195     SmallVector<EVT, 1> PtrValueVTs;
2196     ComputeValueVTs(TLI, DL,
2197                     PointerType::get(F->getContext(),
2198                                      DAG.getDataLayout().getAllocaAddrSpace()),
2199                     PtrValueVTs);
2200 
2201     SDValue RetPtr =
2202         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2203     SDValue RetOp = getValue(I.getOperand(0));
2204 
2205     SmallVector<EVT, 4> ValueVTs, MemVTs;
2206     SmallVector<uint64_t, 4> Offsets;
2207     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2208                     &Offsets, 0);
2209     unsigned NumValues = ValueVTs.size();
2210 
2211     SmallVector<SDValue, 4> Chains(NumValues);
2212     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2213     for (unsigned i = 0; i != NumValues; ++i) {
2214       // An aggregate return value cannot wrap around the address space, so
2215       // offsets to its parts don't wrap either.
2216       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2217                                            TypeSize::getFixed(Offsets[i]));
2218 
2219       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2220       if (MemVTs[i] != ValueVTs[i])
2221         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2222       Chains[i] = DAG.getStore(
2223           Chain, getCurSDLoc(), Val,
2224           // FIXME: better loc info would be nice.
2225           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2226           commonAlignment(BaseAlign, Offsets[i]));
2227     }
2228 
2229     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2230                         MVT::Other, Chains);
2231   } else if (I.getNumOperands() != 0) {
2232     SmallVector<EVT, 4> ValueVTs;
2233     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2234     unsigned NumValues = ValueVTs.size();
2235     if (NumValues) {
2236       SDValue RetOp = getValue(I.getOperand(0));
2237 
2238       const Function *F = I.getParent()->getParent();
2239 
2240       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2241           I.getOperand(0)->getType(), F->getCallingConv(),
2242           /*IsVarArg*/ false, DL);
2243 
2244       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2245       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2246         ExtendKind = ISD::SIGN_EXTEND;
2247       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2248         ExtendKind = ISD::ZERO_EXTEND;
2249 
2250       LLVMContext &Context = F->getContext();
2251       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2252 
2253       for (unsigned j = 0; j != NumValues; ++j) {
2254         EVT VT = ValueVTs[j];
2255 
2256         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2257           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2258 
2259         CallingConv::ID CC = F->getCallingConv();
2260 
2261         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2262         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2263         SmallVector<SDValue, 4> Parts(NumParts);
2264         getCopyToParts(DAG, getCurSDLoc(),
2265                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2266                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2267 
2268         // 'inreg' on function refers to return value
2269         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2270         if (RetInReg)
2271           Flags.setInReg();
2272 
2273         if (I.getOperand(0)->getType()->isPointerTy()) {
2274           Flags.setPointer();
2275           Flags.setPointerAddrSpace(
2276               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2277         }
2278 
2279         if (NeedsRegBlock) {
2280           Flags.setInConsecutiveRegs();
2281           if (j == NumValues - 1)
2282             Flags.setInConsecutiveRegsLast();
2283         }
2284 
2285         // Propagate extension type if any
2286         if (ExtendKind == ISD::SIGN_EXTEND)
2287           Flags.setSExt();
2288         else if (ExtendKind == ISD::ZERO_EXTEND)
2289           Flags.setZExt();
2290 
2291         for (unsigned i = 0; i < NumParts; ++i) {
2292           Outs.push_back(ISD::OutputArg(Flags,
2293                                         Parts[i].getValueType().getSimpleVT(),
2294                                         VT, /*isfixed=*/true, 0, 0));
2295           OutVals.push_back(Parts[i]);
2296         }
2297       }
2298     }
2299   }
2300 
2301   // Push in swifterror virtual register as the last element of Outs. This makes
2302   // sure swifterror virtual register will be returned in the swifterror
2303   // physical register.
2304   const Function *F = I.getParent()->getParent();
2305   if (TLI.supportSwiftError() &&
2306       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2307     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2308     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2309     Flags.setSwiftError();
2310     Outs.push_back(ISD::OutputArg(
2311         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2312         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2313     // Create SDNode for the swifterror virtual register.
2314     OutVals.push_back(
2315         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2316                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2317                         EVT(TLI.getPointerTy(DL))));
2318   }
2319 
2320   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2321   CallingConv::ID CallConv =
2322     DAG.getMachineFunction().getFunction().getCallingConv();
2323   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2324       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2325 
2326   // Verify that the target's LowerReturn behaved as expected.
2327   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2328          "LowerReturn didn't return a valid chain!");
2329 
2330   // Update the DAG with the new chain value resulting from return lowering.
2331   DAG.setRoot(Chain);
2332 }
2333 
2334 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2335 /// created for it, emit nodes to copy the value into the virtual
2336 /// registers.
CopyToExportRegsIfNeeded(const Value * V)2337 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2338   // Skip empty types
2339   if (V->getType()->isEmptyTy())
2340     return;
2341 
2342   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2343   if (VMI != FuncInfo.ValueMap.end()) {
2344     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2345            "Unused value assigned virtual registers!");
2346     CopyValueToVirtualRegister(V, VMI->second);
2347   }
2348 }
2349 
2350 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2351 /// the current basic block, add it to ValueMap now so that we'll get a
2352 /// CopyTo/FromReg.
ExportFromCurrentBlock(const Value * V)2353 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2354   // No need to export constants.
2355   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2356 
2357   // Already exported?
2358   if (FuncInfo.isExportedInst(V)) return;
2359 
2360   Register Reg = FuncInfo.InitializeRegForValue(V);
2361   CopyValueToVirtualRegister(V, Reg);
2362 }
2363 
isExportableFromCurrentBlock(const Value * V,const BasicBlock * FromBB)2364 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2365                                                      const BasicBlock *FromBB) {
2366   // The operands of the setcc have to be in this block.  We don't know
2367   // how to export them from some other block.
2368   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2369     // Can export from current BB.
2370     if (VI->getParent() == FromBB)
2371       return true;
2372 
2373     // Is already exported, noop.
2374     return FuncInfo.isExportedInst(V);
2375   }
2376 
2377   // If this is an argument, we can export it if the BB is the entry block or
2378   // if it is already exported.
2379   if (isa<Argument>(V)) {
2380     if (FromBB->isEntryBlock())
2381       return true;
2382 
2383     // Otherwise, can only export this if it is already exported.
2384     return FuncInfo.isExportedInst(V);
2385   }
2386 
2387   // Otherwise, constants can always be exported.
2388   return true;
2389 }
2390 
2391 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2392 BranchProbability
getEdgeProbability(const MachineBasicBlock * Src,const MachineBasicBlock * Dst) const2393 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2394                                         const MachineBasicBlock *Dst) const {
2395   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2396   const BasicBlock *SrcBB = Src->getBasicBlock();
2397   const BasicBlock *DstBB = Dst->getBasicBlock();
2398   if (!BPI) {
2399     // If BPI is not available, set the default probability as 1 / N, where N is
2400     // the number of successors.
2401     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2402     return BranchProbability(1, SuccSize);
2403   }
2404   return BPI->getEdgeProbability(SrcBB, DstBB);
2405 }
2406 
addSuccessorWithProb(MachineBasicBlock * Src,MachineBasicBlock * Dst,BranchProbability Prob)2407 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2408                                                MachineBasicBlock *Dst,
2409                                                BranchProbability Prob) {
2410   if (!FuncInfo.BPI)
2411     Src->addSuccessorWithoutProb(Dst);
2412   else {
2413     if (Prob.isUnknown())
2414       Prob = getEdgeProbability(Src, Dst);
2415     Src->addSuccessor(Dst, Prob);
2416   }
2417 }
2418 
InBlock(const Value * V,const BasicBlock * BB)2419 static bool InBlock(const Value *V, const BasicBlock *BB) {
2420   if (const Instruction *I = dyn_cast<Instruction>(V))
2421     return I->getParent() == BB;
2422   return true;
2423 }
2424 
2425 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2426 /// This function emits a branch and is used at the leaves of an OR or an
2427 /// AND operator tree.
2428 void
EmitBranchForMergedCondition(const Value * Cond,MachineBasicBlock * TBB,MachineBasicBlock * FBB,MachineBasicBlock * CurBB,MachineBasicBlock * SwitchBB,BranchProbability TProb,BranchProbability FProb,bool InvertCond)2429 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2430                                                   MachineBasicBlock *TBB,
2431                                                   MachineBasicBlock *FBB,
2432                                                   MachineBasicBlock *CurBB,
2433                                                   MachineBasicBlock *SwitchBB,
2434                                                   BranchProbability TProb,
2435                                                   BranchProbability FProb,
2436                                                   bool InvertCond) {
2437   const BasicBlock *BB = CurBB->getBasicBlock();
2438 
2439   // If the leaf of the tree is a comparison, merge the condition into
2440   // the caseblock.
2441   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2442     // The operands of the cmp have to be in this block.  We don't know
2443     // how to export them from some other block.  If this is the first block
2444     // of the sequence, no exporting is needed.
2445     if (CurBB == SwitchBB ||
2446         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2447          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2448       ISD::CondCode Condition;
2449       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2450         ICmpInst::Predicate Pred =
2451             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2452         Condition = getICmpCondCode(Pred);
2453       } else {
2454         const FCmpInst *FC = cast<FCmpInst>(Cond);
2455         FCmpInst::Predicate Pred =
2456             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2457         Condition = getFCmpCondCode(Pred);
2458         if (TM.Options.NoNaNsFPMath)
2459           Condition = getFCmpCodeWithoutNaN(Condition);
2460       }
2461 
2462       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2463                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2464       SL->SwitchCases.push_back(CB);
2465       return;
2466     }
2467   }
2468 
2469   // Create a CaseBlock record representing this branch.
2470   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2471   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2472                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2473   SL->SwitchCases.push_back(CB);
2474 }
2475 
2476 // Collect dependencies on V recursively. This is used for the cost analysis in
2477 // `shouldKeepJumpConditionsTogether`.
collectInstructionDeps(SmallMapVector<const Instruction *,bool,8> * Deps,const Value * V,SmallMapVector<const Instruction *,bool,8> * Necessary=nullptr,unsigned Depth=0)2478 static bool collectInstructionDeps(
2479     SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2480     SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2481     unsigned Depth = 0) {
2482   // Return false if we have an incomplete count.
2483   if (Depth >= SelectionDAG::MaxRecursionDepth)
2484     return false;
2485 
2486   auto *I = dyn_cast<Instruction>(V);
2487   if (I == nullptr)
2488     return true;
2489 
2490   if (Necessary != nullptr) {
2491     // This instruction is necessary for the other side of the condition so
2492     // don't count it.
2493     if (Necessary->contains(I))
2494       return true;
2495   }
2496 
2497   // Already added this dep.
2498   if (!Deps->try_emplace(I, false).second)
2499     return true;
2500 
2501   for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2502     if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2503                                 Depth + 1))
2504       return false;
2505   return true;
2506 }
2507 
shouldKeepJumpConditionsTogether(const FunctionLoweringInfo & FuncInfo,const BranchInst & I,Instruction::BinaryOps Opc,const Value * Lhs,const Value * Rhs,TargetLoweringBase::CondMergingParams Params) const2508 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2509     const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2510     Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2511     TargetLoweringBase::CondMergingParams Params) const {
2512   if (I.getNumSuccessors() != 2)
2513     return false;
2514 
2515   if (!I.isConditional())
2516     return false;
2517 
2518   if (Params.BaseCost < 0)
2519     return false;
2520 
2521   // Baseline cost.
2522   InstructionCost CostThresh = Params.BaseCost;
2523 
2524   BranchProbabilityInfo *BPI = nullptr;
2525   if (Params.LikelyBias || Params.UnlikelyBias)
2526     BPI = FuncInfo.BPI;
2527   if (BPI != nullptr) {
2528     // See if we are either likely to get an early out or compute both lhs/rhs
2529     // of the condition.
2530     BasicBlock *IfFalse = I.getSuccessor(0);
2531     BasicBlock *IfTrue = I.getSuccessor(1);
2532 
2533     std::optional<bool> Likely;
2534     if (BPI->isEdgeHot(I.getParent(), IfTrue))
2535       Likely = true;
2536     else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2537       Likely = false;
2538 
2539     if (Likely) {
2540       if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2541         // Its likely we will have to compute both lhs and rhs of condition
2542         CostThresh += Params.LikelyBias;
2543       else {
2544         if (Params.UnlikelyBias < 0)
2545           return false;
2546         // Its likely we will get an early out.
2547         CostThresh -= Params.UnlikelyBias;
2548       }
2549     }
2550   }
2551 
2552   if (CostThresh <= 0)
2553     return false;
2554 
2555   // Collect "all" instructions that lhs condition is dependent on.
2556   // Use map for stable iteration (to avoid non-determanism of iteration of
2557   // SmallPtrSet). The `bool` value is just a dummy.
2558   SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2559   collectInstructionDeps(&LhsDeps, Lhs);
2560   // Collect "all" instructions that rhs condition is dependent on AND are
2561   // dependencies of lhs. This gives us an estimate on which instructions we
2562   // stand to save by splitting the condition.
2563   if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2564     return false;
2565   // Add the compare instruction itself unless its a dependency on the LHS.
2566   if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2567     if (!LhsDeps.contains(RhsI))
2568       RhsDeps.try_emplace(RhsI, false);
2569 
2570   const auto &TLI = DAG.getTargetLoweringInfo();
2571   const auto &TTI =
2572       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
2573 
2574   InstructionCost CostOfIncluding = 0;
2575   // See if this instruction will need to computed independently of whether RHS
2576   // is.
2577   Value *BrCond = I.getCondition();
2578   auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2579     for (const auto *U : Ins->users()) {
2580       // If user is independent of RHS calculation we don't need to count it.
2581       if (auto *UIns = dyn_cast<Instruction>(U))
2582         if (UIns != BrCond && !RhsDeps.contains(UIns))
2583           return false;
2584     }
2585     return true;
2586   };
2587 
2588   // Prune instructions from RHS Deps that are dependencies of unrelated
2589   // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2590   // arbitrary and just meant to cap the how much time we spend in the pruning
2591   // loop. Its highly unlikely to come into affect.
2592   const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2593   // Stop after a certain point. No incorrectness from including too many
2594   // instructions.
2595   for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2596     const Instruction *ToDrop = nullptr;
2597     for (const auto &InsPair : RhsDeps) {
2598       if (!ShouldCountInsn(InsPair.first)) {
2599         ToDrop = InsPair.first;
2600         break;
2601       }
2602     }
2603     if (ToDrop == nullptr)
2604       break;
2605     RhsDeps.erase(ToDrop);
2606   }
2607 
2608   for (const auto &InsPair : RhsDeps) {
2609     // Finally accumulate latency that we can only attribute to computing the
2610     // RHS condition. Use latency because we are essentially trying to calculate
2611     // the cost of the dependency chain.
2612     // Possible TODO: We could try to estimate ILP and make this more precise.
2613     CostOfIncluding +=
2614         TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency);
2615 
2616     if (CostOfIncluding > CostThresh)
2617       return false;
2618   }
2619   return true;
2620 }
2621 
FindMergedConditions(const Value * Cond,MachineBasicBlock * TBB,MachineBasicBlock * FBB,MachineBasicBlock * CurBB,MachineBasicBlock * SwitchBB,Instruction::BinaryOps Opc,BranchProbability TProb,BranchProbability FProb,bool InvertCond)2622 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2623                                                MachineBasicBlock *TBB,
2624                                                MachineBasicBlock *FBB,
2625                                                MachineBasicBlock *CurBB,
2626                                                MachineBasicBlock *SwitchBB,
2627                                                Instruction::BinaryOps Opc,
2628                                                BranchProbability TProb,
2629                                                BranchProbability FProb,
2630                                                bool InvertCond) {
2631   // Skip over not part of the tree and remember to invert op and operands at
2632   // next level.
2633   Value *NotCond;
2634   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2635       InBlock(NotCond, CurBB->getBasicBlock())) {
2636     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2637                          !InvertCond);
2638     return;
2639   }
2640 
2641   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2642   const Value *BOpOp0, *BOpOp1;
2643   // Compute the effective opcode for Cond, taking into account whether it needs
2644   // to be inverted, e.g.
2645   //   and (not (or A, B)), C
2646   // gets lowered as
2647   //   and (and (not A, not B), C)
2648   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2649   if (BOp) {
2650     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2651                ? Instruction::And
2652                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2653                       ? Instruction::Or
2654                       : (Instruction::BinaryOps)0);
2655     if (InvertCond) {
2656       if (BOpc == Instruction::And)
2657         BOpc = Instruction::Or;
2658       else if (BOpc == Instruction::Or)
2659         BOpc = Instruction::And;
2660     }
2661   }
2662 
2663   // If this node is not part of the or/and tree, emit it as a branch.
2664   // Note that all nodes in the tree should have same opcode.
2665   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2666   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2667       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2668       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2669     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2670                                  TProb, FProb, InvertCond);
2671     return;
2672   }
2673 
2674   //  Create TmpBB after CurBB.
2675   MachineFunction::iterator BBI(CurBB);
2676   MachineFunction &MF = DAG.getMachineFunction();
2677   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2678   CurBB->getParent()->insert(++BBI, TmpBB);
2679 
2680   if (Opc == Instruction::Or) {
2681     // Codegen X | Y as:
2682     // BB1:
2683     //   jmp_if_X TBB
2684     //   jmp TmpBB
2685     // TmpBB:
2686     //   jmp_if_Y TBB
2687     //   jmp FBB
2688     //
2689 
2690     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2691     // The requirement is that
2692     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2693     //     = TrueProb for original BB.
2694     // Assuming the original probabilities are A and B, one choice is to set
2695     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2696     // A/(1+B) and 2B/(1+B). This choice assumes that
2697     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2698     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2699     // TmpBB, but the math is more complicated.
2700 
2701     auto NewTrueProb = TProb / 2;
2702     auto NewFalseProb = TProb / 2 + FProb;
2703     // Emit the LHS condition.
2704     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2705                          NewFalseProb, InvertCond);
2706 
2707     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2708     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2709     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2710     // Emit the RHS condition into TmpBB.
2711     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2712                          Probs[1], InvertCond);
2713   } else {
2714     assert(Opc == Instruction::And && "Unknown merge op!");
2715     // Codegen X & Y as:
2716     // BB1:
2717     //   jmp_if_X TmpBB
2718     //   jmp FBB
2719     // TmpBB:
2720     //   jmp_if_Y TBB
2721     //   jmp FBB
2722     //
2723     //  This requires creation of TmpBB after CurBB.
2724 
2725     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2726     // The requirement is that
2727     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2728     //     = FalseProb for original BB.
2729     // Assuming the original probabilities are A and B, one choice is to set
2730     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2731     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2732     // TrueProb for BB1 * FalseProb for TmpBB.
2733 
2734     auto NewTrueProb = TProb + FProb / 2;
2735     auto NewFalseProb = FProb / 2;
2736     // Emit the LHS condition.
2737     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2738                          NewFalseProb, InvertCond);
2739 
2740     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2741     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2742     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2743     // Emit the RHS condition into TmpBB.
2744     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2745                          Probs[1], InvertCond);
2746   }
2747 }
2748 
2749 /// If the set of cases should be emitted as a series of branches, return true.
2750 /// If we should emit this as a bunch of and/or'd together conditions, return
2751 /// false.
2752 bool
ShouldEmitAsBranches(const std::vector<CaseBlock> & Cases)2753 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2754   if (Cases.size() != 2) return true;
2755 
2756   // If this is two comparisons of the same values or'd or and'd together, they
2757   // will get folded into a single comparison, so don't emit two blocks.
2758   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2759        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2760       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2761        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2762     return false;
2763   }
2764 
2765   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2766   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2767   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2768       Cases[0].CC == Cases[1].CC &&
2769       isa<Constant>(Cases[0].CmpRHS) &&
2770       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2771     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2772       return false;
2773     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2774       return false;
2775   }
2776 
2777   return true;
2778 }
2779 
visitBr(const BranchInst & I)2780 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2781   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2782 
2783   // Update machine-CFG edges.
2784   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2785 
2786   if (I.isUnconditional()) {
2787     // Update machine-CFG edges.
2788     BrMBB->addSuccessor(Succ0MBB);
2789 
2790     // If this is not a fall-through branch or optimizations are switched off,
2791     // emit the branch.
2792     if (Succ0MBB != NextBlock(BrMBB) ||
2793         TM.getOptLevel() == CodeGenOptLevel::None) {
2794       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2795                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2796       setValue(&I, Br);
2797       DAG.setRoot(Br);
2798     }
2799 
2800     return;
2801   }
2802 
2803   // If this condition is one of the special cases we handle, do special stuff
2804   // now.
2805   const Value *CondVal = I.getCondition();
2806   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2807 
2808   // If this is a series of conditions that are or'd or and'd together, emit
2809   // this as a sequence of branches instead of setcc's with and/or operations.
2810   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2811   // unpredictable branches, and vector extracts because those jumps are likely
2812   // expensive for any target), this should improve performance.
2813   // For example, instead of something like:
2814   //     cmp A, B
2815   //     C = seteq
2816   //     cmp D, E
2817   //     F = setle
2818   //     or C, F
2819   //     jnz foo
2820   // Emit:
2821   //     cmp A, B
2822   //     je foo
2823   //     cmp D, E
2824   //     jle foo
2825   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2826   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2827       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2828     Value *Vec;
2829     const Value *BOp0, *BOp1;
2830     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2831     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2832       Opcode = Instruction::And;
2833     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2834       Opcode = Instruction::Or;
2835 
2836     if (Opcode &&
2837         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2838           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2839         !shouldKeepJumpConditionsTogether(
2840             FuncInfo, I, Opcode, BOp0, BOp1,
2841             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2842                 Opcode, BOp0, BOp1))) {
2843       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2844                            getEdgeProbability(BrMBB, Succ0MBB),
2845                            getEdgeProbability(BrMBB, Succ1MBB),
2846                            /*InvertCond=*/false);
2847       // If the compares in later blocks need to use values not currently
2848       // exported from this block, export them now.  This block should always
2849       // be the first entry.
2850       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2851 
2852       // Allow some cases to be rejected.
2853       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2854         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2855           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2856           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2857         }
2858 
2859         // Emit the branch for this block.
2860         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2861         SL->SwitchCases.erase(SL->SwitchCases.begin());
2862         return;
2863       }
2864 
2865       // Okay, we decided not to do this, remove any inserted MBB's and clear
2866       // SwitchCases.
2867       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2868         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2869 
2870       SL->SwitchCases.clear();
2871     }
2872   }
2873 
2874   // Create a CaseBlock record representing this branch.
2875   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2876                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2877 
2878   // Use visitSwitchCase to actually insert the fast branch sequence for this
2879   // cond branch.
2880   visitSwitchCase(CB, BrMBB);
2881 }
2882 
2883 /// visitSwitchCase - Emits the necessary code to represent a single node in
2884 /// the binary search tree resulting from lowering a switch instruction.
visitSwitchCase(CaseBlock & CB,MachineBasicBlock * SwitchBB)2885 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2886                                           MachineBasicBlock *SwitchBB) {
2887   SDValue Cond;
2888   SDValue CondLHS = getValue(CB.CmpLHS);
2889   SDLoc dl = CB.DL;
2890 
2891   if (CB.CC == ISD::SETTRUE) {
2892     // Branch or fall through to TrueBB.
2893     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2894     SwitchBB->normalizeSuccProbs();
2895     if (CB.TrueBB != NextBlock(SwitchBB)) {
2896       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2897                               DAG.getBasicBlock(CB.TrueBB)));
2898     }
2899     return;
2900   }
2901 
2902   auto &TLI = DAG.getTargetLoweringInfo();
2903   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2904 
2905   // Build the setcc now.
2906   if (!CB.CmpMHS) {
2907     // Fold "(X == true)" to X and "(X == false)" to !X to
2908     // handle common cases produced by branch lowering.
2909     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2910         CB.CC == ISD::SETEQ)
2911       Cond = CondLHS;
2912     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2913              CB.CC == ISD::SETEQ) {
2914       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2915       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2916     } else {
2917       SDValue CondRHS = getValue(CB.CmpRHS);
2918 
2919       // If a pointer's DAG type is larger than its memory type then the DAG
2920       // values are zero-extended. This breaks signed comparisons so truncate
2921       // back to the underlying type before doing the compare.
2922       if (CondLHS.getValueType() != MemVT) {
2923         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2924         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2925       }
2926       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2927     }
2928   } else {
2929     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2930 
2931     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2932     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2933 
2934     SDValue CmpOp = getValue(CB.CmpMHS);
2935     EVT VT = CmpOp.getValueType();
2936 
2937     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2938       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2939                           ISD::SETLE);
2940     } else {
2941       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2942                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2943       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2944                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2945     }
2946   }
2947 
2948   // Update successor info
2949   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2950   // TrueBB and FalseBB are always different unless the incoming IR is
2951   // degenerate. This only happens when running llc on weird IR.
2952   if (CB.TrueBB != CB.FalseBB)
2953     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2954   SwitchBB->normalizeSuccProbs();
2955 
2956   // If the lhs block is the next block, invert the condition so that we can
2957   // fall through to the lhs instead of the rhs block.
2958   if (CB.TrueBB == NextBlock(SwitchBB)) {
2959     std::swap(CB.TrueBB, CB.FalseBB);
2960     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2961     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2962   }
2963 
2964   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2965                                MVT::Other, getControlRoot(), Cond,
2966                                DAG.getBasicBlock(CB.TrueBB));
2967 
2968   setValue(CurInst, BrCond);
2969 
2970   // Insert the false branch. Do this even if it's a fall through branch,
2971   // this makes it easier to do DAG optimizations which require inverting
2972   // the branch condition.
2973   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2974                        DAG.getBasicBlock(CB.FalseBB));
2975 
2976   DAG.setRoot(BrCond);
2977 }
2978 
2979 /// visitJumpTable - Emit JumpTable node in the current MBB
visitJumpTable(SwitchCG::JumpTable & JT)2980 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2981   // Emit the code for the jump table
2982   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2983   assert(JT.Reg != -1U && "Should lower JT Header first!");
2984   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2985   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2986   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2987   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2988                                     Index.getValue(1), Table, Index);
2989   DAG.setRoot(BrJumpTable);
2990 }
2991 
2992 /// visitJumpTableHeader - This function emits necessary code to produce index
2993 /// in the JumpTable from switch case.
visitJumpTableHeader(SwitchCG::JumpTable & JT,JumpTableHeader & JTH,MachineBasicBlock * SwitchBB)2994 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2995                                                JumpTableHeader &JTH,
2996                                                MachineBasicBlock *SwitchBB) {
2997   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2998   const SDLoc &dl = *JT.SL;
2999 
3000   // Subtract the lowest switch case value from the value being switched on.
3001   SDValue SwitchOp = getValue(JTH.SValue);
3002   EVT VT = SwitchOp.getValueType();
3003   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3004                             DAG.getConstant(JTH.First, dl, VT));
3005 
3006   // The SDNode we just created, which holds the value being switched on minus
3007   // the smallest case value, needs to be copied to a virtual register so it
3008   // can be used as an index into the jump table in a subsequent basic block.
3009   // This value may be smaller or larger than the target's pointer type, and
3010   // therefore require extension or truncating.
3011   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3012   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
3013 
3014   unsigned JumpTableReg =
3015       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
3016   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
3017                                     JumpTableReg, SwitchOp);
3018   JT.Reg = JumpTableReg;
3019 
3020   if (!JTH.FallthroughUnreachable) {
3021     // Emit the range check for the jump table, and branch to the default block
3022     // for the switch statement if the value being switched on exceeds the
3023     // largest case in the switch.
3024     SDValue CMP = DAG.getSetCC(
3025         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3026                                    Sub.getValueType()),
3027         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3028 
3029     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3030                                  MVT::Other, CopyTo, CMP,
3031                                  DAG.getBasicBlock(JT.Default));
3032 
3033     // Avoid emitting unnecessary branches to the next block.
3034     if (JT.MBB != NextBlock(SwitchBB))
3035       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3036                            DAG.getBasicBlock(JT.MBB));
3037 
3038     DAG.setRoot(BrCond);
3039   } else {
3040     // Avoid emitting unnecessary branches to the next block.
3041     if (JT.MBB != NextBlock(SwitchBB))
3042       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3043                               DAG.getBasicBlock(JT.MBB)));
3044     else
3045       DAG.setRoot(CopyTo);
3046   }
3047 }
3048 
3049 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3050 /// variable if there exists one.
getLoadStackGuard(SelectionDAG & DAG,const SDLoc & DL,SDValue & Chain)3051 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3052                                  SDValue &Chain) {
3053   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3054   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3055   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3056   MachineFunction &MF = DAG.getMachineFunction();
3057   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3058   MachineSDNode *Node =
3059       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3060   if (Global) {
3061     MachinePointerInfo MPInfo(Global);
3062     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3063                  MachineMemOperand::MODereferenceable;
3064     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3065         MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8),
3066         DAG.getEVTAlign(PtrTy));
3067     DAG.setNodeMemRefs(Node, {MemRef});
3068   }
3069   if (PtrTy != PtrMemTy)
3070     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3071   return SDValue(Node, 0);
3072 }
3073 
3074 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3075 /// tail spliced into a stack protector check success bb.
3076 ///
3077 /// For a high level explanation of how this fits into the stack protector
3078 /// generation see the comment on the declaration of class
3079 /// StackProtectorDescriptor.
visitSPDescriptorParent(StackProtectorDescriptor & SPD,MachineBasicBlock * ParentBB)3080 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3081                                                   MachineBasicBlock *ParentBB) {
3082 
3083   // First create the loads to the guard/stack slot for the comparison.
3084   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3085   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3086   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3087 
3088   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3089   int FI = MFI.getStackProtectorIndex();
3090 
3091   SDValue Guard;
3092   SDLoc dl = getCurSDLoc();
3093   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3094   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3095   Align Align =
3096       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3097 
3098   // Generate code to load the content of the guard slot.
3099   SDValue GuardVal = DAG.getLoad(
3100       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3101       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3102       MachineMemOperand::MOVolatile);
3103 
3104   if (TLI.useStackGuardXorFP())
3105     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3106 
3107   // Retrieve guard check function, nullptr if instrumentation is inlined.
3108   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3109     // The target provides a guard check function to validate the guard value.
3110     // Generate a call to that function with the content of the guard slot as
3111     // argument.
3112     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3113     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3114 
3115     TargetLowering::ArgListTy Args;
3116     TargetLowering::ArgListEntry Entry;
3117     Entry.Node = GuardVal;
3118     Entry.Ty = FnTy->getParamType(0);
3119     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3120       Entry.IsInReg = true;
3121     Args.push_back(Entry);
3122 
3123     TargetLowering::CallLoweringInfo CLI(DAG);
3124     CLI.setDebugLoc(getCurSDLoc())
3125         .setChain(DAG.getEntryNode())
3126         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3127                    getValue(GuardCheckFn), std::move(Args));
3128 
3129     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3130     DAG.setRoot(Result.second);
3131     return;
3132   }
3133 
3134   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3135   // Otherwise, emit a volatile load to retrieve the stack guard value.
3136   SDValue Chain = DAG.getEntryNode();
3137   if (TLI.useLoadStackGuardNode()) {
3138     Guard = getLoadStackGuard(DAG, dl, Chain);
3139   } else {
3140     const Value *IRGuard = TLI.getSDagStackGuard(M);
3141     SDValue GuardPtr = getValue(IRGuard);
3142 
3143     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3144                         MachinePointerInfo(IRGuard, 0), Align,
3145                         MachineMemOperand::MOVolatile);
3146   }
3147 
3148   // Perform the comparison via a getsetcc.
3149   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3150                                                         *DAG.getContext(),
3151                                                         Guard.getValueType()),
3152                              Guard, GuardVal, ISD::SETNE);
3153 
3154   // If the guard/stackslot do not equal, branch to failure MBB.
3155   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3156                                MVT::Other, GuardVal.getOperand(0),
3157                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3158   // Otherwise branch to success MBB.
3159   SDValue Br = DAG.getNode(ISD::BR, dl,
3160                            MVT::Other, BrCond,
3161                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3162 
3163   DAG.setRoot(Br);
3164 }
3165 
3166 /// Codegen the failure basic block for a stack protector check.
3167 ///
3168 /// A failure stack protector machine basic block consists simply of a call to
3169 /// __stack_chk_fail().
3170 ///
3171 /// For a high level explanation of how this fits into the stack protector
3172 /// generation see the comment on the declaration of class
3173 /// StackProtectorDescriptor.
3174 void
visitSPDescriptorFailure(StackProtectorDescriptor & SPD)3175 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3176   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3177   TargetLowering::MakeLibCallOptions CallOptions;
3178   CallOptions.setDiscardResult(true);
3179   SDValue Chain =
3180       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3181                       std::nullopt, CallOptions, getCurSDLoc())
3182           .second;
3183   // On PS4/PS5, the "return address" must still be within the calling
3184   // function, even if it's at the very end, so emit an explicit TRAP here.
3185   // Passing 'true' for doesNotReturn above won't generate the trap for us.
3186   if (TM.getTargetTriple().isPS())
3187     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3188   // WebAssembly needs an unreachable instruction after a non-returning call,
3189   // because the function return type can be different from __stack_chk_fail's
3190   // return type (void).
3191   if (TM.getTargetTriple().isWasm())
3192     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3193 
3194   DAG.setRoot(Chain);
3195 }
3196 
3197 /// visitBitTestHeader - This function emits necessary code to produce value
3198 /// suitable for "bit tests"
visitBitTestHeader(BitTestBlock & B,MachineBasicBlock * SwitchBB)3199 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3200                                              MachineBasicBlock *SwitchBB) {
3201   SDLoc dl = getCurSDLoc();
3202 
3203   // Subtract the minimum value.
3204   SDValue SwitchOp = getValue(B.SValue);
3205   EVT VT = SwitchOp.getValueType();
3206   SDValue RangeSub =
3207       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3208 
3209   // Determine the type of the test operands.
3210   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3211   bool UsePtrType = false;
3212   if (!TLI.isTypeLegal(VT)) {
3213     UsePtrType = true;
3214   } else {
3215     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3216       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3217         // Switch table case range are encoded into series of masks.
3218         // Just use pointer type, it's guaranteed to fit.
3219         UsePtrType = true;
3220         break;
3221       }
3222   }
3223   SDValue Sub = RangeSub;
3224   if (UsePtrType) {
3225     VT = TLI.getPointerTy(DAG.getDataLayout());
3226     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3227   }
3228 
3229   B.RegVT = VT.getSimpleVT();
3230   B.Reg = FuncInfo.CreateReg(B.RegVT);
3231   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3232 
3233   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3234 
3235   if (!B.FallthroughUnreachable)
3236     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3237   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3238   SwitchBB->normalizeSuccProbs();
3239 
3240   SDValue Root = CopyTo;
3241   if (!B.FallthroughUnreachable) {
3242     // Conditional branch to the default block.
3243     SDValue RangeCmp = DAG.getSetCC(dl,
3244         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3245                                RangeSub.getValueType()),
3246         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3247         ISD::SETUGT);
3248 
3249     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3250                        DAG.getBasicBlock(B.Default));
3251   }
3252 
3253   // Avoid emitting unnecessary branches to the next block.
3254   if (MBB != NextBlock(SwitchBB))
3255     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3256 
3257   DAG.setRoot(Root);
3258 }
3259 
3260 /// visitBitTestCase - this function produces one "bit test"
visitBitTestCase(BitTestBlock & BB,MachineBasicBlock * NextMBB,BranchProbability BranchProbToNext,unsigned Reg,BitTestCase & B,MachineBasicBlock * SwitchBB)3261 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3262                                            MachineBasicBlock* NextMBB,
3263                                            BranchProbability BranchProbToNext,
3264                                            unsigned Reg,
3265                                            BitTestCase &B,
3266                                            MachineBasicBlock *SwitchBB) {
3267   SDLoc dl = getCurSDLoc();
3268   MVT VT = BB.RegVT;
3269   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3270   SDValue Cmp;
3271   unsigned PopCount = llvm::popcount(B.Mask);
3272   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3273   if (PopCount == 1) {
3274     // Testing for a single bit; just compare the shift count with what it
3275     // would need to be to shift a 1 bit in that position.
3276     Cmp = DAG.getSetCC(
3277         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3278         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3279         ISD::SETEQ);
3280   } else if (PopCount == BB.Range) {
3281     // There is only one zero bit in the range, test for it directly.
3282     Cmp = DAG.getSetCC(
3283         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3284         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3285   } else {
3286     // Make desired shift
3287     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3288                                     DAG.getConstant(1, dl, VT), ShiftOp);
3289 
3290     // Emit bit tests and jumps
3291     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3292                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3293     Cmp = DAG.getSetCC(
3294         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3295         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3296   }
3297 
3298   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3299   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3300   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3301   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3302   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3303   // one as they are relative probabilities (and thus work more like weights),
3304   // and hence we need to normalize them to let the sum of them become one.
3305   SwitchBB->normalizeSuccProbs();
3306 
3307   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3308                               MVT::Other, getControlRoot(),
3309                               Cmp, DAG.getBasicBlock(B.TargetBB));
3310 
3311   // Avoid emitting unnecessary branches to the next block.
3312   if (NextMBB != NextBlock(SwitchBB))
3313     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3314                         DAG.getBasicBlock(NextMBB));
3315 
3316   DAG.setRoot(BrAnd);
3317 }
3318 
visitInvoke(const InvokeInst & I)3319 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3320   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3321 
3322   // Retrieve successors. Look through artificial IR level blocks like
3323   // catchswitch for successors.
3324   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
3325   const BasicBlock *EHPadBB = I.getSuccessor(1);
3326   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
3327 
3328   // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3329   // have to do anything here to lower funclet bundles.
3330   assert(!I.hasOperandBundlesOtherThan(
3331              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3332               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3333               LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3334               LLVMContext::OB_clang_arc_attachedcall}) &&
3335          "Cannot lower invokes with arbitrary operand bundles yet!");
3336 
3337   const Value *Callee(I.getCalledOperand());
3338   const Function *Fn = dyn_cast<Function>(Callee);
3339   if (isa<InlineAsm>(Callee))
3340     visitInlineAsm(I, EHPadBB);
3341   else if (Fn && Fn->isIntrinsic()) {
3342     switch (Fn->getIntrinsicID()) {
3343     default:
3344       llvm_unreachable("Cannot invoke this intrinsic");
3345     case Intrinsic::donothing:
3346       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3347     case Intrinsic::seh_try_begin:
3348     case Intrinsic::seh_scope_begin:
3349     case Intrinsic::seh_try_end:
3350     case Intrinsic::seh_scope_end:
3351       if (EHPadMBB)
3352           // a block referenced by EH table
3353           // so dtor-funclet not removed by opts
3354           EHPadMBB->setMachineBlockAddressTaken();
3355       break;
3356     case Intrinsic::experimental_patchpoint_void:
3357     case Intrinsic::experimental_patchpoint:
3358       visitPatchpoint(I, EHPadBB);
3359       break;
3360     case Intrinsic::experimental_gc_statepoint:
3361       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3362       break;
3363     case Intrinsic::wasm_rethrow: {
3364       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3365       // special because it can be invoked, so we manually lower it to a DAG
3366       // node here.
3367       SmallVector<SDValue, 8> Ops;
3368       Ops.push_back(getControlRoot()); // inchain for the terminator node
3369       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3370       Ops.push_back(
3371           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3372                                 TLI.getPointerTy(DAG.getDataLayout())));
3373       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3374       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3375       break;
3376     }
3377     }
3378   } else if (I.hasDeoptState()) {
3379     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3380     // Eventually we will support lowering the @llvm.experimental.deoptimize
3381     // intrinsic, and right now there are no plans to support other intrinsics
3382     // with deopt state.
3383     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3384   } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3385     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB);
3386   } else {
3387     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3388   }
3389 
3390   // If the value of the invoke is used outside of its defining block, make it
3391   // available as a virtual register.
3392   // We already took care of the exported value for the statepoint instruction
3393   // during call to the LowerStatepoint.
3394   if (!isa<GCStatepointInst>(I)) {
3395     CopyToExportRegsIfNeeded(&I);
3396   }
3397 
3398   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3399   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3400   BranchProbability EHPadBBProb =
3401       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3402           : BranchProbability::getZero();
3403   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3404 
3405   // Update successor info.
3406   addSuccessorWithProb(InvokeMBB, Return);
3407   for (auto &UnwindDest : UnwindDests) {
3408     UnwindDest.first->setIsEHPad();
3409     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3410   }
3411   InvokeMBB->normalizeSuccProbs();
3412 
3413   // Drop into normal successor.
3414   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3415                           DAG.getBasicBlock(Return)));
3416 }
3417 
visitCallBr(const CallBrInst & I)3418 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3419   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3420 
3421   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3422   // have to do anything here to lower funclet bundles.
3423   assert(!I.hasOperandBundlesOtherThan(
3424              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3425          "Cannot lower callbrs with arbitrary operand bundles yet!");
3426 
3427   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3428   visitInlineAsm(I);
3429   CopyToExportRegsIfNeeded(&I);
3430 
3431   // Retrieve successors.
3432   SmallPtrSet<BasicBlock *, 8> Dests;
3433   Dests.insert(I.getDefaultDest());
3434   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3435 
3436   // Update successor info.
3437   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3438   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3439     BasicBlock *Dest = I.getIndirectDest(i);
3440     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3441     Target->setIsInlineAsmBrIndirectTarget();
3442     Target->setMachineBlockAddressTaken();
3443     Target->setLabelMustBeEmitted();
3444     // Don't add duplicate machine successors.
3445     if (Dests.insert(Dest).second)
3446       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3447   }
3448   CallBrMBB->normalizeSuccProbs();
3449 
3450   // Drop into default successor.
3451   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3452                           MVT::Other, getControlRoot(),
3453                           DAG.getBasicBlock(Return)));
3454 }
3455 
visitResume(const ResumeInst & RI)3456 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3457   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3458 }
3459 
visitLandingPad(const LandingPadInst & LP)3460 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3461   assert(FuncInfo.MBB->isEHPad() &&
3462          "Call to landingpad not in landing pad!");
3463 
3464   // If there aren't registers to copy the values into (e.g., during SjLj
3465   // exceptions), then don't bother to create these DAG nodes.
3466   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3467   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3468   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3469       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3470     return;
3471 
3472   // If landingpad's return type is token type, we don't create DAG nodes
3473   // for its exception pointer and selector value. The extraction of exception
3474   // pointer or selector value from token type landingpads is not currently
3475   // supported.
3476   if (LP.getType()->isTokenTy())
3477     return;
3478 
3479   SmallVector<EVT, 2> ValueVTs;
3480   SDLoc dl = getCurSDLoc();
3481   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3482   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3483 
3484   // Get the two live-in registers as SDValues. The physregs have already been
3485   // copied into virtual registers.
3486   SDValue Ops[2];
3487   if (FuncInfo.ExceptionPointerVirtReg) {
3488     Ops[0] = DAG.getZExtOrTrunc(
3489         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3490                            FuncInfo.ExceptionPointerVirtReg,
3491                            TLI.getPointerTy(DAG.getDataLayout())),
3492         dl, ValueVTs[0]);
3493   } else {
3494     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3495   }
3496   Ops[1] = DAG.getZExtOrTrunc(
3497       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3498                          FuncInfo.ExceptionSelectorVirtReg,
3499                          TLI.getPointerTy(DAG.getDataLayout())),
3500       dl, ValueVTs[1]);
3501 
3502   // Merge into one.
3503   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3504                             DAG.getVTList(ValueVTs), Ops);
3505   setValue(&LP, Res);
3506 }
3507 
UpdateSplitBlock(MachineBasicBlock * First,MachineBasicBlock * Last)3508 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3509                                            MachineBasicBlock *Last) {
3510   // Update JTCases.
3511   for (JumpTableBlock &JTB : SL->JTCases)
3512     if (JTB.first.HeaderBB == First)
3513       JTB.first.HeaderBB = Last;
3514 
3515   // Update BitTestCases.
3516   for (BitTestBlock &BTB : SL->BitTestCases)
3517     if (BTB.Parent == First)
3518       BTB.Parent = Last;
3519 }
3520 
visitIndirectBr(const IndirectBrInst & I)3521 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3522   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3523 
3524   // Update machine-CFG edges with unique successors.
3525   SmallSet<BasicBlock*, 32> Done;
3526   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3527     BasicBlock *BB = I.getSuccessor(i);
3528     bool Inserted = Done.insert(BB).second;
3529     if (!Inserted)
3530         continue;
3531 
3532     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3533     addSuccessorWithProb(IndirectBrMBB, Succ);
3534   }
3535   IndirectBrMBB->normalizeSuccProbs();
3536 
3537   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3538                           MVT::Other, getControlRoot(),
3539                           getValue(I.getAddress())));
3540 }
3541 
visitUnreachable(const UnreachableInst & I)3542 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3543   if (!DAG.getTarget().Options.TrapUnreachable)
3544     return;
3545 
3546   // We may be able to ignore unreachable behind a noreturn call.
3547   if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode());
3548       Call && Call->doesNotReturn()) {
3549     if (DAG.getTarget().Options.NoTrapAfterNoreturn)
3550       return;
3551     // Do not emit an additional trap instruction.
3552     if (Call->isNonContinuableTrap())
3553       return;
3554   }
3555 
3556   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3557 }
3558 
visitUnary(const User & I,unsigned Opcode)3559 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3560   SDNodeFlags Flags;
3561   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3562     Flags.copyFMF(*FPOp);
3563 
3564   SDValue Op = getValue(I.getOperand(0));
3565   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3566                                     Op, Flags);
3567   setValue(&I, UnNodeValue);
3568 }
3569 
visitBinary(const User & I,unsigned Opcode)3570 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3571   SDNodeFlags Flags;
3572   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3573     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3574     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3575   }
3576   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3577     Flags.setExact(ExactOp->isExact());
3578   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3579     Flags.setDisjoint(DisjointOp->isDisjoint());
3580   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3581     Flags.copyFMF(*FPOp);
3582 
3583   SDValue Op1 = getValue(I.getOperand(0));
3584   SDValue Op2 = getValue(I.getOperand(1));
3585   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3586                                      Op1, Op2, Flags);
3587   setValue(&I, BinNodeValue);
3588 }
3589 
visitShift(const User & I,unsigned Opcode)3590 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3591   SDValue Op1 = getValue(I.getOperand(0));
3592   SDValue Op2 = getValue(I.getOperand(1));
3593 
3594   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3595       Op1.getValueType(), DAG.getDataLayout());
3596 
3597   // Coerce the shift amount to the right type if we can. This exposes the
3598   // truncate or zext to optimization early.
3599   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3600     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3601            "Unexpected shift type");
3602     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3603   }
3604 
3605   bool nuw = false;
3606   bool nsw = false;
3607   bool exact = false;
3608 
3609   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3610 
3611     if (const OverflowingBinaryOperator *OFBinOp =
3612             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3613       nuw = OFBinOp->hasNoUnsignedWrap();
3614       nsw = OFBinOp->hasNoSignedWrap();
3615     }
3616     if (const PossiblyExactOperator *ExactOp =
3617             dyn_cast<const PossiblyExactOperator>(&I))
3618       exact = ExactOp->isExact();
3619   }
3620   SDNodeFlags Flags;
3621   Flags.setExact(exact);
3622   Flags.setNoSignedWrap(nsw);
3623   Flags.setNoUnsignedWrap(nuw);
3624   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3625                             Flags);
3626   setValue(&I, Res);
3627 }
3628 
visitSDiv(const User & I)3629 void SelectionDAGBuilder::visitSDiv(const User &I) {
3630   SDValue Op1 = getValue(I.getOperand(0));
3631   SDValue Op2 = getValue(I.getOperand(1));
3632 
3633   SDNodeFlags Flags;
3634   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3635                  cast<PossiblyExactOperator>(&I)->isExact());
3636   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3637                            Op2, Flags));
3638 }
3639 
visitICmp(const ICmpInst & I)3640 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3641   ICmpInst::Predicate predicate = I.getPredicate();
3642   SDValue Op1 = getValue(I.getOperand(0));
3643   SDValue Op2 = getValue(I.getOperand(1));
3644   ISD::CondCode Opcode = getICmpCondCode(predicate);
3645 
3646   auto &TLI = DAG.getTargetLoweringInfo();
3647   EVT MemVT =
3648       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3649 
3650   // If a pointer's DAG type is larger than its memory type then the DAG values
3651   // are zero-extended. This breaks signed comparisons so truncate back to the
3652   // underlying type before doing the compare.
3653   if (Op1.getValueType() != MemVT) {
3654     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3655     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3656   }
3657 
3658   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3659                                                         I.getType());
3660   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3661 }
3662 
visitFCmp(const FCmpInst & I)3663 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3664   FCmpInst::Predicate predicate = I.getPredicate();
3665   SDValue Op1 = getValue(I.getOperand(0));
3666   SDValue Op2 = getValue(I.getOperand(1));
3667 
3668   ISD::CondCode Condition = getFCmpCondCode(predicate);
3669   auto *FPMO = cast<FPMathOperator>(&I);
3670   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3671     Condition = getFCmpCodeWithoutNaN(Condition);
3672 
3673   SDNodeFlags Flags;
3674   Flags.copyFMF(*FPMO);
3675   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3676 
3677   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3678                                                         I.getType());
3679   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3680 }
3681 
3682 // Check if the condition of the select has one use or two users that are both
3683 // selects with the same condition.
hasOnlySelectUsers(const Value * Cond)3684 static bool hasOnlySelectUsers(const Value *Cond) {
3685   return llvm::all_of(Cond->users(), [](const Value *V) {
3686     return isa<SelectInst>(V);
3687   });
3688 }
3689 
visitSelect(const User & I)3690 void SelectionDAGBuilder::visitSelect(const User &I) {
3691   SmallVector<EVT, 4> ValueVTs;
3692   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3693                   ValueVTs);
3694   unsigned NumValues = ValueVTs.size();
3695   if (NumValues == 0) return;
3696 
3697   SmallVector<SDValue, 4> Values(NumValues);
3698   SDValue Cond     = getValue(I.getOperand(0));
3699   SDValue LHSVal   = getValue(I.getOperand(1));
3700   SDValue RHSVal   = getValue(I.getOperand(2));
3701   SmallVector<SDValue, 1> BaseOps(1, Cond);
3702   ISD::NodeType OpCode =
3703       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3704 
3705   bool IsUnaryAbs = false;
3706   bool Negate = false;
3707 
3708   SDNodeFlags Flags;
3709   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3710     Flags.copyFMF(*FPOp);
3711 
3712   Flags.setUnpredictable(
3713       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3714 
3715   // Min/max matching is only viable if all output VTs are the same.
3716   if (all_equal(ValueVTs)) {
3717     EVT VT = ValueVTs[0];
3718     LLVMContext &Ctx = *DAG.getContext();
3719     auto &TLI = DAG.getTargetLoweringInfo();
3720 
3721     // We care about the legality of the operation after it has been type
3722     // legalized.
3723     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3724       VT = TLI.getTypeToTransformTo(Ctx, VT);
3725 
3726     // If the vselect is legal, assume we want to leave this as a vector setcc +
3727     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3728     // min/max is legal on the scalar type.
3729     bool UseScalarMinMax = VT.isVector() &&
3730       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3731 
3732     // ValueTracking's select pattern matching does not account for -0.0,
3733     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3734     // -0.0 is less than +0.0.
3735     Value *LHS, *RHS;
3736     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3737     ISD::NodeType Opc = ISD::DELETED_NODE;
3738     switch (SPR.Flavor) {
3739     case SPF_UMAX:    Opc = ISD::UMAX; break;
3740     case SPF_UMIN:    Opc = ISD::UMIN; break;
3741     case SPF_SMAX:    Opc = ISD::SMAX; break;
3742     case SPF_SMIN:    Opc = ISD::SMIN; break;
3743     case SPF_FMINNUM:
3744       switch (SPR.NaNBehavior) {
3745       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3746       case SPNB_RETURNS_NAN: break;
3747       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3748       case SPNB_RETURNS_ANY:
3749         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3750             (UseScalarMinMax &&
3751              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3752           Opc = ISD::FMINNUM;
3753         break;
3754       }
3755       break;
3756     case SPF_FMAXNUM:
3757       switch (SPR.NaNBehavior) {
3758       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3759       case SPNB_RETURNS_NAN: break;
3760       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3761       case SPNB_RETURNS_ANY:
3762         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3763             (UseScalarMinMax &&
3764              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3765           Opc = ISD::FMAXNUM;
3766         break;
3767       }
3768       break;
3769     case SPF_NABS:
3770       Negate = true;
3771       [[fallthrough]];
3772     case SPF_ABS:
3773       IsUnaryAbs = true;
3774       Opc = ISD::ABS;
3775       break;
3776     default: break;
3777     }
3778 
3779     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3780         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3781          (UseScalarMinMax &&
3782           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3783         // If the underlying comparison instruction is used by any other
3784         // instruction, the consumed instructions won't be destroyed, so it is
3785         // not profitable to convert to a min/max.
3786         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3787       OpCode = Opc;
3788       LHSVal = getValue(LHS);
3789       RHSVal = getValue(RHS);
3790       BaseOps.clear();
3791     }
3792 
3793     if (IsUnaryAbs) {
3794       OpCode = Opc;
3795       LHSVal = getValue(LHS);
3796       BaseOps.clear();
3797     }
3798   }
3799 
3800   if (IsUnaryAbs) {
3801     for (unsigned i = 0; i != NumValues; ++i) {
3802       SDLoc dl = getCurSDLoc();
3803       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3804       Values[i] =
3805           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3806       if (Negate)
3807         Values[i] = DAG.getNegative(Values[i], dl, VT);
3808     }
3809   } else {
3810     for (unsigned i = 0; i != NumValues; ++i) {
3811       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3812       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3813       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3814       Values[i] = DAG.getNode(
3815           OpCode, getCurSDLoc(),
3816           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3817     }
3818   }
3819 
3820   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3821                            DAG.getVTList(ValueVTs), Values));
3822 }
3823 
visitTrunc(const User & I)3824 void SelectionDAGBuilder::visitTrunc(const User &I) {
3825   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3826   SDValue N = getValue(I.getOperand(0));
3827   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3828                                                         I.getType());
3829   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3830 }
3831 
visitZExt(const User & I)3832 void SelectionDAGBuilder::visitZExt(const User &I) {
3833   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3834   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3835   SDValue N = getValue(I.getOperand(0));
3836   auto &TLI = DAG.getTargetLoweringInfo();
3837   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3838 
3839   SDNodeFlags Flags;
3840   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3841     Flags.setNonNeg(PNI->hasNonNeg());
3842 
3843   // Eagerly use nonneg information to canonicalize towards sign_extend if
3844   // that is the target's preference.
3845   // TODO: Let the target do this later.
3846   if (Flags.hasNonNeg() &&
3847       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3848     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3849     return;
3850   }
3851 
3852   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3853 }
3854 
visitSExt(const User & I)3855 void SelectionDAGBuilder::visitSExt(const User &I) {
3856   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3857   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3858   SDValue N = getValue(I.getOperand(0));
3859   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3860                                                         I.getType());
3861   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3862 }
3863 
visitFPTrunc(const User & I)3864 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3865   // FPTrunc is never a no-op cast, no need to check
3866   SDValue N = getValue(I.getOperand(0));
3867   SDLoc dl = getCurSDLoc();
3868   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3869   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3870   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3871                            DAG.getTargetConstant(
3872                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3873 }
3874 
visitFPExt(const User & I)3875 void SelectionDAGBuilder::visitFPExt(const User &I) {
3876   // FPExt is never a no-op cast, no need to check
3877   SDValue N = getValue(I.getOperand(0));
3878   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3879                                                         I.getType());
3880   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3881 }
3882 
visitFPToUI(const User & I)3883 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3884   // FPToUI is never a no-op cast, no need to check
3885   SDValue N = getValue(I.getOperand(0));
3886   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3887                                                         I.getType());
3888   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3889 }
3890 
visitFPToSI(const User & I)3891 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3892   // FPToSI is never a no-op cast, no need to check
3893   SDValue N = getValue(I.getOperand(0));
3894   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3895                                                         I.getType());
3896   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3897 }
3898 
visitUIToFP(const User & I)3899 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3900   // UIToFP is never a no-op cast, no need to check
3901   SDValue N = getValue(I.getOperand(0));
3902   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3903                                                         I.getType());
3904   SDNodeFlags Flags;
3905   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3906     Flags.setNonNeg(PNI->hasNonNeg());
3907 
3908   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
3909 }
3910 
visitSIToFP(const User & I)3911 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3912   // SIToFP is never a no-op cast, no need to check
3913   SDValue N = getValue(I.getOperand(0));
3914   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3915                                                         I.getType());
3916   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3917 }
3918 
visitPtrToInt(const User & I)3919 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3920   // What to do depends on the size of the integer and the size of the pointer.
3921   // We can either truncate, zero extend, or no-op, accordingly.
3922   SDValue N = getValue(I.getOperand(0));
3923   auto &TLI = DAG.getTargetLoweringInfo();
3924   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3925                                                         I.getType());
3926   EVT PtrMemVT =
3927       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3928   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3929   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3930   setValue(&I, N);
3931 }
3932 
visitIntToPtr(const User & I)3933 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3934   // What to do depends on the size of the integer and the size of the pointer.
3935   // We can either truncate, zero extend, or no-op, accordingly.
3936   SDValue N = getValue(I.getOperand(0));
3937   auto &TLI = DAG.getTargetLoweringInfo();
3938   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3939   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3940   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3941   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3942   setValue(&I, N);
3943 }
3944 
visitBitCast(const User & I)3945 void SelectionDAGBuilder::visitBitCast(const User &I) {
3946   SDValue N = getValue(I.getOperand(0));
3947   SDLoc dl = getCurSDLoc();
3948   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3949                                                         I.getType());
3950 
3951   // BitCast assures us that source and destination are the same size so this is
3952   // either a BITCAST or a no-op.
3953   if (DestVT != N.getValueType())
3954     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3955                              DestVT, N)); // convert types.
3956   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3957   // might fold any kind of constant expression to an integer constant and that
3958   // is not what we are looking for. Only recognize a bitcast of a genuine
3959   // constant integer as an opaque constant.
3960   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3961     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3962                                  /*isOpaque*/true));
3963   else
3964     setValue(&I, N);            // noop cast.
3965 }
3966 
visitAddrSpaceCast(const User & I)3967 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3969   const Value *SV = I.getOperand(0);
3970   SDValue N = getValue(SV);
3971   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3972 
3973   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3974   unsigned DestAS = I.getType()->getPointerAddressSpace();
3975 
3976   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3977     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3978 
3979   setValue(&I, N);
3980 }
3981 
visitInsertElement(const User & I)3982 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3983   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3984   SDValue InVec = getValue(I.getOperand(0));
3985   SDValue InVal = getValue(I.getOperand(1));
3986   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3987                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3988   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3989                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3990                            InVec, InVal, InIdx));
3991 }
3992 
visitExtractElement(const User & I)3993 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3994   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3995   SDValue InVec = getValue(I.getOperand(0));
3996   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3997                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3998   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3999                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
4000                            InVec, InIdx));
4001 }
4002 
visitShuffleVector(const User & I)4003 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4004   SDValue Src1 = getValue(I.getOperand(0));
4005   SDValue Src2 = getValue(I.getOperand(1));
4006   ArrayRef<int> Mask;
4007   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4008     Mask = SVI->getShuffleMask();
4009   else
4010     Mask = cast<ConstantExpr>(I).getShuffleMask();
4011   SDLoc DL = getCurSDLoc();
4012   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4013   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4014   EVT SrcVT = Src1.getValueType();
4015 
4016   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
4017       VT.isScalableVector()) {
4018     // Canonical splat form of first element of first input vector.
4019     SDValue FirstElt =
4020         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4021                     DAG.getVectorIdxConstant(0, DL));
4022     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4023     return;
4024   }
4025 
4026   // For now, we only handle splats for scalable vectors.
4027   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4028   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4029   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4030 
4031   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4032   unsigned MaskNumElts = Mask.size();
4033 
4034   if (SrcNumElts == MaskNumElts) {
4035     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4036     return;
4037   }
4038 
4039   // Normalize the shuffle vector since mask and vector length don't match.
4040   if (SrcNumElts < MaskNumElts) {
4041     // Mask is longer than the source vectors. We can use concatenate vector to
4042     // make the mask and vectors lengths match.
4043 
4044     if (MaskNumElts % SrcNumElts == 0) {
4045       // Mask length is a multiple of the source vector length.
4046       // Check if the shuffle is some kind of concatenation of the input
4047       // vectors.
4048       unsigned NumConcat = MaskNumElts / SrcNumElts;
4049       bool IsConcat = true;
4050       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4051       for (unsigned i = 0; i != MaskNumElts; ++i) {
4052         int Idx = Mask[i];
4053         if (Idx < 0)
4054           continue;
4055         // Ensure the indices in each SrcVT sized piece are sequential and that
4056         // the same source is used for the whole piece.
4057         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4058             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4059              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4060           IsConcat = false;
4061           break;
4062         }
4063         // Remember which source this index came from.
4064         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4065       }
4066 
4067       // The shuffle is concatenating multiple vectors together. Just emit
4068       // a CONCAT_VECTORS operation.
4069       if (IsConcat) {
4070         SmallVector<SDValue, 8> ConcatOps;
4071         for (auto Src : ConcatSrcs) {
4072           if (Src < 0)
4073             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4074           else if (Src == 0)
4075             ConcatOps.push_back(Src1);
4076           else
4077             ConcatOps.push_back(Src2);
4078         }
4079         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4080         return;
4081       }
4082     }
4083 
4084     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4085     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4086     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4087                                     PaddedMaskNumElts);
4088 
4089     // Pad both vectors with undefs to make them the same length as the mask.
4090     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4091 
4092     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4093     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4094     MOps1[0] = Src1;
4095     MOps2[0] = Src2;
4096 
4097     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4098     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4099 
4100     // Readjust mask for new input vector length.
4101     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4102     for (unsigned i = 0; i != MaskNumElts; ++i) {
4103       int Idx = Mask[i];
4104       if (Idx >= (int)SrcNumElts)
4105         Idx -= SrcNumElts - PaddedMaskNumElts;
4106       MappedOps[i] = Idx;
4107     }
4108 
4109     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4110 
4111     // If the concatenated vector was padded, extract a subvector with the
4112     // correct number of elements.
4113     if (MaskNumElts != PaddedMaskNumElts)
4114       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4115                            DAG.getVectorIdxConstant(0, DL));
4116 
4117     setValue(&I, Result);
4118     return;
4119   }
4120 
4121   if (SrcNumElts > MaskNumElts) {
4122     // Analyze the access pattern of the vector to see if we can extract
4123     // two subvectors and do the shuffle.
4124     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
4125     bool CanExtract = true;
4126     for (int Idx : Mask) {
4127       unsigned Input = 0;
4128       if (Idx < 0)
4129         continue;
4130 
4131       if (Idx >= (int)SrcNumElts) {
4132         Input = 1;
4133         Idx -= SrcNumElts;
4134       }
4135 
4136       // If all the indices come from the same MaskNumElts sized portion of
4137       // the sources we can use extract. Also make sure the extract wouldn't
4138       // extract past the end of the source.
4139       int NewStartIdx = alignDown(Idx, MaskNumElts);
4140       if (NewStartIdx + MaskNumElts > SrcNumElts ||
4141           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4142         CanExtract = false;
4143       // Make sure we always update StartIdx as we use it to track if all
4144       // elements are undef.
4145       StartIdx[Input] = NewStartIdx;
4146     }
4147 
4148     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4149       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4150       return;
4151     }
4152     if (CanExtract) {
4153       // Extract appropriate subvector and generate a vector shuffle
4154       for (unsigned Input = 0; Input < 2; ++Input) {
4155         SDValue &Src = Input == 0 ? Src1 : Src2;
4156         if (StartIdx[Input] < 0)
4157           Src = DAG.getUNDEF(VT);
4158         else {
4159           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4160                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
4161         }
4162       }
4163 
4164       // Calculate new mask.
4165       SmallVector<int, 8> MappedOps(Mask);
4166       for (int &Idx : MappedOps) {
4167         if (Idx >= (int)SrcNumElts)
4168           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4169         else if (Idx >= 0)
4170           Idx -= StartIdx[0];
4171       }
4172 
4173       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4174       return;
4175     }
4176   }
4177 
4178   // We can't use either concat vectors or extract subvectors so fall back to
4179   // replacing the shuffle with extract and build vector.
4180   // to insert and build vector.
4181   EVT EltVT = VT.getVectorElementType();
4182   SmallVector<SDValue,8> Ops;
4183   for (int Idx : Mask) {
4184     SDValue Res;
4185 
4186     if (Idx < 0) {
4187       Res = DAG.getUNDEF(EltVT);
4188     } else {
4189       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4190       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4191 
4192       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4193                         DAG.getVectorIdxConstant(Idx, DL));
4194     }
4195 
4196     Ops.push_back(Res);
4197   }
4198 
4199   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4200 }
4201 
visitInsertValue(const InsertValueInst & I)4202 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4203   ArrayRef<unsigned> Indices = I.getIndices();
4204   const Value *Op0 = I.getOperand(0);
4205   const Value *Op1 = I.getOperand(1);
4206   Type *AggTy = I.getType();
4207   Type *ValTy = Op1->getType();
4208   bool IntoUndef = isa<UndefValue>(Op0);
4209   bool FromUndef = isa<UndefValue>(Op1);
4210 
4211   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4212 
4213   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4214   SmallVector<EVT, 4> AggValueVTs;
4215   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4216   SmallVector<EVT, 4> ValValueVTs;
4217   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4218 
4219   unsigned NumAggValues = AggValueVTs.size();
4220   unsigned NumValValues = ValValueVTs.size();
4221   SmallVector<SDValue, 4> Values(NumAggValues);
4222 
4223   // Ignore an insertvalue that produces an empty object
4224   if (!NumAggValues) {
4225     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4226     return;
4227   }
4228 
4229   SDValue Agg = getValue(Op0);
4230   unsigned i = 0;
4231   // Copy the beginning value(s) from the original aggregate.
4232   for (; i != LinearIndex; ++i)
4233     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4234                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4235   // Copy values from the inserted value(s).
4236   if (NumValValues) {
4237     SDValue Val = getValue(Op1);
4238     for (; i != LinearIndex + NumValValues; ++i)
4239       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4240                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4241   }
4242   // Copy remaining value(s) from the original aggregate.
4243   for (; i != NumAggValues; ++i)
4244     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4245                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4246 
4247   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4248                            DAG.getVTList(AggValueVTs), Values));
4249 }
4250 
visitExtractValue(const ExtractValueInst & I)4251 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4252   ArrayRef<unsigned> Indices = I.getIndices();
4253   const Value *Op0 = I.getOperand(0);
4254   Type *AggTy = Op0->getType();
4255   Type *ValTy = I.getType();
4256   bool OutOfUndef = isa<UndefValue>(Op0);
4257 
4258   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4259 
4260   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4261   SmallVector<EVT, 4> ValValueVTs;
4262   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4263 
4264   unsigned NumValValues = ValValueVTs.size();
4265 
4266   // Ignore a extractvalue that produces an empty object
4267   if (!NumValValues) {
4268     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4269     return;
4270   }
4271 
4272   SmallVector<SDValue, 4> Values(NumValValues);
4273 
4274   SDValue Agg = getValue(Op0);
4275   // Copy out the selected value(s).
4276   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4277     Values[i - LinearIndex] =
4278       OutOfUndef ?
4279         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4280         SDValue(Agg.getNode(), Agg.getResNo() + i);
4281 
4282   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4283                            DAG.getVTList(ValValueVTs), Values));
4284 }
4285 
visitGetElementPtr(const User & I)4286 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4287   Value *Op0 = I.getOperand(0);
4288   // Note that the pointer operand may be a vector of pointers. Take the scalar
4289   // element which holds a pointer.
4290   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4291   SDValue N = getValue(Op0);
4292   SDLoc dl = getCurSDLoc();
4293   auto &TLI = DAG.getTargetLoweringInfo();
4294 
4295   // Normalize Vector GEP - all scalar operands should be converted to the
4296   // splat vector.
4297   bool IsVectorGEP = I.getType()->isVectorTy();
4298   ElementCount VectorElementCount =
4299       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4300                   : ElementCount::getFixed(0);
4301 
4302   if (IsVectorGEP && !N.getValueType().isVector()) {
4303     LLVMContext &Context = *DAG.getContext();
4304     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4305     N = DAG.getSplat(VT, dl, N);
4306   }
4307 
4308   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4309        GTI != E; ++GTI) {
4310     const Value *Idx = GTI.getOperand();
4311     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4312       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4313       if (Field) {
4314         // N = N + Offset
4315         uint64_t Offset =
4316             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4317 
4318         // In an inbounds GEP with an offset that is nonnegative even when
4319         // interpreted as signed, assume there is no unsigned overflow.
4320         SDNodeFlags Flags;
4321         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
4322           Flags.setNoUnsignedWrap(true);
4323 
4324         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4325                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4326       }
4327     } else {
4328       // IdxSize is the width of the arithmetic according to IR semantics.
4329       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4330       // (and fix up the result later).
4331       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4332       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4333       TypeSize ElementSize =
4334           GTI.getSequentialElementStride(DAG.getDataLayout());
4335       // We intentionally mask away the high bits here; ElementSize may not
4336       // fit in IdxTy.
4337       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4338       bool ElementScalable = ElementSize.isScalable();
4339 
4340       // If this is a scalar constant or a splat vector of constants,
4341       // handle it quickly.
4342       const auto *C = dyn_cast<Constant>(Idx);
4343       if (C && isa<VectorType>(C->getType()))
4344         C = C->getSplatValue();
4345 
4346       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4347       if (CI && CI->isZero())
4348         continue;
4349       if (CI && !ElementScalable) {
4350         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4351         LLVMContext &Context = *DAG.getContext();
4352         SDValue OffsVal;
4353         if (IsVectorGEP)
4354           OffsVal = DAG.getConstant(
4355               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4356         else
4357           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4358 
4359         // In an inbounds GEP with an offset that is nonnegative even when
4360         // interpreted as signed, assume there is no unsigned overflow.
4361         SDNodeFlags Flags;
4362         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4363           Flags.setNoUnsignedWrap(true);
4364 
4365         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4366 
4367         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4368         continue;
4369       }
4370 
4371       // N = N + Idx * ElementMul;
4372       SDValue IdxN = getValue(Idx);
4373 
4374       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4375         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4376                                   VectorElementCount);
4377         IdxN = DAG.getSplat(VT, dl, IdxN);
4378       }
4379 
4380       // If the index is smaller or larger than intptr_t, truncate or extend
4381       // it.
4382       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4383 
4384       if (ElementScalable) {
4385         EVT VScaleTy = N.getValueType().getScalarType();
4386         SDValue VScale = DAG.getNode(
4387             ISD::VSCALE, dl, VScaleTy,
4388             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4389         if (IsVectorGEP)
4390           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4391         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4392       } else {
4393         // If this is a multiply by a power of two, turn it into a shl
4394         // immediately.  This is a very common case.
4395         if (ElementMul != 1) {
4396           if (ElementMul.isPowerOf2()) {
4397             unsigned Amt = ElementMul.logBase2();
4398             IdxN = DAG.getNode(ISD::SHL, dl,
4399                                N.getValueType(), IdxN,
4400                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4401           } else {
4402             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4403                                             IdxN.getValueType());
4404             IdxN = DAG.getNode(ISD::MUL, dl,
4405                                N.getValueType(), IdxN, Scale);
4406           }
4407         }
4408       }
4409 
4410       N = DAG.getNode(ISD::ADD, dl,
4411                       N.getValueType(), N, IdxN);
4412     }
4413   }
4414 
4415   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4416   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4417   if (IsVectorGEP) {
4418     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4419     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4420   }
4421 
4422   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4423     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4424 
4425   setValue(&I, N);
4426 }
4427 
visitAlloca(const AllocaInst & I)4428 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4429   // If this is a fixed sized alloca in the entry block of the function,
4430   // allocate it statically on the stack.
4431   if (FuncInfo.StaticAllocaMap.count(&I))
4432     return;   // getValue will auto-populate this.
4433 
4434   SDLoc dl = getCurSDLoc();
4435   Type *Ty = I.getAllocatedType();
4436   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4437   auto &DL = DAG.getDataLayout();
4438   TypeSize TySize = DL.getTypeAllocSize(Ty);
4439   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4440 
4441   SDValue AllocSize = getValue(I.getArraySize());
4442 
4443   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4444   if (AllocSize.getValueType() != IntPtr)
4445     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4446 
4447   if (TySize.isScalable())
4448     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4449                             DAG.getVScale(dl, IntPtr,
4450                                           APInt(IntPtr.getScalarSizeInBits(),
4451                                                 TySize.getKnownMinValue())));
4452   else {
4453     SDValue TySizeValue =
4454         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4455     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4456                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4457   }
4458 
4459   // Handle alignment.  If the requested alignment is less than or equal to
4460   // the stack alignment, ignore it.  If the size is greater than or equal to
4461   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4462   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4463   if (*Alignment <= StackAlign)
4464     Alignment = std::nullopt;
4465 
4466   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4467   // Round the size of the allocation up to the stack alignment size
4468   // by add SA-1 to the size. This doesn't overflow because we're computing
4469   // an address inside an alloca.
4470   SDNodeFlags Flags;
4471   Flags.setNoUnsignedWrap(true);
4472   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4473                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4474 
4475   // Mask out the low bits for alignment purposes.
4476   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4477                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4478 
4479   SDValue Ops[] = {
4480       getRoot(), AllocSize,
4481       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4482   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4483   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4484   setValue(&I, DSA);
4485   DAG.setRoot(DSA.getValue(1));
4486 
4487   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4488 }
4489 
getRangeMetadata(const Instruction & I)4490 static const MDNode *getRangeMetadata(const Instruction &I) {
4491   // If !noundef is not present, then !range violation results in a poison
4492   // value rather than immediate undefined behavior. In theory, transferring
4493   // these annotations to SDAG is fine, but in practice there are key SDAG
4494   // transforms that are known not to be poison-safe, such as folding logical
4495   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4496   // also present.
4497   if (!I.hasMetadata(LLVMContext::MD_noundef))
4498     return nullptr;
4499   return I.getMetadata(LLVMContext::MD_range);
4500 }
4501 
getRange(const Instruction & I)4502 static std::optional<ConstantRange> getRange(const Instruction &I) {
4503   if (const auto *CB = dyn_cast<CallBase>(&I)) {
4504     // see comment in getRangeMetadata about this check
4505     if (CB->hasRetAttr(Attribute::NoUndef))
4506       return CB->getRange();
4507   }
4508   if (const MDNode *Range = getRangeMetadata(I))
4509     return getConstantRangeFromMetadata(*Range);
4510   return std::nullopt;
4511 }
4512 
visitLoad(const LoadInst & I)4513 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4514   if (I.isAtomic())
4515     return visitAtomicLoad(I);
4516 
4517   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4518   const Value *SV = I.getOperand(0);
4519   if (TLI.supportSwiftError()) {
4520     // Swifterror values can come from either a function parameter with
4521     // swifterror attribute or an alloca with swifterror attribute.
4522     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4523       if (Arg->hasSwiftErrorAttr())
4524         return visitLoadFromSwiftError(I);
4525     }
4526 
4527     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4528       if (Alloca->isSwiftError())
4529         return visitLoadFromSwiftError(I);
4530     }
4531   }
4532 
4533   SDValue Ptr = getValue(SV);
4534 
4535   Type *Ty = I.getType();
4536   SmallVector<EVT, 4> ValueVTs, MemVTs;
4537   SmallVector<TypeSize, 4> Offsets;
4538   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4539   unsigned NumValues = ValueVTs.size();
4540   if (NumValues == 0)
4541     return;
4542 
4543   Align Alignment = I.getAlign();
4544   AAMDNodes AAInfo = I.getAAMetadata();
4545   const MDNode *Ranges = getRangeMetadata(I);
4546   bool isVolatile = I.isVolatile();
4547   MachineMemOperand::Flags MMOFlags =
4548       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4549 
4550   SDValue Root;
4551   bool ConstantMemory = false;
4552   if (isVolatile)
4553     // Serialize volatile loads with other side effects.
4554     Root = getRoot();
4555   else if (NumValues > MaxParallelChains)
4556     Root = getMemoryRoot();
4557   else if (AA &&
4558            AA->pointsToConstantMemory(MemoryLocation(
4559                SV,
4560                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4561                AAInfo))) {
4562     // Do not serialize (non-volatile) loads of constant memory with anything.
4563     Root = DAG.getEntryNode();
4564     ConstantMemory = true;
4565     MMOFlags |= MachineMemOperand::MOInvariant;
4566   } else {
4567     // Do not serialize non-volatile loads against each other.
4568     Root = DAG.getRoot();
4569   }
4570 
4571   SDLoc dl = getCurSDLoc();
4572 
4573   if (isVolatile)
4574     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4575 
4576   SmallVector<SDValue, 4> Values(NumValues);
4577   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4578 
4579   unsigned ChainI = 0;
4580   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4581     // Serializing loads here may result in excessive register pressure, and
4582     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4583     // could recover a bit by hoisting nodes upward in the chain by recognizing
4584     // they are side-effect free or do not alias. The optimizer should really
4585     // avoid this case by converting large object/array copies to llvm.memcpy
4586     // (MaxParallelChains should always remain as failsafe).
4587     if (ChainI == MaxParallelChains) {
4588       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4589       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4590                                   ArrayRef(Chains.data(), ChainI));
4591       Root = Chain;
4592       ChainI = 0;
4593     }
4594 
4595     // TODO: MachinePointerInfo only supports a fixed length offset.
4596     MachinePointerInfo PtrInfo =
4597         !Offsets[i].isScalable() || Offsets[i].isZero()
4598             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4599             : MachinePointerInfo();
4600 
4601     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4602     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4603                             MMOFlags, AAInfo, Ranges);
4604     Chains[ChainI] = L.getValue(1);
4605 
4606     if (MemVTs[i] != ValueVTs[i])
4607       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4608 
4609     Values[i] = L;
4610   }
4611 
4612   if (!ConstantMemory) {
4613     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4614                                 ArrayRef(Chains.data(), ChainI));
4615     if (isVolatile)
4616       DAG.setRoot(Chain);
4617     else
4618       PendingLoads.push_back(Chain);
4619   }
4620 
4621   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4622                            DAG.getVTList(ValueVTs), Values));
4623 }
4624 
visitStoreToSwiftError(const StoreInst & I)4625 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4626   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4627          "call visitStoreToSwiftError when backend supports swifterror");
4628 
4629   SmallVector<EVT, 4> ValueVTs;
4630   SmallVector<uint64_t, 4> Offsets;
4631   const Value *SrcV = I.getOperand(0);
4632   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4633                   SrcV->getType(), ValueVTs, &Offsets, 0);
4634   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4635          "expect a single EVT for swifterror");
4636 
4637   SDValue Src = getValue(SrcV);
4638   // Create a virtual register, then update the virtual register.
4639   Register VReg =
4640       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4641   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4642   // Chain can be getRoot or getControlRoot.
4643   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4644                                       SDValue(Src.getNode(), Src.getResNo()));
4645   DAG.setRoot(CopyNode);
4646 }
4647 
visitLoadFromSwiftError(const LoadInst & I)4648 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4649   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4650          "call visitLoadFromSwiftError when backend supports swifterror");
4651 
4652   assert(!I.isVolatile() &&
4653          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4654          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4655          "Support volatile, non temporal, invariant for load_from_swift_error");
4656 
4657   const Value *SV = I.getOperand(0);
4658   Type *Ty = I.getType();
4659   assert(
4660       (!AA ||
4661        !AA->pointsToConstantMemory(MemoryLocation(
4662            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4663            I.getAAMetadata()))) &&
4664       "load_from_swift_error should not be constant memory");
4665 
4666   SmallVector<EVT, 4> ValueVTs;
4667   SmallVector<uint64_t, 4> Offsets;
4668   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4669                   ValueVTs, &Offsets, 0);
4670   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4671          "expect a single EVT for swifterror");
4672 
4673   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4674   SDValue L = DAG.getCopyFromReg(
4675       getRoot(), getCurSDLoc(),
4676       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4677 
4678   setValue(&I, L);
4679 }
4680 
visitStore(const StoreInst & I)4681 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4682   if (I.isAtomic())
4683     return visitAtomicStore(I);
4684 
4685   const Value *SrcV = I.getOperand(0);
4686   const Value *PtrV = I.getOperand(1);
4687 
4688   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4689   if (TLI.supportSwiftError()) {
4690     // Swifterror values can come from either a function parameter with
4691     // swifterror attribute or an alloca with swifterror attribute.
4692     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4693       if (Arg->hasSwiftErrorAttr())
4694         return visitStoreToSwiftError(I);
4695     }
4696 
4697     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4698       if (Alloca->isSwiftError())
4699         return visitStoreToSwiftError(I);
4700     }
4701   }
4702 
4703   SmallVector<EVT, 4> ValueVTs, MemVTs;
4704   SmallVector<TypeSize, 4> Offsets;
4705   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4706                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4707   unsigned NumValues = ValueVTs.size();
4708   if (NumValues == 0)
4709     return;
4710 
4711   // Get the lowered operands. Note that we do this after
4712   // checking if NumResults is zero, because with zero results
4713   // the operands won't have values in the map.
4714   SDValue Src = getValue(SrcV);
4715   SDValue Ptr = getValue(PtrV);
4716 
4717   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4718   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4719   SDLoc dl = getCurSDLoc();
4720   Align Alignment = I.getAlign();
4721   AAMDNodes AAInfo = I.getAAMetadata();
4722 
4723   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4724 
4725   unsigned ChainI = 0;
4726   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4727     // See visitLoad comments.
4728     if (ChainI == MaxParallelChains) {
4729       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4730                                   ArrayRef(Chains.data(), ChainI));
4731       Root = Chain;
4732       ChainI = 0;
4733     }
4734 
4735     // TODO: MachinePointerInfo only supports a fixed length offset.
4736     MachinePointerInfo PtrInfo =
4737         !Offsets[i].isScalable() || Offsets[i].isZero()
4738             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4739             : MachinePointerInfo();
4740 
4741     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4742     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4743     if (MemVTs[i] != ValueVTs[i])
4744       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4745     SDValue St =
4746         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4747     Chains[ChainI] = St;
4748   }
4749 
4750   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4751                                   ArrayRef(Chains.data(), ChainI));
4752   setValue(&I, StoreNode);
4753   DAG.setRoot(StoreNode);
4754 }
4755 
visitMaskedStore(const CallInst & I,bool IsCompressing)4756 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4757                                            bool IsCompressing) {
4758   SDLoc sdl = getCurSDLoc();
4759 
4760   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4761                                Align &Alignment) {
4762     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4763     Src0 = I.getArgOperand(0);
4764     Ptr = I.getArgOperand(1);
4765     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue();
4766     Mask = I.getArgOperand(3);
4767   };
4768   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4769                                     Align &Alignment) {
4770     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4771     Src0 = I.getArgOperand(0);
4772     Ptr = I.getArgOperand(1);
4773     Mask = I.getArgOperand(2);
4774     Alignment = I.getParamAlign(1).valueOrOne();
4775   };
4776 
4777   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4778   Align Alignment;
4779   if (IsCompressing)
4780     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4781   else
4782     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4783 
4784   SDValue Ptr = getValue(PtrOperand);
4785   SDValue Src0 = getValue(Src0Operand);
4786   SDValue Mask = getValue(MaskOperand);
4787   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4788 
4789   EVT VT = Src0.getValueType();
4790 
4791   auto MMOFlags = MachineMemOperand::MOStore;
4792   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4793     MMOFlags |= MachineMemOperand::MONonTemporal;
4794 
4795   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4796       MachinePointerInfo(PtrOperand), MMOFlags,
4797       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4798 
4799   const auto &TLI = DAG.getTargetLoweringInfo();
4800   const auto &TTI =
4801       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4802   SDValue StoreNode =
4803       !IsCompressing &&
4804               TTI.hasConditionalLoadStoreForType(I.getArgOperand(0)->getType())
4805           ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
4806                                  Mask)
4807           : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
4808                                VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
4809                                IsCompressing);
4810   DAG.setRoot(StoreNode);
4811   setValue(&I, StoreNode);
4812 }
4813 
4814 // Get a uniform base for the Gather/Scatter intrinsic.
4815 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4816 // We try to represent it as a base pointer + vector of indices.
4817 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4818 // The first operand of the GEP may be a single pointer or a vector of pointers
4819 // Example:
4820 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4821 //  or
4822 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4823 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4824 //
4825 // When the first GEP operand is a single pointer - it is the uniform base we
4826 // are looking for. If first operand of the GEP is a splat vector - we
4827 // extract the splat value and use it as a uniform base.
4828 // In all other cases the function returns 'false'.
getUniformBase(const Value * Ptr,SDValue & Base,SDValue & Index,ISD::MemIndexType & IndexType,SDValue & Scale,SelectionDAGBuilder * SDB,const BasicBlock * CurBB,uint64_t ElemSize)4829 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4830                            ISD::MemIndexType &IndexType, SDValue &Scale,
4831                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4832                            uint64_t ElemSize) {
4833   SelectionDAG& DAG = SDB->DAG;
4834   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4835   const DataLayout &DL = DAG.getDataLayout();
4836 
4837   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4838 
4839   // Handle splat constant pointer.
4840   if (auto *C = dyn_cast<Constant>(Ptr)) {
4841     C = C->getSplatValue();
4842     if (!C)
4843       return false;
4844 
4845     Base = SDB->getValue(C);
4846 
4847     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4848     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4849     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4850     IndexType = ISD::SIGNED_SCALED;
4851     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4852     return true;
4853   }
4854 
4855   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4856   if (!GEP || GEP->getParent() != CurBB)
4857     return false;
4858 
4859   if (GEP->getNumOperands() != 2)
4860     return false;
4861 
4862   const Value *BasePtr = GEP->getPointerOperand();
4863   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4864 
4865   // Make sure the base is scalar and the index is a vector.
4866   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4867     return false;
4868 
4869   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4870   if (ScaleVal.isScalable())
4871     return false;
4872 
4873   // Target may not support the required addressing mode.
4874   if (ScaleVal != 1 &&
4875       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4876     return false;
4877 
4878   Base = SDB->getValue(BasePtr);
4879   Index = SDB->getValue(IndexVal);
4880   IndexType = ISD::SIGNED_SCALED;
4881 
4882   Scale =
4883       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4884   return true;
4885 }
4886 
visitMaskedScatter(const CallInst & I)4887 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4888   SDLoc sdl = getCurSDLoc();
4889 
4890   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4891   const Value *Ptr = I.getArgOperand(1);
4892   SDValue Src0 = getValue(I.getArgOperand(0));
4893   SDValue Mask = getValue(I.getArgOperand(3));
4894   EVT VT = Src0.getValueType();
4895   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4896                         ->getMaybeAlignValue()
4897                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4898   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4899 
4900   SDValue Base;
4901   SDValue Index;
4902   ISD::MemIndexType IndexType;
4903   SDValue Scale;
4904   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4905                                     I.getParent(), VT.getScalarStoreSize());
4906 
4907   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4908   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4909       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4910       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4911   if (!UniformBase) {
4912     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4913     Index = getValue(Ptr);
4914     IndexType = ISD::SIGNED_SCALED;
4915     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4916   }
4917 
4918   EVT IdxVT = Index.getValueType();
4919   EVT EltTy = IdxVT.getVectorElementType();
4920   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4921     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4922     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4923   }
4924 
4925   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4926   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4927                                          Ops, MMO, IndexType, false);
4928   DAG.setRoot(Scatter);
4929   setValue(&I, Scatter);
4930 }
4931 
visitMaskedLoad(const CallInst & I,bool IsExpanding)4932 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4933   SDLoc sdl = getCurSDLoc();
4934 
4935   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4936                               Align &Alignment) {
4937     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4938     Ptr = I.getArgOperand(0);
4939     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue();
4940     Mask = I.getArgOperand(2);
4941     Src0 = I.getArgOperand(3);
4942   };
4943   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4944                                  Align &Alignment) {
4945     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4946     Ptr = I.getArgOperand(0);
4947     Alignment = I.getParamAlign(0).valueOrOne();
4948     Mask = I.getArgOperand(1);
4949     Src0 = I.getArgOperand(2);
4950   };
4951 
4952   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4953   Align Alignment;
4954   if (IsExpanding)
4955     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4956   else
4957     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4958 
4959   SDValue Ptr = getValue(PtrOperand);
4960   SDValue Src0 = getValue(Src0Operand);
4961   SDValue Mask = getValue(MaskOperand);
4962   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4963 
4964   EVT VT = Src0.getValueType();
4965   AAMDNodes AAInfo = I.getAAMetadata();
4966   const MDNode *Ranges = getRangeMetadata(I);
4967 
4968   // Do not serialize masked loads of constant memory with anything.
4969   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4970   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4971 
4972   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4973 
4974   auto MMOFlags = MachineMemOperand::MOLoad;
4975   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4976     MMOFlags |= MachineMemOperand::MONonTemporal;
4977 
4978   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4979       MachinePointerInfo(PtrOperand), MMOFlags,
4980       LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges);
4981 
4982   const auto &TLI = DAG.getTargetLoweringInfo();
4983   const auto &TTI =
4984       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4985   // The Load/Res may point to different values and both of them are output
4986   // variables.
4987   SDValue Load;
4988   SDValue Res;
4989   if (!IsExpanding &&
4990       TTI.hasConditionalLoadStoreForType(Src0Operand->getType()))
4991     Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
4992   else
4993     Res = Load =
4994         DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4995                           ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4996   if (AddToChain)
4997     PendingLoads.push_back(Load.getValue(1));
4998   setValue(&I, Res);
4999 }
5000 
visitMaskedGather(const CallInst & I)5001 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5002   SDLoc sdl = getCurSDLoc();
5003 
5004   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
5005   const Value *Ptr = I.getArgOperand(0);
5006   SDValue Src0 = getValue(I.getArgOperand(3));
5007   SDValue Mask = getValue(I.getArgOperand(2));
5008 
5009   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5010   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5011   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
5012                         ->getMaybeAlignValue()
5013                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
5014 
5015   const MDNode *Ranges = getRangeMetadata(I);
5016 
5017   SDValue Root = DAG.getRoot();
5018   SDValue Base;
5019   SDValue Index;
5020   ISD::MemIndexType IndexType;
5021   SDValue Scale;
5022   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
5023                                     I.getParent(), VT.getScalarStoreSize());
5024   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5025   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5026       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5027       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(),
5028       Ranges);
5029 
5030   if (!UniformBase) {
5031     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5032     Index = getValue(Ptr);
5033     IndexType = ISD::SIGNED_SCALED;
5034     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5035   }
5036 
5037   EVT IdxVT = Index.getValueType();
5038   EVT EltTy = IdxVT.getVectorElementType();
5039   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5040     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
5041     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5042   }
5043 
5044   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5045   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
5046                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
5047 
5048   PendingLoads.push_back(Gather.getValue(1));
5049   setValue(&I, Gather);
5050 }
5051 
visitAtomicCmpXchg(const AtomicCmpXchgInst & I)5052 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5053   SDLoc dl = getCurSDLoc();
5054   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5055   AtomicOrdering FailureOrdering = I.getFailureOrdering();
5056   SyncScope::ID SSID = I.getSyncScopeID();
5057 
5058   SDValue InChain = getRoot();
5059 
5060   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5061   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5062 
5063   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5064   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5065 
5066   MachineFunction &MF = DAG.getMachineFunction();
5067   MachineMemOperand *MMO = MF.getMachineMemOperand(
5068       MachinePointerInfo(I.getPointerOperand()), Flags,
5069       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5070       AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering);
5071 
5072   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5073                                    dl, MemVT, VTs, InChain,
5074                                    getValue(I.getPointerOperand()),
5075                                    getValue(I.getCompareOperand()),
5076                                    getValue(I.getNewValOperand()), MMO);
5077 
5078   SDValue OutChain = L.getValue(2);
5079 
5080   setValue(&I, L);
5081   DAG.setRoot(OutChain);
5082 }
5083 
visitAtomicRMW(const AtomicRMWInst & I)5084 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5085   SDLoc dl = getCurSDLoc();
5086   ISD::NodeType NT;
5087   switch (I.getOperation()) {
5088   default: llvm_unreachable("Unknown atomicrmw operation");
5089   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5090   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5091   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5092   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5093   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5094   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5095   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5096   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5097   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5098   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5099   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5100   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5101   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5102   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5103   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5104   case AtomicRMWInst::UIncWrap:
5105     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5106     break;
5107   case AtomicRMWInst::UDecWrap:
5108     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5109     break;
5110   }
5111   AtomicOrdering Ordering = I.getOrdering();
5112   SyncScope::ID SSID = I.getSyncScopeID();
5113 
5114   SDValue InChain = getRoot();
5115 
5116   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5117   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5118   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5119 
5120   MachineFunction &MF = DAG.getMachineFunction();
5121   MachineMemOperand *MMO = MF.getMachineMemOperand(
5122       MachinePointerInfo(I.getPointerOperand()), Flags,
5123       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5124       AAMDNodes(), nullptr, SSID, Ordering);
5125 
5126   SDValue L =
5127     DAG.getAtomic(NT, dl, MemVT, InChain,
5128                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5129                   MMO);
5130 
5131   SDValue OutChain = L.getValue(1);
5132 
5133   setValue(&I, L);
5134   DAG.setRoot(OutChain);
5135 }
5136 
visitFence(const FenceInst & I)5137 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5138   SDLoc dl = getCurSDLoc();
5139   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5140   SDValue Ops[3];
5141   Ops[0] = getRoot();
5142   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5143                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5144   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5145                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5146   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5147   setValue(&I, N);
5148   DAG.setRoot(N);
5149 }
5150 
visitAtomicLoad(const LoadInst & I)5151 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5152   SDLoc dl = getCurSDLoc();
5153   AtomicOrdering Order = I.getOrdering();
5154   SyncScope::ID SSID = I.getSyncScopeID();
5155 
5156   SDValue InChain = getRoot();
5157 
5158   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5159   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5160   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5161 
5162   if (!TLI.supportsUnalignedAtomics() &&
5163       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5164     report_fatal_error("Cannot generate unaligned atomic load");
5165 
5166   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5167 
5168   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5169       MachinePointerInfo(I.getPointerOperand()), Flags,
5170       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5171       nullptr, SSID, Order);
5172 
5173   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5174 
5175   SDValue Ptr = getValue(I.getPointerOperand());
5176   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5177                             Ptr, MMO);
5178 
5179   SDValue OutChain = L.getValue(1);
5180   if (MemVT != VT)
5181     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5182 
5183   setValue(&I, L);
5184   DAG.setRoot(OutChain);
5185 }
5186 
visitAtomicStore(const StoreInst & I)5187 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5188   SDLoc dl = getCurSDLoc();
5189 
5190   AtomicOrdering Ordering = I.getOrdering();
5191   SyncScope::ID SSID = I.getSyncScopeID();
5192 
5193   SDValue InChain = getRoot();
5194 
5195   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5196   EVT MemVT =
5197       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5198 
5199   if (!TLI.supportsUnalignedAtomics() &&
5200       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5201     report_fatal_error("Cannot generate unaligned atomic store");
5202 
5203   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5204 
5205   MachineFunction &MF = DAG.getMachineFunction();
5206   MachineMemOperand *MMO = MF.getMachineMemOperand(
5207       MachinePointerInfo(I.getPointerOperand()), Flags,
5208       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5209       nullptr, SSID, Ordering);
5210 
5211   SDValue Val = getValue(I.getValueOperand());
5212   if (Val.getValueType() != MemVT)
5213     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5214   SDValue Ptr = getValue(I.getPointerOperand());
5215 
5216   SDValue OutChain =
5217       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5218 
5219   setValue(&I, OutChain);
5220   DAG.setRoot(OutChain);
5221 }
5222 
5223 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5224 /// node.
visitTargetIntrinsic(const CallInst & I,unsigned Intrinsic)5225 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5226                                                unsigned Intrinsic) {
5227   // Ignore the callsite's attributes. A specific call site may be marked with
5228   // readnone, but the lowering code will expect the chain based on the
5229   // definition.
5230   const Function *F = I.getCalledFunction();
5231   bool HasChain = !F->doesNotAccessMemory();
5232   bool OnlyLoad = HasChain && F->onlyReadsMemory();
5233 
5234   // Build the operand list.
5235   SmallVector<SDValue, 8> Ops;
5236   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5237     if (OnlyLoad) {
5238       // We don't need to serialize loads against other loads.
5239       Ops.push_back(DAG.getRoot());
5240     } else {
5241       Ops.push_back(getRoot());
5242     }
5243   }
5244 
5245   // Info is set by getTgtMemIntrinsic
5246   TargetLowering::IntrinsicInfo Info;
5247   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5248   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5249                                                DAG.getMachineFunction(),
5250                                                Intrinsic);
5251 
5252   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5253   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5254       Info.opc == ISD::INTRINSIC_W_CHAIN)
5255     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5256                                         TLI.getPointerTy(DAG.getDataLayout())));
5257 
5258   // Add all operands of the call to the operand list.
5259   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5260     const Value *Arg = I.getArgOperand(i);
5261     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5262       Ops.push_back(getValue(Arg));
5263       continue;
5264     }
5265 
5266     // Use TargetConstant instead of a regular constant for immarg.
5267     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5268     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5269       assert(CI->getBitWidth() <= 64 &&
5270              "large intrinsic immediates not handled");
5271       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5272     } else {
5273       Ops.push_back(
5274           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5275     }
5276   }
5277 
5278   SmallVector<EVT, 4> ValueVTs;
5279   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5280 
5281   if (HasChain)
5282     ValueVTs.push_back(MVT::Other);
5283 
5284   SDVTList VTs = DAG.getVTList(ValueVTs);
5285 
5286   // Propagate fast-math-flags from IR to node(s).
5287   SDNodeFlags Flags;
5288   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5289     Flags.copyFMF(*FPMO);
5290   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5291 
5292   // Create the node.
5293   SDValue Result;
5294 
5295   if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5296     auto *Token = Bundle->Inputs[0].get();
5297     SDValue ConvControlToken = getValue(Token);
5298     assert(Ops.back().getValueType() != MVT::Glue &&
5299            "Did not expected another glue node here.");
5300     ConvControlToken =
5301         DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5302     Ops.push_back(ConvControlToken);
5303   }
5304 
5305   // In some cases, custom collection of operands from CallInst I may be needed.
5306   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5307   if (IsTgtIntrinsic) {
5308     // This is target intrinsic that touches memory
5309     //
5310     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5311     //       didn't yield anything useful.
5312     MachinePointerInfo MPI;
5313     if (Info.ptrVal)
5314       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5315     else if (Info.fallbackAddressSpace)
5316       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5317     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5318                                      Info.memVT, MPI, Info.align, Info.flags,
5319                                      Info.size, I.getAAMetadata());
5320   } else if (!HasChain) {
5321     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5322   } else if (!I.getType()->isVoidTy()) {
5323     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5324   } else {
5325     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5326   }
5327 
5328   if (HasChain) {
5329     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5330     if (OnlyLoad)
5331       PendingLoads.push_back(Chain);
5332     else
5333       DAG.setRoot(Chain);
5334   }
5335 
5336   if (!I.getType()->isVoidTy()) {
5337     if (!isa<VectorType>(I.getType()))
5338       Result = lowerRangeToAssertZExt(DAG, I, Result);
5339 
5340     MaybeAlign Alignment = I.getRetAlign();
5341 
5342     // Insert `assertalign` node if there's an alignment.
5343     if (InsertAssertAlign && Alignment) {
5344       Result =
5345           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5346     }
5347   }
5348 
5349   setValue(&I, Result);
5350 }
5351 
5352 /// GetSignificand - Get the significand and build it into a floating-point
5353 /// number with exponent of 1:
5354 ///
5355 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5356 ///
5357 /// where Op is the hexadecimal representation of floating point value.
GetSignificand(SelectionDAG & DAG,SDValue Op,const SDLoc & dl)5358 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5359   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5360                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5361   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5362                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5363   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5364 }
5365 
5366 /// GetExponent - Get the exponent:
5367 ///
5368 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5369 ///
5370 /// where Op is the hexadecimal representation of floating point value.
GetExponent(SelectionDAG & DAG,SDValue Op,const TargetLowering & TLI,const SDLoc & dl)5371 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5372                            const TargetLowering &TLI, const SDLoc &dl) {
5373   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5374                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5375   SDValue t1 = DAG.getNode(
5376       ISD::SRL, dl, MVT::i32, t0,
5377       DAG.getConstant(23, dl,
5378                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5379   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5380                            DAG.getConstant(127, dl, MVT::i32));
5381   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5382 }
5383 
5384 /// getF32Constant - Get 32-bit floating point constant.
getF32Constant(SelectionDAG & DAG,unsigned Flt,const SDLoc & dl)5385 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5386                               const SDLoc &dl) {
5387   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5388                            MVT::f32);
5389 }
5390 
getLimitedPrecisionExp2(SDValue t0,const SDLoc & dl,SelectionDAG & DAG)5391 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5392                                        SelectionDAG &DAG) {
5393   // TODO: What fast-math-flags should be set on the floating-point nodes?
5394 
5395   //   IntegerPartOfX = ((int32_t)(t0);
5396   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5397 
5398   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5399   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5400   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5401 
5402   //   IntegerPartOfX <<= 23;
5403   IntegerPartOfX =
5404       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5405                   DAG.getConstant(23, dl,
5406                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5407                                       MVT::i32, DAG.getDataLayout())));
5408 
5409   SDValue TwoToFractionalPartOfX;
5410   if (LimitFloatPrecision <= 6) {
5411     // For floating-point precision of 6:
5412     //
5413     //   TwoToFractionalPartOfX =
5414     //     0.997535578f +
5415     //       (0.735607626f + 0.252464424f * x) * x;
5416     //
5417     // error 0.0144103317, which is 6 bits
5418     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5419                              getF32Constant(DAG, 0x3e814304, dl));
5420     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5421                              getF32Constant(DAG, 0x3f3c50c8, dl));
5422     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5423     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5424                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5425   } else if (LimitFloatPrecision <= 12) {
5426     // For floating-point precision of 12:
5427     //
5428     //   TwoToFractionalPartOfX =
5429     //     0.999892986f +
5430     //       (0.696457318f +
5431     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5432     //
5433     // error 0.000107046256, which is 13 to 14 bits
5434     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5435                              getF32Constant(DAG, 0x3da235e3, dl));
5436     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5437                              getF32Constant(DAG, 0x3e65b8f3, dl));
5438     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5439     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5440                              getF32Constant(DAG, 0x3f324b07, dl));
5441     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5442     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5443                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5444   } else { // LimitFloatPrecision <= 18
5445     // For floating-point precision of 18:
5446     //
5447     //   TwoToFractionalPartOfX =
5448     //     0.999999982f +
5449     //       (0.693148872f +
5450     //         (0.240227044f +
5451     //           (0.554906021e-1f +
5452     //             (0.961591928e-2f +
5453     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5454     // error 2.47208000*10^(-7), which is better than 18 bits
5455     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5456                              getF32Constant(DAG, 0x3924b03e, dl));
5457     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5458                              getF32Constant(DAG, 0x3ab24b87, dl));
5459     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5460     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5461                              getF32Constant(DAG, 0x3c1d8c17, dl));
5462     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5463     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5464                              getF32Constant(DAG, 0x3d634a1d, dl));
5465     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5466     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5467                              getF32Constant(DAG, 0x3e75fe14, dl));
5468     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5469     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5470                               getF32Constant(DAG, 0x3f317234, dl));
5471     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5472     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5473                                          getF32Constant(DAG, 0x3f800000, dl));
5474   }
5475 
5476   // Add the exponent into the result in integer domain.
5477   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5478   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5479                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5480 }
5481 
5482 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5483 /// limited-precision mode.
expandExp(const SDLoc & dl,SDValue Op,SelectionDAG & DAG,const TargetLowering & TLI,SDNodeFlags Flags)5484 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5485                          const TargetLowering &TLI, SDNodeFlags Flags) {
5486   if (Op.getValueType() == MVT::f32 &&
5487       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5488 
5489     // Put the exponent in the right bit position for later addition to the
5490     // final result:
5491     //
5492     // t0 = Op * log2(e)
5493 
5494     // TODO: What fast-math-flags should be set here?
5495     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5496                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5497     return getLimitedPrecisionExp2(t0, dl, DAG);
5498   }
5499 
5500   // No special expansion.
5501   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5502 }
5503 
5504 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5505 /// limited-precision mode.
expandLog(const SDLoc & dl,SDValue Op,SelectionDAG & DAG,const TargetLowering & TLI,SDNodeFlags Flags)5506 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5507                          const TargetLowering &TLI, SDNodeFlags Flags) {
5508   // TODO: What fast-math-flags should be set on the floating-point nodes?
5509 
5510   if (Op.getValueType() == MVT::f32 &&
5511       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5512     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5513 
5514     // Scale the exponent by log(2).
5515     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5516     SDValue LogOfExponent =
5517         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5518                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5519 
5520     // Get the significand and build it into a floating-point number with
5521     // exponent of 1.
5522     SDValue X = GetSignificand(DAG, Op1, dl);
5523 
5524     SDValue LogOfMantissa;
5525     if (LimitFloatPrecision <= 6) {
5526       // For floating-point precision of 6:
5527       //
5528       //   LogofMantissa =
5529       //     -1.1609546f +
5530       //       (1.4034025f - 0.23903021f * x) * x;
5531       //
5532       // error 0.0034276066, which is better than 8 bits
5533       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5534                                getF32Constant(DAG, 0xbe74c456, dl));
5535       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5536                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5537       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5538       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5539                                   getF32Constant(DAG, 0x3f949a29, dl));
5540     } else if (LimitFloatPrecision <= 12) {
5541       // For floating-point precision of 12:
5542       //
5543       //   LogOfMantissa =
5544       //     -1.7417939f +
5545       //       (2.8212026f +
5546       //         (-1.4699568f +
5547       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5548       //
5549       // error 0.000061011436, which is 14 bits
5550       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5551                                getF32Constant(DAG, 0xbd67b6d6, dl));
5552       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5553                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5554       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5555       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5556                                getF32Constant(DAG, 0x3fbc278b, dl));
5557       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5558       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5559                                getF32Constant(DAG, 0x40348e95, dl));
5560       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5561       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5562                                   getF32Constant(DAG, 0x3fdef31a, dl));
5563     } else { // LimitFloatPrecision <= 18
5564       // For floating-point precision of 18:
5565       //
5566       //   LogOfMantissa =
5567       //     -2.1072184f +
5568       //       (4.2372794f +
5569       //         (-3.7029485f +
5570       //           (2.2781945f +
5571       //             (-0.87823314f +
5572       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5573       //
5574       // error 0.0000023660568, which is better than 18 bits
5575       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5576                                getF32Constant(DAG, 0xbc91e5ac, dl));
5577       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5578                                getF32Constant(DAG, 0x3e4350aa, dl));
5579       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5580       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5581                                getF32Constant(DAG, 0x3f60d3e3, dl));
5582       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5583       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5584                                getF32Constant(DAG, 0x4011cdf0, dl));
5585       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5586       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5587                                getF32Constant(DAG, 0x406cfd1c, dl));
5588       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5589       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5590                                getF32Constant(DAG, 0x408797cb, dl));
5591       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5592       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5593                                   getF32Constant(DAG, 0x4006dcab, dl));
5594     }
5595 
5596     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5597   }
5598 
5599   // No special expansion.
5600   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5601 }
5602 
5603 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5604 /// limited-precision mode.
expandLog2(const SDLoc & dl,SDValue Op,SelectionDAG & DAG,const TargetLowering & TLI,SDNodeFlags Flags)5605 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5606                           const TargetLowering &TLI, SDNodeFlags Flags) {
5607   // TODO: What fast-math-flags should be set on the floating-point nodes?
5608 
5609   if (Op.getValueType() == MVT::f32 &&
5610       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5611     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5612 
5613     // Get the exponent.
5614     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5615 
5616     // Get the significand and build it into a floating-point number with
5617     // exponent of 1.
5618     SDValue X = GetSignificand(DAG, Op1, dl);
5619 
5620     // Different possible minimax approximations of significand in
5621     // floating-point for various degrees of accuracy over [1,2].
5622     SDValue Log2ofMantissa;
5623     if (LimitFloatPrecision <= 6) {
5624       // For floating-point precision of 6:
5625       //
5626       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5627       //
5628       // error 0.0049451742, which is more than 7 bits
5629       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5630                                getF32Constant(DAG, 0xbeb08fe0, dl));
5631       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5632                                getF32Constant(DAG, 0x40019463, dl));
5633       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5634       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5635                                    getF32Constant(DAG, 0x3fd6633d, dl));
5636     } else if (LimitFloatPrecision <= 12) {
5637       // For floating-point precision of 12:
5638       //
5639       //   Log2ofMantissa =
5640       //     -2.51285454f +
5641       //       (4.07009056f +
5642       //         (-2.12067489f +
5643       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5644       //
5645       // error 0.0000876136000, which is better than 13 bits
5646       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5647                                getF32Constant(DAG, 0xbda7262e, dl));
5648       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5649                                getF32Constant(DAG, 0x3f25280b, dl));
5650       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5651       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5652                                getF32Constant(DAG, 0x4007b923, dl));
5653       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5654       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5655                                getF32Constant(DAG, 0x40823e2f, dl));
5656       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5657       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5658                                    getF32Constant(DAG, 0x4020d29c, dl));
5659     } else { // LimitFloatPrecision <= 18
5660       // For floating-point precision of 18:
5661       //
5662       //   Log2ofMantissa =
5663       //     -3.0400495f +
5664       //       (6.1129976f +
5665       //         (-5.3420409f +
5666       //           (3.2865683f +
5667       //             (-1.2669343f +
5668       //               (0.27515199f -
5669       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5670       //
5671       // error 0.0000018516, which is better than 18 bits
5672       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5673                                getF32Constant(DAG, 0xbcd2769e, dl));
5674       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5675                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5676       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5677       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5678                                getF32Constant(DAG, 0x3fa22ae7, dl));
5679       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5680       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5681                                getF32Constant(DAG, 0x40525723, dl));
5682       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5683       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5684                                getF32Constant(DAG, 0x40aaf200, dl));
5685       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5686       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5687                                getF32Constant(DAG, 0x40c39dad, dl));
5688       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5689       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5690                                    getF32Constant(DAG, 0x4042902c, dl));
5691     }
5692 
5693     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5694   }
5695 
5696   // No special expansion.
5697   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5698 }
5699 
5700 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5701 /// limited-precision mode.
expandLog10(const SDLoc & dl,SDValue Op,SelectionDAG & DAG,const TargetLowering & TLI,SDNodeFlags Flags)5702 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5703                            const TargetLowering &TLI, SDNodeFlags Flags) {
5704   // TODO: What fast-math-flags should be set on the floating-point nodes?
5705 
5706   if (Op.getValueType() == MVT::f32 &&
5707       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5708     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5709 
5710     // Scale the exponent by log10(2) [0.30102999f].
5711     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5712     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5713                                         getF32Constant(DAG, 0x3e9a209a, dl));
5714 
5715     // Get the significand and build it into a floating-point number with
5716     // exponent of 1.
5717     SDValue X = GetSignificand(DAG, Op1, dl);
5718 
5719     SDValue Log10ofMantissa;
5720     if (LimitFloatPrecision <= 6) {
5721       // For floating-point precision of 6:
5722       //
5723       //   Log10ofMantissa =
5724       //     -0.50419619f +
5725       //       (0.60948995f - 0.10380950f * x) * x;
5726       //
5727       // error 0.0014886165, which is 6 bits
5728       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5729                                getF32Constant(DAG, 0xbdd49a13, dl));
5730       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5731                                getF32Constant(DAG, 0x3f1c0789, dl));
5732       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5733       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5734                                     getF32Constant(DAG, 0x3f011300, dl));
5735     } else if (LimitFloatPrecision <= 12) {
5736       // For floating-point precision of 12:
5737       //
5738       //   Log10ofMantissa =
5739       //     -0.64831180f +
5740       //       (0.91751397f +
5741       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5742       //
5743       // error 0.00019228036, which is better than 12 bits
5744       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5745                                getF32Constant(DAG, 0x3d431f31, dl));
5746       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5747                                getF32Constant(DAG, 0x3ea21fb2, dl));
5748       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5749       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5750                                getF32Constant(DAG, 0x3f6ae232, dl));
5751       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5752       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5753                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5754     } else { // LimitFloatPrecision <= 18
5755       // For floating-point precision of 18:
5756       //
5757       //   Log10ofMantissa =
5758       //     -0.84299375f +
5759       //       (1.5327582f +
5760       //         (-1.0688956f +
5761       //           (0.49102474f +
5762       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5763       //
5764       // error 0.0000037995730, which is better than 18 bits
5765       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5766                                getF32Constant(DAG, 0x3c5d51ce, dl));
5767       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5768                                getF32Constant(DAG, 0x3e00685a, dl));
5769       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5770       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5771                                getF32Constant(DAG, 0x3efb6798, dl));
5772       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5773       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5774                                getF32Constant(DAG, 0x3f88d192, dl));
5775       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5776       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5777                                getF32Constant(DAG, 0x3fc4316c, dl));
5778       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5779       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5780                                     getF32Constant(DAG, 0x3f57ce70, dl));
5781     }
5782 
5783     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5784   }
5785 
5786   // No special expansion.
5787   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5788 }
5789 
5790 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5791 /// limited-precision mode.
expandExp2(const SDLoc & dl,SDValue Op,SelectionDAG & DAG,const TargetLowering & TLI,SDNodeFlags Flags)5792 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5793                           const TargetLowering &TLI, SDNodeFlags Flags) {
5794   if (Op.getValueType() == MVT::f32 &&
5795       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5796     return getLimitedPrecisionExp2(Op, dl, DAG);
5797 
5798   // No special expansion.
5799   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5800 }
5801 
5802 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5803 /// limited-precision mode with x == 10.0f.
expandPow(const SDLoc & dl,SDValue LHS,SDValue RHS,SelectionDAG & DAG,const TargetLowering & TLI,SDNodeFlags Flags)5804 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5805                          SelectionDAG &DAG, const TargetLowering &TLI,
5806                          SDNodeFlags Flags) {
5807   bool IsExp10 = false;
5808   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5809       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5810     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5811       APFloat Ten(10.0f);
5812       IsExp10 = LHSC->isExactlyValue(Ten);
5813     }
5814   }
5815 
5816   // TODO: What fast-math-flags should be set on the FMUL node?
5817   if (IsExp10) {
5818     // Put the exponent in the right bit position for later addition to the
5819     // final result:
5820     //
5821     //   #define LOG2OF10 3.3219281f
5822     //   t0 = Op * LOG2OF10;
5823     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5824                              getF32Constant(DAG, 0x40549a78, dl));
5825     return getLimitedPrecisionExp2(t0, dl, DAG);
5826   }
5827 
5828   // No special expansion.
5829   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5830 }
5831 
5832 /// ExpandPowI - Expand a llvm.powi intrinsic.
ExpandPowI(const SDLoc & DL,SDValue LHS,SDValue RHS,SelectionDAG & DAG)5833 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5834                           SelectionDAG &DAG) {
5835   // If RHS is a constant, we can expand this out to a multiplication tree if
5836   // it's beneficial on the target, otherwise we end up lowering to a call to
5837   // __powidf2 (for example).
5838   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5839     unsigned Val = RHSC->getSExtValue();
5840 
5841     // powi(x, 0) -> 1.0
5842     if (Val == 0)
5843       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5844 
5845     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5846             Val, DAG.shouldOptForSize())) {
5847       // Get the exponent as a positive value.
5848       if ((int)Val < 0)
5849         Val = -Val;
5850       // We use the simple binary decomposition method to generate the multiply
5851       // sequence.  There are more optimal ways to do this (for example,
5852       // powi(x,15) generates one more multiply than it should), but this has
5853       // the benefit of being both really simple and much better than a libcall.
5854       SDValue Res; // Logically starts equal to 1.0
5855       SDValue CurSquare = LHS;
5856       // TODO: Intrinsics should have fast-math-flags that propagate to these
5857       // nodes.
5858       while (Val) {
5859         if (Val & 1) {
5860           if (Res.getNode())
5861             Res =
5862                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5863           else
5864             Res = CurSquare; // 1.0*CurSquare.
5865         }
5866 
5867         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5868                                 CurSquare, CurSquare);
5869         Val >>= 1;
5870       }
5871 
5872       // If the original was negative, invert the result, producing 1/(x*x*x).
5873       if (RHSC->getSExtValue() < 0)
5874         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5875                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5876       return Res;
5877     }
5878   }
5879 
5880   // Otherwise, expand to a libcall.
5881   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5882 }
5883 
expandDivFix(unsigned Opcode,const SDLoc & DL,SDValue LHS,SDValue RHS,SDValue Scale,SelectionDAG & DAG,const TargetLowering & TLI)5884 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5885                             SDValue LHS, SDValue RHS, SDValue Scale,
5886                             SelectionDAG &DAG, const TargetLowering &TLI) {
5887   EVT VT = LHS.getValueType();
5888   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5889   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5890   LLVMContext &Ctx = *DAG.getContext();
5891 
5892   // If the type is legal but the operation isn't, this node might survive all
5893   // the way to operation legalization. If we end up there and we do not have
5894   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5895   // node.
5896 
5897   // Coax the legalizer into expanding the node during type legalization instead
5898   // by bumping the size by one bit. This will force it to Promote, enabling the
5899   // early expansion and avoiding the need to expand later.
5900 
5901   // We don't have to do this if Scale is 0; that can always be expanded, unless
5902   // it's a saturating signed operation. Those can experience true integer
5903   // division overflow, a case which we must avoid.
5904 
5905   // FIXME: We wouldn't have to do this (or any of the early
5906   // expansion/promotion) if it was possible to expand a libcall of an
5907   // illegal type during operation legalization. But it's not, so things
5908   // get a bit hacky.
5909   unsigned ScaleInt = Scale->getAsZExtVal();
5910   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5911       (TLI.isTypeLegal(VT) ||
5912        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5913     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5914         Opcode, VT, ScaleInt);
5915     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5916       EVT PromVT;
5917       if (VT.isScalarInteger())
5918         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5919       else if (VT.isVector()) {
5920         PromVT = VT.getVectorElementType();
5921         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5922         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5923       } else
5924         llvm_unreachable("Wrong VT for DIVFIX?");
5925       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5926       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5927       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5928       // For saturating operations, we need to shift up the LHS to get the
5929       // proper saturation width, and then shift down again afterwards.
5930       if (Saturating)
5931         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5932                           DAG.getConstant(1, DL, ShiftTy));
5933       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5934       if (Saturating)
5935         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5936                           DAG.getConstant(1, DL, ShiftTy));
5937       return DAG.getZExtOrTrunc(Res, DL, VT);
5938     }
5939   }
5940 
5941   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5942 }
5943 
5944 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5945 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5946 static void
getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned,TypeSize>> & Regs,const SDValue & N)5947 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5948                      const SDValue &N) {
5949   switch (N.getOpcode()) {
5950   case ISD::CopyFromReg: {
5951     SDValue Op = N.getOperand(1);
5952     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5953                       Op.getValueType().getSizeInBits());
5954     return;
5955   }
5956   case ISD::BITCAST:
5957   case ISD::AssertZext:
5958   case ISD::AssertSext:
5959   case ISD::TRUNCATE:
5960     getUnderlyingArgRegs(Regs, N.getOperand(0));
5961     return;
5962   case ISD::BUILD_PAIR:
5963   case ISD::BUILD_VECTOR:
5964   case ISD::CONCAT_VECTORS:
5965     for (SDValue Op : N->op_values())
5966       getUnderlyingArgRegs(Regs, Op);
5967     return;
5968   default:
5969     return;
5970   }
5971 }
5972 
5973 /// If the DbgValueInst is a dbg_value of a function argument, create the
5974 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5975 /// instruction selection, they will be inserted to the entry BB.
5976 /// We don't currently support this for variadic dbg_values, as they shouldn't
5977 /// appear for function arguments or in the prologue.
EmitFuncArgumentDbgValue(const Value * V,DILocalVariable * Variable,DIExpression * Expr,DILocation * DL,FuncArgumentDbgValueKind Kind,const SDValue & N)5978 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5979     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5980     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5981   const Argument *Arg = dyn_cast<Argument>(V);
5982   if (!Arg)
5983     return false;
5984 
5985   MachineFunction &MF = DAG.getMachineFunction();
5986   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5987 
5988   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5989   // we've been asked to pursue.
5990   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5991                               bool Indirect) {
5992     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5993       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5994       // pointing at the VReg, which will be patched up later.
5995       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5996       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5997           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5998           /* isKill */ false, /* isDead */ false,
5999           /* isUndef */ false, /* isEarlyClobber */ false,
6000           /* SubReg */ 0, /* isDebug */ true)});
6001 
6002       auto *NewDIExpr = FragExpr;
6003       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6004       // the DIExpression.
6005       if (Indirect)
6006         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6007       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6008       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6009       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6010     } else {
6011       // Create a completely standard DBG_VALUE.
6012       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6013       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6014     }
6015   };
6016 
6017   if (Kind == FuncArgumentDbgValueKind::Value) {
6018     // ArgDbgValues are hoisted to the beginning of the entry block. So we
6019     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6020     // the entry block.
6021     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6022     if (!IsInEntryBlock)
6023       return false;
6024 
6025     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
6026     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6027     // variable that also is a param.
6028     //
6029     // Although, if we are at the top of the entry block already, we can still
6030     // emit using ArgDbgValue. This might catch some situations when the
6031     // dbg.value refers to an argument that isn't used in the entry block, so
6032     // any CopyToReg node would be optimized out and the only way to express
6033     // this DBG_VALUE is by using the physical reg (or FI) as done in this
6034     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
6035     // we should only emit as ArgDbgValue if the Variable is an argument to the
6036     // current function, and the dbg.value intrinsic is found in the entry
6037     // block.
6038     bool VariableIsFunctionInputArg = Variable->isParameter() &&
6039         !DL->getInlinedAt();
6040     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6041     if (!IsInPrologue && !VariableIsFunctionInputArg)
6042       return false;
6043 
6044     // Here we assume that a function argument on IR level only can be used to
6045     // describe one input parameter on source level. If we for example have
6046     // source code like this
6047     //
6048     //    struct A { long x, y; };
6049     //    void foo(struct A a, long b) {
6050     //      ...
6051     //      b = a.x;
6052     //      ...
6053     //    }
6054     //
6055     // and IR like this
6056     //
6057     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
6058     //  entry:
6059     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6060     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6061     //    call void @llvm.dbg.value(metadata i32 %b, "b",
6062     //    ...
6063     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
6064     //    ...
6065     //
6066     // then the last dbg.value is describing a parameter "b" using a value that
6067     // is an argument. But since we already has used %a1 to describe a parameter
6068     // we should not handle that last dbg.value here (that would result in an
6069     // incorrect hoisting of the DBG_VALUE to the function entry).
6070     // Notice that we allow one dbg.value per IR level argument, to accommodate
6071     // for the situation with fragments above.
6072     // If there is no node for the value being handled, we return true to skip
6073     // the normal generation of debug info, as it would kill existing debug
6074     // info for the parameter in case of duplicates.
6075     if (VariableIsFunctionInputArg) {
6076       unsigned ArgNo = Arg->getArgNo();
6077       if (ArgNo >= FuncInfo.DescribedArgs.size())
6078         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6079       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6080         return !NodeMap[V].getNode();
6081       FuncInfo.DescribedArgs.set(ArgNo);
6082     }
6083   }
6084 
6085   bool IsIndirect = false;
6086   std::optional<MachineOperand> Op;
6087   // Some arguments' frame index is recorded during argument lowering.
6088   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6089   if (FI != std::numeric_limits<int>::max())
6090     Op = MachineOperand::CreateFI(FI);
6091 
6092   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
6093   if (!Op && N.getNode()) {
6094     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6095     Register Reg;
6096     if (ArgRegsAndSizes.size() == 1)
6097       Reg = ArgRegsAndSizes.front().first;
6098 
6099     if (Reg && Reg.isVirtual()) {
6100       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6101       Register PR = RegInfo.getLiveInPhysReg(Reg);
6102       if (PR)
6103         Reg = PR;
6104     }
6105     if (Reg) {
6106       Op = MachineOperand::CreateReg(Reg, false);
6107       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6108     }
6109   }
6110 
6111   if (!Op && N.getNode()) {
6112     // Check if frame index is available.
6113     SDValue LCandidate = peekThroughBitcasts(N);
6114     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6115       if (FrameIndexSDNode *FINode =
6116           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6117         Op = MachineOperand::CreateFI(FINode->getIndex());
6118   }
6119 
6120   if (!Op) {
6121     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6122     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
6123                                          SplitRegs) {
6124       unsigned Offset = 0;
6125       for (const auto &RegAndSize : SplitRegs) {
6126         // If the expression is already a fragment, the current register
6127         // offset+size might extend beyond the fragment. In this case, only
6128         // the register bits that are inside the fragment are relevant.
6129         int RegFragmentSizeInBits = RegAndSize.second;
6130         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6131           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6132           // The register is entirely outside the expression fragment,
6133           // so is irrelevant for debug info.
6134           if (Offset >= ExprFragmentSizeInBits)
6135             break;
6136           // The register is partially outside the expression fragment, only
6137           // the low bits within the fragment are relevant for debug info.
6138           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6139             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6140           }
6141         }
6142 
6143         auto FragmentExpr = DIExpression::createFragmentExpression(
6144             Expr, Offset, RegFragmentSizeInBits);
6145         Offset += RegAndSize.second;
6146         // If a valid fragment expression cannot be created, the variable's
6147         // correct value cannot be determined and so it is set as Undef.
6148         if (!FragmentExpr) {
6149           SDDbgValue *SDV = DAG.getConstantDbgValue(
6150               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6151           DAG.AddDbgValue(SDV, false);
6152           continue;
6153         }
6154         MachineInstr *NewMI =
6155             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6156                              Kind != FuncArgumentDbgValueKind::Value);
6157         FuncInfo.ArgDbgValues.push_back(NewMI);
6158       }
6159     };
6160 
6161     // Check if ValueMap has reg number.
6162     DenseMap<const Value *, Register>::const_iterator
6163       VMI = FuncInfo.ValueMap.find(V);
6164     if (VMI != FuncInfo.ValueMap.end()) {
6165       const auto &TLI = DAG.getTargetLoweringInfo();
6166       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6167                        V->getType(), std::nullopt);
6168       if (RFV.occupiesMultipleRegs()) {
6169         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6170         return true;
6171       }
6172 
6173       Op = MachineOperand::CreateReg(VMI->second, false);
6174       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6175     } else if (ArgRegsAndSizes.size() > 1) {
6176       // This was split due to the calling convention, and no virtual register
6177       // mapping exists for the value.
6178       splitMultiRegDbgValue(ArgRegsAndSizes);
6179       return true;
6180     }
6181   }
6182 
6183   if (!Op)
6184     return false;
6185 
6186   assert(Variable->isValidLocationForIntrinsic(DL) &&
6187          "Expected inlined-at fields to agree");
6188   MachineInstr *NewMI = nullptr;
6189 
6190   if (Op->isReg())
6191     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6192   else
6193     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6194                     Variable, Expr);
6195 
6196   // Otherwise, use ArgDbgValues.
6197   FuncInfo.ArgDbgValues.push_back(NewMI);
6198   return true;
6199 }
6200 
6201 /// Return the appropriate SDDbgValue based on N.
getDbgValue(SDValue N,DILocalVariable * Variable,DIExpression * Expr,const DebugLoc & dl,unsigned DbgSDNodeOrder)6202 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6203                                              DILocalVariable *Variable,
6204                                              DIExpression *Expr,
6205                                              const DebugLoc &dl,
6206                                              unsigned DbgSDNodeOrder) {
6207   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6208     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6209     // stack slot locations.
6210     //
6211     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6212     // debug values here after optimization:
6213     //
6214     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6215     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6216     //
6217     // Both describe the direct values of their associated variables.
6218     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6219                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6220   }
6221   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6222                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6223 }
6224 
FixedPointIntrinsicToOpcode(unsigned Intrinsic)6225 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6226   switch (Intrinsic) {
6227   case Intrinsic::smul_fix:
6228     return ISD::SMULFIX;
6229   case Intrinsic::umul_fix:
6230     return ISD::UMULFIX;
6231   case Intrinsic::smul_fix_sat:
6232     return ISD::SMULFIXSAT;
6233   case Intrinsic::umul_fix_sat:
6234     return ISD::UMULFIXSAT;
6235   case Intrinsic::sdiv_fix:
6236     return ISD::SDIVFIX;
6237   case Intrinsic::udiv_fix:
6238     return ISD::UDIVFIX;
6239   case Intrinsic::sdiv_fix_sat:
6240     return ISD::SDIVFIXSAT;
6241   case Intrinsic::udiv_fix_sat:
6242     return ISD::UDIVFIXSAT;
6243   default:
6244     llvm_unreachable("Unhandled fixed point intrinsic");
6245   }
6246 }
6247 
lowerCallToExternalSymbol(const CallInst & I,const char * FunctionName)6248 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6249                                            const char *FunctionName) {
6250   assert(FunctionName && "FunctionName must not be nullptr");
6251   SDValue Callee = DAG.getExternalSymbol(
6252       FunctionName,
6253       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6254   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6255 }
6256 
6257 /// Given a @llvm.call.preallocated.setup, return the corresponding
6258 /// preallocated call.
FindPreallocatedCall(const Value * PreallocatedSetup)6259 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6260   assert(cast<CallBase>(PreallocatedSetup)
6261                  ->getCalledFunction()
6262                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6263          "expected call_preallocated_setup Value");
6264   for (const auto *U : PreallocatedSetup->users()) {
6265     auto *UseCall = cast<CallBase>(U);
6266     const Function *Fn = UseCall->getCalledFunction();
6267     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6268       return UseCall;
6269     }
6270   }
6271   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6272 }
6273 
6274 /// If DI is a debug value with an EntryValue expression, lower it using the
6275 /// corresponding physical register of the associated Argument value
6276 /// (guaranteed to exist by the verifier).
visitEntryValueDbgValue(ArrayRef<const Value * > Values,DILocalVariable * Variable,DIExpression * Expr,DebugLoc DbgLoc)6277 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6278     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6279     DIExpression *Expr, DebugLoc DbgLoc) {
6280   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6281     return false;
6282 
6283   // These properties are guaranteed by the verifier.
6284   const Argument *Arg = cast<Argument>(Values[0]);
6285   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6286 
6287   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6288   if (ArgIt == FuncInfo.ValueMap.end()) {
6289     LLVM_DEBUG(
6290         dbgs() << "Dropping dbg.value: expression is entry_value but "
6291                   "couldn't find an associated register for the Argument\n");
6292     return true;
6293   }
6294   Register ArgVReg = ArgIt->getSecond();
6295 
6296   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6297     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6298       SDDbgValue *SDV = DAG.getVRegDbgValue(
6299           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6300       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6301       return true;
6302     }
6303   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6304                        "couldn't find a physical register\n");
6305   return true;
6306 }
6307 
6308 /// Lower the call to the specified intrinsic function.
visitConvergenceControl(const CallInst & I,unsigned Intrinsic)6309 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6310                                                   unsigned Intrinsic) {
6311   SDLoc sdl = getCurSDLoc();
6312   switch (Intrinsic) {
6313   case Intrinsic::experimental_convergence_anchor:
6314     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6315     break;
6316   case Intrinsic::experimental_convergence_entry:
6317     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6318     break;
6319   case Intrinsic::experimental_convergence_loop: {
6320     auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6321     auto *Token = Bundle->Inputs[0].get();
6322     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6323                              getValue(Token)));
6324     break;
6325   }
6326   }
6327 }
6328 
visitVectorHistogram(const CallInst & I,unsigned IntrinsicID)6329 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6330                                                unsigned IntrinsicID) {
6331   // For now, we're only lowering an 'add' histogram.
6332   // We can add others later, e.g. saturating adds, min/max.
6333   assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6334          "Tried to lower unsupported histogram type");
6335   SDLoc sdl = getCurSDLoc();
6336   Value *Ptr = I.getOperand(0);
6337   SDValue Inc = getValue(I.getOperand(1));
6338   SDValue Mask = getValue(I.getOperand(2));
6339 
6340   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6341   DataLayout TargetDL = DAG.getDataLayout();
6342   EVT VT = Inc.getValueType();
6343   Align Alignment = DAG.getEVTAlign(VT);
6344 
6345   const MDNode *Ranges = getRangeMetadata(I);
6346 
6347   SDValue Root = DAG.getRoot();
6348   SDValue Base;
6349   SDValue Index;
6350   ISD::MemIndexType IndexType;
6351   SDValue Scale;
6352   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
6353                                     I.getParent(), VT.getScalarStoreSize());
6354 
6355   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6356 
6357   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6358       MachinePointerInfo(AS),
6359       MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6360       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
6361 
6362   if (!UniformBase) {
6363     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6364     Index = getValue(Ptr);
6365     IndexType = ISD::SIGNED_SCALED;
6366     Scale =
6367         DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6368   }
6369 
6370   EVT IdxVT = Index.getValueType();
6371   EVT EltTy = IdxVT.getVectorElementType();
6372   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6373     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
6374     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6375   }
6376 
6377   SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6378 
6379   SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6380   SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6381                                              Ops, MMO, IndexType);
6382 
6383   setValue(&I, Histogram);
6384   DAG.setRoot(Histogram);
6385 }
6386 
6387 /// Lower the call to the specified intrinsic function.
visitIntrinsicCall(const CallInst & I,unsigned Intrinsic)6388 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6389                                              unsigned Intrinsic) {
6390   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6391   SDLoc sdl = getCurSDLoc();
6392   DebugLoc dl = getCurDebugLoc();
6393   SDValue Res;
6394 
6395   SDNodeFlags Flags;
6396   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6397     Flags.copyFMF(*FPOp);
6398 
6399   switch (Intrinsic) {
6400   default:
6401     // By default, turn this into a target intrinsic node.
6402     visitTargetIntrinsic(I, Intrinsic);
6403     return;
6404   case Intrinsic::vscale: {
6405     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6406     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6407     return;
6408   }
6409   case Intrinsic::vastart:  visitVAStart(I); return;
6410   case Intrinsic::vaend:    visitVAEnd(I); return;
6411   case Intrinsic::vacopy:   visitVACopy(I); return;
6412   case Intrinsic::returnaddress:
6413     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6414                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6415                              getValue(I.getArgOperand(0))));
6416     return;
6417   case Intrinsic::addressofreturnaddress:
6418     setValue(&I,
6419              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6420                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6421     return;
6422   case Intrinsic::sponentry:
6423     setValue(&I,
6424              DAG.getNode(ISD::SPONENTRY, sdl,
6425                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6426     return;
6427   case Intrinsic::frameaddress:
6428     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6429                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6430                              getValue(I.getArgOperand(0))));
6431     return;
6432   case Intrinsic::read_volatile_register:
6433   case Intrinsic::read_register: {
6434     Value *Reg = I.getArgOperand(0);
6435     SDValue Chain = getRoot();
6436     SDValue RegName =
6437         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6438     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6439     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6440       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6441     setValue(&I, Res);
6442     DAG.setRoot(Res.getValue(1));
6443     return;
6444   }
6445   case Intrinsic::write_register: {
6446     Value *Reg = I.getArgOperand(0);
6447     Value *RegValue = I.getArgOperand(1);
6448     SDValue Chain = getRoot();
6449     SDValue RegName =
6450         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6451     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6452                             RegName, getValue(RegValue)));
6453     return;
6454   }
6455   case Intrinsic::memcpy: {
6456     const auto &MCI = cast<MemCpyInst>(I);
6457     SDValue Op1 = getValue(I.getArgOperand(0));
6458     SDValue Op2 = getValue(I.getArgOperand(1));
6459     SDValue Op3 = getValue(I.getArgOperand(2));
6460     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6461     Align DstAlign = MCI.getDestAlign().valueOrOne();
6462     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6463     Align Alignment = std::min(DstAlign, SrcAlign);
6464     bool isVol = MCI.isVolatile();
6465     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6466     // node.
6467     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6468     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6469                                /* AlwaysInline */ false, &I, std::nullopt,
6470                                MachinePointerInfo(I.getArgOperand(0)),
6471                                MachinePointerInfo(I.getArgOperand(1)),
6472                                I.getAAMetadata(), AA);
6473     updateDAGForMaybeTailCall(MC);
6474     return;
6475   }
6476   case Intrinsic::memcpy_inline: {
6477     const auto &MCI = cast<MemCpyInlineInst>(I);
6478     SDValue Dst = getValue(I.getArgOperand(0));
6479     SDValue Src = getValue(I.getArgOperand(1));
6480     SDValue Size = getValue(I.getArgOperand(2));
6481     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6482     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6483     Align DstAlign = MCI.getDestAlign().valueOrOne();
6484     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6485     Align Alignment = std::min(DstAlign, SrcAlign);
6486     bool isVol = MCI.isVolatile();
6487     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6488     // node.
6489     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6490                                /* AlwaysInline */ true, &I, std::nullopt,
6491                                MachinePointerInfo(I.getArgOperand(0)),
6492                                MachinePointerInfo(I.getArgOperand(1)),
6493                                I.getAAMetadata(), AA);
6494     updateDAGForMaybeTailCall(MC);
6495     return;
6496   }
6497   case Intrinsic::memset: {
6498     const auto &MSI = cast<MemSetInst>(I);
6499     SDValue Op1 = getValue(I.getArgOperand(0));
6500     SDValue Op2 = getValue(I.getArgOperand(1));
6501     SDValue Op3 = getValue(I.getArgOperand(2));
6502     // @llvm.memset defines 0 and 1 to both mean no alignment.
6503     Align Alignment = MSI.getDestAlign().valueOrOne();
6504     bool isVol = MSI.isVolatile();
6505     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6506     SDValue MS = DAG.getMemset(
6507         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6508         &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6509     updateDAGForMaybeTailCall(MS);
6510     return;
6511   }
6512   case Intrinsic::memset_inline: {
6513     const auto &MSII = cast<MemSetInlineInst>(I);
6514     SDValue Dst = getValue(I.getArgOperand(0));
6515     SDValue Value = getValue(I.getArgOperand(1));
6516     SDValue Size = getValue(I.getArgOperand(2));
6517     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6518     // @llvm.memset defines 0 and 1 to both mean no alignment.
6519     Align DstAlign = MSII.getDestAlign().valueOrOne();
6520     bool isVol = MSII.isVolatile();
6521     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6522     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6523                                /* AlwaysInline */ true, &I,
6524                                MachinePointerInfo(I.getArgOperand(0)),
6525                                I.getAAMetadata());
6526     updateDAGForMaybeTailCall(MC);
6527     return;
6528   }
6529   case Intrinsic::memmove: {
6530     const auto &MMI = cast<MemMoveInst>(I);
6531     SDValue Op1 = getValue(I.getArgOperand(0));
6532     SDValue Op2 = getValue(I.getArgOperand(1));
6533     SDValue Op3 = getValue(I.getArgOperand(2));
6534     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6535     Align DstAlign = MMI.getDestAlign().valueOrOne();
6536     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6537     Align Alignment = std::min(DstAlign, SrcAlign);
6538     bool isVol = MMI.isVolatile();
6539     // FIXME: Support passing different dest/src alignments to the memmove DAG
6540     // node.
6541     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6542     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, &I,
6543                                 /* OverrideTailCall */ std::nullopt,
6544                                 MachinePointerInfo(I.getArgOperand(0)),
6545                                 MachinePointerInfo(I.getArgOperand(1)),
6546                                 I.getAAMetadata(), AA);
6547     updateDAGForMaybeTailCall(MM);
6548     return;
6549   }
6550   case Intrinsic::memcpy_element_unordered_atomic: {
6551     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6552     SDValue Dst = getValue(MI.getRawDest());
6553     SDValue Src = getValue(MI.getRawSource());
6554     SDValue Length = getValue(MI.getLength());
6555 
6556     Type *LengthTy = MI.getLength()->getType();
6557     unsigned ElemSz = MI.getElementSizeInBytes();
6558     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6559     SDValue MC =
6560         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6561                             isTC, MachinePointerInfo(MI.getRawDest()),
6562                             MachinePointerInfo(MI.getRawSource()));
6563     updateDAGForMaybeTailCall(MC);
6564     return;
6565   }
6566   case Intrinsic::memmove_element_unordered_atomic: {
6567     auto &MI = cast<AtomicMemMoveInst>(I);
6568     SDValue Dst = getValue(MI.getRawDest());
6569     SDValue Src = getValue(MI.getRawSource());
6570     SDValue Length = getValue(MI.getLength());
6571 
6572     Type *LengthTy = MI.getLength()->getType();
6573     unsigned ElemSz = MI.getElementSizeInBytes();
6574     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6575     SDValue MC =
6576         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6577                              isTC, MachinePointerInfo(MI.getRawDest()),
6578                              MachinePointerInfo(MI.getRawSource()));
6579     updateDAGForMaybeTailCall(MC);
6580     return;
6581   }
6582   case Intrinsic::memset_element_unordered_atomic: {
6583     auto &MI = cast<AtomicMemSetInst>(I);
6584     SDValue Dst = getValue(MI.getRawDest());
6585     SDValue Val = getValue(MI.getValue());
6586     SDValue Length = getValue(MI.getLength());
6587 
6588     Type *LengthTy = MI.getLength()->getType();
6589     unsigned ElemSz = MI.getElementSizeInBytes();
6590     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6591     SDValue MC =
6592         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6593                             isTC, MachinePointerInfo(MI.getRawDest()));
6594     updateDAGForMaybeTailCall(MC);
6595     return;
6596   }
6597   case Intrinsic::call_preallocated_setup: {
6598     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6599     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6600     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6601                               getRoot(), SrcValue);
6602     setValue(&I, Res);
6603     DAG.setRoot(Res);
6604     return;
6605   }
6606   case Intrinsic::call_preallocated_arg: {
6607     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6608     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6609     SDValue Ops[3];
6610     Ops[0] = getRoot();
6611     Ops[1] = SrcValue;
6612     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6613                                    MVT::i32); // arg index
6614     SDValue Res = DAG.getNode(
6615         ISD::PREALLOCATED_ARG, sdl,
6616         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6617     setValue(&I, Res);
6618     DAG.setRoot(Res.getValue(1));
6619     return;
6620   }
6621   case Intrinsic::dbg_declare: {
6622     const auto &DI = cast<DbgDeclareInst>(I);
6623     // Debug intrinsics are handled separately in assignment tracking mode.
6624     // Some intrinsics are handled right after Argument lowering.
6625     if (AssignmentTrackingEnabled ||
6626         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6627       return;
6628     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6629     DILocalVariable *Variable = DI.getVariable();
6630     DIExpression *Expression = DI.getExpression();
6631     dropDanglingDebugInfo(Variable, Expression);
6632     // Assume dbg.declare can not currently use DIArgList, i.e.
6633     // it is non-variadic.
6634     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6635     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6636                        DI.getDebugLoc());
6637     return;
6638   }
6639   case Intrinsic::dbg_label: {
6640     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6641     DILabel *Label = DI.getLabel();
6642     assert(Label && "Missing label");
6643 
6644     SDDbgLabel *SDV;
6645     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6646     DAG.AddDbgLabel(SDV);
6647     return;
6648   }
6649   case Intrinsic::dbg_assign: {
6650     // Debug intrinsics are handled separately in assignment tracking mode.
6651     if (AssignmentTrackingEnabled)
6652       return;
6653     // If assignment tracking hasn't been enabled then fall through and treat
6654     // the dbg.assign as a dbg.value.
6655     [[fallthrough]];
6656   }
6657   case Intrinsic::dbg_value: {
6658     // Debug intrinsics are handled separately in assignment tracking mode.
6659     if (AssignmentTrackingEnabled)
6660       return;
6661     const DbgValueInst &DI = cast<DbgValueInst>(I);
6662     assert(DI.getVariable() && "Missing variable");
6663 
6664     DILocalVariable *Variable = DI.getVariable();
6665     DIExpression *Expression = DI.getExpression();
6666     dropDanglingDebugInfo(Variable, Expression);
6667 
6668     if (DI.isKillLocation()) {
6669       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6670       return;
6671     }
6672 
6673     SmallVector<Value *, 4> Values(DI.getValues());
6674     if (Values.empty())
6675       return;
6676 
6677     bool IsVariadic = DI.hasArgList();
6678     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6679                           SDNodeOrder, IsVariadic))
6680       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6681                            DI.getDebugLoc(), SDNodeOrder);
6682     return;
6683   }
6684 
6685   case Intrinsic::eh_typeid_for: {
6686     // Find the type id for the given typeinfo.
6687     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6688     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6689     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6690     setValue(&I, Res);
6691     return;
6692   }
6693 
6694   case Intrinsic::eh_return_i32:
6695   case Intrinsic::eh_return_i64:
6696     DAG.getMachineFunction().setCallsEHReturn(true);
6697     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6698                             MVT::Other,
6699                             getControlRoot(),
6700                             getValue(I.getArgOperand(0)),
6701                             getValue(I.getArgOperand(1))));
6702     return;
6703   case Intrinsic::eh_unwind_init:
6704     DAG.getMachineFunction().setCallsUnwindInit(true);
6705     return;
6706   case Intrinsic::eh_dwarf_cfa:
6707     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6708                              TLI.getPointerTy(DAG.getDataLayout()),
6709                              getValue(I.getArgOperand(0))));
6710     return;
6711   case Intrinsic::eh_sjlj_callsite: {
6712     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6713     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6714     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6715 
6716     MMI.setCurrentCallSite(CI->getZExtValue());
6717     return;
6718   }
6719   case Intrinsic::eh_sjlj_functioncontext: {
6720     // Get and store the index of the function context.
6721     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6722     AllocaInst *FnCtx =
6723       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6724     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6725     MFI.setFunctionContextIndex(FI);
6726     return;
6727   }
6728   case Intrinsic::eh_sjlj_setjmp: {
6729     SDValue Ops[2];
6730     Ops[0] = getRoot();
6731     Ops[1] = getValue(I.getArgOperand(0));
6732     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6733                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6734     setValue(&I, Op.getValue(0));
6735     DAG.setRoot(Op.getValue(1));
6736     return;
6737   }
6738   case Intrinsic::eh_sjlj_longjmp:
6739     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6740                             getRoot(), getValue(I.getArgOperand(0))));
6741     return;
6742   case Intrinsic::eh_sjlj_setup_dispatch:
6743     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6744                             getRoot()));
6745     return;
6746   case Intrinsic::masked_gather:
6747     visitMaskedGather(I);
6748     return;
6749   case Intrinsic::masked_load:
6750     visitMaskedLoad(I);
6751     return;
6752   case Intrinsic::masked_scatter:
6753     visitMaskedScatter(I);
6754     return;
6755   case Intrinsic::masked_store:
6756     visitMaskedStore(I);
6757     return;
6758   case Intrinsic::masked_expandload:
6759     visitMaskedLoad(I, true /* IsExpanding */);
6760     return;
6761   case Intrinsic::masked_compressstore:
6762     visitMaskedStore(I, true /* IsCompressing */);
6763     return;
6764   case Intrinsic::powi:
6765     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6766                             getValue(I.getArgOperand(1)), DAG));
6767     return;
6768   case Intrinsic::log:
6769     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6770     return;
6771   case Intrinsic::log2:
6772     setValue(&I,
6773              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6774     return;
6775   case Intrinsic::log10:
6776     setValue(&I,
6777              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6778     return;
6779   case Intrinsic::exp:
6780     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6781     return;
6782   case Intrinsic::exp2:
6783     setValue(&I,
6784              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6785     return;
6786   case Intrinsic::pow:
6787     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6788                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6789     return;
6790   case Intrinsic::sqrt:
6791   case Intrinsic::fabs:
6792   case Intrinsic::sin:
6793   case Intrinsic::cos:
6794   case Intrinsic::tan:
6795   case Intrinsic::asin:
6796   case Intrinsic::acos:
6797   case Intrinsic::atan:
6798   case Intrinsic::sinh:
6799   case Intrinsic::cosh:
6800   case Intrinsic::tanh:
6801   case Intrinsic::exp10:
6802   case Intrinsic::floor:
6803   case Intrinsic::ceil:
6804   case Intrinsic::trunc:
6805   case Intrinsic::rint:
6806   case Intrinsic::nearbyint:
6807   case Intrinsic::round:
6808   case Intrinsic::roundeven:
6809   case Intrinsic::canonicalize: {
6810     unsigned Opcode;
6811     // clang-format off
6812     switch (Intrinsic) {
6813     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6814     case Intrinsic::sqrt:         Opcode = ISD::FSQRT;         break;
6815     case Intrinsic::fabs:         Opcode = ISD::FABS;          break;
6816     case Intrinsic::sin:          Opcode = ISD::FSIN;          break;
6817     case Intrinsic::cos:          Opcode = ISD::FCOS;          break;
6818     case Intrinsic::tan:          Opcode = ISD::FTAN;          break;
6819     case Intrinsic::asin:         Opcode = ISD::FASIN;         break;
6820     case Intrinsic::acos:         Opcode = ISD::FACOS;         break;
6821     case Intrinsic::atan:         Opcode = ISD::FATAN;         break;
6822     case Intrinsic::sinh:         Opcode = ISD::FSINH;         break;
6823     case Intrinsic::cosh:         Opcode = ISD::FCOSH;         break;
6824     case Intrinsic::tanh:         Opcode = ISD::FTANH;         break;
6825     case Intrinsic::exp10:        Opcode = ISD::FEXP10;        break;
6826     case Intrinsic::floor:        Opcode = ISD::FFLOOR;        break;
6827     case Intrinsic::ceil:         Opcode = ISD::FCEIL;         break;
6828     case Intrinsic::trunc:        Opcode = ISD::FTRUNC;        break;
6829     case Intrinsic::rint:         Opcode = ISD::FRINT;         break;
6830     case Intrinsic::nearbyint:    Opcode = ISD::FNEARBYINT;    break;
6831     case Intrinsic::round:        Opcode = ISD::FROUND;        break;
6832     case Intrinsic::roundeven:    Opcode = ISD::FROUNDEVEN;    break;
6833     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6834     }
6835     // clang-format on
6836 
6837     setValue(&I, DAG.getNode(Opcode, sdl,
6838                              getValue(I.getArgOperand(0)).getValueType(),
6839                              getValue(I.getArgOperand(0)), Flags));
6840     return;
6841   }
6842   case Intrinsic::lround:
6843   case Intrinsic::llround:
6844   case Intrinsic::lrint:
6845   case Intrinsic::llrint: {
6846     unsigned Opcode;
6847     // clang-format off
6848     switch (Intrinsic) {
6849     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6850     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6851     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6852     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6853     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6854     }
6855     // clang-format on
6856 
6857     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6858     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6859                              getValue(I.getArgOperand(0))));
6860     return;
6861   }
6862   case Intrinsic::minnum:
6863     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6864                              getValue(I.getArgOperand(0)).getValueType(),
6865                              getValue(I.getArgOperand(0)),
6866                              getValue(I.getArgOperand(1)), Flags));
6867     return;
6868   case Intrinsic::maxnum:
6869     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6870                              getValue(I.getArgOperand(0)).getValueType(),
6871                              getValue(I.getArgOperand(0)),
6872                              getValue(I.getArgOperand(1)), Flags));
6873     return;
6874   case Intrinsic::minimum:
6875     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6876                              getValue(I.getArgOperand(0)).getValueType(),
6877                              getValue(I.getArgOperand(0)),
6878                              getValue(I.getArgOperand(1)), Flags));
6879     return;
6880   case Intrinsic::maximum:
6881     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6882                              getValue(I.getArgOperand(0)).getValueType(),
6883                              getValue(I.getArgOperand(0)),
6884                              getValue(I.getArgOperand(1)), Flags));
6885     return;
6886   case Intrinsic::copysign:
6887     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6888                              getValue(I.getArgOperand(0)).getValueType(),
6889                              getValue(I.getArgOperand(0)),
6890                              getValue(I.getArgOperand(1)), Flags));
6891     return;
6892   case Intrinsic::ldexp:
6893     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6894                              getValue(I.getArgOperand(0)).getValueType(),
6895                              getValue(I.getArgOperand(0)),
6896                              getValue(I.getArgOperand(1)), Flags));
6897     return;
6898   case Intrinsic::frexp: {
6899     SmallVector<EVT, 2> ValueVTs;
6900     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6901     SDVTList VTs = DAG.getVTList(ValueVTs);
6902     setValue(&I,
6903              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6904     return;
6905   }
6906   case Intrinsic::arithmetic_fence: {
6907     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6908                              getValue(I.getArgOperand(0)).getValueType(),
6909                              getValue(I.getArgOperand(0)), Flags));
6910     return;
6911   }
6912   case Intrinsic::fma:
6913     setValue(&I, DAG.getNode(
6914                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6915                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6916                      getValue(I.getArgOperand(2)), Flags));
6917     return;
6918 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6919   case Intrinsic::INTRINSIC:
6920 #include "llvm/IR/ConstrainedOps.def"
6921     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6922     return;
6923 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6924 #include "llvm/IR/VPIntrinsics.def"
6925     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6926     return;
6927   case Intrinsic::fptrunc_round: {
6928     // Get the last argument, the metadata and convert it to an integer in the
6929     // call
6930     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6931     std::optional<RoundingMode> RoundMode =
6932         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6933 
6934     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6935 
6936     // Propagate fast-math-flags from IR to node(s).
6937     SDNodeFlags Flags;
6938     Flags.copyFMF(*cast<FPMathOperator>(&I));
6939     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6940 
6941     SDValue Result;
6942     Result = DAG.getNode(
6943         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6944         DAG.getTargetConstant((int)*RoundMode, sdl,
6945                               TLI.getPointerTy(DAG.getDataLayout())));
6946     setValue(&I, Result);
6947 
6948     return;
6949   }
6950   case Intrinsic::fmuladd: {
6951     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6952     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6953         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6954       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6955                                getValue(I.getArgOperand(0)).getValueType(),
6956                                getValue(I.getArgOperand(0)),
6957                                getValue(I.getArgOperand(1)),
6958                                getValue(I.getArgOperand(2)), Flags));
6959     } else {
6960       // TODO: Intrinsic calls should have fast-math-flags.
6961       SDValue Mul = DAG.getNode(
6962           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6963           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6964       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6965                                 getValue(I.getArgOperand(0)).getValueType(),
6966                                 Mul, getValue(I.getArgOperand(2)), Flags);
6967       setValue(&I, Add);
6968     }
6969     return;
6970   }
6971   case Intrinsic::convert_to_fp16:
6972     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6973                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6974                                          getValue(I.getArgOperand(0)),
6975                                          DAG.getTargetConstant(0, sdl,
6976                                                                MVT::i32))));
6977     return;
6978   case Intrinsic::convert_from_fp16:
6979     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6980                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6981                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6982                                          getValue(I.getArgOperand(0)))));
6983     return;
6984   case Intrinsic::fptosi_sat: {
6985     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6986     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6987                              getValue(I.getArgOperand(0)),
6988                              DAG.getValueType(VT.getScalarType())));
6989     return;
6990   }
6991   case Intrinsic::fptoui_sat: {
6992     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6993     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6994                              getValue(I.getArgOperand(0)),
6995                              DAG.getValueType(VT.getScalarType())));
6996     return;
6997   }
6998   case Intrinsic::set_rounding:
6999     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7000                       {getRoot(), getValue(I.getArgOperand(0))});
7001     setValue(&I, Res);
7002     DAG.setRoot(Res.getValue(0));
7003     return;
7004   case Intrinsic::is_fpclass: {
7005     const DataLayout DLayout = DAG.getDataLayout();
7006     EVT DestVT = TLI.getValueType(DLayout, I.getType());
7007     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7008     FPClassTest Test = static_cast<FPClassTest>(
7009         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7010     MachineFunction &MF = DAG.getMachineFunction();
7011     const Function &F = MF.getFunction();
7012     SDValue Op = getValue(I.getArgOperand(0));
7013     SDNodeFlags Flags;
7014     Flags.setNoFPExcept(
7015         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7016     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7017     // expansion can use illegal types. Making expansion early allows
7018     // legalizing these types prior to selection.
7019     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
7020       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7021       setValue(&I, Result);
7022       return;
7023     }
7024 
7025     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7026     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7027     setValue(&I, V);
7028     return;
7029   }
7030   case Intrinsic::get_fpenv: {
7031     const DataLayout DLayout = DAG.getDataLayout();
7032     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7033     Align TempAlign = DAG.getEVTAlign(EnvVT);
7034     SDValue Chain = getRoot();
7035     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7036     // and temporary storage in stack.
7037     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7038       Res = DAG.getNode(
7039           ISD::GET_FPENV, sdl,
7040           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7041                         MVT::Other),
7042           Chain);
7043     } else {
7044       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7045       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7046       auto MPI =
7047           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7048       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7049           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
7050           TempAlign);
7051       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7052       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7053     }
7054     setValue(&I, Res);
7055     DAG.setRoot(Res.getValue(1));
7056     return;
7057   }
7058   case Intrinsic::set_fpenv: {
7059     const DataLayout DLayout = DAG.getDataLayout();
7060     SDValue Env = getValue(I.getArgOperand(0));
7061     EVT EnvVT = Env.getValueType();
7062     Align TempAlign = DAG.getEVTAlign(EnvVT);
7063     SDValue Chain = getRoot();
7064     // If SET_FPENV is custom or legal, use it. Otherwise use loading
7065     // environment from memory.
7066     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7067       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7068     } else {
7069       // Allocate space in stack, copy environment bits into it and use this
7070       // memory in SET_FPENV_MEM.
7071       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7072       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7073       auto MPI =
7074           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7075       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7076                            MachineMemOperand::MOStore);
7077       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7078           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
7079           TempAlign);
7080       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7081     }
7082     DAG.setRoot(Chain);
7083     return;
7084   }
7085   case Intrinsic::reset_fpenv:
7086     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7087     return;
7088   case Intrinsic::get_fpmode:
7089     Res = DAG.getNode(
7090         ISD::GET_FPMODE, sdl,
7091         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7092                       MVT::Other),
7093         DAG.getRoot());
7094     setValue(&I, Res);
7095     DAG.setRoot(Res.getValue(1));
7096     return;
7097   case Intrinsic::set_fpmode:
7098     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7099                       getValue(I.getArgOperand(0)));
7100     DAG.setRoot(Res);
7101     return;
7102   case Intrinsic::reset_fpmode: {
7103     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7104     DAG.setRoot(Res);
7105     return;
7106   }
7107   case Intrinsic::pcmarker: {
7108     SDValue Tmp = getValue(I.getArgOperand(0));
7109     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7110     return;
7111   }
7112   case Intrinsic::readcyclecounter: {
7113     SDValue Op = getRoot();
7114     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7115                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7116     setValue(&I, Res);
7117     DAG.setRoot(Res.getValue(1));
7118     return;
7119   }
7120   case Intrinsic::readsteadycounter: {
7121     SDValue Op = getRoot();
7122     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7123                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7124     setValue(&I, Res);
7125     DAG.setRoot(Res.getValue(1));
7126     return;
7127   }
7128   case Intrinsic::bitreverse:
7129     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7130                              getValue(I.getArgOperand(0)).getValueType(),
7131                              getValue(I.getArgOperand(0))));
7132     return;
7133   case Intrinsic::bswap:
7134     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7135                              getValue(I.getArgOperand(0)).getValueType(),
7136                              getValue(I.getArgOperand(0))));
7137     return;
7138   case Intrinsic::cttz: {
7139     SDValue Arg = getValue(I.getArgOperand(0));
7140     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7141     EVT Ty = Arg.getValueType();
7142     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7143                              sdl, Ty, Arg));
7144     return;
7145   }
7146   case Intrinsic::ctlz: {
7147     SDValue Arg = getValue(I.getArgOperand(0));
7148     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7149     EVT Ty = Arg.getValueType();
7150     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7151                              sdl, Ty, Arg));
7152     return;
7153   }
7154   case Intrinsic::ctpop: {
7155     SDValue Arg = getValue(I.getArgOperand(0));
7156     EVT Ty = Arg.getValueType();
7157     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7158     return;
7159   }
7160   case Intrinsic::fshl:
7161   case Intrinsic::fshr: {
7162     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7163     SDValue X = getValue(I.getArgOperand(0));
7164     SDValue Y = getValue(I.getArgOperand(1));
7165     SDValue Z = getValue(I.getArgOperand(2));
7166     EVT VT = X.getValueType();
7167 
7168     if (X == Y) {
7169       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7170       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7171     } else {
7172       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7173       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7174     }
7175     return;
7176   }
7177   case Intrinsic::sadd_sat: {
7178     SDValue Op1 = getValue(I.getArgOperand(0));
7179     SDValue Op2 = getValue(I.getArgOperand(1));
7180     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7181     return;
7182   }
7183   case Intrinsic::uadd_sat: {
7184     SDValue Op1 = getValue(I.getArgOperand(0));
7185     SDValue Op2 = getValue(I.getArgOperand(1));
7186     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7187     return;
7188   }
7189   case Intrinsic::ssub_sat: {
7190     SDValue Op1 = getValue(I.getArgOperand(0));
7191     SDValue Op2 = getValue(I.getArgOperand(1));
7192     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7193     return;
7194   }
7195   case Intrinsic::usub_sat: {
7196     SDValue Op1 = getValue(I.getArgOperand(0));
7197     SDValue Op2 = getValue(I.getArgOperand(1));
7198     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7199     return;
7200   }
7201   case Intrinsic::sshl_sat: {
7202     SDValue Op1 = getValue(I.getArgOperand(0));
7203     SDValue Op2 = getValue(I.getArgOperand(1));
7204     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7205     return;
7206   }
7207   case Intrinsic::ushl_sat: {
7208     SDValue Op1 = getValue(I.getArgOperand(0));
7209     SDValue Op2 = getValue(I.getArgOperand(1));
7210     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7211     return;
7212   }
7213   case Intrinsic::smul_fix:
7214   case Intrinsic::umul_fix:
7215   case Intrinsic::smul_fix_sat:
7216   case Intrinsic::umul_fix_sat: {
7217     SDValue Op1 = getValue(I.getArgOperand(0));
7218     SDValue Op2 = getValue(I.getArgOperand(1));
7219     SDValue Op3 = getValue(I.getArgOperand(2));
7220     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7221                              Op1.getValueType(), Op1, Op2, Op3));
7222     return;
7223   }
7224   case Intrinsic::sdiv_fix:
7225   case Intrinsic::udiv_fix:
7226   case Intrinsic::sdiv_fix_sat:
7227   case Intrinsic::udiv_fix_sat: {
7228     SDValue Op1 = getValue(I.getArgOperand(0));
7229     SDValue Op2 = getValue(I.getArgOperand(1));
7230     SDValue Op3 = getValue(I.getArgOperand(2));
7231     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7232                               Op1, Op2, Op3, DAG, TLI));
7233     return;
7234   }
7235   case Intrinsic::smax: {
7236     SDValue Op1 = getValue(I.getArgOperand(0));
7237     SDValue Op2 = getValue(I.getArgOperand(1));
7238     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7239     return;
7240   }
7241   case Intrinsic::smin: {
7242     SDValue Op1 = getValue(I.getArgOperand(0));
7243     SDValue Op2 = getValue(I.getArgOperand(1));
7244     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7245     return;
7246   }
7247   case Intrinsic::umax: {
7248     SDValue Op1 = getValue(I.getArgOperand(0));
7249     SDValue Op2 = getValue(I.getArgOperand(1));
7250     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7251     return;
7252   }
7253   case Intrinsic::umin: {
7254     SDValue Op1 = getValue(I.getArgOperand(0));
7255     SDValue Op2 = getValue(I.getArgOperand(1));
7256     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7257     return;
7258   }
7259   case Intrinsic::abs: {
7260     // TODO: Preserve "int min is poison" arg in SDAG?
7261     SDValue Op1 = getValue(I.getArgOperand(0));
7262     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7263     return;
7264   }
7265   case Intrinsic::scmp: {
7266     SDValue Op1 = getValue(I.getArgOperand(0));
7267     SDValue Op2 = getValue(I.getArgOperand(1));
7268     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7269     setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7270     break;
7271   }
7272   case Intrinsic::ucmp: {
7273     SDValue Op1 = getValue(I.getArgOperand(0));
7274     SDValue Op2 = getValue(I.getArgOperand(1));
7275     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7276     setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7277     break;
7278   }
7279   case Intrinsic::stacksave: {
7280     SDValue Op = getRoot();
7281     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7282     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7283     setValue(&I, Res);
7284     DAG.setRoot(Res.getValue(1));
7285     return;
7286   }
7287   case Intrinsic::stackrestore:
7288     Res = getValue(I.getArgOperand(0));
7289     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7290     return;
7291   case Intrinsic::get_dynamic_area_offset: {
7292     SDValue Op = getRoot();
7293     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7294     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7295     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7296     // target.
7297     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7298       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7299                          " intrinsic!");
7300     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7301                       Op);
7302     DAG.setRoot(Op);
7303     setValue(&I, Res);
7304     return;
7305   }
7306   case Intrinsic::stackguard: {
7307     MachineFunction &MF = DAG.getMachineFunction();
7308     const Module &M = *MF.getFunction().getParent();
7309     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7310     SDValue Chain = getRoot();
7311     if (TLI.useLoadStackGuardNode()) {
7312       Res = getLoadStackGuard(DAG, sdl, Chain);
7313       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7314     } else {
7315       const Value *Global = TLI.getSDagStackGuard(M);
7316       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7317       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7318                         MachinePointerInfo(Global, 0), Align,
7319                         MachineMemOperand::MOVolatile);
7320     }
7321     if (TLI.useStackGuardXorFP())
7322       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7323     DAG.setRoot(Chain);
7324     setValue(&I, Res);
7325     return;
7326   }
7327   case Intrinsic::stackprotector: {
7328     // Emit code into the DAG to store the stack guard onto the stack.
7329     MachineFunction &MF = DAG.getMachineFunction();
7330     MachineFrameInfo &MFI = MF.getFrameInfo();
7331     SDValue Src, Chain = getRoot();
7332 
7333     if (TLI.useLoadStackGuardNode())
7334       Src = getLoadStackGuard(DAG, sdl, Chain);
7335     else
7336       Src = getValue(I.getArgOperand(0));   // The guard's value.
7337 
7338     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7339 
7340     int FI = FuncInfo.StaticAllocaMap[Slot];
7341     MFI.setStackProtectorIndex(FI);
7342     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7343 
7344     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7345 
7346     // Store the stack protector onto the stack.
7347     Res = DAG.getStore(
7348         Chain, sdl, Src, FIN,
7349         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7350         MaybeAlign(), MachineMemOperand::MOVolatile);
7351     setValue(&I, Res);
7352     DAG.setRoot(Res);
7353     return;
7354   }
7355   case Intrinsic::objectsize:
7356     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7357 
7358   case Intrinsic::is_constant:
7359     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7360 
7361   case Intrinsic::annotation:
7362   case Intrinsic::ptr_annotation:
7363   case Intrinsic::launder_invariant_group:
7364   case Intrinsic::strip_invariant_group:
7365     // Drop the intrinsic, but forward the value
7366     setValue(&I, getValue(I.getOperand(0)));
7367     return;
7368 
7369   case Intrinsic::assume:
7370   case Intrinsic::experimental_noalias_scope_decl:
7371   case Intrinsic::var_annotation:
7372   case Intrinsic::sideeffect:
7373     // Discard annotate attributes, noalias scope declarations, assumptions, and
7374     // artificial side-effects.
7375     return;
7376 
7377   case Intrinsic::codeview_annotation: {
7378     // Emit a label associated with this metadata.
7379     MachineFunction &MF = DAG.getMachineFunction();
7380     MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7381     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7382     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7383     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7384     DAG.setRoot(Res);
7385     return;
7386   }
7387 
7388   case Intrinsic::init_trampoline: {
7389     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7390 
7391     SDValue Ops[6];
7392     Ops[0] = getRoot();
7393     Ops[1] = getValue(I.getArgOperand(0));
7394     Ops[2] = getValue(I.getArgOperand(1));
7395     Ops[3] = getValue(I.getArgOperand(2));
7396     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7397     Ops[5] = DAG.getSrcValue(F);
7398 
7399     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7400 
7401     DAG.setRoot(Res);
7402     return;
7403   }
7404   case Intrinsic::adjust_trampoline:
7405     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7406                              TLI.getPointerTy(DAG.getDataLayout()),
7407                              getValue(I.getArgOperand(0))));
7408     return;
7409   case Intrinsic::gcroot: {
7410     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7411            "only valid in functions with gc specified, enforced by Verifier");
7412     assert(GFI && "implied by previous");
7413     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7414     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7415 
7416     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7417     GFI->addStackRoot(FI->getIndex(), TypeMap);
7418     return;
7419   }
7420   case Intrinsic::gcread:
7421   case Intrinsic::gcwrite:
7422     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7423   case Intrinsic::get_rounding:
7424     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7425     setValue(&I, Res);
7426     DAG.setRoot(Res.getValue(1));
7427     return;
7428 
7429   case Intrinsic::expect:
7430     // Just replace __builtin_expect(exp, c) with EXP.
7431     setValue(&I, getValue(I.getArgOperand(0)));
7432     return;
7433 
7434   case Intrinsic::ubsantrap:
7435   case Intrinsic::debugtrap:
7436   case Intrinsic::trap: {
7437     StringRef TrapFuncName =
7438         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7439     if (TrapFuncName.empty()) {
7440       switch (Intrinsic) {
7441       case Intrinsic::trap:
7442         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7443         break;
7444       case Intrinsic::debugtrap:
7445         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7446         break;
7447       case Intrinsic::ubsantrap:
7448         DAG.setRoot(DAG.getNode(
7449             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7450             DAG.getTargetConstant(
7451                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7452                 MVT::i32)));
7453         break;
7454       default: llvm_unreachable("unknown trap intrinsic");
7455       }
7456       return;
7457     }
7458     TargetLowering::ArgListTy Args;
7459     if (Intrinsic == Intrinsic::ubsantrap) {
7460       Args.push_back(TargetLoweringBase::ArgListEntry());
7461       Args[0].Val = I.getArgOperand(0);
7462       Args[0].Node = getValue(Args[0].Val);
7463       Args[0].Ty = Args[0].Val->getType();
7464     }
7465 
7466     TargetLowering::CallLoweringInfo CLI(DAG);
7467     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7468         CallingConv::C, I.getType(),
7469         DAG.getExternalSymbol(TrapFuncName.data(),
7470                               TLI.getPointerTy(DAG.getDataLayout())),
7471         std::move(Args));
7472 
7473     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7474     DAG.setRoot(Result.second);
7475     return;
7476   }
7477 
7478   case Intrinsic::allow_runtime_check:
7479   case Intrinsic::allow_ubsan_check:
7480     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7481     return;
7482 
7483   case Intrinsic::uadd_with_overflow:
7484   case Intrinsic::sadd_with_overflow:
7485   case Intrinsic::usub_with_overflow:
7486   case Intrinsic::ssub_with_overflow:
7487   case Intrinsic::umul_with_overflow:
7488   case Intrinsic::smul_with_overflow: {
7489     ISD::NodeType Op;
7490     switch (Intrinsic) {
7491     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7492     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7493     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7494     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7495     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7496     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7497     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7498     }
7499     SDValue Op1 = getValue(I.getArgOperand(0));
7500     SDValue Op2 = getValue(I.getArgOperand(1));
7501 
7502     EVT ResultVT = Op1.getValueType();
7503     EVT OverflowVT = MVT::i1;
7504     if (ResultVT.isVector())
7505       OverflowVT = EVT::getVectorVT(
7506           *Context, OverflowVT, ResultVT.getVectorElementCount());
7507 
7508     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7509     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7510     return;
7511   }
7512   case Intrinsic::prefetch: {
7513     SDValue Ops[5];
7514     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7515     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7516     Ops[0] = DAG.getRoot();
7517     Ops[1] = getValue(I.getArgOperand(0));
7518     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7519                                    MVT::i32);
7520     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7521                                    MVT::i32);
7522     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7523                                    MVT::i32);
7524     SDValue Result = DAG.getMemIntrinsicNode(
7525         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7526         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7527         /* align */ std::nullopt, Flags);
7528 
7529     // Chain the prefetch in parallel with any pending loads, to stay out of
7530     // the way of later optimizations.
7531     PendingLoads.push_back(Result);
7532     Result = getRoot();
7533     DAG.setRoot(Result);
7534     return;
7535   }
7536   case Intrinsic::lifetime_start:
7537   case Intrinsic::lifetime_end: {
7538     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7539     // Stack coloring is not enabled in O0, discard region information.
7540     if (TM.getOptLevel() == CodeGenOptLevel::None)
7541       return;
7542 
7543     const int64_t ObjectSize =
7544         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7545     Value *const ObjectPtr = I.getArgOperand(1);
7546     SmallVector<const Value *, 4> Allocas;
7547     getUnderlyingObjects(ObjectPtr, Allocas);
7548 
7549     for (const Value *Alloca : Allocas) {
7550       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7551 
7552       // Could not find an Alloca.
7553       if (!LifetimeObject)
7554         continue;
7555 
7556       // First check that the Alloca is static, otherwise it won't have a
7557       // valid frame index.
7558       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7559       if (SI == FuncInfo.StaticAllocaMap.end())
7560         return;
7561 
7562       const int FrameIndex = SI->second;
7563       int64_t Offset;
7564       if (GetPointerBaseWithConstantOffset(
7565               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7566         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7567       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7568                                 Offset);
7569       DAG.setRoot(Res);
7570     }
7571     return;
7572   }
7573   case Intrinsic::pseudoprobe: {
7574     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7575     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7576     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7577     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7578     DAG.setRoot(Res);
7579     return;
7580   }
7581   case Intrinsic::invariant_start:
7582     // Discard region information.
7583     setValue(&I,
7584              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7585     return;
7586   case Intrinsic::invariant_end:
7587     // Discard region information.
7588     return;
7589   case Intrinsic::clear_cache: {
7590     SDValue InputChain = DAG.getRoot();
7591     SDValue StartVal = getValue(I.getArgOperand(0));
7592     SDValue EndVal = getValue(I.getArgOperand(1));
7593     Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7594                       {InputChain, StartVal, EndVal});
7595     setValue(&I, Res);
7596     DAG.setRoot(Res);
7597     return;
7598   }
7599   case Intrinsic::donothing:
7600   case Intrinsic::seh_try_begin:
7601   case Intrinsic::seh_scope_begin:
7602   case Intrinsic::seh_try_end:
7603   case Intrinsic::seh_scope_end:
7604     // ignore
7605     return;
7606   case Intrinsic::experimental_stackmap:
7607     visitStackmap(I);
7608     return;
7609   case Intrinsic::experimental_patchpoint_void:
7610   case Intrinsic::experimental_patchpoint:
7611     visitPatchpoint(I);
7612     return;
7613   case Intrinsic::experimental_gc_statepoint:
7614     LowerStatepoint(cast<GCStatepointInst>(I));
7615     return;
7616   case Intrinsic::experimental_gc_result:
7617     visitGCResult(cast<GCResultInst>(I));
7618     return;
7619   case Intrinsic::experimental_gc_relocate:
7620     visitGCRelocate(cast<GCRelocateInst>(I));
7621     return;
7622   case Intrinsic::instrprof_cover:
7623     llvm_unreachable("instrprof failed to lower a cover");
7624   case Intrinsic::instrprof_increment:
7625     llvm_unreachable("instrprof failed to lower an increment");
7626   case Intrinsic::instrprof_timestamp:
7627     llvm_unreachable("instrprof failed to lower a timestamp");
7628   case Intrinsic::instrprof_value_profile:
7629     llvm_unreachable("instrprof failed to lower a value profiling call");
7630   case Intrinsic::instrprof_mcdc_parameters:
7631     llvm_unreachable("instrprof failed to lower mcdc parameters");
7632   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7633     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7634   case Intrinsic::localescape: {
7635     MachineFunction &MF = DAG.getMachineFunction();
7636     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7637 
7638     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7639     // is the same on all targets.
7640     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7641       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7642       if (isa<ConstantPointerNull>(Arg))
7643         continue; // Skip null pointers. They represent a hole in index space.
7644       AllocaInst *Slot = cast<AllocaInst>(Arg);
7645       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7646              "can only escape static allocas");
7647       int FI = FuncInfo.StaticAllocaMap[Slot];
7648       MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7649           GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7650       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7651               TII->get(TargetOpcode::LOCAL_ESCAPE))
7652           .addSym(FrameAllocSym)
7653           .addFrameIndex(FI);
7654     }
7655 
7656     return;
7657   }
7658 
7659   case Intrinsic::localrecover: {
7660     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7661     MachineFunction &MF = DAG.getMachineFunction();
7662 
7663     // Get the symbol that defines the frame offset.
7664     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7665     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7666     unsigned IdxVal =
7667         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7668     MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7669         GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7670 
7671     Value *FP = I.getArgOperand(1);
7672     SDValue FPVal = getValue(FP);
7673     EVT PtrVT = FPVal.getValueType();
7674 
7675     // Create a MCSymbol for the label to avoid any target lowering
7676     // that would make this PC relative.
7677     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7678     SDValue OffsetVal =
7679         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7680 
7681     // Add the offset to the FP.
7682     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7683     setValue(&I, Add);
7684 
7685     return;
7686   }
7687 
7688   case Intrinsic::eh_exceptionpointer:
7689   case Intrinsic::eh_exceptioncode: {
7690     // Get the exception pointer vreg, copy from it, and resize it to fit.
7691     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7692     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7693     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7694     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7695     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7696     if (Intrinsic == Intrinsic::eh_exceptioncode)
7697       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7698     setValue(&I, N);
7699     return;
7700   }
7701   case Intrinsic::xray_customevent: {
7702     // Here we want to make sure that the intrinsic behaves as if it has a
7703     // specific calling convention.
7704     const auto &Triple = DAG.getTarget().getTargetTriple();
7705     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7706       return;
7707 
7708     SmallVector<SDValue, 8> Ops;
7709 
7710     // We want to say that we always want the arguments in registers.
7711     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7712     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7713     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7714     SDValue Chain = getRoot();
7715     Ops.push_back(LogEntryVal);
7716     Ops.push_back(StrSizeVal);
7717     Ops.push_back(Chain);
7718 
7719     // We need to enforce the calling convention for the callsite, so that
7720     // argument ordering is enforced correctly, and that register allocation can
7721     // see that some registers may be assumed clobbered and have to preserve
7722     // them across calls to the intrinsic.
7723     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7724                                            sdl, NodeTys, Ops);
7725     SDValue patchableNode = SDValue(MN, 0);
7726     DAG.setRoot(patchableNode);
7727     setValue(&I, patchableNode);
7728     return;
7729   }
7730   case Intrinsic::xray_typedevent: {
7731     // Here we want to make sure that the intrinsic behaves as if it has a
7732     // specific calling convention.
7733     const auto &Triple = DAG.getTarget().getTargetTriple();
7734     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7735       return;
7736 
7737     SmallVector<SDValue, 8> Ops;
7738 
7739     // We want to say that we always want the arguments in registers.
7740     // It's unclear to me how manipulating the selection DAG here forces callers
7741     // to provide arguments in registers instead of on the stack.
7742     SDValue LogTypeId = getValue(I.getArgOperand(0));
7743     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7744     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7745     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7746     SDValue Chain = getRoot();
7747     Ops.push_back(LogTypeId);
7748     Ops.push_back(LogEntryVal);
7749     Ops.push_back(StrSizeVal);
7750     Ops.push_back(Chain);
7751 
7752     // We need to enforce the calling convention for the callsite, so that
7753     // argument ordering is enforced correctly, and that register allocation can
7754     // see that some registers may be assumed clobbered and have to preserve
7755     // them across calls to the intrinsic.
7756     MachineSDNode *MN = DAG.getMachineNode(
7757         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7758     SDValue patchableNode = SDValue(MN, 0);
7759     DAG.setRoot(patchableNode);
7760     setValue(&I, patchableNode);
7761     return;
7762   }
7763   case Intrinsic::experimental_deoptimize:
7764     LowerDeoptimizeCall(&I);
7765     return;
7766   case Intrinsic::experimental_stepvector:
7767     visitStepVector(I);
7768     return;
7769   case Intrinsic::vector_reduce_fadd:
7770   case Intrinsic::vector_reduce_fmul:
7771   case Intrinsic::vector_reduce_add:
7772   case Intrinsic::vector_reduce_mul:
7773   case Intrinsic::vector_reduce_and:
7774   case Intrinsic::vector_reduce_or:
7775   case Intrinsic::vector_reduce_xor:
7776   case Intrinsic::vector_reduce_smax:
7777   case Intrinsic::vector_reduce_smin:
7778   case Intrinsic::vector_reduce_umax:
7779   case Intrinsic::vector_reduce_umin:
7780   case Intrinsic::vector_reduce_fmax:
7781   case Intrinsic::vector_reduce_fmin:
7782   case Intrinsic::vector_reduce_fmaximum:
7783   case Intrinsic::vector_reduce_fminimum:
7784     visitVectorReduce(I, Intrinsic);
7785     return;
7786 
7787   case Intrinsic::icall_branch_funnel: {
7788     SmallVector<SDValue, 16> Ops;
7789     Ops.push_back(getValue(I.getArgOperand(0)));
7790 
7791     int64_t Offset;
7792     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7793         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7794     if (!Base)
7795       report_fatal_error(
7796           "llvm.icall.branch.funnel operand must be a GlobalValue");
7797     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7798 
7799     struct BranchFunnelTarget {
7800       int64_t Offset;
7801       SDValue Target;
7802     };
7803     SmallVector<BranchFunnelTarget, 8> Targets;
7804 
7805     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7806       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7807           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7808       if (ElemBase != Base)
7809         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7810                            "to the same GlobalValue");
7811 
7812       SDValue Val = getValue(I.getArgOperand(Op + 1));
7813       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7814       if (!GA)
7815         report_fatal_error(
7816             "llvm.icall.branch.funnel operand must be a GlobalValue");
7817       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7818                                      GA->getGlobal(), sdl, Val.getValueType(),
7819                                      GA->getOffset())});
7820     }
7821     llvm::sort(Targets,
7822                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7823                  return T1.Offset < T2.Offset;
7824                });
7825 
7826     for (auto &T : Targets) {
7827       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7828       Ops.push_back(T.Target);
7829     }
7830 
7831     Ops.push_back(DAG.getRoot()); // Chain
7832     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7833                                  MVT::Other, Ops),
7834               0);
7835     DAG.setRoot(N);
7836     setValue(&I, N);
7837     HasTailCall = true;
7838     return;
7839   }
7840 
7841   case Intrinsic::wasm_landingpad_index:
7842     // Information this intrinsic contained has been transferred to
7843     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7844     // delete it now.
7845     return;
7846 
7847   case Intrinsic::aarch64_settag:
7848   case Intrinsic::aarch64_settag_zero: {
7849     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7850     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7851     SDValue Val = TSI.EmitTargetCodeForSetTag(
7852         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7853         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7854         ZeroMemory);
7855     DAG.setRoot(Val);
7856     setValue(&I, Val);
7857     return;
7858   }
7859   case Intrinsic::amdgcn_cs_chain: {
7860     assert(I.arg_size() == 5 && "Additional args not supported yet");
7861     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7862            "Non-zero flags not supported yet");
7863 
7864     // At this point we don't care if it's amdgpu_cs_chain or
7865     // amdgpu_cs_chain_preserve.
7866     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7867 
7868     Type *RetTy = I.getType();
7869     assert(RetTy->isVoidTy() && "Should not return");
7870 
7871     SDValue Callee = getValue(I.getOperand(0));
7872 
7873     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7874     // We'll also tack the value of the EXEC mask at the end.
7875     TargetLowering::ArgListTy Args;
7876     Args.reserve(3);
7877 
7878     for (unsigned Idx : {2, 3, 1}) {
7879       TargetLowering::ArgListEntry Arg;
7880       Arg.Node = getValue(I.getOperand(Idx));
7881       Arg.Ty = I.getOperand(Idx)->getType();
7882       Arg.setAttributes(&I, Idx);
7883       Args.push_back(Arg);
7884     }
7885 
7886     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7887     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7888     Args[2].IsInReg = true; // EXEC should be inreg
7889 
7890     TargetLowering::CallLoweringInfo CLI(DAG);
7891     CLI.setDebugLoc(getCurSDLoc())
7892         .setChain(getRoot())
7893         .setCallee(CC, RetTy, Callee, std::move(Args))
7894         .setNoReturn(true)
7895         .setTailCall(true)
7896         .setConvergent(I.isConvergent());
7897     CLI.CB = &I;
7898     std::pair<SDValue, SDValue> Result =
7899         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7900     (void)Result;
7901     assert(!Result.first.getNode() && !Result.second.getNode() &&
7902            "Should've lowered as tail call");
7903 
7904     HasTailCall = true;
7905     return;
7906   }
7907   case Intrinsic::ptrmask: {
7908     SDValue Ptr = getValue(I.getOperand(0));
7909     SDValue Mask = getValue(I.getOperand(1));
7910 
7911     // On arm64_32, pointers are 32 bits when stored in memory, but
7912     // zero-extended to 64 bits when in registers.  Thus the mask is 32 bits to
7913     // match the index type, but the pointer is 64 bits, so the the mask must be
7914     // zero-extended up to 64 bits to match the pointer.
7915     EVT PtrVT =
7916         TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7917     EVT MemVT =
7918         TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7919     assert(PtrVT == Ptr.getValueType());
7920     assert(MemVT == Mask.getValueType());
7921     if (MemVT != PtrVT)
7922       Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
7923 
7924     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7925     return;
7926   }
7927   case Intrinsic::threadlocal_address: {
7928     setValue(&I, getValue(I.getOperand(0)));
7929     return;
7930   }
7931   case Intrinsic::get_active_lane_mask: {
7932     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7933     SDValue Index = getValue(I.getOperand(0));
7934     EVT ElementVT = Index.getValueType();
7935 
7936     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7937       visitTargetIntrinsic(I, Intrinsic);
7938       return;
7939     }
7940 
7941     SDValue TripCount = getValue(I.getOperand(1));
7942     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7943                                  CCVT.getVectorElementCount());
7944 
7945     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7946     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7947     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7948     SDValue VectorInduction = DAG.getNode(
7949         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7950     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7951                                  VectorTripCount, ISD::CondCode::SETULT);
7952     setValue(&I, SetCC);
7953     return;
7954   }
7955   case Intrinsic::experimental_get_vector_length: {
7956     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7957            "Expected positive VF");
7958     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7959     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7960 
7961     SDValue Count = getValue(I.getOperand(0));
7962     EVT CountVT = Count.getValueType();
7963 
7964     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7965       visitTargetIntrinsic(I, Intrinsic);
7966       return;
7967     }
7968 
7969     // Expand to a umin between the trip count and the maximum elements the type
7970     // can hold.
7971     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7972 
7973     // Extend the trip count to at least the result VT.
7974     if (CountVT.bitsLT(VT)) {
7975       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7976       CountVT = VT;
7977     }
7978 
7979     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7980                                          ElementCount::get(VF, IsScalable));
7981 
7982     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7983     // Clip to the result type if needed.
7984     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7985 
7986     setValue(&I, Trunc);
7987     return;
7988   }
7989   case Intrinsic::experimental_vector_partial_reduce_add: {
7990     SDValue OpNode = getValue(I.getOperand(1));
7991     EVT ReducedTy = EVT::getEVT(I.getType());
7992     EVT FullTy = OpNode.getValueType();
7993 
7994     unsigned Stride = ReducedTy.getVectorMinNumElements();
7995     unsigned ScaleFactor = FullTy.getVectorMinNumElements() / Stride;
7996 
7997     // Collect all of the subvectors
7998     std::deque<SDValue> Subvectors;
7999     Subvectors.push_back(getValue(I.getOperand(0)));
8000     for (unsigned i = 0; i < ScaleFactor; i++) {
8001       auto SourceIndex = DAG.getVectorIdxConstant(i * Stride, sdl);
8002       Subvectors.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ReducedTy,
8003                                        {OpNode, SourceIndex}));
8004     }
8005 
8006     // Flatten the subvector tree
8007     while (Subvectors.size() > 1) {
8008       Subvectors.push_back(DAG.getNode(ISD::ADD, sdl, ReducedTy,
8009                                        {Subvectors[0], Subvectors[1]}));
8010       Subvectors.pop_front();
8011       Subvectors.pop_front();
8012     }
8013 
8014     assert(Subvectors.size() == 1 &&
8015            "There should only be one subvector after tree flattening");
8016 
8017     setValue(&I, Subvectors[0]);
8018     return;
8019   }
8020   case Intrinsic::experimental_cttz_elts: {
8021     auto DL = getCurSDLoc();
8022     SDValue Op = getValue(I.getOperand(0));
8023     EVT OpVT = Op.getValueType();
8024 
8025     if (!TLI.shouldExpandCttzElements(OpVT)) {
8026       visitTargetIntrinsic(I, Intrinsic);
8027       return;
8028     }
8029 
8030     if (OpVT.getScalarType() != MVT::i1) {
8031       // Compare the input vector elements to zero & use to count trailing zeros
8032       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
8033       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
8034                               OpVT.getVectorElementCount());
8035       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
8036     }
8037 
8038     // If the zero-is-poison flag is set, we can assume the upper limit
8039     // of the result is VF-1.
8040     bool ZeroIsPoison =
8041         !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8042     ConstantRange VScaleRange(1, true); // Dummy value.
8043     if (isa<ScalableVectorType>(I.getOperand(0)->getType()))
8044       VScaleRange = getVScaleRange(I.getCaller(), 64);
8045     unsigned EltWidth = TLI.getBitWidthForCttzElements(
8046         I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
8047 
8048     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
8049 
8050     // Create the new vector type & get the vector length
8051     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
8052                                  OpVT.getVectorElementCount());
8053 
8054     SDValue VL =
8055         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
8056 
8057     SDValue StepVec = DAG.getStepVector(DL, NewVT);
8058     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
8059     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
8060     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
8061     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
8062     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
8063     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
8064 
8065     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8066     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
8067 
8068     setValue(&I, Ret);
8069     return;
8070   }
8071   case Intrinsic::vector_insert: {
8072     SDValue Vec = getValue(I.getOperand(0));
8073     SDValue SubVec = getValue(I.getOperand(1));
8074     SDValue Index = getValue(I.getOperand(2));
8075 
8076     // The intrinsic's index type is i64, but the SDNode requires an index type
8077     // suitable for the target. Convert the index as required.
8078     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8079     if (Index.getValueType() != VectorIdxTy)
8080       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8081 
8082     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8083     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8084                              Index));
8085     return;
8086   }
8087   case Intrinsic::vector_extract: {
8088     SDValue Vec = getValue(I.getOperand(0));
8089     SDValue Index = getValue(I.getOperand(1));
8090     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8091 
8092     // The intrinsic's index type is i64, but the SDNode requires an index type
8093     // suitable for the target. Convert the index as required.
8094     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8095     if (Index.getValueType() != VectorIdxTy)
8096       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8097 
8098     setValue(&I,
8099              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8100     return;
8101   }
8102   case Intrinsic::vector_reverse:
8103     visitVectorReverse(I);
8104     return;
8105   case Intrinsic::vector_splice:
8106     visitVectorSplice(I);
8107     return;
8108   case Intrinsic::callbr_landingpad:
8109     visitCallBrLandingPad(I);
8110     return;
8111   case Intrinsic::vector_interleave2:
8112     visitVectorInterleave(I);
8113     return;
8114   case Intrinsic::vector_deinterleave2:
8115     visitVectorDeinterleave(I);
8116     return;
8117   case Intrinsic::experimental_vector_compress:
8118     setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8119                              getValue(I.getArgOperand(0)).getValueType(),
8120                              getValue(I.getArgOperand(0)),
8121                              getValue(I.getArgOperand(1)),
8122                              getValue(I.getArgOperand(2)), Flags));
8123     return;
8124   case Intrinsic::experimental_convergence_anchor:
8125   case Intrinsic::experimental_convergence_entry:
8126   case Intrinsic::experimental_convergence_loop:
8127     visitConvergenceControl(I, Intrinsic);
8128     return;
8129   case Intrinsic::experimental_vector_histogram_add: {
8130     visitVectorHistogram(I, Intrinsic);
8131     return;
8132   }
8133   }
8134 }
8135 
visitConstrainedFPIntrinsic(const ConstrainedFPIntrinsic & FPI)8136 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8137     const ConstrainedFPIntrinsic &FPI) {
8138   SDLoc sdl = getCurSDLoc();
8139 
8140   // We do not need to serialize constrained FP intrinsics against
8141   // each other or against (nonvolatile) loads, so they can be
8142   // chained like loads.
8143   SDValue Chain = DAG.getRoot();
8144   SmallVector<SDValue, 4> Opers;
8145   Opers.push_back(Chain);
8146   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8147     Opers.push_back(getValue(FPI.getArgOperand(I)));
8148 
8149   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
8150     assert(Result.getNode()->getNumValues() == 2);
8151 
8152     // Push node to the appropriate list so that future instructions can be
8153     // chained up correctly.
8154     SDValue OutChain = Result.getValue(1);
8155     switch (EB) {
8156     case fp::ExceptionBehavior::ebIgnore:
8157       // The only reason why ebIgnore nodes still need to be chained is that
8158       // they might depend on the current rounding mode, and therefore must
8159       // not be moved across instruction that may change that mode.
8160       [[fallthrough]];
8161     case fp::ExceptionBehavior::ebMayTrap:
8162       // These must not be moved across calls or instructions that may change
8163       // floating-point exception masks.
8164       PendingConstrainedFP.push_back(OutChain);
8165       break;
8166     case fp::ExceptionBehavior::ebStrict:
8167       // These must not be moved across calls or instructions that may change
8168       // floating-point exception masks or read floating-point exception flags.
8169       // In addition, they cannot be optimized out even if unused.
8170       PendingConstrainedFPStrict.push_back(OutChain);
8171       break;
8172     }
8173   };
8174 
8175   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8176   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8177   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8178   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8179 
8180   SDNodeFlags Flags;
8181   if (EB == fp::ExceptionBehavior::ebIgnore)
8182     Flags.setNoFPExcept(true);
8183 
8184   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8185     Flags.copyFMF(*FPOp);
8186 
8187   unsigned Opcode;
8188   switch (FPI.getIntrinsicID()) {
8189   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8190 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8191   case Intrinsic::INTRINSIC:                                                   \
8192     Opcode = ISD::STRICT_##DAGN;                                               \
8193     break;
8194 #include "llvm/IR/ConstrainedOps.def"
8195   case Intrinsic::experimental_constrained_fmuladd: {
8196     Opcode = ISD::STRICT_FMA;
8197     // Break fmuladd into fmul and fadd.
8198     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8199         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8200       Opers.pop_back();
8201       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8202       pushOutChain(Mul, EB);
8203       Opcode = ISD::STRICT_FADD;
8204       Opers.clear();
8205       Opers.push_back(Mul.getValue(1));
8206       Opers.push_back(Mul.getValue(0));
8207       Opers.push_back(getValue(FPI.getArgOperand(2)));
8208     }
8209     break;
8210   }
8211   }
8212 
8213   // A few strict DAG nodes carry additional operands that are not
8214   // set up by the default code above.
8215   switch (Opcode) {
8216   default: break;
8217   case ISD::STRICT_FP_ROUND:
8218     Opers.push_back(
8219         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8220     break;
8221   case ISD::STRICT_FSETCC:
8222   case ISD::STRICT_FSETCCS: {
8223     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8224     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8225     if (TM.Options.NoNaNsFPMath)
8226       Condition = getFCmpCodeWithoutNaN(Condition);
8227     Opers.push_back(DAG.getCondCode(Condition));
8228     break;
8229   }
8230   }
8231 
8232   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8233   pushOutChain(Result, EB);
8234 
8235   SDValue FPResult = Result.getValue(0);
8236   setValue(&FPI, FPResult);
8237 }
8238 
getISDForVPIntrinsic(const VPIntrinsic & VPIntrin)8239 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8240   std::optional<unsigned> ResOPC;
8241   switch (VPIntrin.getIntrinsicID()) {
8242   case Intrinsic::vp_ctlz: {
8243     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8244     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8245     break;
8246   }
8247   case Intrinsic::vp_cttz: {
8248     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8249     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8250     break;
8251   }
8252   case Intrinsic::vp_cttz_elts: {
8253     bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8254     ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8255     break;
8256   }
8257 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8258   case Intrinsic::VPID:                                                        \
8259     ResOPC = ISD::VPSD;                                                        \
8260     break;
8261 #include "llvm/IR/VPIntrinsics.def"
8262   }
8263 
8264   if (!ResOPC)
8265     llvm_unreachable(
8266         "Inconsistency: no SDNode available for this VPIntrinsic!");
8267 
8268   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8269       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8270     if (VPIntrin.getFastMathFlags().allowReassoc())
8271       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8272                                                 : ISD::VP_REDUCE_FMUL;
8273   }
8274 
8275   return *ResOPC;
8276 }
8277 
visitVPLoad(const VPIntrinsic & VPIntrin,EVT VT,const SmallVectorImpl<SDValue> & OpValues)8278 void SelectionDAGBuilder::visitVPLoad(
8279     const VPIntrinsic &VPIntrin, EVT VT,
8280     const SmallVectorImpl<SDValue> &OpValues) {
8281   SDLoc DL = getCurSDLoc();
8282   Value *PtrOperand = VPIntrin.getArgOperand(0);
8283   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8284   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8285   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8286   SDValue LD;
8287   // Do not serialize variable-length loads of constant memory with
8288   // anything.
8289   if (!Alignment)
8290     Alignment = DAG.getEVTAlign(VT);
8291   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8292   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8293   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8294   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8295       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8296       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8297   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8298                      MMO, false /*IsExpanding */);
8299   if (AddToChain)
8300     PendingLoads.push_back(LD.getValue(1));
8301   setValue(&VPIntrin, LD);
8302 }
8303 
visitVPGather(const VPIntrinsic & VPIntrin,EVT VT,const SmallVectorImpl<SDValue> & OpValues)8304 void SelectionDAGBuilder::visitVPGather(
8305     const VPIntrinsic &VPIntrin, EVT VT,
8306     const SmallVectorImpl<SDValue> &OpValues) {
8307   SDLoc DL = getCurSDLoc();
8308   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8309   Value *PtrOperand = VPIntrin.getArgOperand(0);
8310   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8311   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8312   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8313   SDValue LD;
8314   if (!Alignment)
8315     Alignment = DAG.getEVTAlign(VT.getScalarType());
8316   unsigned AS =
8317     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8318   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8319       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8320       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8321   SDValue Base, Index, Scale;
8322   ISD::MemIndexType IndexType;
8323   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8324                                     this, VPIntrin.getParent(),
8325                                     VT.getScalarStoreSize());
8326   if (!UniformBase) {
8327     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8328     Index = getValue(PtrOperand);
8329     IndexType = ISD::SIGNED_SCALED;
8330     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8331   }
8332   EVT IdxVT = Index.getValueType();
8333   EVT EltTy = IdxVT.getVectorElementType();
8334   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8335     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8336     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8337   }
8338   LD = DAG.getGatherVP(
8339       DAG.getVTList(VT, MVT::Other), VT, DL,
8340       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8341       IndexType);
8342   PendingLoads.push_back(LD.getValue(1));
8343   setValue(&VPIntrin, LD);
8344 }
8345 
visitVPStore(const VPIntrinsic & VPIntrin,const SmallVectorImpl<SDValue> & OpValues)8346 void SelectionDAGBuilder::visitVPStore(
8347     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8348   SDLoc DL = getCurSDLoc();
8349   Value *PtrOperand = VPIntrin.getArgOperand(1);
8350   EVT VT = OpValues[0].getValueType();
8351   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8352   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8353   SDValue ST;
8354   if (!Alignment)
8355     Alignment = DAG.getEVTAlign(VT);
8356   SDValue Ptr = OpValues[1];
8357   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8358   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8359       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8360       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8361   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8362                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8363                       /* IsTruncating */ false, /*IsCompressing*/ false);
8364   DAG.setRoot(ST);
8365   setValue(&VPIntrin, ST);
8366 }
8367 
visitVPScatter(const VPIntrinsic & VPIntrin,const SmallVectorImpl<SDValue> & OpValues)8368 void SelectionDAGBuilder::visitVPScatter(
8369     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8370   SDLoc DL = getCurSDLoc();
8371   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8372   Value *PtrOperand = VPIntrin.getArgOperand(1);
8373   EVT VT = OpValues[0].getValueType();
8374   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8375   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8376   SDValue ST;
8377   if (!Alignment)
8378     Alignment = DAG.getEVTAlign(VT.getScalarType());
8379   unsigned AS =
8380       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8381   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8382       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8383       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8384   SDValue Base, Index, Scale;
8385   ISD::MemIndexType IndexType;
8386   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8387                                     this, VPIntrin.getParent(),
8388                                     VT.getScalarStoreSize());
8389   if (!UniformBase) {
8390     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8391     Index = getValue(PtrOperand);
8392     IndexType = ISD::SIGNED_SCALED;
8393     Scale =
8394       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8395   }
8396   EVT IdxVT = Index.getValueType();
8397   EVT EltTy = IdxVT.getVectorElementType();
8398   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8399     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8400     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8401   }
8402   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8403                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8404                          OpValues[2], OpValues[3]},
8405                         MMO, IndexType);
8406   DAG.setRoot(ST);
8407   setValue(&VPIntrin, ST);
8408 }
8409 
visitVPStridedLoad(const VPIntrinsic & VPIntrin,EVT VT,const SmallVectorImpl<SDValue> & OpValues)8410 void SelectionDAGBuilder::visitVPStridedLoad(
8411     const VPIntrinsic &VPIntrin, EVT VT,
8412     const SmallVectorImpl<SDValue> &OpValues) {
8413   SDLoc DL = getCurSDLoc();
8414   Value *PtrOperand = VPIntrin.getArgOperand(0);
8415   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8416   if (!Alignment)
8417     Alignment = DAG.getEVTAlign(VT.getScalarType());
8418   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8419   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8420   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8421   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8422   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8423   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8424   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8425       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8426       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8427 
8428   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8429                                     OpValues[2], OpValues[3], MMO,
8430                                     false /*IsExpanding*/);
8431 
8432   if (AddToChain)
8433     PendingLoads.push_back(LD.getValue(1));
8434   setValue(&VPIntrin, LD);
8435 }
8436 
visitVPStridedStore(const VPIntrinsic & VPIntrin,const SmallVectorImpl<SDValue> & OpValues)8437 void SelectionDAGBuilder::visitVPStridedStore(
8438     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8439   SDLoc DL = getCurSDLoc();
8440   Value *PtrOperand = VPIntrin.getArgOperand(1);
8441   EVT VT = OpValues[0].getValueType();
8442   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8443   if (!Alignment)
8444     Alignment = DAG.getEVTAlign(VT.getScalarType());
8445   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8446   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8447   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8448       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8449       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8450 
8451   SDValue ST = DAG.getStridedStoreVP(
8452       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8453       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8454       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8455       /*IsCompressing*/ false);
8456 
8457   DAG.setRoot(ST);
8458   setValue(&VPIntrin, ST);
8459 }
8460 
visitVPCmp(const VPCmpIntrinsic & VPIntrin)8461 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8462   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8463   SDLoc DL = getCurSDLoc();
8464 
8465   ISD::CondCode Condition;
8466   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8467   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8468   if (IsFP) {
8469     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8470     // flags, but calls that don't return floating-point types can't be
8471     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8472     Condition = getFCmpCondCode(CondCode);
8473     if (TM.Options.NoNaNsFPMath)
8474       Condition = getFCmpCodeWithoutNaN(Condition);
8475   } else {
8476     Condition = getICmpCondCode(CondCode);
8477   }
8478 
8479   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8480   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8481   // #2 is the condition code
8482   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8483   SDValue EVL = getValue(VPIntrin.getOperand(4));
8484   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8485   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8486          "Unexpected target EVL type");
8487   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8488 
8489   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8490                                                         VPIntrin.getType());
8491   setValue(&VPIntrin,
8492            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8493 }
8494 
visitVectorPredicationIntrinsic(const VPIntrinsic & VPIntrin)8495 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8496     const VPIntrinsic &VPIntrin) {
8497   SDLoc DL = getCurSDLoc();
8498   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8499 
8500   auto IID = VPIntrin.getIntrinsicID();
8501 
8502   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8503     return visitVPCmp(*CmpI);
8504 
8505   SmallVector<EVT, 4> ValueVTs;
8506   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8507   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8508   SDVTList VTs = DAG.getVTList(ValueVTs);
8509 
8510   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8511 
8512   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8513   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8514          "Unexpected target EVL type");
8515 
8516   // Request operands.
8517   SmallVector<SDValue, 7> OpValues;
8518   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8519     auto Op = getValue(VPIntrin.getArgOperand(I));
8520     if (I == EVLParamPos)
8521       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8522     OpValues.push_back(Op);
8523   }
8524 
8525   switch (Opcode) {
8526   default: {
8527     SDNodeFlags SDFlags;
8528     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8529       SDFlags.copyFMF(*FPMO);
8530     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8531     setValue(&VPIntrin, Result);
8532     break;
8533   }
8534   case ISD::VP_LOAD:
8535     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8536     break;
8537   case ISD::VP_GATHER:
8538     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8539     break;
8540   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8541     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8542     break;
8543   case ISD::VP_STORE:
8544     visitVPStore(VPIntrin, OpValues);
8545     break;
8546   case ISD::VP_SCATTER:
8547     visitVPScatter(VPIntrin, OpValues);
8548     break;
8549   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8550     visitVPStridedStore(VPIntrin, OpValues);
8551     break;
8552   case ISD::VP_FMULADD: {
8553     assert(OpValues.size() == 5 && "Unexpected number of operands");
8554     SDNodeFlags SDFlags;
8555     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8556       SDFlags.copyFMF(*FPMO);
8557     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8558         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8559       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8560     } else {
8561       SDValue Mul = DAG.getNode(
8562           ISD::VP_FMUL, DL, VTs,
8563           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8564       SDValue Add =
8565           DAG.getNode(ISD::VP_FADD, DL, VTs,
8566                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8567       setValue(&VPIntrin, Add);
8568     }
8569     break;
8570   }
8571   case ISD::VP_IS_FPCLASS: {
8572     const DataLayout DLayout = DAG.getDataLayout();
8573     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8574     auto Constant = OpValues[1]->getAsZExtVal();
8575     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8576     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8577                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8578     setValue(&VPIntrin, V);
8579     return;
8580   }
8581   case ISD::VP_INTTOPTR: {
8582     SDValue N = OpValues[0];
8583     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8584     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8585     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8586                                OpValues[2]);
8587     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8588                              OpValues[2]);
8589     setValue(&VPIntrin, N);
8590     break;
8591   }
8592   case ISD::VP_PTRTOINT: {
8593     SDValue N = OpValues[0];
8594     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8595                                                           VPIntrin.getType());
8596     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8597                                        VPIntrin.getOperand(0)->getType());
8598     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8599                                OpValues[2]);
8600     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8601                              OpValues[2]);
8602     setValue(&VPIntrin, N);
8603     break;
8604   }
8605   case ISD::VP_ABS:
8606   case ISD::VP_CTLZ:
8607   case ISD::VP_CTLZ_ZERO_UNDEF:
8608   case ISD::VP_CTTZ:
8609   case ISD::VP_CTTZ_ZERO_UNDEF:
8610   case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8611   case ISD::VP_CTTZ_ELTS: {
8612     SDValue Result =
8613         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8614     setValue(&VPIntrin, Result);
8615     break;
8616   }
8617   }
8618 }
8619 
lowerStartEH(SDValue Chain,const BasicBlock * EHPadBB,MCSymbol * & BeginLabel)8620 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8621                                           const BasicBlock *EHPadBB,
8622                                           MCSymbol *&BeginLabel) {
8623   MachineFunction &MF = DAG.getMachineFunction();
8624   MachineModuleInfo &MMI = MF.getMMI();
8625 
8626   // Insert a label before the invoke call to mark the try range.  This can be
8627   // used to detect deletion of the invoke via the MachineModuleInfo.
8628   BeginLabel = MF.getContext().createTempSymbol();
8629 
8630   // For SjLj, keep track of which landing pads go with which invokes
8631   // so as to maintain the ordering of pads in the LSDA.
8632   unsigned CallSiteIndex = MMI.getCurrentCallSite();
8633   if (CallSiteIndex) {
8634     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8635     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
8636 
8637     // Now that the call site is handled, stop tracking it.
8638     MMI.setCurrentCallSite(0);
8639   }
8640 
8641   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8642 }
8643 
lowerEndEH(SDValue Chain,const InvokeInst * II,const BasicBlock * EHPadBB,MCSymbol * BeginLabel)8644 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8645                                         const BasicBlock *EHPadBB,
8646                                         MCSymbol *BeginLabel) {
8647   assert(BeginLabel && "BeginLabel should've been set");
8648 
8649   MachineFunction &MF = DAG.getMachineFunction();
8650 
8651   // Insert a label at the end of the invoke call to mark the try range.  This
8652   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8653   MCSymbol *EndLabel = MF.getContext().createTempSymbol();
8654   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8655 
8656   // Inform MachineModuleInfo of range.
8657   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8658   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8659   // actually use outlined funclets and their LSDA info style.
8660   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8661     assert(II && "II should've been set");
8662     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8663     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8664   } else if (!isScopedEHPersonality(Pers)) {
8665     assert(EHPadBB);
8666     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
8667   }
8668 
8669   return Chain;
8670 }
8671 
8672 std::pair<SDValue, SDValue>
lowerInvokable(TargetLowering::CallLoweringInfo & CLI,const BasicBlock * EHPadBB)8673 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8674                                     const BasicBlock *EHPadBB) {
8675   MCSymbol *BeginLabel = nullptr;
8676 
8677   if (EHPadBB) {
8678     // Both PendingLoads and PendingExports must be flushed here;
8679     // this call might not return.
8680     (void)getRoot();
8681     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8682     CLI.setChain(getRoot());
8683   }
8684 
8685   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8686   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8687 
8688   assert((CLI.IsTailCall || Result.second.getNode()) &&
8689          "Non-null chain expected with non-tail call!");
8690   assert((Result.second.getNode() || !Result.first.getNode()) &&
8691          "Null value expected with tail call!");
8692 
8693   if (!Result.second.getNode()) {
8694     // As a special case, a null chain means that a tail call has been emitted
8695     // and the DAG root is already updated.
8696     HasTailCall = true;
8697 
8698     // Since there's no actual continuation from this block, nothing can be
8699     // relying on us setting vregs for them.
8700     PendingExports.clear();
8701   } else {
8702     DAG.setRoot(Result.second);
8703   }
8704 
8705   if (EHPadBB) {
8706     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8707                            BeginLabel));
8708     Result.second = getRoot();
8709   }
8710 
8711   return Result;
8712 }
8713 
LowerCallTo(const CallBase & CB,SDValue Callee,bool isTailCall,bool isMustTailCall,const BasicBlock * EHPadBB,const TargetLowering::PtrAuthInfo * PAI)8714 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8715                                       bool isTailCall, bool isMustTailCall,
8716                                       const BasicBlock *EHPadBB,
8717                                       const TargetLowering::PtrAuthInfo *PAI) {
8718   auto &DL = DAG.getDataLayout();
8719   FunctionType *FTy = CB.getFunctionType();
8720   Type *RetTy = CB.getType();
8721 
8722   TargetLowering::ArgListTy Args;
8723   Args.reserve(CB.arg_size());
8724 
8725   const Value *SwiftErrorVal = nullptr;
8726   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8727 
8728   if (isTailCall) {
8729     // Avoid emitting tail calls in functions with the disable-tail-calls
8730     // attribute.
8731     auto *Caller = CB.getParent()->getParent();
8732     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8733         "true" && !isMustTailCall)
8734       isTailCall = false;
8735 
8736     // We can't tail call inside a function with a swifterror argument. Lowering
8737     // does not support this yet. It would have to move into the swifterror
8738     // register before the call.
8739     if (TLI.supportSwiftError() &&
8740         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8741       isTailCall = false;
8742   }
8743 
8744   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8745     TargetLowering::ArgListEntry Entry;
8746     const Value *V = *I;
8747 
8748     // Skip empty types
8749     if (V->getType()->isEmptyTy())
8750       continue;
8751 
8752     SDValue ArgNode = getValue(V);
8753     Entry.Node = ArgNode; Entry.Ty = V->getType();
8754 
8755     Entry.setAttributes(&CB, I - CB.arg_begin());
8756 
8757     // Use swifterror virtual register as input to the call.
8758     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8759       SwiftErrorVal = V;
8760       // We find the virtual register for the actual swifterror argument.
8761       // Instead of using the Value, we use the virtual register instead.
8762       Entry.Node =
8763           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8764                           EVT(TLI.getPointerTy(DL)));
8765     }
8766 
8767     Args.push_back(Entry);
8768 
8769     // If we have an explicit sret argument that is an Instruction, (i.e., it
8770     // might point to function-local memory), we can't meaningfully tail-call.
8771     if (Entry.IsSRet && isa<Instruction>(V))
8772       isTailCall = false;
8773   }
8774 
8775   // If call site has a cfguardtarget operand bundle, create and add an
8776   // additional ArgListEntry.
8777   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8778     TargetLowering::ArgListEntry Entry;
8779     Value *V = Bundle->Inputs[0];
8780     SDValue ArgNode = getValue(V);
8781     Entry.Node = ArgNode;
8782     Entry.Ty = V->getType();
8783     Entry.IsCFGuardTarget = true;
8784     Args.push_back(Entry);
8785   }
8786 
8787   // Check if target-independent constraints permit a tail call here.
8788   // Target-dependent constraints are checked within TLI->LowerCallTo.
8789   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8790     isTailCall = false;
8791 
8792   // Disable tail calls if there is an swifterror argument. Targets have not
8793   // been updated to support tail calls.
8794   if (TLI.supportSwiftError() && SwiftErrorVal)
8795     isTailCall = false;
8796 
8797   ConstantInt *CFIType = nullptr;
8798   if (CB.isIndirectCall()) {
8799     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8800       if (!TLI.supportKCFIBundles())
8801         report_fatal_error(
8802             "Target doesn't support calls with kcfi operand bundles.");
8803       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8804       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8805     }
8806   }
8807 
8808   SDValue ConvControlToken;
8809   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8810     auto *Token = Bundle->Inputs[0].get();
8811     ConvControlToken = getValue(Token);
8812   }
8813 
8814   TargetLowering::CallLoweringInfo CLI(DAG);
8815   CLI.setDebugLoc(getCurSDLoc())
8816       .setChain(getRoot())
8817       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8818       .setTailCall(isTailCall)
8819       .setConvergent(CB.isConvergent())
8820       .setIsPreallocated(
8821           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8822       .setCFIType(CFIType)
8823       .setConvergenceControlToken(ConvControlToken);
8824 
8825   // Set the pointer authentication info if we have it.
8826   if (PAI) {
8827     if (!TLI.supportPtrAuthBundles())
8828       report_fatal_error(
8829           "This target doesn't support calls with ptrauth operand bundles.");
8830     CLI.setPtrAuth(*PAI);
8831   }
8832 
8833   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8834 
8835   if (Result.first.getNode()) {
8836     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8837     setValue(&CB, Result.first);
8838   }
8839 
8840   // The last element of CLI.InVals has the SDValue for swifterror return.
8841   // Here we copy it to a virtual register and update SwiftErrorMap for
8842   // book-keeping.
8843   if (SwiftErrorVal && TLI.supportSwiftError()) {
8844     // Get the last element of InVals.
8845     SDValue Src = CLI.InVals.back();
8846     Register VReg =
8847         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8848     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8849     DAG.setRoot(CopyNode);
8850   }
8851 }
8852 
getMemCmpLoad(const Value * PtrVal,MVT LoadVT,SelectionDAGBuilder & Builder)8853 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8854                              SelectionDAGBuilder &Builder) {
8855   // Check to see if this load can be trivially constant folded, e.g. if the
8856   // input is from a string literal.
8857   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8858     // Cast pointer to the type we really want to load.
8859     Type *LoadTy =
8860         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8861     if (LoadVT.isVector())
8862       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8863 
8864     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8865                                          PointerType::getUnqual(LoadTy));
8866 
8867     if (const Constant *LoadCst =
8868             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8869                                          LoadTy, Builder.DAG.getDataLayout()))
8870       return Builder.getValue(LoadCst);
8871   }
8872 
8873   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8874   // still constant memory, the input chain can be the entry node.
8875   SDValue Root;
8876   bool ConstantMemory = false;
8877 
8878   // Do not serialize (non-volatile) loads of constant memory with anything.
8879   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8880     Root = Builder.DAG.getEntryNode();
8881     ConstantMemory = true;
8882   } else {
8883     // Do not serialize non-volatile loads against each other.
8884     Root = Builder.DAG.getRoot();
8885   }
8886 
8887   SDValue Ptr = Builder.getValue(PtrVal);
8888   SDValue LoadVal =
8889       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8890                           MachinePointerInfo(PtrVal), Align(1));
8891 
8892   if (!ConstantMemory)
8893     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8894   return LoadVal;
8895 }
8896 
8897 /// Record the value for an instruction that produces an integer result,
8898 /// converting the type where necessary.
processIntegerCallValue(const Instruction & I,SDValue Value,bool IsSigned)8899 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8900                                                   SDValue Value,
8901                                                   bool IsSigned) {
8902   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8903                                                     I.getType(), true);
8904   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8905   setValue(&I, Value);
8906 }
8907 
8908 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8909 /// true and lower it. Otherwise return false, and it will be lowered like a
8910 /// normal call.
8911 /// The caller already checked that \p I calls the appropriate LibFunc with a
8912 /// correct prototype.
visitMemCmpBCmpCall(const CallInst & I)8913 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8914   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8915   const Value *Size = I.getArgOperand(2);
8916   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8917   if (CSize && CSize->getZExtValue() == 0) {
8918     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8919                                                           I.getType(), true);
8920     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8921     return true;
8922   }
8923 
8924   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8925   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8926       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8927       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8928   if (Res.first.getNode()) {
8929     processIntegerCallValue(I, Res.first, true);
8930     PendingLoads.push_back(Res.second);
8931     return true;
8932   }
8933 
8934   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8935   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8936   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8937     return false;
8938 
8939   // If the target has a fast compare for the given size, it will return a
8940   // preferred load type for that size. Require that the load VT is legal and
8941   // that the target supports unaligned loads of that type. Otherwise, return
8942   // INVALID.
8943   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8944     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8945     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8946     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8947       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8948       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8949       // TODO: Check alignment of src and dest ptrs.
8950       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8951       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8952       if (!TLI.isTypeLegal(LVT) ||
8953           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8954           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8955         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8956     }
8957 
8958     return LVT;
8959   };
8960 
8961   // This turns into unaligned loads. We only do this if the target natively
8962   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8963   // we'll only produce a small number of byte loads.
8964   MVT LoadVT;
8965   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8966   switch (NumBitsToCompare) {
8967   default:
8968     return false;
8969   case 16:
8970     LoadVT = MVT::i16;
8971     break;
8972   case 32:
8973     LoadVT = MVT::i32;
8974     break;
8975   case 64:
8976   case 128:
8977   case 256:
8978     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8979     break;
8980   }
8981 
8982   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8983     return false;
8984 
8985   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8986   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8987 
8988   // Bitcast to a wide integer type if the loads are vectors.
8989   if (LoadVT.isVector()) {
8990     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8991     LoadL = DAG.getBitcast(CmpVT, LoadL);
8992     LoadR = DAG.getBitcast(CmpVT, LoadR);
8993   }
8994 
8995   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8996   processIntegerCallValue(I, Cmp, false);
8997   return true;
8998 }
8999 
9000 /// See if we can lower a memchr call into an optimized form. If so, return
9001 /// true and lower it. Otherwise return false, and it will be lowered like a
9002 /// normal call.
9003 /// The caller already checked that \p I calls the appropriate LibFunc with a
9004 /// correct prototype.
visitMemChrCall(const CallInst & I)9005 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9006   const Value *Src = I.getArgOperand(0);
9007   const Value *Char = I.getArgOperand(1);
9008   const Value *Length = I.getArgOperand(2);
9009 
9010   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9011   std::pair<SDValue, SDValue> Res =
9012     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9013                                 getValue(Src), getValue(Char), getValue(Length),
9014                                 MachinePointerInfo(Src));
9015   if (Res.first.getNode()) {
9016     setValue(&I, Res.first);
9017     PendingLoads.push_back(Res.second);
9018     return true;
9019   }
9020 
9021   return false;
9022 }
9023 
9024 /// See if we can lower a mempcpy call into an optimized form. If so, return
9025 /// true and lower it. Otherwise return false, and it will be lowered like a
9026 /// normal call.
9027 /// The caller already checked that \p I calls the appropriate LibFunc with a
9028 /// correct prototype.
visitMemPCpyCall(const CallInst & I)9029 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9030   SDValue Dst = getValue(I.getArgOperand(0));
9031   SDValue Src = getValue(I.getArgOperand(1));
9032   SDValue Size = getValue(I.getArgOperand(2));
9033 
9034   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9035   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9036   // DAG::getMemcpy needs Alignment to be defined.
9037   Align Alignment = std::min(DstAlign, SrcAlign);
9038 
9039   SDLoc sdl = getCurSDLoc();
9040 
9041   // In the mempcpy context we need to pass in a false value for isTailCall
9042   // because the return pointer needs to be adjusted by the size of
9043   // the copied memory.
9044   SDValue Root = getMemoryRoot();
9045   SDValue MC = DAG.getMemcpy(
9046       Root, sdl, Dst, Src, Size, Alignment, false, false, /*CI=*/nullptr,
9047       std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9048       MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9049   assert(MC.getNode() != nullptr &&
9050          "** memcpy should not be lowered as TailCall in mempcpy context **");
9051   DAG.setRoot(MC);
9052 
9053   // Check if Size needs to be truncated or extended.
9054   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9055 
9056   // Adjust return pointer to point just past the last dst byte.
9057   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
9058                                     Dst, Size);
9059   setValue(&I, DstPlusSize);
9060   return true;
9061 }
9062 
9063 /// See if we can lower a strcpy call into an optimized form.  If so, return
9064 /// true and lower it, otherwise return false and it will be lowered like a
9065 /// normal call.
9066 /// The caller already checked that \p I calls the appropriate LibFunc with a
9067 /// correct prototype.
visitStrCpyCall(const CallInst & I,bool isStpcpy)9068 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9069   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9070 
9071   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9072   std::pair<SDValue, SDValue> Res =
9073     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
9074                                 getValue(Arg0), getValue(Arg1),
9075                                 MachinePointerInfo(Arg0),
9076                                 MachinePointerInfo(Arg1), isStpcpy);
9077   if (Res.first.getNode()) {
9078     setValue(&I, Res.first);
9079     DAG.setRoot(Res.second);
9080     return true;
9081   }
9082 
9083   return false;
9084 }
9085 
9086 /// See if we can lower a strcmp call into an optimized form.  If so, return
9087 /// true and lower it, otherwise return false and it will be lowered like a
9088 /// normal call.
9089 /// The caller already checked that \p I calls the appropriate LibFunc with a
9090 /// correct prototype.
visitStrCmpCall(const CallInst & I)9091 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9092   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9093 
9094   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9095   std::pair<SDValue, SDValue> Res =
9096     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
9097                                 getValue(Arg0), getValue(Arg1),
9098                                 MachinePointerInfo(Arg0),
9099                                 MachinePointerInfo(Arg1));
9100   if (Res.first.getNode()) {
9101     processIntegerCallValue(I, Res.first, true);
9102     PendingLoads.push_back(Res.second);
9103     return true;
9104   }
9105 
9106   return false;
9107 }
9108 
9109 /// See if we can lower a strlen call into an optimized form.  If so, return
9110 /// true and lower it, otherwise return false and it will be lowered like a
9111 /// normal call.
9112 /// The caller already checked that \p I calls the appropriate LibFunc with a
9113 /// correct prototype.
visitStrLenCall(const CallInst & I)9114 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9115   const Value *Arg0 = I.getArgOperand(0);
9116 
9117   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9118   std::pair<SDValue, SDValue> Res =
9119     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
9120                                 getValue(Arg0), MachinePointerInfo(Arg0));
9121   if (Res.first.getNode()) {
9122     processIntegerCallValue(I, Res.first, false);
9123     PendingLoads.push_back(Res.second);
9124     return true;
9125   }
9126 
9127   return false;
9128 }
9129 
9130 /// See if we can lower a strnlen call into an optimized form.  If so, return
9131 /// true and lower it, otherwise return false and it will be lowered like a
9132 /// normal call.
9133 /// The caller already checked that \p I calls the appropriate LibFunc with a
9134 /// correct prototype.
visitStrNLenCall(const CallInst & I)9135 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9136   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9137 
9138   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9139   std::pair<SDValue, SDValue> Res =
9140     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9141                                  getValue(Arg0), getValue(Arg1),
9142                                  MachinePointerInfo(Arg0));
9143   if (Res.first.getNode()) {
9144     processIntegerCallValue(I, Res.first, false);
9145     PendingLoads.push_back(Res.second);
9146     return true;
9147   }
9148 
9149   return false;
9150 }
9151 
9152 /// See if we can lower a unary floating-point operation into an SDNode with
9153 /// the specified Opcode.  If so, return true and lower it, otherwise return
9154 /// false and it will be lowered like a normal call.
9155 /// The caller already checked that \p I calls the appropriate LibFunc with a
9156 /// correct prototype.
visitUnaryFloatCall(const CallInst & I,unsigned Opcode)9157 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9158                                               unsigned Opcode) {
9159   // We already checked this call's prototype; verify it doesn't modify errno.
9160   if (!I.onlyReadsMemory())
9161     return false;
9162 
9163   SDNodeFlags Flags;
9164   Flags.copyFMF(cast<FPMathOperator>(I));
9165 
9166   SDValue Tmp = getValue(I.getArgOperand(0));
9167   setValue(&I,
9168            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9169   return true;
9170 }
9171 
9172 /// See if we can lower a binary floating-point operation into an SDNode with
9173 /// the specified Opcode. If so, return true and lower it. Otherwise return
9174 /// false, and it will be lowered like a normal call.
9175 /// The caller already checked that \p I calls the appropriate LibFunc with a
9176 /// correct prototype.
visitBinaryFloatCall(const CallInst & I,unsigned Opcode)9177 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9178                                                unsigned Opcode) {
9179   // We already checked this call's prototype; verify it doesn't modify errno.
9180   if (!I.onlyReadsMemory())
9181     return false;
9182 
9183   SDNodeFlags Flags;
9184   Flags.copyFMF(cast<FPMathOperator>(I));
9185 
9186   SDValue Tmp0 = getValue(I.getArgOperand(0));
9187   SDValue Tmp1 = getValue(I.getArgOperand(1));
9188   EVT VT = Tmp0.getValueType();
9189   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9190   return true;
9191 }
9192 
visitCall(const CallInst & I)9193 void SelectionDAGBuilder::visitCall(const CallInst &I) {
9194   // Handle inline assembly differently.
9195   if (I.isInlineAsm()) {
9196     visitInlineAsm(I);
9197     return;
9198   }
9199 
9200   diagnoseDontCall(I);
9201 
9202   if (Function *F = I.getCalledFunction()) {
9203     if (F->isDeclaration()) {
9204       // Is this an LLVM intrinsic or a target-specific intrinsic?
9205       unsigned IID = F->getIntrinsicID();
9206       if (!IID)
9207         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9208           IID = II->getIntrinsicID(F);
9209 
9210       if (IID) {
9211         visitIntrinsicCall(I, IID);
9212         return;
9213       }
9214     }
9215 
9216     // Check for well-known libc/libm calls.  If the function is internal, it
9217     // can't be a library call.  Don't do the check if marked as nobuiltin for
9218     // some reason or the call site requires strict floating point semantics.
9219     LibFunc Func;
9220     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9221         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9222         LibInfo->hasOptimizedCodeGen(Func)) {
9223       switch (Func) {
9224       default: break;
9225       case LibFunc_bcmp:
9226         if (visitMemCmpBCmpCall(I))
9227           return;
9228         break;
9229       case LibFunc_copysign:
9230       case LibFunc_copysignf:
9231       case LibFunc_copysignl:
9232         // We already checked this call's prototype; verify it doesn't modify
9233         // errno.
9234         if (I.onlyReadsMemory()) {
9235           SDValue LHS = getValue(I.getArgOperand(0));
9236           SDValue RHS = getValue(I.getArgOperand(1));
9237           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9238                                    LHS.getValueType(), LHS, RHS));
9239           return;
9240         }
9241         break;
9242       case LibFunc_fabs:
9243       case LibFunc_fabsf:
9244       case LibFunc_fabsl:
9245         if (visitUnaryFloatCall(I, ISD::FABS))
9246           return;
9247         break;
9248       case LibFunc_fmin:
9249       case LibFunc_fminf:
9250       case LibFunc_fminl:
9251         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9252           return;
9253         break;
9254       case LibFunc_fmax:
9255       case LibFunc_fmaxf:
9256       case LibFunc_fmaxl:
9257         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9258           return;
9259         break;
9260       case LibFunc_sin:
9261       case LibFunc_sinf:
9262       case LibFunc_sinl:
9263         if (visitUnaryFloatCall(I, ISD::FSIN))
9264           return;
9265         break;
9266       case LibFunc_cos:
9267       case LibFunc_cosf:
9268       case LibFunc_cosl:
9269         if (visitUnaryFloatCall(I, ISD::FCOS))
9270           return;
9271         break;
9272       case LibFunc_tan:
9273       case LibFunc_tanf:
9274       case LibFunc_tanl:
9275         if (visitUnaryFloatCall(I, ISD::FTAN))
9276           return;
9277         break;
9278       case LibFunc_asin:
9279       case LibFunc_asinf:
9280       case LibFunc_asinl:
9281         if (visitUnaryFloatCall(I, ISD::FASIN))
9282           return;
9283         break;
9284       case LibFunc_acos:
9285       case LibFunc_acosf:
9286       case LibFunc_acosl:
9287         if (visitUnaryFloatCall(I, ISD::FACOS))
9288           return;
9289         break;
9290       case LibFunc_atan:
9291       case LibFunc_atanf:
9292       case LibFunc_atanl:
9293         if (visitUnaryFloatCall(I, ISD::FATAN))
9294           return;
9295         break;
9296       case LibFunc_sinh:
9297       case LibFunc_sinhf:
9298       case LibFunc_sinhl:
9299         if (visitUnaryFloatCall(I, ISD::FSINH))
9300           return;
9301         break;
9302       case LibFunc_cosh:
9303       case LibFunc_coshf:
9304       case LibFunc_coshl:
9305         if (visitUnaryFloatCall(I, ISD::FCOSH))
9306           return;
9307         break;
9308       case LibFunc_tanh:
9309       case LibFunc_tanhf:
9310       case LibFunc_tanhl:
9311         if (visitUnaryFloatCall(I, ISD::FTANH))
9312           return;
9313         break;
9314       case LibFunc_sqrt:
9315       case LibFunc_sqrtf:
9316       case LibFunc_sqrtl:
9317       case LibFunc_sqrt_finite:
9318       case LibFunc_sqrtf_finite:
9319       case LibFunc_sqrtl_finite:
9320         if (visitUnaryFloatCall(I, ISD::FSQRT))
9321           return;
9322         break;
9323       case LibFunc_floor:
9324       case LibFunc_floorf:
9325       case LibFunc_floorl:
9326         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9327           return;
9328         break;
9329       case LibFunc_nearbyint:
9330       case LibFunc_nearbyintf:
9331       case LibFunc_nearbyintl:
9332         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9333           return;
9334         break;
9335       case LibFunc_ceil:
9336       case LibFunc_ceilf:
9337       case LibFunc_ceill:
9338         if (visitUnaryFloatCall(I, ISD::FCEIL))
9339           return;
9340         break;
9341       case LibFunc_rint:
9342       case LibFunc_rintf:
9343       case LibFunc_rintl:
9344         if (visitUnaryFloatCall(I, ISD::FRINT))
9345           return;
9346         break;
9347       case LibFunc_round:
9348       case LibFunc_roundf:
9349       case LibFunc_roundl:
9350         if (visitUnaryFloatCall(I, ISD::FROUND))
9351           return;
9352         break;
9353       case LibFunc_trunc:
9354       case LibFunc_truncf:
9355       case LibFunc_truncl:
9356         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9357           return;
9358         break;
9359       case LibFunc_log2:
9360       case LibFunc_log2f:
9361       case LibFunc_log2l:
9362         if (visitUnaryFloatCall(I, ISD::FLOG2))
9363           return;
9364         break;
9365       case LibFunc_exp2:
9366       case LibFunc_exp2f:
9367       case LibFunc_exp2l:
9368         if (visitUnaryFloatCall(I, ISD::FEXP2))
9369           return;
9370         break;
9371       case LibFunc_exp10:
9372       case LibFunc_exp10f:
9373       case LibFunc_exp10l:
9374         if (visitUnaryFloatCall(I, ISD::FEXP10))
9375           return;
9376         break;
9377       case LibFunc_ldexp:
9378       case LibFunc_ldexpf:
9379       case LibFunc_ldexpl:
9380         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9381           return;
9382         break;
9383       case LibFunc_memcmp:
9384         if (visitMemCmpBCmpCall(I))
9385           return;
9386         break;
9387       case LibFunc_mempcpy:
9388         if (visitMemPCpyCall(I))
9389           return;
9390         break;
9391       case LibFunc_memchr:
9392         if (visitMemChrCall(I))
9393           return;
9394         break;
9395       case LibFunc_strcpy:
9396         if (visitStrCpyCall(I, false))
9397           return;
9398         break;
9399       case LibFunc_stpcpy:
9400         if (visitStrCpyCall(I, true))
9401           return;
9402         break;
9403       case LibFunc_strcmp:
9404         if (visitStrCmpCall(I))
9405           return;
9406         break;
9407       case LibFunc_strlen:
9408         if (visitStrLenCall(I))
9409           return;
9410         break;
9411       case LibFunc_strnlen:
9412         if (visitStrNLenCall(I))
9413           return;
9414         break;
9415       }
9416     }
9417   }
9418 
9419   if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9420     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9421     return;
9422   }
9423 
9424   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9425   // have to do anything here to lower funclet bundles.
9426   // CFGuardTarget bundles are lowered in LowerCallTo.
9427   assert(!I.hasOperandBundlesOtherThan(
9428              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9429               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9430               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9431               LLVMContext::OB_convergencectrl}) &&
9432          "Cannot lower calls with arbitrary operand bundles!");
9433 
9434   SDValue Callee = getValue(I.getCalledOperand());
9435 
9436   if (I.hasDeoptState())
9437     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9438   else
9439     // Check if we can potentially perform a tail call. More detailed checking
9440     // is be done within LowerCallTo, after more information about the call is
9441     // known.
9442     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9443 }
9444 
LowerCallSiteWithPtrAuthBundle(const CallBase & CB,const BasicBlock * EHPadBB)9445 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9446     const CallBase &CB, const BasicBlock *EHPadBB) {
9447   auto PAB = CB.getOperandBundle("ptrauth");
9448   const Value *CalleeV = CB.getCalledOperand();
9449 
9450   // Gather the call ptrauth data from the operand bundle:
9451   //   [ i32 <key>, i64 <discriminator> ]
9452   const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9453   const Value *Discriminator = PAB->Inputs[1];
9454 
9455   assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9456   assert(Discriminator->getType()->isIntegerTy(64) &&
9457          "Invalid ptrauth discriminator");
9458 
9459   // Look through ptrauth constants to find the raw callee.
9460   // Do a direct unauthenticated call if we found it and everything matches.
9461   if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
9462     if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9463                                          DAG.getDataLayout()))
9464       return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
9465                          CB.isMustTailCall(), EHPadBB);
9466 
9467   // Functions should never be ptrauth-called directly.
9468   assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9469 
9470   // Otherwise, do an authenticated indirect call.
9471   TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9472                                      getValue(Discriminator)};
9473 
9474   LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9475               EHPadBB, &PAI);
9476 }
9477 
9478 namespace {
9479 
9480 /// AsmOperandInfo - This contains information for each constraint that we are
9481 /// lowering.
9482 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9483 public:
9484   /// CallOperand - If this is the result output operand or a clobber
9485   /// this is null, otherwise it is the incoming operand to the CallInst.
9486   /// This gets modified as the asm is processed.
9487   SDValue CallOperand;
9488 
9489   /// AssignedRegs - If this is a register or register class operand, this
9490   /// contains the set of register corresponding to the operand.
9491   RegsForValue AssignedRegs;
9492 
SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo & info)9493   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9494     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9495   }
9496 
9497   /// Whether or not this operand accesses memory
hasMemory(const TargetLowering & TLI) const9498   bool hasMemory(const TargetLowering &TLI) const {
9499     // Indirect operand accesses access memory.
9500     if (isIndirect)
9501       return true;
9502 
9503     for (const auto &Code : Codes)
9504       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9505         return true;
9506 
9507     return false;
9508   }
9509 };
9510 
9511 
9512 } // end anonymous namespace
9513 
9514 /// Make sure that the output operand \p OpInfo and its corresponding input
9515 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9516 /// out).
patchMatchingInput(const SDISelAsmOperandInfo & OpInfo,SDISelAsmOperandInfo & MatchingOpInfo,SelectionDAG & DAG)9517 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9518                                SDISelAsmOperandInfo &MatchingOpInfo,
9519                                SelectionDAG &DAG) {
9520   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9521     return;
9522 
9523   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9524   const auto &TLI = DAG.getTargetLoweringInfo();
9525 
9526   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9527       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9528                                        OpInfo.ConstraintVT);
9529   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9530       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9531                                        MatchingOpInfo.ConstraintVT);
9532   if ((OpInfo.ConstraintVT.isInteger() !=
9533        MatchingOpInfo.ConstraintVT.isInteger()) ||
9534       (MatchRC.second != InputRC.second)) {
9535     // FIXME: error out in a more elegant fashion
9536     report_fatal_error("Unsupported asm: input constraint"
9537                        " with a matching output constraint of"
9538                        " incompatible type!");
9539   }
9540   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9541 }
9542 
9543 /// Get a direct memory input to behave well as an indirect operand.
9544 /// This may introduce stores, hence the need for a \p Chain.
9545 /// \return The (possibly updated) chain.
getAddressForMemoryInput(SDValue Chain,const SDLoc & Location,SDISelAsmOperandInfo & OpInfo,SelectionDAG & DAG)9546 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9547                                         SDISelAsmOperandInfo &OpInfo,
9548                                         SelectionDAG &DAG) {
9549   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9550 
9551   // If we don't have an indirect input, put it in the constpool if we can,
9552   // otherwise spill it to a stack slot.
9553   // TODO: This isn't quite right. We need to handle these according to
9554   // the addressing mode that the constraint wants. Also, this may take
9555   // an additional register for the computation and we don't want that
9556   // either.
9557 
9558   // If the operand is a float, integer, or vector constant, spill to a
9559   // constant pool entry to get its address.
9560   const Value *OpVal = OpInfo.CallOperandVal;
9561   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9562       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9563     OpInfo.CallOperand = DAG.getConstantPool(
9564         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9565     return Chain;
9566   }
9567 
9568   // Otherwise, create a stack slot and emit a store to it before the asm.
9569   Type *Ty = OpVal->getType();
9570   auto &DL = DAG.getDataLayout();
9571   TypeSize TySize = DL.getTypeAllocSize(Ty);
9572   MachineFunction &MF = DAG.getMachineFunction();
9573   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
9574   int StackID = 0;
9575   if (TySize.isScalable())
9576     StackID = TFI->getStackIDForScalableVectors();
9577   int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
9578                                                  DL.getPrefTypeAlign(Ty), false,
9579                                                  nullptr, StackID);
9580   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9581   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9582                             MachinePointerInfo::getFixedStack(MF, SSFI),
9583                             TLI.getMemValueType(DL, Ty));
9584   OpInfo.CallOperand = StackSlot;
9585 
9586   return Chain;
9587 }
9588 
9589 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9590 /// specified operand.  We prefer to assign virtual registers, to allow the
9591 /// register allocator to handle the assignment process.  However, if the asm
9592 /// uses features that we can't model on machineinstrs, we have SDISel do the
9593 /// allocation.  This produces generally horrible, but correct, code.
9594 ///
9595 ///   OpInfo describes the operand
9596 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9597 static std::optional<unsigned>
getRegistersForValue(SelectionDAG & DAG,const SDLoc & DL,SDISelAsmOperandInfo & OpInfo,SDISelAsmOperandInfo & RefOpInfo)9598 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9599                      SDISelAsmOperandInfo &OpInfo,
9600                      SDISelAsmOperandInfo &RefOpInfo) {
9601   LLVMContext &Context = *DAG.getContext();
9602   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9603 
9604   MachineFunction &MF = DAG.getMachineFunction();
9605   SmallVector<unsigned, 4> Regs;
9606   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9607 
9608   // No work to do for memory/address operands.
9609   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9610       OpInfo.ConstraintType == TargetLowering::C_Address)
9611     return std::nullopt;
9612 
9613   // If this is a constraint for a single physreg, or a constraint for a
9614   // register class, find it.
9615   unsigned AssignedReg;
9616   const TargetRegisterClass *RC;
9617   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9618       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9619   // RC is unset only on failure. Return immediately.
9620   if (!RC)
9621     return std::nullopt;
9622 
9623   // Get the actual register value type.  This is important, because the user
9624   // may have asked for (e.g.) the AX register in i32 type.  We need to
9625   // remember that AX is actually i16 to get the right extension.
9626   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9627 
9628   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9629     // If this is an FP operand in an integer register (or visa versa), or more
9630     // generally if the operand value disagrees with the register class we plan
9631     // to stick it in, fix the operand type.
9632     //
9633     // If this is an input value, the bitcast to the new type is done now.
9634     // Bitcast for output value is done at the end of visitInlineAsm().
9635     if ((OpInfo.Type == InlineAsm::isOutput ||
9636          OpInfo.Type == InlineAsm::isInput) &&
9637         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9638       // Try to convert to the first EVT that the reg class contains.  If the
9639       // types are identical size, use a bitcast to convert (e.g. two differing
9640       // vector types).  Note: output bitcast is done at the end of
9641       // visitInlineAsm().
9642       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9643         // Exclude indirect inputs while they are unsupported because the code
9644         // to perform the load is missing and thus OpInfo.CallOperand still
9645         // refers to the input address rather than the pointed-to value.
9646         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9647           OpInfo.CallOperand =
9648               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9649         OpInfo.ConstraintVT = RegVT;
9650         // If the operand is an FP value and we want it in integer registers,
9651         // use the corresponding integer type. This turns an f64 value into
9652         // i64, which can be passed with two i32 values on a 32-bit machine.
9653       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9654         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9655         if (OpInfo.Type == InlineAsm::isInput)
9656           OpInfo.CallOperand =
9657               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9658         OpInfo.ConstraintVT = VT;
9659       }
9660     }
9661   }
9662 
9663   // No need to allocate a matching input constraint since the constraint it's
9664   // matching to has already been allocated.
9665   if (OpInfo.isMatchingInputConstraint())
9666     return std::nullopt;
9667 
9668   EVT ValueVT = OpInfo.ConstraintVT;
9669   if (OpInfo.ConstraintVT == MVT::Other)
9670     ValueVT = RegVT;
9671 
9672   // Initialize NumRegs.
9673   unsigned NumRegs = 1;
9674   if (OpInfo.ConstraintVT != MVT::Other)
9675     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9676 
9677   // If this is a constraint for a specific physical register, like {r17},
9678   // assign it now.
9679 
9680   // If this associated to a specific register, initialize iterator to correct
9681   // place. If virtual, make sure we have enough registers
9682 
9683   // Initialize iterator if necessary
9684   TargetRegisterClass::iterator I = RC->begin();
9685   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9686 
9687   // Do not check for single registers.
9688   if (AssignedReg) {
9689     I = std::find(I, RC->end(), AssignedReg);
9690     if (I == RC->end()) {
9691       // RC does not contain the selected register, which indicates a
9692       // mismatch between the register and the required type/bitwidth.
9693       return {AssignedReg};
9694     }
9695   }
9696 
9697   for (; NumRegs; --NumRegs, ++I) {
9698     assert(I != RC->end() && "Ran out of registers to allocate!");
9699     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9700     Regs.push_back(R);
9701   }
9702 
9703   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9704   return std::nullopt;
9705 }
9706 
9707 static unsigned
findMatchingInlineAsmOperand(unsigned OperandNo,const std::vector<SDValue> & AsmNodeOperands)9708 findMatchingInlineAsmOperand(unsigned OperandNo,
9709                              const std::vector<SDValue> &AsmNodeOperands) {
9710   // Scan until we find the definition we already emitted of this operand.
9711   unsigned CurOp = InlineAsm::Op_FirstOperand;
9712   for (; OperandNo; --OperandNo) {
9713     // Advance to the next operand.
9714     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9715     const InlineAsm::Flag F(OpFlag);
9716     assert(
9717         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9718         "Skipped past definitions?");
9719     CurOp += F.getNumOperandRegisters() + 1;
9720   }
9721   return CurOp;
9722 }
9723 
9724 namespace {
9725 
9726 class ExtraFlags {
9727   unsigned Flags = 0;
9728 
9729 public:
ExtraFlags(const CallBase & Call)9730   explicit ExtraFlags(const CallBase &Call) {
9731     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9732     if (IA->hasSideEffects())
9733       Flags |= InlineAsm::Extra_HasSideEffects;
9734     if (IA->isAlignStack())
9735       Flags |= InlineAsm::Extra_IsAlignStack;
9736     if (Call.isConvergent())
9737       Flags |= InlineAsm::Extra_IsConvergent;
9738     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9739   }
9740 
update(const TargetLowering::AsmOperandInfo & OpInfo)9741   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9742     // Ideally, we would only check against memory constraints.  However, the
9743     // meaning of an Other constraint can be target-specific and we can't easily
9744     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9745     // for Other constraints as well.
9746     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9747         OpInfo.ConstraintType == TargetLowering::C_Other) {
9748       if (OpInfo.Type == InlineAsm::isInput)
9749         Flags |= InlineAsm::Extra_MayLoad;
9750       else if (OpInfo.Type == InlineAsm::isOutput)
9751         Flags |= InlineAsm::Extra_MayStore;
9752       else if (OpInfo.Type == InlineAsm::isClobber)
9753         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9754     }
9755   }
9756 
get() const9757   unsigned get() const { return Flags; }
9758 };
9759 
9760 } // end anonymous namespace
9761 
isFunction(SDValue Op)9762 static bool isFunction(SDValue Op) {
9763   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9764     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9765       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9766 
9767       // In normal "call dllimport func" instruction (non-inlineasm) it force
9768       // indirect access by specifing call opcode. And usually specially print
9769       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9770       // not do in this way now. (In fact, this is similar with "Data Access"
9771       // action). So here we ignore dllimport function.
9772       if (Fn && !Fn->hasDLLImportStorageClass())
9773         return true;
9774     }
9775   }
9776   return false;
9777 }
9778 
9779 /// visitInlineAsm - Handle a call to an InlineAsm object.
visitInlineAsm(const CallBase & Call,const BasicBlock * EHPadBB)9780 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9781                                          const BasicBlock *EHPadBB) {
9782   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9783 
9784   /// ConstraintOperands - Information about all of the constraints.
9785   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9786 
9787   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9788   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9789       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9790 
9791   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9792   // AsmDialect, MayLoad, MayStore).
9793   bool HasSideEffect = IA->hasSideEffects();
9794   ExtraFlags ExtraInfo(Call);
9795 
9796   for (auto &T : TargetConstraints) {
9797     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9798     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9799 
9800     if (OpInfo.CallOperandVal)
9801       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9802 
9803     if (!HasSideEffect)
9804       HasSideEffect = OpInfo.hasMemory(TLI);
9805 
9806     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9807     // FIXME: Could we compute this on OpInfo rather than T?
9808 
9809     // Compute the constraint code and ConstraintType to use.
9810     TLI.ComputeConstraintToUse(T, SDValue());
9811 
9812     if (T.ConstraintType == TargetLowering::C_Immediate &&
9813         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9814       // We've delayed emitting a diagnostic like the "n" constraint because
9815       // inlining could cause an integer showing up.
9816       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9817                                           "' expects an integer constant "
9818                                           "expression");
9819 
9820     ExtraInfo.update(T);
9821   }
9822 
9823   // We won't need to flush pending loads if this asm doesn't touch
9824   // memory and is nonvolatile.
9825   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9826 
9827   bool EmitEHLabels = isa<InvokeInst>(Call);
9828   if (EmitEHLabels) {
9829     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9830   }
9831   bool IsCallBr = isa<CallBrInst>(Call);
9832 
9833   if (IsCallBr || EmitEHLabels) {
9834     // If this is a callbr or invoke we need to flush pending exports since
9835     // inlineasm_br and invoke are terminators.
9836     // We need to do this before nodes are glued to the inlineasm_br node.
9837     Chain = getControlRoot();
9838   }
9839 
9840   MCSymbol *BeginLabel = nullptr;
9841   if (EmitEHLabels) {
9842     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9843   }
9844 
9845   int OpNo = -1;
9846   SmallVector<StringRef> AsmStrs;
9847   IA->collectAsmStrs(AsmStrs);
9848 
9849   // Second pass over the constraints: compute which constraint option to use.
9850   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9851     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9852       OpNo++;
9853 
9854     // If this is an output operand with a matching input operand, look up the
9855     // matching input. If their types mismatch, e.g. one is an integer, the
9856     // other is floating point, or their sizes are different, flag it as an
9857     // error.
9858     if (OpInfo.hasMatchingInput()) {
9859       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9860       patchMatchingInput(OpInfo, Input, DAG);
9861     }
9862 
9863     // Compute the constraint code and ConstraintType to use.
9864     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9865 
9866     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9867          OpInfo.Type == InlineAsm::isClobber) ||
9868         OpInfo.ConstraintType == TargetLowering::C_Address)
9869       continue;
9870 
9871     // In Linux PIC model, there are 4 cases about value/label addressing:
9872     //
9873     // 1: Function call or Label jmp inside the module.
9874     // 2: Data access (such as global variable, static variable) inside module.
9875     // 3: Function call or Label jmp outside the module.
9876     // 4: Data access (such as global variable) outside the module.
9877     //
9878     // Due to current llvm inline asm architecture designed to not "recognize"
9879     // the asm code, there are quite troubles for us to treat mem addressing
9880     // differently for same value/adress used in different instuctions.
9881     // For example, in pic model, call a func may in plt way or direclty
9882     // pc-related, but lea/mov a function adress may use got.
9883     //
9884     // Here we try to "recognize" function call for the case 1 and case 3 in
9885     // inline asm. And try to adjust the constraint for them.
9886     //
9887     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9888     // label, so here we don't handle jmp function label now, but we need to
9889     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9890     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9891         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9892         TM.getCodeModel() != CodeModel::Large) {
9893       OpInfo.isIndirect = false;
9894       OpInfo.ConstraintType = TargetLowering::C_Address;
9895     }
9896 
9897     // If this is a memory input, and if the operand is not indirect, do what we
9898     // need to provide an address for the memory input.
9899     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9900         !OpInfo.isIndirect) {
9901       assert((OpInfo.isMultipleAlternative ||
9902               (OpInfo.Type == InlineAsm::isInput)) &&
9903              "Can only indirectify direct input operands!");
9904 
9905       // Memory operands really want the address of the value.
9906       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9907 
9908       // There is no longer a Value* corresponding to this operand.
9909       OpInfo.CallOperandVal = nullptr;
9910 
9911       // It is now an indirect operand.
9912       OpInfo.isIndirect = true;
9913     }
9914 
9915   }
9916 
9917   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9918   std::vector<SDValue> AsmNodeOperands;
9919   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9920   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9921       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9922 
9923   // If we have a !srcloc metadata node associated with it, we want to attach
9924   // this to the ultimately generated inline asm machineinstr.  To do this, we
9925   // pass in the third operand as this (potentially null) inline asm MDNode.
9926   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9927   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9928 
9929   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9930   // bits as operand 3.
9931   AsmNodeOperands.push_back(DAG.getTargetConstant(
9932       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9933 
9934   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9935   // this, assign virtual and physical registers for inputs and otput.
9936   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9937     // Assign Registers.
9938     SDISelAsmOperandInfo &RefOpInfo =
9939         OpInfo.isMatchingInputConstraint()
9940             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9941             : OpInfo;
9942     const auto RegError =
9943         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9944     if (RegError) {
9945       const MachineFunction &MF = DAG.getMachineFunction();
9946       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9947       const char *RegName = TRI.getName(*RegError);
9948       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9949                                    "' allocated for constraint '" +
9950                                    Twine(OpInfo.ConstraintCode) +
9951                                    "' does not match required type");
9952       return;
9953     }
9954 
9955     auto DetectWriteToReservedRegister = [&]() {
9956       const MachineFunction &MF = DAG.getMachineFunction();
9957       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9958       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9959         if (Register::isPhysicalRegister(Reg) &&
9960             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9961           const char *RegName = TRI.getName(Reg);
9962           emitInlineAsmError(Call, "write to reserved register '" +
9963                                        Twine(RegName) + "'");
9964           return true;
9965         }
9966       }
9967       return false;
9968     };
9969     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9970             (OpInfo.Type == InlineAsm::isInput &&
9971              !OpInfo.isMatchingInputConstraint())) &&
9972            "Only address as input operand is allowed.");
9973 
9974     switch (OpInfo.Type) {
9975     case InlineAsm::isOutput:
9976       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9977         const InlineAsm::ConstraintCode ConstraintID =
9978             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9979         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9980                "Failed to convert memory constraint code to constraint id.");
9981 
9982         // Add information to the INLINEASM node to know about this output.
9983         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
9984         OpFlags.setMemConstraint(ConstraintID);
9985         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9986                                                         MVT::i32));
9987         AsmNodeOperands.push_back(OpInfo.CallOperand);
9988       } else {
9989         // Otherwise, this outputs to a register (directly for C_Register /
9990         // C_RegisterClass, and a target-defined fashion for
9991         // C_Immediate/C_Other). Find a register that we can use.
9992         if (OpInfo.AssignedRegs.Regs.empty()) {
9993           emitInlineAsmError(
9994               Call, "couldn't allocate output register for constraint '" +
9995                         Twine(OpInfo.ConstraintCode) + "'");
9996           return;
9997         }
9998 
9999         if (DetectWriteToReservedRegister())
10000           return;
10001 
10002         // Add information to the INLINEASM node to know that this register is
10003         // set.
10004         OpInfo.AssignedRegs.AddInlineAsmOperands(
10005             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10006                                   : InlineAsm::Kind::RegDef,
10007             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
10008       }
10009       break;
10010 
10011     case InlineAsm::isInput:
10012     case InlineAsm::isLabel: {
10013       SDValue InOperandVal = OpInfo.CallOperand;
10014 
10015       if (OpInfo.isMatchingInputConstraint()) {
10016         // If this is required to match an output register we have already set,
10017         // just use its register.
10018         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10019                                                   AsmNodeOperands);
10020         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
10021         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10022           if (OpInfo.isIndirect) {
10023             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10024             emitInlineAsmError(Call, "inline asm not supported yet: "
10025                                      "don't know how to handle tied "
10026                                      "indirect register inputs");
10027             return;
10028           }
10029 
10030           SmallVector<unsigned, 4> Regs;
10031           MachineFunction &MF = DAG.getMachineFunction();
10032           MachineRegisterInfo &MRI = MF.getRegInfo();
10033           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10034           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
10035           Register TiedReg = R->getReg();
10036           MVT RegVT = R->getSimpleValueType(0);
10037           const TargetRegisterClass *RC =
10038               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
10039               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10040                                       : TRI.getMinimalPhysRegClass(TiedReg);
10041           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
10042             Regs.push_back(MRI.createVirtualRegister(RC));
10043 
10044           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10045 
10046           SDLoc dl = getCurSDLoc();
10047           // Use the produced MatchedRegs object to
10048           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
10049           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
10050                                            OpInfo.getMatchedOperand(), dl, DAG,
10051                                            AsmNodeOperands);
10052           break;
10053         }
10054 
10055         assert(Flag.isMemKind() && "Unknown matching constraint!");
10056         assert(Flag.getNumOperandRegisters() == 1 &&
10057                "Unexpected number of operands");
10058         // Add information to the INLINEASM node to know about this input.
10059         // See InlineAsm.h isUseOperandTiedToDef.
10060         Flag.clearMemConstraint();
10061         Flag.setMatchingOp(OpInfo.getMatchedOperand());
10062         AsmNodeOperands.push_back(DAG.getTargetConstant(
10063             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10064         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
10065         break;
10066       }
10067 
10068       // Treat indirect 'X' constraint as memory.
10069       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10070           OpInfo.isIndirect)
10071         OpInfo.ConstraintType = TargetLowering::C_Memory;
10072 
10073       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10074           OpInfo.ConstraintType == TargetLowering::C_Other) {
10075         std::vector<SDValue> Ops;
10076         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10077                                           Ops, DAG);
10078         if (Ops.empty()) {
10079           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10080             if (isa<ConstantSDNode>(InOperandVal)) {
10081               emitInlineAsmError(Call, "value out of range for constraint '" +
10082                                            Twine(OpInfo.ConstraintCode) + "'");
10083               return;
10084             }
10085 
10086           emitInlineAsmError(Call,
10087                              "invalid operand for inline asm constraint '" +
10088                                  Twine(OpInfo.ConstraintCode) + "'");
10089           return;
10090         }
10091 
10092         // Add information to the INLINEASM node to know about this input.
10093         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10094         AsmNodeOperands.push_back(DAG.getTargetConstant(
10095             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10096         llvm::append_range(AsmNodeOperands, Ops);
10097         break;
10098       }
10099 
10100       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10101         assert((OpInfo.isIndirect ||
10102                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10103                "Operand must be indirect to be a mem!");
10104         assert(InOperandVal.getValueType() ==
10105                    TLI.getPointerTy(DAG.getDataLayout()) &&
10106                "Memory operands expect pointer values");
10107 
10108         const InlineAsm::ConstraintCode ConstraintID =
10109             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10110         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10111                "Failed to convert memory constraint code to constraint id.");
10112 
10113         // Add information to the INLINEASM node to know about this input.
10114         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10115         ResOpType.setMemConstraint(ConstraintID);
10116         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
10117                                                         getCurSDLoc(),
10118                                                         MVT::i32));
10119         AsmNodeOperands.push_back(InOperandVal);
10120         break;
10121       }
10122 
10123       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10124         const InlineAsm::ConstraintCode ConstraintID =
10125             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10126         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10127                "Failed to convert memory constraint code to constraint id.");
10128 
10129         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10130 
10131         SDValue AsmOp = InOperandVal;
10132         if (isFunction(InOperandVal)) {
10133           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10134           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10135           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
10136                                              InOperandVal.getValueType(),
10137                                              GA->getOffset());
10138         }
10139 
10140         // Add information to the INLINEASM node to know about this input.
10141         ResOpType.setMemConstraint(ConstraintID);
10142 
10143         AsmNodeOperands.push_back(
10144             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
10145 
10146         AsmNodeOperands.push_back(AsmOp);
10147         break;
10148       }
10149 
10150       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10151           OpInfo.ConstraintType != TargetLowering::C_Register) {
10152         emitInlineAsmError(Call, "unknown asm constraint '" +
10153                                      Twine(OpInfo.ConstraintCode) + "'");
10154         return;
10155       }
10156 
10157       // TODO: Support this.
10158       if (OpInfo.isIndirect) {
10159         emitInlineAsmError(
10160             Call, "Don't know how to handle indirect register inputs yet "
10161                   "for constraint '" +
10162                       Twine(OpInfo.ConstraintCode) + "'");
10163         return;
10164       }
10165 
10166       // Copy the input into the appropriate registers.
10167       if (OpInfo.AssignedRegs.Regs.empty()) {
10168         emitInlineAsmError(Call,
10169                            "couldn't allocate input reg for constraint '" +
10170                                Twine(OpInfo.ConstraintCode) + "'");
10171         return;
10172       }
10173 
10174       if (DetectWriteToReservedRegister())
10175         return;
10176 
10177       SDLoc dl = getCurSDLoc();
10178 
10179       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
10180                                         &Call);
10181 
10182       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
10183                                                0, dl, DAG, AsmNodeOperands);
10184       break;
10185     }
10186     case InlineAsm::isClobber:
10187       // Add the clobbered value to the operand list, so that the register
10188       // allocator is aware that the physreg got clobbered.
10189       if (!OpInfo.AssignedRegs.Regs.empty())
10190         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
10191                                                  false, 0, getCurSDLoc(), DAG,
10192                                                  AsmNodeOperands);
10193       break;
10194     }
10195   }
10196 
10197   // Finish up input operands.  Set the input chain and add the flag last.
10198   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10199   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
10200 
10201   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10202   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
10203                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
10204   Glue = Chain.getValue(1);
10205 
10206   // Do additional work to generate outputs.
10207 
10208   SmallVector<EVT, 1> ResultVTs;
10209   SmallVector<SDValue, 1> ResultValues;
10210   SmallVector<SDValue, 8> OutChains;
10211 
10212   llvm::Type *CallResultType = Call.getType();
10213   ArrayRef<Type *> ResultTypes;
10214   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10215     ResultTypes = StructResult->elements();
10216   else if (!CallResultType->isVoidTy())
10217     ResultTypes = ArrayRef(CallResultType);
10218 
10219   auto CurResultType = ResultTypes.begin();
10220   auto handleRegAssign = [&](SDValue V) {
10221     assert(CurResultType != ResultTypes.end() && "Unexpected value");
10222     assert((*CurResultType)->isSized() && "Unexpected unsized type");
10223     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10224     ++CurResultType;
10225     // If the type of the inline asm call site return value is different but has
10226     // same size as the type of the asm output bitcast it.  One example of this
10227     // is for vectors with different width / number of elements.  This can
10228     // happen for register classes that can contain multiple different value
10229     // types.  The preg or vreg allocated may not have the same VT as was
10230     // expected.
10231     //
10232     // This can also happen for a return value that disagrees with the register
10233     // class it is put in, eg. a double in a general-purpose register on a
10234     // 32-bit machine.
10235     if (ResultVT != V.getValueType() &&
10236         ResultVT.getSizeInBits() == V.getValueSizeInBits())
10237       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10238     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10239              V.getValueType().isInteger()) {
10240       // If a result value was tied to an input value, the computed result
10241       // may have a wider width than the expected result.  Extract the
10242       // relevant portion.
10243       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10244     }
10245     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10246     ResultVTs.push_back(ResultVT);
10247     ResultValues.push_back(V);
10248   };
10249 
10250   // Deal with output operands.
10251   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10252     if (OpInfo.Type == InlineAsm::isOutput) {
10253       SDValue Val;
10254       // Skip trivial output operands.
10255       if (OpInfo.AssignedRegs.Regs.empty())
10256         continue;
10257 
10258       switch (OpInfo.ConstraintType) {
10259       case TargetLowering::C_Register:
10260       case TargetLowering::C_RegisterClass:
10261         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10262                                                   Chain, &Glue, &Call);
10263         break;
10264       case TargetLowering::C_Immediate:
10265       case TargetLowering::C_Other:
10266         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10267                                               OpInfo, DAG);
10268         break;
10269       case TargetLowering::C_Memory:
10270         break; // Already handled.
10271       case TargetLowering::C_Address:
10272         break; // Silence warning.
10273       case TargetLowering::C_Unknown:
10274         assert(false && "Unexpected unknown constraint");
10275       }
10276 
10277       // Indirect output manifest as stores. Record output chains.
10278       if (OpInfo.isIndirect) {
10279         const Value *Ptr = OpInfo.CallOperandVal;
10280         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10281         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10282                                      MachinePointerInfo(Ptr));
10283         OutChains.push_back(Store);
10284       } else {
10285         // generate CopyFromRegs to associated registers.
10286         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10287         if (Val.getOpcode() == ISD::MERGE_VALUES) {
10288           for (const SDValue &V : Val->op_values())
10289             handleRegAssign(V);
10290         } else
10291           handleRegAssign(Val);
10292       }
10293     }
10294   }
10295 
10296   // Set results.
10297   if (!ResultValues.empty()) {
10298     assert(CurResultType == ResultTypes.end() &&
10299            "Mismatch in number of ResultTypes");
10300     assert(ResultValues.size() == ResultTypes.size() &&
10301            "Mismatch in number of output operands in asm result");
10302 
10303     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10304                             DAG.getVTList(ResultVTs), ResultValues);
10305     setValue(&Call, V);
10306   }
10307 
10308   // Collect store chains.
10309   if (!OutChains.empty())
10310     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10311 
10312   if (EmitEHLabels) {
10313     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10314   }
10315 
10316   // Only Update Root if inline assembly has a memory effect.
10317   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10318       EmitEHLabels)
10319     DAG.setRoot(Chain);
10320 }
10321 
emitInlineAsmError(const CallBase & Call,const Twine & Message)10322 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10323                                              const Twine &Message) {
10324   LLVMContext &Ctx = *DAG.getContext();
10325   Ctx.emitError(&Call, Message);
10326 
10327   // Make sure we leave the DAG in a valid state
10328   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10329   SmallVector<EVT, 1> ValueVTs;
10330   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10331 
10332   if (ValueVTs.empty())
10333     return;
10334 
10335   SmallVector<SDValue, 1> Ops;
10336   for (const EVT &VT : ValueVTs)
10337     Ops.push_back(DAG.getUNDEF(VT));
10338 
10339   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10340 }
10341 
visitVAStart(const CallInst & I)10342 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10343   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10344                           MVT::Other, getRoot(),
10345                           getValue(I.getArgOperand(0)),
10346                           DAG.getSrcValue(I.getArgOperand(0))));
10347 }
10348 
visitVAArg(const VAArgInst & I)10349 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10350   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10351   const DataLayout &DL = DAG.getDataLayout();
10352   SDValue V = DAG.getVAArg(
10353       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10354       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10355       DL.getABITypeAlign(I.getType()).value());
10356   DAG.setRoot(V.getValue(1));
10357 
10358   if (I.getType()->isPointerTy())
10359     V = DAG.getPtrExtOrTrunc(
10360         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10361   setValue(&I, V);
10362 }
10363 
visitVAEnd(const CallInst & I)10364 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10365   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10366                           MVT::Other, getRoot(),
10367                           getValue(I.getArgOperand(0)),
10368                           DAG.getSrcValue(I.getArgOperand(0))));
10369 }
10370 
visitVACopy(const CallInst & I)10371 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10372   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10373                           MVT::Other, getRoot(),
10374                           getValue(I.getArgOperand(0)),
10375                           getValue(I.getArgOperand(1)),
10376                           DAG.getSrcValue(I.getArgOperand(0)),
10377                           DAG.getSrcValue(I.getArgOperand(1))));
10378 }
10379 
lowerRangeToAssertZExt(SelectionDAG & DAG,const Instruction & I,SDValue Op)10380 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10381                                                     const Instruction &I,
10382                                                     SDValue Op) {
10383   std::optional<ConstantRange> CR = getRange(I);
10384 
10385   if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10386     return Op;
10387 
10388   APInt Lo = CR->getUnsignedMin();
10389   if (!Lo.isMinValue())
10390     return Op;
10391 
10392   APInt Hi = CR->getUnsignedMax();
10393   unsigned Bits = std::max(Hi.getActiveBits(),
10394                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10395 
10396   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10397 
10398   SDLoc SL = getCurSDLoc();
10399 
10400   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10401                              DAG.getValueType(SmallVT));
10402   unsigned NumVals = Op.getNode()->getNumValues();
10403   if (NumVals == 1)
10404     return ZExt;
10405 
10406   SmallVector<SDValue, 4> Ops;
10407 
10408   Ops.push_back(ZExt);
10409   for (unsigned I = 1; I != NumVals; ++I)
10410     Ops.push_back(Op.getValue(I));
10411 
10412   return DAG.getMergeValues(Ops, SL);
10413 }
10414 
10415 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10416 /// the call being lowered.
10417 ///
10418 /// This is a helper for lowering intrinsics that follow a target calling
10419 /// convention or require stack pointer adjustment. Only a subset of the
10420 /// intrinsic's operands need to participate in the calling convention.
populateCallLoweringInfo(TargetLowering::CallLoweringInfo & CLI,const CallBase * Call,unsigned ArgIdx,unsigned NumArgs,SDValue Callee,Type * ReturnTy,AttributeSet RetAttrs,bool IsPatchPoint)10421 void SelectionDAGBuilder::populateCallLoweringInfo(
10422     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10423     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10424     AttributeSet RetAttrs, bool IsPatchPoint) {
10425   TargetLowering::ArgListTy Args;
10426   Args.reserve(NumArgs);
10427 
10428   // Populate the argument list.
10429   // Attributes for args start at offset 1, after the return attribute.
10430   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10431        ArgI != ArgE; ++ArgI) {
10432     const Value *V = Call->getOperand(ArgI);
10433 
10434     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10435 
10436     TargetLowering::ArgListEntry Entry;
10437     Entry.Node = getValue(V);
10438     Entry.Ty = V->getType();
10439     Entry.setAttributes(Call, ArgI);
10440     Args.push_back(Entry);
10441   }
10442 
10443   CLI.setDebugLoc(getCurSDLoc())
10444       .setChain(getRoot())
10445       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10446                  RetAttrs)
10447       .setDiscardResult(Call->use_empty())
10448       .setIsPatchPoint(IsPatchPoint)
10449       .setIsPreallocated(
10450           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10451 }
10452 
10453 /// Add a stack map intrinsic call's live variable operands to a stackmap
10454 /// or patchpoint target node's operand list.
10455 ///
10456 /// Constants are converted to TargetConstants purely as an optimization to
10457 /// avoid constant materialization and register allocation.
10458 ///
10459 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10460 /// generate addess computation nodes, and so FinalizeISel can convert the
10461 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10462 /// address materialization and register allocation, but may also be required
10463 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10464 /// alloca in the entry block, then the runtime may assume that the alloca's
10465 /// StackMap location can be read immediately after compilation and that the
10466 /// location is valid at any point during execution (this is similar to the
10467 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10468 /// only available in a register, then the runtime would need to trap when
10469 /// execution reaches the StackMap in order to read the alloca's location.
addStackMapLiveVars(const CallBase & Call,unsigned StartIdx,const SDLoc & DL,SmallVectorImpl<SDValue> & Ops,SelectionDAGBuilder & Builder)10470 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10471                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10472                                 SelectionDAGBuilder &Builder) {
10473   SelectionDAG &DAG = Builder.DAG;
10474   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10475     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10476 
10477     // Things on the stack are pointer-typed, meaning that they are already
10478     // legal and can be emitted directly to target nodes.
10479     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10480       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10481     } else {
10482       // Otherwise emit a target independent node to be legalised.
10483       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10484     }
10485   }
10486 }
10487 
10488 /// Lower llvm.experimental.stackmap.
visitStackmap(const CallInst & CI)10489 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10490   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10491   //                                  [live variables...])
10492 
10493   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10494 
10495   SDValue Chain, InGlue, Callee;
10496   SmallVector<SDValue, 32> Ops;
10497 
10498   SDLoc DL = getCurSDLoc();
10499   Callee = getValue(CI.getCalledOperand());
10500 
10501   // The stackmap intrinsic only records the live variables (the arguments
10502   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10503   // intrinsic, this won't be lowered to a function call. This means we don't
10504   // have to worry about calling conventions and target specific lowering code.
10505   // Instead we perform the call lowering right here.
10506   //
10507   // chain, flag = CALLSEQ_START(chain, 0, 0)
10508   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10509   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10510   //
10511   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10512   InGlue = Chain.getValue(1);
10513 
10514   // Add the STACKMAP operands, starting with DAG house-keeping.
10515   Ops.push_back(Chain);
10516   Ops.push_back(InGlue);
10517 
10518   // Add the <id>, <numShadowBytes> operands.
10519   //
10520   // These do not require legalisation, and can be emitted directly to target
10521   // constant nodes.
10522   SDValue ID = getValue(CI.getArgOperand(0));
10523   assert(ID.getValueType() == MVT::i64);
10524   SDValue IDConst =
10525       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10526   Ops.push_back(IDConst);
10527 
10528   SDValue Shad = getValue(CI.getArgOperand(1));
10529   assert(Shad.getValueType() == MVT::i32);
10530   SDValue ShadConst =
10531       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10532   Ops.push_back(ShadConst);
10533 
10534   // Add the live variables.
10535   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10536 
10537   // Create the STACKMAP node.
10538   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10539   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10540   InGlue = Chain.getValue(1);
10541 
10542   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10543 
10544   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10545 
10546   // Set the root to the target-lowered call chain.
10547   DAG.setRoot(Chain);
10548 
10549   // Inform the Frame Information that we have a stackmap in this function.
10550   FuncInfo.MF->getFrameInfo().setHasStackMap();
10551 }
10552 
10553 /// Lower llvm.experimental.patchpoint directly to its target opcode.
visitPatchpoint(const CallBase & CB,const BasicBlock * EHPadBB)10554 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10555                                           const BasicBlock *EHPadBB) {
10556   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10557   //                                         i32 <numBytes>,
10558   //                                         i8* <target>,
10559   //                                         i32 <numArgs>,
10560   //                                         [Args...],
10561   //                                         [live variables...])
10562 
10563   CallingConv::ID CC = CB.getCallingConv();
10564   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10565   bool HasDef = !CB.getType()->isVoidTy();
10566   SDLoc dl = getCurSDLoc();
10567   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10568 
10569   // Handle immediate and symbolic callees.
10570   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10571     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10572                                    /*isTarget=*/true);
10573   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10574     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10575                                          SDLoc(SymbolicCallee),
10576                                          SymbolicCallee->getValueType(0));
10577 
10578   // Get the real number of arguments participating in the call <numArgs>
10579   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10580   unsigned NumArgs = NArgVal->getAsZExtVal();
10581 
10582   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10583   // Intrinsics include all meta-operands up to but not including CC.
10584   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10585   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10586          "Not enough arguments provided to the patchpoint intrinsic");
10587 
10588   // For AnyRegCC the arguments are lowered later on manually.
10589   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10590   Type *ReturnTy =
10591       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10592 
10593   TargetLowering::CallLoweringInfo CLI(DAG);
10594   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10595                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10596   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10597 
10598   SDNode *CallEnd = Result.second.getNode();
10599   if (CallEnd->getOpcode() == ISD::EH_LABEL)
10600     CallEnd = CallEnd->getOperand(0).getNode();
10601   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10602     CallEnd = CallEnd->getOperand(0).getNode();
10603 
10604   /// Get a call instruction from the call sequence chain.
10605   /// Tail calls are not allowed.
10606   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10607          "Expected a callseq node.");
10608   SDNode *Call = CallEnd->getOperand(0).getNode();
10609   bool HasGlue = Call->getGluedNode();
10610 
10611   // Replace the target specific call node with the patchable intrinsic.
10612   SmallVector<SDValue, 8> Ops;
10613 
10614   // Push the chain.
10615   Ops.push_back(*(Call->op_begin()));
10616 
10617   // Optionally, push the glue (if any).
10618   if (HasGlue)
10619     Ops.push_back(*(Call->op_end() - 1));
10620 
10621   // Push the register mask info.
10622   if (HasGlue)
10623     Ops.push_back(*(Call->op_end() - 2));
10624   else
10625     Ops.push_back(*(Call->op_end() - 1));
10626 
10627   // Add the <id> and <numBytes> constants.
10628   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10629   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10630   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10631   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10632 
10633   // Add the callee.
10634   Ops.push_back(Callee);
10635 
10636   // Adjust <numArgs> to account for any arguments that have been passed on the
10637   // stack instead.
10638   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10639   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10640   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10641   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10642 
10643   // Add the calling convention
10644   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10645 
10646   // Add the arguments we omitted previously. The register allocator should
10647   // place these in any free register.
10648   if (IsAnyRegCC)
10649     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10650       Ops.push_back(getValue(CB.getArgOperand(i)));
10651 
10652   // Push the arguments from the call instruction.
10653   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10654   Ops.append(Call->op_begin() + 2, e);
10655 
10656   // Push live variables for the stack map.
10657   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10658 
10659   SDVTList NodeTys;
10660   if (IsAnyRegCC && HasDef) {
10661     // Create the return types based on the intrinsic definition
10662     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10663     SmallVector<EVT, 3> ValueVTs;
10664     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10665     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10666 
10667     // There is always a chain and a glue type at the end
10668     ValueVTs.push_back(MVT::Other);
10669     ValueVTs.push_back(MVT::Glue);
10670     NodeTys = DAG.getVTList(ValueVTs);
10671   } else
10672     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10673 
10674   // Replace the target specific call node with a PATCHPOINT node.
10675   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10676 
10677   // Update the NodeMap.
10678   if (HasDef) {
10679     if (IsAnyRegCC)
10680       setValue(&CB, SDValue(PPV.getNode(), 0));
10681     else
10682       setValue(&CB, Result.first);
10683   }
10684 
10685   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10686   // call sequence. Furthermore the location of the chain and glue can change
10687   // when the AnyReg calling convention is used and the intrinsic returns a
10688   // value.
10689   if (IsAnyRegCC && HasDef) {
10690     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10691     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10692     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10693   } else
10694     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10695   DAG.DeleteNode(Call);
10696 
10697   // Inform the Frame Information that we have a patchpoint in this function.
10698   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10699 }
10700 
visitVectorReduce(const CallInst & I,unsigned Intrinsic)10701 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10702                                             unsigned Intrinsic) {
10703   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10704   SDValue Op1 = getValue(I.getArgOperand(0));
10705   SDValue Op2;
10706   if (I.arg_size() > 1)
10707     Op2 = getValue(I.getArgOperand(1));
10708   SDLoc dl = getCurSDLoc();
10709   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10710   SDValue Res;
10711   SDNodeFlags SDFlags;
10712   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10713     SDFlags.copyFMF(*FPMO);
10714 
10715   switch (Intrinsic) {
10716   case Intrinsic::vector_reduce_fadd:
10717     if (SDFlags.hasAllowReassociation())
10718       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10719                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10720                         SDFlags);
10721     else
10722       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10723     break;
10724   case Intrinsic::vector_reduce_fmul:
10725     if (SDFlags.hasAllowReassociation())
10726       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10727                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10728                         SDFlags);
10729     else
10730       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10731     break;
10732   case Intrinsic::vector_reduce_add:
10733     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10734     break;
10735   case Intrinsic::vector_reduce_mul:
10736     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10737     break;
10738   case Intrinsic::vector_reduce_and:
10739     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10740     break;
10741   case Intrinsic::vector_reduce_or:
10742     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10743     break;
10744   case Intrinsic::vector_reduce_xor:
10745     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10746     break;
10747   case Intrinsic::vector_reduce_smax:
10748     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10749     break;
10750   case Intrinsic::vector_reduce_smin:
10751     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10752     break;
10753   case Intrinsic::vector_reduce_umax:
10754     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10755     break;
10756   case Intrinsic::vector_reduce_umin:
10757     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10758     break;
10759   case Intrinsic::vector_reduce_fmax:
10760     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10761     break;
10762   case Intrinsic::vector_reduce_fmin:
10763     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10764     break;
10765   case Intrinsic::vector_reduce_fmaximum:
10766     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10767     break;
10768   case Intrinsic::vector_reduce_fminimum:
10769     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10770     break;
10771   default:
10772     llvm_unreachable("Unhandled vector reduce intrinsic");
10773   }
10774   setValue(&I, Res);
10775 }
10776 
10777 /// Returns an AttributeList representing the attributes applied to the return
10778 /// value of the given call.
getReturnAttrs(TargetLowering::CallLoweringInfo & CLI)10779 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10780   SmallVector<Attribute::AttrKind, 2> Attrs;
10781   if (CLI.RetSExt)
10782     Attrs.push_back(Attribute::SExt);
10783   if (CLI.RetZExt)
10784     Attrs.push_back(Attribute::ZExt);
10785   if (CLI.IsInReg)
10786     Attrs.push_back(Attribute::InReg);
10787 
10788   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10789                             Attrs);
10790 }
10791 
10792 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10793 /// implementation, which just calls LowerCall.
10794 /// FIXME: When all targets are
10795 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10796 std::pair<SDValue, SDValue>
LowerCallTo(TargetLowering::CallLoweringInfo & CLI) const10797 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10798   // Handle the incoming return values from the call.
10799   CLI.Ins.clear();
10800   Type *OrigRetTy = CLI.RetTy;
10801   SmallVector<EVT, 4> RetTys;
10802   SmallVector<TypeSize, 4> Offsets;
10803   auto &DL = CLI.DAG.getDataLayout();
10804   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10805 
10806   if (CLI.IsPostTypeLegalization) {
10807     // If we are lowering a libcall after legalization, split the return type.
10808     SmallVector<EVT, 4> OldRetTys;
10809     SmallVector<TypeSize, 4> OldOffsets;
10810     RetTys.swap(OldRetTys);
10811     Offsets.swap(OldOffsets);
10812 
10813     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10814       EVT RetVT = OldRetTys[i];
10815       uint64_t Offset = OldOffsets[i];
10816       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10817       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10818       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10819       RetTys.append(NumRegs, RegisterVT);
10820       for (unsigned j = 0; j != NumRegs; ++j)
10821         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
10822     }
10823   }
10824 
10825   SmallVector<ISD::OutputArg, 4> Outs;
10826   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10827 
10828   bool CanLowerReturn =
10829       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10830                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10831 
10832   SDValue DemoteStackSlot;
10833   int DemoteStackIdx = -100;
10834   if (!CanLowerReturn) {
10835     // FIXME: equivalent assert?
10836     // assert(!CS.hasInAllocaArgument() &&
10837     //        "sret demotion is incompatible with inalloca");
10838     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10839     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10840     MachineFunction &MF = CLI.DAG.getMachineFunction();
10841     DemoteStackIdx =
10842         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10843     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10844                                               DL.getAllocaAddrSpace());
10845 
10846     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10847     ArgListEntry Entry;
10848     Entry.Node = DemoteStackSlot;
10849     Entry.Ty = StackSlotPtrType;
10850     Entry.IsSExt = false;
10851     Entry.IsZExt = false;
10852     Entry.IsInReg = false;
10853     Entry.IsSRet = true;
10854     Entry.IsNest = false;
10855     Entry.IsByVal = false;
10856     Entry.IsByRef = false;
10857     Entry.IsReturned = false;
10858     Entry.IsSwiftSelf = false;
10859     Entry.IsSwiftAsync = false;
10860     Entry.IsSwiftError = false;
10861     Entry.IsCFGuardTarget = false;
10862     Entry.Alignment = Alignment;
10863     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10864     CLI.NumFixedArgs += 1;
10865     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10866     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10867 
10868     // sret demotion isn't compatible with tail-calls, since the sret argument
10869     // points into the callers stack frame.
10870     CLI.IsTailCall = false;
10871   } else {
10872     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10873         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10874     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10875       ISD::ArgFlagsTy Flags;
10876       if (NeedsRegBlock) {
10877         Flags.setInConsecutiveRegs();
10878         if (I == RetTys.size() - 1)
10879           Flags.setInConsecutiveRegsLast();
10880       }
10881       EVT VT = RetTys[I];
10882       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10883                                                      CLI.CallConv, VT);
10884       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10885                                                        CLI.CallConv, VT);
10886       for (unsigned i = 0; i != NumRegs; ++i) {
10887         ISD::InputArg MyFlags;
10888         MyFlags.Flags = Flags;
10889         MyFlags.VT = RegisterVT;
10890         MyFlags.ArgVT = VT;
10891         MyFlags.Used = CLI.IsReturnValueUsed;
10892         if (CLI.RetTy->isPointerTy()) {
10893           MyFlags.Flags.setPointer();
10894           MyFlags.Flags.setPointerAddrSpace(
10895               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10896         }
10897         if (CLI.RetSExt)
10898           MyFlags.Flags.setSExt();
10899         if (CLI.RetZExt)
10900           MyFlags.Flags.setZExt();
10901         if (CLI.IsInReg)
10902           MyFlags.Flags.setInReg();
10903         CLI.Ins.push_back(MyFlags);
10904       }
10905     }
10906   }
10907 
10908   // We push in swifterror return as the last element of CLI.Ins.
10909   ArgListTy &Args = CLI.getArgs();
10910   if (supportSwiftError()) {
10911     for (const ArgListEntry &Arg : Args) {
10912       if (Arg.IsSwiftError) {
10913         ISD::InputArg MyFlags;
10914         MyFlags.VT = getPointerTy(DL);
10915         MyFlags.ArgVT = EVT(getPointerTy(DL));
10916         MyFlags.Flags.setSwiftError();
10917         CLI.Ins.push_back(MyFlags);
10918       }
10919     }
10920   }
10921 
10922   // Handle all of the outgoing arguments.
10923   CLI.Outs.clear();
10924   CLI.OutVals.clear();
10925   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10926     SmallVector<EVT, 4> ValueVTs;
10927     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10928     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10929     Type *FinalType = Args[i].Ty;
10930     if (Args[i].IsByVal)
10931       FinalType = Args[i].IndirectType;
10932     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10933         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10934     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10935          ++Value) {
10936       EVT VT = ValueVTs[Value];
10937       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10938       SDValue Op = SDValue(Args[i].Node.getNode(),
10939                            Args[i].Node.getResNo() + Value);
10940       ISD::ArgFlagsTy Flags;
10941 
10942       // Certain targets (such as MIPS), may have a different ABI alignment
10943       // for a type depending on the context. Give the target a chance to
10944       // specify the alignment it wants.
10945       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10946       Flags.setOrigAlign(OriginalAlignment);
10947 
10948       if (Args[i].Ty->isPointerTy()) {
10949         Flags.setPointer();
10950         Flags.setPointerAddrSpace(
10951             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10952       }
10953       if (Args[i].IsZExt)
10954         Flags.setZExt();
10955       if (Args[i].IsSExt)
10956         Flags.setSExt();
10957       if (Args[i].IsInReg) {
10958         // If we are using vectorcall calling convention, a structure that is
10959         // passed InReg - is surely an HVA
10960         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10961             isa<StructType>(FinalType)) {
10962           // The first value of a structure is marked
10963           if (0 == Value)
10964             Flags.setHvaStart();
10965           Flags.setHva();
10966         }
10967         // Set InReg Flag
10968         Flags.setInReg();
10969       }
10970       if (Args[i].IsSRet)
10971         Flags.setSRet();
10972       if (Args[i].IsSwiftSelf)
10973         Flags.setSwiftSelf();
10974       if (Args[i].IsSwiftAsync)
10975         Flags.setSwiftAsync();
10976       if (Args[i].IsSwiftError)
10977         Flags.setSwiftError();
10978       if (Args[i].IsCFGuardTarget)
10979         Flags.setCFGuardTarget();
10980       if (Args[i].IsByVal)
10981         Flags.setByVal();
10982       if (Args[i].IsByRef)
10983         Flags.setByRef();
10984       if (Args[i].IsPreallocated) {
10985         Flags.setPreallocated();
10986         // Set the byval flag for CCAssignFn callbacks that don't know about
10987         // preallocated.  This way we can know how many bytes we should've
10988         // allocated and how many bytes a callee cleanup function will pop.  If
10989         // we port preallocated to more targets, we'll have to add custom
10990         // preallocated handling in the various CC lowering callbacks.
10991         Flags.setByVal();
10992       }
10993       if (Args[i].IsInAlloca) {
10994         Flags.setInAlloca();
10995         // Set the byval flag for CCAssignFn callbacks that don't know about
10996         // inalloca.  This way we can know how many bytes we should've allocated
10997         // and how many bytes a callee cleanup function will pop.  If we port
10998         // inalloca to more targets, we'll have to add custom inalloca handling
10999         // in the various CC lowering callbacks.
11000         Flags.setByVal();
11001       }
11002       Align MemAlign;
11003       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11004         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11005         Flags.setByValSize(FrameSize);
11006 
11007         // info is not there but there are cases it cannot get right.
11008         if (auto MA = Args[i].Alignment)
11009           MemAlign = *MA;
11010         else
11011           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
11012       } else if (auto MA = Args[i].Alignment) {
11013         MemAlign = *MA;
11014       } else {
11015         MemAlign = OriginalAlignment;
11016       }
11017       Flags.setMemAlign(MemAlign);
11018       if (Args[i].IsNest)
11019         Flags.setNest();
11020       if (NeedsRegBlock)
11021         Flags.setInConsecutiveRegs();
11022 
11023       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11024                                                  CLI.CallConv, VT);
11025       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11026                                                         CLI.CallConv, VT);
11027       SmallVector<SDValue, 4> Parts(NumParts);
11028       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11029 
11030       if (Args[i].IsSExt)
11031         ExtendKind = ISD::SIGN_EXTEND;
11032       else if (Args[i].IsZExt)
11033         ExtendKind = ISD::ZERO_EXTEND;
11034 
11035       // Conservatively only handle 'returned' on non-vectors that can be lowered,
11036       // for now.
11037       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11038           CanLowerReturn) {
11039         assert((CLI.RetTy == Args[i].Ty ||
11040                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11041                  CLI.RetTy->getPointerAddressSpace() ==
11042                      Args[i].Ty->getPointerAddressSpace())) &&
11043                RetTys.size() == NumValues && "unexpected use of 'returned'");
11044         // Before passing 'returned' to the target lowering code, ensure that
11045         // either the register MVT and the actual EVT are the same size or that
11046         // the return value and argument are extended in the same way; in these
11047         // cases it's safe to pass the argument register value unchanged as the
11048         // return register value (although it's at the target's option whether
11049         // to do so)
11050         // TODO: allow code generation to take advantage of partially preserved
11051         // registers rather than clobbering the entire register when the
11052         // parameter extension method is not compatible with the return
11053         // extension method
11054         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11055             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11056              CLI.RetZExt == Args[i].IsZExt))
11057           Flags.setReturned();
11058       }
11059 
11060       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11061                      CLI.CallConv, ExtendKind);
11062 
11063       for (unsigned j = 0; j != NumParts; ++j) {
11064         // if it isn't first piece, alignment must be 1
11065         // For scalable vectors the scalable part is currently handled
11066         // by individual targets, so we just use the known minimum size here.
11067         ISD::OutputArg MyFlags(
11068             Flags, Parts[j].getValueType().getSimpleVT(), VT,
11069             i < CLI.NumFixedArgs, i,
11070             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11071         if (NumParts > 1 && j == 0)
11072           MyFlags.Flags.setSplit();
11073         else if (j != 0) {
11074           MyFlags.Flags.setOrigAlign(Align(1));
11075           if (j == NumParts - 1)
11076             MyFlags.Flags.setSplitEnd();
11077         }
11078 
11079         CLI.Outs.push_back(MyFlags);
11080         CLI.OutVals.push_back(Parts[j]);
11081       }
11082 
11083       if (NeedsRegBlock && Value == NumValues - 1)
11084         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11085     }
11086   }
11087 
11088   SmallVector<SDValue, 4> InVals;
11089   CLI.Chain = LowerCall(CLI, InVals);
11090 
11091   // Update CLI.InVals to use outside of this function.
11092   CLI.InVals = InVals;
11093 
11094   // Verify that the target's LowerCall behaved as expected.
11095   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11096          "LowerCall didn't return a valid chain!");
11097   assert((!CLI.IsTailCall || InVals.empty()) &&
11098          "LowerCall emitted a return value for a tail call!");
11099   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11100          "LowerCall didn't emit the correct number of values!");
11101 
11102   // For a tail call, the return value is merely live-out and there aren't
11103   // any nodes in the DAG representing it. Return a special value to
11104   // indicate that a tail call has been emitted and no more Instructions
11105   // should be processed in the current block.
11106   if (CLI.IsTailCall) {
11107     CLI.DAG.setRoot(CLI.Chain);
11108     return std::make_pair(SDValue(), SDValue());
11109   }
11110 
11111 #ifndef NDEBUG
11112   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11113     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11114     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11115            "LowerCall emitted a value with the wrong type!");
11116   }
11117 #endif
11118 
11119   SmallVector<SDValue, 4> ReturnValues;
11120   if (!CanLowerReturn) {
11121     // The instruction result is the result of loading from the
11122     // hidden sret parameter.
11123     SmallVector<EVT, 1> PVTs;
11124     Type *PtrRetTy =
11125         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
11126 
11127     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
11128     assert(PVTs.size() == 1 && "Pointers should fit in one register");
11129     EVT PtrVT = PVTs[0];
11130 
11131     unsigned NumValues = RetTys.size();
11132     ReturnValues.resize(NumValues);
11133     SmallVector<SDValue, 4> Chains(NumValues);
11134 
11135     // An aggregate return value cannot wrap around the address space, so
11136     // offsets to its parts don't wrap either.
11137     SDNodeFlags Flags;
11138     Flags.setNoUnsignedWrap(true);
11139 
11140     MachineFunction &MF = CLI.DAG.getMachineFunction();
11141     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11142     for (unsigned i = 0; i < NumValues; ++i) {
11143       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
11144                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
11145                                                         PtrVT), Flags);
11146       SDValue L = CLI.DAG.getLoad(
11147           RetTys[i], CLI.DL, CLI.Chain, Add,
11148           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
11149                                             DemoteStackIdx, Offsets[i]),
11150           HiddenSRetAlign);
11151       ReturnValues[i] = L;
11152       Chains[i] = L.getValue(1);
11153     }
11154 
11155     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11156   } else {
11157     // Collect the legal value parts into potentially illegal values
11158     // that correspond to the original function's return values.
11159     std::optional<ISD::NodeType> AssertOp;
11160     if (CLI.RetSExt)
11161       AssertOp = ISD::AssertSext;
11162     else if (CLI.RetZExt)
11163       AssertOp = ISD::AssertZext;
11164     unsigned CurReg = 0;
11165     for (EVT VT : RetTys) {
11166       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11167                                                      CLI.CallConv, VT);
11168       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11169                                                        CLI.CallConv, VT);
11170 
11171       ReturnValues.push_back(getCopyFromParts(
11172           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11173           CLI.Chain, CLI.CallConv, AssertOp));
11174       CurReg += NumRegs;
11175     }
11176 
11177     // For a function returning void, there is no return value. We can't create
11178     // such a node, so we just return a null return value in that case. In
11179     // that case, nothing will actually look at the value.
11180     if (ReturnValues.empty())
11181       return std::make_pair(SDValue(), CLI.Chain);
11182   }
11183 
11184   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11185                                 CLI.DAG.getVTList(RetTys), ReturnValues);
11186   return std::make_pair(Res, CLI.Chain);
11187 }
11188 
11189 /// Places new result values for the node in Results (their number
11190 /// and types must exactly match those of the original return values of
11191 /// the node), or leaves Results empty, which indicates that the node is not
11192 /// to be custom lowered after all.
LowerOperationWrapper(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const11193 void TargetLowering::LowerOperationWrapper(SDNode *N,
11194                                            SmallVectorImpl<SDValue> &Results,
11195                                            SelectionDAG &DAG) const {
11196   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11197 
11198   if (!Res.getNode())
11199     return;
11200 
11201   // If the original node has one result, take the return value from
11202   // LowerOperation as is. It might not be result number 0.
11203   if (N->getNumValues() == 1) {
11204     Results.push_back(Res);
11205     return;
11206   }
11207 
11208   // If the original node has multiple results, then the return node should
11209   // have the same number of results.
11210   assert((N->getNumValues() == Res->getNumValues()) &&
11211       "Lowering returned the wrong number of results!");
11212 
11213   // Places new result values base on N result number.
11214   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11215     Results.push_back(Res.getValue(I));
11216 }
11217 
LowerOperation(SDValue Op,SelectionDAG & DAG) const11218 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11219   llvm_unreachable("LowerOperation not implemented for this target!");
11220 }
11221 
CopyValueToVirtualRegister(const Value * V,unsigned Reg,ISD::NodeType ExtendType)11222 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11223                                                      unsigned Reg,
11224                                                      ISD::NodeType ExtendType) {
11225   SDValue Op = getNonRegisterValue(V);
11226   assert((Op.getOpcode() != ISD::CopyFromReg ||
11227           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11228          "Copy from a reg to the same reg!");
11229   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
11230 
11231   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11232   // If this is an InlineAsm we have to match the registers required, not the
11233   // notional registers required by the type.
11234 
11235   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11236                    std::nullopt); // This is not an ABI copy.
11237   SDValue Chain = DAG.getEntryNode();
11238 
11239   if (ExtendType == ISD::ANY_EXTEND) {
11240     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11241     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11242       ExtendType = PreferredExtendIt->second;
11243   }
11244   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11245   PendingExports.push_back(Chain);
11246 }
11247 
11248 #include "llvm/CodeGen/SelectionDAGISel.h"
11249 
11250 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11251 /// entry block, return true.  This includes arguments used by switches, since
11252 /// the switch may expand into multiple basic blocks.
isOnlyUsedInEntryBlock(const Argument * A,bool FastISel)11253 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11254   // With FastISel active, we may be splitting blocks, so force creation
11255   // of virtual registers for all non-dead arguments.
11256   if (FastISel)
11257     return A->use_empty();
11258 
11259   const BasicBlock &Entry = A->getParent()->front();
11260   for (const User *U : A->users())
11261     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11262       return false;  // Use not in entry block.
11263 
11264   return true;
11265 }
11266 
11267 using ArgCopyElisionMapTy =
11268     DenseMap<const Argument *,
11269              std::pair<const AllocaInst *, const StoreInst *>>;
11270 
11271 /// Scan the entry block of the function in FuncInfo for arguments that look
11272 /// like copies into a local alloca. Record any copied arguments in
11273 /// ArgCopyElisionCandidates.
11274 static void
findArgumentCopyElisionCandidates(const DataLayout & DL,FunctionLoweringInfo * FuncInfo,ArgCopyElisionMapTy & ArgCopyElisionCandidates)11275 findArgumentCopyElisionCandidates(const DataLayout &DL,
11276                                   FunctionLoweringInfo *FuncInfo,
11277                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11278   // Record the state of every static alloca used in the entry block. Argument
11279   // allocas are all used in the entry block, so we need approximately as many
11280   // entries as we have arguments.
11281   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11282   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11283   unsigned NumArgs = FuncInfo->Fn->arg_size();
11284   StaticAllocas.reserve(NumArgs * 2);
11285 
11286   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11287     if (!V)
11288       return nullptr;
11289     V = V->stripPointerCasts();
11290     const auto *AI = dyn_cast<AllocaInst>(V);
11291     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11292       return nullptr;
11293     auto Iter = StaticAllocas.insert({AI, Unknown});
11294     return &Iter.first->second;
11295   };
11296 
11297   // Look for stores of arguments to static allocas. Look through bitcasts and
11298   // GEPs to handle type coercions, as long as the alloca is fully initialized
11299   // by the store. Any non-store use of an alloca escapes it and any subsequent
11300   // unanalyzed store might write it.
11301   // FIXME: Handle structs initialized with multiple stores.
11302   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11303     // Look for stores, and handle non-store uses conservatively.
11304     const auto *SI = dyn_cast<StoreInst>(&I);
11305     if (!SI) {
11306       // We will look through cast uses, so ignore them completely.
11307       if (I.isCast())
11308         continue;
11309       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11310       // to allocas.
11311       if (I.isDebugOrPseudoInst())
11312         continue;
11313       // This is an unknown instruction. Assume it escapes or writes to all
11314       // static alloca operands.
11315       for (const Use &U : I.operands()) {
11316         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11317           *Info = StaticAllocaInfo::Clobbered;
11318       }
11319       continue;
11320     }
11321 
11322     // If the stored value is a static alloca, mark it as escaped.
11323     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11324       *Info = StaticAllocaInfo::Clobbered;
11325 
11326     // Check if the destination is a static alloca.
11327     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11328     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11329     if (!Info)
11330       continue;
11331     const AllocaInst *AI = cast<AllocaInst>(Dst);
11332 
11333     // Skip allocas that have been initialized or clobbered.
11334     if (*Info != StaticAllocaInfo::Unknown)
11335       continue;
11336 
11337     // Check if the stored value is an argument, and that this store fully
11338     // initializes the alloca.
11339     // If the argument type has padding bits we can't directly forward a pointer
11340     // as the upper bits may contain garbage.
11341     // Don't elide copies from the same argument twice.
11342     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11343     const auto *Arg = dyn_cast<Argument>(Val);
11344     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11345         Arg->getType()->isEmptyTy() ||
11346         DL.getTypeStoreSize(Arg->getType()) !=
11347             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11348         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11349         ArgCopyElisionCandidates.count(Arg)) {
11350       *Info = StaticAllocaInfo::Clobbered;
11351       continue;
11352     }
11353 
11354     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11355                       << '\n');
11356 
11357     // Mark this alloca and store for argument copy elision.
11358     *Info = StaticAllocaInfo::Elidable;
11359     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11360 
11361     // Stop scanning if we've seen all arguments. This will happen early in -O0
11362     // builds, which is useful, because -O0 builds have large entry blocks and
11363     // many allocas.
11364     if (ArgCopyElisionCandidates.size() == NumArgs)
11365       break;
11366   }
11367 }
11368 
11369 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11370 /// ArgVal is a load from a suitable fixed stack object.
tryToElideArgumentCopy(FunctionLoweringInfo & FuncInfo,SmallVectorImpl<SDValue> & Chains,DenseMap<int,int> & ArgCopyElisionFrameIndexMap,SmallPtrSetImpl<const Instruction * > & ElidedArgCopyInstrs,ArgCopyElisionMapTy & ArgCopyElisionCandidates,const Argument & Arg,ArrayRef<SDValue> ArgVals,bool & ArgHasUses)11371 static void tryToElideArgumentCopy(
11372     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11373     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11374     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11375     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11376     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11377   // Check if this is a load from a fixed stack object.
11378   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11379   if (!LNode)
11380     return;
11381   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11382   if (!FINode)
11383     return;
11384 
11385   // Check that the fixed stack object is the right size and alignment.
11386   // Look at the alignment that the user wrote on the alloca instead of looking
11387   // at the stack object.
11388   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11389   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11390   const AllocaInst *AI = ArgCopyIter->second.first;
11391   int FixedIndex = FINode->getIndex();
11392   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11393   int OldIndex = AllocaIndex;
11394   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11395   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11396     LLVM_DEBUG(
11397         dbgs() << "  argument copy elision failed due to bad fixed stack "
11398                   "object size\n");
11399     return;
11400   }
11401   Align RequiredAlignment = AI->getAlign();
11402   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11403     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11404                          "greater than stack argument alignment ("
11405                       << DebugStr(RequiredAlignment) << " vs "
11406                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11407     return;
11408   }
11409 
11410   // Perform the elision. Delete the old stack object and replace its only use
11411   // in the variable info map. Mark the stack object as mutable and aliased.
11412   LLVM_DEBUG({
11413     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11414            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11415            << '\n';
11416   });
11417   MFI.RemoveStackObject(OldIndex);
11418   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11419   MFI.setIsAliasedObjectIndex(FixedIndex, true);
11420   AllocaIndex = FixedIndex;
11421   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11422   for (SDValue ArgVal : ArgVals)
11423     Chains.push_back(ArgVal.getValue(1));
11424 
11425   // Avoid emitting code for the store implementing the copy.
11426   const StoreInst *SI = ArgCopyIter->second.second;
11427   ElidedArgCopyInstrs.insert(SI);
11428 
11429   // Check for uses of the argument again so that we can avoid exporting ArgVal
11430   // if it is't used by anything other than the store.
11431   for (const Value *U : Arg.users()) {
11432     if (U != SI) {
11433       ArgHasUses = true;
11434       break;
11435     }
11436   }
11437 }
11438 
LowerArguments(const Function & F)11439 void SelectionDAGISel::LowerArguments(const Function &F) {
11440   SelectionDAG &DAG = SDB->DAG;
11441   SDLoc dl = SDB->getCurSDLoc();
11442   const DataLayout &DL = DAG.getDataLayout();
11443   SmallVector<ISD::InputArg, 16> Ins;
11444 
11445   // In Naked functions we aren't going to save any registers.
11446   if (F.hasFnAttribute(Attribute::Naked))
11447     return;
11448 
11449   if (!FuncInfo->CanLowerReturn) {
11450     // Put in an sret pointer parameter before all the other parameters.
11451     SmallVector<EVT, 1> ValueVTs;
11452     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11453                     PointerType::get(F.getContext(),
11454                                      DAG.getDataLayout().getAllocaAddrSpace()),
11455                     ValueVTs);
11456 
11457     // NOTE: Assuming that a pointer will never break down to more than one VT
11458     // or one register.
11459     ISD::ArgFlagsTy Flags;
11460     Flags.setSRet();
11461     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
11462     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
11463                          ISD::InputArg::NoArgIndex, 0);
11464     Ins.push_back(RetArg);
11465   }
11466 
11467   // Look for stores of arguments to static allocas. Mark such arguments with a
11468   // flag to ask the target to give us the memory location of that argument if
11469   // available.
11470   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11471   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11472                                     ArgCopyElisionCandidates);
11473 
11474   // Set up the incoming argument description vector.
11475   for (const Argument &Arg : F.args()) {
11476     unsigned ArgNo = Arg.getArgNo();
11477     SmallVector<EVT, 4> ValueVTs;
11478     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11479     bool isArgValueUsed = !Arg.use_empty();
11480     unsigned PartBase = 0;
11481     Type *FinalType = Arg.getType();
11482     if (Arg.hasAttribute(Attribute::ByVal))
11483       FinalType = Arg.getParamByValType();
11484     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11485         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11486     for (unsigned Value = 0, NumValues = ValueVTs.size();
11487          Value != NumValues; ++Value) {
11488       EVT VT = ValueVTs[Value];
11489       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11490       ISD::ArgFlagsTy Flags;
11491 
11492 
11493       if (Arg.getType()->isPointerTy()) {
11494         Flags.setPointer();
11495         Flags.setPointerAddrSpace(
11496             cast<PointerType>(Arg.getType())->getAddressSpace());
11497       }
11498       if (Arg.hasAttribute(Attribute::ZExt))
11499         Flags.setZExt();
11500       if (Arg.hasAttribute(Attribute::SExt))
11501         Flags.setSExt();
11502       if (Arg.hasAttribute(Attribute::InReg)) {
11503         // If we are using vectorcall calling convention, a structure that is
11504         // passed InReg - is surely an HVA
11505         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11506             isa<StructType>(Arg.getType())) {
11507           // The first value of a structure is marked
11508           if (0 == Value)
11509             Flags.setHvaStart();
11510           Flags.setHva();
11511         }
11512         // Set InReg Flag
11513         Flags.setInReg();
11514       }
11515       if (Arg.hasAttribute(Attribute::StructRet))
11516         Flags.setSRet();
11517       if (Arg.hasAttribute(Attribute::SwiftSelf))
11518         Flags.setSwiftSelf();
11519       if (Arg.hasAttribute(Attribute::SwiftAsync))
11520         Flags.setSwiftAsync();
11521       if (Arg.hasAttribute(Attribute::SwiftError))
11522         Flags.setSwiftError();
11523       if (Arg.hasAttribute(Attribute::ByVal))
11524         Flags.setByVal();
11525       if (Arg.hasAttribute(Attribute::ByRef))
11526         Flags.setByRef();
11527       if (Arg.hasAttribute(Attribute::InAlloca)) {
11528         Flags.setInAlloca();
11529         // Set the byval flag for CCAssignFn callbacks that don't know about
11530         // inalloca.  This way we can know how many bytes we should've allocated
11531         // and how many bytes a callee cleanup function will pop.  If we port
11532         // inalloca to more targets, we'll have to add custom inalloca handling
11533         // in the various CC lowering callbacks.
11534         Flags.setByVal();
11535       }
11536       if (Arg.hasAttribute(Attribute::Preallocated)) {
11537         Flags.setPreallocated();
11538         // Set the byval flag for CCAssignFn callbacks that don't know about
11539         // preallocated.  This way we can know how many bytes we should've
11540         // allocated and how many bytes a callee cleanup function will pop.  If
11541         // we port preallocated to more targets, we'll have to add custom
11542         // preallocated handling in the various CC lowering callbacks.
11543         Flags.setByVal();
11544       }
11545 
11546       // Certain targets (such as MIPS), may have a different ABI alignment
11547       // for a type depending on the context. Give the target a chance to
11548       // specify the alignment it wants.
11549       const Align OriginalAlignment(
11550           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11551       Flags.setOrigAlign(OriginalAlignment);
11552 
11553       Align MemAlign;
11554       Type *ArgMemTy = nullptr;
11555       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11556           Flags.isByRef()) {
11557         if (!ArgMemTy)
11558           ArgMemTy = Arg.getPointeeInMemoryValueType();
11559 
11560         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11561 
11562         // For in-memory arguments, size and alignment should be passed from FE.
11563         // BE will guess if this info is not there but there are cases it cannot
11564         // get right.
11565         if (auto ParamAlign = Arg.getParamStackAlign())
11566           MemAlign = *ParamAlign;
11567         else if ((ParamAlign = Arg.getParamAlign()))
11568           MemAlign = *ParamAlign;
11569         else
11570           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11571         if (Flags.isByRef())
11572           Flags.setByRefSize(MemSize);
11573         else
11574           Flags.setByValSize(MemSize);
11575       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11576         MemAlign = *ParamAlign;
11577       } else {
11578         MemAlign = OriginalAlignment;
11579       }
11580       Flags.setMemAlign(MemAlign);
11581 
11582       if (Arg.hasAttribute(Attribute::Nest))
11583         Flags.setNest();
11584       if (NeedsRegBlock)
11585         Flags.setInConsecutiveRegs();
11586       if (ArgCopyElisionCandidates.count(&Arg))
11587         Flags.setCopyElisionCandidate();
11588       if (Arg.hasAttribute(Attribute::Returned))
11589         Flags.setReturned();
11590 
11591       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11592           *CurDAG->getContext(), F.getCallingConv(), VT);
11593       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11594           *CurDAG->getContext(), F.getCallingConv(), VT);
11595       for (unsigned i = 0; i != NumRegs; ++i) {
11596         // For scalable vectors, use the minimum size; individual targets
11597         // are responsible for handling scalable vector arguments and
11598         // return values.
11599         ISD::InputArg MyFlags(
11600             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11601             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11602         if (NumRegs > 1 && i == 0)
11603           MyFlags.Flags.setSplit();
11604         // if it isn't first piece, alignment must be 1
11605         else if (i > 0) {
11606           MyFlags.Flags.setOrigAlign(Align(1));
11607           if (i == NumRegs - 1)
11608             MyFlags.Flags.setSplitEnd();
11609         }
11610         Ins.push_back(MyFlags);
11611       }
11612       if (NeedsRegBlock && Value == NumValues - 1)
11613         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11614       PartBase += VT.getStoreSize().getKnownMinValue();
11615     }
11616   }
11617 
11618   // Call the target to set up the argument values.
11619   SmallVector<SDValue, 8> InVals;
11620   SDValue NewRoot = TLI->LowerFormalArguments(
11621       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11622 
11623   // Verify that the target's LowerFormalArguments behaved as expected.
11624   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11625          "LowerFormalArguments didn't return a valid chain!");
11626   assert(InVals.size() == Ins.size() &&
11627          "LowerFormalArguments didn't emit the correct number of values!");
11628   LLVM_DEBUG({
11629     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11630       assert(InVals[i].getNode() &&
11631              "LowerFormalArguments emitted a null value!");
11632       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11633              "LowerFormalArguments emitted a value with the wrong type!");
11634     }
11635   });
11636 
11637   // Update the DAG with the new chain value resulting from argument lowering.
11638   DAG.setRoot(NewRoot);
11639 
11640   // Set up the argument values.
11641   unsigned i = 0;
11642   if (!FuncInfo->CanLowerReturn) {
11643     // Create a virtual register for the sret pointer, and put in a copy
11644     // from the sret argument into it.
11645     SmallVector<EVT, 1> ValueVTs;
11646     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11647                     PointerType::get(F.getContext(),
11648                                      DAG.getDataLayout().getAllocaAddrSpace()),
11649                     ValueVTs);
11650     MVT VT = ValueVTs[0].getSimpleVT();
11651     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11652     std::optional<ISD::NodeType> AssertOp;
11653     SDValue ArgValue =
11654         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11655                          F.getCallingConv(), AssertOp);
11656 
11657     MachineFunction& MF = SDB->DAG.getMachineFunction();
11658     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11659     Register SRetReg =
11660         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11661     FuncInfo->DemoteRegister = SRetReg;
11662     NewRoot =
11663         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11664     DAG.setRoot(NewRoot);
11665 
11666     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11667     ++i;
11668   }
11669 
11670   SmallVector<SDValue, 4> Chains;
11671   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11672   for (const Argument &Arg : F.args()) {
11673     SmallVector<SDValue, 4> ArgValues;
11674     SmallVector<EVT, 4> ValueVTs;
11675     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11676     unsigned NumValues = ValueVTs.size();
11677     if (NumValues == 0)
11678       continue;
11679 
11680     bool ArgHasUses = !Arg.use_empty();
11681 
11682     // Elide the copying store if the target loaded this argument from a
11683     // suitable fixed stack object.
11684     if (Ins[i].Flags.isCopyElisionCandidate()) {
11685       unsigned NumParts = 0;
11686       for (EVT VT : ValueVTs)
11687         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11688                                                        F.getCallingConv(), VT);
11689 
11690       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11691                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11692                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11693     }
11694 
11695     // If this argument is unused then remember its value. It is used to generate
11696     // debugging information.
11697     bool isSwiftErrorArg =
11698         TLI->supportSwiftError() &&
11699         Arg.hasAttribute(Attribute::SwiftError);
11700     if (!ArgHasUses && !isSwiftErrorArg) {
11701       SDB->setUnusedArgValue(&Arg, InVals[i]);
11702 
11703       // Also remember any frame index for use in FastISel.
11704       if (FrameIndexSDNode *FI =
11705           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11706         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11707     }
11708 
11709     for (unsigned Val = 0; Val != NumValues; ++Val) {
11710       EVT VT = ValueVTs[Val];
11711       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11712                                                       F.getCallingConv(), VT);
11713       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11714           *CurDAG->getContext(), F.getCallingConv(), VT);
11715 
11716       // Even an apparent 'unused' swifterror argument needs to be returned. So
11717       // we do generate a copy for it that can be used on return from the
11718       // function.
11719       if (ArgHasUses || isSwiftErrorArg) {
11720         std::optional<ISD::NodeType> AssertOp;
11721         if (Arg.hasAttribute(Attribute::SExt))
11722           AssertOp = ISD::AssertSext;
11723         else if (Arg.hasAttribute(Attribute::ZExt))
11724           AssertOp = ISD::AssertZext;
11725 
11726         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11727                                              PartVT, VT, nullptr, NewRoot,
11728                                              F.getCallingConv(), AssertOp));
11729       }
11730 
11731       i += NumParts;
11732     }
11733 
11734     // We don't need to do anything else for unused arguments.
11735     if (ArgValues.empty())
11736       continue;
11737 
11738     // Note down frame index.
11739     if (FrameIndexSDNode *FI =
11740         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11741       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11742 
11743     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11744                                      SDB->getCurSDLoc());
11745 
11746     SDB->setValue(&Arg, Res);
11747     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11748       // We want to associate the argument with the frame index, among
11749       // involved operands, that correspond to the lowest address. The
11750       // getCopyFromParts function, called earlier, is swapping the order of
11751       // the operands to BUILD_PAIR depending on endianness. The result of
11752       // that swapping is that the least significant bits of the argument will
11753       // be in the first operand of the BUILD_PAIR node, and the most
11754       // significant bits will be in the second operand.
11755       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11756       if (LoadSDNode *LNode =
11757           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11758         if (FrameIndexSDNode *FI =
11759             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11760           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11761     }
11762 
11763     // Analyses past this point are naive and don't expect an assertion.
11764     if (Res.getOpcode() == ISD::AssertZext)
11765       Res = Res.getOperand(0);
11766 
11767     // Update the SwiftErrorVRegDefMap.
11768     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11769       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11770       if (Register::isVirtualRegister(Reg))
11771         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11772                                    Reg);
11773     }
11774 
11775     // If this argument is live outside of the entry block, insert a copy from
11776     // wherever we got it to the vreg that other BB's will reference it as.
11777     if (Res.getOpcode() == ISD::CopyFromReg) {
11778       // If we can, though, try to skip creating an unnecessary vreg.
11779       // FIXME: This isn't very clean... it would be nice to make this more
11780       // general.
11781       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11782       if (Register::isVirtualRegister(Reg)) {
11783         FuncInfo->ValueMap[&Arg] = Reg;
11784         continue;
11785       }
11786     }
11787     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11788       FuncInfo->InitializeRegForValue(&Arg);
11789       SDB->CopyToExportRegsIfNeeded(&Arg);
11790     }
11791   }
11792 
11793   if (!Chains.empty()) {
11794     Chains.push_back(NewRoot);
11795     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11796   }
11797 
11798   DAG.setRoot(NewRoot);
11799 
11800   assert(i == InVals.size() && "Argument register count mismatch!");
11801 
11802   // If any argument copy elisions occurred and we have debug info, update the
11803   // stale frame indices used in the dbg.declare variable info table.
11804   if (!ArgCopyElisionFrameIndexMap.empty()) {
11805     for (MachineFunction::VariableDbgInfo &VI :
11806          MF->getInStackSlotVariableDbgInfo()) {
11807       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11808       if (I != ArgCopyElisionFrameIndexMap.end())
11809         VI.updateStackSlot(I->second);
11810     }
11811   }
11812 
11813   // Finally, if the target has anything special to do, allow it to do so.
11814   emitFunctionEntryCode();
11815 }
11816 
11817 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11818 /// ensure constants are generated when needed.  Remember the virtual registers
11819 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11820 /// directly add them, because expansion might result in multiple MBB's for one
11821 /// BB.  As such, the start of the BB might correspond to a different MBB than
11822 /// the end.
11823 void
HandlePHINodesInSuccessorBlocks(const BasicBlock * LLVMBB)11824 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11825   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11826 
11827   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11828 
11829   // Check PHI nodes in successors that expect a value to be available from this
11830   // block.
11831   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11832     if (!isa<PHINode>(SuccBB->begin())) continue;
11833     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11834 
11835     // If this terminator has multiple identical successors (common for
11836     // switches), only handle each succ once.
11837     if (!SuccsHandled.insert(SuccMBB).second)
11838       continue;
11839 
11840     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11841 
11842     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11843     // nodes and Machine PHI nodes, but the incoming operands have not been
11844     // emitted yet.
11845     for (const PHINode &PN : SuccBB->phis()) {
11846       // Ignore dead phi's.
11847       if (PN.use_empty())
11848         continue;
11849 
11850       // Skip empty types
11851       if (PN.getType()->isEmptyTy())
11852         continue;
11853 
11854       unsigned Reg;
11855       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11856 
11857       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11858         unsigned &RegOut = ConstantsOut[C];
11859         if (RegOut == 0) {
11860           RegOut = FuncInfo.CreateRegs(C);
11861           // We need to zero/sign extend ConstantInt phi operands to match
11862           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11863           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11864           if (auto *CI = dyn_cast<ConstantInt>(C))
11865             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11866                                                     : ISD::ZERO_EXTEND;
11867           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11868         }
11869         Reg = RegOut;
11870       } else {
11871         DenseMap<const Value *, Register>::iterator I =
11872           FuncInfo.ValueMap.find(PHIOp);
11873         if (I != FuncInfo.ValueMap.end())
11874           Reg = I->second;
11875         else {
11876           assert(isa<AllocaInst>(PHIOp) &&
11877                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11878                  "Didn't codegen value into a register!??");
11879           Reg = FuncInfo.CreateRegs(PHIOp);
11880           CopyValueToVirtualRegister(PHIOp, Reg);
11881         }
11882       }
11883 
11884       // Remember that this register needs to added to the machine PHI node as
11885       // the input for this MBB.
11886       SmallVector<EVT, 4> ValueVTs;
11887       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11888       for (EVT VT : ValueVTs) {
11889         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11890         for (unsigned i = 0; i != NumRegisters; ++i)
11891           FuncInfo.PHINodesToUpdate.push_back(
11892               std::make_pair(&*MBBI++, Reg + i));
11893         Reg += NumRegisters;
11894       }
11895     }
11896   }
11897 
11898   ConstantsOut.clear();
11899 }
11900 
NextBlock(MachineBasicBlock * MBB)11901 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11902   MachineFunction::iterator I(MBB);
11903   if (++I == FuncInfo.MF->end())
11904     return nullptr;
11905   return &*I;
11906 }
11907 
11908 /// During lowering new call nodes can be created (such as memset, etc.).
11909 /// Those will become new roots of the current DAG, but complications arise
11910 /// when they are tail calls. In such cases, the call lowering will update
11911 /// the root, but the builder still needs to know that a tail call has been
11912 /// lowered in order to avoid generating an additional return.
updateDAGForMaybeTailCall(SDValue MaybeTC)11913 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11914   // If the node is null, we do have a tail call.
11915   if (MaybeTC.getNode() != nullptr)
11916     DAG.setRoot(MaybeTC);
11917   else
11918     HasTailCall = true;
11919 }
11920 
lowerWorkItem(SwitchWorkListItem W,Value * Cond,MachineBasicBlock * SwitchMBB,MachineBasicBlock * DefaultMBB)11921 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11922                                         MachineBasicBlock *SwitchMBB,
11923                                         MachineBasicBlock *DefaultMBB) {
11924   MachineFunction *CurMF = FuncInfo.MF;
11925   MachineBasicBlock *NextMBB = nullptr;
11926   MachineFunction::iterator BBI(W.MBB);
11927   if (++BBI != FuncInfo.MF->end())
11928     NextMBB = &*BBI;
11929 
11930   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11931 
11932   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11933 
11934   if (Size == 2 && W.MBB == SwitchMBB) {
11935     // If any two of the cases has the same destination, and if one value
11936     // is the same as the other, but has one bit unset that the other has set,
11937     // use bit manipulation to do two compares at once.  For example:
11938     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11939     // TODO: This could be extended to merge any 2 cases in switches with 3
11940     // cases.
11941     // TODO: Handle cases where W.CaseBB != SwitchBB.
11942     CaseCluster &Small = *W.FirstCluster;
11943     CaseCluster &Big = *W.LastCluster;
11944 
11945     if (Small.Low == Small.High && Big.Low == Big.High &&
11946         Small.MBB == Big.MBB) {
11947       const APInt &SmallValue = Small.Low->getValue();
11948       const APInt &BigValue = Big.Low->getValue();
11949 
11950       // Check that there is only one bit different.
11951       APInt CommonBit = BigValue ^ SmallValue;
11952       if (CommonBit.isPowerOf2()) {
11953         SDValue CondLHS = getValue(Cond);
11954         EVT VT = CondLHS.getValueType();
11955         SDLoc DL = getCurSDLoc();
11956 
11957         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11958                                  DAG.getConstant(CommonBit, DL, VT));
11959         SDValue Cond = DAG.getSetCC(
11960             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11961             ISD::SETEQ);
11962 
11963         // Update successor info.
11964         // Both Small and Big will jump to Small.BB, so we sum up the
11965         // probabilities.
11966         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11967         if (BPI)
11968           addSuccessorWithProb(
11969               SwitchMBB, DefaultMBB,
11970               // The default destination is the first successor in IR.
11971               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11972         else
11973           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11974 
11975         // Insert the true branch.
11976         SDValue BrCond =
11977             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11978                         DAG.getBasicBlock(Small.MBB));
11979         // Insert the false branch.
11980         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11981                              DAG.getBasicBlock(DefaultMBB));
11982 
11983         DAG.setRoot(BrCond);
11984         return;
11985       }
11986     }
11987   }
11988 
11989   if (TM.getOptLevel() != CodeGenOptLevel::None) {
11990     // Here, we order cases by probability so the most likely case will be
11991     // checked first. However, two clusters can have the same probability in
11992     // which case their relative ordering is non-deterministic. So we use Low
11993     // as a tie-breaker as clusters are guaranteed to never overlap.
11994     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11995                [](const CaseCluster &a, const CaseCluster &b) {
11996       return a.Prob != b.Prob ?
11997              a.Prob > b.Prob :
11998              a.Low->getValue().slt(b.Low->getValue());
11999     });
12000 
12001     // Rearrange the case blocks so that the last one falls through if possible
12002     // without changing the order of probabilities.
12003     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12004       --I;
12005       if (I->Prob > W.LastCluster->Prob)
12006         break;
12007       if (I->Kind == CC_Range && I->MBB == NextMBB) {
12008         std::swap(*I, *W.LastCluster);
12009         break;
12010       }
12011     }
12012   }
12013 
12014   // Compute total probability.
12015   BranchProbability DefaultProb = W.DefaultProb;
12016   BranchProbability UnhandledProbs = DefaultProb;
12017   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12018     UnhandledProbs += I->Prob;
12019 
12020   MachineBasicBlock *CurMBB = W.MBB;
12021   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12022     bool FallthroughUnreachable = false;
12023     MachineBasicBlock *Fallthrough;
12024     if (I == W.LastCluster) {
12025       // For the last cluster, fall through to the default destination.
12026       Fallthrough = DefaultMBB;
12027       FallthroughUnreachable = isa<UnreachableInst>(
12028           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12029     } else {
12030       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12031       CurMF->insert(BBI, Fallthrough);
12032       // Put Cond in a virtual register to make it available from the new blocks.
12033       ExportFromCurrentBlock(Cond);
12034     }
12035     UnhandledProbs -= I->Prob;
12036 
12037     switch (I->Kind) {
12038       case CC_JumpTable: {
12039         // FIXME: Optimize away range check based on pivot comparisons.
12040         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12041         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12042 
12043         // The jump block hasn't been inserted yet; insert it here.
12044         MachineBasicBlock *JumpMBB = JT->MBB;
12045         CurMF->insert(BBI, JumpMBB);
12046 
12047         auto JumpProb = I->Prob;
12048         auto FallthroughProb = UnhandledProbs;
12049 
12050         // If the default statement is a target of the jump table, we evenly
12051         // distribute the default probability to successors of CurMBB. Also
12052         // update the probability on the edge from JumpMBB to Fallthrough.
12053         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12054                                               SE = JumpMBB->succ_end();
12055              SI != SE; ++SI) {
12056           if (*SI == DefaultMBB) {
12057             JumpProb += DefaultProb / 2;
12058             FallthroughProb -= DefaultProb / 2;
12059             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12060             JumpMBB->normalizeSuccProbs();
12061             break;
12062           }
12063         }
12064 
12065         // If the default clause is unreachable, propagate that knowledge into
12066         // JTH->FallthroughUnreachable which will use it to suppress the range
12067         // check.
12068         //
12069         // However, don't do this if we're doing branch target enforcement,
12070         // because a table branch _without_ a range check can be a tempting JOP
12071         // gadget - out-of-bounds inputs that are impossible in correct
12072         // execution become possible again if an attacker can influence the
12073         // control flow. So if an attacker doesn't already have a BTI bypass
12074         // available, we don't want them to be able to get one out of this
12075         // table branch.
12076         if (FallthroughUnreachable) {
12077           Function &CurFunc = CurMF->getFunction();
12078           if (!CurFunc.hasFnAttribute("branch-target-enforcement"))
12079             JTH->FallthroughUnreachable = true;
12080         }
12081 
12082         if (!JTH->FallthroughUnreachable)
12083           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12084         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12085         CurMBB->normalizeSuccProbs();
12086 
12087         // The jump table header will be inserted in our current block, do the
12088         // range check, and fall through to our fallthrough block.
12089         JTH->HeaderBB = CurMBB;
12090         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12091 
12092         // If we're in the right place, emit the jump table header right now.
12093         if (CurMBB == SwitchMBB) {
12094           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12095           JTH->Emitted = true;
12096         }
12097         break;
12098       }
12099       case CC_BitTests: {
12100         // FIXME: Optimize away range check based on pivot comparisons.
12101         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12102 
12103         // The bit test blocks haven't been inserted yet; insert them here.
12104         for (BitTestCase &BTC : BTB->Cases)
12105           CurMF->insert(BBI, BTC.ThisBB);
12106 
12107         // Fill in fields of the BitTestBlock.
12108         BTB->Parent = CurMBB;
12109         BTB->Default = Fallthrough;
12110 
12111         BTB->DefaultProb = UnhandledProbs;
12112         // If the cases in bit test don't form a contiguous range, we evenly
12113         // distribute the probability on the edge to Fallthrough to two
12114         // successors of CurMBB.
12115         if (!BTB->ContiguousRange) {
12116           BTB->Prob += DefaultProb / 2;
12117           BTB->DefaultProb -= DefaultProb / 2;
12118         }
12119 
12120         if (FallthroughUnreachable)
12121           BTB->FallthroughUnreachable = true;
12122 
12123         // If we're in the right place, emit the bit test header right now.
12124         if (CurMBB == SwitchMBB) {
12125           visitBitTestHeader(*BTB, SwitchMBB);
12126           BTB->Emitted = true;
12127         }
12128         break;
12129       }
12130       case CC_Range: {
12131         const Value *RHS, *LHS, *MHS;
12132         ISD::CondCode CC;
12133         if (I->Low == I->High) {
12134           // Check Cond == I->Low.
12135           CC = ISD::SETEQ;
12136           LHS = Cond;
12137           RHS=I->Low;
12138           MHS = nullptr;
12139         } else {
12140           // Check I->Low <= Cond <= I->High.
12141           CC = ISD::SETLE;
12142           LHS = I->Low;
12143           MHS = Cond;
12144           RHS = I->High;
12145         }
12146 
12147         // If Fallthrough is unreachable, fold away the comparison.
12148         if (FallthroughUnreachable)
12149           CC = ISD::SETTRUE;
12150 
12151         // The false probability is the sum of all unhandled cases.
12152         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12153                      getCurSDLoc(), I->Prob, UnhandledProbs);
12154 
12155         if (CurMBB == SwitchMBB)
12156           visitSwitchCase(CB, SwitchMBB);
12157         else
12158           SL->SwitchCases.push_back(CB);
12159 
12160         break;
12161       }
12162     }
12163     CurMBB = Fallthrough;
12164   }
12165 }
12166 
splitWorkItem(SwitchWorkList & WorkList,const SwitchWorkListItem & W,Value * Cond,MachineBasicBlock * SwitchMBB)12167 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12168                                         const SwitchWorkListItem &W,
12169                                         Value *Cond,
12170                                         MachineBasicBlock *SwitchMBB) {
12171   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12172          "Clusters not sorted?");
12173   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12174 
12175   auto [LastLeft, FirstRight, LeftProb, RightProb] =
12176       SL->computeSplitWorkItemInfo(W);
12177 
12178   // Use the first element on the right as pivot since we will make less-than
12179   // comparisons against it.
12180   CaseClusterIt PivotCluster = FirstRight;
12181   assert(PivotCluster > W.FirstCluster);
12182   assert(PivotCluster <= W.LastCluster);
12183 
12184   CaseClusterIt FirstLeft = W.FirstCluster;
12185   CaseClusterIt LastRight = W.LastCluster;
12186 
12187   const ConstantInt *Pivot = PivotCluster->Low;
12188 
12189   // New blocks will be inserted immediately after the current one.
12190   MachineFunction::iterator BBI(W.MBB);
12191   ++BBI;
12192 
12193   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12194   // we can branch to its destination directly if it's squeezed exactly in
12195   // between the known lower bound and Pivot - 1.
12196   MachineBasicBlock *LeftMBB;
12197   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12198       FirstLeft->Low == W.GE &&
12199       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12200     LeftMBB = FirstLeft->MBB;
12201   } else {
12202     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12203     FuncInfo.MF->insert(BBI, LeftMBB);
12204     WorkList.push_back(
12205         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12206     // Put Cond in a virtual register to make it available from the new blocks.
12207     ExportFromCurrentBlock(Cond);
12208   }
12209 
12210   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12211   // single cluster, RHS.Low == Pivot, and we can branch to its destination
12212   // directly if RHS.High equals the current upper bound.
12213   MachineBasicBlock *RightMBB;
12214   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12215       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12216     RightMBB = FirstRight->MBB;
12217   } else {
12218     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12219     FuncInfo.MF->insert(BBI, RightMBB);
12220     WorkList.push_back(
12221         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12222     // Put Cond in a virtual register to make it available from the new blocks.
12223     ExportFromCurrentBlock(Cond);
12224   }
12225 
12226   // Create the CaseBlock record that will be used to lower the branch.
12227   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12228                getCurSDLoc(), LeftProb, RightProb);
12229 
12230   if (W.MBB == SwitchMBB)
12231     visitSwitchCase(CB, SwitchMBB);
12232   else
12233     SL->SwitchCases.push_back(CB);
12234 }
12235 
12236 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12237 // from the swith statement.
scaleCaseProbality(BranchProbability CaseProb,BranchProbability PeeledCaseProb)12238 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12239                                             BranchProbability PeeledCaseProb) {
12240   if (PeeledCaseProb == BranchProbability::getOne())
12241     return BranchProbability::getZero();
12242   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12243 
12244   uint32_t Numerator = CaseProb.getNumerator();
12245   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12246   return BranchProbability(Numerator, std::max(Numerator, Denominator));
12247 }
12248 
12249 // Try to peel the top probability case if it exceeds the threshold.
12250 // Return current MachineBasicBlock for the switch statement if the peeling
12251 // does not occur.
12252 // If the peeling is performed, return the newly created MachineBasicBlock
12253 // for the peeled switch statement. Also update Clusters to remove the peeled
12254 // case. PeeledCaseProb is the BranchProbability for the peeled case.
peelDominantCaseCluster(const SwitchInst & SI,CaseClusterVector & Clusters,BranchProbability & PeeledCaseProb)12255 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12256     const SwitchInst &SI, CaseClusterVector &Clusters,
12257     BranchProbability &PeeledCaseProb) {
12258   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12259   // Don't perform if there is only one cluster or optimizing for size.
12260   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12261       TM.getOptLevel() == CodeGenOptLevel::None ||
12262       SwitchMBB->getParent()->getFunction().hasMinSize())
12263     return SwitchMBB;
12264 
12265   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12266   unsigned PeeledCaseIndex = 0;
12267   bool SwitchPeeled = false;
12268   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12269     CaseCluster &CC = Clusters[Index];
12270     if (CC.Prob < TopCaseProb)
12271       continue;
12272     TopCaseProb = CC.Prob;
12273     PeeledCaseIndex = Index;
12274     SwitchPeeled = true;
12275   }
12276   if (!SwitchPeeled)
12277     return SwitchMBB;
12278 
12279   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12280                     << TopCaseProb << "\n");
12281 
12282   // Record the MBB for the peeled switch statement.
12283   MachineFunction::iterator BBI(SwitchMBB);
12284   ++BBI;
12285   MachineBasicBlock *PeeledSwitchMBB =
12286       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12287   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12288 
12289   ExportFromCurrentBlock(SI.getCondition());
12290   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12291   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12292                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12293   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12294 
12295   Clusters.erase(PeeledCaseIt);
12296   for (CaseCluster &CC : Clusters) {
12297     LLVM_DEBUG(
12298         dbgs() << "Scale the probablity for one cluster, before scaling: "
12299                << CC.Prob << "\n");
12300     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12301     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12302   }
12303   PeeledCaseProb = TopCaseProb;
12304   return PeeledSwitchMBB;
12305 }
12306 
visitSwitch(const SwitchInst & SI)12307 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12308   // Extract cases from the switch.
12309   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12310   CaseClusterVector Clusters;
12311   Clusters.reserve(SI.getNumCases());
12312   for (auto I : SI.cases()) {
12313     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
12314     const ConstantInt *CaseVal = I.getCaseValue();
12315     BranchProbability Prob =
12316         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12317             : BranchProbability(1, SI.getNumCases() + 1);
12318     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12319   }
12320 
12321   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
12322 
12323   // Cluster adjacent cases with the same destination. We do this at all
12324   // optimization levels because it's cheap to do and will make codegen faster
12325   // if there are many clusters.
12326   sortAndRangeify(Clusters);
12327 
12328   // The branch probablity of the peeled case.
12329   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12330   MachineBasicBlock *PeeledSwitchMBB =
12331       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12332 
12333   // If there is only the default destination, jump there directly.
12334   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12335   if (Clusters.empty()) {
12336     assert(PeeledSwitchMBB == SwitchMBB);
12337     SwitchMBB->addSuccessor(DefaultMBB);
12338     if (DefaultMBB != NextBlock(SwitchMBB)) {
12339       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12340                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12341     }
12342     return;
12343   }
12344 
12345   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12346                      DAG.getBFI());
12347   SL->findBitTestClusters(Clusters, &SI);
12348 
12349   LLVM_DEBUG({
12350     dbgs() << "Case clusters: ";
12351     for (const CaseCluster &C : Clusters) {
12352       if (C.Kind == CC_JumpTable)
12353         dbgs() << "JT:";
12354       if (C.Kind == CC_BitTests)
12355         dbgs() << "BT:";
12356 
12357       C.Low->getValue().print(dbgs(), true);
12358       if (C.Low != C.High) {
12359         dbgs() << '-';
12360         C.High->getValue().print(dbgs(), true);
12361       }
12362       dbgs() << ' ';
12363     }
12364     dbgs() << '\n';
12365   });
12366 
12367   assert(!Clusters.empty());
12368   SwitchWorkList WorkList;
12369   CaseClusterIt First = Clusters.begin();
12370   CaseClusterIt Last = Clusters.end() - 1;
12371   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12372   // Scale the branchprobability for DefaultMBB if the peel occurs and
12373   // DefaultMBB is not replaced.
12374   if (PeeledCaseProb != BranchProbability::getZero() &&
12375       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
12376     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12377   WorkList.push_back(
12378       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12379 
12380   while (!WorkList.empty()) {
12381     SwitchWorkListItem W = WorkList.pop_back_val();
12382     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12383 
12384     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12385         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12386       // For optimized builds, lower large range as a balanced binary tree.
12387       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12388       continue;
12389     }
12390 
12391     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12392   }
12393 }
12394 
visitStepVector(const CallInst & I)12395 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12396   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12397   auto DL = getCurSDLoc();
12398   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12399   setValue(&I, DAG.getStepVector(DL, ResultVT));
12400 }
12401 
visitVectorReverse(const CallInst & I)12402 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12404   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12405 
12406   SDLoc DL = getCurSDLoc();
12407   SDValue V = getValue(I.getOperand(0));
12408   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12409 
12410   if (VT.isScalableVector()) {
12411     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12412     return;
12413   }
12414 
12415   // Use VECTOR_SHUFFLE for the fixed-length vector
12416   // to maintain existing behavior.
12417   SmallVector<int, 8> Mask;
12418   unsigned NumElts = VT.getVectorMinNumElements();
12419   for (unsigned i = 0; i != NumElts; ++i)
12420     Mask.push_back(NumElts - 1 - i);
12421 
12422   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12423 }
12424 
visitVectorDeinterleave(const CallInst & I)12425 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12426   auto DL = getCurSDLoc();
12427   SDValue InVec = getValue(I.getOperand(0));
12428   EVT OutVT =
12429       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12430 
12431   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12432 
12433   // ISD Node needs the input vectors split into two equal parts
12434   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12435                            DAG.getVectorIdxConstant(0, DL));
12436   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12437                            DAG.getVectorIdxConstant(OutNumElts, DL));
12438 
12439   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12440   // legalisation and combines.
12441   if (OutVT.isFixedLengthVector()) {
12442     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12443                                         createStrideMask(0, 2, OutNumElts));
12444     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12445                                        createStrideMask(1, 2, OutNumElts));
12446     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12447     setValue(&I, Res);
12448     return;
12449   }
12450 
12451   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12452                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12453   setValue(&I, Res);
12454 }
12455 
visitVectorInterleave(const CallInst & I)12456 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12457   auto DL = getCurSDLoc();
12458   EVT InVT = getValue(I.getOperand(0)).getValueType();
12459   SDValue InVec0 = getValue(I.getOperand(0));
12460   SDValue InVec1 = getValue(I.getOperand(1));
12461   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12462   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12463 
12464   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12465   // legalisation and combines.
12466   if (OutVT.isFixedLengthVector()) {
12467     unsigned NumElts = InVT.getVectorMinNumElements();
12468     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12469     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12470                                       createInterleaveMask(NumElts, 2)));
12471     return;
12472   }
12473 
12474   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12475                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12476   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12477                     Res.getValue(1));
12478   setValue(&I, Res);
12479 }
12480 
visitFreeze(const FreezeInst & I)12481 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12482   SmallVector<EVT, 4> ValueVTs;
12483   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12484                   ValueVTs);
12485   unsigned NumValues = ValueVTs.size();
12486   if (NumValues == 0) return;
12487 
12488   SmallVector<SDValue, 4> Values(NumValues);
12489   SDValue Op = getValue(I.getOperand(0));
12490 
12491   for (unsigned i = 0; i != NumValues; ++i)
12492     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12493                             SDValue(Op.getNode(), Op.getResNo() + i));
12494 
12495   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12496                            DAG.getVTList(ValueVTs), Values));
12497 }
12498 
visitVectorSplice(const CallInst & I)12499 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12500   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12501   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12502 
12503   SDLoc DL = getCurSDLoc();
12504   SDValue V1 = getValue(I.getOperand(0));
12505   SDValue V2 = getValue(I.getOperand(1));
12506   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12507 
12508   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12509   if (VT.isScalableVector()) {
12510     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12511                              DAG.getVectorIdxConstant(Imm, DL)));
12512     return;
12513   }
12514 
12515   unsigned NumElts = VT.getVectorNumElements();
12516 
12517   uint64_t Idx = (NumElts + Imm) % NumElts;
12518 
12519   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12520   SmallVector<int, 8> Mask;
12521   for (unsigned i = 0; i < NumElts; ++i)
12522     Mask.push_back(Idx + i);
12523   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12524 }
12525 
12526 // Consider the following MIR after SelectionDAG, which produces output in
12527 // phyregs in the first case or virtregs in the second case.
12528 //
12529 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12530 // %5:gr32 = COPY $ebx
12531 // %6:gr32 = COPY $edx
12532 // %1:gr32 = COPY %6:gr32
12533 // %0:gr32 = COPY %5:gr32
12534 //
12535 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12536 // %1:gr32 = COPY %6:gr32
12537 // %0:gr32 = COPY %5:gr32
12538 //
12539 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12540 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12541 //
12542 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12543 // to a single virtreg (such as %0). The remaining outputs monotonically
12544 // increase in virtreg number from there. If a callbr has no outputs, then it
12545 // should not have a corresponding callbr landingpad; in fact, the callbr
12546 // landingpad would not even be able to refer to such a callbr.
FollowCopyChain(MachineRegisterInfo & MRI,Register Reg)12547 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12548   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12549   // There is definitely at least one copy.
12550   assert(MI->getOpcode() == TargetOpcode::COPY &&
12551          "start of copy chain MUST be COPY");
12552   Reg = MI->getOperand(1).getReg();
12553   MI = MRI.def_begin(Reg)->getParent();
12554   // There may be an optional second copy.
12555   if (MI->getOpcode() == TargetOpcode::COPY) {
12556     assert(Reg.isVirtual() && "expected COPY of virtual register");
12557     Reg = MI->getOperand(1).getReg();
12558     assert(Reg.isPhysical() && "expected COPY of physical register");
12559     MI = MRI.def_begin(Reg)->getParent();
12560   }
12561   // The start of the chain must be an INLINEASM_BR.
12562   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12563          "end of copy chain MUST be INLINEASM_BR");
12564   return Reg;
12565 }
12566 
12567 // We must do this walk rather than the simpler
12568 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12569 // otherwise we will end up with copies of virtregs only valid along direct
12570 // edges.
visitCallBrLandingPad(const CallInst & I)12571 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12572   SmallVector<EVT, 8> ResultVTs;
12573   SmallVector<SDValue, 8> ResultValues;
12574   const auto *CBR =
12575       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12576 
12577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12578   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12579   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12580 
12581   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12582   SDValue Chain = DAG.getRoot();
12583 
12584   // Re-parse the asm constraints string.
12585   TargetLowering::AsmOperandInfoVector TargetConstraints =
12586       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12587   for (auto &T : TargetConstraints) {
12588     SDISelAsmOperandInfo OpInfo(T);
12589     if (OpInfo.Type != InlineAsm::isOutput)
12590       continue;
12591 
12592     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12593     // individual constraint.
12594     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12595 
12596     switch (OpInfo.ConstraintType) {
12597     case TargetLowering::C_Register:
12598     case TargetLowering::C_RegisterClass: {
12599       // Fill in OpInfo.AssignedRegs.Regs.
12600       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12601 
12602       // getRegistersForValue may produce 1 to many registers based on whether
12603       // the OpInfo.ConstraintVT is legal on the target or not.
12604       for (unsigned &Reg : OpInfo.AssignedRegs.Regs) {
12605         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12606         if (Register::isPhysicalRegister(OriginalDef))
12607           FuncInfo.MBB->addLiveIn(OriginalDef);
12608         // Update the assigned registers to use the original defs.
12609         Reg = OriginalDef;
12610       }
12611 
12612       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12613           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12614       ResultValues.push_back(V);
12615       ResultVTs.push_back(OpInfo.ConstraintVT);
12616       break;
12617     }
12618     case TargetLowering::C_Other: {
12619       SDValue Flag;
12620       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12621                                                   OpInfo, DAG);
12622       ++InitialDef;
12623       ResultValues.push_back(V);
12624       ResultVTs.push_back(OpInfo.ConstraintVT);
12625       break;
12626     }
12627     default:
12628       break;
12629     }
12630   }
12631   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12632                           DAG.getVTList(ResultVTs), ResultValues);
12633   setValue(&I, V);
12634 }
12635