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/StringExtras.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/SelectionDAG.h"
48#include "llvm/CodeGen/SelectionDAGNodes.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/TargetMachine.h"
102#include "llvm/Target/TargetOptions.h"
103#include "llvm/TargetParser/Triple.h"
104#include "llvm/Transforms/Utils/Local.h"
105#include <cstddef>
106#include <limits>
107#include <optional>
108#include <tuple>
109
110using namespace llvm;
111using namespace PatternMatch;
112using namespace SwitchCG;
113
114#define DEBUG_TYPE "isel"
115
116/// LimitFloatPrecision - Generate low-precision inline sequences for
117/// some float libcalls (6, 8 or 12 bits).
118static unsigned LimitFloatPrecision;
119
120static cl::opt<bool>
121 InsertAssertAlign("insert-assert-align", cl::init(Val: true),
122 cl::desc("Insert the experimental `assertalign` node."),
123 cl::ReallyHidden);
124
125static cl::opt<unsigned, true>
126 LimitFPPrecision("limit-float-precision",
127 cl::desc("Generate low-precision inline sequences "
128 "for some float libcalls"),
129 cl::location(L&: LimitFloatPrecision), cl::Hidden,
130 cl::init(Val: 0));
131
132static cl::opt<unsigned> SwitchPeelThreshold(
133 "switch-peel-threshold", cl::Hidden, cl::init(Val: 66),
134 cl::desc("Set the case probability threshold for peeling the case from a "
135 "switch statement. A value greater than 100 will void this "
136 "optimization"));
137
138// Limit the width of DAG chains. This is important in general to prevent
139// DAG-based analysis from blowing up. For example, alias analysis and
140// load clustering may not complete in reasonable time. It is difficult to
141// recognize and avoid this situation within each individual analysis, and
142// future analyses are likely to have the same behavior. Limiting DAG width is
143// the safe approach and will be especially important with global DAGs.
144//
145// MaxParallelChains default is arbitrarily high to avoid affecting
146// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
147// sequence over this should have been converted to llvm.memcpy by the
148// frontend. It is easy to induce this behavior with .ll code such as:
149// %buffer = alloca [4096 x i8]
150// %data = load [4096 x i8]* %argPtr
151// store [4096 x i8] %data, [4096 x i8]* %buffer
152static const unsigned MaxParallelChains = 64;
153
154static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
155 const SDValue *Parts, unsigned NumParts,
156 MVT PartVT, EVT ValueVT, const Value *V,
157 SDValue InChain,
158 std::optional<CallingConv::ID> CC);
159
160/// getCopyFromParts - Create a value that contains the specified legal parts
161/// combined into the value they represent. If the parts combine to a type
162/// larger than ValueVT then AssertOp can be used to specify whether the extra
163/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
164/// (ISD::AssertSext).
165static SDValue
166getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
167 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
168 SDValue InChain,
169 std::optional<CallingConv::ID> CC = std::nullopt,
170 std::optional<ISD::NodeType> AssertOp = std::nullopt) {
171 // Let the target assemble the parts if it wants to
172 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
173 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
174 PartVT, ValueVT, CC))
175 return Val;
176
177 if (ValueVT.isVector())
178 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
179 InChain, CC);
180
181 assert(NumParts > 0 && "No parts to assemble!");
182 SDValue Val = Parts[0];
183
184 if (NumParts > 1) {
185 // Assemble the value from multiple parts.
186 if (ValueVT.isInteger()) {
187 unsigned PartBits = PartVT.getSizeInBits();
188 unsigned ValueBits = ValueVT.getSizeInBits();
189
190 // Assemble the power of 2 part.
191 unsigned RoundParts = llvm::bit_floor(Value: NumParts);
192 unsigned RoundBits = PartBits * RoundParts;
193 EVT RoundVT = RoundBits == ValueBits ?
194 ValueVT : EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: RoundBits);
195 SDValue Lo, Hi;
196
197 EVT HalfVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: RoundBits/2);
198
199 if (RoundParts > 2) {
200 Lo = getCopyFromParts(DAG, DL, Parts, NumParts: RoundParts / 2, PartVT, ValueVT: HalfVT, V,
201 InChain);
202 Hi = getCopyFromParts(DAG, DL, Parts: Parts + RoundParts / 2, NumParts: RoundParts / 2,
203 PartVT, ValueVT: HalfVT, V, InChain);
204 } else {
205 Lo = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: HalfVT, Operand: Parts[0]);
206 Hi = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: HalfVT, Operand: Parts[1]);
207 }
208
209 if (DAG.getDataLayout().isBigEndian())
210 std::swap(a&: Lo, b&: Hi);
211
212 Val = DAG.getNode(Opcode: ISD::BUILD_PAIR, DL, VT: RoundVT, N1: Lo, N2: Hi);
213
214 if (RoundParts < NumParts) {
215 // Assemble the trailing non-power-of-2 part.
216 unsigned OddParts = NumParts - RoundParts;
217 EVT OddVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: OddParts * PartBits);
218 Hi = getCopyFromParts(DAG, DL, Parts: Parts + RoundParts, NumParts: OddParts, PartVT,
219 ValueVT: OddVT, V, InChain, CC);
220
221 // Combine the round and odd parts.
222 Lo = Val;
223 if (DAG.getDataLayout().isBigEndian())
224 std::swap(a&: Lo, b&: Hi);
225 EVT TotalVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: NumParts * PartBits);
226 Hi = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: TotalVT, Operand: Hi);
227 Hi = DAG.getNode(
228 Opcode: ISD::SHL, DL, VT: TotalVT, N1: Hi,
229 N2: DAG.getShiftAmountConstant(Val: Lo.getValueSizeInBits(), VT: TotalVT, DL));
230 Lo = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL, VT: TotalVT, Operand: Lo);
231 Val = DAG.getNode(Opcode: ISD::OR, DL, VT: TotalVT, N1: Lo, N2: Hi);
232 }
233 } else if (PartVT.isFloatingPoint()) {
234 // FP split into multiple FP parts (for ppcf128)
235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
236 "Unexpected split");
237 SDValue Lo, Hi;
238 Lo = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: EVT(MVT::f64), Operand: Parts[0]);
239 Hi = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: EVT(MVT::f64), Operand: Parts[1]);
240 if (TLI.hasBigEndianPartOrdering(VT: ValueVT, DL: DAG.getDataLayout()))
241 std::swap(a&: Lo, b&: Hi);
242 Val = DAG.getNode(Opcode: ISD::BUILD_PAIR, DL, VT: ValueVT, N1: Lo, N2: Hi);
243 } else {
244 // FP split into integer parts (soft fp)
245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
246 !PartVT.isVector() && "Unexpected split");
247 EVT IntVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueVT.getSizeInBits());
248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, ValueVT: IntVT, V,
249 InChain, CC);
250 }
251 }
252
253 // There is now one part, held in Val. Correct it to match ValueVT.
254 // PartEVT is the type of the register class that holds the value.
255 // ValueVT is the type of the inline asm operation.
256 EVT PartEVT = Val.getValueType();
257
258 if (PartEVT == ValueVT)
259 return Val;
260
261 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
262 ValueVT.bitsLT(VT: PartEVT)) {
263 // For an FP value in an integer part, we need to truncate to the right
264 // width first.
265 PartEVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueVT.getSizeInBits());
266 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: PartEVT, Operand: Val);
267 }
268
269 // Handle types that have the same size.
270 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
271 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
272
273 // Handle types with different sizes.
274 if (PartEVT.isInteger() && ValueVT.isInteger()) {
275 if (ValueVT.bitsLT(VT: PartEVT)) {
276 // For a truncate, see if we have any information to
277 // indicate whether the truncated bits will always be
278 // zero or sign-extension.
279 if (AssertOp)
280 Val = DAG.getNode(Opcode: *AssertOp, DL, VT: PartEVT, N1: Val,
281 N2: DAG.getValueType(ValueVT));
282 return DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: ValueVT, Operand: Val);
283 }
284 return DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: ValueVT, Operand: Val);
285 }
286
287 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
288 // FP_ROUND's are always exact here.
289 if (ValueVT.bitsLT(VT: Val.getValueType())) {
290
291 SDValue NoChange =
292 DAG.getTargetConstant(Val: 1, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
293
294 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
295 Kind: llvm::Attribute::StrictFP)) {
296 return DAG.getNode(Opcode: ISD::STRICT_FP_ROUND, DL,
297 VTList: DAG.getVTList(VT1: ValueVT, VT2: MVT::Other), N1: InChain, N2: Val,
298 N3: NoChange);
299 }
300
301 return DAG.getNode(Opcode: ISD::FP_ROUND, DL, VT: ValueVT, N1: Val, N2: NoChange);
302 }
303
304 return DAG.getNode(Opcode: ISD::FP_EXTEND, DL, VT: ValueVT, Operand: Val);
305 }
306
307 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
308 // then truncating.
309 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
310 ValueVT.bitsLT(VT: PartEVT)) {
311 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::i64, Operand: Val);
312 return DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: ValueVT, Operand: Val);
313 }
314
315 report_fatal_error(reason: "Unknown mismatch in getCopyFromParts!");
316}
317
318static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
319 const Twine &ErrMsg) {
320 const Instruction *I = dyn_cast_or_null<Instruction>(Val: V);
321 if (!I)
322 return Ctx.emitError(ErrorStr: ErrMsg);
323
324 if (const CallInst *CI = dyn_cast<CallInst>(Val: I))
325 if (CI->isInlineAsm()) {
326 return Ctx.diagnose(DI: DiagnosticInfoInlineAsm(
327 *CI, ErrMsg + ", possible invalid constraint for vector type"));
328 }
329
330 return Ctx.emitError(I, ErrorStr: ErrMsg);
331}
332
333/// getCopyFromPartsVector - Create a value that contains the specified legal
334/// parts combined into the value they represent. If the parts combine to a
335/// type larger than ValueVT then AssertOp can be used to specify whether the
336/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
337/// ValueVT (ISD::AssertSext).
338static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
339 const SDValue *Parts, unsigned NumParts,
340 MVT PartVT, EVT ValueVT, const Value *V,
341 SDValue InChain,
342 std::optional<CallingConv::ID> CallConv) {
343 assert(ValueVT.isVector() && "Not a vector value");
344 assert(NumParts > 0 && "No parts to assemble!");
345 const bool IsABIRegCopy = CallConv.has_value();
346
347 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
348 SDValue Val = Parts[0];
349
350 // Handle a multi-element vector.
351 if (NumParts > 1) {
352 EVT IntermediateVT;
353 MVT RegisterVT;
354 unsigned NumIntermediates;
355 unsigned NumRegs;
356
357 if (IsABIRegCopy) {
358 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
359 Context&: *DAG.getContext(), CC: *CallConv, VT: ValueVT, IntermediateVT,
360 NumIntermediates, RegisterVT);
361 } else {
362 NumRegs =
363 TLI.getVectorTypeBreakdown(Context&: *DAG.getContext(), VT: ValueVT, IntermediateVT,
364 NumIntermediates, RegisterVT);
365 }
366
367 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
368 NumParts = NumRegs; // Silence a compiler warning.
369 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
370 assert(RegisterVT.getSizeInBits() ==
371 Parts[0].getSimpleValueType().getSizeInBits() &&
372 "Part type sizes don't match!");
373
374 // Assemble the parts into intermediate operands.
375 SmallVector<SDValue, 8> Ops(NumIntermediates);
376 if (NumIntermediates == NumParts) {
377 // If the register was not expanded, truncate or copy the value,
378 // as appropriate.
379 for (unsigned i = 0; i != NumParts; ++i)
380 Ops[i] = getCopyFromParts(DAG, DL, Parts: &Parts[i], NumParts: 1, PartVT, ValueVT: IntermediateVT,
381 V, InChain, CC: CallConv);
382 } else if (NumParts > 0) {
383 // If the intermediate type was expanded, build the intermediate
384 // operands from the parts.
385 assert(NumParts % NumIntermediates == 0 &&
386 "Must expand into a divisible number of parts!");
387 unsigned Factor = NumParts / NumIntermediates;
388 for (unsigned i = 0; i != NumIntermediates; ++i)
389 Ops[i] = getCopyFromParts(DAG, DL, Parts: &Parts[i * Factor], NumParts: Factor, PartVT,
390 ValueVT: IntermediateVT, V, InChain, CC: CallConv);
391 }
392
393 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
394 // intermediate operands.
395 EVT BuiltVectorTy =
396 IntermediateVT.isVector()
397 ? EVT::getVectorVT(
398 Context&: *DAG.getContext(), VT: IntermediateVT.getScalarType(),
399 EC: IntermediateVT.getVectorElementCount() * NumParts)
400 : EVT::getVectorVT(Context&: *DAG.getContext(),
401 VT: IntermediateVT.getScalarType(),
402 NumElements: NumIntermediates);
403 Val = DAG.getNode(Opcode: IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
404 : ISD::BUILD_VECTOR,
405 DL, VT: BuiltVectorTy, Ops);
406 }
407
408 // There is now one part, held in Val. Correct it to match ValueVT.
409 EVT PartEVT = Val.getValueType();
410
411 if (PartEVT == ValueVT)
412 return Val;
413
414 if (PartEVT.isVector()) {
415 // Vector/Vector bitcast.
416 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
417 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
418
419 // If the parts vector has more elements than the value vector, then we
420 // have a vector widening case (e.g. <2 x float> -> <4 x float>).
421 // Extract the elements we want.
422 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
423 assert((PartEVT.getVectorElementCount().getKnownMinValue() >
424 ValueVT.getVectorElementCount().getKnownMinValue()) &&
425 (PartEVT.getVectorElementCount().isScalable() ==
426 ValueVT.getVectorElementCount().isScalable()) &&
427 "Cannot narrow, it would be a lossy transformation");
428 PartEVT =
429 EVT::getVectorVT(Context&: *DAG.getContext(), VT: PartEVT.getVectorElementType(),
430 EC: ValueVT.getVectorElementCount());
431 Val = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: PartEVT, N1: Val,
432 N2: DAG.getVectorIdxConstant(Val: 0, DL));
433 if (PartEVT == ValueVT)
434 return Val;
435 if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
436 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
437
438 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
439 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
440 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
441 }
442
443 // Promoted vector extract
444 return DAG.getAnyExtOrTrunc(Op: Val, DL, VT: ValueVT);
445 }
446
447 // Trivial bitcast if the types are the same size and the destination
448 // vector type is legal.
449 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
450 TLI.isTypeLegal(VT: ValueVT))
451 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
452
453 if (ValueVT.getVectorNumElements() != 1) {
454 // Certain ABIs require that vectors are passed as integers. For vectors
455 // are the same size, this is an obvious bitcast.
456 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
457 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
458 } else if (ValueVT.bitsLT(VT: PartEVT)) {
459 const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
460 EVT IntermediateType = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueSize);
461 // Drop the extra bits.
462 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: IntermediateType, Operand: Val);
463 return DAG.getBitcast(VT: ValueVT, V: Val);
464 }
465
466 diagnosePossiblyInvalidConstraint(
467 Ctx&: *DAG.getContext(), V, ErrMsg: "non-trivial scalar-to-vector conversion");
468 return DAG.getUNDEF(VT: ValueVT);
469 }
470
471 // Handle cases such as i8 -> <1 x i1>
472 EVT ValueSVT = ValueVT.getVectorElementType();
473 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
474 unsigned ValueSize = ValueSVT.getSizeInBits();
475 if (ValueSize == PartEVT.getSizeInBits()) {
476 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueSVT, Operand: Val);
477 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
478 // It's possible a scalar floating point type gets softened to integer and
479 // then promoted to a larger integer. If PartEVT is the larger integer
480 // we need to truncate it and then bitcast to the FP type.
481 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
482 EVT IntermediateType = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueSize);
483 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: IntermediateType, Operand: Val);
484 Val = DAG.getBitcast(VT: ValueSVT, V: Val);
485 } else {
486 Val = ValueVT.isFloatingPoint()
487 ? DAG.getFPExtendOrRound(Op: Val, DL, VT: ValueSVT)
488 : DAG.getAnyExtOrTrunc(Op: Val, DL, VT: ValueSVT);
489 }
490 }
491
492 return DAG.getBuildVector(VT: ValueVT, DL, Ops: Val);
493}
494
495static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
496 SDValue Val, SDValue *Parts, unsigned NumParts,
497 MVT PartVT, const Value *V,
498 std::optional<CallingConv::ID> CallConv);
499
500/// getCopyToParts - Create a series of nodes that contain the specified value
501/// split into legal parts. If the parts contain more bits than Val, then, for
502/// integers, ExtendKind can be used to specify how to generate the extra bits.
503static void
504getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
505 unsigned NumParts, MVT PartVT, const Value *V,
506 std::optional<CallingConv::ID> CallConv = std::nullopt,
507 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
508 // Let the target split the parts if it wants to
509 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
510 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
511 CC: CallConv))
512 return;
513 EVT ValueVT = Val.getValueType();
514
515 // Handle the vector case separately.
516 if (ValueVT.isVector())
517 return getCopyToPartsVector(DAG, dl: DL, Val, Parts, NumParts, PartVT, V,
518 CallConv);
519
520 unsigned OrigNumParts = NumParts;
521 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
522 "Copying to an illegal type!");
523
524 if (NumParts == 0)
525 return;
526
527 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
528 EVT PartEVT = PartVT;
529 if (PartEVT == ValueVT) {
530 assert(NumParts == 1 && "No-op copy with multiple parts!");
531 Parts[0] = Val;
532 return;
533 }
534
535 unsigned PartBits = PartVT.getSizeInBits();
536 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
537 // If the parts cover more bits than the value has, promote the value.
538 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
539 assert(NumParts == 1 && "Do not know what to promote to!");
540 Val = DAG.getNode(Opcode: ISD::FP_EXTEND, DL, VT: PartVT, Operand: Val);
541 } else {
542 if (ValueVT.isFloatingPoint()) {
543 // FP values need to be bitcast, then extended if they are being put
544 // into a larger container.
545 ValueVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueVT.getSizeInBits());
546 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
547 }
548 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
549 ValueVT.isInteger() &&
550 "Unknown mismatch!");
551 ValueVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: NumParts * PartBits);
552 Val = DAG.getNode(Opcode: ExtendKind, DL, VT: ValueVT, Operand: Val);
553 if (PartVT == MVT::x86mmx)
554 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
555 }
556 } else if (PartBits == ValueVT.getSizeInBits()) {
557 // Different types of the same size.
558 assert(NumParts == 1 && PartEVT != ValueVT);
559 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
560 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
561 // If the parts cover less bits than value has, truncate the value.
562 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
563 ValueVT.isInteger() &&
564 "Unknown mismatch!");
565 ValueVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: NumParts * PartBits);
566 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: ValueVT, Operand: Val);
567 if (PartVT == MVT::x86mmx)
568 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
569 }
570
571 // The value may have changed - recompute ValueVT.
572 ValueVT = Val.getValueType();
573 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
574 "Failed to tile the value with PartVT!");
575
576 if (NumParts == 1) {
577 if (PartEVT != ValueVT) {
578 diagnosePossiblyInvalidConstraint(Ctx&: *DAG.getContext(), V,
579 ErrMsg: "scalar-to-vector conversion failed");
580 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
581 }
582
583 Parts[0] = Val;
584 return;
585 }
586
587 // Expand the value into multiple parts.
588 if (NumParts & (NumParts - 1)) {
589 // The number of parts is not a power of 2. Split off and copy the tail.
590 assert(PartVT.isInteger() && ValueVT.isInteger() &&
591 "Do not know what to expand to!");
592 unsigned RoundParts = llvm::bit_floor(Value: NumParts);
593 unsigned RoundBits = RoundParts * PartBits;
594 unsigned OddParts = NumParts - RoundParts;
595 SDValue OddVal = DAG.getNode(Opcode: ISD::SRL, DL, VT: ValueVT, N1: Val,
596 N2: DAG.getShiftAmountConstant(Val: RoundBits, VT: ValueVT, DL));
597
598 getCopyToParts(DAG, DL, Val: OddVal, Parts: Parts + RoundParts, NumParts: OddParts, PartVT, V,
599 CallConv);
600
601 if (DAG.getDataLayout().isBigEndian())
602 // The odd parts were reversed by getCopyToParts - unreverse them.
603 std::reverse(first: Parts + RoundParts, last: Parts + NumParts);
604
605 NumParts = RoundParts;
606 ValueVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: NumParts * PartBits);
607 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: ValueVT, Operand: Val);
608 }
609
610 // The number of parts is a power of 2. Repeatedly bisect the value using
611 // EXTRACT_ELEMENT.
612 Parts[0] = DAG.getNode(Opcode: ISD::BITCAST, DL,
613 VT: EVT::getIntegerVT(Context&: *DAG.getContext(),
614 BitWidth: ValueVT.getSizeInBits()),
615 Operand: Val);
616
617 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
618 for (unsigned i = 0; i < NumParts; i += StepSize) {
619 unsigned ThisBits = StepSize * PartBits / 2;
620 EVT ThisVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ThisBits);
621 SDValue &Part0 = Parts[i];
622 SDValue &Part1 = Parts[i+StepSize/2];
623
624 Part1 = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL,
625 VT: ThisVT, N1: Part0, N2: DAG.getIntPtrConstant(Val: 1, DL));
626 Part0 = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL,
627 VT: ThisVT, N1: Part0, N2: DAG.getIntPtrConstant(Val: 0, DL));
628
629 if (ThisBits == PartBits && ThisVT != PartVT) {
630 Part0 = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Part0);
631 Part1 = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Part1);
632 }
633 }
634 }
635
636 if (DAG.getDataLayout().isBigEndian())
637 std::reverse(first: Parts, last: Parts + OrigNumParts);
638}
639
640static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
641 const SDLoc &DL, EVT PartVT) {
642 if (!PartVT.isVector())
643 return SDValue();
644
645 EVT ValueVT = Val.getValueType();
646 EVT PartEVT = PartVT.getVectorElementType();
647 EVT ValueEVT = ValueVT.getVectorElementType();
648 ElementCount PartNumElts = PartVT.getVectorElementCount();
649 ElementCount ValueNumElts = ValueVT.getVectorElementCount();
650
651 // We only support widening vectors with equivalent element types and
652 // fixed/scalable properties. If a target needs to widen a fixed-length type
653 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
654 if (ElementCount::isKnownLE(LHS: PartNumElts, RHS: ValueNumElts) ||
655 PartNumElts.isScalable() != ValueNumElts.isScalable())
656 return SDValue();
657
658 // Have a try for bf16 because some targets share its ABI with fp16.
659 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
660 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
661 "Cannot widen to illegal type");
662 Val = DAG.getNode(
663 Opcode: ISD::BITCAST, DL,
664 VT: ValueVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: MVT::f16), Operand: Val);
665 } else if (PartEVT != ValueEVT) {
666 return SDValue();
667 }
668
669 // Widening a scalable vector to another scalable vector is done by inserting
670 // the vector into a larger undef one.
671 if (PartNumElts.isScalable())
672 return DAG.getNode(Opcode: ISD::INSERT_SUBVECTOR, DL, VT: PartVT, N1: DAG.getUNDEF(VT: PartVT),
673 N2: Val, N3: DAG.getVectorIdxConstant(Val: 0, DL));
674
675 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
676 // undef elements.
677 SmallVector<SDValue, 16> Ops;
678 DAG.ExtractVectorElements(Op: Val, Args&: Ops);
679 SDValue EltUndef = DAG.getUNDEF(VT: PartEVT);
680 Ops.append(NumInputs: (PartNumElts - ValueNumElts).getFixedValue(), Elt: EltUndef);
681
682 // FIXME: Use CONCAT for 2x -> 4x.
683 return DAG.getBuildVector(VT: PartVT, DL, Ops);
684}
685
686/// getCopyToPartsVector - Create a series of nodes that contain the specified
687/// value split into legal parts.
688static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
689 SDValue Val, SDValue *Parts, unsigned NumParts,
690 MVT PartVT, const Value *V,
691 std::optional<CallingConv::ID> CallConv) {
692 EVT ValueVT = Val.getValueType();
693 assert(ValueVT.isVector() && "Not a vector");
694 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
695 const bool IsABIRegCopy = CallConv.has_value();
696
697 if (NumParts == 1) {
698 EVT PartEVT = PartVT;
699 if (PartEVT == ValueVT) {
700 // Nothing to do.
701 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
702 // Bitconvert vector->vector case.
703 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
704 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
705 Val = Widened;
706 } else if (PartVT.isVector() &&
707 PartEVT.getVectorElementType().bitsGE(
708 VT: ValueVT.getVectorElementType()) &&
709 PartEVT.getVectorElementCount() ==
710 ValueVT.getVectorElementCount()) {
711
712 // Promoted vector extract
713 Val = DAG.getAnyExtOrTrunc(Op: Val, DL, VT: PartVT);
714 } else if (PartEVT.isVector() &&
715 PartEVT.getVectorElementType() !=
716 ValueVT.getVectorElementType() &&
717 TLI.getTypeAction(Context&: *DAG.getContext(), VT: ValueVT) ==
718 TargetLowering::TypeWidenVector) {
719 // Combination of widening and promotion.
720 EVT WidenVT =
721 EVT::getVectorVT(Context&: *DAG.getContext(), VT: ValueVT.getVectorElementType(),
722 EC: PartVT.getVectorElementCount());
723 SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT: WidenVT);
724 Val = DAG.getAnyExtOrTrunc(Op: Widened, DL, VT: PartVT);
725 } else {
726 // Don't extract an integer from a float vector. This can happen if the
727 // FP type gets softened to integer and then promoted. The promotion
728 // prevents it from being picked up by the earlier bitcast case.
729 if (ValueVT.getVectorElementCount().isScalar() &&
730 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
731 // If we reach this condition and PartVT is FP, this means that
732 // ValueVT is also FP and both have a different size, otherwise we
733 // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
734 // would be invalid since that would mean the smaller FP type has to
735 // be extended to the larger one.
736 if (PartVT.isFloatingPoint()) {
737 Val = DAG.getBitcast(VT: ValueVT.getScalarType(), V: Val);
738 Val = DAG.getNode(Opcode: ISD::FP_EXTEND, DL, VT: PartVT, Operand: Val);
739 } else
740 Val = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: PartVT, N1: Val,
741 N2: DAG.getVectorIdxConstant(Val: 0, DL));
742 } else {
743 uint64_t ValueSize = ValueVT.getFixedSizeInBits();
744 assert(PartVT.getFixedSizeInBits() > ValueSize &&
745 "lossy conversion of vector to scalar type");
746 EVT IntermediateType = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueSize);
747 Val = DAG.getBitcast(VT: IntermediateType, V: Val);
748 Val = DAG.getAnyExtOrTrunc(Op: Val, DL, VT: PartVT);
749 }
750 }
751
752 assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
753 Parts[0] = Val;
754 return;
755 }
756
757 // Handle a multi-element vector.
758 EVT IntermediateVT;
759 MVT RegisterVT;
760 unsigned NumIntermediates;
761 unsigned NumRegs;
762 if (IsABIRegCopy) {
763 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
764 Context&: *DAG.getContext(), CC: *CallConv, VT: ValueVT, IntermediateVT, NumIntermediates,
765 RegisterVT);
766 } else {
767 NumRegs =
768 TLI.getVectorTypeBreakdown(Context&: *DAG.getContext(), VT: ValueVT, IntermediateVT,
769 NumIntermediates, RegisterVT);
770 }
771
772 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
773 NumParts = NumRegs; // Silence a compiler warning.
774 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
775
776 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
777 "Mixing scalable and fixed vectors when copying in parts");
778
779 std::optional<ElementCount> DestEltCnt;
780
781 if (IntermediateVT.isVector())
782 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
783 else
784 DestEltCnt = ElementCount::getFixed(MinVal: NumIntermediates);
785
786 EVT BuiltVectorTy = EVT::getVectorVT(
787 Context&: *DAG.getContext(), VT: IntermediateVT.getScalarType(), EC: *DestEltCnt);
788
789 if (ValueVT == BuiltVectorTy) {
790 // Nothing to do.
791 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
792 // Bitconvert vector->vector case.
793 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: BuiltVectorTy, Operand: Val);
794 } else {
795 if (BuiltVectorTy.getVectorElementType().bitsGT(
796 VT: ValueVT.getVectorElementType())) {
797 // Integer promotion.
798 ValueVT = EVT::getVectorVT(Context&: *DAG.getContext(),
799 VT: BuiltVectorTy.getVectorElementType(),
800 EC: ValueVT.getVectorElementCount());
801 Val = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: ValueVT, Operand: Val);
802 }
803
804 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT: BuiltVectorTy)) {
805 Val = Widened;
806 }
807 }
808
809 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
810
811 // Split the vector into intermediate operands.
812 SmallVector<SDValue, 8> Ops(NumIntermediates);
813 for (unsigned i = 0; i != NumIntermediates; ++i) {
814 if (IntermediateVT.isVector()) {
815 // This does something sensible for scalable vectors - see the
816 // definition of EXTRACT_SUBVECTOR for further details.
817 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
818 Ops[i] =
819 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: IntermediateVT, N1: Val,
820 N2: DAG.getVectorIdxConstant(Val: i * IntermediateNumElts, DL));
821 } else {
822 Ops[i] = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: IntermediateVT, N1: Val,
823 N2: DAG.getVectorIdxConstant(Val: i, DL));
824 }
825 }
826
827 // Split the intermediate operands into legal parts.
828 if (NumParts == NumIntermediates) {
829 // If the register was not expanded, promote or copy the value,
830 // as appropriate.
831 for (unsigned i = 0; i != NumParts; ++i)
832 getCopyToParts(DAG, DL, Val: Ops[i], Parts: &Parts[i], NumParts: 1, PartVT, V, CallConv);
833 } else if (NumParts > 0) {
834 // If the intermediate type was expanded, split each the value into
835 // legal parts.
836 assert(NumIntermediates != 0 && "division by zero");
837 assert(NumParts % NumIntermediates == 0 &&
838 "Must expand into a divisible number of parts!");
839 unsigned Factor = NumParts / NumIntermediates;
840 for (unsigned i = 0; i != NumIntermediates; ++i)
841 getCopyToParts(DAG, DL, Val: Ops[i], Parts: &Parts[i * Factor], NumParts: Factor, PartVT, V,
842 CallConv);
843 }
844}
845
846static void failForInvalidBundles(const CallBase &I, StringRef Name,
847 ArrayRef<uint32_t> AllowedBundles) {
848 if (I.hasOperandBundlesOtherThan(IDs: AllowedBundles)) {
849 ListSeparator LS;
850 std::string Error;
851 raw_string_ostream OS(Error);
852 for (unsigned i = 0, e = I.getNumOperandBundles(); i != e; ++i) {
853 OperandBundleUse U = I.getOperandBundleAt(Index: i);
854 if (!is_contained(Range&: AllowedBundles, Element: U.getTagID()))
855 OS << LS << U.getTagName();
856 }
857 reportFatalUsageError(
858 reason: Twine("cannot lower ", Name)
859 .concat(Suffix: Twine(" with arbitrary operand bundles: ", Error)));
860 }
861}
862
863RegsForValue::RegsForValue(const SmallVector<Register, 4> &regs, MVT regvt,
864 EVT valuevt, std::optional<CallingConv::ID> CC)
865 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
866 RegCount(1, regs.size()), CallConv(CC) {}
867
868RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
869 const DataLayout &DL, Register Reg, Type *Ty,
870 std::optional<CallingConv::ID> CC) {
871 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
872
873 CallConv = CC;
874
875 for (EVT ValueVT : ValueVTs) {
876 unsigned NumRegs =
877 isABIMangled()
878 ? TLI.getNumRegistersForCallingConv(Context, CC: *CC, VT: ValueVT)
879 : TLI.getNumRegisters(Context, VT: ValueVT);
880 MVT RegisterVT =
881 isABIMangled()
882 ? TLI.getRegisterTypeForCallingConv(Context, CC: *CC, VT: ValueVT)
883 : TLI.getRegisterType(Context, VT: ValueVT);
884 for (unsigned i = 0; i != NumRegs; ++i)
885 Regs.push_back(Elt: Reg + i);
886 RegVTs.push_back(Elt: RegisterVT);
887 RegCount.push_back(Elt: NumRegs);
888 Reg = Reg.id() + NumRegs;
889 }
890}
891
892SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
893 FunctionLoweringInfo &FuncInfo,
894 const SDLoc &dl, SDValue &Chain,
895 SDValue *Glue, const Value *V) const {
896 // A Value with type {} or [0 x %t] needs no registers.
897 if (ValueVTs.empty())
898 return SDValue();
899
900 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
901
902 // Assemble the legal parts into the final values.
903 SmallVector<SDValue, 4> Values(ValueVTs.size());
904 SmallVector<SDValue, 8> Parts;
905 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
906 // Copy the legal parts from the registers.
907 EVT ValueVT = ValueVTs[Value];
908 unsigned NumRegs = RegCount[Value];
909 MVT RegisterVT = isABIMangled()
910 ? TLI.getRegisterTypeForCallingConv(
911 Context&: *DAG.getContext(), CC: *CallConv, VT: RegVTs[Value])
912 : RegVTs[Value];
913
914 Parts.resize(N: NumRegs);
915 for (unsigned i = 0; i != NumRegs; ++i) {
916 SDValue P;
917 if (!Glue) {
918 P = DAG.getCopyFromReg(Chain, dl, Reg: Regs[Part+i], VT: RegisterVT);
919 } else {
920 P = DAG.getCopyFromReg(Chain, dl, Reg: Regs[Part+i], VT: RegisterVT, Glue: *Glue);
921 *Glue = P.getValue(R: 2);
922 }
923
924 Chain = P.getValue(R: 1);
925 Parts[i] = P;
926
927 // If the source register was virtual and if we know something about it,
928 // add an assert node.
929 if (!Regs[Part + i].isVirtual() || !RegisterVT.isInteger())
930 continue;
931
932 const FunctionLoweringInfo::LiveOutInfo *LOI =
933 FuncInfo.GetLiveOutRegInfo(Reg: Regs[Part+i]);
934 if (!LOI)
935 continue;
936
937 unsigned RegSize = RegisterVT.getScalarSizeInBits();
938 unsigned NumSignBits = LOI->NumSignBits;
939 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
940
941 if (NumZeroBits == RegSize) {
942 // The current value is a zero.
943 // Explicitly express that as it would be easier for
944 // optimizations to kick in.
945 Parts[i] = DAG.getConstant(Val: 0, DL: dl, VT: RegisterVT);
946 continue;
947 }
948
949 // FIXME: We capture more information than the dag can represent. For
950 // now, just use the tightest assertzext/assertsext possible.
951 bool isSExt;
952 EVT FromVT(MVT::Other);
953 if (NumZeroBits) {
954 FromVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: RegSize - NumZeroBits);
955 isSExt = false;
956 } else if (NumSignBits > 1) {
957 FromVT =
958 EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: RegSize - NumSignBits + 1);
959 isSExt = true;
960 } else {
961 continue;
962 }
963 // Add an assertion node.
964 assert(FromVT != MVT::Other);
965 Parts[i] = DAG.getNode(Opcode: isSExt ? ISD::AssertSext : ISD::AssertZext, DL: dl,
966 VT: RegisterVT, N1: P, N2: DAG.getValueType(FromVT));
967 }
968
969 Values[Value] = getCopyFromParts(DAG, DL: dl, Parts: Parts.begin(), NumParts: NumRegs,
970 PartVT: RegisterVT, ValueVT, V, InChain: Chain, CC: CallConv);
971 Part += NumRegs;
972 Parts.clear();
973 }
974
975 return DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl, VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values);
976}
977
978void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
979 const SDLoc &dl, SDValue &Chain, SDValue *Glue,
980 const Value *V,
981 ISD::NodeType PreferredExtendType) const {
982 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
983 ISD::NodeType ExtendKind = PreferredExtendType;
984
985 // Get the list of the values's legal parts.
986 unsigned NumRegs = Regs.size();
987 SmallVector<SDValue, 8> Parts(NumRegs);
988 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
989 unsigned NumParts = RegCount[Value];
990
991 MVT RegisterVT = isABIMangled()
992 ? TLI.getRegisterTypeForCallingConv(
993 Context&: *DAG.getContext(), CC: *CallConv, VT: RegVTs[Value])
994 : RegVTs[Value];
995
996 if (ExtendKind == ISD::ANY_EXTEND)
997 if (TLI.isZExtFree(Val: peekThroughFreeze(V: Val), VT2: RegisterVT))
998 ExtendKind = ISD::ZERO_EXTEND;
999
1000 getCopyToParts(DAG, DL: dl, Val: Val.getValue(R: Val.getResNo() + Value), Parts: &Parts[Part],
1001 NumParts, PartVT: RegisterVT, V, CallConv, ExtendKind);
1002 Part += NumParts;
1003 }
1004
1005 // Copy the parts into the registers.
1006 SmallVector<SDValue, 8> Chains(NumRegs);
1007 for (unsigned i = 0; i != NumRegs; ++i) {
1008 SDValue Part;
1009 if (!Glue) {
1010 Part = DAG.getCopyToReg(Chain, dl, Reg: Regs[i], N: Parts[i]);
1011 } else {
1012 Part = DAG.getCopyToReg(Chain, dl, Reg: Regs[i], N: Parts[i], Glue: *Glue);
1013 *Glue = Part.getValue(R: 1);
1014 }
1015
1016 Chains[i] = Part.getValue(R: 0);
1017 }
1018
1019 if (NumRegs == 1 || Glue)
1020 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1021 // flagged to it. That is the CopyToReg nodes and the user are considered
1022 // a single scheduling unit. If we create a TokenFactor and return it as
1023 // chain, then the TokenFactor is both a predecessor (operand) of the
1024 // user as well as a successor (the TF operands are flagged to the user).
1025 // c1, f1 = CopyToReg
1026 // c2, f2 = CopyToReg
1027 // c3 = TokenFactor c1, c2
1028 // ...
1029 // = op c3, ..., f2
1030 Chain = Chains[NumRegs-1];
1031 else
1032 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: Chains);
1033}
1034
1035void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1036 unsigned MatchingIdx, const SDLoc &dl,
1037 SelectionDAG &DAG,
1038 std::vector<SDValue> &Ops) const {
1039 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1040
1041 InlineAsm::Flag Flag(Code, Regs.size());
1042 if (HasMatching)
1043 Flag.setMatchingOp(MatchingIdx);
1044 else if (!Regs.empty() && Regs.front().isVirtual()) {
1045 // Put the register class of the virtual registers in the flag word. That
1046 // way, later passes can recompute register class constraints for inline
1047 // assembly as well as normal instructions.
1048 // Don't do this for tied operands that can use the regclass information
1049 // from the def.
1050 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1051 const TargetRegisterClass *RC = MRI.getRegClass(Reg: Regs.front());
1052 Flag.setRegClass(RC->getID());
1053 }
1054
1055 SDValue Res = DAG.getTargetConstant(Val: Flag, DL: dl, VT: MVT::i32);
1056 Ops.push_back(x: Res);
1057
1058 if (Code == InlineAsm::Kind::Clobber) {
1059 // Clobbers should always have a 1:1 mapping with registers, and may
1060 // reference registers that have illegal (e.g. vector) types. Hence, we
1061 // shouldn't try to apply any sort of splitting logic to them.
1062 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1063 "No 1:1 mapping from clobbers to regs?");
1064 Register SP = TLI.getStackPointerRegisterToSaveRestore();
1065 (void)SP;
1066 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1067 Ops.push_back(x: DAG.getRegister(Reg: Regs[I], VT: RegVTs[I]));
1068 assert(
1069 (Regs[I] != SP ||
1070 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1071 "If we clobbered the stack pointer, MFI should know about it.");
1072 }
1073 return;
1074 }
1075
1076 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1077 MVT RegisterVT = RegVTs[Value];
1078 unsigned NumRegs = TLI.getNumRegisters(Context&: *DAG.getContext(), VT: ValueVTs[Value],
1079 RegisterVT);
1080 for (unsigned i = 0; i != NumRegs; ++i) {
1081 assert(Reg < Regs.size() && "Mismatch in # registers expected");
1082 Register TheReg = Regs[Reg++];
1083 Ops.push_back(x: DAG.getRegister(Reg: TheReg, VT: RegisterVT));
1084 }
1085 }
1086}
1087
1088SmallVector<std::pair<Register, TypeSize>, 4>
1089RegsForValue::getRegsAndSizes() const {
1090 SmallVector<std::pair<Register, TypeSize>, 4> OutVec;
1091 unsigned I = 0;
1092 for (auto CountAndVT : zip_first(t: RegCount, u: RegVTs)) {
1093 unsigned RegCount = std::get<0>(t&: CountAndVT);
1094 MVT RegisterVT = std::get<1>(t&: CountAndVT);
1095 TypeSize RegisterSize = RegisterVT.getSizeInBits();
1096 for (unsigned E = I + RegCount; I != E; ++I)
1097 OutVec.push_back(Elt: std::make_pair(x: Regs[I], y&: RegisterSize));
1098 }
1099 return OutVec;
1100}
1101
1102void SelectionDAGBuilder::init(GCFunctionInfo *gfi, BatchAAResults *aa,
1103 AssumptionCache *ac, const TargetLibraryInfo *li,
1104 const TargetTransformInfo &TTI) {
1105 BatchAA = aa;
1106 AC = ac;
1107 GFI = gfi;
1108 LibInfo = li;
1109 Context = DAG.getContext();
1110 LPadToCallSiteMap.clear();
1111 this->TTI = &TTI;
1112 SL->init(tli: DAG.getTargetLoweringInfo(), tm: TM, dl: DAG.getDataLayout());
1113 AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1114 M: *DAG.getMachineFunction().getFunction().getParent());
1115}
1116
1117void SelectionDAGBuilder::clear() {
1118 NodeMap.clear();
1119 UnusedArgNodeMap.clear();
1120 PendingLoads.clear();
1121 PendingExports.clear();
1122 PendingConstrainedFP.clear();
1123 PendingConstrainedFPStrict.clear();
1124 CurInst = nullptr;
1125 HasTailCall = false;
1126 SDNodeOrder = LowestSDNodeOrder;
1127 StatepointLowering.clear();
1128}
1129
1130void SelectionDAGBuilder::clearDanglingDebugInfo() {
1131 DanglingDebugInfoMap.clear();
1132}
1133
1134// Update DAG root to include dependencies on Pending chains.
1135SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1136 SDValue Root = DAG.getRoot();
1137
1138 if (Pending.empty())
1139 return Root;
1140
1141 // Add current root to PendingChains, unless we already indirectly
1142 // depend on it.
1143 if (Root.getOpcode() != ISD::EntryToken) {
1144 unsigned i = 0, e = Pending.size();
1145 for (; i != e; ++i) {
1146 assert(Pending[i].getNode()->getNumOperands() > 1);
1147 if (Pending[i].getNode()->getOperand(Num: 0) == Root)
1148 break; // Don't add the root if we already indirectly depend on it.
1149 }
1150
1151 if (i == e)
1152 Pending.push_back(Elt: Root);
1153 }
1154
1155 if (Pending.size() == 1)
1156 Root = Pending[0];
1157 else
1158 Root = DAG.getTokenFactor(DL: getCurSDLoc(), Vals&: Pending);
1159
1160 DAG.setRoot(Root);
1161 Pending.clear();
1162 return Root;
1163}
1164
1165SDValue SelectionDAGBuilder::getMemoryRoot() {
1166 return updateRoot(Pending&: PendingLoads);
1167}
1168
1169SDValue SelectionDAGBuilder::getFPOperationRoot(fp::ExceptionBehavior EB) {
1170 // If the new exception behavior differs from that of the pending
1171 // ones, chain up them and update the root.
1172 switch (EB) {
1173 case fp::ExceptionBehavior::ebMayTrap:
1174 case fp::ExceptionBehavior::ebIgnore:
1175 // Floating-point exceptions produced by such operations are not intended
1176 // to be observed, so the sequence of these operations does not need to be
1177 // preserved.
1178 //
1179 // They however must not be mixed with the instructions that have strict
1180 // exception behavior. Placing an operation with 'ebIgnore' behavior between
1181 // 'ebStrict' operations could distort the observed exception behavior.
1182 if (!PendingConstrainedFPStrict.empty()) {
1183 assert(PendingConstrainedFP.empty());
1184 updateRoot(Pending&: PendingConstrainedFPStrict);
1185 }
1186 break;
1187 case fp::ExceptionBehavior::ebStrict:
1188 // Floating-point exception produced by these operations may be observed, so
1189 // they must be correctly chained. If trapping on FP exceptions is
1190 // disabled, the exceptions can be observed only by functions that read
1191 // exception flags, like 'llvm.get_fpenv' or 'fetestexcept'. It means that
1192 // the order of operations is not significant between barriers.
1193 //
1194 // If trapping is enabled, each operation becomes an implicit observation
1195 // point, so the operations must be sequenced according their original
1196 // source order.
1197 if (!PendingConstrainedFP.empty()) {
1198 assert(PendingConstrainedFPStrict.empty());
1199 updateRoot(Pending&: PendingConstrainedFP);
1200 }
1201 // TODO: Add support for trapping-enabled scenarios.
1202 }
1203 return DAG.getRoot();
1204}
1205
1206SDValue SelectionDAGBuilder::getRoot() {
1207 // Chain up all pending constrained intrinsics together with all
1208 // pending loads, by simply appending them to PendingLoads and
1209 // then calling getMemoryRoot().
1210 PendingLoads.reserve(N: PendingLoads.size() +
1211 PendingConstrainedFP.size() +
1212 PendingConstrainedFPStrict.size());
1213 PendingLoads.append(in_start: PendingConstrainedFP.begin(),
1214 in_end: PendingConstrainedFP.end());
1215 PendingLoads.append(in_start: PendingConstrainedFPStrict.begin(),
1216 in_end: PendingConstrainedFPStrict.end());
1217 PendingConstrainedFP.clear();
1218 PendingConstrainedFPStrict.clear();
1219 return getMemoryRoot();
1220}
1221
1222SDValue SelectionDAGBuilder::getControlRoot() {
1223 // We need to emit pending fpexcept.strict constrained intrinsics,
1224 // so append them to the PendingExports list.
1225 PendingExports.append(in_start: PendingConstrainedFPStrict.begin(),
1226 in_end: PendingConstrainedFPStrict.end());
1227 PendingConstrainedFPStrict.clear();
1228 return updateRoot(Pending&: PendingExports);
1229}
1230
1231void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1232 DILocalVariable *Variable,
1233 DIExpression *Expression,
1234 DebugLoc DL) {
1235 assert(Variable && "Missing variable");
1236
1237 // Check if address has undef value.
1238 if (!Address || isa<UndefValue>(Val: Address) ||
1239 (Address->use_empty() && !isa<Argument>(Val: Address))) {
1240 LLVM_DEBUG(
1241 dbgs()
1242 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1243 return;
1244 }
1245
1246 bool IsParameter = Variable->isParameter() || isa<Argument>(Val: Address);
1247
1248 SDValue &N = NodeMap[Address];
1249 if (!N.getNode() && isa<Argument>(Val: Address))
1250 // Check unused arguments map.
1251 N = UnusedArgNodeMap[Address];
1252 SDDbgValue *SDV;
1253 if (N.getNode()) {
1254 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Val: Address))
1255 Address = BCI->getOperand(i_nocapture: 0);
1256 // Parameters are handled specially.
1257 auto *FINode = dyn_cast<FrameIndexSDNode>(Val: N.getNode());
1258 if (IsParameter && FINode) {
1259 // Byval parameter. We have a frame index at this point.
1260 SDV = DAG.getFrameIndexDbgValue(Var: Variable, Expr: Expression, FI: FINode->getIndex(),
1261 /*IsIndirect*/ true, DL, O: SDNodeOrder);
1262 } else if (isa<Argument>(Val: Address)) {
1263 // Address is an argument, so try to emit its dbg value using
1264 // virtual register info from the FuncInfo.ValueMap.
1265 EmitFuncArgumentDbgValue(V: Address, Variable, Expr: Expression, DL,
1266 Kind: FuncArgumentDbgValueKind::Declare, N);
1267 return;
1268 } else {
1269 SDV = DAG.getDbgValue(Var: Variable, Expr: Expression, N: N.getNode(), R: N.getResNo(),
1270 IsIndirect: true, DL, O: SDNodeOrder);
1271 }
1272 DAG.AddDbgValue(DB: SDV, isParameter: IsParameter);
1273 } else {
1274 // If Address is an argument then try to emit its dbg value using
1275 // virtual register info from the FuncInfo.ValueMap.
1276 if (!EmitFuncArgumentDbgValue(V: Address, Variable, Expr: Expression, DL,
1277 Kind: FuncArgumentDbgValueKind::Declare, N)) {
1278 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1279 << " (could not emit func-arg dbg_value)\n");
1280 }
1281 }
1282}
1283
1284void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1285 // Add SDDbgValue nodes for any var locs here. Do so before updating
1286 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1287 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1288 // Add SDDbgValue nodes for any var locs here. Do so before updating
1289 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1290 for (auto It = FnVarLocs->locs_begin(Before: &I), End = FnVarLocs->locs_end(Before: &I);
1291 It != End; ++It) {
1292 auto *Var = FnVarLocs->getDILocalVariable(ID: It->VariableID);
1293 dropDanglingDebugInfo(Variable: Var, Expr: It->Expr);
1294 if (It->Values.isKillLocation(Expression: It->Expr)) {
1295 handleKillDebugValue(Var, Expr: It->Expr, DbgLoc: It->DL, Order: SDNodeOrder);
1296 continue;
1297 }
1298 SmallVector<Value *> Values(It->Values.location_ops());
1299 if (!handleDebugValue(Values, Var, Expr: It->Expr, DbgLoc: It->DL, Order: SDNodeOrder,
1300 IsVariadic: It->Values.hasArgList())) {
1301 SmallVector<Value *, 4> Vals(It->Values.location_ops());
1302 addDanglingDebugInfo(Values&: Vals,
1303 Var: FnVarLocs->getDILocalVariable(ID: It->VariableID),
1304 Expr: It->Expr, IsVariadic: Vals.size() > 1, DL: It->DL, Order: SDNodeOrder);
1305 }
1306 }
1307 }
1308
1309 // We must skip DbgVariableRecords if they've already been processed above as
1310 // we have just emitted the debug values resulting from assignment tracking
1311 // analysis, making any existing DbgVariableRecords redundant (and probably
1312 // less correct). We still need to process DbgLabelRecords. This does sink
1313 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1314 // be important as it does so deterministcally and ordering between
1315 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1316 // printing).
1317 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1318 // Is there is any debug-info attached to this instruction, in the form of
1319 // DbgRecord non-instruction debug-info records.
1320 for (DbgRecord &DR : I.getDbgRecordRange()) {
1321 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(Val: &DR)) {
1322 assert(DLR->getLabel() && "Missing label");
1323 SDDbgLabel *SDV =
1324 DAG.getDbgLabel(Label: DLR->getLabel(), DL: DLR->getDebugLoc(), O: SDNodeOrder);
1325 DAG.AddDbgLabel(DB: SDV);
1326 continue;
1327 }
1328
1329 if (SkipDbgVariableRecords)
1330 continue;
1331 DbgVariableRecord &DVR = cast<DbgVariableRecord>(Val&: DR);
1332 DILocalVariable *Variable = DVR.getVariable();
1333 DIExpression *Expression = DVR.getExpression();
1334 dropDanglingDebugInfo(Variable, Expr: Expression);
1335
1336 if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1337 if (FuncInfo.PreprocessedDVRDeclares.contains(Ptr: &DVR))
1338 continue;
1339 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1340 << "\n");
1341 handleDebugDeclare(Address: DVR.getVariableLocationOp(OpIdx: 0), Variable, Expression,
1342 DL: DVR.getDebugLoc());
1343 continue;
1344 }
1345
1346 // A DbgVariableRecord with no locations is a kill location.
1347 SmallVector<Value *, 4> Values(DVR.location_ops());
1348 if (Values.empty()) {
1349 handleKillDebugValue(Var: Variable, Expr: Expression, DbgLoc: DVR.getDebugLoc(),
1350 Order: SDNodeOrder);
1351 continue;
1352 }
1353
1354 // A DbgVariableRecord with an undef or absent location is also a kill
1355 // location.
1356 if (llvm::any_of(Range&: Values,
1357 P: [](Value *V) { return !V || isa<UndefValue>(Val: V); })) {
1358 handleKillDebugValue(Var: Variable, Expr: Expression, DbgLoc: DVR.getDebugLoc(),
1359 Order: SDNodeOrder);
1360 continue;
1361 }
1362
1363 bool IsVariadic = DVR.hasArgList();
1364 if (!handleDebugValue(Values, Var: Variable, Expr: Expression, DbgLoc: DVR.getDebugLoc(),
1365 Order: SDNodeOrder, IsVariadic)) {
1366 addDanglingDebugInfo(Values, Var: Variable, Expr: Expression, IsVariadic,
1367 DL: DVR.getDebugLoc(), Order: SDNodeOrder);
1368 }
1369 }
1370}
1371
1372void SelectionDAGBuilder::visit(const Instruction &I) {
1373 visitDbgInfo(I);
1374
1375 // Set up outgoing PHI node register values before emitting the terminator.
1376 if (I.isTerminator()) {
1377 HandlePHINodesInSuccessorBlocks(LLVMBB: I.getParent());
1378 }
1379
1380 ++SDNodeOrder;
1381 CurInst = &I;
1382
1383 // Set inserted listener only if required.
1384 bool NodeInserted = false;
1385 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1386 MDNode *PCSectionsMD = I.getMetadata(KindID: LLVMContext::MD_pcsections);
1387 MDNode *MMRA = I.getMetadata(KindID: LLVMContext::MD_mmra);
1388 if (PCSectionsMD || MMRA) {
1389 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1390 args&: DAG, args: [&](SDNode *) { NodeInserted = true; });
1391 }
1392
1393 visit(Opcode: I.getOpcode(), I);
1394
1395 if (!I.isTerminator() && !HasTailCall &&
1396 !isa<GCStatepointInst>(Val: I)) // statepoints handle their exports internally
1397 CopyToExportRegsIfNeeded(V: &I);
1398
1399 // Handle metadata.
1400 if (PCSectionsMD || MMRA) {
1401 auto It = NodeMap.find(Val: &I);
1402 if (It != NodeMap.end()) {
1403 if (PCSectionsMD)
1404 DAG.addPCSections(Node: It->second.getNode(), MD: PCSectionsMD);
1405 if (MMRA)
1406 DAG.addMMRAMetadata(Node: It->second.getNode(), MMRA);
1407 } else if (NodeInserted) {
1408 // This should not happen; if it does, don't let it go unnoticed so we can
1409 // fix it. Relevant visit*() function is probably missing a setValue().
1410 errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1411 << I.getModule()->getName() << "]\n";
1412 LLVM_DEBUG(I.dump());
1413 assert(false);
1414 }
1415 }
1416
1417 CurInst = nullptr;
1418}
1419
1420void SelectionDAGBuilder::visitPHI(const PHINode &) {
1421 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1422}
1423
1424void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1425 // Note: this doesn't use InstVisitor, because it has to work with
1426 // ConstantExpr's in addition to instructions.
1427 switch (Opcode) {
1428 default: llvm_unreachable("Unknown instruction type encountered!");
1429 // Build the switch statement using the Instruction.def file.
1430#define HANDLE_INST(NUM, OPCODE, CLASS) \
1431 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1432#include "llvm/IR/Instruction.def"
1433 }
1434}
1435
1436static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1437 DILocalVariable *Variable,
1438 DebugLoc DL, unsigned Order,
1439 SmallVectorImpl<Value *> &Values,
1440 DIExpression *Expression) {
1441 // For variadic dbg_values we will now insert poison.
1442 // FIXME: We can potentially recover these!
1443 SmallVector<SDDbgOperand, 2> Locs;
1444 for (const Value *V : Values) {
1445 auto *Poison = PoisonValue::get(T: V->getType());
1446 Locs.push_back(Elt: SDDbgOperand::fromConst(Const: Poison));
1447 }
1448 SDDbgValue *SDV = DAG.getDbgValueList(Var: Variable, Expr: Expression, Locs, Dependencies: {},
1449 /*IsIndirect=*/false, DL, O: Order,
1450 /*IsVariadic=*/true);
1451 DAG.AddDbgValue(DB: SDV, /*isParameter=*/false);
1452 return true;
1453}
1454
1455void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1456 DILocalVariable *Var,
1457 DIExpression *Expr,
1458 bool IsVariadic, DebugLoc DL,
1459 unsigned Order) {
1460 if (IsVariadic) {
1461 handleDanglingVariadicDebugInfo(DAG, Variable: Var, DL, Order, Values, Expression: Expr);
1462 return;
1463 }
1464 // TODO: Dangling debug info will eventually either be resolved or produce
1465 // a poison DBG_VALUE. However in the resolution case, a gap may appear
1466 // between the original dbg.value location and its resolved DBG_VALUE,
1467 // which we should ideally fill with an extra poison DBG_VALUE.
1468 assert(Values.size() == 1);
1469 DanglingDebugInfoMap[Values[0]].emplace_back(args&: Var, args&: Expr, args&: DL, args&: Order);
1470}
1471
1472void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1473 const DIExpression *Expr) {
1474 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1475 DIVariable *DanglingVariable = DDI.getVariable();
1476 DIExpression *DanglingExpr = DDI.getExpression();
1477 if (DanglingVariable == Variable && Expr->fragmentsOverlap(Other: DanglingExpr)) {
1478 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1479 << printDDI(nullptr, DDI) << "\n");
1480 return true;
1481 }
1482 return false;
1483 };
1484
1485 for (auto &DDIMI : DanglingDebugInfoMap) {
1486 DanglingDebugInfoVector &DDIV = DDIMI.second;
1487
1488 // If debug info is to be dropped, run it through final checks to see
1489 // whether it can be salvaged.
1490 for (auto &DDI : DDIV)
1491 if (isMatchingDbgValue(DDI))
1492 salvageUnresolvedDbgValue(V: DDIMI.first, DDI);
1493
1494 erase_if(C&: DDIV, P: isMatchingDbgValue);
1495 }
1496}
1497
1498// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1499// generate the debug data structures now that we've seen its definition.
1500void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1501 SDValue Val) {
1502 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(Key: V);
1503 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1504 return;
1505
1506 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1507 for (auto &DDI : DDIV) {
1508 DebugLoc DL = DDI.getDebugLoc();
1509 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1510 DILocalVariable *Variable = DDI.getVariable();
1511 DIExpression *Expr = DDI.getExpression();
1512 assert(Variable->isValidLocationForIntrinsic(DL) &&
1513 "Expected inlined-at fields to agree");
1514 SDDbgValue *SDV;
1515 if (Val.getNode()) {
1516 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1517 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1518 // we couldn't resolve it directly when examining the DbgValue intrinsic
1519 // in the first place we should not be more successful here). Unless we
1520 // have some test case that prove this to be correct we should avoid
1521 // calling EmitFuncArgumentDbgValue here.
1522 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1523 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1524 Kind: FuncArgumentDbgValueKind::Value, N: Val)) {
1525 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1526 << printDDI(V, DDI) << "\n");
1527 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1528 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1529 // inserted after the definition of Val when emitting the instructions
1530 // after ISel. An alternative could be to teach
1531 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1532 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1533 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1534 << ValSDNodeOrder << "\n");
1535 SDV = getDbgValue(N: Val, Variable, Expr, dl: DL,
1536 DbgSDNodeOrder: std::max(a: DbgSDNodeOrder, b: ValSDNodeOrder));
1537 DAG.AddDbgValue(DB: SDV, isParameter: false);
1538 } else
1539 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1540 << printDDI(V, DDI)
1541 << " in EmitFuncArgumentDbgValue\n");
1542 } else {
1543 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1544 << "\n");
1545 auto Poison = PoisonValue::get(T: V->getType());
1546 auto SDV =
1547 DAG.getConstantDbgValue(Var: Variable, Expr, C: Poison, DL, O: DbgSDNodeOrder);
1548 DAG.AddDbgValue(DB: SDV, isParameter: false);
1549 }
1550 }
1551 DDIV.clear();
1552}
1553
1554void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1555 DanglingDebugInfo &DDI) {
1556 // TODO: For the variadic implementation, instead of only checking the fail
1557 // state of `handleDebugValue`, we need know specifically which values were
1558 // invalid, so that we attempt to salvage only those values when processing
1559 // a DIArgList.
1560 const Value *OrigV = V;
1561 DILocalVariable *Var = DDI.getVariable();
1562 DIExpression *Expr = DDI.getExpression();
1563 DebugLoc DL = DDI.getDebugLoc();
1564 unsigned SDOrder = DDI.getSDNodeOrder();
1565
1566 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1567 // that DW_OP_stack_value is desired.
1568 bool StackValue = true;
1569
1570 // Can this Value can be encoded without any further work?
1571 if (handleDebugValue(Values: V, Var, Expr, DbgLoc: DL, Order: SDOrder, /*IsVariadic=*/false))
1572 return;
1573
1574 // Attempt to salvage back through as many instructions as possible. Bail if
1575 // a non-instruction is seen, such as a constant expression or global
1576 // variable. FIXME: Further work could recover those too.
1577 while (isa<Instruction>(Val: V)) {
1578 const Instruction &VAsInst = *cast<const Instruction>(Val: V);
1579 // Temporary "0", awaiting real implementation.
1580 SmallVector<uint64_t, 16> Ops;
1581 SmallVector<Value *, 4> AdditionalValues;
1582 V = salvageDebugInfoImpl(I&: const_cast<Instruction &>(VAsInst),
1583 CurrentLocOps: Expr->getNumLocationOperands(), Ops,
1584 AdditionalValues);
1585 // If we cannot salvage any further, and haven't yet found a suitable debug
1586 // expression, bail out.
1587 if (!V)
1588 break;
1589
1590 // TODO: If AdditionalValues isn't empty, then the salvage can only be
1591 // represented with a DBG_VALUE_LIST, so we give up. When we have support
1592 // here for variadic dbg_values, remove that condition.
1593 if (!AdditionalValues.empty())
1594 break;
1595
1596 // New value and expr now represent this debuginfo.
1597 Expr = DIExpression::appendOpsToArg(Expr, Ops, ArgNo: 0, StackValue);
1598
1599 // Some kind of simplification occurred: check whether the operand of the
1600 // salvaged debug expression can be encoded in this DAG.
1601 if (handleDebugValue(Values: V, Var, Expr, DbgLoc: DL, Order: SDOrder, /*IsVariadic=*/false)) {
1602 LLVM_DEBUG(
1603 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n"
1604 << *OrigV << "\nBy stripping back to:\n " << *V << "\n");
1605 return;
1606 }
1607 }
1608
1609 // This was the final opportunity to salvage this debug information, and it
1610 // couldn't be done. Place a poison DBG_VALUE at this location to terminate
1611 // any earlier variable location.
1612 assert(OrigV && "V shouldn't be null");
1613 auto *Poison = PoisonValue::get(T: OrigV->getType());
1614 auto *SDV = DAG.getConstantDbgValue(Var, Expr, C: Poison, DL, O: SDNodeOrder);
1615 DAG.AddDbgValue(DB: SDV, isParameter: false);
1616 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n "
1617 << printDDI(OrigV, DDI) << "\n");
1618}
1619
1620void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1621 DIExpression *Expr,
1622 DebugLoc DbgLoc,
1623 unsigned Order) {
1624 Value *Poison = PoisonValue::get(T: Type::getInt1Ty(C&: *Context));
1625 DIExpression *NewExpr =
1626 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1627 handleDebugValue(Values: Poison, Var, Expr: NewExpr, DbgLoc, Order,
1628 /*IsVariadic*/ false);
1629}
1630
1631bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1632 DILocalVariable *Var,
1633 DIExpression *Expr, DebugLoc DbgLoc,
1634 unsigned Order, bool IsVariadic) {
1635 if (Values.empty())
1636 return true;
1637
1638 // Filter EntryValue locations out early.
1639 if (visitEntryValueDbgValue(Values, Variable: Var, Expr, DbgLoc))
1640 return true;
1641
1642 SmallVector<SDDbgOperand> LocationOps;
1643 SmallVector<SDNode *> Dependencies;
1644 for (const Value *V : Values) {
1645 // Constant value.
1646 if (isa<ConstantInt>(Val: V) || isa<ConstantFP>(Val: V) || isa<UndefValue>(Val: V) ||
1647 isa<ConstantPointerNull>(Val: V)) {
1648 LocationOps.emplace_back(Args: SDDbgOperand::fromConst(Const: V));
1649 continue;
1650 }
1651
1652 // Look through IntToPtr constants.
1653 if (auto *CE = dyn_cast<ConstantExpr>(Val: V))
1654 if (CE->getOpcode() == Instruction::IntToPtr) {
1655 LocationOps.emplace_back(Args: SDDbgOperand::fromConst(Const: CE->getOperand(i_nocapture: 0)));
1656 continue;
1657 }
1658
1659 // If the Value is a frame index, we can create a FrameIndex debug value
1660 // without relying on the DAG at all.
1661 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Val: V)) {
1662 auto SI = FuncInfo.StaticAllocaMap.find(Val: AI);
1663 if (SI != FuncInfo.StaticAllocaMap.end()) {
1664 LocationOps.emplace_back(Args: SDDbgOperand::fromFrameIdx(FrameIdx: SI->second));
1665 continue;
1666 }
1667 }
1668
1669 // Do not use getValue() in here; we don't want to generate code at
1670 // this point if it hasn't been done yet.
1671 SDValue N = NodeMap[V];
1672 if (!N.getNode() && isa<Argument>(Val: V)) // Check unused arguments map.
1673 N = UnusedArgNodeMap[V];
1674
1675 if (N.getNode()) {
1676 // Only emit func arg dbg value for non-variadic dbg.values for now.
1677 if (!IsVariadic &&
1678 EmitFuncArgumentDbgValue(V, Variable: Var, Expr, DL: DbgLoc,
1679 Kind: FuncArgumentDbgValueKind::Value, N))
1680 return true;
1681 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Val: N.getNode())) {
1682 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1683 // describe stack slot locations.
1684 //
1685 // Consider "int x = 0; int *px = &x;". There are two kinds of
1686 // interesting debug values here after optimization:
1687 //
1688 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
1689 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1690 //
1691 // Both describe the direct values of their associated variables.
1692 Dependencies.push_back(Elt: N.getNode());
1693 LocationOps.emplace_back(Args: SDDbgOperand::fromFrameIdx(FrameIdx: FISDN->getIndex()));
1694 continue;
1695 }
1696 LocationOps.emplace_back(
1697 Args: SDDbgOperand::fromNode(Node: N.getNode(), ResNo: N.getResNo()));
1698 continue;
1699 }
1700
1701 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1702 // Special rules apply for the first dbg.values of parameter variables in a
1703 // function. Identify them by the fact they reference Argument Values, that
1704 // they're parameters, and they are parameters of the current function. We
1705 // need to let them dangle until they get an SDNode.
1706 bool IsParamOfFunc =
1707 isa<Argument>(Val: V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1708 if (IsParamOfFunc)
1709 return false;
1710
1711 // The value is not used in this block yet (or it would have an SDNode).
1712 // We still want the value to appear for the user if possible -- if it has
1713 // an associated VReg, we can refer to that instead.
1714 auto VMI = FuncInfo.ValueMap.find(Val: V);
1715 if (VMI != FuncInfo.ValueMap.end()) {
1716 Register Reg = VMI->second;
1717 // If this is a PHI node, it may be split up into several MI PHI nodes
1718 // (in FunctionLoweringInfo::set).
1719 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1720 V->getType(), std::nullopt);
1721 if (RFV.occupiesMultipleRegs()) {
1722 // FIXME: We could potentially support variadic dbg_values here.
1723 if (IsVariadic)
1724 return false;
1725 unsigned Offset = 0;
1726 unsigned BitsToDescribe = 0;
1727 if (auto VarSize = Var->getSizeInBits())
1728 BitsToDescribe = *VarSize;
1729 if (auto Fragment = Expr->getFragmentInfo())
1730 BitsToDescribe = Fragment->SizeInBits;
1731 for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1732 // Bail out if all bits are described already.
1733 if (Offset >= BitsToDescribe)
1734 break;
1735 // TODO: handle scalable vectors.
1736 unsigned RegisterSize = RegAndSize.second;
1737 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1738 ? BitsToDescribe - Offset
1739 : RegisterSize;
1740 auto FragmentExpr = DIExpression::createFragmentExpression(
1741 Expr, OffsetInBits: Offset, SizeInBits: FragmentSize);
1742 if (!FragmentExpr)
1743 continue;
1744 SDDbgValue *SDV = DAG.getVRegDbgValue(
1745 Var, Expr: *FragmentExpr, VReg: RegAndSize.first, IsIndirect: false, DL: DbgLoc, O: Order);
1746 DAG.AddDbgValue(DB: SDV, isParameter: false);
1747 Offset += RegisterSize;
1748 }
1749 return true;
1750 }
1751 // We can use simple vreg locations for variadic dbg_values as well.
1752 LocationOps.emplace_back(Args: SDDbgOperand::fromVReg(VReg: Reg));
1753 continue;
1754 }
1755 // We failed to create a SDDbgOperand for V.
1756 return false;
1757 }
1758
1759 // We have created a SDDbgOperand for each Value in Values.
1760 assert(!LocationOps.empty());
1761 SDDbgValue *SDV =
1762 DAG.getDbgValueList(Var, Expr, Locs: LocationOps, Dependencies,
1763 /*IsIndirect=*/false, DL: DbgLoc, O: Order, IsVariadic);
1764 DAG.AddDbgValue(DB: SDV, /*isParameter=*/false);
1765 return true;
1766}
1767
1768void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1769 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1770 for (auto &Pair : DanglingDebugInfoMap)
1771 for (auto &DDI : Pair.second)
1772 salvageUnresolvedDbgValue(V: const_cast<Value *>(Pair.first), DDI);
1773 clearDanglingDebugInfo();
1774}
1775
1776/// getCopyFromRegs - If there was virtual register allocated for the value V
1777/// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1778SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1779 auto It = FuncInfo.ValueMap.find(Val: V);
1780 SDValue Result;
1781
1782 if (It != FuncInfo.ValueMap.end()) {
1783 Register InReg = It->second;
1784
1785 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1786 DAG.getDataLayout(), InReg, Ty,
1787 std::nullopt); // This is not an ABI copy.
1788 SDValue Chain = DAG.getEntryNode();
1789 Result = RFV.getCopyFromRegs(DAG, FuncInfo, dl: getCurSDLoc(), Chain, Glue: nullptr,
1790 V);
1791 resolveDanglingDebugInfo(V, Val: Result);
1792 }
1793
1794 return Result;
1795}
1796
1797/// getValue - Return an SDValue for the given Value.
1798SDValue SelectionDAGBuilder::getValue(const Value *V) {
1799 // If we already have an SDValue for this value, use it. It's important
1800 // to do this first, so that we don't create a CopyFromReg if we already
1801 // have a regular SDValue.
1802 SDValue &N = NodeMap[V];
1803 if (N.getNode()) return N;
1804
1805 // If there's a virtual register allocated and initialized for this
1806 // value, use it.
1807 if (SDValue copyFromReg = getCopyFromRegs(V, Ty: V->getType()))
1808 return copyFromReg;
1809
1810 // Otherwise create a new SDValue and remember it.
1811 SDValue Val = getValueImpl(V);
1812 NodeMap[V] = Val;
1813 resolveDanglingDebugInfo(V, Val);
1814 return Val;
1815}
1816
1817/// getNonRegisterValue - Return an SDValue for the given Value, but
1818/// don't look in FuncInfo.ValueMap for a virtual register.
1819SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1820 // If we already have an SDValue for this value, use it.
1821 SDValue &N = NodeMap[V];
1822 if (N.getNode()) {
1823 if (isIntOrFPConstant(V: N)) {
1824 // Remove the debug location from the node as the node is about to be used
1825 // in a location which may differ from the original debug location. This
1826 // is relevant to Constant and ConstantFP nodes because they can appear
1827 // as constant expressions inside PHI nodes.
1828 N->setDebugLoc(DebugLoc());
1829 }
1830 return N;
1831 }
1832
1833 // Otherwise create a new SDValue and remember it.
1834 SDValue Val = getValueImpl(V);
1835 NodeMap[V] = Val;
1836 resolveDanglingDebugInfo(V, Val);
1837 return Val;
1838}
1839
1840/// getValueImpl - Helper function for getValue and getNonRegisterValue.
1841/// Create an SDValue for the given value.
1842SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1843 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1844
1845 if (const Constant *C = dyn_cast<Constant>(Val: V)) {
1846 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: V->getType(), AllowUnknown: true);
1847
1848 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: C)) {
1849 SDLoc DL = getCurSDLoc();
1850
1851 // DAG.getConstant() may attempt to legalise the vector constant which can
1852 // significantly change the combines applied to the DAG. To reduce the
1853 // divergence when enabling ConstantInt based vectors we try to construct
1854 // the DAG in the same way as shufflevector based splats. TODO: The
1855 // divergence sometimes leads to better optimisations. Ideally we should
1856 // prevent DAG.getConstant() from legalising too early but there are some
1857 // degradations preventing this.
1858 if (VT.isScalableVector())
1859 return DAG.getNode(
1860 Opcode: ISD::SPLAT_VECTOR, DL, VT,
1861 Operand: DAG.getConstant(Val: CI->getValue(), DL, VT: VT.getVectorElementType()));
1862 if (VT.isFixedLengthVector())
1863 return DAG.getSplatBuildVector(
1864 VT, DL,
1865 Op: DAG.getConstant(Val: CI->getValue(), DL, VT: VT.getVectorElementType()));
1866 return DAG.getConstant(Val: *CI, DL, VT);
1867 }
1868
1869 if (const ConstantByte *CB = dyn_cast<ConstantByte>(Val: C))
1870 return DAG.getConstant(Val: CB->getValue(), DL: getCurSDLoc(), VT);
1871
1872 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Val: C))
1873 return DAG.getGlobalAddress(GV, DL: getCurSDLoc(), VT);
1874
1875 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(Val: C)) {
1876 return DAG.getNode(Opcode: ISD::PtrAuthGlobalAddress, DL: getCurSDLoc(), VT,
1877 N1: getValue(V: CPA->getPointer()), N2: getValue(V: CPA->getKey()),
1878 N3: getValue(V: CPA->getAddrDiscriminator()),
1879 N4: getValue(V: CPA->getDiscriminator()));
1880 }
1881
1882 if (isa<ConstantPointerNull>(Val: C))
1883 return DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT);
1884
1885 if (match(V: C, P: m_VScale()))
1886 return DAG.getVScale(DL: getCurSDLoc(), VT, MulImm: APInt(VT.getSizeInBits(), 1));
1887
1888 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Val: C))
1889 return DAG.getConstantFP(V: *CFP, DL: getCurSDLoc(), VT);
1890
1891 if (isa<UndefValue>(Val: C) && !V->getType()->isAggregateType())
1892 return isa<PoisonValue>(Val: C) ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
1893
1894 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: C)) {
1895 visit(Opcode: CE->getOpcode(), I: *CE);
1896 SDValue N1 = NodeMap[V];
1897 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1898 return N1;
1899 }
1900
1901 if (isa<ConstantStruct>(Val: C) || isa<ConstantArray>(Val: C)) {
1902 SmallVector<SDValue, 4> Constants;
1903 for (const Use &U : C->operands()) {
1904 SDNode *Val = getValue(V: U).getNode();
1905 // If the operand is an empty aggregate, there are no values.
1906 if (!Val) continue;
1907 // Add each leaf value from the operand to the Constants list
1908 // to form a flattened list of all the values.
1909 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1910 Constants.push_back(Elt: SDValue(Val, i));
1911 }
1912
1913 return DAG.getMergeValues(Ops: Constants, dl: getCurSDLoc());
1914 }
1915
1916 if (const ConstantDataSequential *CDS =
1917 dyn_cast<ConstantDataSequential>(Val: C)) {
1918 SmallVector<SDValue, 4> Ops;
1919 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i) {
1920 SDNode *Val = getValue(V: CDS->getElementAsConstant(i)).getNode();
1921 // Add each leaf value from the operand to the Constants list
1922 // to form a flattened list of all the values.
1923 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1924 Ops.push_back(Elt: SDValue(Val, i));
1925 }
1926
1927 if (isa<ArrayType>(Val: CDS->getType()))
1928 return DAG.getMergeValues(Ops, dl: getCurSDLoc());
1929 return DAG.getBuildVector(VT, DL: getCurSDLoc(), Ops);
1930 }
1931
1932 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1933 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1934 "Unknown struct or array constant!");
1935
1936 SmallVector<EVT, 4> ValueVTs;
1937 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: C->getType(), ValueVTs);
1938 unsigned NumElts = ValueVTs.size();
1939 if (NumElts == 0)
1940 return SDValue(); // empty struct
1941 SmallVector<SDValue, 4> Constants(NumElts);
1942 for (unsigned i = 0; i != NumElts; ++i) {
1943 EVT EltVT = ValueVTs[i];
1944 if (isa<UndefValue>(Val: C))
1945 Constants[i] = DAG.getUNDEF(VT: EltVT);
1946 else if (EltVT.isFloatingPoint())
1947 Constants[i] = DAG.getConstantFP(Val: 0, DL: getCurSDLoc(), VT: EltVT);
1948 else
1949 Constants[i] = DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: EltVT);
1950 }
1951
1952 return DAG.getMergeValues(Ops: Constants, dl: getCurSDLoc());
1953 }
1954
1955 if (const BlockAddress *BA = dyn_cast<BlockAddress>(Val: C))
1956 return DAG.getBlockAddress(BA, VT);
1957
1958 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(Val: C))
1959 return getValue(V: Equiv->getGlobalValue());
1960
1961 if (const auto *NC = dyn_cast<NoCFIValue>(Val: C))
1962 return getValue(V: NC->getGlobalValue());
1963
1964 if (VT == MVT::aarch64svcount) {
1965 assert(C->isNullValue() && "Can only zero this target type!");
1966 return DAG.getNode(Opcode: ISD::BITCAST, DL: getCurSDLoc(), VT,
1967 Operand: DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: MVT::nxv16i1));
1968 }
1969
1970 if (VT.isRISCVVectorTuple()) {
1971 assert(C->isNullValue() && "Can only zero this target type!");
1972 return DAG.getNode(
1973 Opcode: ISD::BITCAST, DL: getCurSDLoc(), VT,
1974 Operand: DAG.getNode(
1975 Opcode: ISD::SPLAT_VECTOR, DL: getCurSDLoc(),
1976 VT: EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::i8,
1977 NumElements: VT.getSizeInBits().getKnownMinValue() / 8, IsScalable: true),
1978 Operand: DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: MVT::getIntegerVT(BitWidth: 8))));
1979 }
1980
1981 if (VT == MVT::externref || VT == MVT::funcref) {
1982 assert(C->isNullValue() && "Can only zero this target type!");
1983 // The zero value of a WebAssembly reference type is the null reference,
1984 // materialized with ref.null.
1985 Intrinsic::ID IID = VT == MVT::externref ? Intrinsic::wasm_ref_null_extern
1986 : Intrinsic::wasm_ref_null_func;
1987 return DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: getCurSDLoc(), VT,
1988 Operand: DAG.getTargetConstant(Val: IID, DL: getCurSDLoc(), VT: MVT::i32));
1989 }
1990
1991 VectorType *VecTy = cast<VectorType>(Val: V->getType());
1992
1993 // Now that we know the number and type of the elements, get that number of
1994 // elements into the Ops array based on what kind of constant it is.
1995 if (const ConstantVector *CV = dyn_cast<ConstantVector>(Val: C)) {
1996 SmallVector<SDValue, 16> Ops;
1997 unsigned NumElements = cast<FixedVectorType>(Val: VecTy)->getNumElements();
1998 for (unsigned i = 0; i != NumElements; ++i)
1999 Ops.push_back(Elt: getValue(V: CV->getOperand(i_nocapture: i)));
2000
2001 return DAG.getBuildVector(VT, DL: getCurSDLoc(), Ops);
2002 }
2003
2004 if (isa<ConstantAggregateZero>(Val: C)) {
2005 EVT EltVT =
2006 TLI.getValueType(DL: DAG.getDataLayout(), Ty: VecTy->getElementType());
2007
2008 SDValue Op;
2009 if (EltVT.isFloatingPoint())
2010 Op = DAG.getConstantFP(Val: 0, DL: getCurSDLoc(), VT: EltVT);
2011 else
2012 Op = DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: EltVT);
2013
2014 return DAG.getSplat(VT, DL: getCurSDLoc(), Op);
2015 }
2016
2017 llvm_unreachable("Unknown vector constant");
2018 }
2019
2020 // If this is a static alloca, generate it as the frameindex instead of
2021 // computation.
2022 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Val: V)) {
2023 auto SI = FuncInfo.StaticAllocaMap.find(Val: AI);
2024 if (SI != FuncInfo.StaticAllocaMap.end())
2025 return DAG.getFrameIndex(
2026 FI: SI->second, VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: AI->getType()));
2027 }
2028
2029 // If this is an instruction which fast-isel has deferred, select it now.
2030 if (const Instruction *Inst = dyn_cast<Instruction>(Val: V)) {
2031 Register InReg = FuncInfo.InitializeRegForValue(V: Inst);
2032 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
2033 Inst->getType(), std::nullopt);
2034 SDValue Chain = DAG.getEntryNode();
2035 return RFV.getCopyFromRegs(DAG, FuncInfo, dl: getCurSDLoc(), Chain, Glue: nullptr, V);
2036 }
2037
2038 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(Val: V))
2039 return DAG.getMDNode(MD: cast<MDNode>(Val: MD->getMetadata()));
2040
2041 if (const auto *BB = dyn_cast<BasicBlock>(Val: V))
2042 return DAG.getBasicBlock(MBB: FuncInfo.getMBB(BB));
2043
2044 llvm_unreachable("Can't get register for value!");
2045}
2046
2047void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
2048 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2049 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
2050 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
2051 bool IsSEH = isAsynchronousEHPersonality(Pers);
2052 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
2053 if (IsSEH) {
2054 // For SEH, EHCont Guard needs to know that this catchpad is a target.
2055 CatchPadMBB->setIsEHContTarget(true);
2056 DAG.getMachineFunction().setHasEHContTarget(true);
2057 } else
2058 CatchPadMBB->setIsEHScopeEntry();
2059 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
2060 if (IsMSVCCXX || IsCoreCLR)
2061 CatchPadMBB->setIsEHFuncletEntry();
2062}
2063
2064void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
2065 // Update machine-CFG edge.
2066 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(BB: I.getSuccessor());
2067 FuncInfo.MBB->addSuccessor(Succ: TargetMBB);
2068
2069 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2070 bool IsSEH = isAsynchronousEHPersonality(Pers);
2071 if (IsSEH) {
2072 // If this is not a fall-through branch or optimizations are switched off,
2073 // emit the branch.
2074 if (TargetMBB != NextBlock(MBB: FuncInfo.MBB) ||
2075 TM.getOptLevel() == CodeGenOptLevel::None)
2076 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other,
2077 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: TargetMBB)));
2078 return;
2079 }
2080
2081 // For non-SEH, EHCont Guard needs to know that this catchret is a target.
2082 TargetMBB->setIsEHContTarget(true);
2083 DAG.getMachineFunction().setHasEHContTarget(true);
2084
2085 // Figure out the funclet membership for the catchret's successor.
2086 // This will be used by the FuncletLayout pass to determine how to order the
2087 // BB's.
2088 // A 'catchret' returns to the outer scope's color.
2089 Value *ParentPad = I.getCatchSwitchParentPad();
2090 const BasicBlock *SuccessorColor;
2091 if (isa<ConstantTokenNone>(Val: ParentPad))
2092 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2093 else
2094 SuccessorColor = cast<Instruction>(Val: ParentPad)->getParent();
2095 assert(SuccessorColor && "No parent funclet for catchret!");
2096 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(BB: SuccessorColor);
2097 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2098
2099 // Create the terminator node.
2100 SDValue Ret = DAG.getNode(Opcode: ISD::CATCHRET, DL: getCurSDLoc(), VT: MVT::Other,
2101 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: TargetMBB),
2102 N3: DAG.getBasicBlock(MBB: SuccessorColorMBB));
2103 DAG.setRoot(Ret);
2104}
2105
2106void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2107 // Don't emit any special code for the cleanuppad instruction. It just marks
2108 // the start of an EH scope/funclet.
2109 FuncInfo.MBB->setIsEHScopeEntry();
2110 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2111 if (Pers != EHPersonality::Wasm_CXX) {
2112 FuncInfo.MBB->setIsEHFuncletEntry();
2113 FuncInfo.MBB->setIsCleanupFuncletEntry();
2114 }
2115}
2116
2117/// When an invoke or a cleanupret unwinds to the next EH pad, there are
2118/// many places it could ultimately go. In the IR, we have a single unwind
2119/// destination, but in the machine CFG, we enumerate all the possible blocks.
2120/// This function skips over imaginary basic blocks that hold catchswitch
2121/// instructions, and finds all the "real" machine
2122/// basic block destinations. As those destinations may not be successors of
2123/// EHPadBB, here we also calculate the edge probability to those destinations.
2124/// The passed-in Prob is the edge probability to EHPadBB.
2125static void findUnwindDestinations(
2126 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2127 BranchProbability Prob,
2128 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2129 &UnwindDests) {
2130 EHPersonality Personality =
2131 classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2132 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2133 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2134 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2135 bool IsSEH = isAsynchronousEHPersonality(Pers: Personality);
2136
2137 while (EHPadBB) {
2138 BasicBlock::const_iterator Pad = EHPadBB->getFirstNonPHIIt();
2139 BasicBlock *NewEHPadBB = nullptr;
2140 if (isa<LandingPadInst>(Val: Pad)) {
2141 // Stop on landingpads. They are not funclets.
2142 UnwindDests.emplace_back(Args: FuncInfo.getMBB(BB: EHPadBB), Args&: Prob);
2143 break;
2144 } else if (isa<CleanupPadInst>(Val: Pad)) {
2145 // Stop on cleanup pads. Cleanups are always funclet entries for all known
2146 // personalities except Wasm. And in Wasm this becomes a catch_all(_ref),
2147 // which always catches an exception.
2148 UnwindDests.emplace_back(Args: FuncInfo.getMBB(BB: EHPadBB), Args&: Prob);
2149 UnwindDests.back().first->setIsEHScopeEntry();
2150 // In Wasm, EH scopes are not funclets
2151 if (!IsWasmCXX)
2152 UnwindDests.back().first->setIsEHFuncletEntry();
2153 break;
2154 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Val&: Pad)) {
2155 // Add the catchpad handlers to the possible destinations.
2156 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2157 UnwindDests.emplace_back(Args: FuncInfo.getMBB(BB: CatchPadBB), Args&: Prob);
2158 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2159 if (IsMSVCCXX || IsCoreCLR)
2160 UnwindDests.back().first->setIsEHFuncletEntry();
2161 if (!IsSEH)
2162 UnwindDests.back().first->setIsEHScopeEntry();
2163 }
2164 NewEHPadBB = CatchSwitch->getUnwindDest();
2165 } else {
2166 continue;
2167 }
2168
2169 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2170 if (BPI && NewEHPadBB)
2171 Prob *= BPI->getEdgeProbability(Src: EHPadBB, Dst: NewEHPadBB);
2172 EHPadBB = NewEHPadBB;
2173 }
2174}
2175
2176void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2177 // Update successor info.
2178 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2179 auto UnwindDest = I.getUnwindDest();
2180 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2181 BranchProbability UnwindDestProb =
2182 (BPI && UnwindDest)
2183 ? BPI->getEdgeProbability(Src: FuncInfo.MBB->getBasicBlock(), Dst: UnwindDest)
2184 : BranchProbability::getZero();
2185 findUnwindDestinations(FuncInfo, EHPadBB: UnwindDest, Prob: UnwindDestProb, UnwindDests);
2186 for (auto &UnwindDest : UnwindDests) {
2187 UnwindDest.first->setIsEHPad();
2188 addSuccessorWithProb(Src: FuncInfo.MBB, Dst: UnwindDest.first, Prob: UnwindDest.second);
2189 }
2190 FuncInfo.MBB->normalizeSuccProbs();
2191
2192 // Create the terminator node.
2193 MachineBasicBlock *CleanupPadMBB =
2194 FuncInfo.getMBB(BB: I.getCleanupPad()->getParent());
2195 SDValue Ret = DAG.getNode(Opcode: ISD::CLEANUPRET, DL: getCurSDLoc(), VT: MVT::Other,
2196 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: CleanupPadMBB));
2197 DAG.setRoot(Ret);
2198}
2199
2200void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2201 report_fatal_error(reason: "visitCatchSwitch not yet implemented!");
2202}
2203
2204void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2205 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2206 auto &DL = DAG.getDataLayout();
2207 SDValue Chain = getControlRoot();
2208 SmallVector<ISD::OutputArg, 8> Outs;
2209 SmallVector<SDValue, 8> OutVals;
2210
2211 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2212 // lower
2213 //
2214 // %val = call <ty> @llvm.experimental.deoptimize()
2215 // ret <ty> %val
2216 //
2217 // differently.
2218 if (I.getParent()->getTerminatingDeoptimizeCall()) {
2219 LowerDeoptimizingReturn();
2220 return;
2221 }
2222
2223 if (!FuncInfo.CanLowerReturn) {
2224 Register DemoteReg = FuncInfo.DemoteRegister;
2225
2226 // Emit a store of the return value through the virtual register.
2227 // Leave Outs empty so that LowerReturn won't try to load return
2228 // registers the usual way.
2229 MVT PtrValueVT = TLI.getPointerTy(DL, AS: DL.getAllocaAddrSpace());
2230 SDValue RetPtr =
2231 DAG.getCopyFromReg(Chain, dl: getCurSDLoc(), Reg: DemoteReg, VT: PtrValueVT);
2232 SDValue RetOp = getValue(V: I.getOperand(i_nocapture: 0));
2233
2234 SmallVector<EVT, 4> ValueVTs, MemVTs;
2235 SmallVector<uint64_t, 4> Offsets;
2236 ComputeValueVTs(TLI, DL, Ty: I.getOperand(i_nocapture: 0)->getType(), ValueVTs, MemVTs: &MemVTs,
2237 FixedOffsets: &Offsets, StartingOffset: 0);
2238 unsigned NumValues = ValueVTs.size();
2239
2240 SmallVector<SDValue, 4> Chains(NumValues);
2241 Align BaseAlign = DL.getPrefTypeAlign(Ty: I.getOperand(i_nocapture: 0)->getType());
2242 for (unsigned i = 0; i != NumValues; ++i) {
2243 // An aggregate return value cannot wrap around the address space, so
2244 // offsets to its parts don't wrap either.
2245 SDValue Ptr = DAG.getObjectPtrOffset(SL: getCurSDLoc(), Ptr: RetPtr,
2246 Offset: TypeSize::getFixed(ExactSize: Offsets[i]));
2247
2248 SDValue Val = RetOp.getValue(R: RetOp.getResNo() + i);
2249 if (MemVTs[i] != ValueVTs[i])
2250 Val = DAG.getPtrExtOrTrunc(Op: Val, DL: getCurSDLoc(), VT: MemVTs[i]);
2251 Chains[i] = DAG.getStore(
2252 Chain, dl: getCurSDLoc(), Val,
2253 // FIXME: better loc info would be nice.
2254 Ptr, PtrInfo: MachinePointerInfo::getUnknownStack(MF&: DAG.getMachineFunction()),
2255 Alignment: commonAlignment(A: BaseAlign, Offset: Offsets[i]));
2256 }
2257
2258 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: getCurSDLoc(),
2259 VT: MVT::Other, Ops: Chains);
2260 } else if (I.getNumOperands() != 0) {
2261 SmallVector<Type *, 4> Types;
2262 ComputeValueTypes(DL, Ty: I.getOperand(i_nocapture: 0)->getType(), Types);
2263 unsigned NumValues = Types.size();
2264 if (NumValues) {
2265 SDValue RetOp = getValue(V: I.getOperand(i_nocapture: 0));
2266
2267 const Function *F = I.getParent()->getParent();
2268
2269 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2270 Ty: I.getOperand(i_nocapture: 0)->getType(), CallConv: F->getCallingConv(),
2271 /*IsVarArg*/ isVarArg: false, DL);
2272
2273 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2274 if (F->getAttributes().hasRetAttr(Kind: Attribute::SExt))
2275 ExtendKind = ISD::SIGN_EXTEND;
2276 else if (F->getAttributes().hasRetAttr(Kind: Attribute::ZExt))
2277 ExtendKind = ISD::ZERO_EXTEND;
2278
2279 LLVMContext &Context = F->getContext();
2280 bool RetInReg = F->getAttributes().hasRetAttr(Kind: Attribute::InReg);
2281
2282 for (unsigned j = 0; j != NumValues; ++j) {
2283 EVT VT = TLI.getValueType(DL, Ty: Types[j]);
2284
2285 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2286 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2287
2288 CallingConv::ID CC = F->getCallingConv();
2289
2290 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2291 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2292 SmallVector<SDValue, 4> Parts(NumParts);
2293 getCopyToParts(DAG, DL: getCurSDLoc(),
2294 Val: SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2295 Parts: &Parts[0], NumParts, PartVT, V: &I, CallConv: CC, ExtendKind);
2296
2297 // 'inreg' on function refers to return value
2298 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2299 if (RetInReg)
2300 Flags.setInReg();
2301
2302 if (I.getOperand(i_nocapture: 0)->getType()->isPointerTy()) {
2303 Flags.setPointer();
2304 Flags.setPointerAddrSpace(
2305 cast<PointerType>(Val: I.getOperand(i_nocapture: 0)->getType())->getAddressSpace());
2306 }
2307
2308 if (NeedsRegBlock) {
2309 Flags.setInConsecutiveRegs();
2310 if (j == NumValues - 1)
2311 Flags.setInConsecutiveRegsLast();
2312 }
2313
2314 // Propagate extension type if any
2315 if (ExtendKind == ISD::SIGN_EXTEND)
2316 Flags.setSExt();
2317 else if (ExtendKind == ISD::ZERO_EXTEND)
2318 Flags.setZExt();
2319 else if (F->getAttributes().hasRetAttr(Kind: Attribute::NoExt))
2320 Flags.setNoExt();
2321
2322 for (unsigned i = 0; i < NumParts; ++i) {
2323 Outs.push_back(Elt: ISD::OutputArg(Flags,
2324 Parts[i].getValueType().getSimpleVT(),
2325 VT, Types[j], 0, 0));
2326 OutVals.push_back(Elt: Parts[i]);
2327 }
2328 }
2329 }
2330 }
2331
2332 // Push in swifterror virtual register as the last element of Outs. This makes
2333 // sure swifterror virtual register will be returned in the swifterror
2334 // physical register.
2335 const Function *F = I.getParent()->getParent();
2336 if (TLI.supportSwiftError() &&
2337 F->getAttributes().hasAttrSomewhere(Kind: Attribute::SwiftError)) {
2338 assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2339 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2340 Flags.setSwiftError();
2341 Outs.push_back(Elt: ISD::OutputArg(Flags, /*vt=*/TLI.getPointerTy(DL),
2342 /*argvt=*/EVT(TLI.getPointerTy(DL)),
2343 PointerType::getUnqual(C&: *DAG.getContext()),
2344 /*origidx=*/1, /*partOffs=*/0));
2345 // Create SDNode for the swifterror virtual register.
2346 OutVals.push_back(
2347 Elt: DAG.getRegister(Reg: SwiftError.getOrCreateVRegUseAt(
2348 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2349 VT: EVT(TLI.getPointerTy(DL))));
2350 }
2351
2352 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2353 CallingConv::ID CallConv =
2354 DAG.getMachineFunction().getFunction().getCallingConv();
2355 Chain = DAG.getTargetLoweringInfo().LowerReturn(
2356 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2357
2358 // Verify that the target's LowerReturn behaved as expected.
2359 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2360 "LowerReturn didn't return a valid chain!");
2361
2362 // Update the DAG with the new chain value resulting from return lowering.
2363 DAG.setRoot(Chain);
2364}
2365
2366/// CopyToExportRegsIfNeeded - If the given value has virtual registers
2367/// created for it, emit nodes to copy the value into the virtual
2368/// registers.
2369void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2370 // Skip empty types
2371 if (V->getType()->isEmptyTy())
2372 return;
2373
2374 auto VMI = FuncInfo.ValueMap.find(Val: V);
2375 if (VMI != FuncInfo.ValueMap.end()) {
2376 assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2377 "Unused value assigned virtual registers!");
2378 CopyValueToVirtualRegister(V, Reg: VMI->second);
2379 }
2380}
2381
2382/// ExportFromCurrentBlock - If this condition isn't known to be exported from
2383/// the current basic block, add it to ValueMap now so that we'll get a
2384/// CopyTo/FromReg.
2385void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2386 // No need to export constants.
2387 if (!isa<Instruction>(Val: V) && !isa<Argument>(Val: V)) return;
2388
2389 // Already exported?
2390 if (FuncInfo.isExportedInst(V)) return;
2391
2392 Register Reg = FuncInfo.InitializeRegForValue(V);
2393 CopyValueToVirtualRegister(V, Reg);
2394}
2395
2396bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2397 const BasicBlock *FromBB) {
2398 // The operands of the setcc have to be in this block. We don't know
2399 // how to export them from some other block.
2400 if (const Instruction *VI = dyn_cast<Instruction>(Val: V)) {
2401 // Can export from current BB.
2402 if (VI->getParent() == FromBB)
2403 return true;
2404
2405 // Is already exported, noop.
2406 return FuncInfo.isExportedInst(V);
2407 }
2408
2409 // If this is an argument, we can export it if the BB is the entry block or
2410 // if it is already exported.
2411 if (isa<Argument>(Val: V)) {
2412 if (FromBB->isEntryBlock())
2413 return true;
2414
2415 // Otherwise, can only export this if it is already exported.
2416 return FuncInfo.isExportedInst(V);
2417 }
2418
2419 // Otherwise, constants can always be exported.
2420 return true;
2421}
2422
2423/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2424BranchProbability
2425SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2426 const MachineBasicBlock *Dst) const {
2427 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2428 const BasicBlock *SrcBB = Src->getBasicBlock();
2429 const BasicBlock *DstBB = Dst->getBasicBlock();
2430 if (!BPI) {
2431 // If BPI is not available, set the default probability as 1 / N, where N is
2432 // the number of successors.
2433 auto SuccSize = std::max<uint32_t>(a: succ_size(BB: SrcBB), b: 1);
2434 return BranchProbability(1, SuccSize);
2435 }
2436 return BPI->getEdgeProbability(Src: SrcBB, Dst: DstBB);
2437}
2438
2439void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2440 MachineBasicBlock *Dst,
2441 BranchProbability Prob) {
2442 if (!FuncInfo.BPI)
2443 Src->addSuccessorWithoutProb(Succ: Dst);
2444 else {
2445 if (Prob.isUnknown())
2446 Prob = getEdgeProbability(Src, Dst);
2447 Src->addSuccessor(Succ: Dst, Prob);
2448 }
2449}
2450
2451static bool InBlock(const Value *V, const BasicBlock *BB) {
2452 if (const Instruction *I = dyn_cast<Instruction>(Val: V))
2453 return I->getParent() == BB;
2454 return true;
2455}
2456
2457/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2458/// This function emits a branch and is used at the leaves of an OR or an
2459/// AND operator tree.
2460void
2461SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2462 MachineBasicBlock *TBB,
2463 MachineBasicBlock *FBB,
2464 MachineBasicBlock *CurBB,
2465 MachineBasicBlock *SwitchBB,
2466 BranchProbability TProb,
2467 BranchProbability FProb,
2468 bool InvertCond) {
2469 const BasicBlock *BB = CurBB->getBasicBlock();
2470
2471 // If the leaf of the tree is a comparison, merge the condition into
2472 // the caseblock.
2473 if (const CmpInst *BOp = dyn_cast<CmpInst>(Val: Cond)) {
2474 // The operands of the cmp have to be in this block. We don't know
2475 // how to export them from some other block. If this is the first block
2476 // of the sequence, no exporting is needed.
2477 if (CurBB == SwitchBB ||
2478 (isExportableFromCurrentBlock(V: BOp->getOperand(i_nocapture: 0), FromBB: BB) &&
2479 isExportableFromCurrentBlock(V: BOp->getOperand(i_nocapture: 1), FromBB: BB))) {
2480 ISD::CondCode Condition;
2481 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Val: Cond)) {
2482 ICmpInst::Predicate Pred =
2483 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2484 Condition = getICmpCondCode(Pred);
2485 } else {
2486 const FCmpInst *FC = cast<FCmpInst>(Val: Cond);
2487 FCmpInst::Predicate Pred =
2488 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2489 Condition = getFCmpCondCode(Pred);
2490 if (FC->hasNoNaNs() ||
2491 (isKnownNeverNaN(V: FC->getOperand(i_nocapture: 0),
2492 SQ: SimplifyQuery(DAG.getDataLayout(), FC)) &&
2493 isKnownNeverNaN(V: FC->getOperand(i_nocapture: 1),
2494 SQ: SimplifyQuery(DAG.getDataLayout(), FC))))
2495 Condition = getFCmpCodeWithoutNaN(CC: Condition);
2496 }
2497
2498 CaseBlock CB(Condition, BOp->getOperand(i_nocapture: 0), BOp->getOperand(i_nocapture: 1), nullptr,
2499 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2500 SL->SwitchCases.push_back(x: CB);
2501 return;
2502 }
2503 }
2504
2505 // Create a CaseBlock record representing this branch.
2506 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2507 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(Context&: *DAG.getContext()),
2508 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2509 SL->SwitchCases.push_back(x: CB);
2510}
2511
2512// Collect dependencies on V recursively. This is used for the cost analysis in
2513// `shouldKeepJumpConditionsTogether`.
2514static bool collectInstructionDeps(
2515 SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2516 SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2517 unsigned Depth = 0) {
2518 // Return false if we have an incomplete count.
2519 if (Depth >= SelectionDAG::MaxRecursionDepth)
2520 return false;
2521
2522 auto *I = dyn_cast<Instruction>(Val: V);
2523 if (I == nullptr)
2524 return true;
2525
2526 if (Necessary != nullptr) {
2527 // This instruction is necessary for the other side of the condition so
2528 // don't count it.
2529 if (Necessary->contains(Key: I))
2530 return true;
2531 }
2532
2533 // Already added this dep.
2534 if (!Deps->try_emplace(Key: I, Args: false).second)
2535 return true;
2536
2537 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2538 if (!collectInstructionDeps(Deps, V: I->getOperand(i: OpIdx), Necessary,
2539 Depth: Depth + 1))
2540 return false;
2541 return true;
2542}
2543
2544bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2545 const FunctionLoweringInfo &FuncInfo, const CondBrInst &I,
2546 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2547 TargetLoweringBase::CondMergingParams Params) const {
2548 if (Params.BaseCost < 0)
2549 return false;
2550
2551 // Baseline cost.
2552 InstructionCost CostThresh = Params.BaseCost;
2553
2554 BranchProbabilityInfo *BPI = nullptr;
2555 if (Params.LikelyBias || Params.UnlikelyBias)
2556 BPI = FuncInfo.BPI;
2557 if (BPI != nullptr) {
2558 // See if we are either likely to get an early out or compute both lhs/rhs
2559 // of the condition.
2560 BasicBlock *IfFalse = I.getSuccessor(i: 0);
2561 BasicBlock *IfTrue = I.getSuccessor(i: 1);
2562
2563 std::optional<bool> Likely;
2564 if (BPI->isEdgeHot(Src: I.getParent(), Dst: IfTrue))
2565 Likely = true;
2566 else if (BPI->isEdgeHot(Src: I.getParent(), Dst: IfFalse))
2567 Likely = false;
2568
2569 if (Likely) {
2570 if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2571 // Its likely we will have to compute both lhs and rhs of condition
2572 CostThresh += Params.LikelyBias;
2573 else {
2574 if (Params.UnlikelyBias < 0)
2575 return false;
2576 // Its likely we will get an early out.
2577 CostThresh -= Params.UnlikelyBias;
2578 }
2579 }
2580 }
2581
2582 if (CostThresh <= 0)
2583 return false;
2584
2585 // Collect "all" instructions that lhs condition is dependent on.
2586 // Use map for stable iteration (to avoid non-determanism of iteration of
2587 // SmallPtrSet). The `bool` value is just a dummy.
2588 SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2589 collectInstructionDeps(Deps: &LhsDeps, V: Lhs);
2590 // Collect "all" instructions that rhs condition is dependent on AND are
2591 // dependencies of lhs. This gives us an estimate on which instructions we
2592 // stand to save by splitting the condition.
2593 if (!collectInstructionDeps(Deps: &RhsDeps, V: Rhs, Necessary: &LhsDeps))
2594 return false;
2595 // Add the compare instruction itself unless its a dependency on the LHS.
2596 if (const auto *RhsI = dyn_cast<Instruction>(Val: Rhs))
2597 if (!LhsDeps.contains(Key: RhsI))
2598 RhsDeps.try_emplace(Key: RhsI, Args: false);
2599
2600 InstructionCost CostOfIncluding = 0;
2601 // See if this instruction will need to computed independently of whether RHS
2602 // is.
2603 Value *BrCond = I.getCondition();
2604 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2605 for (const auto *U : Ins->users()) {
2606 // If user is independent of RHS calculation we don't need to count it.
2607 if (auto *UIns = dyn_cast<Instruction>(Val: U))
2608 if (UIns != BrCond && !RhsDeps.contains(Key: UIns))
2609 return false;
2610 }
2611 return true;
2612 };
2613
2614 // Prune instructions from RHS Deps that are dependencies of unrelated
2615 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2616 // arbitrary and just meant to cap the how much time we spend in the pruning
2617 // loop. Its highly unlikely to come into affect.
2618 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2619 // Stop after a certain point. No incorrectness from including too many
2620 // instructions.
2621 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2622 const Instruction *ToDrop = nullptr;
2623 for (const auto &InsPair : RhsDeps) {
2624 if (!ShouldCountInsn(InsPair.first)) {
2625 ToDrop = InsPair.first;
2626 break;
2627 }
2628 }
2629 if (ToDrop == nullptr)
2630 break;
2631 RhsDeps.erase(Key: ToDrop);
2632 }
2633
2634 for (const auto &InsPair : RhsDeps) {
2635 // Finally accumulate latency that we can only attribute to computing the
2636 // RHS condition. Use latency because we are essentially trying to calculate
2637 // the cost of the dependency chain.
2638 // Possible TODO: We could try to estimate ILP and make this more precise.
2639 CostOfIncluding += TTI->getInstructionCost(
2640 U: InsPair.first, CostKind: TargetTransformInfo::TCK_Latency);
2641
2642 if (CostOfIncluding > CostThresh)
2643 return false;
2644 }
2645 return true;
2646}
2647
2648void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2649 MachineBasicBlock *TBB,
2650 MachineBasicBlock *FBB,
2651 MachineBasicBlock *CurBB,
2652 MachineBasicBlock *SwitchBB,
2653 Instruction::BinaryOps Opc,
2654 BranchProbability TProb,
2655 BranchProbability FProb,
2656 bool InvertCond) {
2657 // Skip over not part of the tree and remember to invert op and operands at
2658 // next level.
2659 Value *NotCond;
2660 if (match(V: Cond, P: m_OneUse(SubPattern: m_Not(V: m_Value(V&: NotCond)))) &&
2661 InBlock(V: NotCond, BB: CurBB->getBasicBlock())) {
2662 FindMergedConditions(Cond: NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2663 InvertCond: !InvertCond);
2664 return;
2665 }
2666
2667 const Instruction *BOp = dyn_cast<Instruction>(Val: Cond);
2668 const Value *BOpOp0, *BOpOp1;
2669 // Compute the effective opcode for Cond, taking into account whether it needs
2670 // to be inverted, e.g.
2671 // and (not (or A, B)), C
2672 // gets lowered as
2673 // and (and (not A, not B), C)
2674 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2675 if (BOp) {
2676 BOpc = match(V: BOp, P: m_LogicalAnd(L: m_Value(V&: BOpOp0), R: m_Value(V&: BOpOp1)))
2677 ? Instruction::And
2678 : (match(V: BOp, P: m_LogicalOr(L: m_Value(V&: BOpOp0), R: m_Value(V&: BOpOp1)))
2679 ? Instruction::Or
2680 : (Instruction::BinaryOps)0);
2681 if (InvertCond) {
2682 if (BOpc == Instruction::And)
2683 BOpc = Instruction::Or;
2684 else if (BOpc == Instruction::Or)
2685 BOpc = Instruction::And;
2686 }
2687 }
2688
2689 // If this node is not part of the or/and tree, emit it as a branch.
2690 // Note that all nodes in the tree should have same opcode.
2691 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2692 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2693 !InBlock(V: BOpOp0, BB: CurBB->getBasicBlock()) ||
2694 !InBlock(V: BOpOp1, BB: CurBB->getBasicBlock())) {
2695 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2696 TProb, FProb, InvertCond);
2697 return;
2698 }
2699
2700 // Create TmpBB after CurBB.
2701 MachineFunction::iterator BBI(CurBB);
2702 MachineFunction &MF = DAG.getMachineFunction();
2703 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(BB: CurBB->getBasicBlock());
2704 CurBB->getParent()->insert(MBBI: ++BBI, MBB: TmpBB);
2705
2706 if (Opc == Instruction::Or) {
2707 // Codegen X | Y as:
2708 // BB1:
2709 // jmp_if_X TBB
2710 // jmp TmpBB
2711 // TmpBB:
2712 // jmp_if_Y TBB
2713 // jmp FBB
2714 //
2715
2716 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2717 // The requirement is that
2718 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2719 // = TrueProb for original BB.
2720 // Assuming the original probabilities are A and B, one choice is to set
2721 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2722 // A/(1+B) and 2B/(1+B). This choice assumes that
2723 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2724 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2725 // TmpBB, but the math is more complicated.
2726
2727 auto NewTrueProb = TProb / 2;
2728 auto NewFalseProb = TProb / 2 + FProb;
2729 // Emit the LHS condition.
2730 FindMergedConditions(Cond: BOpOp0, TBB, FBB: TmpBB, CurBB, SwitchBB, Opc, TProb: NewTrueProb,
2731 FProb: NewFalseProb, InvertCond);
2732
2733 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2734 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2735 BranchProbability::normalizeProbabilities(Begin: Probs.begin(), End: Probs.end());
2736 // Emit the RHS condition into TmpBB.
2737 FindMergedConditions(Cond: BOpOp1, TBB, FBB, CurBB: TmpBB, SwitchBB, Opc, TProb: Probs[0],
2738 FProb: Probs[1], InvertCond);
2739 } else {
2740 assert(Opc == Instruction::And && "Unknown merge op!");
2741 // Codegen X & Y as:
2742 // BB1:
2743 // jmp_if_X TmpBB
2744 // jmp FBB
2745 // TmpBB:
2746 // jmp_if_Y TBB
2747 // jmp FBB
2748 //
2749 // This requires creation of TmpBB after CurBB.
2750
2751 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2752 // The requirement is that
2753 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2754 // = FalseProb for original BB.
2755 // Assuming the original probabilities are A and B, one choice is to set
2756 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2757 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2758 // TrueProb for BB1 * FalseProb for TmpBB.
2759
2760 auto NewTrueProb = TProb + FProb / 2;
2761 auto NewFalseProb = FProb / 2;
2762 // Emit the LHS condition.
2763 FindMergedConditions(Cond: BOpOp0, TBB: TmpBB, FBB, CurBB, SwitchBB, Opc, TProb: NewTrueProb,
2764 FProb: NewFalseProb, InvertCond);
2765
2766 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2767 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2768 BranchProbability::normalizeProbabilities(Begin: Probs.begin(), End: Probs.end());
2769 // Emit the RHS condition into TmpBB.
2770 FindMergedConditions(Cond: BOpOp1, TBB, FBB, CurBB: TmpBB, SwitchBB, Opc, TProb: Probs[0],
2771 FProb: Probs[1], InvertCond);
2772 }
2773}
2774
2775/// If the set of cases should be emitted as a series of branches, return true.
2776/// If we should emit this as a bunch of and/or'd together conditions, return
2777/// false.
2778bool
2779SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2780 if (Cases.size() != 2) return true;
2781
2782 // If this is two comparisons of the same values or'd or and'd together, they
2783 // will get folded into a single comparison, so don't emit two blocks.
2784 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2785 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2786 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2787 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2788 return false;
2789 }
2790
2791 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2792 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2793 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2794 Cases[0].CC == Cases[1].CC &&
2795 isa<Constant>(Val: Cases[0].CmpRHS) &&
2796 cast<Constant>(Val: Cases[0].CmpRHS)->isNullValue()) {
2797 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2798 return false;
2799 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2800 return false;
2801 }
2802
2803 return true;
2804}
2805
2806void SelectionDAGBuilder::visitUncondBr(const UncondBrInst &I) {
2807 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2808
2809 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(BB: I.getSuccessor(i: 0));
2810
2811 // Update machine-CFG edges.
2812 BrMBB->addSuccessor(Succ: Succ0MBB);
2813
2814 // If this is not a fall-through branch or optimizations are switched off,
2815 // emit the branch.
2816 if (Succ0MBB != NextBlock(MBB: BrMBB) ||
2817 TM.getOptLevel() == CodeGenOptLevel::None) {
2818 auto Br = DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other, N1: getControlRoot(),
2819 N2: DAG.getBasicBlock(MBB: Succ0MBB));
2820 setValue(V: &I, NewN: Br);
2821 DAG.setRoot(Br);
2822 }
2823}
2824
2825void SelectionDAGBuilder::visitCondBr(const CondBrInst &I) {
2826 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2827
2828 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(BB: I.getSuccessor(i: 0));
2829
2830 // If this condition is one of the special cases we handle, do special stuff
2831 // now.
2832 const Value *CondVal = I.getCondition();
2833 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(BB: I.getSuccessor(i: 1));
2834
2835 // If this is a series of conditions that are or'd or and'd together, emit
2836 // this as a sequence of branches instead of setcc's with and/or operations.
2837 // As long as jumps are not expensive (exceptions for multi-use logic ops,
2838 // unpredictable branches, and vector extracts because those jumps are likely
2839 // expensive for any target), this should improve performance.
2840 // For example, instead of something like:
2841 // cmp A, B
2842 // C = seteq
2843 // cmp D, E
2844 // F = setle
2845 // or C, F
2846 // jnz foo
2847 // Emit:
2848 // cmp A, B
2849 // je foo
2850 // cmp D, E
2851 // jle foo
2852 bool IsUnpredictable = I.hasMetadata(KindID: LLVMContext::MD_unpredictable);
2853 const Instruction *BOp = dyn_cast<Instruction>(Val: CondVal);
2854 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2855 BOp->hasOneUse() && !IsUnpredictable) {
2856 Value *Vec;
2857 const Value *BOp0, *BOp1;
2858 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2859 if (match(V: BOp, P: m_LogicalAnd(L: m_Value(V&: BOp0), R: m_Value(V&: BOp1))))
2860 Opcode = Instruction::And;
2861 else if (match(V: BOp, P: m_LogicalOr(L: m_Value(V&: BOp0), R: m_Value(V&: BOp1))))
2862 Opcode = Instruction::Or;
2863
2864 if (Opcode &&
2865 !(match(V: BOp0, P: m_ExtractElt(Val: m_Value(V&: Vec), Idx: m_Value())) &&
2866 match(V: BOp1, P: m_ExtractElt(Val: m_Specific(V: Vec), Idx: m_Value()))) &&
2867 !shouldKeepJumpConditionsTogether(
2868 FuncInfo, I, Opc: Opcode, Lhs: BOp0, Rhs: BOp1,
2869 Params: DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2870 Opcode, BOp0, BOp1))) {
2871 FindMergedConditions(Cond: BOp, TBB: Succ0MBB, FBB: Succ1MBB, CurBB: BrMBB, SwitchBB: BrMBB, Opc: Opcode,
2872 TProb: getEdgeProbability(Src: BrMBB, Dst: Succ0MBB),
2873 FProb: getEdgeProbability(Src: BrMBB, Dst: Succ1MBB),
2874 /*InvertCond=*/false);
2875 // If the compares in later blocks need to use values not currently
2876 // exported from this block, export them now. This block should always
2877 // be the first entry.
2878 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2879
2880 // Allow some cases to be rejected.
2881 if (ShouldEmitAsBranches(Cases: SL->SwitchCases)) {
2882 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2883 ExportFromCurrentBlock(V: SL->SwitchCases[i].CmpLHS);
2884 ExportFromCurrentBlock(V: SL->SwitchCases[i].CmpRHS);
2885 }
2886
2887 // Emit the branch for this block.
2888 visitSwitchCase(CB&: SL->SwitchCases[0], SwitchBB: BrMBB);
2889 SL->SwitchCases.erase(position: SL->SwitchCases.begin());
2890 return;
2891 }
2892
2893 // Okay, we decided not to do this, remove any inserted MBB's and clear
2894 // SwitchCases.
2895 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2896 FuncInfo.MF->erase(MBBI: SL->SwitchCases[i].ThisBB);
2897
2898 SL->SwitchCases.clear();
2899 }
2900 }
2901
2902 // Create a CaseBlock record representing this branch.
2903 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(Context&: *DAG.getContext()),
2904 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2905 BranchProbability::getUnknown(), BranchProbability::getUnknown(),
2906 IsUnpredictable);
2907
2908 // Use visitSwitchCase to actually insert the fast branch sequence for this
2909 // cond branch.
2910 visitSwitchCase(CB, SwitchBB: BrMBB);
2911}
2912
2913/// visitSwitchCase - Emits the necessary code to represent a single node in
2914/// the binary search tree resulting from lowering a switch instruction.
2915void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2916 MachineBasicBlock *SwitchBB) {
2917 SDValue Cond;
2918 SDValue CondLHS = getValue(V: CB.CmpLHS);
2919 SDLoc dl = CB.DL;
2920
2921 if (CB.CC == ISD::SETTRUE) {
2922 // Branch or fall through to TrueBB.
2923 addSuccessorWithProb(Src: SwitchBB, Dst: CB.TrueBB, Prob: CB.TrueProb);
2924 SwitchBB->normalizeSuccProbs();
2925 if (CB.TrueBB != NextBlock(MBB: SwitchBB)) {
2926 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: getControlRoot(),
2927 N2: DAG.getBasicBlock(MBB: CB.TrueBB)));
2928 }
2929 return;
2930 }
2931
2932 auto &TLI = DAG.getTargetLoweringInfo();
2933 EVT MemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: CB.CmpLHS->getType());
2934
2935 // Build the setcc now.
2936 if (!CB.CmpMHS) {
2937 // Fold "(X == true)" to X and "(X == false)" to !X to
2938 // handle common cases produced by branch lowering.
2939 if (CB.CmpRHS == ConstantInt::getTrue(Context&: *DAG.getContext()) &&
2940 CB.CC == ISD::SETEQ)
2941 Cond = CondLHS;
2942 else if (CB.CmpRHS == ConstantInt::getFalse(Context&: *DAG.getContext()) &&
2943 CB.CC == ISD::SETEQ) {
2944 SDValue True = DAG.getConstant(Val: 1, DL: dl, VT: CondLHS.getValueType());
2945 Cond = DAG.getNode(Opcode: ISD::XOR, DL: dl, VT: CondLHS.getValueType(), N1: CondLHS, N2: True);
2946 } else {
2947 SDValue CondRHS = getValue(V: CB.CmpRHS);
2948
2949 // If a pointer's DAG type is larger than its memory type then the DAG
2950 // values are zero-extended. This breaks signed comparisons so truncate
2951 // back to the underlying type before doing the compare.
2952 if (CondLHS.getValueType() != MemVT) {
2953 CondLHS = DAG.getPtrExtOrTrunc(Op: CondLHS, DL: getCurSDLoc(), VT: MemVT);
2954 CondRHS = DAG.getPtrExtOrTrunc(Op: CondRHS, DL: getCurSDLoc(), VT: MemVT);
2955 }
2956 Cond = DAG.getSetCC(DL: dl, VT: MVT::i1, LHS: CondLHS, RHS: CondRHS, Cond: CB.CC);
2957 }
2958 } else {
2959 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2960
2961 const APInt& Low = cast<ConstantInt>(Val: CB.CmpLHS)->getValue();
2962 const APInt& High = cast<ConstantInt>(Val: CB.CmpRHS)->getValue();
2963
2964 SDValue CmpOp = getValue(V: CB.CmpMHS);
2965 EVT VT = CmpOp.getValueType();
2966
2967 if (cast<ConstantInt>(Val: CB.CmpLHS)->isMinValue(IsSigned: true)) {
2968 Cond = DAG.getSetCC(DL: dl, VT: MVT::i1, LHS: CmpOp, RHS: DAG.getConstant(Val: High, DL: dl, VT),
2969 Cond: ISD::SETLE);
2970 } else {
2971 SDValue SUB = DAG.getNode(Opcode: ISD::SUB, DL: dl,
2972 VT, N1: CmpOp, N2: DAG.getConstant(Val: Low, DL: dl, VT));
2973 Cond = DAG.getSetCC(DL: dl, VT: MVT::i1, LHS: SUB,
2974 RHS: DAG.getConstant(Val: High-Low, DL: dl, VT), Cond: ISD::SETULE);
2975 }
2976 }
2977
2978 // Update successor info
2979 addSuccessorWithProb(Src: SwitchBB, Dst: CB.TrueBB, Prob: CB.TrueProb);
2980 // TrueBB and FalseBB are always different unless the incoming IR is
2981 // degenerate. This only happens when running llc on weird IR.
2982 if (CB.TrueBB != CB.FalseBB)
2983 addSuccessorWithProb(Src: SwitchBB, Dst: CB.FalseBB, Prob: CB.FalseProb);
2984 SwitchBB->normalizeSuccProbs();
2985
2986 // If the lhs block is the next block, invert the condition so that we can
2987 // fall through to the lhs instead of the rhs block.
2988 if (CB.TrueBB == NextBlock(MBB: SwitchBB)) {
2989 std::swap(a&: CB.TrueBB, b&: CB.FalseBB);
2990 SDValue True = DAG.getConstant(Val: 1, DL: dl, VT: Cond.getValueType());
2991 Cond = DAG.getNode(Opcode: ISD::XOR, DL: dl, VT: Cond.getValueType(), N1: Cond, N2: True);
2992 }
2993
2994 SDNodeFlags Flags;
2995 Flags.setUnpredictable(CB.IsUnpredictable);
2996 SDValue BrCond = DAG.getNode(Opcode: ISD::BRCOND, DL: dl, VT: MVT::Other, N1: getControlRoot(),
2997 N2: Cond, N3: DAG.getBasicBlock(MBB: CB.TrueBB), Flags);
2998
2999 setValue(V: CurInst, NewN: BrCond);
3000
3001 // Insert the false branch. Do this even if it's a fall through branch,
3002 // this makes it easier to do DAG optimizations which require inverting
3003 // the branch condition.
3004 BrCond = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: BrCond,
3005 N2: DAG.getBasicBlock(MBB: CB.FalseBB));
3006
3007 DAG.setRoot(BrCond);
3008}
3009
3010/// visitJumpTable - Emit JumpTable node in the current MBB
3011void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
3012 // Emit the code for the jump table
3013 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3014 assert(JT.Reg && "Should lower JT Header first!");
3015 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DL: DAG.getDataLayout());
3016 SDValue Index = DAG.getCopyFromReg(Chain: getControlRoot(), dl: *JT.SL, Reg: JT.Reg, VT: PTy);
3017 SDValue Table = DAG.getJumpTable(JTI: JT.JTI, VT: PTy);
3018 SDValue BrJumpTable = DAG.getNode(Opcode: ISD::BR_JT, DL: *JT.SL, VT: MVT::Other,
3019 N1: Index.getValue(R: 1), N2: Table, N3: Index);
3020 DAG.setRoot(BrJumpTable);
3021}
3022
3023/// visitJumpTableHeader - This function emits necessary code to produce index
3024/// in the JumpTable from switch case.
3025void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
3026 JumpTableHeader &JTH,
3027 MachineBasicBlock *SwitchBB) {
3028 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3029 const SDLoc &dl = *JT.SL;
3030
3031 // Subtract the lowest switch case value from the value being switched on.
3032 SDValue SwitchOp = getValue(V: JTH.SValue);
3033 EVT VT = SwitchOp.getValueType();
3034 SDValue Sub = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: SwitchOp,
3035 N2: DAG.getConstant(Val: JTH.First, DL: dl, VT));
3036
3037 // The SDNode we just created, which holds the value being switched on minus
3038 // the smallest case value, needs to be copied to a virtual register so it
3039 // can be used as an index into the jump table in a subsequent basic block.
3040 // This value may be smaller or larger than the target's pointer type, and
3041 // therefore require extension or truncating.
3042 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3043 SwitchOp =
3044 DAG.getZExtOrTrunc(Op: Sub, DL: dl, VT: TLI.getJumpTableRegTy(DL: DAG.getDataLayout()));
3045
3046 Register JumpTableReg =
3047 FuncInfo.CreateReg(VT: TLI.getJumpTableRegTy(DL: DAG.getDataLayout()));
3048 SDValue CopyTo =
3049 DAG.getCopyToReg(Chain: getControlRoot(), dl, Reg: JumpTableReg, N: SwitchOp);
3050 JT.Reg = JumpTableReg;
3051
3052 if (!JTH.FallthroughUnreachable) {
3053 // Emit the range check for the jump table, and branch to the default block
3054 // for the switch statement if the value being switched on exceeds the
3055 // largest case in the switch.
3056 SDValue CMP = DAG.getSetCC(
3057 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(),
3058 VT: Sub.getValueType()),
3059 LHS: Sub, RHS: DAG.getConstant(Val: JTH.Last - JTH.First, DL: dl, VT), Cond: ISD::SETUGT);
3060
3061 SDValue BrCond = DAG.getNode(Opcode: ISD::BRCOND, DL: dl,
3062 VT: MVT::Other, N1: CopyTo, N2: CMP,
3063 N3: DAG.getBasicBlock(MBB: JT.Default));
3064
3065 // Avoid emitting unnecessary branches to the next block.
3066 if (JT.MBB != NextBlock(MBB: SwitchBB))
3067 BrCond = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: BrCond,
3068 N2: DAG.getBasicBlock(MBB: JT.MBB));
3069
3070 DAG.setRoot(BrCond);
3071 } else {
3072 // Avoid emitting unnecessary branches to the next block.
3073 if (JT.MBB != NextBlock(MBB: SwitchBB))
3074 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: CopyTo,
3075 N2: DAG.getBasicBlock(MBB: JT.MBB)));
3076 else
3077 DAG.setRoot(CopyTo);
3078 }
3079}
3080
3081/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3082/// variable if there exists one.
3083static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3084 SDValue &Chain) {
3085 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3086 EVT PtrTy = TLI.getPointerTy(DL: DAG.getDataLayout());
3087 EVT PtrMemTy = TLI.getPointerMemTy(DL: DAG.getDataLayout());
3088 MachineFunction &MF = DAG.getMachineFunction();
3089 Value *Global =
3090 TLI.getSDagStackGuard(M: *MF.getFunction().getParent(), Libcalls: DAG.getLibcalls());
3091 MachineSDNode *Node =
3092 DAG.getMachineNode(Opcode: TargetOpcode::LOAD_STACK_GUARD, dl: DL, VT: PtrTy, Op1: Chain);
3093 if (Global) {
3094 MachinePointerInfo MPInfo(Global);
3095 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3096 MachineMemOperand::MODereferenceable;
3097 MachineMemOperand *MemRef = MF.getMachineMemOperand(
3098 PtrInfo: MPInfo, F: Flags, Size: PtrTy.getSizeInBits() / 8, BaseAlignment: DAG.getEVTAlign(MemoryVT: PtrTy));
3099 DAG.setNodeMemRefs(N: Node, NewMemRefs: {MemRef});
3100 }
3101 if (PtrTy != PtrMemTy)
3102 return DAG.getPtrExtOrTrunc(Op: SDValue(Node, 0), DL, VT: PtrMemTy);
3103 return SDValue(Node, 0);
3104}
3105
3106/// Codegen a new tail for a stack protector check ParentMBB which has had its
3107/// tail spliced into a stack protector check success bb.
3108///
3109/// For a high level explanation of how this fits into the stack protector
3110/// generation see the comment on the declaration of class
3111/// StackProtectorDescriptor.
3112void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3113 MachineBasicBlock *ParentBB) {
3114
3115 // First create the loads to the guard/stack slot for the comparison.
3116 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3117 auto &DL = DAG.getDataLayout();
3118 EVT PtrTy = TLI.getFrameIndexTy(DL);
3119 EVT PtrMemTy = TLI.getPointerMemTy(DL, AS: DL.getAllocaAddrSpace());
3120
3121 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3122 int FI = MFI.getStackProtectorIndex();
3123
3124 SDValue Guard;
3125 SDLoc dl = getCurSDLoc();
3126 SDValue StackSlotPtr = DAG.getFrameIndex(FI, VT: PtrTy);
3127 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3128 Align Align = DL.getPrefTypeAlign(
3129 Ty: PointerType::get(C&: M.getContext(), AddressSpace: DL.getAllocaAddrSpace()));
3130
3131 // Generate code to load the content of the guard slot.
3132 SDValue GuardVal = DAG.getLoad(
3133 VT: PtrMemTy, dl, Chain: DAG.getEntryNode(), Ptr: StackSlotPtr,
3134 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI), Alignment: Align,
3135 MMOFlags: MachineMemOperand::MOVolatile);
3136
3137 if (TLI.useStackGuardXorFP())
3138 GuardVal = TLI.emitStackGuardXorFP(DAG, Val: GuardVal, DL: dl);
3139
3140 // If we're using function-based instrumentation, call the guard check
3141 // function
3142 if (SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3143 // Get the guard check function from the target and verify it exists since
3144 // we're using function-based instrumentation
3145 const Function *GuardCheckFn =
3146 TLI.getSSPStackGuardCheck(M, Libcalls: DAG.getLibcalls());
3147 assert(GuardCheckFn && "Guard check function is null");
3148
3149 // The target provides a guard check function to validate the guard value.
3150 // Generate a call to that function with the content of the guard slot as
3151 // argument.
3152 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3153 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3154
3155 TargetLowering::ArgListTy Args;
3156 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(i: 0));
3157 if (GuardCheckFn->hasParamAttribute(ArgNo: 0, Kind: Attribute::AttrKind::InReg))
3158 Entry.IsInReg = true;
3159 Args.push_back(x: Entry);
3160
3161 TargetLowering::CallLoweringInfo CLI(DAG);
3162 CLI.setDebugLoc(getCurSDLoc())
3163 .setChain(DAG.getEntryNode())
3164 .setCallee(CC: GuardCheckFn->getCallingConv(), ResultType: FnTy->getReturnType(),
3165 Target: getValue(V: GuardCheckFn), ArgsList: std::move(Args));
3166
3167 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3168 DAG.setRoot(Result.second);
3169 return;
3170 }
3171
3172 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3173 // Otherwise, emit a volatile load to retrieve the stack guard value.
3174 SDValue Chain = DAG.getEntryNode();
3175 if (TLI.useLoadStackGuardNode(M)) {
3176 Guard = getLoadStackGuard(DAG, DL: dl, Chain);
3177 } else {
3178 if (const Value *IRGuard = TLI.getSDagStackGuard(M, Libcalls: DAG.getLibcalls())) {
3179 SDValue GuardPtr = getValue(V: IRGuard);
3180 Guard = DAG.getLoad(VT: PtrMemTy, dl, Chain, Ptr: GuardPtr,
3181 PtrInfo: MachinePointerInfo(IRGuard, 0), Alignment: Align,
3182 MMOFlags: MachineMemOperand::MOVolatile);
3183 } else {
3184 LLVMContext &Ctx = *DAG.getContext();
3185 Ctx.diagnose(DI: DiagnosticInfoGeneric("unable to lower stackguard"));
3186 Guard = DAG.getPOISON(VT: PtrMemTy);
3187 }
3188 }
3189
3190 // Perform the comparison via a getsetcc.
3191 SDValue Cmp = DAG.getSetCC(
3192 DL: dl, VT: TLI.getSetCCResultType(DL, Context&: *DAG.getContext(), VT: Guard.getValueType()),
3193 LHS: Guard, RHS: GuardVal, Cond: ISD::SETNE);
3194
3195 // If the guard/stackslot do not equal, branch to failure MBB.
3196 SDValue BrCond = DAG.getNode(Opcode: ISD::BRCOND, DL: dl, VT: MVT::Other, N1: getControlRoot(),
3197 N2: Cmp, N3: DAG.getBasicBlock(MBB: SPD.getFailureMBB()));
3198 // Otherwise branch to success MBB.
3199 SDValue Br = DAG.getNode(Opcode: ISD::BR, DL: dl,
3200 VT: MVT::Other, N1: BrCond,
3201 N2: DAG.getBasicBlock(MBB: SPD.getSuccessMBB()));
3202
3203 DAG.setRoot(Br);
3204}
3205
3206/// Codegen the failure basic block for a stack protector check.
3207///
3208/// A failure stack protector machine basic block consists simply of a call to
3209/// __stack_chk_fail().
3210///
3211/// For a high level explanation of how this fits into the stack protector
3212/// generation see the comment on the declaration of class
3213/// StackProtectorDescriptor.
3214void SelectionDAGBuilder::visitSPDescriptorFailure(
3215 StackProtectorDescriptor &SPD) {
3216
3217 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3218 MachineBasicBlock *ParentBB = SPD.getParentMBB();
3219 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3220 SDValue Chain;
3221
3222 // For -Oz builds with a guard check function, we use function-based
3223 // instrumentation. Otherwise, if we have a guard check function, we call it
3224 // in the failure block.
3225 auto *GuardCheckFn = TLI.getSSPStackGuardCheck(M, Libcalls: DAG.getLibcalls());
3226 if (GuardCheckFn && !SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3227 // First create the loads to the guard/stack slot for the comparison.
3228 auto &DL = DAG.getDataLayout();
3229 EVT PtrTy = TLI.getFrameIndexTy(DL);
3230 EVT PtrMemTy = TLI.getPointerMemTy(DL, AS: DL.getAllocaAddrSpace());
3231
3232 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3233 int FI = MFI.getStackProtectorIndex();
3234
3235 SDLoc dl = getCurSDLoc();
3236 SDValue StackSlotPtr = DAG.getFrameIndex(FI, VT: PtrTy);
3237 Align Align = DL.getPrefTypeAlign(
3238 Ty: PointerType::get(C&: M.getContext(), AddressSpace: DL.getAllocaAddrSpace()));
3239
3240 // Generate code to load the content of the guard slot.
3241 SDValue GuardVal = DAG.getLoad(
3242 VT: PtrMemTy, dl, Chain: DAG.getEntryNode(), Ptr: StackSlotPtr,
3243 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI), Alignment: Align,
3244 MMOFlags: MachineMemOperand::MOVolatile);
3245
3246 if (TLI.useStackGuardXorFP())
3247 GuardVal = TLI.emitStackGuardXorFP(DAG, Val: GuardVal, DL: dl);
3248
3249 // The target provides a guard check function to validate the guard value.
3250 // Generate a call to that function with the content of the guard slot as
3251 // argument.
3252 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3253 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3254
3255 TargetLowering::ArgListTy Args;
3256 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(i: 0));
3257 if (GuardCheckFn->hasParamAttribute(ArgNo: 0, Kind: Attribute::AttrKind::InReg))
3258 Entry.IsInReg = true;
3259 Args.push_back(x: Entry);
3260
3261 TargetLowering::CallLoweringInfo CLI(DAG);
3262 CLI.setDebugLoc(getCurSDLoc())
3263 .setChain(DAG.getEntryNode())
3264 .setCallee(CC: GuardCheckFn->getCallingConv(), ResultType: FnTy->getReturnType(),
3265 Target: getValue(V: GuardCheckFn), ArgsList: std::move(Args));
3266
3267 Chain = TLI.LowerCallTo(CLI).second;
3268 } else {
3269 TargetLowering::MakeLibCallOptions CallOptions;
3270 CallOptions.setDiscardResult(true);
3271 Chain = TLI.makeLibCall(DAG, LC: RTLIB::STACKPROTECTOR_CHECK_FAIL, RetVT: MVT::isVoid,
3272 Ops: {}, CallOptions, dl: getCurSDLoc())
3273 .second;
3274 }
3275
3276 // Emit a trap instruction if we are required to do so.
3277 const TargetOptions &TargetOpts = DAG.getTarget().Options;
3278 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3279 Chain = DAG.getNode(Opcode: ISD::TRAP, DL: getCurSDLoc(), VT: MVT::Other, Operand: Chain);
3280
3281 DAG.setRoot(Chain);
3282}
3283
3284/// visitBitTestHeader - This function emits necessary code to produce value
3285/// suitable for "bit tests"
3286void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3287 MachineBasicBlock *SwitchBB) {
3288 SDLoc dl = getCurSDLoc();
3289
3290 // Subtract the minimum value.
3291 SDValue SwitchOp = getValue(V: B.SValue);
3292 EVT VT = SwitchOp.getValueType();
3293 SDValue RangeSub =
3294 DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: SwitchOp, N2: DAG.getConstant(Val: B.First, DL: dl, VT));
3295
3296 // Determine the type of the test operands.
3297 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3298 bool UsePtrType = false;
3299 if (!TLI.isTypeLegal(VT)) {
3300 UsePtrType = true;
3301 } else {
3302 for (const BitTestCase &Case : B.Cases)
3303 if (!isUIntN(N: VT.getSizeInBits(), x: Case.Mask)) {
3304 // Switch table case range are encoded into series of masks.
3305 // Just use pointer type, it's guaranteed to fit.
3306 UsePtrType = true;
3307 break;
3308 }
3309 }
3310 SDValue Sub = RangeSub;
3311 if (UsePtrType) {
3312 VT = TLI.getPointerTy(DL: DAG.getDataLayout());
3313 Sub = DAG.getZExtOrTrunc(Op: Sub, DL: dl, VT);
3314 }
3315
3316 B.RegVT = VT.getSimpleVT();
3317 B.Reg = FuncInfo.CreateReg(VT: B.RegVT);
3318 SDValue CopyTo = DAG.getCopyToReg(Chain: getControlRoot(), dl, Reg: B.Reg, N: Sub);
3319
3320 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3321
3322 if (!B.FallthroughUnreachable)
3323 addSuccessorWithProb(Src: SwitchBB, Dst: B.Default, Prob: B.DefaultProb);
3324 addSuccessorWithProb(Src: SwitchBB, Dst: MBB, Prob: B.Prob);
3325 SwitchBB->normalizeSuccProbs();
3326
3327 SDValue Root = CopyTo;
3328 if (!B.FallthroughUnreachable) {
3329 // Conditional branch to the default block.
3330 SDValue RangeCmp = DAG.getSetCC(DL: dl,
3331 VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(),
3332 VT: RangeSub.getValueType()),
3333 LHS: RangeSub, RHS: DAG.getConstant(Val: B.Range, DL: dl, VT: RangeSub.getValueType()),
3334 Cond: ISD::SETUGT);
3335
3336 Root = DAG.getNode(Opcode: ISD::BRCOND, DL: dl, VT: MVT::Other, N1: Root, N2: RangeCmp,
3337 N3: DAG.getBasicBlock(MBB: B.Default));
3338 }
3339
3340 // Avoid emitting unnecessary branches to the next block.
3341 if (MBB != NextBlock(MBB: SwitchBB))
3342 Root = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: Root, N2: DAG.getBasicBlock(MBB));
3343
3344 DAG.setRoot(Root);
3345}
3346
3347/// visitBitTestCase - this function produces one "bit test"
3348void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3349 MachineBasicBlock *NextMBB,
3350 BranchProbability BranchProbToNext,
3351 Register Reg, BitTestCase &B,
3352 MachineBasicBlock *SwitchBB) {
3353 SDLoc dl = getCurSDLoc();
3354 MVT VT = BB.RegVT;
3355 SDValue ShiftOp = DAG.getCopyFromReg(Chain: getControlRoot(), dl, Reg, VT);
3356 SDValue Cmp;
3357 unsigned PopCount = llvm::popcount(Value: B.Mask);
3358 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3359 if (PopCount == 1) {
3360 // Testing for a single bit; just compare the shift count with what it
3361 // would need to be to shift a 1 bit in that position.
3362 Cmp = DAG.getSetCC(
3363 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(), VT),
3364 LHS: ShiftOp, RHS: DAG.getConstant(Val: llvm::countr_zero(Val: B.Mask), DL: dl, VT),
3365 Cond: ISD::SETEQ);
3366 } else if (PopCount == BB.Range) {
3367 // There is only one zero bit in the range, test for it directly.
3368 Cmp = DAG.getSetCC(
3369 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(), VT),
3370 LHS: ShiftOp, RHS: DAG.getConstant(Val: llvm::countr_one(Value: B.Mask), DL: dl, VT), Cond: ISD::SETNE);
3371 } else {
3372 // Make desired shift
3373 SDValue SwitchVal = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT,
3374 N1: DAG.getConstant(Val: 1, DL: dl, VT), N2: ShiftOp);
3375
3376 // Emit bit tests and jumps
3377 SDValue AndOp = DAG.getNode(Opcode: ISD::AND, DL: dl,
3378 VT, N1: SwitchVal, N2: DAG.getConstant(Val: B.Mask, DL: dl, VT));
3379 Cmp = DAG.getSetCC(
3380 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(), VT),
3381 LHS: AndOp, RHS: DAG.getConstant(Val: 0, DL: dl, VT), Cond: ISD::SETNE);
3382 }
3383
3384 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3385 addSuccessorWithProb(Src: SwitchBB, Dst: B.TargetBB, Prob: B.ExtraProb);
3386 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3387 addSuccessorWithProb(Src: SwitchBB, Dst: NextMBB, Prob: BranchProbToNext);
3388 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3389 // one as they are relative probabilities (and thus work more like weights),
3390 // and hence we need to normalize them to let the sum of them become one.
3391 SwitchBB->normalizeSuccProbs();
3392
3393 SDValue BrAnd = DAG.getNode(Opcode: ISD::BRCOND, DL: dl,
3394 VT: MVT::Other, N1: getControlRoot(),
3395 N2: Cmp, N3: DAG.getBasicBlock(MBB: B.TargetBB));
3396
3397 // Avoid emitting unnecessary branches to the next block.
3398 if (NextMBB != NextBlock(MBB: SwitchBB))
3399 BrAnd = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: BrAnd,
3400 N2: DAG.getBasicBlock(MBB: NextMBB));
3401
3402 DAG.setRoot(BrAnd);
3403}
3404
3405void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3406 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3407
3408 // Retrieve successors. Look through artificial IR level blocks like
3409 // catchswitch for successors.
3410 MachineBasicBlock *Return = FuncInfo.getMBB(BB: I.getSuccessor(i: 0));
3411 const BasicBlock *EHPadBB = I.getSuccessor(i: 1);
3412 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(BB: EHPadBB);
3413
3414 // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3415 // have to do anything here to lower funclet bundles.
3416 failForInvalidBundles(I, Name: "invokes",
3417 AllowedBundles: {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3418 LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3419 LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3420 LLVMContext::OB_clang_arc_attachedcall,
3421 LLVMContext::OB_kcfi});
3422
3423 const Value *Callee(I.getCalledOperand());
3424 const Function *Fn = dyn_cast<Function>(Val: Callee);
3425 if (isa<InlineAsm>(Val: Callee))
3426 visitInlineAsm(Call: I, EHPadBB);
3427 else if (Fn && Fn->isIntrinsic()) {
3428 switch (Fn->getIntrinsicID()) {
3429 default:
3430 llvm_unreachable("Cannot invoke this intrinsic");
3431 case Intrinsic::donothing:
3432 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3433 case Intrinsic::seh_try_begin:
3434 case Intrinsic::seh_scope_begin:
3435 case Intrinsic::seh_try_end:
3436 case Intrinsic::seh_scope_end:
3437 if (EHPadMBB)
3438 // a block referenced by EH table
3439 // so dtor-funclet not removed by opts
3440 EHPadMBB->setMachineBlockAddressTaken();
3441 break;
3442 case Intrinsic::experimental_patchpoint_void:
3443 case Intrinsic::experimental_patchpoint:
3444 visitPatchpoint(CB: I, EHPadBB);
3445 break;
3446 case Intrinsic::experimental_gc_statepoint:
3447 LowerStatepoint(I: cast<GCStatepointInst>(Val: I), EHPadBB);
3448 break;
3449 // wasm_throw, wasm_rethrow: This is usually done in visitTargetIntrinsic,
3450 // but these intrinsics are special because they can be invoked, so we
3451 // manually lower it to a DAG node here.
3452 case Intrinsic::wasm_throw: {
3453 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3454 std::array<SDValue, 4> Ops = {
3455 getControlRoot(), // inchain for the terminator node
3456 DAG.getTargetConstant(Val: Intrinsic::wasm_throw, DL: getCurSDLoc(),
3457 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
3458 getValue(V: I.getArgOperand(i: 0)), // tag
3459 getValue(V: I.getArgOperand(i: 1)) // thrown value
3460 };
3461 SDVTList VTs = DAG.getVTList(VTs: ArrayRef<EVT>({MVT::Other})); // outchain
3462 DAG.setRoot(DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL: getCurSDLoc(), VTList: VTs, Ops));
3463 break;
3464 }
3465 case Intrinsic::wasm_rethrow: {
3466 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3467 std::array<SDValue, 2> Ops = {
3468 getControlRoot(), // inchain for the terminator node
3469 DAG.getTargetConstant(Val: Intrinsic::wasm_rethrow, DL: getCurSDLoc(),
3470 VT: TLI.getPointerTy(DL: DAG.getDataLayout()))};
3471 SDVTList VTs = DAG.getVTList(VTs: ArrayRef<EVT>({MVT::Other})); // outchain
3472 DAG.setRoot(DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL: getCurSDLoc(), VTList: VTs, Ops));
3473 break;
3474 }
3475 }
3476 } else if (I.hasDeoptState()) {
3477 // Currently we do not lower any intrinsic calls with deopt operand bundles.
3478 // Eventually we will support lowering the @llvm.experimental.deoptimize
3479 // intrinsic, and right now there are no plans to support other intrinsics
3480 // with deopt state.
3481 LowerCallSiteWithDeoptBundle(Call: &I, Callee: getValue(V: Callee), EHPadBB);
3482 } else if (I.countOperandBundlesOfType(ID: LLVMContext::OB_ptrauth)) {
3483 LowerCallSiteWithPtrAuthBundle(CB: cast<CallBase>(Val: I), EHPadBB);
3484 } else {
3485 LowerCallTo(CB: I, Callee: getValue(V: Callee), IsTailCall: false, IsMustTailCall: false, EHPadBB);
3486 }
3487
3488 // If the value of the invoke is used outside of its defining block, make it
3489 // available as a virtual register.
3490 // We already took care of the exported value for the statepoint instruction
3491 // during call to the LowerStatepoint.
3492 if (!isa<GCStatepointInst>(Val: I)) {
3493 CopyToExportRegsIfNeeded(V: &I);
3494 }
3495
3496 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3497 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3498 BranchProbability EHPadBBProb =
3499 BPI ? BPI->getEdgeProbability(Src: InvokeMBB->getBasicBlock(), Dst: EHPadBB)
3500 : BranchProbability::getZero();
3501 findUnwindDestinations(FuncInfo, EHPadBB, Prob: EHPadBBProb, UnwindDests);
3502
3503 // Update successor info.
3504 addSuccessorWithProb(Src: InvokeMBB, Dst: Return);
3505 for (auto &UnwindDest : UnwindDests) {
3506 UnwindDest.first->setIsEHPad();
3507 addSuccessorWithProb(Src: InvokeMBB, Dst: UnwindDest.first, Prob: UnwindDest.second);
3508 }
3509 InvokeMBB->normalizeSuccProbs();
3510
3511 // Drop into normal successor.
3512 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other, N1: getControlRoot(),
3513 N2: DAG.getBasicBlock(MBB: Return)));
3514}
3515
3516/// The intrinsics currently supported by callbr are implicit control flow
3517/// intrinsics such as amdgcn.kill.
3518/// - they should be called (no "dontcall-" attributes)
3519/// - they do not touch memory on the target (= !TLI.getTgtMemIntrinsic())
3520/// - they do not need custom argument handling (no
3521/// TLI.CollectTargetIntrinsicOperands())
3522void SelectionDAGBuilder::visitCallBrIntrinsic(const CallBrInst &I) {
3523#ifndef NDEBUG
3524 SmallVector<TargetLowering::IntrinsicInfo, 2> Infos;
3525 DAG.getTargetLoweringInfo().getTgtMemIntrinsic(
3526 Infos, I, DAG.getMachineFunction(), I.getIntrinsicID());
3527 assert(Infos.empty() && "Intrinsic touches memory");
3528#endif
3529
3530 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
3531
3532 SmallVector<SDValue, 8> Ops =
3533 getTargetIntrinsicOperands(I, HasChain, OnlyLoad);
3534 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
3535
3536 // Create the node.
3537 SDValue Result =
3538 getTargetNonMemIntrinsicNode(IntrinsicVT: *I.getType(), HasChain, Ops, VTs);
3539 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
3540
3541 setValue(V: &I, NewN: Result);
3542}
3543
3544void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3545 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3546
3547 if (I.isInlineAsm()) {
3548 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3549 // have to do anything here to lower funclet bundles.
3550 failForInvalidBundles(I, Name: "callbrs",
3551 AllowedBundles: {LLVMContext::OB_deopt, LLVMContext::OB_funclet});
3552 visitInlineAsm(Call: I);
3553 } else {
3554 assert(!I.hasOperandBundles() &&
3555 "Can't have operand bundles for intrinsics");
3556 visitCallBrIntrinsic(I);
3557 }
3558 CopyToExportRegsIfNeeded(V: &I);
3559
3560 // Retrieve successors.
3561 SmallPtrSet<BasicBlock *, 8> Dests;
3562 Dests.insert(Ptr: I.getDefaultDest());
3563 MachineBasicBlock *Return = FuncInfo.getMBB(BB: I.getDefaultDest());
3564
3565 // Update successor info.
3566 addSuccessorWithProb(Src: CallBrMBB, Dst: Return, Prob: BranchProbability::getOne());
3567 // TODO: For most of the cases where there is an intrinsic callbr, we're
3568 // having exactly one indirect target, which will be unreachable. As soon as
3569 // this changes, we might need to enhance
3570 // Target->setIsInlineAsmBrIndirectTarget or add something similar for
3571 // intrinsic indirect branches.
3572 if (I.isInlineAsm()) {
3573 for (BasicBlock *Dest : I.getIndirectDests()) {
3574 MachineBasicBlock *Target = FuncInfo.getMBB(BB: Dest);
3575 Target->setIsInlineAsmBrIndirectTarget();
3576 // If we introduce a type of asm goto statement that is permitted to use
3577 // an indirect call instruction to jump to its labels, then we should add
3578 // a call to Target->setMachineBlockAddressTaken() here, to mark the
3579 // target block as requiring a BTI.
3580
3581 Target->setLabelMustBeEmitted();
3582 // Don't add duplicate machine successors.
3583 if (Dests.insert(Ptr: Dest).second)
3584 addSuccessorWithProb(Src: CallBrMBB, Dst: Target, Prob: BranchProbability::getZero());
3585 }
3586 }
3587 CallBrMBB->normalizeSuccProbs();
3588
3589 // Drop into default successor.
3590 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(),
3591 VT: MVT::Other, N1: getControlRoot(),
3592 N2: DAG.getBasicBlock(MBB: Return)));
3593}
3594
3595void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3596 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3597}
3598
3599void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3600 assert(FuncInfo.MBB->isEHPad() &&
3601 "Call to landingpad not in landing pad!");
3602
3603 // If there aren't registers to copy the values into (e.g., during SjLj
3604 // exceptions), then don't bother to create these DAG nodes.
3605 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3606 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3607 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3608 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3609 return;
3610
3611 // If landingpad's return type is token type, we don't create DAG nodes
3612 // for its exception pointer and selector value. The extraction of exception
3613 // pointer or selector value from token type landingpads is not currently
3614 // supported.
3615 if (LP.getType()->isTokenTy())
3616 return;
3617
3618 SmallVector<EVT, 2> ValueVTs;
3619 SDLoc dl = getCurSDLoc();
3620 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: LP.getType(), ValueVTs);
3621 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3622
3623 // Get the two live-in registers as SDValues. The physregs have already been
3624 // copied into virtual registers.
3625 SDValue Ops[2];
3626 if (FuncInfo.ExceptionPointerVirtReg) {
3627 Ops[0] = DAG.getZExtOrTrunc(
3628 Op: DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl,
3629 Reg: FuncInfo.ExceptionPointerVirtReg,
3630 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
3631 DL: dl, VT: ValueVTs[0]);
3632 } else {
3633 Ops[0] = DAG.getConstant(Val: 0, DL: dl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
3634 }
3635 Ops[1] = DAG.getZExtOrTrunc(
3636 Op: DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl,
3637 Reg: FuncInfo.ExceptionSelectorVirtReg,
3638 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
3639 DL: dl, VT: ValueVTs[1]);
3640
3641 // Merge into one.
3642 SDValue Res = DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl,
3643 VTList: DAG.getVTList(VTs: ValueVTs), Ops);
3644 setValue(V: &LP, NewN: Res);
3645}
3646
3647void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3648 MachineBasicBlock *Last) {
3649 // Update JTCases.
3650 for (JumpTableBlock &JTB : SL->JTCases)
3651 if (JTB.first.HeaderBB == First)
3652 JTB.first.HeaderBB = Last;
3653
3654 // Update BitTestCases.
3655 for (BitTestBlock &BTB : SL->BitTestCases)
3656 if (BTB.Parent == First)
3657 BTB.Parent = Last;
3658}
3659
3660void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3661 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3662
3663 // Update machine-CFG edges with unique successors.
3664 SmallPtrSet<BasicBlock *, 32> Done;
3665 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3666 BasicBlock *BB = I.getSuccessor(i);
3667 bool Inserted = Done.insert(Ptr: BB).second;
3668 if (!Inserted)
3669 continue;
3670
3671 MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3672 addSuccessorWithProb(Src: IndirectBrMBB, Dst: Succ);
3673 }
3674 IndirectBrMBB->normalizeSuccProbs();
3675
3676 DAG.setRoot(DAG.getNode(Opcode: ISD::BRIND, DL: getCurSDLoc(),
3677 VT: MVT::Other, N1: getControlRoot(),
3678 N2: getValue(V: I.getAddress())));
3679}
3680
3681void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3682 if (!I.shouldLowerToTrap(TrapUnreachable: DAG.getTarget().Options.TrapUnreachable,
3683 NoTrapAfterNoreturn: DAG.getTarget().Options.NoTrapAfterNoreturn))
3684 return;
3685
3686 DAG.setRoot(DAG.getNode(Opcode: ISD::TRAP, DL: getCurSDLoc(), VT: MVT::Other, Operand: DAG.getRoot()));
3687}
3688
3689void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3690 SDNodeFlags Flags;
3691 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
3692 Flags.copyFMF(FPMO: *FPOp);
3693
3694 SDValue Op = getValue(V: I.getOperand(i: 0));
3695 SDValue UnNodeValue = DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Op.getValueType(),
3696 Operand: Op, Flags);
3697 setValue(V: &I, NewN: UnNodeValue);
3698}
3699
3700void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3701 SDNodeFlags Flags;
3702 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(Val: &I)) {
3703 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3704 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3705 }
3706 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(Val: &I))
3707 Flags.setExact(ExactOp->isExact());
3708 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(Val: &I))
3709 Flags.setDisjoint(DisjointOp->isDisjoint());
3710 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
3711 Flags.copyFMF(FPMO: *FPOp);
3712
3713 SDValue Op1 = getValue(V: I.getOperand(i: 0));
3714 SDValue Op2 = getValue(V: I.getOperand(i: 1));
3715 SDValue BinNodeValue = DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Op1.getValueType(),
3716 N1: Op1, N2: Op2, Flags);
3717 setValue(V: &I, NewN: BinNodeValue);
3718}
3719
3720void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3721 SDValue Op1 = getValue(V: I.getOperand(i: 0));
3722 SDValue Op2 = getValue(V: I.getOperand(i: 1));
3723
3724 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3725 LHSTy: Op1.getValueType(), DL: DAG.getDataLayout());
3726
3727 // Coerce the shift amount to the right type if we can. This exposes the
3728 // truncate or zext to optimization early.
3729 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3730 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3731 "Unexpected shift type");
3732 Op2 = DAG.getZExtOrTrunc(Op: Op2, DL: getCurSDLoc(), VT: ShiftTy);
3733 }
3734
3735 bool nuw = false;
3736 bool nsw = false;
3737 bool exact = false;
3738
3739 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3740
3741 if (const OverflowingBinaryOperator *OFBinOp =
3742 dyn_cast<const OverflowingBinaryOperator>(Val: &I)) {
3743 nuw = OFBinOp->hasNoUnsignedWrap();
3744 nsw = OFBinOp->hasNoSignedWrap();
3745 }
3746 if (const PossiblyExactOperator *ExactOp =
3747 dyn_cast<const PossiblyExactOperator>(Val: &I))
3748 exact = ExactOp->isExact();
3749 }
3750 SDNodeFlags Flags;
3751 Flags.setExact(exact);
3752 Flags.setNoSignedWrap(nsw);
3753 Flags.setNoUnsignedWrap(nuw);
3754 SDValue Res = DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Op1.getValueType(), N1: Op1, N2: Op2,
3755 Flags);
3756 setValue(V: &I, NewN: Res);
3757}
3758
3759void SelectionDAGBuilder::visitSDiv(const User &I) {
3760 SDValue Op1 = getValue(V: I.getOperand(i: 0));
3761 SDValue Op2 = getValue(V: I.getOperand(i: 1));
3762
3763 SDNodeFlags Flags;
3764 Flags.setExact(isa<PossiblyExactOperator>(Val: &I) &&
3765 cast<PossiblyExactOperator>(Val: &I)->isExact());
3766 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SDIV, DL: getCurSDLoc(), VT: Op1.getValueType(), N1: Op1,
3767 N2: Op2, Flags));
3768}
3769
3770void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3771 ICmpInst::Predicate predicate = I.getPredicate();
3772 SDValue Op1 = getValue(V: I.getOperand(i_nocapture: 0));
3773 SDValue Op2 = getValue(V: I.getOperand(i_nocapture: 1));
3774 ISD::CondCode Opcode = getICmpCondCode(Pred: predicate);
3775
3776 auto &TLI = DAG.getTargetLoweringInfo();
3777 EVT MemVT =
3778 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i_nocapture: 0)->getType());
3779
3780 // If a pointer's DAG type is larger than its memory type then the DAG values
3781 // are zero-extended. This breaks signed comparisons so truncate back to the
3782 // underlying type before doing the compare.
3783 if (Op1.getValueType() != MemVT) {
3784 Op1 = DAG.getPtrExtOrTrunc(Op: Op1, DL: getCurSDLoc(), VT: MemVT);
3785 Op2 = DAG.getPtrExtOrTrunc(Op: Op2, DL: getCurSDLoc(), VT: MemVT);
3786 }
3787
3788 SDNodeFlags Flags;
3789 Flags.setSameSign(I.hasSameSign());
3790
3791 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
3792 Ty: I.getType());
3793 setValue(V: &I, NewN: DAG.getSetCC(DL: getCurSDLoc(), VT: DestVT, LHS: Op1, RHS: Op2, Cond: Opcode,
3794 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3795}
3796
3797void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3798 FCmpInst::Predicate predicate = I.getPredicate();
3799 SDValue Op1 = getValue(V: I.getOperand(i_nocapture: 0));
3800 SDValue Op2 = getValue(V: I.getOperand(i_nocapture: 1));
3801
3802 ISD::CondCode Condition = getFCmpCondCode(Pred: predicate);
3803 auto *FPMO = cast<FPMathOperator>(Val: &I);
3804 if (FPMO->hasNoNaNs() ||
3805 (DAG.isKnownNeverNaN(Op: Op1) && DAG.isKnownNeverNaN(Op: Op2)))
3806 Condition = getFCmpCodeWithoutNaN(CC: Condition);
3807
3808 SDNodeFlags Flags;
3809 Flags.copyFMF(FPMO: *FPMO);
3810
3811 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
3812 Ty: I.getType());
3813 setValue(V: &I, NewN: DAG.getSetCC(DL: getCurSDLoc(), VT: DestVT, LHS: Op1, RHS: Op2, Cond: Condition,
3814 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3815}
3816
3817// Check if the condition of the select has one use or two users that are both
3818// selects with the same condition.
3819static bool hasOnlySelectUsers(const Value *Cond) {
3820 return llvm::all_of(Range: Cond->users(), P: [](const Value *V) {
3821 return isa<SelectInst>(Val: V);
3822 });
3823}
3824
3825void SelectionDAGBuilder::visitSelect(const User &I) {
3826 SmallVector<EVT, 4> ValueVTs;
3827 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty: I.getType(),
3828 ValueVTs);
3829 unsigned NumValues = ValueVTs.size();
3830 if (NumValues == 0) return;
3831
3832 SmallVector<SDValue, 4> Values(NumValues);
3833 SDValue Cond = getValue(V: I.getOperand(i: 0));
3834 SDValue LHSVal = getValue(V: I.getOperand(i: 1));
3835 SDValue RHSVal = getValue(V: I.getOperand(i: 2));
3836 SmallVector<SDValue, 1> BaseOps(1, Cond);
3837 ISD::NodeType OpCode =
3838 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3839
3840 bool IsUnaryAbs = false;
3841 bool Negate = false;
3842
3843 SDNodeFlags Flags;
3844 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
3845 Flags.copyFMF(FPMO: *FPOp);
3846
3847 Flags.setUnpredictable(
3848 cast<SelectInst>(Val: I).getMetadata(KindID: LLVMContext::MD_unpredictable));
3849
3850 // Min/max matching is only viable if all output VTs are the same.
3851 if (all_equal(Range&: ValueVTs)) {
3852 EVT VT = ValueVTs[0];
3853 LLVMContext &Ctx = *DAG.getContext();
3854 auto &TLI = DAG.getTargetLoweringInfo();
3855
3856 // We care about the legality of the operation after it has been type
3857 // legalized.
3858 while (TLI.getTypeAction(Context&: Ctx, VT) != TargetLoweringBase::TypeLegal)
3859 VT = TLI.getTypeToTransformTo(Context&: Ctx, VT);
3860
3861 // If the vselect is legal, assume we want to leave this as a vector setcc +
3862 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3863 // min/max is legal on the scalar type.
3864 bool UseScalarMinMax = VT.isVector() &&
3865 !TLI.isOperationLegalOrCustom(Op: ISD::VSELECT, VT);
3866
3867 // ValueTracking's select pattern matching does not account for -0.0,
3868 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3869 // -0.0 is less than +0.0.
3870 const Value *LHS, *RHS;
3871 auto SPR = matchSelectPattern(V: &I, LHS, RHS);
3872 ISD::NodeType Opc = ISD::DELETED_NODE;
3873 switch (SPR.Flavor) {
3874 case SPF_UMAX: Opc = ISD::UMAX; break;
3875 case SPF_UMIN: Opc = ISD::UMIN; break;
3876 case SPF_SMAX: Opc = ISD::SMAX; break;
3877 case SPF_SMIN: Opc = ISD::SMIN; break;
3878 case SPF_FMINNUM:
3879 if (!TLI.isProfitableToCombineMinNumMaxNum(VT))
3880 break;
3881
3882 switch (SPR.NaNBehavior) {
3883 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3884 case SPNB_RETURNS_NAN: break;
3885 case SPNB_RETURNS_OTHER:
3886 Opc = ISD::FMINIMUMNUM;
3887 Flags.setNoSignedZeros(true);
3888 break;
3889 case SPNB_RETURNS_ANY:
3890 if (TLI.isOperationLegalOrCustom(Op: ISD::FMINNUM, VT) ||
3891 (UseScalarMinMax &&
3892 TLI.isOperationLegalOrCustom(Op: ISD::FMINNUM, VT: VT.getScalarType())))
3893 Opc = ISD::FMINNUM;
3894 break;
3895 }
3896 break;
3897 case SPF_FMAXNUM:
3898 if (!TLI.isProfitableToCombineMinNumMaxNum(VT))
3899 break;
3900
3901 switch (SPR.NaNBehavior) {
3902 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3903 case SPNB_RETURNS_NAN: break;
3904 case SPNB_RETURNS_OTHER:
3905 Opc = ISD::FMAXIMUMNUM;
3906 Flags.setNoSignedZeros(true);
3907 break;
3908 case SPNB_RETURNS_ANY:
3909 if (TLI.isOperationLegalOrCustom(Op: ISD::FMAXNUM, VT) ||
3910 (UseScalarMinMax &&
3911 TLI.isOperationLegalOrCustom(Op: ISD::FMAXNUM, VT: VT.getScalarType())))
3912 Opc = ISD::FMAXNUM;
3913 break;
3914 }
3915 break;
3916 case SPF_NABS:
3917 Negate = true;
3918 [[fallthrough]];
3919 case SPF_ABS:
3920 IsUnaryAbs = true;
3921 Opc = ISD::ABS;
3922 break;
3923 default: break;
3924 }
3925
3926 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3927 (TLI.isOperationLegalOrCustom(Op: Opc, VT) ||
3928 (UseScalarMinMax &&
3929 TLI.isOperationLegalOrCustom(Op: Opc, VT: VT.getScalarType()))) &&
3930 // If the underlying comparison instruction is used by any other
3931 // instruction, the consumed instructions won't be destroyed, so it is
3932 // not profitable to convert to a min/max.
3933 hasOnlySelectUsers(Cond: cast<SelectInst>(Val: I).getCondition())) {
3934 OpCode = Opc;
3935 LHSVal = getValue(V: LHS);
3936 RHSVal = getValue(V: RHS);
3937 BaseOps.clear();
3938 }
3939
3940 if (IsUnaryAbs) {
3941 OpCode = Opc;
3942 LHSVal = getValue(V: LHS);
3943 BaseOps.clear();
3944 }
3945 }
3946
3947 if (IsUnaryAbs) {
3948 for (unsigned i = 0; i != NumValues; ++i) {
3949 SDLoc dl = getCurSDLoc();
3950 EVT VT = LHSVal.getNode()->getValueType(ResNo: LHSVal.getResNo() + i);
3951 Values[i] =
3952 DAG.getNode(Opcode: OpCode, DL: dl, VT, Operand: LHSVal.getValue(R: LHSVal.getResNo() + i));
3953 if (Negate)
3954 Values[i] = DAG.getNegative(Val: Values[i], DL: dl, VT);
3955 }
3956 } else {
3957 for (unsigned i = 0; i != NumValues; ++i) {
3958 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3959 Ops.push_back(Elt: SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3960 Ops.push_back(Elt: SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3961 Values[i] = DAG.getNode(
3962 Opcode: OpCode, DL: getCurSDLoc(),
3963 VT: LHSVal.getNode()->getValueType(ResNo: LHSVal.getResNo() + i), Ops, Flags);
3964 }
3965 }
3966
3967 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
3968 VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values));
3969}
3970
3971void SelectionDAGBuilder::visitTrunc(const User &I) {
3972 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3973 SDValue N = getValue(V: I.getOperand(i: 0));
3974 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
3975 Ty: I.getType());
3976 SDNodeFlags Flags;
3977 if (auto *Trunc = dyn_cast<TruncInst>(Val: &I)) {
3978 Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
3979 Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
3980 }
3981
3982 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::TRUNCATE, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
3983}
3984
3985void SelectionDAGBuilder::visitZExt(const User &I) {
3986 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3987 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3988 SDValue N = getValue(V: I.getOperand(i: 0));
3989 auto &TLI = DAG.getTargetLoweringInfo();
3990 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
3991
3992 SDNodeFlags Flags;
3993 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(Val: &I))
3994 Flags.setNonNeg(PNI->hasNonNeg());
3995
3996 // Eagerly use nonneg information to canonicalize towards sign_extend if
3997 // that is the target's preference.
3998 // TODO: Let the target do this later.
3999 if (Flags.hasNonNeg() &&
4000 TLI.isSExtCheaperThanZExt(FromTy: N.getValueType(), ToTy: DestVT)) {
4001 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4002 return;
4003 }
4004
4005 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
4006}
4007
4008void SelectionDAGBuilder::visitSExt(const User &I) {
4009 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4010 // SExt also can't be a cast to bool for same reason. So, nothing much to do
4011 SDValue N = getValue(V: I.getOperand(i: 0));
4012 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4013 Ty: I.getType());
4014 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4015}
4016
4017void SelectionDAGBuilder::visitFPTrunc(const User &I) {
4018 // FPTrunc is never a no-op cast, no need to check
4019 SDValue N = getValue(V: I.getOperand(i: 0));
4020 SDLoc dl = getCurSDLoc();
4021 SDNodeFlags Flags;
4022 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
4023 Flags.copyFMF(FPMO: *FPOp);
4024 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4025 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4026 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_ROUND, DL: dl, VT: DestVT, N1: N,
4027 N2: DAG.getTargetConstant(
4028 Val: 0, DL: dl, VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
4029 Flags));
4030}
4031
4032void SelectionDAGBuilder::visitFPExt(const User &I) {
4033 // FPExt is never a no-op cast, no need to check
4034 SDValue N = getValue(V: I.getOperand(i: 0));
4035 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4036 Ty: I.getType());
4037 SDNodeFlags Flags;
4038 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
4039 Flags.copyFMF(FPMO: *FPOp);
4040 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
4041}
4042
4043void SelectionDAGBuilder::visitFPToUI(const User &I) {
4044 // FPToUI is never a no-op cast, no need to check
4045 SDValue N = getValue(V: I.getOperand(i: 0));
4046 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4047 Ty: I.getType());
4048 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_UINT, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4049}
4050
4051void SelectionDAGBuilder::visitFPToSI(const User &I) {
4052 // FPToSI is never a no-op cast, no need to check
4053 SDValue N = getValue(V: I.getOperand(i: 0));
4054 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4055 Ty: I.getType());
4056 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_SINT, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4057}
4058
4059void SelectionDAGBuilder::visitUIToFP(const User &I) {
4060 // UIToFP is never a no-op cast, no need to check
4061 SDValue N = getValue(V: I.getOperand(i: 0));
4062 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4063 Ty: I.getType());
4064 SDNodeFlags Flags;
4065 Flags.setNonNeg(cast<PossiblyNonNegInst>(Val: &I)->hasNonNeg());
4066 Flags.copyFMF(FPMO: *cast<FPMathOperator>(Val: &I));
4067
4068 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UINT_TO_FP, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
4069}
4070
4071void SelectionDAGBuilder::visitSIToFP(const User &I) {
4072 // SIToFP is never a no-op cast, no need to check
4073 SDValue N = getValue(V: I.getOperand(i: 0));
4074 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4075 Ty: I.getType());
4076 SDNodeFlags Flags;
4077 Flags.copyFMF(FPMO: *cast<FPMathOperator>(Val: &I));
4078
4079 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
4080}
4081
4082void SelectionDAGBuilder::visitPtrToAddr(const User &I) {
4083 SDValue N = getValue(V: I.getOperand(i: 0));
4084 // By definition the type of the ptrtoaddr must be equal to the address type.
4085 const auto &TLI = DAG.getTargetLoweringInfo();
4086 EVT AddrVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4087 // The address width must be smaller or equal to the pointer representation
4088 // width, so we lower ptrtoaddr as a truncate (possibly folded to a no-op).
4089 N = DAG.getNode(Opcode: ISD::TRUNCATE, DL: getCurSDLoc(), VT: AddrVT, Operand: N);
4090 setValue(V: &I, NewN: N);
4091}
4092
4093void SelectionDAGBuilder::visitPtrToInt(const User &I) {
4094 // What to do depends on the size of the integer and the size of the pointer.
4095 // We can either truncate, zero extend, or no-op, accordingly.
4096 SDValue N = getValue(V: I.getOperand(i: 0));
4097 auto &TLI = DAG.getTargetLoweringInfo();
4098 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4099 Ty: I.getType());
4100 EVT PtrMemVT =
4101 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i: 0)->getType());
4102 N = DAG.getPtrExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: PtrMemVT);
4103 N = DAG.getZExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: DestVT);
4104 setValue(V: &I, NewN: N);
4105}
4106
4107void SelectionDAGBuilder::visitIntToPtr(const User &I) {
4108 // What to do depends on the size of the integer and the size of the pointer.
4109 // We can either truncate, zero extend, or no-op, accordingly.
4110 SDValue N = getValue(V: I.getOperand(i: 0));
4111 auto &TLI = DAG.getTargetLoweringInfo();
4112 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4113 EVT PtrMemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4114 N = DAG.getZExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: PtrMemVT);
4115 N = DAG.getPtrExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: DestVT);
4116 setValue(V: &I, NewN: N);
4117}
4118
4119void SelectionDAGBuilder::visitBitCast(const User &I) {
4120 SDValue N = getValue(V: I.getOperand(i: 0));
4121 SDLoc dl = getCurSDLoc();
4122 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4123 Ty: I.getType());
4124
4125 // BitCast assures us that source and destination are the same size so this is
4126 // either a BITCAST or a no-op.
4127 if (DestVT != N.getValueType())
4128 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::BITCAST, DL: dl,
4129 VT: DestVT, Operand: N)); // convert types.
4130 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
4131 // might fold any kind of constant expression to an integer constant and that
4132 // is not what we are looking for. Only recognize a bitcast of a genuine
4133 // constant integer as an opaque constant.
4134 else if(ConstantInt *C = dyn_cast<ConstantInt>(Val: I.getOperand(i: 0)))
4135 setValue(V: &I, NewN: DAG.getConstant(Val: C->getValue(), DL: dl, VT: DestVT, /*isTarget=*/false,
4136 /*isOpaque*/true));
4137 else
4138 setValue(V: &I, NewN: N); // noop cast.
4139}
4140
4141void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
4142 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4143 const Value *SV = I.getOperand(i: 0);
4144 SDValue N = getValue(V: SV);
4145 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4146
4147 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
4148 unsigned DestAS = I.getType()->getPointerAddressSpace();
4149
4150 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
4151 N = DAG.getAddrSpaceCast(dl: getCurSDLoc(), VT: DestVT, Ptr: N, SrcAS, DestAS);
4152
4153 setValue(V: &I, NewN: N);
4154}
4155
4156void SelectionDAGBuilder::visitInsertElement(const User &I) {
4157 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4158 SDValue InVec = getValue(V: I.getOperand(i: 0));
4159 SDValue InVal = getValue(V: I.getOperand(i: 1));
4160 SDValue InIdx = DAG.getZExtOrTrunc(Op: getValue(V: I.getOperand(i: 2)), DL: getCurSDLoc(),
4161 VT: TLI.getVectorIdxTy(DL: DAG.getDataLayout()));
4162 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: getCurSDLoc(),
4163 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
4164 N1: InVec, N2: InVal, N3: InIdx));
4165}
4166
4167void SelectionDAGBuilder::visitExtractElement(const User &I) {
4168 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4169 SDValue InVec = getValue(V: I.getOperand(i: 0));
4170 SDValue InIdx = DAG.getZExtOrTrunc(Op: getValue(V: I.getOperand(i: 1)), DL: getCurSDLoc(),
4171 VT: TLI.getVectorIdxTy(DL: DAG.getDataLayout()));
4172 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: getCurSDLoc(),
4173 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
4174 N1: InVec, N2: InIdx));
4175}
4176
4177void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4178 SDValue Src1 = getValue(V: I.getOperand(i: 0));
4179 SDValue Src2 = getValue(V: I.getOperand(i: 1));
4180 ArrayRef<int> Mask;
4181 if (auto *SVI = dyn_cast<ShuffleVectorInst>(Val: &I))
4182 Mask = SVI->getShuffleMask();
4183 else
4184 Mask = cast<ConstantExpr>(Val: I).getShuffleMask();
4185 SDLoc DL = getCurSDLoc();
4186 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4187 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4188 EVT SrcVT = Src1.getValueType();
4189
4190 if (all_of(Range&: Mask, P: equal_to(Arg: 0)) && VT.isScalableVector()) {
4191 // Canonical splat form of first element of first input vector.
4192 SDValue FirstElt =
4193 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: SrcVT.getScalarType(), N1: Src1,
4194 N2: DAG.getVectorIdxConstant(Val: 0, DL));
4195 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SPLAT_VECTOR, DL, VT, Operand: FirstElt));
4196 return;
4197 }
4198
4199 // For now, we only handle splats for scalable vectors.
4200 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4201 // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4202 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4203
4204 unsigned SrcNumElts = SrcVT.getVectorNumElements();
4205 unsigned MaskNumElts = Mask.size();
4206
4207 if (SrcNumElts == MaskNumElts) {
4208 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: Src1, N2: Src2, Mask));
4209 return;
4210 }
4211
4212 // Normalize the shuffle vector since mask and vector length don't match.
4213 if (SrcNumElts < MaskNumElts) {
4214 // Mask is longer than the source vectors. We can use concatenate vector to
4215 // make the mask and vectors lengths match.
4216
4217 if (MaskNumElts % SrcNumElts == 0) {
4218 // Mask length is a multiple of the source vector length.
4219 // Check if the shuffle is some kind of concatenation of the input
4220 // vectors.
4221 unsigned NumConcat = MaskNumElts / SrcNumElts;
4222 bool IsConcat = true;
4223 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4224 for (unsigned i = 0; i != MaskNumElts; ++i) {
4225 int Idx = Mask[i];
4226 if (Idx < 0)
4227 continue;
4228 // Ensure the indices in each SrcVT sized piece are sequential and that
4229 // the same source is used for the whole piece.
4230 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4231 (ConcatSrcs[i / SrcNumElts] >= 0 &&
4232 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4233 IsConcat = false;
4234 break;
4235 }
4236 // Remember which source this index came from.
4237 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4238 }
4239
4240 // The shuffle is concatenating multiple vectors together. Just emit
4241 // a CONCAT_VECTORS operation.
4242 if (IsConcat) {
4243 SmallVector<SDValue, 8> ConcatOps;
4244 for (auto Src : ConcatSrcs) {
4245 if (Src < 0)
4246 ConcatOps.push_back(Elt: DAG.getUNDEF(VT: SrcVT));
4247 else if (Src == 0)
4248 ConcatOps.push_back(Elt: Src1);
4249 else
4250 ConcatOps.push_back(Elt: Src2);
4251 }
4252 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT, Ops: ConcatOps));
4253 return;
4254 }
4255 }
4256
4257 unsigned PaddedMaskNumElts = alignTo(Value: MaskNumElts, Align: SrcNumElts);
4258 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4259 EVT PaddedVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: VT.getScalarType(),
4260 NumElements: PaddedMaskNumElts);
4261
4262 // Pad both vectors with undefs to make them the same length as the mask.
4263 SDValue UndefVal = DAG.getUNDEF(VT: SrcVT);
4264
4265 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4266 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4267 MOps1[0] = Src1;
4268 MOps2[0] = Src2;
4269
4270 Src1 = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: PaddedVT, Ops: MOps1);
4271 Src2 = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: PaddedVT, Ops: MOps2);
4272
4273 // Readjust mask for new input vector length.
4274 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4275 for (unsigned i = 0; i != MaskNumElts; ++i) {
4276 int Idx = Mask[i];
4277 if (Idx >= (int)SrcNumElts)
4278 Idx -= SrcNumElts - PaddedMaskNumElts;
4279 MappedOps[i] = Idx;
4280 }
4281
4282 SDValue Result = DAG.getVectorShuffle(VT: PaddedVT, dl: DL, N1: Src1, N2: Src2, Mask: MappedOps);
4283
4284 // If the concatenated vector was padded, extract a subvector with the
4285 // correct number of elements.
4286 if (MaskNumElts != PaddedMaskNumElts)
4287 Result = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT, N1: Result,
4288 N2: DAG.getVectorIdxConstant(Val: 0, DL));
4289
4290 setValue(V: &I, NewN: Result);
4291 return;
4292 }
4293
4294 assert(SrcNumElts > MaskNumElts);
4295
4296 // Analyze the access pattern of the vector to see if we can extract
4297 // two subvectors and do the shuffle.
4298 int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4299 bool CanExtract = true;
4300 for (int Idx : Mask) {
4301 unsigned Input = 0;
4302 if (Idx < 0)
4303 continue;
4304
4305 if (Idx >= (int)SrcNumElts) {
4306 Input = 1;
4307 Idx -= SrcNumElts;
4308 }
4309
4310 // If all the indices come from the same MaskNumElts sized portion of
4311 // the sources we can use extract. Also make sure the extract wouldn't
4312 // extract past the end of the source.
4313 int NewStartIdx = alignDown(Value: Idx, Align: MaskNumElts);
4314 if (NewStartIdx + MaskNumElts > SrcNumElts ||
4315 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4316 CanExtract = false;
4317 // Make sure we always update StartIdx as we use it to track if all
4318 // elements are undef.
4319 StartIdx[Input] = NewStartIdx;
4320 }
4321
4322 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4323 setValue(V: &I, NewN: DAG.getUNDEF(VT)); // Vectors are not used.
4324 return;
4325 }
4326 if (CanExtract) {
4327 // Extract appropriate subvector and generate a vector shuffle
4328 for (unsigned Input = 0; Input < 2; ++Input) {
4329 SDValue &Src = Input == 0 ? Src1 : Src2;
4330 if (StartIdx[Input] < 0)
4331 Src = DAG.getUNDEF(VT);
4332 else {
4333 Src = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT, N1: Src,
4334 N2: DAG.getVectorIdxConstant(Val: StartIdx[Input], DL));
4335 }
4336 }
4337
4338 // Calculate new mask.
4339 SmallVector<int, 8> MappedOps(Mask);
4340 for (int &Idx : MappedOps) {
4341 if (Idx >= (int)SrcNumElts)
4342 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4343 else if (Idx >= 0)
4344 Idx -= StartIdx[0];
4345 }
4346
4347 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: Src1, N2: Src2, Mask: MappedOps));
4348 return;
4349 }
4350
4351 // We can't use either concat vectors or extract subvectors so fall back to
4352 // replacing the shuffle with extract and build vector.
4353 // to insert and build vector.
4354 EVT EltVT = VT.getVectorElementType();
4355 SmallVector<SDValue,8> Ops;
4356 for (int Idx : Mask) {
4357 SDValue Res;
4358
4359 if (Idx < 0) {
4360 Res = DAG.getUNDEF(VT: EltVT);
4361 } else {
4362 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4363 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4364
4365 Res = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: EltVT, N1: Src,
4366 N2: DAG.getVectorIdxConstant(Val: Idx, DL));
4367 }
4368
4369 Ops.push_back(Elt: Res);
4370 }
4371
4372 setValue(V: &I, NewN: DAG.getBuildVector(VT, DL, Ops));
4373}
4374
4375void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4376 ArrayRef<unsigned> Indices = I.getIndices();
4377 const Value *Op0 = I.getOperand(i_nocapture: 0);
4378 const Value *Op1 = I.getOperand(i_nocapture: 1);
4379 Type *AggTy = I.getType();
4380 Type *ValTy = Op1->getType();
4381 bool IntoUndef = isa<UndefValue>(Val: Op0);
4382 bool FromUndef = isa<UndefValue>(Val: Op1);
4383
4384 unsigned LinearIndex = ComputeLinearIndex(Ty: AggTy, Indices);
4385
4386 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4387 SmallVector<EVT, 4> AggValueVTs;
4388 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: AggTy, ValueVTs&: AggValueVTs);
4389 SmallVector<EVT, 4> ValValueVTs;
4390 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: ValTy, ValueVTs&: ValValueVTs);
4391
4392 unsigned NumAggValues = AggValueVTs.size();
4393 unsigned NumValValues = ValValueVTs.size();
4394 SmallVector<SDValue, 4> Values(NumAggValues);
4395
4396 // Ignore an insertvalue that produces an empty object
4397 if (!NumAggValues) {
4398 setValue(V: &I, NewN: DAG.getUNDEF(VT: MVT(MVT::Other)));
4399 return;
4400 }
4401
4402 SDValue Agg = getValue(V: Op0);
4403 unsigned i = 0;
4404 // Copy the beginning value(s) from the original aggregate.
4405 for (; i != LinearIndex; ++i)
4406 Values[i] = IntoUndef ? DAG.getUNDEF(VT: AggValueVTs[i]) :
4407 SDValue(Agg.getNode(), Agg.getResNo() + i);
4408 // Copy values from the inserted value(s).
4409 if (NumValValues) {
4410 SDValue Val = getValue(V: Op1);
4411 for (; i != LinearIndex + NumValValues; ++i)
4412 Values[i] = FromUndef ? DAG.getUNDEF(VT: AggValueVTs[i]) :
4413 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4414 }
4415 // Copy remaining value(s) from the original aggregate.
4416 for (; i != NumAggValues; ++i)
4417 Values[i] = IntoUndef ? DAG.getUNDEF(VT: AggValueVTs[i]) :
4418 SDValue(Agg.getNode(), Agg.getResNo() + i);
4419
4420 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
4421 VTList: DAG.getVTList(VTs: AggValueVTs), Ops: Values));
4422}
4423
4424void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4425 ArrayRef<unsigned> Indices = I.getIndices();
4426 const Value *Op0 = I.getOperand(i_nocapture: 0);
4427 Type *AggTy = Op0->getType();
4428 Type *ValTy = I.getType();
4429 bool OutOfUndef = isa<UndefValue>(Val: Op0);
4430
4431 unsigned LinearIndex = ComputeLinearIndex(Ty: AggTy, Indices);
4432
4433 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4434 SmallVector<EVT, 4> ValValueVTs;
4435 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: ValTy, ValueVTs&: ValValueVTs);
4436
4437 unsigned NumValValues = ValValueVTs.size();
4438
4439 // Ignore a extractvalue that produces an empty object
4440 if (!NumValValues) {
4441 setValue(V: &I, NewN: DAG.getUNDEF(VT: MVT(MVT::Other)));
4442 return;
4443 }
4444
4445 SmallVector<SDValue, 4> Values(NumValValues);
4446
4447 SDValue Agg = getValue(V: Op0);
4448 // Copy out the selected value(s).
4449 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4450 Values[i - LinearIndex] =
4451 OutOfUndef ?
4452 DAG.getUNDEF(VT: Agg.getNode()->getValueType(ResNo: Agg.getResNo() + i)) :
4453 SDValue(Agg.getNode(), Agg.getResNo() + i);
4454
4455 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
4456 VTList: DAG.getVTList(VTs: ValValueVTs), Ops: Values));
4457}
4458
4459void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4460 Value *Op0 = I.getOperand(i: 0);
4461 // Note that the pointer operand may be a vector of pointers. Take the scalar
4462 // element which holds a pointer.
4463 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4464 SDValue N = getValue(V: Op0);
4465 SDLoc dl = getCurSDLoc();
4466 auto &TLI = DAG.getTargetLoweringInfo();
4467 GEPNoWrapFlags NW = cast<GEPOperator>(Val: I).getNoWrapFlags();
4468
4469 // For a vector GEP, keep the prefix scalar as long as possible, then
4470 // convert any scalars encountered after the first vector operand to vectors.
4471 bool IsVectorGEP = I.getType()->isVectorTy();
4472 ElementCount VectorElementCount =
4473 IsVectorGEP ? cast<VectorType>(Val: I.getType())->getElementCount()
4474 : ElementCount::getFixed(MinVal: 0);
4475
4476 for (gep_type_iterator GTI = gep_type_begin(GEP: &I), E = gep_type_end(GEP: &I);
4477 GTI != E; ++GTI) {
4478 const Value *Idx = GTI.getOperand();
4479 if (StructType *StTy = GTI.getStructTypeOrNull()) {
4480 unsigned Field = cast<Constant>(Val: Idx)->getUniqueInteger().getZExtValue();
4481 if (Field) {
4482 // N = N + Offset
4483 uint64_t Offset =
4484 DAG.getDataLayout().getStructLayout(Ty: StTy)->getElementOffset(Idx: Field);
4485
4486 // In an inbounds GEP with an offset that is nonnegative even when
4487 // interpreted as signed, assume there is no unsigned overflow.
4488 SDNodeFlags Flags;
4489 if (NW.hasNoUnsignedWrap() ||
4490 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4491 Flags |= SDNodeFlags::NoUnsignedWrap;
4492 Flags.setInBounds(NW.isInBounds());
4493
4494 N = DAG.getMemBasePlusOffset(
4495 Base: N, Offset: DAG.getConstant(Val: Offset, DL: dl, VT: N.getValueType()), DL: dl, Flags);
4496 }
4497 } else {
4498 // IdxSize is the width of the arithmetic according to IR semantics.
4499 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4500 // (and fix up the result later).
4501 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4502 MVT IdxTy = MVT::getIntegerVT(BitWidth: IdxSize);
4503 TypeSize ElementSize =
4504 GTI.getSequentialElementStride(DL: DAG.getDataLayout());
4505 // We intentionally mask away the high bits here; ElementSize may not
4506 // fit in IdxTy.
4507 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4508 /*isSigned=*/false, /*implicitTrunc=*/true);
4509 bool ElementScalable = ElementSize.isScalable();
4510
4511 // If this is a scalar constant or a splat vector of constants,
4512 // handle it quickly.
4513 const auto *C = dyn_cast<Constant>(Val: Idx);
4514 if (C && isa<VectorType>(Val: C->getType()))
4515 C = C->getSplatValue();
4516
4517 const auto *CI = dyn_cast_or_null<ConstantInt>(Val: C);
4518 if (CI && CI->isZero())
4519 continue;
4520 if (CI && !ElementScalable) {
4521 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(width: IdxSize);
4522 LLVMContext &Context = *DAG.getContext();
4523 SDValue OffsVal;
4524 if (N.getValueType().isVector())
4525 OffsVal = DAG.getConstant(
4526 Val: Offs, DL: dl, VT: EVT::getVectorVT(Context, VT: IdxTy, EC: VectorElementCount));
4527 else
4528 OffsVal = DAG.getConstant(Val: Offs, DL: dl, VT: IdxTy);
4529
4530 // In an inbounds GEP with an offset that is nonnegative even when
4531 // interpreted as signed, assume there is no unsigned overflow.
4532 SDNodeFlags Flags;
4533 if (NW.hasNoUnsignedWrap() ||
4534 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4535 Flags.setNoUnsignedWrap(true);
4536 Flags.setInBounds(NW.isInBounds());
4537
4538 OffsVal = DAG.getSExtOrTrunc(Op: OffsVal, DL: dl, VT: N.getValueType());
4539
4540 N = DAG.getMemBasePlusOffset(Base: N, Offset: OffsVal, DL: dl, Flags);
4541 continue;
4542 }
4543
4544 // N = N + Idx * ElementMul;
4545 SDValue IdxN = getValue(V: Idx);
4546
4547 if (IdxN.getValueType().isVector() != N.getValueType().isVector()) {
4548 if (N.getValueType().isVector()) {
4549 EVT VT = EVT::getVectorVT(Context&: *Context, VT: IdxN.getValueType(),
4550 EC: VectorElementCount);
4551 IdxN = DAG.getSplat(VT, DL: dl, Op: IdxN);
4552 } else {
4553 EVT VT =
4554 EVT::getVectorVT(Context&: *Context, VT: N.getValueType(), EC: VectorElementCount);
4555 N = DAG.getSplat(VT, DL: dl, Op: N);
4556 }
4557 }
4558
4559 // If the index is smaller or larger than intptr_t, truncate or extend
4560 // it.
4561 IdxN = DAG.getSExtOrTrunc(Op: IdxN, DL: dl, VT: N.getValueType());
4562
4563 SDNodeFlags ScaleFlags;
4564 // The multiplication of an index by the type size does not wrap the
4565 // pointer index type in a signed sense (mul nsw).
4566 ScaleFlags.setNoSignedWrap(NW.hasNoUnsignedSignedWrap());
4567
4568 // The multiplication of an index by the type size does not wrap the
4569 // pointer index type in an unsigned sense (mul nuw).
4570 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4571
4572 if (ElementScalable) {
4573 EVT VScaleTy = N.getValueType().getScalarType();
4574 SDValue VScale = DAG.getNode(
4575 Opcode: ISD::VSCALE, DL: dl, VT: VScaleTy,
4576 Operand: DAG.getConstant(Val: ElementMul.getZExtValue(), DL: dl, VT: VScaleTy));
4577 if (N.getValueType().isVector())
4578 VScale = DAG.getSplatVector(VT: N.getValueType(), DL: dl, Op: VScale);
4579 IdxN = DAG.getNode(Opcode: ISD::MUL, DL: dl, VT: N.getValueType(), N1: IdxN, N2: VScale,
4580 Flags: ScaleFlags);
4581 } else {
4582 // If this is a multiply by a power of two, turn it into a shl
4583 // immediately. This is a very common case.
4584 if (ElementMul != 1) {
4585 if (ElementMul.isPowerOf2()) {
4586 unsigned Amt = ElementMul.logBase2();
4587 IdxN = DAG.getNode(
4588 Opcode: ISD::SHL, DL: dl, VT: N.getValueType(), N1: IdxN,
4589 N2: DAG.getShiftAmountConstant(Val: Amt, VT: N.getValueType(), DL: dl),
4590 Flags: ScaleFlags);
4591 } else {
4592 SDValue Scale = DAG.getConstant(Val: ElementMul.getZExtValue(), DL: dl,
4593 VT: IdxN.getValueType());
4594 IdxN = DAG.getNode(Opcode: ISD::MUL, DL: dl, VT: N.getValueType(), N1: IdxN, N2: Scale,
4595 Flags: ScaleFlags);
4596 }
4597 }
4598 }
4599
4600 // The successive addition of the current address, truncated to the
4601 // pointer index type and interpreted as an unsigned number, and each
4602 // offset, also interpreted as an unsigned number, does not wrap the
4603 // pointer index type (add nuw).
4604 SDNodeFlags AddFlags;
4605 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4606 AddFlags.setInBounds(NW.isInBounds());
4607
4608 N = DAG.getMemBasePlusOffset(Base: N, Offset: IdxN, DL: dl, Flags: AddFlags);
4609 }
4610 }
4611
4612 if (IsVectorGEP && !N.getValueType().isVector()) {
4613 EVT VT = EVT::getVectorVT(Context&: *Context, VT: N.getValueType(), EC: VectorElementCount);
4614 N = DAG.getSplat(VT, DL: dl, Op: N);
4615 }
4616
4617 MVT PtrTy = TLI.getPointerTy(DL: DAG.getDataLayout(), AS);
4618 MVT PtrMemTy = TLI.getPointerMemTy(DL: DAG.getDataLayout(), AS);
4619 if (IsVectorGEP) {
4620 PtrTy = MVT::getVectorVT(VT: PtrTy, EC: VectorElementCount);
4621 PtrMemTy = MVT::getVectorVT(VT: PtrMemTy, EC: VectorElementCount);
4622 }
4623
4624 if (PtrMemTy != PtrTy && !cast<GEPOperator>(Val: I).isInBounds())
4625 N = DAG.getPtrExtendInReg(Op: N, DL: dl, VT: PtrMemTy);
4626
4627 setValue(V: &I, NewN: N);
4628}
4629
4630void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4631 // If this is a fixed sized alloca in the entry block of the function,
4632 // allocate it statically on the stack.
4633 if (FuncInfo.StaticAllocaMap.count(Val: &I))
4634 return; // getValue will auto-populate this.
4635
4636 SDLoc dl = getCurSDLoc();
4637 Type *Ty = I.getAllocatedType();
4638 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4639 auto &DL = DAG.getDataLayout();
4640 TypeSize TySize = DL.getTypeAllocSize(Ty);
4641 MaybeAlign Alignment = I.getAlign();
4642
4643 SDValue AllocSize = getValue(V: I.getArraySize());
4644
4645 EVT IntPtr = TLI.getPointerTy(DL, AS: I.getAddressSpace());
4646 if (AllocSize.getValueType() != IntPtr)
4647 AllocSize = DAG.getZExtOrTrunc(Op: AllocSize, DL: dl, VT: IntPtr);
4648
4649 AllocSize = DAG.getNode(
4650 Opcode: ISD::MUL, DL: dl, VT: IntPtr, N1: AllocSize,
4651 N2: DAG.getZExtOrTrunc(Op: DAG.getTypeSize(DL: dl, VT: MVT::i64, TS: TySize), DL: dl, VT: IntPtr));
4652
4653 // Handle alignment. If the requested alignment is less than or equal to
4654 // the stack alignment, ignore it. If the size is greater than or equal to
4655 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4656 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4657 if (*Alignment <= StackAlign)
4658 Alignment = std::nullopt;
4659
4660 const uint64_t StackAlignMask = StackAlign.value() - 1U;
4661 // Round the size of the allocation up to the stack alignment size
4662 // by add SA-1 to the size. This doesn't overflow because we're computing
4663 // an address inside an alloca.
4664 AllocSize = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: AllocSize.getValueType(), N1: AllocSize,
4665 N2: DAG.getConstant(Val: StackAlignMask, DL: dl, VT: IntPtr),
4666 Flags: SDNodeFlags::NoUnsignedWrap);
4667
4668 // Mask out the low bits for alignment purposes.
4669 AllocSize = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: AllocSize.getValueType(), N1: AllocSize,
4670 N2: DAG.getSignedConstant(Val: ~StackAlignMask, DL: dl, VT: IntPtr));
4671
4672 SDValue Ops[] = {
4673 getRoot(), AllocSize,
4674 DAG.getConstant(Val: Alignment ? Alignment->value() : 0, DL: dl, VT: IntPtr)};
4675 SDVTList VTs = DAG.getVTList(VT1: AllocSize.getValueType(), VT2: MVT::Other);
4676 SDValue DSA = DAG.getNode(Opcode: ISD::DYNAMIC_STACKALLOC, DL: dl, VTList: VTs, Ops);
4677 setValue(V: &I, NewN: DSA);
4678 DAG.setRoot(DSA.getValue(R: 1));
4679
4680 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4681}
4682
4683static const MDNode *getRangeMetadata(const Instruction &I) {
4684 return I.getMetadata(KindID: LLVMContext::MD_range);
4685}
4686
4687static std::optional<ConstantRange> getRange(const Instruction &I) {
4688 if (const auto *CB = dyn_cast<CallBase>(Val: &I))
4689 if (std::optional<ConstantRange> CR = CB->getRange())
4690 return CR;
4691 if (const MDNode *Range = getRangeMetadata(I))
4692 return getConstantRangeFromMetadata(RangeMD: *Range);
4693 return std::nullopt;
4694}
4695
4696static FPClassTest getNoFPClass(const Instruction &I) {
4697 if (const auto *CB = dyn_cast<CallBase>(Val: &I))
4698 return CB->getRetNoFPClass();
4699 return fcNone;
4700}
4701
4702void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4703 if (I.isAtomic())
4704 return visitAtomicLoad(I);
4705
4706 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4707 const Value *SV = I.getOperand(i_nocapture: 0);
4708 if (TLI.supportSwiftError()) {
4709 // Swifterror values can come from either a function parameter with
4710 // swifterror attribute or an alloca with swifterror attribute.
4711 if (const Argument *Arg = dyn_cast<Argument>(Val: SV)) {
4712 if (Arg->hasSwiftErrorAttr())
4713 return visitLoadFromSwiftError(I);
4714 }
4715
4716 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(Val: SV)) {
4717 if (Alloca->isSwiftError())
4718 return visitLoadFromSwiftError(I);
4719 }
4720 }
4721
4722 SDValue Ptr = getValue(V: SV);
4723
4724 Type *Ty = I.getType();
4725 SmallVector<EVT, 4> ValueVTs, MemVTs;
4726 SmallVector<TypeSize, 4> Offsets;
4727 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty, ValueVTs, MemVTs: &MemVTs, Offsets: &Offsets);
4728 unsigned NumValues = ValueVTs.size();
4729 if (NumValues == 0)
4730 return;
4731
4732 Align Alignment = I.getAlign();
4733 AAMDNodes AAInfo = I.getAAMetadata();
4734 const MDNode *Ranges = getRangeMetadata(I);
4735 bool isVolatile = I.isVolatile();
4736 MachineMemOperand::Flags MMOFlags =
4737 TLI.getLoadMemOperandFlags(LI: I, DL: DAG.getDataLayout(), AC, LibInfo);
4738
4739 SDValue Root;
4740 bool ConstantMemory = false;
4741 if (isVolatile)
4742 // Serialize volatile loads with other side effects.
4743 Root = getRoot();
4744 else if (NumValues > MaxParallelChains)
4745 Root = getMemoryRoot();
4746 else if (BatchAA &&
4747 BatchAA->pointsToConstantMemory(Loc: MemoryLocation(
4748 SV,
4749 LocationSize::precise(Value: DAG.getDataLayout().getTypeStoreSize(Ty)),
4750 AAInfo))) {
4751 // Do not serialize (non-volatile) loads of constant memory with anything.
4752 Root = DAG.getEntryNode();
4753 ConstantMemory = true;
4754 MMOFlags |= MachineMemOperand::MOInvariant;
4755 } else {
4756 // Do not serialize non-volatile loads against each other.
4757 Root = DAG.getRoot();
4758 }
4759
4760 SDLoc dl = getCurSDLoc();
4761
4762 if (isVolatile)
4763 Root = TLI.prepareVolatileOrAtomicLoad(Chain: Root, DL: dl, DAG);
4764
4765 SmallVector<SDValue, 4> Values(NumValues);
4766 SmallVector<SDValue, 4> Chains(std::min(a: MaxParallelChains, b: NumValues));
4767
4768 unsigned ChainI = 0;
4769 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4770 // Serializing loads here may result in excessive register pressure, and
4771 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4772 // could recover a bit by hoisting nodes upward in the chain by recognizing
4773 // they are side-effect free or do not alias. The optimizer should really
4774 // avoid this case by converting large object/array copies to llvm.memcpy
4775 // (MaxParallelChains should always remain as failsafe).
4776 if (ChainI == MaxParallelChains) {
4777 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4778 SDValue Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4779 Ops: ArrayRef(Chains.data(), ChainI));
4780 Root = Chain;
4781 ChainI = 0;
4782 }
4783
4784 // TODO: MachinePointerInfo only supports a fixed length offset.
4785 MachinePointerInfo PtrInfo =
4786 !Offsets[i].isScalable() || Offsets[i].isZero()
4787 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4788 : MachinePointerInfo();
4789
4790 SDValue A = DAG.getObjectPtrOffset(SL: dl, Ptr, Offset: Offsets[i]);
4791 SDValue L = DAG.getLoad(VT: MemVTs[i], dl, Chain: Root, Ptr: A, PtrInfo, Alignment,
4792 MMOFlags, AAInfo, Ranges);
4793 Chains[ChainI] = L.getValue(R: 1);
4794
4795 if (MemVTs[i] != ValueVTs[i])
4796 L = DAG.getPtrExtOrTrunc(Op: L, DL: dl, VT: ValueVTs[i]);
4797
4798 if (MDNode *NoFPClassMD = I.getMetadata(KindID: LLVMContext::MD_nofpclass)) {
4799 uint64_t FPTestInt =
4800 cast<ConstantInt>(
4801 Val: cast<ConstantAsMetadata>(Val: NoFPClassMD->getOperand(I: 0))->getValue())
4802 ->getZExtValue();
4803 if (FPTestInt != fcNone) {
4804 SDValue FPTestConst =
4805 DAG.getTargetConstant(Val: FPTestInt, DL: SDLoc(), VT: MVT::i32);
4806 L = DAG.getNode(Opcode: ISD::AssertNoFPClass, DL: dl, VT: L.getValueType(), N1: L,
4807 N2: FPTestConst);
4808 }
4809 }
4810 Values[i] = L;
4811 }
4812
4813 if (!ConstantMemory) {
4814 SDValue Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4815 Ops: ArrayRef(Chains.data(), ChainI));
4816 if (isVolatile)
4817 DAG.setRoot(Chain);
4818 else
4819 PendingLoads.push_back(Elt: Chain);
4820 }
4821
4822 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl,
4823 VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values));
4824}
4825
4826void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4827 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4828 "call visitStoreToSwiftError when backend supports swifterror");
4829
4830 SmallVector<EVT, 4> ValueVTs;
4831 SmallVector<uint64_t, 4> Offsets;
4832 const Value *SrcV = I.getOperand(i_nocapture: 0);
4833 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(),
4834 Ty: SrcV->getType(), ValueVTs, /*MemVTs=*/nullptr, FixedOffsets: &Offsets, StartingOffset: 0);
4835 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4836 "expect a single EVT for swifterror");
4837
4838 SDValue Src = getValue(V: SrcV);
4839 // Create a virtual register, then update the virtual register.
4840 Register VReg =
4841 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4842 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4843 // Chain can be getRoot or getControlRoot.
4844 SDValue CopyNode = DAG.getCopyToReg(Chain: getRoot(), dl: getCurSDLoc(), Reg: VReg,
4845 N: SDValue(Src.getNode(), Src.getResNo()));
4846 DAG.setRoot(CopyNode);
4847}
4848
4849void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4850 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4851 "call visitLoadFromSwiftError when backend supports swifterror");
4852
4853 assert(!I.isVolatile() &&
4854 !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4855 !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4856 "Support volatile, non temporal, invariant for load_from_swift_error");
4857
4858 const Value *SV = I.getOperand(i_nocapture: 0);
4859 Type *Ty = I.getType();
4860 assert(
4861 (!BatchAA ||
4862 !BatchAA->pointsToConstantMemory(MemoryLocation(
4863 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4864 I.getAAMetadata()))) &&
4865 "load_from_swift_error should not be constant memory");
4866
4867 SmallVector<EVT, 4> ValueVTs;
4868 SmallVector<uint64_t, 4> Offsets;
4869 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty,
4870 ValueVTs, /*MemVTs=*/nullptr, FixedOffsets: &Offsets, StartingOffset: 0);
4871 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4872 "expect a single EVT for swifterror");
4873
4874 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4875 SDValue L = DAG.getCopyFromReg(
4876 Chain: getRoot(), dl: getCurSDLoc(),
4877 Reg: SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), VT: ValueVTs[0]);
4878
4879 setValue(V: &I, NewN: L);
4880}
4881
4882void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4883 if (I.isAtomic())
4884 return visitAtomicStore(I);
4885
4886 const Value *SrcV = I.getOperand(i_nocapture: 0);
4887 const Value *PtrV = I.getOperand(i_nocapture: 1);
4888
4889 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4890 if (TLI.supportSwiftError()) {
4891 // Swifterror values can come from either a function parameter with
4892 // swifterror attribute or an alloca with swifterror attribute.
4893 if (const Argument *Arg = dyn_cast<Argument>(Val: PtrV)) {
4894 if (Arg->hasSwiftErrorAttr())
4895 return visitStoreToSwiftError(I);
4896 }
4897
4898 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(Val: PtrV)) {
4899 if (Alloca->isSwiftError())
4900 return visitStoreToSwiftError(I);
4901 }
4902 }
4903
4904 SmallVector<EVT, 4> ValueVTs, MemVTs;
4905 SmallVector<TypeSize, 4> Offsets;
4906 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(),
4907 Ty: SrcV->getType(), ValueVTs, MemVTs: &MemVTs, Offsets: &Offsets);
4908 unsigned NumValues = ValueVTs.size();
4909 if (NumValues == 0)
4910 return;
4911
4912 // Get the lowered operands. Note that we do this after
4913 // checking if NumResults is zero, because with zero results
4914 // the operands won't have values in the map.
4915 SDValue Src = getValue(V: SrcV);
4916 SDValue Ptr = getValue(V: PtrV);
4917
4918 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4919 SmallVector<SDValue, 4> Chains(std::min(a: MaxParallelChains, b: NumValues));
4920 SDLoc dl = getCurSDLoc();
4921 Align Alignment = I.getAlign();
4922 AAMDNodes AAInfo = I.getAAMetadata();
4923
4924 auto MMOFlags = TLI.getStoreMemOperandFlags(SI: I, DL: DAG.getDataLayout());
4925
4926 unsigned ChainI = 0;
4927 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4928 // See visitLoad comments.
4929 if (ChainI == MaxParallelChains) {
4930 SDValue Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4931 Ops: ArrayRef(Chains.data(), ChainI));
4932 Root = Chain;
4933 ChainI = 0;
4934 }
4935
4936 // TODO: MachinePointerInfo only supports a fixed length offset.
4937 MachinePointerInfo PtrInfo =
4938 !Offsets[i].isScalable() || Offsets[i].isZero()
4939 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4940 : MachinePointerInfo();
4941
4942 SDValue Add = DAG.getObjectPtrOffset(SL: dl, Ptr, Offset: Offsets[i]);
4943 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4944 if (MemVTs[i] != ValueVTs[i])
4945 Val = DAG.getPtrExtOrTrunc(Op: Val, DL: dl, VT: MemVTs[i]);
4946 SDValue St =
4947 DAG.getStore(Chain: Root, dl, Val, Ptr: Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4948 Chains[ChainI] = St;
4949 }
4950
4951 SDValue StoreNode = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4952 Ops: ArrayRef(Chains.data(), ChainI));
4953 setValue(V: &I, NewN: StoreNode);
4954 DAG.setRoot(StoreNode);
4955}
4956
4957void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4958 bool IsCompressing) {
4959 SDLoc sdl = getCurSDLoc();
4960
4961 Value *Src0Operand = I.getArgOperand(i: 0);
4962 Value *PtrOperand = I.getArgOperand(i: 1);
4963 Value *MaskOperand = I.getArgOperand(i: 2);
4964 Align Alignment = I.getParamAlign(ArgNo: 1).valueOrOne();
4965
4966 SDValue Ptr = getValue(V: PtrOperand);
4967 SDValue Src0 = getValue(V: Src0Operand);
4968 SDValue Mask = getValue(V: MaskOperand);
4969 SDValue Offset = DAG.getUNDEF(VT: Ptr.getValueType());
4970
4971 EVT VT = Src0.getValueType();
4972
4973 auto MMOFlags = MachineMemOperand::MOStore;
4974 if (I.hasMetadata(KindID: LLVMContext::MD_nontemporal))
4975 MMOFlags |= MachineMemOperand::MONonTemporal;
4976
4977 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4978 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
4979 Size: LocationSize::upperBound(Value: VT.getStoreSize()), BaseAlignment: Alignment,
4980 AAInfo: I.getAAMetadata());
4981
4982 const auto &TLI = DAG.getTargetLoweringInfo();
4983
4984 SDValue StoreNode =
4985 !IsCompressing && TTI->hasConditionalLoadStoreForType(
4986 Ty: I.getArgOperand(i: 0)->getType(), /*IsStore=*/true)
4987 ? TLI.visitMaskedStore(DAG, DL: sdl, Chain: getMemoryRoot(), MMO, Ptr, Val: Src0,
4988 Mask)
4989 : DAG.getMaskedStore(Chain: getMemoryRoot(), dl: sdl, Val: Src0, Base: Ptr, Offset, Mask,
4990 MemVT: VT, MMO, AM: ISD::UNINDEXED, /*Truncating=*/IsTruncating: false,
4991 IsCompressing);
4992 DAG.setRoot(StoreNode);
4993 setValue(V: &I, NewN: StoreNode);
4994}
4995
4996// Get a uniform base for the Gather/Scatter intrinsic.
4997// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4998// We try to represent it as a base pointer + vector of indices.
4999// Usually, the vector of pointers comes from a 'getelementptr' instruction.
5000// The first operand of the GEP may be a single pointer or a vector of pointers
5001// Example:
5002// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
5003// or
5004// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
5005// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
5006//
5007// When the first GEP operand is a single pointer - it is the uniform base we
5008// are looking for. If first operand of the GEP is a splat vector - we
5009// extract the splat value and use it as a uniform base.
5010// In all other cases the function returns 'false'.
5011static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
5012 SDValue &Scale, SelectionDAGBuilder *SDB,
5013 const BasicBlock *CurBB, uint64_t ElemSize) {
5014 SelectionDAG& DAG = SDB->DAG;
5015 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5016 const DataLayout &DL = DAG.getDataLayout();
5017
5018 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
5019
5020 // Handle splat constant pointer.
5021 if (auto *C = dyn_cast<Constant>(Val: Ptr)) {
5022 C = C->getSplatValue();
5023 if (!C)
5024 return false;
5025
5026 Base = SDB->getValue(V: C);
5027
5028 ElementCount NumElts = cast<VectorType>(Val: Ptr->getType())->getElementCount();
5029 EVT VT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: TLI.getPointerTy(DL), EC: NumElts);
5030 Index = DAG.getConstant(Val: 0, DL: SDB->getCurSDLoc(), VT);
5031 Scale = DAG.getTargetConstant(Val: 1, DL: SDB->getCurSDLoc(), VT: TLI.getPointerTy(DL));
5032 return true;
5033 }
5034
5035 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Val: Ptr);
5036 if (!GEP || GEP->getParent() != CurBB)
5037 return false;
5038
5039 if (GEP->getNumOperands() != 2)
5040 return false;
5041
5042 const Value *BasePtr = GEP->getPointerOperand();
5043 const Value *IndexVal = GEP->getOperand(i_nocapture: GEP->getNumOperands() - 1);
5044
5045 // Make sure the base is scalar and the index is a vector.
5046 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
5047 return false;
5048
5049 TypeSize ScaleVal = DL.getTypeAllocSize(Ty: GEP->getResultElementType());
5050 if (ScaleVal.isScalable())
5051 return false;
5052
5053 // Target may not support the required addressing mode.
5054 if (ScaleVal != 1 &&
5055 !TLI.isLegalScaleForGatherScatter(Scale: ScaleVal.getFixedValue(), ElemSize))
5056 return false;
5057
5058 Base = SDB->getValue(V: BasePtr);
5059 Index = SDB->getValue(V: IndexVal);
5060
5061 Scale =
5062 DAG.getTargetConstant(Val: ScaleVal, DL: SDB->getCurSDLoc(), VT: TLI.getPointerTy(DL));
5063 return true;
5064}
5065
5066void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
5067 SDLoc sdl = getCurSDLoc();
5068
5069 // llvm.masked.scatter.*(Src0, Ptrs, Mask)
5070 const Value *Ptr = I.getArgOperand(i: 1);
5071 SDValue Src0 = getValue(V: I.getArgOperand(i: 0));
5072 SDValue Mask = getValue(V: I.getArgOperand(i: 2));
5073 EVT VT = Src0.getValueType();
5074 Align Alignment = I.getParamAlign(ArgNo: 1).valueOrOne();
5075 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5076
5077 SDValue Base;
5078 SDValue Index;
5079 SDValue Scale;
5080 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, SDB: this,
5081 CurBB: I.getParent(), ElemSize: VT.getScalarStoreSize());
5082
5083 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5084 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5085 PtrInfo: MachinePointerInfo(AS), F: MachineMemOperand::MOStore,
5086 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: Alignment, AAInfo: I.getAAMetadata());
5087 if (!UniformBase) {
5088 Base = DAG.getConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5089 Index = getValue(V: Ptr);
5090 Scale =
5091 DAG.getTargetConstant(Val: 1, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5092 }
5093
5094 EVT IdxVT = Index.getValueType();
5095 EVT EltTy = IdxVT.getVectorElementType();
5096 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
5097 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
5098 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: sdl, VT: NewIdxVT, Operand: Index);
5099 }
5100
5101 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
5102 SDValue Scatter = DAG.getMaskedScatter(VTs: DAG.getVTList(VT: MVT::Other), MemVT: VT, dl: sdl,
5103 Ops, MMO, IndexType: ISD::SIGNED_SCALED, IsTruncating: false);
5104 DAG.setRoot(Scatter);
5105 setValue(V: &I, NewN: Scatter);
5106}
5107
5108void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
5109 SDLoc sdl = getCurSDLoc();
5110
5111 Value *PtrOperand = I.getArgOperand(i: 0);
5112 Value *MaskOperand = I.getArgOperand(i: 1);
5113 Value *Src0Operand = I.getArgOperand(i: 2);
5114 Align Alignment = I.getParamAlign(ArgNo: 0).valueOrOne();
5115
5116 SDValue Ptr = getValue(V: PtrOperand);
5117 SDValue Src0 = getValue(V: Src0Operand);
5118 SDValue Mask = getValue(V: MaskOperand);
5119 SDValue Offset = DAG.getUNDEF(VT: Ptr.getValueType());
5120
5121 EVT VT = Src0.getValueType();
5122 AAMDNodes AAInfo = I.getAAMetadata();
5123 const MDNode *Ranges = getRangeMetadata(I);
5124
5125 // Do not serialize masked loads of constant memory with anything.
5126 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
5127 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
5128
5129 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
5130
5131 auto MMOFlags = MachineMemOperand::MOLoad;
5132 if (I.hasMetadata(KindID: LLVMContext::MD_nontemporal))
5133 MMOFlags |= MachineMemOperand::MONonTemporal;
5134 if (I.hasMetadata(KindID: LLVMContext::MD_invariant_load))
5135 MMOFlags |= MachineMemOperand::MOInvariant;
5136
5137 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5138 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
5139 Size: LocationSize::upperBound(Value: VT.getStoreSize()), BaseAlignment: Alignment, AAInfo, Ranges);
5140
5141 const auto &TLI = DAG.getTargetLoweringInfo();
5142
5143 // The Load/Res may point to different values and both of them are output
5144 // variables.
5145 SDValue Load;
5146 SDValue Res;
5147 if (!IsExpanding &&
5148 TTI->hasConditionalLoadStoreForType(Ty: Src0Operand->getType(),
5149 /*IsStore=*/false))
5150 Res = TLI.visitMaskedLoad(DAG, DL: sdl, Chain: InChain, MMO, NewLoad&: Load, Ptr, PassThru: Src0, Mask);
5151 else
5152 Res = Load =
5153 DAG.getMaskedLoad(VT, dl: sdl, Chain: InChain, Base: Ptr, Offset, Mask, Src0, MemVT: VT, MMO,
5154 AM: ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5155 if (AddToChain)
5156 PendingLoads.push_back(Elt: Load.getValue(R: 1));
5157 setValue(V: &I, NewN: Res);
5158}
5159
5160void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5161 SDLoc sdl = getCurSDLoc();
5162
5163 // @llvm.masked.gather.*(Ptrs, Mask, Src0)
5164 const Value *Ptr = I.getArgOperand(i: 0);
5165 SDValue Src0 = getValue(V: I.getArgOperand(i: 2));
5166 SDValue Mask = getValue(V: I.getArgOperand(i: 1));
5167
5168 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5169 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
5170 Align Alignment = I.getParamAlign(ArgNo: 0).valueOrOne();
5171
5172 const MDNode *Ranges = getRangeMetadata(I);
5173
5174 SDValue Root = DAG.getRoot();
5175 SDValue Base;
5176 SDValue Index;
5177 SDValue Scale;
5178 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, SDB: this,
5179 CurBB: I.getParent(), ElemSize: VT.getScalarStoreSize());
5180 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5181 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5182 PtrInfo: MachinePointerInfo(AS), F: MachineMemOperand::MOLoad,
5183 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: Alignment, AAInfo: I.getAAMetadata(),
5184 Ranges);
5185
5186 if (!UniformBase) {
5187 Base = DAG.getConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5188 Index = getValue(V: Ptr);
5189 Scale =
5190 DAG.getTargetConstant(Val: 1, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5191 }
5192
5193 EVT IdxVT = Index.getValueType();
5194 EVT EltTy = IdxVT.getVectorElementType();
5195 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
5196 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
5197 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: sdl, VT: NewIdxVT, Operand: Index);
5198 }
5199
5200 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5201 SDValue Gather =
5202 DAG.getMaskedGather(VTs: DAG.getVTList(VT1: VT, VT2: MVT::Other), MemVT: VT, dl: sdl, Ops, MMO,
5203 IndexType: ISD::SIGNED_SCALED, ExtTy: ISD::NON_EXTLOAD);
5204
5205 PendingLoads.push_back(Elt: Gather.getValue(R: 1));
5206 setValue(V: &I, NewN: Gather);
5207}
5208
5209void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5210 SDLoc dl = getCurSDLoc();
5211 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5212 AtomicOrdering FailureOrdering = I.getFailureOrdering();
5213 SyncScope::ID SSID = I.getSyncScopeID();
5214
5215 SDValue InChain = getRoot();
5216
5217 MVT MemVT = getValue(V: I.getCompareOperand()).getSimpleValueType();
5218 SDVTList VTs = DAG.getVTList(VT1: MemVT, VT2: MVT::i1, VT3: MVT::Other);
5219
5220 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5221 auto Flags = TLI.getAtomicMemOperandFlags(AI: I, DL: DAG.getDataLayout());
5222
5223 MachineFunction &MF = DAG.getMachineFunction();
5224 MachineMemOperand *MMO =
5225 MF.getMachineMemOperand(PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags,
5226 Size: MemVT.getStoreSize(), BaseAlignment: I.getAlign(), AAInfo: AAMDNodes(),
5227 Ranges: nullptr, SSID, Ordering: SuccessOrdering, FailureOrdering);
5228
5229 SDValue L = DAG.getAtomicCmpSwap(Opcode: ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5230 dl, MemVT, VTs, Chain: InChain,
5231 Ptr: getValue(V: I.getPointerOperand()),
5232 Cmp: getValue(V: I.getCompareOperand()),
5233 Swp: getValue(V: I.getNewValOperand()), MMO);
5234
5235 SDValue OutChain = L.getValue(R: 2);
5236
5237 setValue(V: &I, NewN: L);
5238 DAG.setRoot(OutChain);
5239}
5240
5241void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5242 SDLoc dl = getCurSDLoc();
5243 ISD::NodeType NT;
5244 switch (I.getOperation()) {
5245 default: llvm_unreachable("Unknown atomicrmw operation");
5246 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5247 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
5248 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
5249 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
5250 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5251 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
5252 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
5253 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
5254 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
5255 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5256 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5257 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5258 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5259 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5260 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5261 case AtomicRMWInst::FMaximum:
5262 NT = ISD::ATOMIC_LOAD_FMAXIMUM;
5263 break;
5264 case AtomicRMWInst::FMinimum:
5265 NT = ISD::ATOMIC_LOAD_FMINIMUM;
5266 break;
5267 case AtomicRMWInst::FMaximumNum:
5268 NT = ISD::ATOMIC_LOAD_FMAXIMUMNUM;
5269 break;
5270 case AtomicRMWInst::FMinimumNum:
5271 NT = ISD::ATOMIC_LOAD_FMINIMUMNUM;
5272 break;
5273 case AtomicRMWInst::UIncWrap:
5274 NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5275 break;
5276 case AtomicRMWInst::UDecWrap:
5277 NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5278 break;
5279 case AtomicRMWInst::USubCond:
5280 NT = ISD::ATOMIC_LOAD_USUB_COND;
5281 break;
5282 case AtomicRMWInst::USubSat:
5283 NT = ISD::ATOMIC_LOAD_USUB_SAT;
5284 break;
5285 }
5286 AtomicOrdering Ordering = I.getOrdering();
5287 SyncScope::ID SSID = I.getSyncScopeID();
5288
5289 SDValue InChain = getRoot();
5290
5291 auto MemVT = getValue(V: I.getValOperand()).getSimpleValueType();
5292 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5293 auto Flags = TLI.getAtomicMemOperandFlags(AI: I, DL: DAG.getDataLayout());
5294
5295 MachineFunction &MF = DAG.getMachineFunction();
5296 MachineMemOperand *MMO = MF.getMachineMemOperand(
5297 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5298 BaseAlignment: I.getAlign(), AAInfo: AAMDNodes(), Ranges: nullptr, SSID, Ordering);
5299
5300 SDValue L =
5301 DAG.getAtomic(Opcode: NT, dl, MemVT, Chain: InChain,
5302 Ptr: getValue(V: I.getPointerOperand()), Val: getValue(V: I.getValOperand()),
5303 MMO);
5304
5305 SDValue OutChain = L.getValue(R: 1);
5306
5307 setValue(V: &I, NewN: L);
5308 DAG.setRoot(OutChain);
5309}
5310
5311void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5312 SDLoc dl = getCurSDLoc();
5313 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5314 SDValue Ops[3];
5315 Ops[0] = getRoot();
5316 Ops[1] = DAG.getTargetConstant(Val: (unsigned)I.getOrdering(), DL: dl,
5317 VT: TLI.getFenceOperandTy(DL: DAG.getDataLayout()));
5318 Ops[2] = DAG.getTargetConstant(Val: I.getSyncScopeID(), DL: dl,
5319 VT: TLI.getFenceOperandTy(DL: DAG.getDataLayout()));
5320 SDValue N = DAG.getNode(Opcode: ISD::ATOMIC_FENCE, DL: dl, VT: MVT::Other, Ops);
5321 setValue(V: &I, NewN: N);
5322 DAG.setRoot(N);
5323}
5324
5325void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5326 SDLoc dl = getCurSDLoc();
5327 AtomicOrdering Order = I.getOrdering();
5328 SyncScope::ID SSID = I.getSyncScopeID();
5329
5330 SDValue InChain = getRoot();
5331
5332 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5333 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
5334 EVT MemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getType());
5335
5336 if (!TLI.supportsUnalignedAtomics() &&
5337 I.getAlign().value() < MemVT.getSizeInBits() / 8)
5338 report_fatal_error(reason: "Cannot generate unaligned atomic load");
5339
5340 auto Flags = TLI.getLoadMemOperandFlags(LI: I, DL: DAG.getDataLayout(), AC, LibInfo);
5341
5342 const MDNode *Ranges = getRangeMetadata(I);
5343 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5344 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5345 BaseAlignment: I.getAlign(), AAInfo: AAMDNodes(), Ranges, SSID, Ordering: Order);
5346
5347 InChain = TLI.prepareVolatileOrAtomicLoad(Chain: InChain, DL: dl, DAG);
5348
5349 SDValue Ptr = getValue(V: I.getPointerOperand());
5350 SDValue L =
5351 DAG.getAtomicLoad(ExtType: ISD::NON_EXTLOAD, dl, MemVT, VT: MemVT, Chain: InChain, Ptr, MMO);
5352
5353 SDValue OutChain = L.getValue(R: 1);
5354 if (MemVT != VT)
5355 L = DAG.getPtrExtOrTrunc(Op: L, DL: dl, VT);
5356
5357 setValue(V: &I, NewN: L);
5358 DAG.setRoot(OutChain);
5359}
5360
5361void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5362 SDLoc dl = getCurSDLoc();
5363
5364 AtomicOrdering Ordering = I.getOrdering();
5365 SyncScope::ID SSID = I.getSyncScopeID();
5366
5367 SDValue InChain = getRoot();
5368
5369 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5370 EVT MemVT =
5371 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getValueOperand()->getType());
5372
5373 if (!TLI.supportsUnalignedAtomics() &&
5374 I.getAlign().value() < MemVT.getSizeInBits() / 8)
5375 report_fatal_error(reason: "Cannot generate unaligned atomic store");
5376
5377 auto Flags = TLI.getStoreMemOperandFlags(SI: I, DL: DAG.getDataLayout());
5378
5379 MachineFunction &MF = DAG.getMachineFunction();
5380 MachineMemOperand *MMO = MF.getMachineMemOperand(
5381 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5382 BaseAlignment: I.getAlign(), AAInfo: AAMDNodes(), Ranges: nullptr, SSID, Ordering);
5383
5384 SDValue Val = getValue(V: I.getValueOperand());
5385 if (Val.getValueType() != MemVT)
5386 Val = DAG.getPtrExtOrTrunc(Op: Val, DL: dl, VT: MemVT);
5387 SDValue Ptr = getValue(V: I.getPointerOperand());
5388
5389 SDValue OutChain =
5390 DAG.getAtomic(Opcode: ISD::ATOMIC_STORE, dl, MemVT, Chain: InChain, Ptr: Val, Val: Ptr, MMO);
5391
5392 setValue(V: &I, NewN: OutChain);
5393 DAG.setRoot(OutChain);
5394}
5395
5396/// Check if this intrinsic call depends on the chain (1st return value)
5397/// and if it only *loads* memory.
5398/// Ignore the callsite's attributes. A specific call site may be marked with
5399/// readnone, but the lowering code will expect the chain based on the
5400/// definition.
5401std::pair<bool, bool>
5402SelectionDAGBuilder::getTargetIntrinsicCallProperties(const CallBase &I) {
5403 const Function *F = I.getCalledFunction();
5404 bool HasChain = !F->doesNotAccessMemory();
5405 bool OnlyLoad =
5406 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5407
5408 return {HasChain, OnlyLoad};
5409}
5410
5411SmallVector<SDValue, 8> SelectionDAGBuilder::getTargetIntrinsicOperands(
5412 const CallBase &I, bool HasChain, bool OnlyLoad,
5413 TargetLowering::IntrinsicInfo *TgtMemIntrinsicInfo) {
5414 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5415
5416 // Build the operand list.
5417 SmallVector<SDValue, 8> Ops;
5418 if (HasChain) { // If this intrinsic has side-effects, chainify it.
5419 if (OnlyLoad) {
5420 // We don't need to serialize loads against other loads.
5421 Ops.push_back(Elt: DAG.getRoot());
5422 } else {
5423 Ops.push_back(Elt: getRoot());
5424 }
5425 }
5426
5427 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5428 if (!TgtMemIntrinsicInfo || TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_VOID ||
5429 TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_W_CHAIN)
5430 Ops.push_back(Elt: DAG.getTargetConstant(Val: I.getIntrinsicID(), DL: getCurSDLoc(),
5431 VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
5432
5433 // Add all operands of the call to the operand list.
5434 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5435 const Value *Arg = I.getArgOperand(i);
5436 if (!I.paramHasAttr(ArgNo: i, Kind: Attribute::ImmArg)) {
5437 Ops.push_back(Elt: getValue(V: Arg));
5438 continue;
5439 }
5440
5441 // Use TargetConstant instead of a regular constant for immarg.
5442 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: Arg->getType(), AllowUnknown: true);
5443 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: Arg)) {
5444 assert(CI->getBitWidth() <= 64 &&
5445 "large intrinsic immediates not handled");
5446 Ops.push_back(Elt: DAG.getTargetConstant(Val: *CI, DL: SDLoc(), VT));
5447 } else {
5448 Ops.push_back(
5449 Elt: DAG.getTargetConstantFP(Val: *cast<ConstantFP>(Val: Arg), DL: SDLoc(), VT));
5450 }
5451 }
5452
5453 if (std::optional<OperandBundleUse> Bundle =
5454 I.getOperandBundle(ID: LLVMContext::OB_deactivation_symbol)) {
5455 auto *Sym = Bundle->Inputs[0].get();
5456 SDValue SDSym = getValue(V: Sym);
5457 SDSym = DAG.getDeactivationSymbol(GV: cast<GlobalValue>(Val: Sym));
5458 Ops.push_back(Elt: SDSym);
5459 }
5460
5461 if (std::optional<OperandBundleUse> Bundle =
5462 I.getOperandBundle(ID: LLVMContext::OB_convergencectrl)) {
5463 Value *Token = Bundle->Inputs[0].get();
5464 SDValue ConvControlToken = getValue(V: Token);
5465 assert(Ops.back().getValueType() != MVT::Glue &&
5466 "Did not expect another glue node here.");
5467 ConvControlToken =
5468 DAG.getNode(Opcode: ISD::CONVERGENCECTRL_GLUE, DL: {}, VT: MVT::Glue, Operand: ConvControlToken);
5469 Ops.push_back(Elt: ConvControlToken);
5470 }
5471
5472 return Ops;
5473}
5474
5475SDVTList SelectionDAGBuilder::getTargetIntrinsicVTList(const CallBase &I,
5476 bool HasChain) {
5477 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5478
5479 SmallVector<EVT, 4> ValueVTs;
5480 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: I.getType(), ValueVTs);
5481
5482 if (HasChain)
5483 ValueVTs.push_back(Elt: MVT::Other);
5484
5485 return DAG.getVTList(VTs: ValueVTs);
5486}
5487
5488/// Get an INTRINSIC node for a target intrinsic which does not touch memory.
5489SDValue SelectionDAGBuilder::getTargetNonMemIntrinsicNode(
5490 const Type &IntrinsicVT, bool HasChain, ArrayRef<SDValue> Ops,
5491 const SDVTList &VTs) {
5492 if (!HasChain)
5493 return DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: getCurSDLoc(), VTList: VTs, Ops);
5494 if (!IntrinsicVT.isVoidTy())
5495 return DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL: getCurSDLoc(), VTList: VTs, Ops);
5496 return DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL: getCurSDLoc(), VTList: VTs, Ops);
5497}
5498
5499/// Set root, convert return type if necessary and check alignment.
5500SDValue SelectionDAGBuilder::handleTargetIntrinsicRet(const CallBase &I,
5501 bool HasChain,
5502 bool OnlyLoad,
5503 SDValue Result) {
5504 if (HasChain) {
5505 SDValue Chain = Result.getValue(R: Result.getNode()->getNumValues() - 1);
5506 if (OnlyLoad)
5507 PendingLoads.push_back(Elt: Chain);
5508 else
5509 DAG.setRoot(Chain);
5510 }
5511
5512 if (I.getType()->isVoidTy())
5513 return Result;
5514
5515 if (MaybeAlign Alignment = I.getRetAlign(); InsertAssertAlign && Alignment) {
5516 // Insert `assertalign` node if there's an alignment.
5517 Result = DAG.getAssertAlign(DL: getCurSDLoc(), V: Result, A: Alignment.valueOrOne());
5518 } else if (!isa<VectorType>(Val: I.getType())) {
5519 Result = lowerRangeToAssertZExt(DAG, I, Op: Result);
5520 }
5521
5522 return Result;
5523}
5524
5525/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5526/// node.
5527void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5528 unsigned Intrinsic) {
5529 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
5530
5531 // Infos is set by getTgtMemIntrinsic.
5532 SmallVector<TargetLowering::IntrinsicInfo> Infos;
5533 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5534 TLI.getTgtMemIntrinsic(Infos, I, MF&: DAG.getMachineFunction(), Intrinsic);
5535 // Use the first (primary) info determines the node opcode.
5536 TargetLowering::IntrinsicInfo *Info = !Infos.empty() ? &Infos[0] : nullptr;
5537
5538 SmallVector<SDValue, 8> Ops =
5539 getTargetIntrinsicOperands(I, HasChain, OnlyLoad, TgtMemIntrinsicInfo: Info);
5540 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
5541
5542 // Propagate fast-math-flags from IR to node(s).
5543 SDNodeFlags Flags;
5544 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &I))
5545 Flags.copyFMF(FPMO: *FPMO);
5546 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5547
5548 // Create the node.
5549 SDValue Result;
5550
5551 // In some cases, custom collection of operands from CallInst I may be needed.
5552 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5553 if (!Infos.empty()) {
5554 // This is target intrinsic that touches memory
5555 // Create MachineMemOperands for each memory access described by the target.
5556 MachineFunction &MF = DAG.getMachineFunction();
5557 SmallVector<MachineMemOperand *> MMOs;
5558 for (const auto &Info : Infos) {
5559 // TODO: We currently just fallback to address space 0 if
5560 // getTgtMemIntrinsic didn't yield anything useful.
5561 MachinePointerInfo MPI;
5562 if (Info.ptrVal)
5563 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5564 else if (Info.fallbackAddressSpace)
5565 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5566 EVT MemVT = Info.memVT;
5567 LocationSize Size = LocationSize::precise(Value: Info.size);
5568 if (Size.hasValue() && !Size.getValue())
5569 Size = LocationSize::precise(Value: MemVT.getStoreSize());
5570 Align Alignment = Info.align.value_or(u: DAG.getEVTAlign(MemoryVT: MemVT));
5571 MachineMemOperand *MMO = MF.getMachineMemOperand(
5572 PtrInfo: MPI, F: Info.flags, Size, BaseAlignment: Alignment, AAInfo: I.getAAMetadata(),
5573 /*Ranges=*/nullptr, SSID: Info.ssid, Ordering: Info.order, FailureOrdering: Info.failureOrder);
5574 MMOs.push_back(Elt: MMO);
5575 }
5576
5577 Result = DAG.getMemIntrinsicNode(Opcode: Info->opc, dl: getCurSDLoc(), VTList: VTs, Ops,
5578 MemVT: Info->memVT, MMOs);
5579 } else {
5580 Result = getTargetNonMemIntrinsicNode(IntrinsicVT: *I.getType(), HasChain, Ops, VTs);
5581 }
5582
5583 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
5584
5585 setValue(V: &I, NewN: Result);
5586}
5587
5588/// GetSignificand - Get the significand and build it into a floating-point
5589/// number with exponent of 1:
5590///
5591/// Op = (Op & 0x007fffff) | 0x3f800000;
5592///
5593/// where Op is the hexadecimal representation of floating point value.
5594static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5595 SDValue t1 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: Op,
5596 N2: DAG.getConstant(Val: 0x007fffff, DL: dl, VT: MVT::i32));
5597 SDValue t2 = DAG.getNode(Opcode: ISD::OR, DL: dl, VT: MVT::i32, N1: t1,
5598 N2: DAG.getConstant(Val: 0x3f800000, DL: dl, VT: MVT::i32));
5599 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f32, Operand: t2);
5600}
5601
5602/// GetExponent - Get the exponent:
5603///
5604/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5605///
5606/// where Op is the hexadecimal representation of floating point value.
5607static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5608 const TargetLowering &TLI, const SDLoc &dl) {
5609 SDValue t0 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: Op,
5610 N2: DAG.getConstant(Val: 0x7f800000, DL: dl, VT: MVT::i32));
5611 SDValue t1 = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32, N1: t0,
5612 N2: DAG.getShiftAmountConstant(Val: 23, VT: MVT::i32, DL: dl));
5613 SDValue t2 = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32, N1: t1,
5614 N2: DAG.getConstant(Val: 127, DL: dl, VT: MVT::i32));
5615 return DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::f32, Operand: t2);
5616}
5617
5618/// getF32Constant - Get 32-bit floating point constant.
5619static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5620 const SDLoc &dl) {
5621 return DAG.getConstantFP(Val: APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), DL: dl,
5622 VT: MVT::f32);
5623}
5624
5625static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5626 SelectionDAG &DAG) {
5627 // TODO: What fast-math-flags should be set on the floating-point nodes?
5628
5629 // IntegerPartOfX = ((int32_t)(t0);
5630 SDValue IntegerPartOfX = DAG.getNode(Opcode: ISD::FP_TO_SINT, DL: dl, VT: MVT::i32, Operand: t0);
5631
5632 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
5633 SDValue t1 = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::f32, Operand: IntegerPartOfX);
5634 SDValue X = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t0, N2: t1);
5635
5636 // IntegerPartOfX <<= 23;
5637 IntegerPartOfX = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT: MVT::i32, N1: IntegerPartOfX,
5638 N2: DAG.getShiftAmountConstant(Val: 23, VT: MVT::i32, DL: dl));
5639
5640 SDValue TwoToFractionalPartOfX;
5641 if (LimitFloatPrecision <= 6) {
5642 // For floating-point precision of 6:
5643 //
5644 // TwoToFractionalPartOfX =
5645 // 0.997535578f +
5646 // (0.735607626f + 0.252464424f * x) * x;
5647 //
5648 // error 0.0144103317, which is 6 bits
5649 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5650 N2: getF32Constant(DAG, Flt: 0x3e814304, dl));
5651 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5652 N2: getF32Constant(DAG, Flt: 0x3f3c50c8, dl));
5653 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5654 TwoToFractionalPartOfX = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5655 N2: getF32Constant(DAG, Flt: 0x3f7f5e7e, dl));
5656 } else if (LimitFloatPrecision <= 12) {
5657 // For floating-point precision of 12:
5658 //
5659 // TwoToFractionalPartOfX =
5660 // 0.999892986f +
5661 // (0.696457318f +
5662 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
5663 //
5664 // error 0.000107046256, which is 13 to 14 bits
5665 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5666 N2: getF32Constant(DAG, Flt: 0x3da235e3, dl));
5667 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5668 N2: getF32Constant(DAG, Flt: 0x3e65b8f3, dl));
5669 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5670 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5671 N2: getF32Constant(DAG, Flt: 0x3f324b07, dl));
5672 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5673 TwoToFractionalPartOfX = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t6,
5674 N2: getF32Constant(DAG, Flt: 0x3f7ff8fd, dl));
5675 } else { // LimitFloatPrecision <= 18
5676 // For floating-point precision of 18:
5677 //
5678 // TwoToFractionalPartOfX =
5679 // 0.999999982f +
5680 // (0.693148872f +
5681 // (0.240227044f +
5682 // (0.554906021e-1f +
5683 // (0.961591928e-2f +
5684 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5685 // error 2.47208000*10^(-7), which is better than 18 bits
5686 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5687 N2: getF32Constant(DAG, Flt: 0x3924b03e, dl));
5688 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5689 N2: getF32Constant(DAG, Flt: 0x3ab24b87, dl));
5690 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5691 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5692 N2: getF32Constant(DAG, Flt: 0x3c1d8c17, dl));
5693 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5694 SDValue t7 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t6,
5695 N2: getF32Constant(DAG, Flt: 0x3d634a1d, dl));
5696 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
5697 SDValue t9 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t8,
5698 N2: getF32Constant(DAG, Flt: 0x3e75fe14, dl));
5699 SDValue t10 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t9, N2: X);
5700 SDValue t11 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t10,
5701 N2: getF32Constant(DAG, Flt: 0x3f317234, dl));
5702 SDValue t12 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t11, N2: X);
5703 TwoToFractionalPartOfX = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t12,
5704 N2: getF32Constant(DAG, Flt: 0x3f800000, dl));
5705 }
5706
5707 // Add the exponent into the result in integer domain.
5708 SDValue t13 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: TwoToFractionalPartOfX);
5709 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f32,
5710 Operand: DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: t13, N2: IntegerPartOfX));
5711}
5712
5713/// expandExp - Lower an exp intrinsic. Handles the special sequences for
5714/// limited-precision mode.
5715static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5716 const TargetLowering &TLI, SDNodeFlags Flags) {
5717 if (Op.getValueType() == MVT::f32 &&
5718 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5719
5720 // Put the exponent in the right bit position for later addition to the
5721 // final result:
5722 //
5723 // t0 = Op * log2(e)
5724
5725 // TODO: What fast-math-flags should be set here?
5726 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: Op,
5727 N2: DAG.getConstantFP(Val: numbers::log2ef, DL: dl, VT: MVT::f32));
5728 return getLimitedPrecisionExp2(t0, dl, DAG);
5729 }
5730
5731 // No special expansion.
5732 return DAG.getNode(Opcode: ISD::FEXP, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5733}
5734
5735/// expandLog - Lower a log intrinsic. Handles the special sequences for
5736/// limited-precision mode.
5737static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5738 const TargetLowering &TLI, SDNodeFlags Flags) {
5739 // TODO: What fast-math-flags should be set on the floating-point nodes?
5740
5741 if (Op.getValueType() == MVT::f32 &&
5742 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5743 SDValue Op1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Op);
5744
5745 // Scale the exponent by log(2).
5746 SDValue Exp = GetExponent(DAG, Op: Op1, TLI, dl);
5747 SDValue LogOfExponent =
5748 DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: Exp,
5749 N2: DAG.getConstantFP(Val: numbers::ln2f, DL: dl, VT: MVT::f32));
5750
5751 // Get the significand and build it into a floating-point number with
5752 // exponent of 1.
5753 SDValue X = GetSignificand(DAG, Op: Op1, dl);
5754
5755 SDValue LogOfMantissa;
5756 if (LimitFloatPrecision <= 6) {
5757 // For floating-point precision of 6:
5758 //
5759 // LogofMantissa =
5760 // -1.1609546f +
5761 // (1.4034025f - 0.23903021f * x) * x;
5762 //
5763 // error 0.0034276066, which is better than 8 bits
5764 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5765 N2: getF32Constant(DAG, Flt: 0xbe74c456, dl));
5766 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5767 N2: getF32Constant(DAG, Flt: 0x3fb3a2b1, dl));
5768 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5769 LogOfMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5770 N2: getF32Constant(DAG, Flt: 0x3f949a29, dl));
5771 } else if (LimitFloatPrecision <= 12) {
5772 // For floating-point precision of 12:
5773 //
5774 // LogOfMantissa =
5775 // -1.7417939f +
5776 // (2.8212026f +
5777 // (-1.4699568f +
5778 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5779 //
5780 // error 0.000061011436, which is 14 bits
5781 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5782 N2: getF32Constant(DAG, Flt: 0xbd67b6d6, dl));
5783 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5784 N2: getF32Constant(DAG, Flt: 0x3ee4f4b8, dl));
5785 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5786 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5787 N2: getF32Constant(DAG, Flt: 0x3fbc278b, dl));
5788 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5789 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5790 N2: getF32Constant(DAG, Flt: 0x40348e95, dl));
5791 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5792 LogOfMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5793 N2: getF32Constant(DAG, Flt: 0x3fdef31a, dl));
5794 } else { // LimitFloatPrecision <= 18
5795 // For floating-point precision of 18:
5796 //
5797 // LogOfMantissa =
5798 // -2.1072184f +
5799 // (4.2372794f +
5800 // (-3.7029485f +
5801 // (2.2781945f +
5802 // (-0.87823314f +
5803 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5804 //
5805 // error 0.0000023660568, which is better than 18 bits
5806 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5807 N2: getF32Constant(DAG, Flt: 0xbc91e5ac, dl));
5808 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5809 N2: getF32Constant(DAG, Flt: 0x3e4350aa, dl));
5810 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5811 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5812 N2: getF32Constant(DAG, Flt: 0x3f60d3e3, dl));
5813 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5814 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5815 N2: getF32Constant(DAG, Flt: 0x4011cdf0, dl));
5816 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5817 SDValue t7 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5818 N2: getF32Constant(DAG, Flt: 0x406cfd1c, dl));
5819 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
5820 SDValue t9 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t8,
5821 N2: getF32Constant(DAG, Flt: 0x408797cb, dl));
5822 SDValue t10 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t9, N2: X);
5823 LogOfMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t10,
5824 N2: getF32Constant(DAG, Flt: 0x4006dcab, dl));
5825 }
5826
5827 return DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: LogOfExponent, N2: LogOfMantissa);
5828 }
5829
5830 // No special expansion.
5831 return DAG.getNode(Opcode: ISD::FLOG, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5832}
5833
5834/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5835/// limited-precision mode.
5836static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5837 const TargetLowering &TLI, SDNodeFlags Flags) {
5838 // TODO: What fast-math-flags should be set on the floating-point nodes?
5839
5840 if (Op.getValueType() == MVT::f32 &&
5841 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5842 SDValue Op1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Op);
5843
5844 // Get the exponent.
5845 SDValue LogOfExponent = GetExponent(DAG, Op: Op1, TLI, dl);
5846
5847 // Get the significand and build it into a floating-point number with
5848 // exponent of 1.
5849 SDValue X = GetSignificand(DAG, Op: Op1, dl);
5850
5851 // Different possible minimax approximations of significand in
5852 // floating-point for various degrees of accuracy over [1,2].
5853 SDValue Log2ofMantissa;
5854 if (LimitFloatPrecision <= 6) {
5855 // For floating-point precision of 6:
5856 //
5857 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5858 //
5859 // error 0.0049451742, which is more than 7 bits
5860 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5861 N2: getF32Constant(DAG, Flt: 0xbeb08fe0, dl));
5862 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5863 N2: getF32Constant(DAG, Flt: 0x40019463, dl));
5864 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5865 Log2ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5866 N2: getF32Constant(DAG, Flt: 0x3fd6633d, dl));
5867 } else if (LimitFloatPrecision <= 12) {
5868 // For floating-point precision of 12:
5869 //
5870 // Log2ofMantissa =
5871 // -2.51285454f +
5872 // (4.07009056f +
5873 // (-2.12067489f +
5874 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5875 //
5876 // error 0.0000876136000, which is better than 13 bits
5877 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5878 N2: getF32Constant(DAG, Flt: 0xbda7262e, dl));
5879 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5880 N2: getF32Constant(DAG, Flt: 0x3f25280b, dl));
5881 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5882 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5883 N2: getF32Constant(DAG, Flt: 0x4007b923, dl));
5884 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5885 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5886 N2: getF32Constant(DAG, Flt: 0x40823e2f, dl));
5887 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5888 Log2ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5889 N2: getF32Constant(DAG, Flt: 0x4020d29c, dl));
5890 } else { // LimitFloatPrecision <= 18
5891 // For floating-point precision of 18:
5892 //
5893 // Log2ofMantissa =
5894 // -3.0400495f +
5895 // (6.1129976f +
5896 // (-5.3420409f +
5897 // (3.2865683f +
5898 // (-1.2669343f +
5899 // (0.27515199f -
5900 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5901 //
5902 // error 0.0000018516, which is better than 18 bits
5903 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5904 N2: getF32Constant(DAG, Flt: 0xbcd2769e, dl));
5905 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5906 N2: getF32Constant(DAG, Flt: 0x3e8ce0b9, dl));
5907 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5908 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5909 N2: getF32Constant(DAG, Flt: 0x3fa22ae7, dl));
5910 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5911 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5912 N2: getF32Constant(DAG, Flt: 0x40525723, dl));
5913 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5914 SDValue t7 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5915 N2: getF32Constant(DAG, Flt: 0x40aaf200, dl));
5916 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
5917 SDValue t9 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t8,
5918 N2: getF32Constant(DAG, Flt: 0x40c39dad, dl));
5919 SDValue t10 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t9, N2: X);
5920 Log2ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t10,
5921 N2: getF32Constant(DAG, Flt: 0x4042902c, dl));
5922 }
5923
5924 return DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: LogOfExponent, N2: Log2ofMantissa);
5925 }
5926
5927 // No special expansion.
5928 return DAG.getNode(Opcode: ISD::FLOG2, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5929}
5930
5931/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5932/// limited-precision mode.
5933static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5934 const TargetLowering &TLI, SDNodeFlags Flags) {
5935 // TODO: What fast-math-flags should be set on the floating-point nodes?
5936
5937 if (Op.getValueType() == MVT::f32 &&
5938 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5939 SDValue Op1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Op);
5940
5941 // Scale the exponent by log10(2) [0.30102999f].
5942 SDValue Exp = GetExponent(DAG, Op: Op1, TLI, dl);
5943 SDValue LogOfExponent = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: Exp,
5944 N2: getF32Constant(DAG, Flt: 0x3e9a209a, dl));
5945
5946 // Get the significand and build it into a floating-point number with
5947 // exponent of 1.
5948 SDValue X = GetSignificand(DAG, Op: Op1, dl);
5949
5950 SDValue Log10ofMantissa;
5951 if (LimitFloatPrecision <= 6) {
5952 // For floating-point precision of 6:
5953 //
5954 // Log10ofMantissa =
5955 // -0.50419619f +
5956 // (0.60948995f - 0.10380950f * x) * x;
5957 //
5958 // error 0.0014886165, which is 6 bits
5959 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5960 N2: getF32Constant(DAG, Flt: 0xbdd49a13, dl));
5961 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5962 N2: getF32Constant(DAG, Flt: 0x3f1c0789, dl));
5963 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5964 Log10ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5965 N2: getF32Constant(DAG, Flt: 0x3f011300, dl));
5966 } else if (LimitFloatPrecision <= 12) {
5967 // For floating-point precision of 12:
5968 //
5969 // Log10ofMantissa =
5970 // -0.64831180f +
5971 // (0.91751397f +
5972 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5973 //
5974 // error 0.00019228036, which is better than 12 bits
5975 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5976 N2: getF32Constant(DAG, Flt: 0x3d431f31, dl));
5977 SDValue t1 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t0,
5978 N2: getF32Constant(DAG, Flt: 0x3ea21fb2, dl));
5979 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5980 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5981 N2: getF32Constant(DAG, Flt: 0x3f6ae232, dl));
5982 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5983 Log10ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t4,
5984 N2: getF32Constant(DAG, Flt: 0x3f25f7c3, dl));
5985 } else { // LimitFloatPrecision <= 18
5986 // For floating-point precision of 18:
5987 //
5988 // Log10ofMantissa =
5989 // -0.84299375f +
5990 // (1.5327582f +
5991 // (-1.0688956f +
5992 // (0.49102474f +
5993 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5994 //
5995 // error 0.0000037995730, which is better than 18 bits
5996 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5997 N2: getF32Constant(DAG, Flt: 0x3c5d51ce, dl));
5998 SDValue t1 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t0,
5999 N2: getF32Constant(DAG, Flt: 0x3e00685a, dl));
6000 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
6001 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
6002 N2: getF32Constant(DAG, Flt: 0x3efb6798, dl));
6003 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
6004 SDValue t5 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t4,
6005 N2: getF32Constant(DAG, Flt: 0x3f88d192, dl));
6006 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
6007 SDValue t7 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t6,
6008 N2: getF32Constant(DAG, Flt: 0x3fc4316c, dl));
6009 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
6010 Log10ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t8,
6011 N2: getF32Constant(DAG, Flt: 0x3f57ce70, dl));
6012 }
6013
6014 return DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: LogOfExponent, N2: Log10ofMantissa);
6015 }
6016
6017 // No special expansion.
6018 return DAG.getNode(Opcode: ISD::FLOG10, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
6019}
6020
6021/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
6022/// limited-precision mode.
6023static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
6024 const TargetLowering &TLI, SDNodeFlags Flags) {
6025 if (Op.getValueType() == MVT::f32 &&
6026 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
6027 return getLimitedPrecisionExp2(t0: Op, dl, DAG);
6028
6029 // No special expansion.
6030 return DAG.getNode(Opcode: ISD::FEXP2, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
6031}
6032
6033/// visitPow - Lower a pow intrinsic. Handles the special sequences for
6034/// limited-precision mode with x == 10.0f.
6035static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
6036 SelectionDAG &DAG, const TargetLowering &TLI,
6037 SDNodeFlags Flags) {
6038 bool IsExp10 = false;
6039 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
6040 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
6041 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(Val&: LHS)) {
6042 APFloat Ten(10.0f);
6043 IsExp10 = LHSC->isExactlyValue(V: Ten);
6044 }
6045 }
6046
6047 // TODO: What fast-math-flags should be set on the FMUL node?
6048 if (IsExp10) {
6049 // Put the exponent in the right bit position for later addition to the
6050 // final result:
6051 //
6052 // #define LOG2OF10 3.3219281f
6053 // t0 = Op * LOG2OF10;
6054 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: RHS,
6055 N2: getF32Constant(DAG, Flt: 0x40549a78, dl));
6056 return getLimitedPrecisionExp2(t0, dl, DAG);
6057 }
6058
6059 // No special expansion.
6060 return DAG.getNode(Opcode: ISD::FPOW, DL: dl, VT: LHS.getValueType(), N1: LHS, N2: RHS, Flags);
6061}
6062
6063/// ExpandPowI - Expand a llvm.powi intrinsic.
6064static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
6065 SelectionDAG &DAG) {
6066 // If RHS is a constant, we can expand this out to a multiplication tree if
6067 // it's beneficial on the target, otherwise we end up lowering to a call to
6068 // __powidf2 (for example).
6069 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Val&: RHS)) {
6070 unsigned Val = RHSC->getSExtValue();
6071
6072 // powi(x, 0) -> 1.0
6073 if (Val == 0)
6074 return DAG.getConstantFP(Val: 1.0, DL, VT: LHS.getValueType());
6075
6076 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
6077 Exponent: Val, OptForSize: DAG.shouldOptForSize())) {
6078 // Get the exponent as a positive value.
6079 if ((int)Val < 0)
6080 Val = -Val;
6081 // We use the simple binary decomposition method to generate the multiply
6082 // sequence. There are more optimal ways to do this (for example,
6083 // powi(x,15) generates one more multiply than it should), but this has
6084 // the benefit of being both really simple and much better than a libcall.
6085 SDValue Res; // Logically starts equal to 1.0
6086 SDValue CurSquare = LHS;
6087 // TODO: Intrinsics should have fast-math-flags that propagate to these
6088 // nodes.
6089 while (Val) {
6090 if (Val & 1) {
6091 if (Res.getNode())
6092 Res =
6093 DAG.getNode(Opcode: ISD::FMUL, DL, VT: Res.getValueType(), N1: Res, N2: CurSquare);
6094 else
6095 Res = CurSquare; // 1.0*CurSquare.
6096 }
6097
6098 CurSquare = DAG.getNode(Opcode: ISD::FMUL, DL, VT: CurSquare.getValueType(),
6099 N1: CurSquare, N2: CurSquare);
6100 Val >>= 1;
6101 }
6102
6103 // If the original was negative, invert the result, producing 1/(x*x*x).
6104 if (RHSC->getSExtValue() < 0)
6105 Res = DAG.getNode(Opcode: ISD::FDIV, DL, VT: LHS.getValueType(),
6106 N1: DAG.getConstantFP(Val: 1.0, DL, VT: LHS.getValueType()), N2: Res);
6107 return Res;
6108 }
6109 }
6110
6111 // Otherwise, expand to a libcall.
6112 return DAG.getNode(Opcode: ISD::FPOWI, DL, VT: LHS.getValueType(), N1: LHS, N2: RHS);
6113}
6114
6115static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
6116 SDValue LHS, SDValue RHS, SDValue Scale,
6117 SelectionDAG &DAG, const TargetLowering &TLI) {
6118 EVT VT = LHS.getValueType();
6119 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
6120 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
6121 LLVMContext &Ctx = *DAG.getContext();
6122
6123 // If the type is legal but the operation isn't, this node might survive all
6124 // the way to operation legalization. If we end up there and we do not have
6125 // the ability to widen the type (if VT*2 is not legal), we cannot expand the
6126 // node.
6127
6128 // Coax the legalizer into expanding the node during type legalization instead
6129 // by bumping the size by one bit. This will force it to Promote, enabling the
6130 // early expansion and avoiding the need to expand later.
6131
6132 // We don't have to do this if Scale is 0; that can always be expanded, unless
6133 // it's a saturating signed operation. Those can experience true integer
6134 // division overflow, a case which we must avoid.
6135
6136 // FIXME: We wouldn't have to do this (or any of the early
6137 // expansion/promotion) if it was possible to expand a libcall of an
6138 // illegal type during operation legalization. But it's not, so things
6139 // get a bit hacky.
6140 unsigned ScaleInt = Scale->getAsZExtVal();
6141 if ((ScaleInt > 0 || (Saturating && Signed)) &&
6142 (TLI.isTypeLegal(VT) ||
6143 (VT.isVector() && TLI.isTypeLegal(VT: VT.getVectorElementType())))) {
6144 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
6145 Op: Opcode, VT, Scale: ScaleInt);
6146 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
6147 EVT PromVT;
6148 if (VT.isScalarInteger())
6149 PromVT = EVT::getIntegerVT(Context&: Ctx, BitWidth: VT.getSizeInBits() + 1);
6150 else if (VT.isVector()) {
6151 PromVT = VT.getVectorElementType();
6152 PromVT = EVT::getIntegerVT(Context&: Ctx, BitWidth: PromVT.getSizeInBits() + 1);
6153 PromVT = EVT::getVectorVT(Context&: Ctx, VT: PromVT, EC: VT.getVectorElementCount());
6154 } else
6155 llvm_unreachable("Wrong VT for DIVFIX?");
6156 LHS = DAG.getExtOrTrunc(IsSigned: Signed, Op: LHS, DL, VT: PromVT);
6157 RHS = DAG.getExtOrTrunc(IsSigned: Signed, Op: RHS, DL, VT: PromVT);
6158 EVT ShiftTy = TLI.getShiftAmountTy(LHSTy: PromVT, DL: DAG.getDataLayout());
6159 // For saturating operations, we need to shift up the LHS to get the
6160 // proper saturation width, and then shift down again afterwards.
6161 if (Saturating)
6162 LHS = DAG.getNode(Opcode: ISD::SHL, DL, VT: PromVT, N1: LHS,
6163 N2: DAG.getConstant(Val: 1, DL, VT: ShiftTy));
6164 SDValue Res = DAG.getNode(Opcode, DL, VT: PromVT, N1: LHS, N2: RHS, N3: Scale);
6165 if (Saturating)
6166 Res = DAG.getNode(Opcode: Signed ? ISD::SRA : ISD::SRL, DL, VT: PromVT, N1: Res,
6167 N2: DAG.getConstant(Val: 1, DL, VT: ShiftTy));
6168 return DAG.getZExtOrTrunc(Op: Res, DL, VT);
6169 }
6170 }
6171
6172 return DAG.getNode(Opcode, DL, VT, N1: LHS, N2: RHS, N3: Scale);
6173}
6174
6175// getUnderlyingArgRegs - Find underlying registers used for a truncated,
6176// bitcasted, or split argument. Returns a list of <Register, size in bits>
6177static void
6178getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
6179 const SDValue &N) {
6180 switch (N.getOpcode()) {
6181 case ISD::CopyFromReg: {
6182 SDValue Op = N.getOperand(i: 1);
6183 Regs.emplace_back(Args: cast<RegisterSDNode>(Val&: Op)->getReg(),
6184 Args: Op.getValueType().getSizeInBits());
6185 return;
6186 }
6187 case ISD::BITCAST:
6188 case ISD::AssertZext:
6189 case ISD::AssertSext:
6190 case ISD::TRUNCATE:
6191 getUnderlyingArgRegs(Regs, N: N.getOperand(i: 0));
6192 return;
6193 case ISD::BUILD_PAIR:
6194 case ISD::BUILD_VECTOR:
6195 case ISD::CONCAT_VECTORS:
6196 for (SDValue Op : N->op_values())
6197 getUnderlyingArgRegs(Regs, N: Op);
6198 return;
6199 default:
6200 return;
6201 }
6202}
6203
6204/// If the DbgValueInst is a dbg_value of a function argument, create the
6205/// corresponding DBG_VALUE machine instruction for it now. At the end of
6206/// instruction selection, they will be inserted to the entry BB.
6207/// We don't currently support this for variadic dbg_values, as they shouldn't
6208/// appear for function arguments or in the prologue.
6209bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6210 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6211 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6212 const Argument *Arg = dyn_cast<Argument>(Val: V);
6213 if (!Arg)
6214 return false;
6215
6216 MachineFunction &MF = DAG.getMachineFunction();
6217 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6218
6219 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6220 // we've been asked to pursue.
6221 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6222 bool Indirect) {
6223 if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6224 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6225 // pointing at the VReg, which will be patched up later.
6226 auto &Inst = TII->get(Opcode: TargetOpcode::DBG_INSTR_REF);
6227 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
6228 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6229 /* isKill */ false, /* isDead */ false,
6230 /* isUndef */ false, /* isEarlyClobber */ false,
6231 /* SubReg */ 0, /* isDebug */ true)});
6232
6233 auto *NewDIExpr = FragExpr;
6234 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6235 // the DIExpression.
6236 if (Indirect)
6237 NewDIExpr = DIExpression::prepend(Expr: FragExpr, Flags: DIExpression::DerefBefore);
6238 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6239 NewDIExpr = DIExpression::prependOpcodes(Expr: NewDIExpr, Ops);
6240 return BuildMI(MF, DL, MCID: Inst, IsIndirect: false, MOs, Variable, Expr: NewDIExpr);
6241 } else {
6242 // Create a completely standard DBG_VALUE.
6243 auto &Inst = TII->get(Opcode: TargetOpcode::DBG_VALUE);
6244 return BuildMI(MF, DL, MCID: Inst, IsIndirect: Indirect, Reg, Variable, Expr: FragExpr);
6245 }
6246 };
6247
6248 if (Kind == FuncArgumentDbgValueKind::Value) {
6249 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6250 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6251 // the entry block.
6252 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6253 if (!IsInEntryBlock)
6254 return false;
6255
6256 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6257 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6258 // variable that also is a param.
6259 //
6260 // Although, if we are at the top of the entry block already, we can still
6261 // emit using ArgDbgValue. This might catch some situations when the
6262 // dbg.value refers to an argument that isn't used in the entry block, so
6263 // any CopyToReg node would be optimized out and the only way to express
6264 // this DBG_VALUE is by using the physical reg (or FI) as done in this
6265 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
6266 // we should only emit as ArgDbgValue if the Variable is an argument to the
6267 // current function, and the dbg.value intrinsic is found in the entry
6268 // block.
6269 bool VariableIsFunctionInputArg = Variable->isParameter() &&
6270 !DL->getInlinedAt();
6271 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6272 if (!IsInPrologue && !VariableIsFunctionInputArg)
6273 return false;
6274
6275 // Here we assume that a function argument on IR level only can be used to
6276 // describe one input parameter on source level. If we for example have
6277 // source code like this
6278 //
6279 // struct A { long x, y; };
6280 // void foo(struct A a, long b) {
6281 // ...
6282 // b = a.x;
6283 // ...
6284 // }
6285 //
6286 // and IR like this
6287 //
6288 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
6289 // entry:
6290 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6291 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6292 // call void @llvm.dbg.value(metadata i32 %b, "b",
6293 // ...
6294 // call void @llvm.dbg.value(metadata i32 %a1, "b"
6295 // ...
6296 //
6297 // then the last dbg.value is describing a parameter "b" using a value that
6298 // is an argument. But since we already has used %a1 to describe a parameter
6299 // we should not handle that last dbg.value here (that would result in an
6300 // incorrect hoisting of the DBG_VALUE to the function entry).
6301 // Notice that we allow one dbg.value per IR level argument, to accommodate
6302 // for the situation with fragments above.
6303 // If there is no node for the value being handled, we return true to skip
6304 // the normal generation of debug info, as it would kill existing debug
6305 // info for the parameter in case of duplicates.
6306 if (VariableIsFunctionInputArg) {
6307 unsigned ArgNo = Arg->getArgNo();
6308 if (ArgNo >= FuncInfo.DescribedArgs.size())
6309 FuncInfo.DescribedArgs.resize(N: ArgNo + 1, t: false);
6310 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(Idx: ArgNo))
6311 return !NodeMap[V].getNode();
6312 FuncInfo.DescribedArgs.set(ArgNo);
6313 }
6314 }
6315
6316 bool IsIndirect = false;
6317 std::optional<MachineOperand> Op;
6318 // Some arguments' frame index is recorded during argument lowering.
6319 int FI = FuncInfo.getArgumentFrameIndex(A: Arg);
6320 if (FI != std::numeric_limits<int>::max())
6321 Op = MachineOperand::CreateFI(Idx: FI);
6322
6323 SmallVector<std::pair<Register, TypeSize>, 8> ArgRegsAndSizes;
6324 if (!Op && N.getNode()) {
6325 getUnderlyingArgRegs(Regs&: ArgRegsAndSizes, N);
6326 Register Reg;
6327 if (ArgRegsAndSizes.size() == 1)
6328 Reg = ArgRegsAndSizes.front().first;
6329
6330 if (Reg && Reg.isVirtual()) {
6331 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6332 Register PR = RegInfo.getLiveInPhysReg(VReg: Reg);
6333 if (PR)
6334 Reg = PR;
6335 }
6336 if (Reg) {
6337 Op = MachineOperand::CreateReg(Reg, isDef: false);
6338 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6339 }
6340 }
6341
6342 if (!Op && N.getNode()) {
6343 // Check if frame index is available.
6344 SDValue LCandidate = peekThroughBitcasts(V: N);
6345 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(Val: LCandidate.getNode()))
6346 if (FrameIndexSDNode *FINode =
6347 dyn_cast<FrameIndexSDNode>(Val: LNode->getBasePtr().getNode()))
6348 Op = MachineOperand::CreateFI(Idx: FINode->getIndex());
6349 }
6350
6351 if (!Op) {
6352 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6353 auto splitMultiRegDbgValue =
6354 [&](ArrayRef<std::pair<Register, TypeSize>> SplitRegs) -> bool {
6355 unsigned Offset = 0;
6356 for (const auto &[Reg, RegSizeInBits] : SplitRegs) {
6357 // FIXME: Scalable sizes are not supported in fragment expressions.
6358 if (RegSizeInBits.isScalable())
6359 return false;
6360
6361 // If the expression is already a fragment, the current register
6362 // offset+size might extend beyond the fragment. In this case, only
6363 // the register bits that are inside the fragment are relevant.
6364 int RegFragmentSizeInBits = RegSizeInBits.getFixedValue();
6365 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6366 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6367 // The register is entirely outside the expression fragment,
6368 // so is irrelevant for debug info.
6369 if (Offset >= ExprFragmentSizeInBits)
6370 break;
6371 // The register is partially outside the expression fragment, only
6372 // the low bits within the fragment are relevant for debug info.
6373 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6374 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6375 }
6376 }
6377
6378 auto FragmentExpr = DIExpression::createFragmentExpression(
6379 Expr, OffsetInBits: Offset, SizeInBits: RegFragmentSizeInBits);
6380 Offset += RegSizeInBits.getFixedValue();
6381 // If a valid fragment expression cannot be created, the variable's
6382 // correct value cannot be determined and so it is set as poison.
6383 if (!FragmentExpr) {
6384 SDDbgValue *SDV = DAG.getConstantDbgValue(
6385 Var: Variable, Expr, C: PoisonValue::get(T: V->getType()), DL, O: SDNodeOrder);
6386 DAG.AddDbgValue(DB: SDV, isParameter: false);
6387 continue;
6388 }
6389 MachineInstr *NewMI = MakeVRegDbgValue(
6390 Reg, *FragmentExpr, Kind != FuncArgumentDbgValueKind::Value);
6391 FuncInfo.ArgDbgValues.push_back(Elt: NewMI);
6392 }
6393
6394 return true;
6395 };
6396
6397 // Check if ValueMap has reg number.
6398 DenseMap<const Value *, Register>::const_iterator
6399 VMI = FuncInfo.ValueMap.find(Val: V);
6400 if (VMI != FuncInfo.ValueMap.end()) {
6401 const auto &TLI = DAG.getTargetLoweringInfo();
6402 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6403 V->getType(), std::nullopt);
6404 if (RFV.occupiesMultipleRegs())
6405 return splitMultiRegDbgValue(RFV.getRegsAndSizes());
6406
6407 Op = MachineOperand::CreateReg(Reg: VMI->second, isDef: false);
6408 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6409 } else if (ArgRegsAndSizes.size() > 1) {
6410 // This was split due to the calling convention, and no virtual register
6411 // mapping exists for the value.
6412 return splitMultiRegDbgValue(ArgRegsAndSizes);
6413 }
6414 }
6415
6416 if (!Op)
6417 return false;
6418
6419 assert(Variable->isValidLocationForIntrinsic(DL) &&
6420 "Expected inlined-at fields to agree");
6421 MachineInstr *NewMI = nullptr;
6422
6423 if (Op->isReg())
6424 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6425 else
6426 NewMI = BuildMI(MF, DL, MCID: TII->get(Opcode: TargetOpcode::DBG_VALUE), IsIndirect: true, MOs: *Op,
6427 Variable, Expr);
6428
6429 // Otherwise, use ArgDbgValues.
6430 FuncInfo.ArgDbgValues.push_back(Elt: NewMI);
6431 return true;
6432}
6433
6434/// Return the appropriate SDDbgValue based on N.
6435SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6436 DILocalVariable *Variable,
6437 DIExpression *Expr,
6438 const DebugLoc &dl,
6439 unsigned DbgSDNodeOrder) {
6440 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Val: N.getNode())) {
6441 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6442 // stack slot locations.
6443 //
6444 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6445 // debug values here after optimization:
6446 //
6447 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
6448 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6449 //
6450 // Both describe the direct values of their associated variables.
6451 return DAG.getFrameIndexDbgValue(Var: Variable, Expr, FI: FISDN->getIndex(),
6452 /*IsIndirect*/ false, DL: dl, O: DbgSDNodeOrder);
6453 }
6454 return DAG.getDbgValue(Var: Variable, Expr, N: N.getNode(), R: N.getResNo(),
6455 /*IsIndirect*/ false, DL: dl, O: DbgSDNodeOrder);
6456}
6457
6458static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6459 switch (Intrinsic) {
6460 case Intrinsic::smul_fix:
6461 return ISD::SMULFIX;
6462 case Intrinsic::umul_fix:
6463 return ISD::UMULFIX;
6464 case Intrinsic::smul_fix_sat:
6465 return ISD::SMULFIXSAT;
6466 case Intrinsic::umul_fix_sat:
6467 return ISD::UMULFIXSAT;
6468 case Intrinsic::sdiv_fix:
6469 return ISD::SDIVFIX;
6470 case Intrinsic::udiv_fix:
6471 return ISD::UDIVFIX;
6472 case Intrinsic::sdiv_fix_sat:
6473 return ISD::SDIVFIXSAT;
6474 case Intrinsic::udiv_fix_sat:
6475 return ISD::UDIVFIXSAT;
6476 default:
6477 llvm_unreachable("Unhandled fixed point intrinsic");
6478 }
6479}
6480
6481/// Given a @llvm.call.preallocated.setup, return the corresponding
6482/// preallocated call.
6483static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6484 assert(cast<CallBase>(PreallocatedSetup)
6485 ->getCalledFunction()
6486 ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6487 "expected call_preallocated_setup Value");
6488 for (const auto *U : PreallocatedSetup->users()) {
6489 auto *UseCall = cast<CallBase>(Val: U);
6490 const Function *Fn = UseCall->getCalledFunction();
6491 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6492 return UseCall;
6493 }
6494 }
6495 llvm_unreachable("expected corresponding call to preallocated setup/arg");
6496}
6497
6498/// If DI is a debug value with an EntryValue expression, lower it using the
6499/// corresponding physical register of the associated Argument value
6500/// (guaranteed to exist by the verifier).
6501bool SelectionDAGBuilder::visitEntryValueDbgValue(
6502 ArrayRef<const Value *> Values, DILocalVariable *Variable,
6503 DIExpression *Expr, DebugLoc DbgLoc) {
6504 if (!Expr->isEntryValue() || !hasSingleElement(C&: Values))
6505 return false;
6506
6507 // These properties are guaranteed by the verifier.
6508 const Argument *Arg = cast<Argument>(Val: Values[0]);
6509 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6510
6511 auto ArgIt = FuncInfo.ValueMap.find(Val: Arg);
6512 if (ArgIt == FuncInfo.ValueMap.end()) {
6513 LLVM_DEBUG(
6514 dbgs() << "Dropping dbg.value: expression is entry_value but "
6515 "couldn't find an associated register for the Argument\n");
6516 return true;
6517 }
6518 Register ArgVReg = ArgIt->getSecond();
6519
6520 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6521 if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6522 SDDbgValue *SDV = DAG.getVRegDbgValue(
6523 Var: Variable, Expr, VReg: PhysReg, IsIndirect: false /*IsIndidrect*/, DL: DbgLoc, O: SDNodeOrder);
6524 DAG.AddDbgValue(DB: SDV, isParameter: false /*treat as dbg.declare byval parameter*/);
6525 return true;
6526 }
6527 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6528 "couldn't find a physical register\n");
6529 return true;
6530}
6531
6532/// Lower the call to the specified intrinsic function.
6533void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6534 unsigned Intrinsic) {
6535 SDLoc sdl = getCurSDLoc();
6536 switch (Intrinsic) {
6537 case Intrinsic::experimental_convergence_anchor:
6538 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERGENCECTRL_ANCHOR, DL: sdl, VT: MVT::Untyped));
6539 break;
6540 case Intrinsic::experimental_convergence_entry:
6541 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERGENCECTRL_ENTRY, DL: sdl, VT: MVT::Untyped));
6542 break;
6543 case Intrinsic::experimental_convergence_loop: {
6544 auto Bundle = I.getOperandBundle(ID: LLVMContext::OB_convergencectrl);
6545 auto *Token = Bundle->Inputs[0].get();
6546 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERGENCECTRL_LOOP, DL: sdl, VT: MVT::Untyped,
6547 Operand: getValue(V: Token)));
6548 break;
6549 }
6550 }
6551}
6552
6553void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6554 unsigned IntrinsicID) {
6555 // For now, we're only lowering an 'add' histogram.
6556 // We can add others later, e.g. saturating adds, min/max.
6557 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6558 "Tried to lower unsupported histogram type");
6559 SDLoc sdl = getCurSDLoc();
6560 Value *Ptr = I.getOperand(i_nocapture: 0);
6561 SDValue Inc = getValue(V: I.getOperand(i_nocapture: 1));
6562 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 2));
6563
6564 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6565 DataLayout TargetDL = DAG.getDataLayout();
6566 EVT VT = Inc.getValueType();
6567 Align Alignment = DAG.getEVTAlign(MemoryVT: VT);
6568
6569 const MDNode *Ranges = getRangeMetadata(I);
6570
6571 SDValue Root = DAG.getRoot();
6572 SDValue Base;
6573 SDValue Index;
6574 SDValue Scale;
6575 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, SDB: this,
6576 CurBB: I.getParent(), ElemSize: VT.getScalarStoreSize());
6577
6578 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6579
6580 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6581 PtrInfo: MachinePointerInfo(AS),
6582 F: MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6583 Size: MemoryLocation::UnknownSize, BaseAlignment: Alignment, AAInfo: I.getAAMetadata(), Ranges);
6584
6585 if (!UniformBase) {
6586 Base = DAG.getConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
6587 Index = getValue(V: Ptr);
6588 Scale =
6589 DAG.getTargetConstant(Val: 1, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
6590 }
6591
6592 EVT IdxVT = Index.getValueType();
6593
6594 // Avoid using e.g. i32 as index type when the increment must be performed
6595 // on i64's.
6596 bool MustExtendIndex = VT.getScalarSizeInBits() > IdxVT.getScalarSizeInBits();
6597 EVT EltTy = MustExtendIndex ? VT : IdxVT.getVectorElementType();
6598 if (MustExtendIndex || TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
6599 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
6600 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: sdl, VT: NewIdxVT, Operand: Index);
6601 }
6602
6603 SDValue ID = DAG.getTargetConstant(Val: IntrinsicID, DL: sdl, VT: MVT::i32);
6604
6605 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6606 SDValue Histogram = DAG.getMaskedHistogram(VTs: DAG.getVTList(VT: MVT::Other), MemVT: VT, dl: sdl,
6607 Ops, MMO, IndexType: ISD::SIGNED_SCALED);
6608
6609 setValue(V: &I, NewN: Histogram);
6610 DAG.setRoot(Histogram);
6611}
6612
6613void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6614 unsigned Intrinsic) {
6615 assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6616 "Tried lowering invalid vector extract last");
6617 SDLoc sdl = getCurSDLoc();
6618 const DataLayout &Layout = DAG.getDataLayout();
6619 SDValue Data = getValue(V: I.getOperand(i_nocapture: 0));
6620 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 1));
6621
6622 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6623 EVT ResVT = TLI.getValueType(DL: Layout, Ty: I.getType());
6624
6625 EVT ExtVT = TLI.getVectorIdxTy(DL: Layout);
6626 SDValue Idx = DAG.getNode(Opcode: ISD::VECTOR_FIND_LAST_ACTIVE, DL: sdl, VT: ExtVT, Operand: Mask);
6627 SDValue Result = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: sdl, VT: ResVT, N1: Data, N2: Idx);
6628
6629 Value *Default = I.getOperand(i_nocapture: 2);
6630 if (!isa<PoisonValue>(Val: Default) && !isa<UndefValue>(Val: Default)) {
6631 SDValue PassThru = getValue(V: Default);
6632 EVT BoolVT = Mask.getValueType().getScalarType();
6633 SDValue AnyActive = DAG.getNode(Opcode: ISD::VECREDUCE_OR, DL: sdl, VT: BoolVT, Operand: Mask);
6634 Result = DAG.getSelect(DL: sdl, VT: ResVT, Cond: AnyActive, LHS: Result, RHS: PassThru);
6635 }
6636
6637 setValue(V: &I, NewN: Result);
6638}
6639
6640/// Lower the call to the specified intrinsic function.
6641void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6642 unsigned Intrinsic) {
6643 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6644 SDLoc sdl = getCurSDLoc();
6645 DebugLoc dl = getCurDebugLoc();
6646 SDValue Res;
6647
6648 SDNodeFlags Flags;
6649 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
6650 Flags.copyFMF(FPMO: *FPOp);
6651
6652 switch (Intrinsic) {
6653 default:
6654 // By default, turn this into a target intrinsic node.
6655 visitTargetIntrinsic(I, Intrinsic);
6656 return;
6657 case Intrinsic::vscale: {
6658 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
6659 setValue(V: &I, NewN: DAG.getVScale(DL: sdl, VT, MulImm: APInt(VT.getSizeInBits(), 1)));
6660 return;
6661 }
6662 case Intrinsic::vastart: visitVAStart(I); return;
6663 case Intrinsic::vaend: visitVAEnd(I); return;
6664 case Intrinsic::vacopy: visitVACopy(I); return;
6665 case Intrinsic::returnaddress:
6666 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::RETURNADDR, DL: sdl,
6667 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
6668 Operand: getValue(V: I.getArgOperand(i: 0))));
6669 return;
6670 case Intrinsic::addressofreturnaddress:
6671 setValue(V: &I,
6672 NewN: DAG.getNode(Opcode: ISD::ADDROFRETURNADDR, DL: sdl,
6673 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType())));
6674 return;
6675 case Intrinsic::sponentry:
6676 setValue(V: &I,
6677 NewN: DAG.getNode(Opcode: ISD::SPONENTRY, DL: sdl,
6678 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType())));
6679 return;
6680 case Intrinsic::frameaddress:
6681 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FRAMEADDR, DL: sdl,
6682 VT: TLI.getFrameIndexTy(DL: DAG.getDataLayout()),
6683 Operand: getValue(V: I.getArgOperand(i: 0))));
6684 return;
6685 case Intrinsic::read_volatile_register:
6686 case Intrinsic::read_register: {
6687 Value *Reg = I.getArgOperand(i: 0);
6688 SDValue Chain = getRoot();
6689 SDValue RegName =
6690 DAG.getMDNode(MD: cast<MDNode>(Val: cast<MetadataAsValue>(Val: Reg)->getMetadata()));
6691 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
6692 Res = DAG.getNode(Opcode: ISD::READ_REGISTER, DL: sdl,
6693 VTList: DAG.getVTList(VT1: VT, VT2: MVT::Other), N1: Chain, N2: RegName);
6694 setValue(V: &I, NewN: Res);
6695 DAG.setRoot(Res.getValue(R: 1));
6696 return;
6697 }
6698 case Intrinsic::write_register: {
6699 Value *Reg = I.getArgOperand(i: 0);
6700 Value *RegValue = I.getArgOperand(i: 1);
6701 SDValue Chain = getRoot();
6702 SDValue RegName =
6703 DAG.getMDNode(MD: cast<MDNode>(Val: cast<MetadataAsValue>(Val: Reg)->getMetadata()));
6704 DAG.setRoot(DAG.getNode(Opcode: ISD::WRITE_REGISTER, DL: sdl, VT: MVT::Other, N1: Chain,
6705 N2: RegName, N3: getValue(V: RegValue)));
6706 return;
6707 }
6708 case Intrinsic::write_volatile_register: {
6709 Value *Reg = I.getArgOperand(i: 0);
6710 Value *RegValue = I.getArgOperand(i: 1);
6711 SDValue Chain = getRoot();
6712 const MDNode *MD = cast<MDNode>(Val: cast<MetadataAsValue>(Val: Reg)->getMetadata());
6713 SDValue RegName = DAG.getMDNode(MD);
6714 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: RegValue->getType());
6715 SDValue WriteChain = DAG.getNode(Opcode: ISD::WRITE_REGISTER, DL: sdl, VT: MVT::Other,
6716 N1: Chain, N2: RegName, N3: getValue(V: RegValue));
6717 // FAKE_USE of the physical register marks it live after the WRITE_REGISTER,
6718 // preventing the backend from dead-eliminating the write. This is
6719 // preferred over READ_REGISTER, which would emit extra register copies
6720 // (e.g. fmov xN, dN for FP/SIMD registers).
6721 const MDString *RegStr = cast<MDString>(Val: MD->getOperand(I: 0));
6722 LLT Ty = VT.isSimple() ? getLLTForMVT(Ty: VT.getSimpleVT()) : LLT();
6723 const MachineFunction &MF = DAG.getMachineFunction();
6724 Register PhysReg =
6725 TLI.getRegisterByName(RegName: RegStr->getString().data(), Ty, MF);
6726 if (PhysReg.isValid()) {
6727 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6728 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg: PhysReg);
6729 MVT RegVT = *TRI->legalclasstypes_begin(RC: *RC);
6730 DAG.setRoot(DAG.getNode(Opcode: ISD::FAKE_USE, DL: sdl, VT: MVT::Other,
6731 Ops: {WriteChain, DAG.getRegister(Reg: PhysReg, VT: RegVT)}));
6732 } else {
6733 DAG.setRoot(WriteChain);
6734 }
6735 return;
6736 }
6737 case Intrinsic::memcpy:
6738 case Intrinsic::memcpy_inline: {
6739 const auto &MCI = cast<MemCpyInst>(Val: I);
6740 SDValue Dst = getValue(V: I.getArgOperand(i: 0));
6741 SDValue Src = getValue(V: I.getArgOperand(i: 1));
6742 SDValue Size = getValue(V: I.getArgOperand(i: 2));
6743 assert((!MCI.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6744 "memcpy_inline needs constant size");
6745 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6746 Align DstAlign = MCI.getDestAlign().valueOrOne();
6747 Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6748 bool isVol = MCI.isVolatile();
6749 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6750 SDValue MC = DAG.getMemcpy(Chain: Root, dl: sdl, Dst, Src, Size, DstAlign, SrcAlign,
6751 isVol, AlwaysInline: MCI.isForceInlined(), CI: &I, OverrideTailCall: std::nullopt,
6752 DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
6753 SrcPtrInfo: MachinePointerInfo(I.getArgOperand(i: 1)),
6754 AAInfo: I.getAAMetadata(), BatchAA);
6755 updateDAGForMaybeTailCall(MaybeTC: MC);
6756 return;
6757 }
6758 case Intrinsic::memset:
6759 case Intrinsic::memset_inline: {
6760 const auto &MSII = cast<MemSetInst>(Val: I);
6761 SDValue Dst = getValue(V: I.getArgOperand(i: 0));
6762 SDValue Value = getValue(V: I.getArgOperand(i: 1));
6763 SDValue Size = getValue(V: I.getArgOperand(i: 2));
6764 assert((!MSII.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6765 "memset_inline needs constant size");
6766 // @llvm.memset defines 0 and 1 to both mean no alignment.
6767 Align DstAlign = MSII.getDestAlign().valueOrOne();
6768 bool isVol = MSII.isVolatile();
6769 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6770 SDValue MC = DAG.getMemset(
6771 Chain: Root, dl: sdl, Dst, Src: Value, Size, Alignment: DstAlign, isVol, AlwaysInline: MSII.isForceInlined(),
6772 CI: &I, DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)), AAInfo: I.getAAMetadata());
6773 updateDAGForMaybeTailCall(MaybeTC: MC);
6774 return;
6775 }
6776 case Intrinsic::memmove: {
6777 const auto &MMI = cast<MemMoveInst>(Val: I);
6778 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
6779 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
6780 SDValue Op3 = getValue(V: I.getArgOperand(i: 2));
6781 // @llvm.memmove defines 0 and 1 to both mean no alignment.
6782 Align DstAlign = MMI.getDestAlign().valueOrOne();
6783 Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6784 bool isVol = MMI.isVolatile();
6785 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6786 SDValue MM = DAG.getMemmove(
6787 Chain: Root, dl: sdl, Dst: Op1, Src: Op2, Size: Op3, DstAlign, SrcAlign, isVol, CI: &I,
6788 /* OverrideTailCall */ std::nullopt,
6789 DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
6790 SrcPtrInfo: MachinePointerInfo(I.getArgOperand(i: 1)), AAInfo: I.getAAMetadata(), BatchAA);
6791 updateDAGForMaybeTailCall(MaybeTC: MM);
6792 return;
6793 }
6794 case Intrinsic::memcpy_element_unordered_atomic: {
6795 auto &MI = cast<AnyMemCpyInst>(Val: I);
6796 SDValue Dst = getValue(V: MI.getRawDest());
6797 SDValue Src = getValue(V: MI.getRawSource());
6798 SDValue Length = getValue(V: MI.getLength());
6799
6800 Type *LengthTy = MI.getLength()->getType();
6801 unsigned ElemSz = MI.getElementSizeInBytes();
6802 bool isTC = I.isTailCall() && isInTailCallPosition(Call: I, TM: DAG.getTarget());
6803 SDValue MC =
6804 DAG.getAtomicMemcpy(Chain: getRoot(), dl: sdl, Dst, Src, Size: Length, SizeTy: LengthTy, ElemSz,
6805 isTailCall: isTC, DstPtrInfo: MachinePointerInfo(MI.getRawDest()),
6806 SrcPtrInfo: MachinePointerInfo(MI.getRawSource()));
6807 updateDAGForMaybeTailCall(MaybeTC: MC);
6808 return;
6809 }
6810 case Intrinsic::memmove_element_unordered_atomic: {
6811 auto &MI = cast<AnyMemMoveInst>(Val: I);
6812 SDValue Dst = getValue(V: MI.getRawDest());
6813 SDValue Src = getValue(V: MI.getRawSource());
6814 SDValue Length = getValue(V: MI.getLength());
6815
6816 Type *LengthTy = MI.getLength()->getType();
6817 unsigned ElemSz = MI.getElementSizeInBytes();
6818 bool isTC = I.isTailCall() && isInTailCallPosition(Call: I, TM: DAG.getTarget());
6819 SDValue MC =
6820 DAG.getAtomicMemmove(Chain: getRoot(), dl: sdl, Dst, Src, Size: Length, SizeTy: LengthTy, ElemSz,
6821 isTailCall: isTC, DstPtrInfo: MachinePointerInfo(MI.getRawDest()),
6822 SrcPtrInfo: MachinePointerInfo(MI.getRawSource()));
6823 updateDAGForMaybeTailCall(MaybeTC: MC);
6824 return;
6825 }
6826 case Intrinsic::memset_element_unordered_atomic: {
6827 auto &MI = cast<AnyMemSetInst>(Val: I);
6828 SDValue Dst = getValue(V: MI.getRawDest());
6829 SDValue Val = getValue(V: MI.getValue());
6830 SDValue Length = getValue(V: MI.getLength());
6831
6832 Type *LengthTy = MI.getLength()->getType();
6833 unsigned ElemSz = MI.getElementSizeInBytes();
6834 bool isTC = I.isTailCall() && isInTailCallPosition(Call: I, TM: DAG.getTarget());
6835 SDValue MC =
6836 DAG.getAtomicMemset(Chain: getRoot(), dl: sdl, Dst, Value: Val, Size: Length, SizeTy: LengthTy, ElemSz,
6837 isTailCall: isTC, DstPtrInfo: MachinePointerInfo(MI.getRawDest()));
6838 updateDAGForMaybeTailCall(MaybeTC: MC);
6839 return;
6840 }
6841 case Intrinsic::call_preallocated_setup: {
6842 const CallBase *PreallocatedCall = FindPreallocatedCall(PreallocatedSetup: &I);
6843 SDValue SrcValue = DAG.getSrcValue(v: PreallocatedCall);
6844 SDValue Res = DAG.getNode(Opcode: ISD::PREALLOCATED_SETUP, DL: sdl, VT: MVT::Other,
6845 N1: getRoot(), N2: SrcValue);
6846 setValue(V: &I, NewN: Res);
6847 DAG.setRoot(Res);
6848 return;
6849 }
6850 case Intrinsic::call_preallocated_arg: {
6851 const CallBase *PreallocatedCall = FindPreallocatedCall(PreallocatedSetup: I.getOperand(i_nocapture: 0));
6852 SDValue SrcValue = DAG.getSrcValue(v: PreallocatedCall);
6853 SDValue Ops[3];
6854 Ops[0] = getRoot();
6855 Ops[1] = SrcValue;
6856 Ops[2] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 1)), DL: sdl,
6857 VT: MVT::i32); // arg index
6858 SDValue Res = DAG.getNode(
6859 Opcode: ISD::PREALLOCATED_ARG, DL: sdl,
6860 VTList: DAG.getVTList(VT1: TLI.getPointerTy(DL: DAG.getDataLayout()), VT2: MVT::Other), Ops);
6861 setValue(V: &I, NewN: Res);
6862 DAG.setRoot(Res.getValue(R: 1));
6863 return;
6864 }
6865
6866 case Intrinsic::eh_typeid_for: {
6867 // Find the type id for the given typeinfo.
6868 GlobalValue *GV = ExtractTypeInfo(V: I.getArgOperand(i: 0));
6869 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(TI: GV);
6870 Res = DAG.getConstant(Val: TypeID, DL: sdl, VT: MVT::i32);
6871 setValue(V: &I, NewN: Res);
6872 return;
6873 }
6874
6875 case Intrinsic::eh_return_i32:
6876 case Intrinsic::eh_return_i64:
6877 DAG.getMachineFunction().setCallsEHReturn(true);
6878 DAG.setRoot(DAG.getNode(Opcode: ISD::EH_RETURN, DL: sdl,
6879 VT: MVT::Other,
6880 N1: getControlRoot(),
6881 N2: getValue(V: I.getArgOperand(i: 0)),
6882 N3: getValue(V: I.getArgOperand(i: 1))));
6883 return;
6884 case Intrinsic::eh_unwind_init:
6885 DAG.getMachineFunction().setCallsUnwindInit(true);
6886 return;
6887 case Intrinsic::eh_dwarf_cfa:
6888 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::EH_DWARF_CFA, DL: sdl,
6889 VT: TLI.getPointerTy(DL: DAG.getDataLayout()),
6890 Operand: getValue(V: I.getArgOperand(i: 0))));
6891 return;
6892 case Intrinsic::eh_sjlj_callsite: {
6893 ConstantInt *CI = cast<ConstantInt>(Val: I.getArgOperand(i: 0));
6894 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6895
6896 FuncInfo.setCurrentCallSite(CI->getZExtValue());
6897 return;
6898 }
6899 case Intrinsic::eh_sjlj_functioncontext: {
6900 // Get and store the index of the function context.
6901 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6902 AllocaInst *FnCtx =
6903 cast<AllocaInst>(Val: I.getArgOperand(i: 0)->stripPointerCasts());
6904 int FI = FuncInfo.StaticAllocaMap[FnCtx];
6905 MFI.setFunctionContextIndex(FI);
6906 return;
6907 }
6908 case Intrinsic::eh_sjlj_setjmp: {
6909 SDValue Ops[2];
6910 Ops[0] = getRoot();
6911 Ops[1] = getValue(V: I.getArgOperand(i: 0));
6912 SDValue Op = DAG.getNode(Opcode: ISD::EH_SJLJ_SETJMP, DL: sdl,
6913 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::Other), Ops);
6914 setValue(V: &I, NewN: Op.getValue(R: 0));
6915 DAG.setRoot(Op.getValue(R: 1));
6916 return;
6917 }
6918 case Intrinsic::eh_sjlj_longjmp:
6919 DAG.setRoot(DAG.getNode(Opcode: ISD::EH_SJLJ_LONGJMP, DL: sdl, VT: MVT::Other,
6920 N1: getRoot(), N2: getValue(V: I.getArgOperand(i: 0))));
6921 return;
6922 case Intrinsic::eh_sjlj_setup_dispatch:
6923 DAG.setRoot(DAG.getNode(Opcode: ISD::EH_SJLJ_SETUP_DISPATCH, DL: sdl, VT: MVT::Other,
6924 Operand: getRoot()));
6925 return;
6926 case Intrinsic::masked_gather:
6927 visitMaskedGather(I);
6928 return;
6929 case Intrinsic::masked_load:
6930 visitMaskedLoad(I);
6931 return;
6932 case Intrinsic::masked_scatter:
6933 visitMaskedScatter(I);
6934 return;
6935 case Intrinsic::masked_store:
6936 visitMaskedStore(I);
6937 return;
6938 case Intrinsic::masked_expandload:
6939 visitMaskedLoad(I, IsExpanding: true /* IsExpanding */);
6940 return;
6941 case Intrinsic::masked_compressstore:
6942 visitMaskedStore(I, IsCompressing: true /* IsCompressing */);
6943 return;
6944 case Intrinsic::powi:
6945 setValue(V: &I, NewN: ExpandPowI(DL: sdl, LHS: getValue(V: I.getArgOperand(i: 0)),
6946 RHS: getValue(V: I.getArgOperand(i: 1)), DAG));
6947 return;
6948 case Intrinsic::log:
6949 setValue(V: &I, NewN: expandLog(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6950 return;
6951 case Intrinsic::log2:
6952 setValue(V: &I,
6953 NewN: expandLog2(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6954 return;
6955 case Intrinsic::log10:
6956 setValue(V: &I,
6957 NewN: expandLog10(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6958 return;
6959 case Intrinsic::exp:
6960 setValue(V: &I, NewN: expandExp(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6961 return;
6962 case Intrinsic::exp2:
6963 setValue(V: &I,
6964 NewN: expandExp2(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6965 return;
6966 case Intrinsic::pow:
6967 setValue(V: &I, NewN: expandPow(dl: sdl, LHS: getValue(V: I.getArgOperand(i: 0)),
6968 RHS: getValue(V: I.getArgOperand(i: 1)), DAG, TLI, Flags));
6969 return;
6970 case Intrinsic::sqrt:
6971 case Intrinsic::fabs:
6972 case Intrinsic::sin:
6973 case Intrinsic::cos:
6974 case Intrinsic::tan:
6975 case Intrinsic::asin:
6976 case Intrinsic::acos:
6977 case Intrinsic::atan:
6978 case Intrinsic::sinh:
6979 case Intrinsic::cosh:
6980 case Intrinsic::tanh:
6981 case Intrinsic::exp10:
6982 case Intrinsic::floor:
6983 case Intrinsic::ceil:
6984 case Intrinsic::trunc:
6985 case Intrinsic::rint:
6986 case Intrinsic::nearbyint:
6987 case Intrinsic::round:
6988 case Intrinsic::roundeven:
6989 case Intrinsic::canonicalize: {
6990 unsigned Opcode;
6991 // clang-format off
6992 switch (Intrinsic) {
6993 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6994 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
6995 case Intrinsic::fabs: Opcode = ISD::FABS; break;
6996 case Intrinsic::sin: Opcode = ISD::FSIN; break;
6997 case Intrinsic::cos: Opcode = ISD::FCOS; break;
6998 case Intrinsic::tan: Opcode = ISD::FTAN; break;
6999 case Intrinsic::asin: Opcode = ISD::FASIN; break;
7000 case Intrinsic::acos: Opcode = ISD::FACOS; break;
7001 case Intrinsic::atan: Opcode = ISD::FATAN; break;
7002 case Intrinsic::sinh: Opcode = ISD::FSINH; break;
7003 case Intrinsic::cosh: Opcode = ISD::FCOSH; break;
7004 case Intrinsic::tanh: Opcode = ISD::FTANH; break;
7005 case Intrinsic::exp10: Opcode = ISD::FEXP10; break;
7006 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
7007 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
7008 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
7009 case Intrinsic::rint: Opcode = ISD::FRINT; break;
7010 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
7011 case Intrinsic::round: Opcode = ISD::FROUND; break;
7012 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
7013 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
7014 }
7015 // clang-format on
7016
7017 setValue(V: &I, NewN: DAG.getNode(Opcode, DL: sdl,
7018 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7019 Operand: getValue(V: I.getArgOperand(i: 0)), Flags));
7020 return;
7021 }
7022 case Intrinsic::atan2:
7023 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FATAN2, DL: sdl,
7024 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7025 N1: getValue(V: I.getArgOperand(i: 0)),
7026 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7027 return;
7028 case Intrinsic::lround:
7029 case Intrinsic::llround:
7030 case Intrinsic::lrint:
7031 case Intrinsic::llrint: {
7032 unsigned Opcode;
7033 // clang-format off
7034 switch (Intrinsic) {
7035 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7036 case Intrinsic::lround: Opcode = ISD::LROUND; break;
7037 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
7038 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
7039 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
7040 }
7041 // clang-format on
7042
7043 EVT RetVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7044 setValue(V: &I, NewN: DAG.getNode(Opcode, DL: sdl, VT: RetVT,
7045 Operand: getValue(V: I.getArgOperand(i: 0))));
7046 return;
7047 }
7048 case Intrinsic::minnum:
7049 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMINNUM, DL: sdl,
7050 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7051 N1: getValue(V: I.getArgOperand(i: 0)),
7052 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7053 return;
7054 case Intrinsic::maxnum:
7055 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMAXNUM, DL: sdl,
7056 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7057 N1: getValue(V: I.getArgOperand(i: 0)),
7058 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7059 return;
7060 case Intrinsic::minimum:
7061 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMINIMUM, DL: sdl,
7062 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7063 N1: getValue(V: I.getArgOperand(i: 0)),
7064 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7065 return;
7066 case Intrinsic::maximum:
7067 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMAXIMUM, DL: sdl,
7068 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7069 N1: getValue(V: I.getArgOperand(i: 0)),
7070 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7071 return;
7072 case Intrinsic::minimumnum:
7073 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMINIMUMNUM, DL: sdl,
7074 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7075 N1: getValue(V: I.getArgOperand(i: 0)),
7076 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7077 return;
7078 case Intrinsic::maximumnum:
7079 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMAXIMUMNUM, DL: sdl,
7080 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7081 N1: getValue(V: I.getArgOperand(i: 0)),
7082 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7083 return;
7084 case Intrinsic::copysign:
7085 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FCOPYSIGN, DL: sdl,
7086 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7087 N1: getValue(V: I.getArgOperand(i: 0)),
7088 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7089 return;
7090 case Intrinsic::ldexp:
7091 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FLDEXP, DL: sdl,
7092 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7093 N1: getValue(V: I.getArgOperand(i: 0)),
7094 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7095 return;
7096 case Intrinsic::modf:
7097 case Intrinsic::sincos:
7098 case Intrinsic::sincospi:
7099 case Intrinsic::frexp: {
7100 unsigned Opcode;
7101 switch (Intrinsic) {
7102 default:
7103 llvm_unreachable("unexpected intrinsic");
7104 case Intrinsic::sincos:
7105 Opcode = ISD::FSINCOS;
7106 break;
7107 case Intrinsic::sincospi:
7108 Opcode = ISD::FSINCOSPI;
7109 break;
7110 case Intrinsic::modf:
7111 Opcode = ISD::FMODF;
7112 break;
7113 case Intrinsic::frexp:
7114 Opcode = ISD::FFREXP;
7115 break;
7116 }
7117 SmallVector<EVT, 2> ValueVTs;
7118 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: I.getType(), ValueVTs);
7119 SDVTList VTs = DAG.getVTList(VTs: ValueVTs);
7120 setValue(
7121 V: &I, NewN: DAG.getNode(Opcode, DL: sdl, VTList: VTs, Ops: getValue(V: I.getArgOperand(i: 0)), Flags));
7122 return;
7123 }
7124 case Intrinsic::arithmetic_fence: {
7125 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::ARITH_FENCE, DL: sdl,
7126 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7127 Operand: getValue(V: I.getArgOperand(i: 0)), Flags));
7128 return;
7129 }
7130 case Intrinsic::fma:
7131 setValue(V: &I, NewN: DAG.getNode(
7132 Opcode: ISD::FMA, DL: sdl, VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7133 N1: getValue(V: I.getArgOperand(i: 0)), N2: getValue(V: I.getArgOperand(i: 1)),
7134 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
7135 return;
7136#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
7137 case Intrinsic::INTRINSIC:
7138#include "llvm/IR/ConstrainedOps.def"
7139 visitConstrainedFPIntrinsic(FPI: cast<ConstrainedFPIntrinsic>(Val: I));
7140 return;
7141#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7142#include "llvm/IR/VPIntrinsics.def"
7143 visitVectorPredicationIntrinsic(VPIntrin: cast<VPIntrinsic>(Val: I));
7144 return;
7145 case Intrinsic::fptrunc_round: {
7146 // Get the last argument, the metadata and convert it to an integer in the
7147 // call
7148 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 1))->getMetadata();
7149 std::optional<RoundingMode> RoundMode =
7150 convertStrToRoundingMode(cast<MDString>(Val: MD)->getString());
7151
7152 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7153
7154 // Propagate fast-math-flags from IR to node(s).
7155 SDNodeFlags Flags;
7156 Flags.copyFMF(FPMO: *cast<FPMathOperator>(Val: &I));
7157 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7158
7159 SDValue Result;
7160 Result = DAG.getNode(
7161 Opcode: ISD::FPTRUNC_ROUND, DL: sdl, VT, N1: getValue(V: I.getArgOperand(i: 0)),
7162 N2: DAG.getTargetConstant(Val: (int)*RoundMode, DL: sdl, VT: MVT::i32));
7163 setValue(V: &I, NewN: Result);
7164
7165 return;
7166 }
7167 case Intrinsic::fmuladd: {
7168 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7169 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7170 TLI.isFMAFasterThanFMulAndFAdd(MF: DAG.getMachineFunction(), VT)) {
7171 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMA, DL: sdl,
7172 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7173 N1: getValue(V: I.getArgOperand(i: 0)),
7174 N2: getValue(V: I.getArgOperand(i: 1)),
7175 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
7176 } else if (TLI.isOperationLegalOrCustom(Op: ISD::FMULADD, VT)) {
7177 // TODO: Support splitting the vector.
7178 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMULADD, DL: sdl,
7179 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7180 N1: getValue(V: I.getArgOperand(i: 0)),
7181 N2: getValue(V: I.getArgOperand(i: 1)),
7182 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
7183 } else {
7184 // TODO: Intrinsic calls should have fast-math-flags.
7185 SDValue Mul = DAG.getNode(
7186 Opcode: ISD::FMUL, DL: sdl, VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7187 N1: getValue(V: I.getArgOperand(i: 0)), N2: getValue(V: I.getArgOperand(i: 1)), Flags);
7188 SDValue Add = DAG.getNode(Opcode: ISD::FADD, DL: sdl,
7189 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7190 N1: Mul, N2: getValue(V: I.getArgOperand(i: 2)), Flags);
7191 setValue(V: &I, NewN: Add);
7192 }
7193 return;
7194 }
7195 case Intrinsic::fptosi_sat: {
7196 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7197 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_SINT_SAT, DL: sdl, VT,
7198 N1: getValue(V: I.getArgOperand(i: 0)),
7199 N2: DAG.getValueType(VT.getScalarType())));
7200 return;
7201 }
7202 case Intrinsic::fptoui_sat: {
7203 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7204 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_UINT_SAT, DL: sdl, VT,
7205 N1: getValue(V: I.getArgOperand(i: 0)),
7206 N2: DAG.getValueType(VT.getScalarType())));
7207 return;
7208 }
7209 case Intrinsic::convert_from_arbitrary_fp: {
7210 // Extract format metadata and convert to semantics enum.
7211 EVT DstVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7212 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 1))->getMetadata();
7213 StringRef FormatStr = cast<MDString>(Val: MD)->getString();
7214 const fltSemantics *SrcSem =
7215 APFloatBase::getArbitraryFPSemantics(Format: FormatStr);
7216 if (!SrcSem) {
7217 DAG.getContext()->emitError(
7218 ErrorStr: "convert_from_arbitrary_fp: not implemented format '" + FormatStr +
7219 "'");
7220 setValue(V: &I, NewN: DAG.getPOISON(VT: DstVT));
7221 return;
7222 }
7223 APFloatBase::Semantics SemEnum = APFloatBase::SemanticsToEnum(Sem: *SrcSem);
7224
7225 SDValue IntVal = getValue(V: I.getArgOperand(i: 0));
7226
7227 // Emit ISD::CONVERT_FROM_ARBITRARY_FP node.
7228 SDValue SemConst =
7229 DAG.getTargetConstant(Val: static_cast<int>(SemEnum), DL: sdl, VT: MVT::i32);
7230 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERT_FROM_ARBITRARY_FP, DL: sdl, VT: DstVT, N1: IntVal,
7231 N2: SemConst));
7232 return;
7233 }
7234 case Intrinsic::convert_to_arbitrary_fp: {
7235 // Extract format metadata and convert to semantics enum.
7236 EVT DstVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7237 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 1))->getMetadata();
7238 StringRef FormatStr = cast<MDString>(Val: MD)->getString();
7239 const fltSemantics *DstSem =
7240 APFloatBase::getArbitraryFPSemantics(Format: FormatStr);
7241 if (!DstSem) {
7242 DAG.getContext()->emitError(
7243 ErrorStr: "convert_to_arbitrary_fp: not implemented format '" + FormatStr +
7244 "'");
7245 setValue(V: &I, NewN: DAG.getPOISON(VT: DstVT));
7246 return;
7247 }
7248 APFloatBase::Semantics SemEnum = APFloatBase::SemanticsToEnum(Sem: *DstSem);
7249
7250 Metadata *RoundMD =
7251 cast<MetadataAsValue>(Val: I.getArgOperand(i: 2))->getMetadata();
7252 StringRef RoundStr = cast<MDString>(Val: RoundMD)->getString();
7253 std::optional<RoundingMode> RoundMode = convertStrToRoundingMode(RoundStr);
7254 assert(RoundMode && *RoundMode != RoundingMode::Dynamic &&
7255 "Dynamic rounding mode should have been rejected by the verifier");
7256
7257 uint64_t Saturate =
7258 cast<ConstantInt>(Val: I.getArgOperand(i: 3))->getZExtValue() ? 1 : 0;
7259
7260 SDValue FloatVal = getValue(V: I.getArgOperand(i: 0));
7261
7262 SDValue SemConst =
7263 DAG.getTargetConstant(Val: static_cast<int>(SemEnum), DL: sdl, VT: MVT::i32);
7264 SDValue RoundConst =
7265 DAG.getTargetConstant(Val: static_cast<int>(*RoundMode), DL: sdl, VT: MVT::i32);
7266 SDValue SatConst = DAG.getTargetConstant(Val: Saturate, DL: sdl, VT: MVT::i32);
7267 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERT_TO_ARBITRARY_FP, DL: sdl, VT: DstVT, N1: FloatVal,
7268 N2: SemConst, N3: RoundConst, N4: SatConst));
7269 return;
7270 }
7271 case Intrinsic::set_rounding:
7272 Res = DAG.getNode(Opcode: ISD::SET_ROUNDING, DL: sdl, VT: MVT::Other,
7273 Ops: {getRoot(), getValue(V: I.getArgOperand(i: 0))});
7274 setValue(V: &I, NewN: Res);
7275 DAG.setRoot(Res.getValue(R: 0));
7276 return;
7277 case Intrinsic::is_fpclass: {
7278 const DataLayout DLayout = DAG.getDataLayout();
7279 EVT DestVT = TLI.getValueType(DL: DLayout, Ty: I.getType());
7280 EVT ArgVT = TLI.getValueType(DL: DLayout, Ty: I.getArgOperand(i: 0)->getType());
7281 FPClassTest Test = static_cast<FPClassTest>(
7282 cast<ConstantInt>(Val: I.getArgOperand(i: 1))->getZExtValue());
7283 MachineFunction &MF = DAG.getMachineFunction();
7284 const Function &F = MF.getFunction();
7285 SDValue Op = getValue(V: I.getArgOperand(i: 0));
7286 SDNodeFlags Flags;
7287 Flags.setNoFPExcept(
7288 !F.getAttributes().hasFnAttr(Kind: llvm::Attribute::StrictFP));
7289 // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7290 // expansion can use illegal types. Making expansion early allows
7291 // legalizing these types prior to selection.
7292 if (!TLI.isOperationLegal(Op: ISD::IS_FPCLASS, VT: ArgVT) &&
7293 !TLI.isOperationCustom(Op: ISD::IS_FPCLASS, VT: ArgVT)) {
7294 SDValue Result = TLI.expandIS_FPCLASS(ResultVT: DestVT, Op, Test, Flags, DL: sdl, DAG);
7295 setValue(V: &I, NewN: Result);
7296 return;
7297 }
7298
7299 SDValue Check = DAG.getTargetConstant(Val: Test, DL: sdl, VT: MVT::i32);
7300 SDValue V = DAG.getNode(Opcode: ISD::IS_FPCLASS, DL: sdl, VT: DestVT, Ops: {Op, Check}, Flags);
7301 setValue(V: &I, NewN: V);
7302 return;
7303 }
7304 case Intrinsic::get_fpenv: {
7305 const DataLayout DLayout = DAG.getDataLayout();
7306 EVT EnvVT = TLI.getValueType(DL: DLayout, Ty: I.getType());
7307 Align TempAlign = DAG.getEVTAlign(MemoryVT: EnvVT);
7308 SDValue Chain = getRoot();
7309 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7310 // and temporary storage in stack.
7311 if (TLI.isOperationLegalOrCustom(Op: ISD::GET_FPENV, VT: EnvVT)) {
7312 Res = DAG.getNode(
7313 Opcode: ISD::GET_FPENV, DL: sdl,
7314 VTList: DAG.getVTList(VT1: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
7315 VT2: MVT::Other),
7316 N: Chain);
7317 } else {
7318 SDValue Temp = DAG.CreateStackTemporary(VT: EnvVT, minAlign: TempAlign.value());
7319 int SPFI = cast<FrameIndexSDNode>(Val: Temp.getNode())->getIndex();
7320 auto MPI =
7321 MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI: SPFI);
7322 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7323 PtrInfo: MPI, F: MachineMemOperand::MOStore, Size: LocationSize::beforeOrAfterPointer(),
7324 BaseAlignment: TempAlign);
7325 Chain = DAG.getGetFPEnv(Chain, dl: sdl, Ptr: Temp, MemVT: EnvVT, MMO);
7326 Res = DAG.getLoad(VT: EnvVT, dl: sdl, Chain, Ptr: Temp, PtrInfo: MPI);
7327 }
7328 setValue(V: &I, NewN: Res);
7329 DAG.setRoot(Res.getValue(R: 1));
7330 return;
7331 }
7332 case Intrinsic::set_fpenv: {
7333 const DataLayout DLayout = DAG.getDataLayout();
7334 SDValue Env = getValue(V: I.getArgOperand(i: 0));
7335 EVT EnvVT = Env.getValueType();
7336 Align TempAlign = DAG.getEVTAlign(MemoryVT: EnvVT);
7337 SDValue Chain = getRoot();
7338 // If SET_FPENV is custom or legal, use it. Otherwise use loading
7339 // environment from memory.
7340 if (TLI.isOperationLegalOrCustom(Op: ISD::SET_FPENV, VT: EnvVT)) {
7341 Chain = DAG.getNode(Opcode: ISD::SET_FPENV, DL: sdl, VT: MVT::Other, N1: Chain, N2: Env);
7342 } else {
7343 // Allocate space in stack, copy environment bits into it and use this
7344 // memory in SET_FPENV_MEM.
7345 SDValue Temp = DAG.CreateStackTemporary(VT: EnvVT, minAlign: TempAlign.value());
7346 int SPFI = cast<FrameIndexSDNode>(Val: Temp.getNode())->getIndex();
7347 auto MPI =
7348 MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI: SPFI);
7349 Chain = DAG.getStore(Chain, dl: sdl, Val: Env, Ptr: Temp, PtrInfo: MPI, Alignment: TempAlign,
7350 MMOFlags: MachineMemOperand::MOStore);
7351 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7352 PtrInfo: MPI, F: MachineMemOperand::MOLoad, Size: LocationSize::beforeOrAfterPointer(),
7353 BaseAlignment: TempAlign);
7354 Chain = DAG.getSetFPEnv(Chain, dl: sdl, Ptr: Temp, MemVT: EnvVT, MMO);
7355 }
7356 DAG.setRoot(Chain);
7357 return;
7358 }
7359 case Intrinsic::reset_fpenv:
7360 DAG.setRoot(DAG.getNode(Opcode: ISD::RESET_FPENV, DL: sdl, VT: MVT::Other, Operand: getRoot()));
7361 return;
7362 case Intrinsic::get_fpmode:
7363 Res = DAG.getNode(
7364 Opcode: ISD::GET_FPMODE, DL: sdl,
7365 VTList: DAG.getVTList(VT1: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
7366 VT2: MVT::Other),
7367 N: DAG.getRoot());
7368 setValue(V: &I, NewN: Res);
7369 DAG.setRoot(Res.getValue(R: 1));
7370 return;
7371 case Intrinsic::set_fpmode:
7372 Res = DAG.getNode(Opcode: ISD::SET_FPMODE, DL: sdl, VT: MVT::Other, N1: {DAG.getRoot()},
7373 N2: getValue(V: I.getArgOperand(i: 0)));
7374 DAG.setRoot(Res);
7375 return;
7376 case Intrinsic::reset_fpmode: {
7377 Res = DAG.getNode(Opcode: ISD::RESET_FPMODE, DL: sdl, VT: MVT::Other, Operand: getRoot());
7378 DAG.setRoot(Res);
7379 return;
7380 }
7381 case Intrinsic::pcmarker: {
7382 SDValue Tmp = getValue(V: I.getArgOperand(i: 0));
7383 DAG.setRoot(DAG.getNode(Opcode: ISD::PCMARKER, DL: sdl, VT: MVT::Other, N1: getRoot(), N2: Tmp));
7384 return;
7385 }
7386 case Intrinsic::readcyclecounter: {
7387 SDValue Op = getRoot();
7388 Res = DAG.getNode(Opcode: ISD::READCYCLECOUNTER, DL: sdl,
7389 VTList: DAG.getVTList(VT1: MVT::i64, VT2: MVT::Other), N: Op);
7390 setValue(V: &I, NewN: Res);
7391 DAG.setRoot(Res.getValue(R: 1));
7392 return;
7393 }
7394 case Intrinsic::readsteadycounter: {
7395 SDValue Op = getRoot();
7396 Res = DAG.getNode(Opcode: ISD::READSTEADYCOUNTER, DL: sdl,
7397 VTList: DAG.getVTList(VT1: MVT::i64, VT2: MVT::Other), N: Op);
7398 setValue(V: &I, NewN: Res);
7399 DAG.setRoot(Res.getValue(R: 1));
7400 return;
7401 }
7402 case Intrinsic::bitreverse:
7403 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::BITREVERSE, DL: sdl,
7404 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7405 Operand: getValue(V: I.getArgOperand(i: 0))));
7406 return;
7407 case Intrinsic::bswap:
7408 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::BSWAP, DL: sdl,
7409 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7410 Operand: getValue(V: I.getArgOperand(i: 0))));
7411 return;
7412 case Intrinsic::cttz: {
7413 SDValue Arg = getValue(V: I.getArgOperand(i: 0));
7414 ConstantInt *CI = cast<ConstantInt>(Val: I.getArgOperand(i: 1));
7415 EVT Ty = Arg.getValueType();
7416 setValue(V: &I, NewN: DAG.getNode(Opcode: CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_POISON,
7417 DL: sdl, VT: Ty, Operand: Arg));
7418 return;
7419 }
7420 case Intrinsic::ctlz: {
7421 SDValue Arg = getValue(V: I.getArgOperand(i: 0));
7422 ConstantInt *CI = cast<ConstantInt>(Val: I.getArgOperand(i: 1));
7423 EVT Ty = Arg.getValueType();
7424 setValue(V: &I, NewN: DAG.getNode(Opcode: CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_POISON,
7425 DL: sdl, VT: Ty, Operand: Arg));
7426 return;
7427 }
7428 case Intrinsic::ctpop: {
7429 SDValue Arg = getValue(V: I.getArgOperand(i: 0));
7430 EVT Ty = Arg.getValueType();
7431 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CTPOP, DL: sdl, VT: Ty, Operand: Arg));
7432 return;
7433 }
7434 case Intrinsic::fshl:
7435 case Intrinsic::fshr: {
7436 bool IsFSHL = Intrinsic == Intrinsic::fshl;
7437 SDValue X = getValue(V: I.getArgOperand(i: 0));
7438 SDValue Y = getValue(V: I.getArgOperand(i: 1));
7439 SDValue Z = getValue(V: I.getArgOperand(i: 2));
7440 EVT VT = X.getValueType();
7441
7442 if (X == Y) {
7443 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7444 setValue(V: &I, NewN: DAG.getNode(Opcode: RotateOpcode, DL: sdl, VT, N1: X, N2: Z));
7445 } else {
7446 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7447 setValue(V: &I, NewN: DAG.getNode(Opcode: FunnelOpcode, DL: sdl, VT, N1: X, N2: Y, N3: Z));
7448 }
7449 return;
7450 }
7451 case Intrinsic::clmul: {
7452 SDValue X = getValue(V: I.getArgOperand(i: 0));
7453 SDValue Y = getValue(V: I.getArgOperand(i: 1));
7454 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CLMUL, DL: sdl, VT: X.getValueType(), N1: X, N2: Y));
7455 return;
7456 }
7457 case Intrinsic::pext: {
7458 SDValue X = getValue(V: I.getArgOperand(i: 0));
7459 SDValue Y = getValue(V: I.getArgOperand(i: 1));
7460 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::PEXT, DL: sdl, VT: X.getValueType(), N1: X, N2: Y));
7461 return;
7462 }
7463 case Intrinsic::pdep: {
7464 SDValue X = getValue(V: I.getArgOperand(i: 0));
7465 SDValue Y = getValue(V: I.getArgOperand(i: 1));
7466 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::PDEP, DL: sdl, VT: X.getValueType(), N1: X, N2: Y));
7467 return;
7468 }
7469 case Intrinsic::sadd_sat: {
7470 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7471 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7472 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SADDSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7473 return;
7474 }
7475 case Intrinsic::uadd_sat: {
7476 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7477 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7478 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UADDSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7479 return;
7480 }
7481 case Intrinsic::ssub_sat: {
7482 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7483 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7484 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SSUBSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7485 return;
7486 }
7487 case Intrinsic::usub_sat: {
7488 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7489 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7490 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::USUBSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7491 return;
7492 }
7493 case Intrinsic::sshl_sat:
7494 case Intrinsic::ushl_sat: {
7495 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7496 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7497
7498 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
7499 LHSTy: Op1.getValueType(), DL: DAG.getDataLayout());
7500
7501 // Coerce the shift amount to the right type if we can. This exposes the
7502 // truncate or zext to optimization early.
7503 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
7504 assert(ShiftTy.getSizeInBits() >=
7505 Log2_32_Ceil(Op1.getValueSizeInBits()) &&
7506 "Unexpected shift type");
7507 Op2 = DAG.getZExtOrTrunc(Op: Op2, DL: getCurSDLoc(), VT: ShiftTy);
7508 }
7509
7510 unsigned Opc =
7511 Intrinsic == Intrinsic::sshl_sat ? ISD::SSHLSAT : ISD::USHLSAT;
7512 setValue(V: &I, NewN: DAG.getNode(Opcode: Opc, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7513 return;
7514 }
7515 case Intrinsic::smul_fix:
7516 case Intrinsic::umul_fix:
7517 case Intrinsic::smul_fix_sat:
7518 case Intrinsic::umul_fix_sat: {
7519 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7520 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7521 SDValue Op3 = getValue(V: I.getArgOperand(i: 2));
7522 setValue(V: &I, NewN: DAG.getNode(Opcode: FixedPointIntrinsicToOpcode(Intrinsic), DL: sdl,
7523 VT: Op1.getValueType(), N1: Op1, N2: Op2, N3: Op3));
7524 return;
7525 }
7526 case Intrinsic::sdiv_fix:
7527 case Intrinsic::udiv_fix:
7528 case Intrinsic::sdiv_fix_sat:
7529 case Intrinsic::udiv_fix_sat: {
7530 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7531 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7532 SDValue Op3 = getValue(V: I.getArgOperand(i: 2));
7533 setValue(V: &I, NewN: expandDivFix(Opcode: FixedPointIntrinsicToOpcode(Intrinsic), DL: sdl,
7534 LHS: Op1, RHS: Op2, Scale: Op3, DAG, TLI));
7535 return;
7536 }
7537 case Intrinsic::smax: {
7538 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7539 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7540 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SMAX, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7541 return;
7542 }
7543 case Intrinsic::smin: {
7544 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7545 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7546 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SMIN, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7547 return;
7548 }
7549 case Intrinsic::umax: {
7550 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7551 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7552 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UMAX, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7553 return;
7554 }
7555 case Intrinsic::umin: {
7556 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7557 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7558 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UMIN, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7559 return;
7560 }
7561 case Intrinsic::abs: {
7562 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7563 bool IntMinIsPoison = cast<ConstantInt>(Val: I.getArgOperand(i: 1))->isOne();
7564 unsigned Opc = IntMinIsPoison ? ISD::ABS_MIN_POISON : ISD::ABS;
7565 setValue(V: &I, NewN: DAG.getNode(Opcode: Opc, DL: sdl, VT: Op1.getValueType(), Operand: Op1));
7566 return;
7567 }
7568 case Intrinsic::scmp: {
7569 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7570 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7571 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7572 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SCMP, DL: sdl, VT: DestVT, N1: Op1, N2: Op2));
7573 break;
7574 }
7575 case Intrinsic::ucmp: {
7576 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7577 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7578 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7579 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UCMP, DL: sdl, VT: DestVT, N1: Op1, N2: Op2));
7580 break;
7581 }
7582 case Intrinsic::stackaddress:
7583 case Intrinsic::stacksave: {
7584 unsigned SDOpcode = Intrinsic == Intrinsic::stackaddress ? ISD::STACKADDRESS
7585 : ISD::STACKSAVE;
7586 SDValue Op = getRoot();
7587 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7588 Res = DAG.getNode(Opcode: SDOpcode, DL: sdl, VTList: DAG.getVTList(VT1: VT, VT2: MVT::Other), N: Op);
7589 setValue(V: &I, NewN: Res);
7590 DAG.setRoot(Res.getValue(R: 1));
7591 return;
7592 }
7593 case Intrinsic::stackrestore:
7594 Res = getValue(V: I.getArgOperand(i: 0));
7595 DAG.setRoot(DAG.getNode(Opcode: ISD::STACKRESTORE, DL: sdl, VT: MVT::Other, N1: getRoot(), N2: Res));
7596 return;
7597 case Intrinsic::get_dynamic_area_offset: {
7598 SDValue Op = getRoot();
7599 EVT ResTy = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7600 Res = DAG.getNode(Opcode: ISD::GET_DYNAMIC_AREA_OFFSET, DL: sdl, VTList: DAG.getVTList(VT: ResTy),
7601 N: Op);
7602 DAG.setRoot(Op);
7603 setValue(V: &I, NewN: Res);
7604 return;
7605 }
7606 case Intrinsic::stackguard: {
7607 MachineFunction &MF = DAG.getMachineFunction();
7608 const Module &M = *MF.getFunction().getParent();
7609 EVT PtrTy = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7610 SDValue Chain = getRoot();
7611 if (TLI.useLoadStackGuardNode(M)) {
7612 Res = getLoadStackGuard(DAG, DL: sdl, Chain);
7613 Res = DAG.getPtrExtOrTrunc(Op: Res, DL: sdl, VT: PtrTy);
7614 } else {
7615 const Value *Global = TLI.getSDagStackGuard(M, Libcalls: DAG.getLibcalls());
7616 if (!Global) {
7617 LLVMContext &Ctx = *DAG.getContext();
7618 Ctx.diagnose(DI: DiagnosticInfoGeneric("unable to lower stackguard"));
7619 setValue(V: &I, NewN: DAG.getPOISON(VT: PtrTy));
7620 return;
7621 }
7622
7623 Align Align = DAG.getDataLayout().getPrefTypeAlign(Ty: Global->getType());
7624 Res = DAG.getLoad(VT: PtrTy, dl: sdl, Chain, Ptr: getValue(V: Global),
7625 PtrInfo: MachinePointerInfo(Global, 0), Alignment: Align,
7626 MMOFlags: MachineMemOperand::MOVolatile);
7627 }
7628 if (TLI.useStackGuardXorFP())
7629 Res = TLI.emitStackGuardXorFP(DAG, Val: Res, DL: sdl);
7630 DAG.setRoot(Chain);
7631 setValue(V: &I, NewN: Res);
7632 return;
7633 }
7634 case Intrinsic::stackprotector: {
7635 // Emit code into the DAG to store the stack guard onto the stack.
7636 MachineFunction &MF = DAG.getMachineFunction();
7637 MachineFrameInfo &MFI = MF.getFrameInfo();
7638 const Module &M = *MF.getFunction().getParent();
7639 SDValue Src, Chain = getRoot();
7640
7641 if (TLI.useLoadStackGuardNode(M))
7642 Src = getLoadStackGuard(DAG, DL: sdl, Chain);
7643 else
7644 Src = getValue(V: I.getArgOperand(i: 0)); // The guard's value.
7645
7646 AllocaInst *Slot = cast<AllocaInst>(Val: I.getArgOperand(i: 1));
7647
7648 int FI = FuncInfo.StaticAllocaMap[Slot];
7649 MFI.setStackProtectorIndex(FI);
7650 EVT PtrTy = TLI.getFrameIndexTy(DL: DAG.getDataLayout());
7651
7652 SDValue FIN = DAG.getFrameIndex(FI, VT: PtrTy);
7653
7654 // Store the stack protector onto the stack.
7655 Res = DAG.getStore(
7656 Chain, dl: sdl, Val: Src, Ptr: FIN,
7657 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI),
7658 Alignment: MaybeAlign(), MMOFlags: MachineMemOperand::MOVolatile);
7659 setValue(V: &I, NewN: Res);
7660 DAG.setRoot(Res);
7661 return;
7662 }
7663 case Intrinsic::objectsize:
7664 llvm_unreachable("llvm.objectsize.* should have been lowered already");
7665
7666 case Intrinsic::is_constant:
7667 llvm_unreachable("llvm.is.constant.* should have been lowered already");
7668
7669 case Intrinsic::annotation:
7670 case Intrinsic::ptr_annotation:
7671 case Intrinsic::launder_invariant_group:
7672 case Intrinsic::strip_invariant_group:
7673 // Drop the intrinsic, but forward the value
7674 setValue(V: &I, NewN: getValue(V: I.getOperand(i_nocapture: 0)));
7675 return;
7676
7677 case Intrinsic::type_test:
7678 case Intrinsic::public_type_test:
7679 reportFatalUsageError(reason: "llvm.type.test intrinsic must be lowered by the "
7680 "LowerTypeTests pass before code generation");
7681 return;
7682
7683 case Intrinsic::assume:
7684 case Intrinsic::experimental_noalias_scope_decl:
7685 case Intrinsic::var_annotation:
7686 case Intrinsic::sideeffect:
7687 // Discard annotate attributes, noalias scope declarations, assumptions, and
7688 // artificial side-effects.
7689 return;
7690
7691 case Intrinsic::codeview_annotation: {
7692 // Emit a label associated with this metadata.
7693 MachineFunction &MF = DAG.getMachineFunction();
7694 MCSymbol *Label = MF.getContext().createTempSymbol(Name: "annotation", AlwaysAddSuffix: true);
7695 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 0))->getMetadata();
7696 MF.addCodeViewAnnotation(Label, MD: cast<MDNode>(Val: MD));
7697 Res = DAG.getLabelNode(Opcode: ISD::ANNOTATION_LABEL, dl: sdl, Root: getRoot(), Label);
7698 DAG.setRoot(Res);
7699 return;
7700 }
7701
7702 case Intrinsic::init_trampoline: {
7703 const Function *F = cast<Function>(Val: I.getArgOperand(i: 1)->stripPointerCasts());
7704
7705 SDValue Ops[6];
7706 Ops[0] = getRoot();
7707 Ops[1] = getValue(V: I.getArgOperand(i: 0));
7708 Ops[2] = getValue(V: I.getArgOperand(i: 1));
7709 Ops[3] = getValue(V: I.getArgOperand(i: 2));
7710 Ops[4] = DAG.getSrcValue(v: I.getArgOperand(i: 0));
7711 Ops[5] = DAG.getSrcValue(v: F);
7712
7713 Res = DAG.getNode(Opcode: ISD::INIT_TRAMPOLINE, DL: sdl, VT: MVT::Other, Ops);
7714
7715 DAG.setRoot(Res);
7716 return;
7717 }
7718 case Intrinsic::adjust_trampoline:
7719 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::ADJUST_TRAMPOLINE, DL: sdl,
7720 VT: TLI.getPointerTy(DL: DAG.getDataLayout()),
7721 Operand: getValue(V: I.getArgOperand(i: 0))));
7722 return;
7723 case Intrinsic::gcroot: {
7724 assert(DAG.getMachineFunction().getFunction().hasGC() &&
7725 "only valid in functions with gc specified, enforced by Verifier");
7726 assert(GFI && "implied by previous");
7727 const Value *Alloca = I.getArgOperand(i: 0)->stripPointerCasts();
7728 const Constant *TypeMap = cast<Constant>(Val: I.getArgOperand(i: 1));
7729
7730 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(Val: getValue(V: Alloca).getNode());
7731 GFI->addStackRoot(Num: FI->getIndex(), Metadata: TypeMap);
7732 return;
7733 }
7734 case Intrinsic::gcread:
7735 case Intrinsic::gcwrite:
7736 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7737 case Intrinsic::get_rounding:
7738 Res = DAG.getNode(Opcode: ISD::GET_ROUNDING, DL: sdl, ResultTys: {MVT::i32, MVT::Other}, Ops: getRoot());
7739 setValue(V: &I, NewN: Res);
7740 DAG.setRoot(Res.getValue(R: 1));
7741 return;
7742
7743 case Intrinsic::expect:
7744 case Intrinsic::expect_with_probability:
7745 // Just replace __builtin_expect(exp, c) and
7746 // __builtin_expect_with_probability(exp, c, p) with EXP.
7747 setValue(V: &I, NewN: getValue(V: I.getArgOperand(i: 0)));
7748 return;
7749
7750 case Intrinsic::ubsantrap:
7751 case Intrinsic::debugtrap:
7752 case Intrinsic::trap: {
7753 StringRef TrapFuncName =
7754 I.getAttributes().getFnAttr(Kind: "trap-func-name").getValueAsString();
7755 if (TrapFuncName.empty()) {
7756 switch (Intrinsic) {
7757 case Intrinsic::trap:
7758 DAG.setRoot(DAG.getNode(Opcode: ISD::TRAP, DL: sdl, VT: MVT::Other, Operand: getRoot()));
7759 break;
7760 case Intrinsic::debugtrap:
7761 DAG.setRoot(DAG.getNode(Opcode: ISD::DEBUGTRAP, DL: sdl, VT: MVT::Other, Operand: getRoot()));
7762 break;
7763 case Intrinsic::ubsantrap:
7764 DAG.setRoot(DAG.getNode(
7765 Opcode: ISD::UBSANTRAP, DL: sdl, VT: MVT::Other, N1: getRoot(),
7766 N2: DAG.getTargetConstant(
7767 Val: cast<ConstantInt>(Val: I.getArgOperand(i: 0))->getZExtValue(), DL: sdl,
7768 VT: MVT::i32)));
7769 break;
7770 default: llvm_unreachable("unknown trap intrinsic");
7771 }
7772 DAG.addNoMergeSiteInfo(Node: DAG.getRoot().getNode(),
7773 NoMerge: I.hasFnAttr(Kind: Attribute::NoMerge));
7774 return;
7775 }
7776 TargetLowering::ArgListTy Args;
7777 if (Intrinsic == Intrinsic::ubsantrap) {
7778 Value *Arg = I.getArgOperand(i: 0);
7779 Args.emplace_back(args&: Arg, args: getValue(V: Arg));
7780 }
7781
7782 TargetLowering::CallLoweringInfo CLI(DAG);
7783 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7784 CC: CallingConv::C, ResultType: I.getType(),
7785 Target: DAG.getExternalSymbol(Sym: TrapFuncName.data(),
7786 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
7787 ArgsList: std::move(Args));
7788 CLI.NoMerge = I.hasFnAttr(Kind: Attribute::NoMerge);
7789 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7790 DAG.setRoot(Result.second);
7791 return;
7792 }
7793
7794 case Intrinsic::allow_runtime_check:
7795 case Intrinsic::allow_ubsan_check:
7796 setValue(V: &I, NewN: getValue(V: ConstantInt::getTrue(Ty: I.getType())));
7797 return;
7798
7799 case Intrinsic::uadd_with_overflow:
7800 case Intrinsic::sadd_with_overflow:
7801 case Intrinsic::usub_with_overflow:
7802 case Intrinsic::ssub_with_overflow:
7803 case Intrinsic::umul_with_overflow:
7804 case Intrinsic::smul_with_overflow: {
7805 ISD::NodeType Op;
7806 switch (Intrinsic) {
7807 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7808 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7809 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7810 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7811 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7812 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7813 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7814 }
7815 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7816 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7817
7818 EVT ResultVT = Op1.getValueType();
7819 EVT OverflowVT = ResultVT.changeElementType(Context&: *Context, EltVT: MVT::i1);
7820
7821 SDVTList VTs = DAG.getVTList(VT1: ResultVT, VT2: OverflowVT);
7822 setValue(V: &I, NewN: DAG.getNode(Opcode: Op, DL: sdl, VTList: VTs, N1: Op1, N2: Op2));
7823 return;
7824 }
7825 case Intrinsic::prefetch: {
7826 SDValue Ops[5];
7827 unsigned rw = cast<ConstantInt>(Val: I.getArgOperand(i: 1))->getZExtValue();
7828 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7829 Ops[0] = DAG.getRoot();
7830 Ops[1] = getValue(V: I.getArgOperand(i: 0));
7831 Ops[2] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 1)), DL: sdl,
7832 VT: MVT::i32);
7833 Ops[3] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 2)), DL: sdl,
7834 VT: MVT::i32);
7835 Ops[4] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 3)), DL: sdl,
7836 VT: MVT::i32);
7837 SDValue Result = DAG.getMemIntrinsicNode(
7838 Opcode: ISD::PREFETCH, dl: sdl, VTList: DAG.getVTList(VT: MVT::Other), Ops,
7839 MemVT: EVT::getIntegerVT(Context&: *Context, BitWidth: 8), PtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
7840 /* align */ Alignment: std::nullopt, Flags);
7841
7842 // Chain the prefetch in parallel with any pending loads, to stay out of
7843 // the way of later optimizations.
7844 PendingLoads.push_back(Elt: Result);
7845 Result = getRoot();
7846 DAG.setRoot(Result);
7847 return;
7848 }
7849 case Intrinsic::lifetime_start:
7850 case Intrinsic::lifetime_end: {
7851 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7852 // Stack coloring is not enabled in O0, discard region information.
7853 if (TM.getOptLevel() == CodeGenOptLevel::None)
7854 return;
7855
7856 const AllocaInst *LifetimeObject = dyn_cast<AllocaInst>(Val: I.getArgOperand(i: 0));
7857 if (!LifetimeObject)
7858 return;
7859
7860 // First check that the Alloca is static, otherwise it won't have a
7861 // valid frame index.
7862 auto SI = FuncInfo.StaticAllocaMap.find(Val: LifetimeObject);
7863 if (SI == FuncInfo.StaticAllocaMap.end())
7864 return;
7865
7866 const int FrameIndex = SI->second;
7867 Res = DAG.getLifetimeNode(IsStart, dl: sdl, Chain: getRoot(), FrameIndex);
7868 DAG.setRoot(Res);
7869 return;
7870 }
7871 case Intrinsic::pseudoprobe: {
7872 auto Guid = cast<ConstantInt>(Val: I.getArgOperand(i: 0))->getZExtValue();
7873 auto Index = cast<ConstantInt>(Val: I.getArgOperand(i: 1))->getZExtValue();
7874 auto Attr = cast<ConstantInt>(Val: I.getArgOperand(i: 2))->getZExtValue();
7875 Res = DAG.getPseudoProbeNode(Dl: sdl, Chain: getRoot(), Guid, Index, Attr);
7876 DAG.setRoot(Res);
7877 return;
7878 }
7879 case Intrinsic::invariant_start:
7880 // Discard region information.
7881 setValue(V: &I,
7882 NewN: DAG.getUNDEF(VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType())));
7883 return;
7884 case Intrinsic::invariant_end:
7885 // Discard region information.
7886 return;
7887 case Intrinsic::clear_cache: {
7888 SDValue InputChain = DAG.getRoot();
7889 SDValue StartVal = getValue(V: I.getArgOperand(i: 0));
7890 SDValue EndVal = getValue(V: I.getArgOperand(i: 1));
7891 Res = DAG.getNode(Opcode: ISD::CLEAR_CACHE, DL: sdl, VTList: DAG.getVTList(VT: MVT::Other),
7892 Ops: {InputChain, StartVal, EndVal});
7893 setValue(V: &I, NewN: Res);
7894 DAG.setRoot(Res);
7895 return;
7896 }
7897 case Intrinsic::donothing:
7898 case Intrinsic::seh_try_begin:
7899 case Intrinsic::seh_scope_begin:
7900 case Intrinsic::seh_try_end:
7901 case Intrinsic::seh_scope_end:
7902 // ignore
7903 return;
7904 case Intrinsic::experimental_stackmap:
7905 visitStackmap(I);
7906 return;
7907 case Intrinsic::experimental_patchpoint_void:
7908 case Intrinsic::experimental_patchpoint:
7909 visitPatchpoint(CB: I);
7910 return;
7911 case Intrinsic::experimental_gc_statepoint:
7912 LowerStatepoint(I: cast<GCStatepointInst>(Val: I));
7913 return;
7914 case Intrinsic::experimental_gc_result:
7915 visitGCResult(I: cast<GCResultInst>(Val: I));
7916 return;
7917 case Intrinsic::experimental_gc_relocate:
7918 visitGCRelocate(Relocate: cast<GCRelocateInst>(Val: I));
7919 return;
7920 case Intrinsic::instrprof_cover:
7921 llvm_unreachable("instrprof failed to lower a cover");
7922 case Intrinsic::instrprof_increment:
7923 llvm_unreachable("instrprof failed to lower an increment");
7924 case Intrinsic::instrprof_timestamp:
7925 llvm_unreachable("instrprof failed to lower a timestamp");
7926 case Intrinsic::instrprof_value_profile:
7927 llvm_unreachable("instrprof failed to lower a value profiling call");
7928 case Intrinsic::instrprof_mcdc_parameters:
7929 llvm_unreachable("instrprof failed to lower mcdc parameters");
7930 case Intrinsic::instrprof_mcdc_tvbitmap_update:
7931 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7932 case Intrinsic::localescape: {
7933 MachineFunction &MF = DAG.getMachineFunction();
7934 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7935
7936 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7937 // is the same on all targets.
7938 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7939 Value *Arg = I.getArgOperand(i: Idx)->stripPointerCasts();
7940 if (isa<ConstantPointerNull>(Val: Arg))
7941 continue; // Skip null pointers. They represent a hole in index space.
7942 AllocaInst *Slot = cast<AllocaInst>(Val: Arg);
7943 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7944 "can only escape static allocas");
7945 int FI = FuncInfo.StaticAllocaMap[Slot];
7946 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7947 FuncName: GlobalValue::dropLLVMManglingEscape(Name: MF.getName()), Idx);
7948 BuildMI(BB&: *FuncInfo.MBB, I: FuncInfo.InsertPt, MIMD: dl,
7949 MCID: TII->get(Opcode: TargetOpcode::LOCAL_ESCAPE))
7950 .addSym(Sym: FrameAllocSym)
7951 .addFrameIndex(Idx: FI);
7952 }
7953
7954 return;
7955 }
7956
7957 case Intrinsic::localrecover: {
7958 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7959 MachineFunction &MF = DAG.getMachineFunction();
7960
7961 // Get the symbol that defines the frame offset.
7962 auto *Fn = cast<Function>(Val: I.getArgOperand(i: 0)->stripPointerCasts());
7963 auto *Idx = cast<ConstantInt>(Val: I.getArgOperand(i: 2));
7964 unsigned IdxVal =
7965 unsigned(Idx->getLimitedValue(Limit: std::numeric_limits<int>::max()));
7966 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7967 FuncName: GlobalValue::dropLLVMManglingEscape(Name: Fn->getName()), Idx: IdxVal);
7968
7969 Value *FP = I.getArgOperand(i: 1);
7970 SDValue FPVal = getValue(V: FP);
7971 EVT PtrVT = FPVal.getValueType();
7972
7973 // Create a MCSymbol for the label to avoid any target lowering
7974 // that would make this PC relative.
7975 SDValue OffsetSym = DAG.getMCSymbol(Sym: FrameAllocSym, VT: PtrVT);
7976 SDValue OffsetVal =
7977 DAG.getNode(Opcode: ISD::LOCAL_RECOVER, DL: sdl, VT: PtrVT, Operand: OffsetSym);
7978
7979 // Add the offset to the FP.
7980 SDValue Add = DAG.getMemBasePlusOffset(Base: FPVal, Offset: OffsetVal, DL: sdl);
7981 setValue(V: &I, NewN: Add);
7982
7983 return;
7984 }
7985
7986 case Intrinsic::fake_use: {
7987 Value *V = I.getArgOperand(i: 0);
7988 SDValue Ops[2];
7989 // For Values not declared or previously used in this basic block, the
7990 // NodeMap will not have an entry, and `getValue` will assert if V has no
7991 // valid register value.
7992 auto FakeUseValue = [&]() -> SDValue {
7993 SDValue &N = NodeMap[V];
7994 if (N.getNode())
7995 return N;
7996
7997 // If there's a virtual register allocated and initialized for this
7998 // value, use it.
7999 if (SDValue copyFromReg = getCopyFromRegs(V, Ty: V->getType()))
8000 return copyFromReg;
8001 // FIXME: Do we want to preserve constants? It seems pointless.
8002 if (isa<Constant>(Val: V))
8003 return getValue(V);
8004 return SDValue();
8005 }();
8006 if (!FakeUseValue || FakeUseValue.isUndef())
8007 return;
8008 Ops[0] = getRoot();
8009 Ops[1] = FakeUseValue;
8010 // Also, do not translate a fake use with an undef operand, or any other
8011 // empty SDValues.
8012 if (!Ops[1] || Ops[1].isUndef())
8013 return;
8014 DAG.setRoot(DAG.getNode(Opcode: ISD::FAKE_USE, DL: sdl, VT: MVT::Other, Ops));
8015 return;
8016 }
8017
8018 case Intrinsic::reloc_none: {
8019 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 0))->getMetadata();
8020 StringRef SymbolName = cast<MDString>(Val: MD)->getString();
8021 SDValue Ops[2] = {
8022 getRoot(),
8023 DAG.getTargetExternalSymbol(
8024 Sym: SymbolName.data(), VT: TLI.getProgramPointerTy(DL: DAG.getDataLayout()))};
8025 DAG.setRoot(DAG.getNode(Opcode: ISD::RELOC_NONE, DL: sdl, VT: MVT::Other, Ops));
8026 return;
8027 }
8028
8029 case Intrinsic::cond_loop: {
8030 SDValue InputChain = DAG.getRoot();
8031 SDValue P = getValue(V: I.getArgOperand(i: 0));
8032 Res = DAG.getNode(Opcode: ISD::COND_LOOP, DL: sdl, VTList: DAG.getVTList(VT: MVT::Other),
8033 Ops: {InputChain, P});
8034 setValue(V: &I, NewN: Res);
8035 DAG.setRoot(Res);
8036 return;
8037 }
8038
8039 case Intrinsic::eh_exceptionpointer:
8040 case Intrinsic::eh_exceptioncode: {
8041 // Get the exception pointer vreg, copy from it, and resize it to fit.
8042 const auto *CPI = cast<CatchPadInst>(Val: I.getArgOperand(i: 0));
8043 MVT PtrVT = TLI.getPointerTy(DL: DAG.getDataLayout());
8044 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(VT: PtrVT);
8045 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, RC: PtrRC);
8046 SDValue N = DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl: sdl, Reg: VReg, VT: PtrVT);
8047 if (Intrinsic == Intrinsic::eh_exceptioncode)
8048 N = DAG.getZExtOrTrunc(Op: N, DL: sdl, VT: MVT::i32);
8049 setValue(V: &I, NewN: N);
8050 return;
8051 }
8052 case Intrinsic::xray_customevent: {
8053 // Here we want to make sure that the intrinsic behaves as if it has a
8054 // specific calling convention.
8055 const auto &Triple = DAG.getTarget().getTargetTriple();
8056 if (!Triple.isAArch64(PointerWidth: 64) && Triple.getArch() != Triple::x86_64 &&
8057 Triple.getArch() != Triple::hexagon)
8058 return;
8059
8060 SmallVector<SDValue, 8> Ops;
8061
8062 // We want to say that we always want the arguments in registers.
8063 SDValue LogEntryVal = getValue(V: I.getArgOperand(i: 0));
8064 SDValue StrSizeVal = getValue(V: I.getArgOperand(i: 1));
8065 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
8066 SDValue Chain = getRoot();
8067 Ops.push_back(Elt: LogEntryVal);
8068 Ops.push_back(Elt: StrSizeVal);
8069 Ops.push_back(Elt: Chain);
8070
8071 // We need to enforce the calling convention for the callsite, so that
8072 // argument ordering is enforced correctly, and that register allocation can
8073 // see that some registers may be assumed clobbered and have to preserve
8074 // them across calls to the intrinsic.
8075 MachineSDNode *MN = DAG.getMachineNode(Opcode: TargetOpcode::PATCHABLE_EVENT_CALL,
8076 dl: sdl, VTs: NodeTys, Ops);
8077 SDValue patchableNode = SDValue(MN, 0);
8078 DAG.setRoot(patchableNode);
8079 setValue(V: &I, NewN: patchableNode);
8080 return;
8081 }
8082 case Intrinsic::xray_typedevent: {
8083 // Here we want to make sure that the intrinsic behaves as if it has a
8084 // specific calling convention.
8085 const auto &Triple = DAG.getTarget().getTargetTriple();
8086 if (!Triple.isAArch64(PointerWidth: 64) && Triple.getArch() != Triple::x86_64 &&
8087 Triple.getArch() != Triple::hexagon)
8088 return;
8089
8090 SmallVector<SDValue, 8> Ops;
8091
8092 // We want to say that we always want the arguments in registers.
8093 // It's unclear to me how manipulating the selection DAG here forces callers
8094 // to provide arguments in registers instead of on the stack.
8095 SDValue LogTypeId = getValue(V: I.getArgOperand(i: 0));
8096 SDValue LogEntryVal = getValue(V: I.getArgOperand(i: 1));
8097 SDValue StrSizeVal = getValue(V: I.getArgOperand(i: 2));
8098 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
8099 SDValue Chain = getRoot();
8100 Ops.push_back(Elt: LogTypeId);
8101 Ops.push_back(Elt: LogEntryVal);
8102 Ops.push_back(Elt: StrSizeVal);
8103 Ops.push_back(Elt: Chain);
8104
8105 // We need to enforce the calling convention for the callsite, so that
8106 // argument ordering is enforced correctly, and that register allocation can
8107 // see that some registers may be assumed clobbered and have to preserve
8108 // them across calls to the intrinsic.
8109 MachineSDNode *MN = DAG.getMachineNode(
8110 Opcode: TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, dl: sdl, VTs: NodeTys, Ops);
8111 SDValue patchableNode = SDValue(MN, 0);
8112 DAG.setRoot(patchableNode);
8113 setValue(V: &I, NewN: patchableNode);
8114 return;
8115 }
8116 case Intrinsic::experimental_deoptimize:
8117 LowerDeoptimizeCall(CI: &I);
8118 return;
8119 case Intrinsic::stepvector:
8120 visitStepVector(I);
8121 return;
8122 case Intrinsic::vector_reduce_fadd:
8123 case Intrinsic::vector_reduce_fmul:
8124 case Intrinsic::vector_reduce_add:
8125 case Intrinsic::vector_reduce_mul:
8126 case Intrinsic::vector_reduce_and:
8127 case Intrinsic::vector_reduce_or:
8128 case Intrinsic::vector_reduce_xor:
8129 case Intrinsic::vector_reduce_smax:
8130 case Intrinsic::vector_reduce_smin:
8131 case Intrinsic::vector_reduce_umax:
8132 case Intrinsic::vector_reduce_umin:
8133 case Intrinsic::vector_reduce_fmax:
8134 case Intrinsic::vector_reduce_fmin:
8135 case Intrinsic::vector_reduce_fmaximum:
8136 case Intrinsic::vector_reduce_fminimum:
8137 visitVectorReduce(I, Intrinsic);
8138 return;
8139
8140 case Intrinsic::icall_branch_funnel: {
8141 SmallVector<SDValue, 16> Ops;
8142 Ops.push_back(Elt: getValue(V: I.getArgOperand(i: 0)));
8143
8144 int64_t Offset;
8145 auto *Base = dyn_cast<GlobalObject>(Val: GetPointerBaseWithConstantOffset(
8146 Ptr: I.getArgOperand(i: 1), Offset, DL: DAG.getDataLayout()));
8147 if (!Base)
8148 report_fatal_error(
8149 reason: "llvm.icall.branch.funnel operand must be a GlobalValue");
8150 Ops.push_back(Elt: DAG.getTargetGlobalAddress(GV: Base, DL: sdl, VT: MVT::i64, offset: 0));
8151
8152 struct BranchFunnelTarget {
8153 int64_t Offset;
8154 SDValue Target;
8155 };
8156 SmallVector<BranchFunnelTarget, 8> Targets;
8157
8158 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
8159 auto *ElemBase = dyn_cast<GlobalObject>(Val: GetPointerBaseWithConstantOffset(
8160 Ptr: I.getArgOperand(i: Op), Offset, DL: DAG.getDataLayout()));
8161 if (ElemBase != Base)
8162 report_fatal_error(reason: "all llvm.icall.branch.funnel operands must refer "
8163 "to the same GlobalValue");
8164
8165 SDValue Val = getValue(V: I.getArgOperand(i: Op + 1));
8166 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
8167 if (!GA)
8168 report_fatal_error(
8169 reason: "llvm.icall.branch.funnel operand must be a GlobalValue");
8170 Targets.push_back(Elt: {.Offset: Offset, .Target: DAG.getTargetGlobalAddress(
8171 GV: GA->getGlobal(), DL: sdl, VT: Val.getValueType(),
8172 offset: GA->getOffset())});
8173 }
8174 llvm::sort(C&: Targets,
8175 Comp: [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
8176 return T1.Offset < T2.Offset;
8177 });
8178
8179 for (auto &T : Targets) {
8180 Ops.push_back(Elt: DAG.getTargetConstant(Val: T.Offset, DL: sdl, VT: MVT::i32));
8181 Ops.push_back(Elt: T.Target);
8182 }
8183
8184 Ops.push_back(Elt: DAG.getRoot()); // Chain
8185 SDValue N(DAG.getMachineNode(Opcode: TargetOpcode::ICALL_BRANCH_FUNNEL, dl: sdl,
8186 VT: MVT::Other, Ops),
8187 0);
8188 DAG.setRoot(N);
8189 setValue(V: &I, NewN: N);
8190 HasTailCall = true;
8191 return;
8192 }
8193
8194 case Intrinsic::wasm_landingpad_index:
8195 // Information this intrinsic contained has been transferred to
8196 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
8197 // delete it now.
8198 return;
8199
8200 case Intrinsic::aarch64_settag:
8201 case Intrinsic::aarch64_settag_zero: {
8202 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8203 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
8204 SDValue Val = TSI.EmitTargetCodeForSetTag(
8205 DAG, dl: sdl, Chain: getRoot(), Addr: getValue(V: I.getArgOperand(i: 0)),
8206 Size: getValue(V: I.getArgOperand(i: 1)), DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
8207 ZeroData: ZeroMemory);
8208 DAG.setRoot(Val);
8209 setValue(V: &I, NewN: Val);
8210 return;
8211 }
8212 case Intrinsic::amdgcn_cs_chain: {
8213 // At this point we don't care if it's amdgpu_cs_chain or
8214 // amdgpu_cs_chain_preserve.
8215 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
8216
8217 Type *RetTy = I.getType();
8218 assert(RetTy->isVoidTy() && "Should not return");
8219
8220 SDValue Callee = getValue(V: I.getOperand(i_nocapture: 0));
8221
8222 // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8223 // We'll also tack the value of the EXEC mask at the end.
8224 TargetLowering::ArgListTy Args;
8225 Args.reserve(n: 3);
8226
8227 for (unsigned Idx : {2, 3, 1}) {
8228 TargetLowering::ArgListEntry Arg(getValue(V: I.getOperand(i_nocapture: Idx)),
8229 I.getOperand(i_nocapture: Idx)->getType());
8230 Arg.setAttributes(Call: &I, ArgIdx: Idx);
8231 Args.push_back(x: Arg);
8232 }
8233
8234 assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8235 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8236 Args[2].IsInReg = true; // EXEC should be inreg
8237
8238 // Forward the flags and any additional arguments.
8239 for (unsigned Idx = 4; Idx < I.arg_size(); ++Idx) {
8240 TargetLowering::ArgListEntry Arg(getValue(V: I.getOperand(i_nocapture: Idx)),
8241 I.getOperand(i_nocapture: Idx)->getType());
8242 Arg.setAttributes(Call: &I, ArgIdx: Idx);
8243 Args.push_back(x: Arg);
8244 }
8245
8246 TargetLowering::CallLoweringInfo CLI(DAG);
8247 CLI.setDebugLoc(getCurSDLoc())
8248 .setChain(getRoot())
8249 .setCallee(CC, ResultType: RetTy, Target: Callee, ArgsList: std::move(Args))
8250 .setNoReturn(true)
8251 .setTailCall(true)
8252 .setConvergent(I.isConvergent());
8253 CLI.CB = &I;
8254 std::pair<SDValue, SDValue> Result =
8255 lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8256 (void)Result;
8257 assert(!Result.first.getNode() && !Result.second.getNode() &&
8258 "Should've lowered as tail call");
8259
8260 HasTailCall = true;
8261 return;
8262 }
8263 case Intrinsic::amdgcn_call_whole_wave: {
8264 TargetLowering::ArgListTy Args;
8265 bool isTailCall = I.isTailCall();
8266
8267 // The first argument is the callee. Skip it when assembling the call args.
8268 for (unsigned Idx = 1; Idx < I.arg_size(); ++Idx) {
8269 TargetLowering::ArgListEntry Arg(getValue(V: I.getArgOperand(i: Idx)),
8270 I.getArgOperand(i: Idx)->getType());
8271 Arg.setAttributes(Call: &I, ArgIdx: Idx);
8272
8273 // If we have an explicit sret argument that is an Instruction, (i.e., it
8274 // might point to function-local memory), we can't meaningfully tail-call.
8275 if (Arg.IsSRet && isa<Instruction>(Val: I.getArgOperand(i: Idx)))
8276 isTailCall = false;
8277
8278 Args.push_back(x: Arg);
8279 }
8280
8281 SDValue ConvControlToken;
8282 if (auto Bundle = I.getOperandBundle(ID: LLVMContext::OB_convergencectrl)) {
8283 auto *Token = Bundle->Inputs[0].get();
8284 ConvControlToken = getValue(V: Token);
8285 }
8286
8287 TargetLowering::CallLoweringInfo CLI(DAG);
8288 CLI.setDebugLoc(getCurSDLoc())
8289 .setChain(getRoot())
8290 .setCallee(CC: CallingConv::AMDGPU_Gfx_WholeWave, ResultType: I.getType(),
8291 Target: getValue(V: I.getArgOperand(i: 0)), ArgsList: std::move(Args))
8292 .setTailCall(isTailCall && canTailCall(CB: I))
8293 .setIsPreallocated(
8294 I.countOperandBundlesOfType(ID: LLVMContext::OB_preallocated) != 0)
8295 .setConvergent(I.isConvergent())
8296 .setConvergenceControlToken(ConvControlToken);
8297 CLI.CB = &I;
8298
8299 std::pair<SDValue, SDValue> Result =
8300 lowerInvokable(CLI, /*EHPadBB=*/nullptr);
8301
8302 if (Result.first.getNode())
8303 setValue(V: &I, NewN: Result.first);
8304 return;
8305 }
8306 case Intrinsic::ptrmask: {
8307 SDValue Ptr = getValue(V: I.getOperand(i_nocapture: 0));
8308 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 1));
8309
8310 // On arm64_32, pointers are 32 bits when stored in memory, but
8311 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to
8312 // match the index type, but the pointer is 64 bits, so the mask must be
8313 // zero-extended up to 64 bits to match the pointer.
8314 EVT PtrVT =
8315 TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i_nocapture: 0)->getType());
8316 EVT MemVT =
8317 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i_nocapture: 0)->getType());
8318 assert(PtrVT == Ptr.getValueType());
8319 if (Mask.getValueType().getFixedSizeInBits() < MemVT.getFixedSizeInBits()) {
8320 // For AMDGPU buffer descriptors the mask is 48 bits, but the pointer is
8321 // 128-bit, so we have to pad the mask with ones for unused bits.
8322 auto HighOnes = DAG.getNode(
8323 Opcode: ISD::SHL, DL: sdl, VT: PtrVT, N1: DAG.getAllOnesConstant(DL: sdl, VT: PtrVT),
8324 N2: DAG.getShiftAmountConstant(Val: Mask.getValueType().getFixedSizeInBits(),
8325 VT: PtrVT, DL: sdl));
8326 Mask = DAG.getNode(Opcode: ISD::OR, DL: sdl, VT: PtrVT,
8327 N1: DAG.getZExtOrTrunc(Op: Mask, DL: sdl, VT: PtrVT), N2: HighOnes);
8328 } else if (Mask.getValueType() != PtrVT)
8329 Mask = DAG.getPtrExtOrTrunc(Op: Mask, DL: sdl, VT: PtrVT);
8330
8331 assert(Mask.getValueType() == PtrVT);
8332 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::AND, DL: sdl, VT: PtrVT, N1: Ptr, N2: Mask));
8333 return;
8334 }
8335 case Intrinsic::threadlocal_address: {
8336 setValue(V: &I, NewN: getValue(V: I.getOperand(i_nocapture: 0)));
8337 return;
8338 }
8339 case Intrinsic::get_active_lane_mask: {
8340 EVT CCVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8341 SDValue Index = getValue(V: I.getOperand(i_nocapture: 0));
8342 SDValue TripCount = getValue(V: I.getOperand(i_nocapture: 1));
8343 EVT ElementVT = Index.getValueType();
8344
8345 if (!TLI.shouldExpandGetActiveLaneMask(VT: CCVT, OpVT: ElementVT)) {
8346 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::GET_ACTIVE_LANE_MASK, DL: sdl, VT: CCVT, N1: Index,
8347 N2: TripCount));
8348 return;
8349 }
8350
8351 EVT VecTy = EVT::getVectorVT(Context&: *DAG.getContext(), VT: ElementVT,
8352 EC: CCVT.getVectorElementCount());
8353
8354 SDValue VectorIndex = DAG.getSplat(VT: VecTy, DL: sdl, Op: Index);
8355 SDValue VectorTripCount = DAG.getSplat(VT: VecTy, DL: sdl, Op: TripCount);
8356 SDValue VectorStep = DAG.getStepVector(DL: sdl, ResVT: VecTy);
8357 SDValue VectorInduction = DAG.getNode(
8358 Opcode: ISD::UADDSAT, DL: sdl, VT: VecTy, N1: VectorIndex, N2: VectorStep);
8359 SDValue SetCC = DAG.getSetCC(DL: sdl, VT: CCVT, LHS: VectorInduction,
8360 RHS: VectorTripCount, Cond: ISD::CondCode::SETULT);
8361 setValue(V: &I, NewN: SetCC);
8362 return;
8363 }
8364 case Intrinsic::experimental_get_vector_length: {
8365 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8366 "Expected positive VF");
8367 unsigned VF = cast<ConstantInt>(Val: I.getOperand(i_nocapture: 1))->getZExtValue();
8368 bool IsScalable = cast<ConstantInt>(Val: I.getOperand(i_nocapture: 2))->isOne();
8369
8370 SDValue Count = getValue(V: I.getOperand(i_nocapture: 0));
8371 EVT CountVT = Count.getValueType();
8372
8373 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8374 visitTargetIntrinsic(I, Intrinsic);
8375 return;
8376 }
8377
8378 // Expand to a umin between the trip count and the maximum elements the type
8379 // can hold.
8380 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8381
8382 // Extend the trip count to at least the result VT.
8383 if (CountVT.bitsLT(VT)) {
8384 Count = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: sdl, VT, Operand: Count);
8385 CountVT = VT;
8386 }
8387
8388 SDValue MaxEVL = DAG.getElementCount(DL: sdl, VT: CountVT,
8389 EC: ElementCount::get(MinVal: VF, Scalable: IsScalable));
8390
8391 SDValue UMin = DAG.getNode(Opcode: ISD::UMIN, DL: sdl, VT: CountVT, N1: Count, N2: MaxEVL);
8392 // Clip to the result type if needed.
8393 SDValue Trunc = DAG.getNode(Opcode: ISD::TRUNCATE, DL: sdl, VT, Operand: UMin);
8394
8395 setValue(V: &I, NewN: Trunc);
8396 return;
8397 }
8398 case Intrinsic::vector_partial_reduce_add: {
8399 SDValue Acc = getValue(V: I.getOperand(i_nocapture: 0));
8400 SDValue Input = getValue(V: I.getOperand(i_nocapture: 1));
8401 setValue(V: &I,
8402 NewN: DAG.getNode(Opcode: ISD::PARTIAL_REDUCE_UMLA, DL: sdl, VT: Acc.getValueType(), N1: Acc,
8403 N2: Input, N3: DAG.getConstant(Val: 1, DL: sdl, VT: Input.getValueType())));
8404 return;
8405 }
8406 case Intrinsic::vector_partial_reduce_fadd: {
8407 SDValue Acc = getValue(V: I.getOperand(i_nocapture: 0));
8408 SDValue Input = getValue(V: I.getOperand(i_nocapture: 1));
8409 setValue(V: &I, NewN: DAG.getNode(
8410 Opcode: ISD::PARTIAL_REDUCE_FMLA, DL: sdl, VT: Acc.getValueType(), N1: Acc,
8411 N2: Input, N3: DAG.getConstantFP(Val: 1.0, DL: sdl, VT: Input.getValueType())));
8412 return;
8413 }
8414 case Intrinsic::experimental_cttz_elts: {
8415 SDValue Op = getValue(V: I.getOperand(i_nocapture: 0));
8416 EVT OpVT = Op.getValueType();
8417 EVT RetTy = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8418 bool ZeroIsPoison =
8419 !cast<ConstantSDNode>(Val: getValue(V: I.getOperand(i_nocapture: 1)))->isZero();
8420 if (OpVT.getVectorElementType() != MVT::i1) {
8421 // Compare the input vector elements to zero & use to count trailing
8422 // zeros.
8423 SDValue AllZero = DAG.getConstant(Val: 0, DL: sdl, VT: OpVT);
8424 EVT I1OpVT = OpVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: MVT::i1);
8425 Op = DAG.getSetCC(DL: sdl, VT: I1OpVT, LHS: Op, RHS: AllZero, Cond: ISD::SETNE);
8426 }
8427 setValue(V: &I, NewN: DAG.getNode(Opcode: ZeroIsPoison ? ISD::CTTZ_ELTS_ZERO_POISON
8428 : ISD::CTTZ_ELTS,
8429 DL: sdl, VT: RetTy, Operand: Op));
8430 return;
8431 }
8432 case Intrinsic::vector_insert: {
8433 SDValue Vec = getValue(V: I.getOperand(i_nocapture: 0));
8434 SDValue SubVec = getValue(V: I.getOperand(i_nocapture: 1));
8435 SDValue Index = getValue(V: I.getOperand(i_nocapture: 2));
8436
8437 // The intrinsic's index type is i64, but the SDNode requires an index type
8438 // suitable for the target. Convert the index as required.
8439 MVT VectorIdxTy = TLI.getVectorIdxTy(DL: DAG.getDataLayout());
8440 if (Index.getValueType() != VectorIdxTy)
8441 Index = DAG.getVectorIdxConstant(Val: Index->getAsZExtVal(), DL: sdl);
8442
8443 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8444 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::INSERT_SUBVECTOR, DL: sdl, VT: ResultVT, N1: Vec, N2: SubVec,
8445 N3: Index));
8446 return;
8447 }
8448 case Intrinsic::vector_extract: {
8449 SDValue Vec = getValue(V: I.getOperand(i_nocapture: 0));
8450 SDValue Index = getValue(V: I.getOperand(i_nocapture: 1));
8451 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8452
8453 // The intrinsic's index type is i64, but the SDNode requires an index type
8454 // suitable for the target. Convert the index as required.
8455 MVT VectorIdxTy = TLI.getVectorIdxTy(DL: DAG.getDataLayout());
8456 if (Index.getValueType() != VectorIdxTy)
8457 Index = DAG.getVectorIdxConstant(Val: Index->getAsZExtVal(), DL: sdl);
8458
8459 setValue(V: &I,
8460 NewN: DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: sdl, VT: ResultVT, N1: Vec, N2: Index));
8461 return;
8462 }
8463 case Intrinsic::experimental_vector_match: {
8464 SDValue Op1 = getValue(V: I.getOperand(i_nocapture: 0));
8465 SDValue Op2 = getValue(V: I.getOperand(i_nocapture: 1));
8466 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 2));
8467 EVT Op1VT = Op1.getValueType();
8468 EVT Op2VT = Op2.getValueType();
8469 EVT ResVT = Mask.getValueType();
8470 unsigned SearchSize = Op2VT.getVectorNumElements();
8471
8472 // If the target has native support for this vector match operation, lower
8473 // the intrinsic untouched; otherwise, expand it below.
8474 if (!TLI.shouldExpandVectorMatch(VT: Op1VT, SearchSize)) {
8475 visitTargetIntrinsic(I, Intrinsic);
8476 return;
8477 }
8478
8479 SDValue Ret = DAG.getConstant(Val: 0, DL: sdl, VT: ResVT);
8480
8481 for (unsigned i = 0; i < SearchSize; ++i) {
8482 SDValue Op2Elem = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: sdl,
8483 VT: Op2VT.getVectorElementType(), N1: Op2,
8484 N2: DAG.getVectorIdxConstant(Val: i, DL: sdl));
8485 SDValue Splat = DAG.getNode(Opcode: ISD::SPLAT_VECTOR, DL: sdl, VT: Op1VT, Operand: Op2Elem);
8486 SDValue Cmp = DAG.getSetCC(DL: sdl, VT: ResVT, LHS: Op1, RHS: Splat, Cond: ISD::SETEQ);
8487 Ret = DAG.getNode(Opcode: ISD::OR, DL: sdl, VT: ResVT, N1: Ret, N2: Cmp);
8488 }
8489
8490 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::AND, DL: sdl, VT: ResVT, N1: Ret, N2: Mask));
8491 return;
8492 }
8493 case Intrinsic::vector_reverse:
8494 visitVectorReverse(I);
8495 return;
8496 case Intrinsic::vector_splice_left:
8497 case Intrinsic::vector_splice_right:
8498 visitVectorSplice(I);
8499 return;
8500 case Intrinsic::callbr_landingpad:
8501 visitCallBrLandingPad(I);
8502 return;
8503 case Intrinsic::vector_interleave2:
8504 visitVectorInterleave(I, Factor: 2);
8505 return;
8506 case Intrinsic::vector_interleave3:
8507 visitVectorInterleave(I, Factor: 3);
8508 return;
8509 case Intrinsic::vector_interleave4:
8510 visitVectorInterleave(I, Factor: 4);
8511 return;
8512 case Intrinsic::vector_interleave5:
8513 visitVectorInterleave(I, Factor: 5);
8514 return;
8515 case Intrinsic::vector_interleave6:
8516 visitVectorInterleave(I, Factor: 6);
8517 return;
8518 case Intrinsic::vector_interleave7:
8519 visitVectorInterleave(I, Factor: 7);
8520 return;
8521 case Intrinsic::vector_interleave8:
8522 visitVectorInterleave(I, Factor: 8);
8523 return;
8524 case Intrinsic::vector_deinterleave2:
8525 visitVectorDeinterleave(I, Factor: 2);
8526 return;
8527 case Intrinsic::vector_deinterleave3:
8528 visitVectorDeinterleave(I, Factor: 3);
8529 return;
8530 case Intrinsic::vector_deinterleave4:
8531 visitVectorDeinterleave(I, Factor: 4);
8532 return;
8533 case Intrinsic::vector_deinterleave5:
8534 visitVectorDeinterleave(I, Factor: 5);
8535 return;
8536 case Intrinsic::vector_deinterleave6:
8537 visitVectorDeinterleave(I, Factor: 6);
8538 return;
8539 case Intrinsic::vector_deinterleave7:
8540 visitVectorDeinterleave(I, Factor: 7);
8541 return;
8542 case Intrinsic::vector_deinterleave8:
8543 visitVectorDeinterleave(I, Factor: 8);
8544 return;
8545 case Intrinsic::experimental_vector_compress:
8546 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::VECTOR_COMPRESS, DL: sdl,
8547 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
8548 N1: getValue(V: I.getArgOperand(i: 0)),
8549 N2: getValue(V: I.getArgOperand(i: 1)),
8550 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
8551 return;
8552 case Intrinsic::experimental_convergence_anchor:
8553 case Intrinsic::experimental_convergence_entry:
8554 case Intrinsic::experimental_convergence_loop:
8555 visitConvergenceControl(I, Intrinsic);
8556 return;
8557 case Intrinsic::experimental_vector_histogram_add: {
8558 visitVectorHistogram(I, IntrinsicID: Intrinsic);
8559 return;
8560 }
8561 case Intrinsic::experimental_vector_extract_last_active: {
8562 visitVectorExtractLastActive(I, Intrinsic);
8563 return;
8564 }
8565 case Intrinsic::loop_dependence_war_mask:
8566 setValue(V: &I,
8567 NewN: DAG.getNode(Opcode: ISD::LOOP_DEPENDENCE_WAR_MASK, DL: sdl,
8568 VT: EVT::getEVT(Ty: I.getType()), N1: getValue(V: I.getOperand(i_nocapture: 0)),
8569 N2: getValue(V: I.getOperand(i_nocapture: 1)), N3: getValue(V: I.getOperand(i_nocapture: 2)),
8570 N4: DAG.getConstant(Val: 0, DL: sdl, VT: MVT::i64)));
8571 return;
8572 case Intrinsic::loop_dependence_raw_mask:
8573 setValue(V: &I,
8574 NewN: DAG.getNode(Opcode: ISD::LOOP_DEPENDENCE_RAW_MASK, DL: sdl,
8575 VT: EVT::getEVT(Ty: I.getType()), N1: getValue(V: I.getOperand(i_nocapture: 0)),
8576 N2: getValue(V: I.getOperand(i_nocapture: 1)), N3: getValue(V: I.getOperand(i_nocapture: 2)),
8577 N4: DAG.getConstant(Val: 0, DL: sdl, VT: MVT::i64)));
8578 return;
8579 case Intrinsic::masked_udiv:
8580 setValue(V: &I,
8581 NewN: DAG.getNode(Opcode: ISD::MASKED_UDIV, DL: sdl, VT: EVT::getEVT(Ty: I.getType()),
8582 N1: getValue(V: I.getOperand(i_nocapture: 0)), N2: getValue(V: I.getOperand(i_nocapture: 1)),
8583 N3: getValue(V: I.getOperand(i_nocapture: 2))));
8584 return;
8585 case Intrinsic::masked_sdiv:
8586 setValue(V: &I,
8587 NewN: DAG.getNode(Opcode: ISD::MASKED_SDIV, DL: sdl, VT: EVT::getEVT(Ty: I.getType()),
8588 N1: getValue(V: I.getOperand(i_nocapture: 0)), N2: getValue(V: I.getOperand(i_nocapture: 1)),
8589 N3: getValue(V: I.getOperand(i_nocapture: 2))));
8590 return;
8591 case Intrinsic::masked_urem:
8592 setValue(V: &I,
8593 NewN: DAG.getNode(Opcode: ISD::MASKED_UREM, DL: sdl, VT: EVT::getEVT(Ty: I.getType()),
8594 N1: getValue(V: I.getOperand(i_nocapture: 0)), N2: getValue(V: I.getOperand(i_nocapture: 1)),
8595 N3: getValue(V: I.getOperand(i_nocapture: 2))));
8596 return;
8597 case Intrinsic::masked_srem:
8598 setValue(V: &I,
8599 NewN: DAG.getNode(Opcode: ISD::MASKED_SREM, DL: sdl, VT: EVT::getEVT(Ty: I.getType()),
8600 N1: getValue(V: I.getOperand(i_nocapture: 0)), N2: getValue(V: I.getOperand(i_nocapture: 1)),
8601 N3: getValue(V: I.getOperand(i_nocapture: 2))));
8602 return;
8603 }
8604}
8605
8606void SelectionDAGBuilder::pushFPOpOutChain(SDValue Result,
8607 fp::ExceptionBehavior EB) {
8608 assert(Result.getNode()->getNumValues() == 2);
8609 SDValue OutChain = Result.getValue(R: 1);
8610 assert(OutChain.getValueType() == MVT::Other);
8611
8612 // Instead of updating the root immediately, push the produced chain to the
8613 // appropriate list, deferring the update until the root is requested. In this
8614 // case, the nodes from the lists are chained using TokenFactor, indicating
8615 // that the operations are independent.
8616 //
8617 // In particular, the root is updated before any call that might access the
8618 // floating-point environment, except for constrained intrinsics.
8619 switch (EB) {
8620 case fp::ExceptionBehavior::ebMayTrap:
8621 case fp::ExceptionBehavior::ebIgnore:
8622 PendingConstrainedFP.push_back(Elt: OutChain);
8623 break;
8624 case fp::ExceptionBehavior::ebStrict:
8625 PendingConstrainedFPStrict.push_back(Elt: OutChain);
8626 break;
8627 }
8628}
8629
8630void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8631 const ConstrainedFPIntrinsic &FPI) {
8632 SDLoc sdl = getCurSDLoc();
8633
8634 // We do not need to serialize constrained FP intrinsics against
8635 // each other or against (nonvolatile) loads, so they can be
8636 // chained like loads.
8637 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8638 SDValue Chain = getFPOperationRoot(EB);
8639 SmallVector<SDValue, 4> Opers;
8640 Opers.push_back(Elt: Chain);
8641 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8642 Opers.push_back(Elt: getValue(V: FPI.getArgOperand(i: I)));
8643
8644 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8645 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: FPI.getType());
8646 SDVTList VTs = DAG.getVTList(VT1: VT, VT2: MVT::Other);
8647
8648 SDNodeFlags Flags;
8649 if (EB == fp::ExceptionBehavior::ebIgnore)
8650 Flags.setNoFPExcept(true);
8651
8652 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &FPI))
8653 Flags.copyFMF(FPMO: *FPOp);
8654
8655 unsigned Opcode;
8656 switch (FPI.getIntrinsicID()) {
8657 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8658#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8659 case Intrinsic::INTRINSIC: \
8660 Opcode = ISD::STRICT_##DAGN; \
8661 break;
8662#include "llvm/IR/ConstrainedOps.def"
8663 case Intrinsic::experimental_constrained_fmuladd: {
8664 Opcode = ISD::STRICT_FMA;
8665 // Break fmuladd into fmul and fadd.
8666 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8667 !TLI.isFMAFasterThanFMulAndFAdd(MF: DAG.getMachineFunction(), VT)) {
8668 Opers.pop_back();
8669 SDValue Mul = DAG.getNode(Opcode: ISD::STRICT_FMUL, DL: sdl, VTList: VTs, Ops: Opers, Flags);
8670 pushFPOpOutChain(Result: Mul, EB);
8671 Opcode = ISD::STRICT_FADD;
8672 Opers.clear();
8673 Opers.push_back(Elt: Mul.getValue(R: 1));
8674 Opers.push_back(Elt: Mul.getValue(R: 0));
8675 Opers.push_back(Elt: getValue(V: FPI.getArgOperand(i: 2)));
8676 }
8677 break;
8678 }
8679 }
8680
8681 // A few strict DAG nodes carry additional operands that are not
8682 // set up by the default code above.
8683 switch (Opcode) {
8684 default: break;
8685 case ISD::STRICT_FP_ROUND:
8686 Opers.push_back(
8687 Elt: DAG.getTargetConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
8688 break;
8689 case ISD::STRICT_FSETCC:
8690 case ISD::STRICT_FSETCCS: {
8691 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(Val: &FPI);
8692 ISD::CondCode Condition = getFCmpCondCode(Pred: FPCmp->getPredicate());
8693 if (DAG.isKnownNeverNaN(Op: Opers[1]) && DAG.isKnownNeverNaN(Op: Opers[2]))
8694 Condition = getFCmpCodeWithoutNaN(CC: Condition);
8695 Opers.push_back(Elt: DAG.getCondCode(Cond: Condition));
8696 break;
8697 }
8698 }
8699
8700 SDValue Result = DAG.getNode(Opcode, DL: sdl, VTList: VTs, Ops: Opers, Flags);
8701 pushFPOpOutChain(Result, EB);
8702
8703 SDValue FPResult = Result.getValue(R: 0);
8704 setValue(V: &FPI, NewN: FPResult);
8705}
8706
8707static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8708 std::optional<unsigned> ResOPC;
8709 switch (VPIntrin.getIntrinsicID()) {
8710 case Intrinsic::vp_ctlz: {
8711 bool IsZeroUndef = cast<ConstantInt>(Val: VPIntrin.getArgOperand(i: 1))->isOne();
8712 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_POISON : ISD::VP_CTLZ;
8713 break;
8714 }
8715 case Intrinsic::vp_cttz: {
8716 bool IsZeroUndef = cast<ConstantInt>(Val: VPIntrin.getArgOperand(i: 1))->isOne();
8717 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_POISON : ISD::VP_CTTZ;
8718 break;
8719 }
8720 case Intrinsic::vp_cttz_elts: {
8721 bool IsZeroPoison = cast<ConstantInt>(Val: VPIntrin.getArgOperand(i: 1))->isOne();
8722 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_POISON : ISD::VP_CTTZ_ELTS;
8723 break;
8724 }
8725#define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \
8726 case Intrinsic::VPID: \
8727 ResOPC = ISD::VPSD; \
8728 break;
8729#include "llvm/IR/VPIntrinsics.def"
8730 }
8731
8732 if (!ResOPC)
8733 llvm_unreachable(
8734 "Inconsistency: no SDNode available for this VPIntrinsic!");
8735
8736 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8737 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8738 if (VPIntrin.getFastMathFlags().allowReassoc())
8739 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8740 : ISD::VP_REDUCE_FMUL;
8741 }
8742
8743 return *ResOPC;
8744}
8745
8746void SelectionDAGBuilder::visitVPLoad(
8747 const VPIntrinsic &VPIntrin, EVT VT,
8748 const SmallVectorImpl<SDValue> &OpValues) {
8749 SDLoc DL = getCurSDLoc();
8750 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8751 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8752 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8753 const MDNode *Ranges = getRangeMetadata(I: VPIntrin);
8754 SDValue LD;
8755 // Do not serialize variable-length loads of constant memory with
8756 // anything.
8757 if (!Alignment)
8758 Alignment = DAG.getEVTAlign(MemoryVT: VT);
8759 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
8760 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
8761 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8762 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8763 MachineMemOperand::Flags MMOFlags =
8764 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8765 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8766 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
8767 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: *Alignment, AAInfo, Ranges);
8768 LD = DAG.getLoadVP(VT, dl: DL, Chain: InChain, Ptr: OpValues[0], Mask: OpValues[1], EVL: OpValues[2],
8769 MMO, IsExpanding: false /*IsExpanding */);
8770 if (AddToChain)
8771 PendingLoads.push_back(Elt: LD.getValue(R: 1));
8772 setValue(V: &VPIntrin, NewN: LD);
8773}
8774
8775void SelectionDAGBuilder::visitVPLoadFF(
8776 const VPIntrinsic &VPIntrin, EVT VT, EVT EVLVT,
8777 const SmallVectorImpl<SDValue> &OpValues) {
8778 assert(OpValues.size() == 3 && "Unexpected number of operands");
8779 SDLoc DL = getCurSDLoc();
8780 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8781 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8782 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8783 const MDNode *Ranges = VPIntrin.getMetadata(KindID: LLVMContext::MD_range);
8784 SDValue LD;
8785 // Do not serialize variable-length loads of constant memory with
8786 // anything.
8787 if (!Alignment)
8788 Alignment = DAG.getEVTAlign(MemoryVT: VT);
8789 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
8790 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
8791 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8792 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8793 PtrInfo: MachinePointerInfo(PtrOperand), F: MachineMemOperand::MOLoad,
8794 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: *Alignment, AAInfo, Ranges);
8795 LD = DAG.getLoadFFVP(VT, DL, Chain: InChain, Ptr: OpValues[0], Mask: OpValues[1], EVL: OpValues[2],
8796 MMO);
8797 SDValue Trunc = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: EVLVT, Operand: LD.getValue(R: 1));
8798 if (AddToChain)
8799 PendingLoads.push_back(Elt: LD.getValue(R: 2));
8800 setValue(V: &VPIntrin, NewN: DAG.getMergeValues(Ops: {LD.getValue(R: 0), Trunc}, dl: DL));
8801}
8802
8803void SelectionDAGBuilder::visitVPGather(
8804 const VPIntrinsic &VPIntrin, EVT VT,
8805 const SmallVectorImpl<SDValue> &OpValues) {
8806 SDLoc DL = getCurSDLoc();
8807 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8808 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8809 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8810 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8811 const MDNode *Ranges = getRangeMetadata(I: VPIntrin);
8812 SDValue LD;
8813 if (!Alignment)
8814 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
8815 unsigned AS =
8816 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8817 MachineMemOperand::Flags MMOFlags =
8818 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8819 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8820 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
8821 BaseAlignment: *Alignment, AAInfo, Ranges);
8822 SDValue Base, Index, Scale;
8823 bool UniformBase =
8824 getUniformBase(Ptr: PtrOperand, Base, Index, Scale, SDB: this, CurBB: VPIntrin.getParent(),
8825 ElemSize: VT.getScalarStoreSize());
8826 if (!UniformBase) {
8827 Base = DAG.getConstant(Val: 0, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8828 Index = getValue(V: PtrOperand);
8829 Scale = DAG.getTargetConstant(Val: 1, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8830 }
8831 EVT IdxVT = Index.getValueType();
8832 EVT EltTy = IdxVT.getVectorElementType();
8833 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
8834 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
8835 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT: NewIdxVT, Operand: Index);
8836 }
8837 LD = DAG.getGatherVP(
8838 VTs: DAG.getVTList(VT1: VT, VT2: MVT::Other), VT, dl: DL,
8839 Ops: {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8840 IndexType: ISD::SIGNED_SCALED);
8841 PendingLoads.push_back(Elt: LD.getValue(R: 1));
8842 setValue(V: &VPIntrin, NewN: LD);
8843}
8844
8845void SelectionDAGBuilder::visitVPStore(
8846 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8847 SDLoc DL = getCurSDLoc();
8848 Value *PtrOperand = VPIntrin.getArgOperand(i: 1);
8849 EVT VT = OpValues[0].getValueType();
8850 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8851 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8852 SDValue ST;
8853 if (!Alignment)
8854 Alignment = DAG.getEVTAlign(MemoryVT: VT);
8855 SDValue Ptr = OpValues[1];
8856 SDValue Offset = DAG.getUNDEF(VT: Ptr.getValueType());
8857 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8858 MachineMemOperand::Flags MMOFlags =
8859 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8860 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8861 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
8862 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: *Alignment, AAInfo);
8863 ST = DAG.getStoreVP(Chain: getMemoryRoot(), dl: DL, Val: OpValues[0], Ptr, Offset,
8864 Mask: OpValues[2], EVL: OpValues[3], MemVT: VT, MMO, AM: ISD::UNINDEXED,
8865 /* IsTruncating */ false, /*IsCompressing*/ false);
8866 DAG.setRoot(ST);
8867 setValue(V: &VPIntrin, NewN: ST);
8868}
8869
8870void SelectionDAGBuilder::visitVPScatter(
8871 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8872 SDLoc DL = getCurSDLoc();
8873 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8874 Value *PtrOperand = VPIntrin.getArgOperand(i: 1);
8875 EVT VT = OpValues[0].getValueType();
8876 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8877 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8878 SDValue ST;
8879 if (!Alignment)
8880 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
8881 unsigned AS =
8882 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8883 MachineMemOperand::Flags MMOFlags =
8884 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8885 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8886 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
8887 BaseAlignment: *Alignment, AAInfo);
8888 SDValue Base, Index, Scale;
8889 bool UniformBase =
8890 getUniformBase(Ptr: PtrOperand, Base, Index, Scale, SDB: this, CurBB: VPIntrin.getParent(),
8891 ElemSize: VT.getScalarStoreSize());
8892 if (!UniformBase) {
8893 Base = DAG.getConstant(Val: 0, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8894 Index = getValue(V: PtrOperand);
8895 Scale = DAG.getTargetConstant(Val: 1, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8896 }
8897 EVT IdxVT = Index.getValueType();
8898 EVT EltTy = IdxVT.getVectorElementType();
8899 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
8900 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
8901 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT: NewIdxVT, Operand: Index);
8902 }
8903 ST = DAG.getScatterVP(VTs: DAG.getVTList(VT: MVT::Other), VT, dl: DL,
8904 Ops: {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8905 OpValues[2], OpValues[3]},
8906 MMO, IndexType: ISD::SIGNED_SCALED);
8907 DAG.setRoot(ST);
8908 setValue(V: &VPIntrin, NewN: ST);
8909}
8910
8911void SelectionDAGBuilder::visitVPStridedLoad(
8912 const VPIntrinsic &VPIntrin, EVT VT,
8913 const SmallVectorImpl<SDValue> &OpValues) {
8914 SDLoc DL = getCurSDLoc();
8915 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8916 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8917 if (!Alignment)
8918 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
8919 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8920 const MDNode *Ranges = getRangeMetadata(I: VPIntrin);
8921 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
8922 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
8923 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8924 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8925 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8926 MachineMemOperand::Flags MMOFlags =
8927 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8928 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8929 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
8930 BaseAlignment: *Alignment, AAInfo, Ranges);
8931
8932 SDValue LD = DAG.getStridedLoadVP(VT, DL, Chain: InChain, Ptr: OpValues[0], Stride: OpValues[1],
8933 Mask: OpValues[2], EVL: OpValues[3], MMO,
8934 IsExpanding: false /*IsExpanding*/);
8935
8936 if (AddToChain)
8937 PendingLoads.push_back(Elt: LD.getValue(R: 1));
8938 setValue(V: &VPIntrin, NewN: LD);
8939}
8940
8941void SelectionDAGBuilder::visitVPStridedStore(
8942 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8943 SDLoc DL = getCurSDLoc();
8944 Value *PtrOperand = VPIntrin.getArgOperand(i: 1);
8945 EVT VT = OpValues[0].getValueType();
8946 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8947 if (!Alignment)
8948 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
8949 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8950 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8951 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8952 MachineMemOperand::Flags MMOFlags =
8953 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8954 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8955 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
8956 BaseAlignment: *Alignment, AAInfo);
8957
8958 SDValue ST = DAG.getStridedStoreVP(
8959 Chain: getMemoryRoot(), DL, Val: OpValues[0], Ptr: OpValues[1],
8960 Offset: DAG.getUNDEF(VT: OpValues[1].getValueType()), Stride: OpValues[2], Mask: OpValues[3],
8961 EVL: OpValues[4], MemVT: VT, MMO, AM: ISD::UNINDEXED, /*IsTruncating*/ false,
8962 /*IsCompressing*/ false);
8963
8964 DAG.setRoot(ST);
8965 setValue(V: &VPIntrin, NewN: ST);
8966}
8967
8968void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8969 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8970 SDLoc DL = getCurSDLoc();
8971
8972 ISD::CondCode Condition;
8973 CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8974
8975 Value *Op1 = VPIntrin.getOperand(i_nocapture: 0);
8976 Value *Op2 = VPIntrin.getOperand(i_nocapture: 1);
8977 // #2 is the condition code
8978 SDValue MaskOp = getValue(V: VPIntrin.getOperand(i_nocapture: 3));
8979 SDValue EVL = getValue(V: VPIntrin.getOperand(i_nocapture: 4));
8980 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8981 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8982 "Unexpected target EVL type");
8983 EVL = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL, VT: EVLParamVT, Operand: EVL);
8984
8985 if (VPIntrin.getOperand(i_nocapture: 0)->getType()->isFPOrFPVectorTy()) {
8986 Condition = getFCmpCondCode(Pred: CondCode);
8987 SimplifyQuery SQ(DAG.getDataLayout(), &VPIntrin);
8988 if (isKnownNeverNaN(V: Op2, SQ) && isKnownNeverNaN(V: Op1, SQ))
8989 Condition = getFCmpCodeWithoutNaN(CC: Condition);
8990 } else {
8991 Condition = getICmpCondCode(Pred: CondCode);
8992 }
8993
8994 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
8995 Ty: VPIntrin.getType());
8996 setValue(V: &VPIntrin, NewN: DAG.getSetCCVP(DL, VT: DestVT, LHS: getValue(V: Op1), RHS: getValue(V: Op2),
8997 Cond: Condition, Mask: MaskOp, EVL));
8998}
8999
9000void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
9001 const VPIntrinsic &VPIntrin) {
9002 SDLoc DL = getCurSDLoc();
9003 unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
9004
9005 auto IID = VPIntrin.getIntrinsicID();
9006
9007 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(Val: &VPIntrin))
9008 return visitVPCmp(VPIntrin: *CmpI);
9009
9010 SmallVector<EVT, 4> ValueVTs;
9011 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9012 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: VPIntrin.getType(), ValueVTs);
9013 SDVTList VTs = DAG.getVTList(VTs: ValueVTs);
9014
9015 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IntrinsicID: IID);
9016
9017 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
9018 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
9019 "Unexpected target EVL type");
9020
9021 // Request operands.
9022 SmallVector<SDValue, 7> OpValues;
9023 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
9024 auto Op = getValue(V: VPIntrin.getArgOperand(i: I));
9025 if (I == EVLParamPos)
9026 Op = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL, VT: EVLParamVT, Operand: Op);
9027 OpValues.push_back(Elt: Op);
9028 }
9029
9030 switch (Opcode) {
9031 default: {
9032 SDNodeFlags SDFlags;
9033 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &VPIntrin))
9034 SDFlags.copyFMF(FPMO: *FPMO);
9035 SDValue Result = DAG.getNode(Opcode, DL, VTList: VTs, Ops: OpValues, Flags: SDFlags);
9036 setValue(V: &VPIntrin, NewN: Result);
9037 break;
9038 }
9039 case ISD::VP_LOAD:
9040 visitVPLoad(VPIntrin, VT: ValueVTs[0], OpValues);
9041 break;
9042 case ISD::VP_LOAD_FF:
9043 visitVPLoadFF(VPIntrin, VT: ValueVTs[0], EVLVT: ValueVTs[1], OpValues);
9044 break;
9045 case ISD::VP_GATHER:
9046 visitVPGather(VPIntrin, VT: ValueVTs[0], OpValues);
9047 break;
9048 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
9049 visitVPStridedLoad(VPIntrin, VT: ValueVTs[0], OpValues);
9050 break;
9051 case ISD::VP_STORE:
9052 visitVPStore(VPIntrin, OpValues);
9053 break;
9054 case ISD::VP_SCATTER:
9055 visitVPScatter(VPIntrin, OpValues);
9056 break;
9057 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
9058 visitVPStridedStore(VPIntrin, OpValues);
9059 break;
9060 case ISD::VP_FMULADD: {
9061 assert(OpValues.size() == 5 && "Unexpected number of operands");
9062 SDNodeFlags SDFlags;
9063 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &VPIntrin))
9064 SDFlags.copyFMF(FPMO: *FPMO);
9065 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
9066 TLI.isFMAFasterThanFMulAndFAdd(MF: DAG.getMachineFunction(), ValueVTs[0])) {
9067 setValue(V: &VPIntrin, NewN: DAG.getNode(Opcode: ISD::VP_FMA, DL, VTList: VTs, Ops: OpValues, Flags: SDFlags));
9068 } else {
9069 SDValue Mul = DAG.getNode(
9070 Opcode: ISD::VP_FMUL, DL, VTList: VTs,
9071 Ops: {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, Flags: SDFlags);
9072 SDValue Add =
9073 DAG.getNode(Opcode: ISD::VP_FADD, DL, VTList: VTs,
9074 Ops: {Mul, OpValues[2], OpValues[3], OpValues[4]}, Flags: SDFlags);
9075 setValue(V: &VPIntrin, NewN: Add);
9076 }
9077 break;
9078 }
9079 case ISD::VP_IS_FPCLASS: {
9080 const DataLayout DLayout = DAG.getDataLayout();
9081 EVT DestVT = TLI.getValueType(DL: DLayout, Ty: VPIntrin.getType());
9082 auto Constant = OpValues[1]->getAsZExtVal();
9083 SDValue Check = DAG.getTargetConstant(Val: Constant, DL, VT: MVT::i32);
9084 SDValue V = DAG.getNode(Opcode: ISD::VP_IS_FPCLASS, DL, VT: DestVT,
9085 Ops: {OpValues[0], Check, OpValues[2], OpValues[3]});
9086 setValue(V: &VPIntrin, NewN: V);
9087 return;
9088 }
9089 case ISD::VP_INTTOPTR: {
9090 SDValue N = OpValues[0];
9091 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: VPIntrin.getType());
9092 EVT PtrMemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: VPIntrin.getType());
9093 N = DAG.getVPPtrExtOrTrunc(DL: getCurSDLoc(), VT: DestVT, Op: N, Mask: OpValues[1],
9094 EVL: OpValues[2]);
9095 N = DAG.getVPZExtOrTrunc(DL: getCurSDLoc(), VT: PtrMemVT, Op: N, Mask: OpValues[1],
9096 EVL: OpValues[2]);
9097 setValue(V: &VPIntrin, NewN: N);
9098 break;
9099 }
9100 case ISD::VP_PTRTOINT: {
9101 SDValue N = OpValues[0];
9102 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
9103 Ty: VPIntrin.getType());
9104 EVT PtrMemVT = TLI.getMemValueType(DL: DAG.getDataLayout(),
9105 Ty: VPIntrin.getOperand(i_nocapture: 0)->getType());
9106 N = DAG.getVPPtrExtOrTrunc(DL: getCurSDLoc(), VT: PtrMemVT, Op: N, Mask: OpValues[1],
9107 EVL: OpValues[2]);
9108 N = DAG.getVPZExtOrTrunc(DL: getCurSDLoc(), VT: DestVT, Op: N, Mask: OpValues[1],
9109 EVL: OpValues[2]);
9110 setValue(V: &VPIntrin, NewN: N);
9111 break;
9112 }
9113 case ISD::VP_ABS:
9114 case ISD::VP_CTLZ:
9115 case ISD::VP_CTLZ_ZERO_POISON:
9116 case ISD::VP_CTTZ:
9117 case ISD::VP_CTTZ_ZERO_POISON:
9118 case ISD::VP_CTTZ_ELTS_ZERO_POISON:
9119 case ISD::VP_CTTZ_ELTS: {
9120 SDValue Result =
9121 DAG.getNode(Opcode, DL, VTList: VTs, Ops: {OpValues[0], OpValues[2], OpValues[3]});
9122 setValue(V: &VPIntrin, NewN: Result);
9123 break;
9124 }
9125 }
9126}
9127
9128SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
9129 const BasicBlock *EHPadBB,
9130 MCSymbol *&BeginLabel) {
9131 MachineFunction &MF = DAG.getMachineFunction();
9132
9133 // Insert a label before the invoke call to mark the try range. This can be
9134 // used to detect deletion of the invoke via the MachineModuleInfo.
9135 BeginLabel = MF.getContext().createTempSymbol();
9136
9137 // For SjLj, keep track of which landing pads go with which invokes
9138 // so as to maintain the ordering of pads in the LSDA.
9139 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
9140 if (CallSiteIndex) {
9141 MF.setCallSiteBeginLabel(BeginLabel, Site: CallSiteIndex);
9142 LPadToCallSiteMap[FuncInfo.getMBB(BB: EHPadBB)].push_back(Elt: CallSiteIndex);
9143
9144 // Now that the call site is handled, stop tracking it.
9145 FuncInfo.setCurrentCallSite(0);
9146 }
9147
9148 return DAG.getEHLabel(dl: getCurSDLoc(), Root: Chain, Label: BeginLabel);
9149}
9150
9151SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
9152 const BasicBlock *EHPadBB,
9153 MCSymbol *BeginLabel) {
9154 assert(BeginLabel && "BeginLabel should've been set");
9155
9156 MachineFunction &MF = DAG.getMachineFunction();
9157
9158 // Insert a label at the end of the invoke call to mark the try range. This
9159 // can be used to detect deletion of the invoke via the MachineModuleInfo.
9160 MCSymbol *EndLabel = MF.getContext().createTempSymbol();
9161 Chain = DAG.getEHLabel(dl: getCurSDLoc(), Root: Chain, Label: EndLabel);
9162
9163 // Inform MachineModuleInfo of range.
9164 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
9165 // There is a platform (e.g. wasm) that uses funclet style IR but does not
9166 // actually use outlined funclets and their LSDA info style.
9167 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
9168 assert(II && "II should've been set");
9169 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
9170 EHInfo->addIPToStateRange(II, InvokeBegin: BeginLabel, InvokeEnd: EndLabel);
9171 } else if (!isScopedEHPersonality(Pers)) {
9172 assert(EHPadBB);
9173 MF.addInvoke(LandingPad: FuncInfo.getMBB(BB: EHPadBB), BeginLabel, EndLabel);
9174 }
9175
9176 return Chain;
9177}
9178
9179std::pair<SDValue, SDValue>
9180SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
9181 const BasicBlock *EHPadBB) {
9182 MCSymbol *BeginLabel = nullptr;
9183
9184 if (EHPadBB) {
9185 // Both PendingLoads and PendingExports must be flushed here;
9186 // this call might not return.
9187 (void)getRoot();
9188 DAG.setRoot(lowerStartEH(Chain: getControlRoot(), EHPadBB, BeginLabel));
9189 CLI.setChain(getRoot());
9190 }
9191
9192 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9193 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
9194
9195 assert((CLI.IsTailCall || Result.second.getNode()) &&
9196 "Non-null chain expected with non-tail call!");
9197 assert((Result.second.getNode() || !Result.first.getNode()) &&
9198 "Null value expected with tail call!");
9199
9200 if (!Result.second.getNode()) {
9201 // As a special case, a null chain means that a tail call has been emitted
9202 // and the DAG root is already updated.
9203 HasTailCall = true;
9204
9205 // Since there's no actual continuation from this block, nothing can be
9206 // relying on us setting vregs for them.
9207 PendingExports.clear();
9208 } else {
9209 DAG.setRoot(Result.second);
9210 }
9211
9212 if (EHPadBB) {
9213 DAG.setRoot(lowerEndEH(Chain: getRoot(), II: cast_or_null<InvokeInst>(Val: CLI.CB), EHPadBB,
9214 BeginLabel));
9215 Result.second = getRoot();
9216 }
9217
9218 return Result;
9219}
9220
9221bool SelectionDAGBuilder::canTailCall(const CallBase &CB) const {
9222 bool isMustTailCall = CB.isMustTailCall();
9223
9224 // Avoid emitting tail calls in functions with the disable-tail-calls
9225 // attribute.
9226 const Function *Caller = CB.getParent()->getParent();
9227 if (!isMustTailCall &&
9228 Caller->getFnAttribute(Kind: "disable-tail-calls").getValueAsBool())
9229 return false;
9230
9231 // We can't tail call inside a function with a swifterror argument. Lowering
9232 // does not support this yet. It would have to move into the swifterror
9233 // register before the call.
9234 if (DAG.getTargetLoweringInfo().supportSwiftError() &&
9235 Caller->getAttributes().hasAttrSomewhere(Kind: Attribute::SwiftError))
9236 return false;
9237
9238 // Check if target-independent constraints permit a tail call here.
9239 // Target-dependent constraints are checked within TLI->LowerCallTo.
9240 return isInTailCallPosition(Call: CB, TM: DAG.getTarget());
9241}
9242
9243void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
9244 bool isTailCall, bool isMustTailCall,
9245 const BasicBlock *EHPadBB,
9246 const TargetLowering::PtrAuthInfo *PAI) {
9247 auto &DL = DAG.getDataLayout();
9248 FunctionType *FTy = CB.getFunctionType();
9249 Type *RetTy = CB.getType();
9250
9251 TargetLowering::ArgListTy Args;
9252 Args.reserve(n: CB.arg_size());
9253
9254 const Value *SwiftErrorVal = nullptr;
9255 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9256
9257 if (isTailCall)
9258 isTailCall = canTailCall(CB);
9259
9260 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
9261 const Value *V = *I;
9262
9263 // Skip empty types
9264 if (V->getType()->isEmptyTy())
9265 continue;
9266
9267 SDValue ArgNode = getValue(V);
9268 TargetLowering::ArgListEntry Entry(ArgNode, V->getType());
9269 Entry.setAttributes(Call: &CB, ArgIdx: I - CB.arg_begin());
9270
9271 // Use swifterror virtual register as input to the call.
9272 if (Entry.IsSwiftError && TLI.supportSwiftError()) {
9273 SwiftErrorVal = V;
9274 // We find the virtual register for the actual swifterror argument.
9275 // Instead of using the Value, we use the virtual register instead.
9276 Entry.Node =
9277 DAG.getRegister(Reg: SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
9278 VT: EVT(TLI.getPointerTy(DL)));
9279 }
9280
9281 Args.push_back(x: Entry);
9282
9283 // If we have an explicit sret argument that is an Instruction, (i.e., it
9284 // might point to function-local memory), we can't meaningfully tail-call.
9285 if (Entry.IsSRet && isa<Instruction>(Val: V))
9286 isTailCall = false;
9287 }
9288
9289 // If call site has a cfguardtarget operand bundle, create and add an
9290 // additional ArgListEntry.
9291 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_cfguardtarget)) {
9292 Value *V = Bundle->Inputs[0];
9293 TargetLowering::ArgListEntry Entry(V, getValue(V));
9294 Entry.IsCFGuardTarget = true;
9295 Args.push_back(x: Entry);
9296 }
9297
9298 // Disable tail calls if there is an swifterror argument. Targets have not
9299 // been updated to support tail calls.
9300 if (TLI.supportSwiftError() && SwiftErrorVal)
9301 isTailCall = false;
9302
9303 ConstantInt *CFIType = nullptr;
9304 if (CB.isIndirectCall()) {
9305 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_kcfi)) {
9306 if (!TLI.supportKCFIBundles())
9307 report_fatal_error(
9308 reason: "Target doesn't support calls with kcfi operand bundles.");
9309 CFIType = cast<ConstantInt>(Val: Bundle->Inputs[0]);
9310 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
9311 }
9312 }
9313
9314 SDValue ConvControlToken;
9315 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_convergencectrl)) {
9316 auto *Token = Bundle->Inputs[0].get();
9317 ConvControlToken = getValue(V: Token);
9318 }
9319
9320 GlobalValue *DeactivationSymbol = nullptr;
9321 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_deactivation_symbol)) {
9322 DeactivationSymbol = cast<GlobalValue>(Val: Bundle->Inputs[0].get());
9323 }
9324
9325 TargetLowering::CallLoweringInfo CLI(DAG);
9326 CLI.setDebugLoc(getCurSDLoc())
9327 .setChain(getRoot())
9328 .setCallee(ResultType: RetTy, FTy, Target: Callee, ArgsList: std::move(Args), Call: CB)
9329 .setTailCall(isTailCall)
9330 .setConvergent(CB.isConvergent())
9331 .setIsPreallocated(
9332 CB.countOperandBundlesOfType(ID: LLVMContext::OB_preallocated) != 0)
9333 .setCFIType(CFIType)
9334 .setConvergenceControlToken(ConvControlToken)
9335 .setDeactivationSymbol(DeactivationSymbol);
9336
9337 // Set the pointer authentication info if we have it.
9338 if (PAI) {
9339 if (!TLI.supportPtrAuthBundles())
9340 report_fatal_error(
9341 reason: "This target doesn't support calls with ptrauth operand bundles.");
9342 CLI.setPtrAuth(*PAI);
9343 }
9344
9345 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9346
9347 if (Result.first.getNode()) {
9348 Result.first = lowerRangeToAssertZExt(DAG, I: CB, Op: Result.first);
9349 Result.first = lowerNoFPClassToAssertNoFPClass(DAG, I: CB, Op: Result.first);
9350 setValue(V: &CB, NewN: Result.first);
9351 }
9352
9353 // The last element of CLI.InVals has the SDValue for swifterror return.
9354 // Here we copy it to a virtual register and update SwiftErrorMap for
9355 // book-keeping.
9356 if (SwiftErrorVal && TLI.supportSwiftError()) {
9357 // Get the last element of InVals.
9358 SDValue Src = CLI.InVals.back();
9359 Register VReg =
9360 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
9361 SDValue CopyNode = CLI.DAG.getCopyToReg(Chain: Result.second, dl: CLI.DL, Reg: VReg, N: Src);
9362 DAG.setRoot(CopyNode);
9363 }
9364}
9365
9366static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
9367 SelectionDAGBuilder &Builder) {
9368 // Check to see if this load can be trivially constant folded, e.g. if the
9369 // input is from a string literal.
9370 if (const Constant *LoadInput = dyn_cast<Constant>(Val: PtrVal)) {
9371 // Cast pointer to the type we really want to load.
9372 Type *LoadTy =
9373 Type::getIntNTy(C&: PtrVal->getContext(), N: LoadVT.getScalarSizeInBits());
9374 if (LoadVT.isVector())
9375 LoadTy = FixedVectorType::get(ElementType: LoadTy, NumElts: LoadVT.getVectorNumElements());
9376 if (const Constant *LoadCst =
9377 ConstantFoldLoadFromConstPtr(C: const_cast<Constant *>(LoadInput),
9378 Ty: LoadTy, DL: Builder.DAG.getDataLayout()))
9379 return Builder.getValue(V: LoadCst);
9380 }
9381
9382 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
9383 // still constant memory, the input chain can be the entry node.
9384 SDValue Root;
9385 bool ConstantMemory = false;
9386
9387 // Do not serialize (non-volatile) loads of constant memory with anything.
9388 if (Builder.BatchAA && Builder.BatchAA->pointsToConstantMemory(P: PtrVal)) {
9389 Root = Builder.DAG.getEntryNode();
9390 ConstantMemory = true;
9391 } else {
9392 // Do not serialize non-volatile loads against each other.
9393 Root = Builder.DAG.getRoot();
9394 }
9395
9396 SDValue Ptr = Builder.getValue(V: PtrVal);
9397 SDValue LoadVal =
9398 Builder.DAG.getLoad(VT: LoadVT, dl: Builder.getCurSDLoc(), Chain: Root, Ptr,
9399 PtrInfo: MachinePointerInfo(PtrVal), Alignment: Align(1));
9400
9401 if (!ConstantMemory)
9402 Builder.PendingLoads.push_back(Elt: LoadVal.getValue(R: 1));
9403 return LoadVal;
9404}
9405
9406/// Record the value for an instruction that produces an integer result,
9407/// converting the type where necessary.
9408void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
9409 SDValue Value,
9410 bool IsSigned) {
9411 EVT VT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
9412 Ty: I.getType(), AllowUnknown: true);
9413 Value = DAG.getExtOrTrunc(IsSigned, Op: Value, DL: getCurSDLoc(), VT);
9414 setValue(V: &I, NewN: Value);
9415}
9416
9417/// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
9418/// true and lower it. Otherwise return false, and it will be lowered like a
9419/// normal call.
9420/// The caller already checked that \p I calls the appropriate LibFunc with a
9421/// correct prototype.
9422bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
9423 const Value *LHS = I.getArgOperand(i: 0), *RHS = I.getArgOperand(i: 1);
9424 const Value *Size = I.getArgOperand(i: 2);
9425 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(Val: getValue(V: Size));
9426 if (CSize && CSize->getZExtValue() == 0) {
9427 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
9428 Ty: I.getType(), AllowUnknown: true);
9429 setValue(V: &I, NewN: DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: CallVT));
9430 return true;
9431 }
9432
9433 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9434 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9435 DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(), Op1: getValue(V: LHS), Op2: getValue(V: RHS),
9436 Op3: getValue(V: Size), CI: &I);
9437 if (Res.first.getNode()) {
9438 processIntegerCallValue(I, Value: Res.first, IsSigned: true);
9439 PendingLoads.push_back(Elt: Res.second);
9440 return true;
9441 }
9442
9443 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
9444 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
9445 if (!CSize || !isOnlyUsedInZeroEqualityComparison(CxtI: &I))
9446 return false;
9447
9448 // If the target has a fast compare for the given size, it will return a
9449 // preferred load type for that size. Require that the load VT is legal and
9450 // that the target supports unaligned loads of that type. Otherwise, return
9451 // INVALID.
9452 auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9453 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9454 MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9455 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9456 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9457 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9458 // TODO: Check alignment of src and dest ptrs.
9459 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9460 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9461 if (!TLI.isTypeLegal(VT: LVT) ||
9462 !TLI.allowsMisalignedMemoryAccesses(LVT, AddrSpace: SrcAS) ||
9463 !TLI.allowsMisalignedMemoryAccesses(LVT, AddrSpace: DstAS))
9464 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
9465 }
9466
9467 return LVT;
9468 };
9469
9470 // This turns into unaligned loads. We only do this if the target natively
9471 // supports the MVT we'll be loading or if it is small enough (<= 4) that
9472 // we'll only produce a small number of byte loads.
9473 MVT LoadVT;
9474 unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9475 switch (NumBitsToCompare) {
9476 default:
9477 return false;
9478 case 16:
9479 LoadVT = MVT::i16;
9480 break;
9481 case 32:
9482 LoadVT = MVT::i32;
9483 break;
9484 case 64:
9485 case 128:
9486 case 256:
9487 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9488 break;
9489 }
9490
9491 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9492 return false;
9493
9494 SDValue LoadL = getMemCmpLoad(PtrVal: LHS, LoadVT, Builder&: *this);
9495 SDValue LoadR = getMemCmpLoad(PtrVal: RHS, LoadVT, Builder&: *this);
9496
9497 // Bitcast to a wide integer type if the loads are vectors.
9498 if (LoadVT.isVector()) {
9499 EVT CmpVT = EVT::getIntegerVT(Context&: LHS->getContext(), BitWidth: LoadVT.getSizeInBits());
9500 LoadL = DAG.getBitcast(VT: CmpVT, V: LoadL);
9501 LoadR = DAG.getBitcast(VT: CmpVT, V: LoadR);
9502 }
9503
9504 SDValue Cmp = DAG.getSetCC(DL: getCurSDLoc(), VT: MVT::i1, LHS: LoadL, RHS: LoadR, Cond: ISD::SETNE);
9505 processIntegerCallValue(I, Value: Cmp, IsSigned: false);
9506 return true;
9507}
9508
9509/// See if we can lower a memchr call into an optimized form. If so, return
9510/// true and lower it. Otherwise return false, and it will be lowered like a
9511/// normal call.
9512/// The caller already checked that \p I calls the appropriate LibFunc with a
9513/// correct prototype.
9514bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9515 const Value *Src = I.getArgOperand(i: 0);
9516 const Value *Char = I.getArgOperand(i: 1);
9517 const Value *Length = I.getArgOperand(i: 2);
9518
9519 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9520 std::pair<SDValue, SDValue> Res =
9521 TSI.EmitTargetCodeForMemchr(DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(),
9522 Src: getValue(V: Src), Char: getValue(V: Char), Length: getValue(V: Length),
9523 SrcPtrInfo: MachinePointerInfo(Src));
9524 if (Res.first.getNode()) {
9525 setValue(V: &I, NewN: Res.first);
9526 PendingLoads.push_back(Elt: Res.second);
9527 return true;
9528 }
9529
9530 return false;
9531}
9532
9533/// See if we can lower a memccpy call into an optimized form. If so, return
9534/// true and lower it, otherwise return false and it will be lowered like a
9535/// normal call.
9536/// The caller already checked that \p I calls the appropriate LibFunc with a
9537/// correct prototype.
9538bool SelectionDAGBuilder::visitMemCCpyCall(const CallInst &I) {
9539 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9540 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemccpy(
9541 DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(), Dst: getValue(V: I.getArgOperand(i: 0)),
9542 Src: getValue(V: I.getArgOperand(i: 1)), C: getValue(V: I.getArgOperand(i: 2)),
9543 Size: getValue(V: I.getArgOperand(i: 3)), CI: &I);
9544
9545 if (Res.first) {
9546 processIntegerCallValue(I, Value: Res.first, IsSigned: true);
9547 PendingLoads.push_back(Elt: Res.second);
9548 return true;
9549 }
9550 return false;
9551}
9552
9553/// See if we can lower a mempcpy call into an optimized form. If so, return
9554/// true and lower it. Otherwise return false, and it will be lowered like a
9555/// normal call.
9556/// The caller already checked that \p I calls the appropriate LibFunc with a
9557/// correct prototype.
9558bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9559 SDValue Dst = getValue(V: I.getArgOperand(i: 0));
9560 SDValue Src = getValue(V: I.getArgOperand(i: 1));
9561 SDValue Size = getValue(V: I.getArgOperand(i: 2));
9562
9563 Align DstAlign = DAG.InferPtrAlign(Ptr: Dst).valueOrOne();
9564 Align SrcAlign = DAG.InferPtrAlign(Ptr: Src).valueOrOne();
9565
9566 SDLoc sdl = getCurSDLoc();
9567
9568 // In the mempcpy context we need to pass in a false value for isTailCall
9569 // because the return pointer needs to be adjusted by the size of
9570 // the copied memory.
9571 SDValue Root = getMemoryRoot();
9572 SDValue MC = DAG.getMemcpy(
9573 Chain: Root, dl: sdl, Dst, Src, Size, DstAlign, SrcAlign, isVol: false, AlwaysInline: false,
9574 /*CI=*/nullptr, OverrideTailCall: std::nullopt, DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
9575 SrcPtrInfo: MachinePointerInfo(I.getArgOperand(i: 1)), AAInfo: I.getAAMetadata());
9576 assert(MC.getNode() != nullptr &&
9577 "** memcpy should not be lowered as TailCall in mempcpy context **");
9578 DAG.setRoot(MC);
9579
9580 // Check if Size needs to be truncated or extended.
9581 Size = DAG.getSExtOrTrunc(Op: Size, DL: sdl, VT: Dst.getValueType());
9582
9583 // Adjust return pointer to point just past the last dst byte.
9584 SDValue DstPlusSize = DAG.getMemBasePlusOffset(Base: Dst, Offset: Size, DL: sdl);
9585 setValue(V: &I, NewN: DstPlusSize);
9586 return true;
9587}
9588
9589/// See if we can lower a strcpy call into an optimized form. If so, return
9590/// true and lower it, otherwise return false and it will be lowered like a
9591/// normal call.
9592/// The caller already checked that \p I calls the appropriate LibFunc with a
9593/// correct prototype.
9594bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9595 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9596
9597 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9598 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcpy(
9599 DAG, DL: getCurSDLoc(), Chain: getRoot(), Dest: getValue(V: Arg0), Src: getValue(V: Arg1),
9600 DestPtrInfo: MachinePointerInfo(Arg0), SrcPtrInfo: MachinePointerInfo(Arg1), isStpcpy, CI: &I);
9601 if (Res.first.getNode()) {
9602 setValue(V: &I, NewN: Res.first);
9603 DAG.setRoot(Res.second);
9604 return true;
9605 }
9606
9607 return false;
9608}
9609
9610/// See if we can lower a strcmp call into an optimized form. If so, return
9611/// true and lower it, otherwise return false and it will be lowered like a
9612/// normal call.
9613/// The caller already checked that \p I calls the appropriate LibFunc with a
9614/// correct prototype.
9615bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9616 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9617
9618 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9619 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcmp(
9620 DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(), Op1: getValue(V: Arg0), Op2: getValue(V: Arg1),
9621 Op1PtrInfo: MachinePointerInfo(Arg0), Op2PtrInfo: MachinePointerInfo(Arg1), CI: &I);
9622 if (Res.first.getNode()) {
9623 processIntegerCallValue(I, Value: Res.first, IsSigned: true);
9624 PendingLoads.push_back(Elt: Res.second);
9625 return true;
9626 }
9627
9628 return false;
9629}
9630
9631/// See if we can lower a strlen call into an optimized form. If so, return
9632/// true and lower it, otherwise return false and it will be lowered like a
9633/// normal call.
9634/// The caller already checked that \p I calls the appropriate LibFunc with a
9635/// correct prototype.
9636bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9637 const Value *Arg0 = I.getArgOperand(i: 0);
9638
9639 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9640 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrlen(
9641 DAG, DL: getCurSDLoc(), Chain: DAG.getRoot(), Src: getValue(V: Arg0), CI: &I);
9642 if (Res.first.getNode()) {
9643 processIntegerCallValue(I, Value: Res.first, IsSigned: false);
9644 PendingLoads.push_back(Elt: Res.second);
9645 return true;
9646 }
9647
9648 return false;
9649}
9650
9651/// See if we can lower a strnlen call into an optimized form. If so, return
9652/// true and lower it, otherwise return false and it will be lowered like a
9653/// normal call.
9654/// The caller already checked that \p I calls the appropriate LibFunc with a
9655/// correct prototype.
9656bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9657 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9658
9659 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9660 std::pair<SDValue, SDValue> Res =
9661 TSI.EmitTargetCodeForStrnlen(DAG, DL: getCurSDLoc(), Chain: DAG.getRoot(),
9662 Src: getValue(V: Arg0), MaxLength: getValue(V: Arg1),
9663 SrcPtrInfo: MachinePointerInfo(Arg0));
9664 if (Res.first.getNode()) {
9665 processIntegerCallValue(I, Value: Res.first, IsSigned: false);
9666 PendingLoads.push_back(Elt: Res.second);
9667 return true;
9668 }
9669
9670 return false;
9671}
9672
9673/// See if we can lower a Strstr call into an optimized form. If so, return
9674/// true and lower it, otherwise return false and it will be lowered like a
9675/// normal call.
9676/// The caller already checked that \p I calls the appropriate LibFunc with a
9677/// correct prototype.
9678bool SelectionDAGBuilder::visitStrstrCall(const CallInst &I) {
9679 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9680 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9681 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrstr(
9682 DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(), Op1: getValue(V: Arg0), Op2: getValue(V: Arg1), CI: &I);
9683 if (Res.first) {
9684 processIntegerCallValue(I, Value: Res.first, IsSigned: false);
9685 PendingLoads.push_back(Elt: Res.second);
9686 return true;
9687 }
9688 return false;
9689}
9690
9691/// See if we can lower a unary floating-point operation into an SDNode with
9692/// the specified Opcode. If so, return true and lower it, otherwise return
9693/// false and it will be lowered like a normal call.
9694/// The caller already checked that \p I calls the appropriate LibFunc with a
9695/// correct prototype.
9696bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9697 unsigned Opcode) {
9698 // We already checked this call's prototype; verify it doesn't modify errno.
9699 // Do not perform optimizations for call sites that require strict
9700 // floating-point semantics.
9701 if (!I.onlyReadsMemory() || I.isStrictFP())
9702 return false;
9703
9704 SDNodeFlags Flags;
9705 Flags.copyFMF(FPMO: cast<FPMathOperator>(Val: I));
9706
9707 SDValue Tmp = getValue(V: I.getArgOperand(i: 0));
9708 setValue(V: &I,
9709 NewN: DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Tmp.getValueType(), Operand: Tmp, Flags));
9710 return true;
9711}
9712
9713/// See if we can lower a binary floating-point operation into an SDNode with
9714/// the specified Opcode. If so, return true and lower it. Otherwise return
9715/// false, and it will be lowered like a normal call.
9716/// The caller already checked that \p I calls the appropriate LibFunc with a
9717/// correct prototype.
9718bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9719 unsigned Opcode) {
9720 // We already checked this call's prototype; verify it doesn't modify errno.
9721 // Do not perform optimizations for call sites that require strict
9722 // floating-point semantics.
9723 if (!I.onlyReadsMemory() || I.isStrictFP())
9724 return false;
9725
9726 SDNodeFlags Flags;
9727 Flags.copyFMF(FPMO: cast<FPMathOperator>(Val: I));
9728
9729 SDValue Tmp0 = getValue(V: I.getArgOperand(i: 0));
9730 SDValue Tmp1 = getValue(V: I.getArgOperand(i: 1));
9731 EVT VT = Tmp0.getValueType();
9732 setValue(V: &I, NewN: DAG.getNode(Opcode, DL: getCurSDLoc(), VT, N1: Tmp0, N2: Tmp1, Flags));
9733 return true;
9734}
9735
9736void SelectionDAGBuilder::visitCall(const CallInst &I) {
9737 // Handle inline assembly differently.
9738 if (I.isInlineAsm()) {
9739 visitInlineAsm(Call: I);
9740 return;
9741 }
9742
9743 diagnoseDontCall(CI: I);
9744
9745 if (Function *F = I.getCalledFunction()) {
9746 if (F->isDeclaration()) {
9747 // Is this an LLVM intrinsic?
9748 if (unsigned IID = F->getIntrinsicID()) {
9749 visitIntrinsicCall(I, Intrinsic: IID);
9750 return;
9751 }
9752 }
9753
9754 // Check for well-known libc/libm calls. If the function is internal, it
9755 // can't be a library call. Don't do the check if marked as nobuiltin for
9756 // some reason.
9757 // This code should not handle libcalls that are already canonicalized to
9758 // intrinsics by the middle-end.
9759 LibFunc Func;
9760 if (!I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName() &&
9761 LibInfo->getLibFunc(FDecl: *F, F&: Func) && LibInfo->hasOptimizedCodeGen(F: Func)) {
9762 switch (Func) {
9763 default: break;
9764 case LibFunc_bcmp:
9765 if (visitMemCmpBCmpCall(I))
9766 return;
9767 break;
9768 case LibFunc_copysign:
9769 case LibFunc_copysignf:
9770 case LibFunc_copysignl:
9771 // We already checked this call's prototype; verify it doesn't modify
9772 // errno.
9773 if (I.onlyReadsMemory()) {
9774 SDValue LHS = getValue(V: I.getArgOperand(i: 0));
9775 SDValue RHS = getValue(V: I.getArgOperand(i: 1));
9776 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FCOPYSIGN, DL: getCurSDLoc(),
9777 VT: LHS.getValueType(), N1: LHS, N2: RHS));
9778 return;
9779 }
9780 break;
9781 case LibFunc_sin:
9782 case LibFunc_sinf:
9783 case LibFunc_sinl:
9784 if (visitUnaryFloatCall(I, Opcode: ISD::FSIN))
9785 return;
9786 break;
9787 case LibFunc_cos:
9788 case LibFunc_cosf:
9789 case LibFunc_cosl:
9790 if (visitUnaryFloatCall(I, Opcode: ISD::FCOS))
9791 return;
9792 break;
9793 case LibFunc_tan:
9794 case LibFunc_tanf:
9795 case LibFunc_tanl:
9796 if (visitUnaryFloatCall(I, Opcode: ISD::FTAN))
9797 return;
9798 break;
9799 case LibFunc_asin:
9800 case LibFunc_asinf:
9801 case LibFunc_asinl:
9802 if (visitUnaryFloatCall(I, Opcode: ISD::FASIN))
9803 return;
9804 break;
9805 case LibFunc_acos:
9806 case LibFunc_acosf:
9807 case LibFunc_acosl:
9808 if (visitUnaryFloatCall(I, Opcode: ISD::FACOS))
9809 return;
9810 break;
9811 case LibFunc_atan:
9812 case LibFunc_atanf:
9813 case LibFunc_atanl:
9814 if (visitUnaryFloatCall(I, Opcode: ISD::FATAN))
9815 return;
9816 break;
9817 case LibFunc_atan2:
9818 case LibFunc_atan2f:
9819 case LibFunc_atan2l:
9820 if (visitBinaryFloatCall(I, Opcode: ISD::FATAN2))
9821 return;
9822 break;
9823 case LibFunc_sinh:
9824 case LibFunc_sinhf:
9825 case LibFunc_sinhl:
9826 if (visitUnaryFloatCall(I, Opcode: ISD::FSINH))
9827 return;
9828 break;
9829 case LibFunc_cosh:
9830 case LibFunc_coshf:
9831 case LibFunc_coshl:
9832 if (visitUnaryFloatCall(I, Opcode: ISD::FCOSH))
9833 return;
9834 break;
9835 case LibFunc_tanh:
9836 case LibFunc_tanhf:
9837 case LibFunc_tanhl:
9838 if (visitUnaryFloatCall(I, Opcode: ISD::FTANH))
9839 return;
9840 break;
9841 case LibFunc_sqrt:
9842 case LibFunc_sqrtf:
9843 case LibFunc_sqrtl:
9844 case LibFunc_sqrt_finite:
9845 case LibFunc_sqrtf_finite:
9846 case LibFunc_sqrtl_finite:
9847 if (visitUnaryFloatCall(I, Opcode: ISD::FSQRT))
9848 return;
9849 break;
9850 case LibFunc_log2:
9851 case LibFunc_log2f:
9852 case LibFunc_log2l:
9853 if (visitUnaryFloatCall(I, Opcode: ISD::FLOG2))
9854 return;
9855 break;
9856 case LibFunc_exp2:
9857 case LibFunc_exp2f:
9858 case LibFunc_exp2l:
9859 if (visitUnaryFloatCall(I, Opcode: ISD::FEXP2))
9860 return;
9861 break;
9862 case LibFunc_exp10:
9863 case LibFunc_exp10f:
9864 case LibFunc_exp10l:
9865 if (visitUnaryFloatCall(I, Opcode: ISD::FEXP10))
9866 return;
9867 break;
9868 case LibFunc_ldexp:
9869 case LibFunc_ldexpf:
9870 case LibFunc_ldexpl:
9871 if (visitBinaryFloatCall(I, Opcode: ISD::FLDEXP))
9872 return;
9873 break;
9874 case LibFunc_strstr:
9875 if (visitStrstrCall(I))
9876 return;
9877 break;
9878 case LibFunc_memcmp:
9879 if (visitMemCmpBCmpCall(I))
9880 return;
9881 break;
9882 case LibFunc_memccpy:
9883 if (visitMemCCpyCall(I))
9884 return;
9885 break;
9886 case LibFunc_mempcpy:
9887 if (visitMemPCpyCall(I))
9888 return;
9889 break;
9890 case LibFunc_memchr:
9891 if (visitMemChrCall(I))
9892 return;
9893 break;
9894 case LibFunc_strcpy:
9895 if (visitStrCpyCall(I, isStpcpy: false))
9896 return;
9897 break;
9898 case LibFunc_stpcpy:
9899 if (visitStrCpyCall(I, isStpcpy: true))
9900 return;
9901 break;
9902 case LibFunc_strcmp:
9903 if (visitStrCmpCall(I))
9904 return;
9905 break;
9906 case LibFunc_strlen:
9907 if (visitStrLenCall(I))
9908 return;
9909 break;
9910 case LibFunc_strnlen:
9911 if (visitStrNLenCall(I))
9912 return;
9913 break;
9914 }
9915 }
9916 }
9917
9918 if (I.countOperandBundlesOfType(ID: LLVMContext::OB_ptrauth)) {
9919 LowerCallSiteWithPtrAuthBundle(CB: cast<CallBase>(Val: I), /*EHPadBB=*/nullptr);
9920 return;
9921 }
9922
9923 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9924 // have to do anything here to lower funclet bundles.
9925 // CFGuardTarget bundles are lowered in LowerCallTo.
9926 failForInvalidBundles(
9927 I, Name: "calls",
9928 AllowedBundles: {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9929 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9930 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9931 LLVMContext::OB_convergencectrl, LLVMContext::OB_deactivation_symbol});
9932
9933 SDValue Callee = getValue(V: I.getCalledOperand());
9934
9935 if (I.hasDeoptState())
9936 LowerCallSiteWithDeoptBundle(Call: &I, Callee, EHPadBB: nullptr);
9937 else
9938 // Check if we can potentially perform a tail call. More detailed checking
9939 // is be done within LowerCallTo, after more information about the call is
9940 // known.
9941 LowerCallTo(CB: I, Callee, isTailCall: I.isTailCall(), isMustTailCall: I.isMustTailCall());
9942}
9943
9944void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9945 const CallBase &CB, const BasicBlock *EHPadBB) {
9946 auto PAB = CB.getOperandBundle(Name: "ptrauth");
9947 const Value *CalleeV = CB.getCalledOperand();
9948
9949 // Gather the call ptrauth data from the operand bundle:
9950 // [ i32 <key>, i64 <discriminator> ]
9951 const auto *Key = cast<ConstantInt>(Val: PAB->Inputs[0]);
9952 const Value *Discriminator = PAB->Inputs[1];
9953
9954 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9955 assert(Discriminator->getType()->isIntegerTy(64) &&
9956 "Invalid ptrauth discriminator");
9957
9958 // Look through ptrauth constants to find the raw callee.
9959 // Do a direct unauthenticated call if we found it and everything matches.
9960 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(Val: CalleeV))
9961 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9962 DL: DAG.getDataLayout()))
9963 return LowerCallTo(CB, Callee: getValue(V: CalleeCPA->getPointer()), isTailCall: CB.isTailCall(),
9964 isMustTailCall: CB.isMustTailCall(), EHPadBB);
9965
9966 // Functions should never be ptrauth-called directly.
9967 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9968
9969 // Otherwise, do an authenticated indirect call.
9970 TargetLowering::PtrAuthInfo PAI = {.Key: Key->getZExtValue(),
9971 .Discriminator: getValue(V: Discriminator)};
9972
9973 LowerCallTo(CB, Callee: getValue(V: CalleeV), isTailCall: CB.isTailCall(), isMustTailCall: CB.isMustTailCall(),
9974 EHPadBB, PAI: &PAI);
9975}
9976
9977namespace {
9978
9979/// AsmOperandInfo - This contains information for each constraint that we are
9980/// lowering.
9981class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9982public:
9983 /// CallOperand - If this is the result output operand or a clobber
9984 /// this is null, otherwise it is the incoming operand to the CallInst.
9985 /// This gets modified as the asm is processed.
9986 SDValue CallOperand;
9987
9988 /// AssignedRegs - If this is a register or register class operand, this
9989 /// contains the set of register corresponding to the operand.
9990 RegsForValue AssignedRegs;
9991
9992 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9993 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9994 }
9995
9996 /// Whether or not this operand accesses memory
9997 bool hasMemory(const TargetLowering &TLI) const {
9998 // Indirect operand accesses access memory.
9999 if (isIndirect)
10000 return true;
10001
10002 for (const auto &Code : Codes)
10003 if (TLI.getConstraintType(Constraint: Code) == TargetLowering::C_Memory)
10004 return true;
10005
10006 return false;
10007 }
10008};
10009
10010
10011} // end anonymous namespace
10012
10013/// Make sure that the output operand \p OpInfo and its corresponding input
10014/// operand \p MatchingOpInfo have compatible constraint types (otherwise error
10015/// out).
10016static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
10017 SDISelAsmOperandInfo &MatchingOpInfo,
10018 SelectionDAG &DAG) {
10019 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
10020 return;
10021
10022 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
10023 const auto &TLI = DAG.getTargetLoweringInfo();
10024
10025 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
10026 TLI.getRegForInlineAsmConstraint(TRI, Constraint: OpInfo.ConstraintCode,
10027 VT: OpInfo.ConstraintVT);
10028 std::pair<unsigned, const TargetRegisterClass *> InputRC =
10029 TLI.getRegForInlineAsmConstraint(TRI, Constraint: MatchingOpInfo.ConstraintCode,
10030 VT: MatchingOpInfo.ConstraintVT);
10031 const bool OutOpIsIntOrFP =
10032 OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
10033 const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
10034 MatchingOpInfo.ConstraintVT.isFloatingPoint();
10035 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
10036 // FIXME: error out in a more elegant fashion
10037 report_fatal_error(reason: "Unsupported asm: input constraint"
10038 " with a matching output constraint of"
10039 " incompatible type!");
10040 }
10041 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
10042}
10043
10044/// Get a direct memory input to behave well as an indirect operand.
10045/// This may introduce stores, hence the need for a \p Chain.
10046/// \return The (possibly updated) chain.
10047static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
10048 SDISelAsmOperandInfo &OpInfo,
10049 SelectionDAG &DAG) {
10050 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10051
10052 // If we don't have an indirect input, put it in the constpool if we can,
10053 // otherwise spill it to a stack slot.
10054 // TODO: This isn't quite right. We need to handle these according to
10055 // the addressing mode that the constraint wants. Also, this may take
10056 // an additional register for the computation and we don't want that
10057 // either.
10058
10059 // If the operand is a float, integer, or vector constant, spill to a
10060 // constant pool entry to get its address.
10061 const Value *OpVal = OpInfo.CallOperandVal;
10062 if (isa<ConstantFP>(Val: OpVal) || isa<ConstantInt>(Val: OpVal) ||
10063 isa<ConstantVector>(Val: OpVal) || isa<ConstantDataVector>(Val: OpVal)) {
10064 OpInfo.CallOperand = DAG.getConstantPool(
10065 C: cast<Constant>(Val: OpVal), VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
10066 return Chain;
10067 }
10068
10069 // Otherwise, create a stack slot and emit a store to it before the asm.
10070 Type *Ty = OpVal->getType();
10071 auto &DL = DAG.getDataLayout();
10072 TypeSize TySize = DL.getTypeAllocSize(Ty);
10073 MachineFunction &MF = DAG.getMachineFunction();
10074 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
10075 int StackID = 0;
10076 if (TySize.isScalable())
10077 StackID = TFI->getStackIDForScalableVectors();
10078 int SSFI = MF.getFrameInfo().CreateStackObject(Size: TySize.getKnownMinValue(),
10079 Alignment: DL.getPrefTypeAlign(Ty), isSpillSlot: false,
10080 Alloca: nullptr, ID: StackID);
10081 SDValue StackSlot = DAG.getFrameIndex(FI: SSFI, VT: TLI.getFrameIndexTy(DL));
10082 Chain = DAG.getTruncStore(Chain, dl: Location, Val: OpInfo.CallOperand, Ptr: StackSlot,
10083 PtrInfo: MachinePointerInfo::getFixedStack(MF, FI: SSFI),
10084 SVT: TLI.getMemValueType(DL, Ty));
10085 OpInfo.CallOperand = StackSlot;
10086
10087 return Chain;
10088}
10089
10090/// GetRegistersForValue - Assign registers (virtual or physical) for the
10091/// specified operand. We prefer to assign virtual registers, to allow the
10092/// register allocator to handle the assignment process. However, if the asm
10093/// uses features that we can't model on machineinstrs, we have SDISel do the
10094/// allocation. This produces generally horrible, but correct, code.
10095///
10096/// OpInfo describes the operand
10097/// RefOpInfo describes the matching operand if any, the operand otherwise
10098static std::optional<unsigned>
10099getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
10100 SDISelAsmOperandInfo &OpInfo,
10101 SDISelAsmOperandInfo &RefOpInfo) {
10102 LLVMContext &Context = *DAG.getContext();
10103 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10104
10105 MachineFunction &MF = DAG.getMachineFunction();
10106 SmallVector<Register, 4> Regs;
10107 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10108
10109 // No work to do for memory/address operands.
10110 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
10111 OpInfo.ConstraintType == TargetLowering::C_Address)
10112 return std::nullopt;
10113
10114 // If this is a constraint for a single physreg, or a constraint for a
10115 // register class, find it.
10116 unsigned AssignedReg;
10117 const TargetRegisterClass *RC;
10118 std::tie(args&: AssignedReg, args&: RC) = TLI.getRegForInlineAsmConstraint(
10119 TRI: &TRI, Constraint: RefOpInfo.ConstraintCode, VT: RefOpInfo.ConstraintVT);
10120 // RC is unset only on failure. Return immediately.
10121 if (!RC)
10122 return std::nullopt;
10123
10124 // Get the actual register value type. This is important, because the user
10125 // may have asked for (e.g.) the AX register in i32 type. We need to
10126 // remember that AX is actually i16 to get the right extension.
10127 const MVT RegVT = *TRI.legalclasstypes_begin(RC: *RC);
10128
10129 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
10130 // If this is an FP operand in an integer register (or visa versa), or more
10131 // generally if the operand value disagrees with the register class we plan
10132 // to stick it in, fix the operand type.
10133 //
10134 // If this is an input value, the bitcast to the new type is done now.
10135 // Bitcast for output value is done at the end of visitInlineAsm().
10136 if ((OpInfo.Type == InlineAsm::isOutput ||
10137 OpInfo.Type == InlineAsm::isInput) &&
10138 !TRI.isTypeLegalForClass(RC: *RC, T: OpInfo.ConstraintVT)) {
10139 // Try to convert to the first EVT that the reg class contains. If the
10140 // types are identical size, use a bitcast to convert (e.g. two differing
10141 // vector types). Note: output bitcast is done at the end of
10142 // visitInlineAsm().
10143 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
10144 // Exclude indirect inputs while they are unsupported because the code
10145 // to perform the load is missing and thus OpInfo.CallOperand still
10146 // refers to the input address rather than the pointed-to value.
10147 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
10148 OpInfo.CallOperand =
10149 DAG.getNode(Opcode: ISD::BITCAST, DL, VT: RegVT, Operand: OpInfo.CallOperand);
10150 OpInfo.ConstraintVT = RegVT;
10151 // If the operand is an FP value and we want it in integer registers,
10152 // use the corresponding integer type. This turns an f64 value into
10153 // i64, which can be passed with two i32 values on a 32-bit machine.
10154 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
10155 MVT VT = MVT::getIntegerVT(BitWidth: OpInfo.ConstraintVT.getSizeInBits());
10156 if (OpInfo.Type == InlineAsm::isInput)
10157 OpInfo.CallOperand =
10158 DAG.getNode(Opcode: ISD::BITCAST, DL, VT, Operand: OpInfo.CallOperand);
10159 OpInfo.ConstraintVT = VT;
10160 }
10161 }
10162 }
10163
10164 // No need to allocate a matching input constraint since the constraint it's
10165 // matching to has already been allocated.
10166 if (OpInfo.isMatchingInputConstraint())
10167 return std::nullopt;
10168
10169 EVT ValueVT = OpInfo.ConstraintVT;
10170 if (OpInfo.ConstraintVT == MVT::Other)
10171 ValueVT = RegVT;
10172
10173 // Initialize NumRegs.
10174 unsigned NumRegs = 1;
10175 if (OpInfo.ConstraintVT != MVT::Other)
10176 NumRegs = TLI.getNumRegisters(Context, VT: OpInfo.ConstraintVT, RegisterVT: RegVT);
10177
10178 // If this is a constraint for a specific physical register, like {r17},
10179 // assign it now.
10180
10181 // If this associated to a specific register, initialize iterator to correct
10182 // place. If virtual, make sure we have enough registers
10183
10184 // Initialize iterator if necessary
10185 TargetRegisterClass::iterator I = RC->begin();
10186 MachineRegisterInfo &RegInfo = MF.getRegInfo();
10187
10188 // Do not check for single registers.
10189 if (AssignedReg) {
10190 I = std::find(first: I, last: RC->end(), val: AssignedReg);
10191 if (I == RC->end()) {
10192 // RC does not contain the selected register, which indicates a
10193 // mismatch between the register and the required type/bitwidth.
10194 return {AssignedReg};
10195 }
10196 }
10197
10198 for (; NumRegs; --NumRegs, ++I) {
10199 assert(I != RC->end() && "Ran out of registers to allocate!");
10200 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RegClass: RC);
10201 Regs.push_back(Elt: R);
10202 }
10203
10204 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
10205 return std::nullopt;
10206}
10207
10208static unsigned
10209findMatchingInlineAsmOperand(unsigned OperandNo,
10210 const std::vector<SDValue> &AsmNodeOperands) {
10211 // Scan until we find the definition we already emitted of this operand.
10212 unsigned CurOp = InlineAsm::Op_FirstOperand;
10213 for (; OperandNo; --OperandNo) {
10214 // Advance to the next operand.
10215 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
10216 const InlineAsm::Flag F(OpFlag);
10217 assert(
10218 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
10219 "Skipped past definitions?");
10220 CurOp += F.getNumOperandRegisters() + 1;
10221 }
10222 return CurOp;
10223}
10224
10225namespace {
10226
10227class ExtraFlags {
10228 unsigned Flags = 0;
10229
10230public:
10231 explicit ExtraFlags(const CallBase &Call) {
10232 const InlineAsm *IA = cast<InlineAsm>(Val: Call.getCalledOperand());
10233 if (IA->hasSideEffects())
10234 Flags |= InlineAsm::Extra_HasSideEffects;
10235 if (IA->isAlignStack())
10236 Flags |= InlineAsm::Extra_IsAlignStack;
10237 if (IA->canThrow())
10238 Flags |= InlineAsm::Extra_MayUnwind;
10239 if (Call.isConvergent())
10240 Flags |= InlineAsm::Extra_IsConvergent;
10241 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
10242 }
10243
10244 void update(const TargetLowering::AsmOperandInfo &OpInfo) {
10245 // Ideally, we would only check against memory constraints. However, the
10246 // meaning of an Other constraint can be target-specific and we can't easily
10247 // reason about it. Therefore, be conservative and set MayLoad/MayStore
10248 // for Other constraints as well.
10249 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
10250 OpInfo.ConstraintType == TargetLowering::C_Other) {
10251 if (OpInfo.Type == InlineAsm::isInput)
10252 Flags |= InlineAsm::Extra_MayLoad;
10253 else if (OpInfo.Type == InlineAsm::isOutput)
10254 Flags |= InlineAsm::Extra_MayStore;
10255 else if (OpInfo.Type == InlineAsm::isClobber)
10256 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
10257 }
10258 }
10259
10260 unsigned get() const { return Flags; }
10261};
10262
10263} // end anonymous namespace
10264
10265static bool isFunction(SDValue Op) {
10266 if (Op && Op.getOpcode() == ISD::GlobalAddress) {
10267 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Val&: Op)) {
10268 auto Fn = dyn_cast_or_null<Function>(Val: GA->getGlobal());
10269
10270 // In normal "call dllimport func" instruction (non-inlineasm) it force
10271 // indirect access by specifing call opcode. And usually specially print
10272 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
10273 // not do in this way now. (In fact, this is similar with "Data Access"
10274 // action). So here we ignore dllimport function.
10275 if (Fn && !Fn->hasDLLImportStorageClass())
10276 return true;
10277 }
10278 }
10279 return false;
10280}
10281
10282namespace {
10283
10284struct ConstraintDecisionInfo {
10285 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
10286 std::vector<SDValue> AsmNodeOperands;
10287 SDValue Glue, Chain;
10288 bool HasSideEffect = false;
10289 MCSymbol *BeginLabel = nullptr;
10290
10291 SmallVector<char> Buffer;
10292 raw_svector_ostream ErrorMsg;
10293
10294 ConstraintDecisionInfo() : ErrorMsg(Buffer) {}
10295};
10296
10297} // end anonymous namespace
10298
10299/// Construct operand info objects.
10300static bool
10301constructOperandInfo(ConstraintDecisionInfo &Info,
10302 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10303 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10304 ExtraFlags &ExtraInfo) {
10305 for (auto &T : TargetConstraints) {
10306 Info.ConstraintOperands.push_back(Elt: SDISelAsmOperandInfo(T));
10307 SDISelAsmOperandInfo &OpInfo = Info.ConstraintOperands.back();
10308
10309 if (OpInfo.CallOperandVal)
10310 OpInfo.CallOperand = Builder.getValue(V: OpInfo.CallOperandVal);
10311
10312 if (!Info.HasSideEffect)
10313 Info.HasSideEffect = OpInfo.hasMemory(TLI);
10314
10315 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
10316 // FIXME: Could we compute this on OpInfo rather than T?
10317
10318 // Compute the constraint code and ConstraintType to use.
10319 TLI.ComputeConstraintToUse(OpInfo&: T, Op: SDValue());
10320
10321 if (T.ConstraintType == TargetLowering::C_Immediate && OpInfo.CallOperand &&
10322 !isa<ConstantSDNode>(Val: OpInfo.CallOperand)) {
10323 // We've delayed emitting a diagnostic like the "n" constraint because
10324 // inlining could cause an integer showing up.
10325 Info.ErrorMsg << "constraint '" << T.ConstraintCode
10326 << "' expects an integer constant expression";
10327 return true;
10328 }
10329
10330 ExtraInfo.update(OpInfo: T);
10331 }
10332
10333 return false;
10334}
10335
10336/// Compute which constraint option to use for each operand.
10337static void
10338computeConstraintToUse(ConstraintDecisionInfo &Info, const CallBase &Call,
10339 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10340 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10341 const TargetMachine &TM, SelectionDAG &DAG) {
10342 const auto *IA = cast<InlineAsm>(Val: Call.getCalledOperand());
10343 SmallVector<StringRef, 4> AsmStrs;
10344 IA->collectAsmStrs(AsmStrs);
10345
10346 int OpNo = -1;
10347 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10348 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
10349 OpNo++;
10350
10351 // If this is an output operand with a matching input operand, look up the
10352 // matching input. If their types mismatch, e.g. one is an integer, the
10353 // other is floating point, or their sizes are different, flag it as an
10354 // error.
10355 if (OpInfo.hasMatchingInput()) {
10356 SDISelAsmOperandInfo &Input =
10357 Info.ConstraintOperands[OpInfo.MatchingInput];
10358 patchMatchingInput(OpInfo, MatchingOpInfo&: Input, DAG);
10359 }
10360
10361 // Compute the constraint code and ConstraintType to use.
10362 TLI.ComputeConstraintToUse(OpInfo, Op: OpInfo.CallOperand, DAG: &DAG);
10363
10364 if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
10365 OpInfo.Type == InlineAsm::isClobber) ||
10366 OpInfo.ConstraintType == TargetLowering::C_Address)
10367 continue;
10368
10369 // In Linux PIC model, there are 4 cases about value/label addressing:
10370 //
10371 // 1: Function call or Label jmp inside the module.
10372 // 2: Data access (such as global variable, static variable) inside module.
10373 // 3: Function call or Label jmp outside the module.
10374 // 4: Data access (such as global variable) outside the module.
10375 //
10376 // Due to current llvm inline asm architecture designed to not "recognize"
10377 // the asm code, there are quite troubles for us to treat mem addressing
10378 // differently for same value/adress used in different instuctions.
10379 // For example, in pic model, call a func may in plt way or direclty
10380 // pc-related, but lea/mov a function adress may use got.
10381 //
10382 // Here we try to "recognize" function call for the case 1 and case 3 in
10383 // inline asm. And try to adjust the constraint for them.
10384 //
10385 // TODO: Due to current inline asm didn't encourage to jmp to the outsider
10386 // label, so here we don't handle jmp function label now, but we need to
10387 // enhance it (especilly in PIC model) if we meet meaningful requirements.
10388 if (OpInfo.isIndirect && isFunction(Op: OpInfo.CallOperand) &&
10389 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
10390 TM.getCodeModel() != CodeModel::Large) {
10391 OpInfo.isIndirect = false;
10392 OpInfo.ConstraintType = TargetLowering::C_Address;
10393 }
10394
10395 // If this is a memory input, and if the operand is not indirect, do what we
10396 // need to provide an address for the memory input.
10397 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
10398 !OpInfo.isIndirect) {
10399 assert((OpInfo.isMultipleAlternative ||
10400 (OpInfo.Type == InlineAsm::isInput)) &&
10401 "Can only indirectify direct input operands!");
10402
10403 // Memory operands really want the address of the value.
10404 Info.Chain = getAddressForMemoryInput(Chain: Info.Chain, Location: Builder.getCurSDLoc(),
10405 OpInfo, DAG);
10406
10407 // There is no longer a Value* corresponding to this operand.
10408 OpInfo.CallOperandVal = nullptr;
10409
10410 // It is now an indirect operand.
10411 OpInfo.isIndirect = true;
10412 }
10413 }
10414}
10415
10416/// Prepare DAG-level operands. As part of this, assign virtual and physical
10417/// registers for inputs and output.
10418static bool prepareDAGLevelOperands(ConstraintDecisionInfo &Info,
10419 const CallBase &Call,
10420 SelectionDAGBuilder &Builder,
10421 const TargetLowering &TLI,
10422 SelectionDAG &DAG) {
10423 SDLoc DL = Builder.getCurSDLoc();
10424 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10425 // Assign Registers.
10426 SDISelAsmOperandInfo &RefOpInfo =
10427 OpInfo.isMatchingInputConstraint()
10428 ? Info.ConstraintOperands[OpInfo.getMatchedOperand()]
10429 : OpInfo;
10430 const auto RegError = getRegistersForValue(DAG, DL, OpInfo, RefOpInfo);
10431 if (RegError) {
10432 const MachineFunction &MF = DAG.getMachineFunction();
10433 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10434 const char *RegName = TRI.getName(RegNo: *RegError);
10435 Info.ErrorMsg << "register '" << RegName << "' allocated for constraint '"
10436 << OpInfo.ConstraintCode
10437 << "' does not match required type";
10438 return true;
10439 }
10440
10441 auto DetectWriteToReservedRegister = [&]() {
10442 const MachineFunction &MF = DAG.getMachineFunction();
10443 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10444
10445 for (Register Reg : OpInfo.AssignedRegs.Regs) {
10446 if (Reg.isPhysical() && TRI.isInlineAsmReadOnlyReg(MF, PhysReg: Reg)) {
10447 Info.ErrorMsg << "write to reserved register '"
10448 << TRI.getRegAsmName(Reg) << "'";
10449 return true;
10450 }
10451 }
10452
10453 return false;
10454 };
10455 assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10456 (OpInfo.Type == InlineAsm::isInput &&
10457 !OpInfo.isMatchingInputConstraint())) &&
10458 "Only address as input operand is allowed.");
10459
10460 switch (OpInfo.Type) {
10461 case InlineAsm::isOutput:
10462 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10463 const InlineAsm::ConstraintCode ConstraintID =
10464 TLI.getInlineAsmMemConstraint(ConstraintCode: OpInfo.ConstraintCode);
10465 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10466 "Failed to convert memory constraint code to constraint id.");
10467
10468 // Add information to the INLINEASM node to know about this output.
10469 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
10470 OpFlags.setMemConstraint(ConstraintID);
10471 Info.AsmNodeOperands.push_back(
10472 x: DAG.getTargetConstant(Val: OpFlags, DL, VT: MVT::i32));
10473 Info.AsmNodeOperands.push_back(x: OpInfo.CallOperand);
10474 } else {
10475 // Otherwise, this outputs to a register (directly for C_Register /
10476 // C_RegisterClass, and a target-defined fashion for
10477 // C_Immediate/C_Other). Find a register that we can use.
10478 if (OpInfo.AssignedRegs.Regs.empty()) {
10479 Info.ErrorMsg << "could not allocate output register for "
10480 << "constraint '" << OpInfo.ConstraintCode << "'";
10481 return true;
10482 }
10483
10484 if (DetectWriteToReservedRegister())
10485 return true;
10486
10487 // Add information to the INLINEASM node to know that this register is
10488 // set.
10489 OpInfo.AssignedRegs.AddInlineAsmOperands(
10490 Code: OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10491 : InlineAsm::Kind::RegDef,
10492 HasMatching: false, MatchingIdx: 0, dl: DL, DAG, Ops&: Info.AsmNodeOperands);
10493 }
10494 break;
10495
10496 case InlineAsm::isInput:
10497 case InlineAsm::isLabel: {
10498 SDValue InOperandVal = OpInfo.CallOperand;
10499
10500 if (OpInfo.isMatchingInputConstraint()) {
10501 // If this is required to match an output register we have already set,
10502 // just use its register.
10503 auto CurOp = findMatchingInlineAsmOperand(OperandNo: OpInfo.getMatchedOperand(),
10504 AsmNodeOperands: Info.AsmNodeOperands);
10505 InlineAsm::Flag Flag(Info.AsmNodeOperands[CurOp]->getAsZExtVal());
10506 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10507 if (OpInfo.isIndirect) {
10508 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10509 Info.ErrorMsg << "inline asm not supported yet: cannot handle "
10510 << "tied indirect register inputs";
10511 return true;
10512 }
10513
10514 SmallVector<Register, 4> Regs;
10515 MachineFunction &MF = DAG.getMachineFunction();
10516 MachineRegisterInfo &MRI = MF.getRegInfo();
10517 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10518 auto *R = cast<RegisterSDNode>(Val&: Info.AsmNodeOperands[CurOp + 1]);
10519 Register TiedReg = R->getReg();
10520 MVT RegVT = R->getSimpleValueType(ResNo: 0);
10521 const TargetRegisterClass *RC =
10522 TiedReg.isVirtual() ? MRI.getRegClass(Reg: TiedReg)
10523 : RegVT != MVT::Untyped ? TLI.getRegClassFor(VT: RegVT)
10524 : TRI.getMinimalPhysRegClass(Reg: TiedReg);
10525 for (unsigned I = 0, E = Flag.getNumOperandRegisters(); I != E; ++I)
10526 Regs.push_back(Elt: MRI.createVirtualRegister(RegClass: RC));
10527
10528 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10529
10530 // Use the produced MatchedRegs object to
10531 MatchedRegs.getCopyToRegs(Val: InOperandVal, DAG, dl: DL, Chain&: Info.Chain,
10532 Glue: &Info.Glue, V: &Call);
10533 MatchedRegs.AddInlineAsmOperands(Code: InlineAsm::Kind::RegUse, HasMatching: true,
10534 MatchingIdx: OpInfo.getMatchedOperand(), dl: DL, DAG,
10535 Ops&: Info.AsmNodeOperands);
10536 break;
10537 }
10538
10539 assert(Flag.isMemKind() && "Unknown matching constraint!");
10540 assert(Flag.getNumOperandRegisters() == 1 &&
10541 "Unexpected number of operands");
10542
10543 // Add information to the INLINEASM node to know about this input.
10544 // See InlineAsm.h isUseOperandTiedToDef.
10545 Flag.clearMemConstraint();
10546 Flag.setMatchingOp(OpInfo.getMatchedOperand());
10547 Info.AsmNodeOperands.push_back(x: DAG.getTargetConstant(
10548 Val: Flag, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
10549 Info.AsmNodeOperands.push_back(x: Info.AsmNodeOperands[CurOp + 1]);
10550 break;
10551 }
10552
10553 // Treat indirect 'X' constraint as memory.
10554 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10555 OpInfo.isIndirect)
10556 OpInfo.ConstraintType = TargetLowering::C_Memory;
10557
10558 if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10559 OpInfo.ConstraintType == TargetLowering::C_Other) {
10560 std::vector<SDValue> Ops;
10561 TLI.LowerAsmOperandForConstraint(Op: InOperandVal, Constraint: OpInfo.ConstraintCode,
10562 Ops, DAG);
10563 if (Ops.empty()) {
10564 if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10565 if (isa<ConstantSDNode>(Val: InOperandVal)) {
10566 Info.ErrorMsg << "value out of range for constraint '"
10567 << OpInfo.ConstraintCode << "'";
10568 return true;
10569 }
10570
10571 Info.ErrorMsg << "invalid operand for inline asm constraint '"
10572 << OpInfo.ConstraintCode << "'";
10573 return true;
10574 }
10575
10576 // Add information to the INLINEASM node to know about this input.
10577 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10578 Info.AsmNodeOperands.push_back(x: DAG.getTargetConstant(
10579 Val: ResOpType, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
10580 llvm::append_range(C&: Info.AsmNodeOperands, R&: Ops);
10581 break;
10582 }
10583
10584 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10585 assert((OpInfo.isIndirect ||
10586 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10587 "Operand must be indirect to be a mem!");
10588 assert(InOperandVal.getValueType() ==
10589 TLI.getPointerTy(DAG.getDataLayout()) &&
10590 "Memory operands expect pointer values");
10591
10592 const InlineAsm::ConstraintCode ConstraintID =
10593 TLI.getInlineAsmMemConstraint(ConstraintCode: OpInfo.ConstraintCode);
10594 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10595 "Failed to convert memory constraint code to constraint id.");
10596
10597 // Add information to the INLINEASM node to know about this input.
10598 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10599 ResOpType.setMemConstraint(ConstraintID);
10600 Info.AsmNodeOperands.push_back(
10601 x: DAG.getTargetConstant(Val: ResOpType, DL, VT: MVT::i32));
10602 Info.AsmNodeOperands.push_back(x: InOperandVal);
10603 break;
10604 }
10605
10606 if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10607 const InlineAsm::ConstraintCode ConstraintID =
10608 TLI.getInlineAsmMemConstraint(ConstraintCode: OpInfo.ConstraintCode);
10609 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10610 "Failed to convert memory constraint code to constraint id.");
10611
10612 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10613
10614 SDValue AsmOp = InOperandVal;
10615 if (isFunction(Op: InOperandVal)) {
10616 auto *GA = cast<GlobalAddressSDNode>(Val&: InOperandVal);
10617 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10618 AsmOp = DAG.getTargetGlobalAddress(GV: GA->getGlobal(), DL,
10619 VT: InOperandVal.getValueType(),
10620 offset: GA->getOffset());
10621 }
10622
10623 // Add information to the INLINEASM node to know about this input.
10624 ResOpType.setMemConstraint(ConstraintID);
10625
10626 Info.AsmNodeOperands.push_back(
10627 x: DAG.getTargetConstant(Val: ResOpType, DL, VT: MVT::i32));
10628 Info.AsmNodeOperands.push_back(x: AsmOp);
10629 break;
10630 }
10631
10632 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10633 OpInfo.ConstraintType != TargetLowering::C_Register) {
10634 Info.ErrorMsg << "unknown asm constraint '" << OpInfo.ConstraintCode
10635 << "'";
10636 return true;
10637 }
10638
10639 // TODO: Support this.
10640 if (OpInfo.isIndirect) {
10641 Info.ErrorMsg << "cannot handle indirect register inputs yet for "
10642 << "constraint '" << OpInfo.ConstraintCode << "'";
10643 return true;
10644 }
10645
10646 // Copy the input into the appropriate registers.
10647 if (OpInfo.AssignedRegs.Regs.empty()) {
10648 Info.ErrorMsg << "could not allocate input reg for constraint '"
10649 << OpInfo.ConstraintCode << "'";
10650 return true;
10651 }
10652
10653 if (DetectWriteToReservedRegister())
10654 return true;
10655
10656 OpInfo.AssignedRegs.getCopyToRegs(Val: InOperandVal, DAG, dl: DL, Chain&: Info.Chain,
10657 Glue: &Info.Glue, V: &Call);
10658 OpInfo.AssignedRegs.AddInlineAsmOperands(
10659 Code: InlineAsm::Kind::RegUse, HasMatching: false, MatchingIdx: 0, dl: DL, DAG, Ops&: Info.AsmNodeOperands);
10660 break;
10661 }
10662
10663 case InlineAsm::isClobber:
10664 // Add the clobbered value to the operand list, so that the register
10665 // allocator is aware that the physreg got clobbered.
10666 if (!OpInfo.AssignedRegs.Regs.empty())
10667 OpInfo.AssignedRegs.AddInlineAsmOperands(
10668 Code: InlineAsm::Kind::Clobber, HasMatching: false, MatchingIdx: 0, dl: DL, DAG, Ops&: Info.AsmNodeOperands);
10669 break;
10670 }
10671 }
10672
10673 return false;
10674}
10675
10676/// DetermineConstraints - Find the constraints to use for inline asm operands.
10677static bool
10678determineConstraints(ConstraintDecisionInfo &Info,
10679 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10680 const CallBase &Call, SelectionDAGBuilder &Builder,
10681 const TargetLowering &TLI, const TargetMachine &TM,
10682 SelectionDAG &DAG, const BasicBlock *EHPadBB) {
10683 const auto *IA = cast<InlineAsm>(Val: Call.getCalledOperand());
10684 ExtraFlags ExtraInfo(Call);
10685
10686 // First pass: Construct operand info objects.
10687 Info.HasSideEffect = IA->hasSideEffects();
10688 if (constructOperandInfo(Info, TargetConstraints, Builder, TLI, ExtraInfo))
10689 return true;
10690
10691 // We won't need to flush pending loads if this asm doesn't touch
10692 // memory and is nonvolatile.
10693 Info.Chain = Info.HasSideEffect ? Builder.getRoot() : DAG.getRoot();
10694
10695 bool IsCallBr = isa<CallBrInst>(Val: Call);
10696 bool EmitEHLabels = isa<InvokeInst>(Val: Call);
10697 if (IsCallBr || EmitEHLabels)
10698 // If this is a callbr or invoke we need to flush pending exports since
10699 // inlineasm_br and invoke are terminators.
10700 // We need to do this before nodes are glued to the inlineasm_br node.
10701 Info.Chain = Builder.getControlRoot();
10702
10703 if (EmitEHLabels)
10704 Info.Chain = Builder.lowerStartEH(Chain: Info.Chain, EHPadBB, BeginLabel&: Info.BeginLabel);
10705
10706 // Second pass: Compute which constraint option to use.
10707 computeConstraintToUse(Info, Call, TargetConstraints, Builder, TLI, TM, DAG);
10708
10709 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10710 Info.AsmNodeOperands.push_back(x: SDValue()); // reserve space for input chain
10711 Info.AsmNodeOperands.push_back(x: DAG.getTargetExternalSymbol(
10712 Sym: IA->getAsmString().data(), VT: TLI.getProgramPointerTy(DL: DAG.getDataLayout())));
10713
10714 // If we have a !srcloc metadata node associated with it, we want to attach
10715 // this to the ultimately generated inline asm machineinstr. To do this, we
10716 // pass in the third operand as this (potentially null) inline asm MDNode.
10717 const MDNode *SrcLoc = Call.getMetadata(Kind: "srcloc");
10718 Info.AsmNodeOperands.push_back(x: DAG.getMDNode(MD: SrcLoc));
10719
10720 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10721 // bits as operand 3.
10722 Info.AsmNodeOperands.push_back(
10723 x: DAG.getTargetConstant(Val: ExtraInfo.get(), DL: Builder.getCurSDLoc(),
10724 VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
10725
10726 // Third pass: Prepare DAG-level operands
10727 return prepareDAGLevelOperands(Info, Call, Builder, TLI, DAG);
10728}
10729
10730/// visitInlineAsm - Handle a call to an InlineAsm object.
10731void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
10732 const BasicBlock *EHPadBB) {
10733 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10734 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
10735 DL: DAG.getDataLayout(), TRI: DAG.getSubtarget().getRegisterInfo(), Call);
10736
10737 assert((!isa<InvokeInst>(Call) || EHPadBB) &&
10738 "InvokeInst must have an EHPadBB");
10739
10740 ConstraintDecisionInfo Info;
10741 if (determineConstraints(Info, TargetConstraints, Call, Builder&: *this, TLI, TM, DAG,
10742 EHPadBB))
10743 return emitInlineAsmError(Call, Message: Info.ErrorMsg.str());
10744
10745 SDValue Glue = Info.Glue;
10746 SDValue Chain = Info.Chain;
10747
10748 // Finish up input operands. Set the input chain and add the flag last.
10749 Info.AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10750 if (Glue.getNode())
10751 Info.AsmNodeOperands.push_back(x: Glue);
10752
10753 bool IsCallBr = isa<CallBrInst>(Val: Call);
10754 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10755 Chain =
10756 DAG.getNode(Opcode: ISDOpc, DL: getCurSDLoc(), VTList: DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue),
10757 Ops: Info.AsmNodeOperands);
10758 Glue = Chain.getValue(R: 1);
10759
10760 // Do additional work to generate outputs.
10761
10762 SmallVector<EVT, 1> ResultVTs;
10763 SmallVector<SDValue, 1> ResultValues;
10764 SmallVector<SDValue, 8> OutChains;
10765
10766 llvm::Type *CallResultType = Call.getType();
10767 ArrayRef<Type *> ResultTypes;
10768 if (StructType *StructResult = dyn_cast<StructType>(Val: CallResultType))
10769 ResultTypes = StructResult->elements();
10770 else if (!CallResultType->isVoidTy())
10771 ResultTypes = ArrayRef(CallResultType);
10772
10773 auto CurResultType = ResultTypes.begin();
10774 auto handleRegAssign = [&](SDValue V) {
10775 assert(CurResultType != ResultTypes.end() && "Unexpected value");
10776 assert((*CurResultType)->isSized() && "Unexpected unsized type");
10777 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: *CurResultType);
10778 ++CurResultType;
10779 // If the type of the inline asm call site return value is different but has
10780 // same size as the type of the asm output bitcast it. One example of this
10781 // is for vectors with different width / number of elements. This can
10782 // happen for register classes that can contain multiple different value
10783 // types. The preg or vreg allocated may not have the same VT as was
10784 // expected.
10785 //
10786 // This can also happen for a return value that disagrees with the register
10787 // class it is put in, eg. a double in a general-purpose register on a
10788 // 32-bit machine.
10789 if (ResultVT != V.getValueType() &&
10790 ResultVT.getSizeInBits() == V.getValueSizeInBits())
10791 V = DAG.getNode(Opcode: ISD::BITCAST, DL: getCurSDLoc(), VT: ResultVT, Operand: V);
10792 else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10793 V.getValueType().isInteger()) {
10794 // If a result value was tied to an input value, the computed result
10795 // may have a wider width than the expected result. Extract the
10796 // relevant portion.
10797 V = DAG.getNode(Opcode: ISD::TRUNCATE, DL: getCurSDLoc(), VT: ResultVT, Operand: V);
10798 }
10799 assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10800 ResultVTs.push_back(Elt: ResultVT);
10801 ResultValues.push_back(Elt: V);
10802 };
10803
10804 // Deal with output operands.
10805 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10806 if (OpInfo.Type == InlineAsm::isOutput) {
10807 SDValue Val;
10808 // Skip trivial output operands.
10809 if (OpInfo.AssignedRegs.Regs.empty())
10810 continue;
10811
10812 switch (OpInfo.ConstraintType) {
10813 case TargetLowering::C_Register:
10814 case TargetLowering::C_RegisterClass:
10815 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, dl: getCurSDLoc(),
10816 Chain, Glue: &Glue, V: &Call);
10817 break;
10818 case TargetLowering::C_Immediate:
10819 case TargetLowering::C_Other:
10820 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, DL: getCurSDLoc(),
10821 OpInfo, DAG);
10822 break;
10823 case TargetLowering::C_Memory:
10824 break; // Already handled.
10825 case TargetLowering::C_Address:
10826 break; // Silence warning.
10827 case TargetLowering::C_Unknown:
10828 assert(false && "Unexpected unknown constraint");
10829 }
10830
10831 // Indirect output manifest as stores. Record output chains.
10832 if (OpInfo.isIndirect) {
10833 const Value *Ptr = OpInfo.CallOperandVal;
10834 assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10835 SDValue Store = DAG.getStore(Chain, dl: getCurSDLoc(), Val, Ptr: getValue(V: Ptr),
10836 PtrInfo: MachinePointerInfo(Ptr));
10837 OutChains.push_back(Elt: Store);
10838 } else {
10839 // generate CopyFromRegs to associated registers.
10840 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10841 if (Val.getOpcode() == ISD::MERGE_VALUES) {
10842 for (const SDValue &V : Val->op_values())
10843 handleRegAssign(V);
10844 } else
10845 handleRegAssign(Val);
10846 }
10847 }
10848 }
10849
10850 // Set results.
10851 if (!ResultValues.empty()) {
10852 assert(CurResultType == ResultTypes.end() &&
10853 "Mismatch in number of ResultTypes");
10854 assert(ResultValues.size() == ResultTypes.size() &&
10855 "Mismatch in number of output operands in asm result");
10856
10857 SDValue V = DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
10858 VTList: DAG.getVTList(VTs: ResultVTs), Ops: ResultValues);
10859 setValue(V: &Call, NewN: V);
10860 }
10861
10862 // Collect store chains.
10863 if (!OutChains.empty())
10864 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: getCurSDLoc(), VT: MVT::Other, Ops: OutChains);
10865
10866 if (const auto *II = dyn_cast<InvokeInst>(Val: &Call))
10867 Chain = lowerEndEH(Chain, II, EHPadBB, BeginLabel: Info.BeginLabel);
10868
10869 // Only Update Root if inline assembly has a memory effect.
10870 if (ResultValues.empty() || Info.HasSideEffect || !OutChains.empty() ||
10871 IsCallBr || isa<InvokeInst>(Val: Call))
10872 DAG.setRoot(Chain);
10873}
10874
10875void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10876 const Twine &Message) {
10877 LLVMContext &Ctx = *DAG.getContext();
10878 Ctx.diagnose(DI: DiagnosticInfoInlineAsm(Call, Message));
10879
10880 // Make sure we leave the DAG in a valid state
10881 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10882 SmallVector<EVT, 1> ValueVTs;
10883 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: Call.getType(), ValueVTs);
10884
10885 if (ValueVTs.empty())
10886 return;
10887
10888 SmallVector<SDValue, 1> Ops;
10889 for (const EVT &VT : ValueVTs)
10890 Ops.push_back(Elt: DAG.getUNDEF(VT));
10891
10892 setValue(V: &Call, NewN: DAG.getMergeValues(Ops, dl: getCurSDLoc()));
10893}
10894
10895void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10896 DAG.setRoot(DAG.getNode(Opcode: ISD::VASTART, DL: getCurSDLoc(),
10897 VT: MVT::Other, N1: getRoot(),
10898 N2: getValue(V: I.getArgOperand(i: 0)),
10899 N3: DAG.getSrcValue(v: I.getArgOperand(i: 0))));
10900}
10901
10902void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10903 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10904 const DataLayout &DL = DAG.getDataLayout();
10905 SDValue V = DAG.getVAArg(
10906 VT: TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getType()), dl: getCurSDLoc(),
10907 Chain: getRoot(), Ptr: getValue(V: I.getOperand(i_nocapture: 0)), SV: DAG.getSrcValue(v: I.getOperand(i_nocapture: 0)),
10908 Align: DL.getABITypeAlign(Ty: I.getType()).value());
10909 DAG.setRoot(V.getValue(R: 1));
10910
10911 if (I.getType()->isPointerTy())
10912 V = DAG.getPtrExtOrTrunc(
10913 Op: V, DL: getCurSDLoc(), VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()));
10914 setValue(V: &I, NewN: V);
10915}
10916
10917void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10918 DAG.setRoot(DAG.getNode(Opcode: ISD::VAEND, DL: getCurSDLoc(),
10919 VT: MVT::Other, N1: getRoot(),
10920 N2: getValue(V: I.getArgOperand(i: 0)),
10921 N3: DAG.getSrcValue(v: I.getArgOperand(i: 0))));
10922}
10923
10924void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10925 DAG.setRoot(DAG.getNode(Opcode: ISD::VACOPY, DL: getCurSDLoc(),
10926 VT: MVT::Other, N1: getRoot(),
10927 N2: getValue(V: I.getArgOperand(i: 0)),
10928 N3: getValue(V: I.getArgOperand(i: 1)),
10929 N4: DAG.getSrcValue(v: I.getArgOperand(i: 0)),
10930 N5: DAG.getSrcValue(v: I.getArgOperand(i: 1))));
10931}
10932
10933SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10934 const Instruction &I,
10935 SDValue Op) {
10936 std::optional<ConstantRange> CR = getRange(I);
10937
10938 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10939 return Op;
10940
10941 APInt Hi = CR->getUnsignedMax();
10942 unsigned Bits = std::max(a: Hi.getActiveBits(),
10943 b: static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10944
10945 EVT SmallVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: Bits);
10946
10947 SDLoc SL = getCurSDLoc();
10948
10949 SDValue ZExt = DAG.getNode(Opcode: ISD::AssertZext, DL: SL, VT: Op.getValueType(), N1: Op,
10950 N2: DAG.getValueType(SmallVT));
10951 unsigned NumVals = Op.getNode()->getNumValues();
10952 if (NumVals == 1)
10953 return ZExt;
10954
10955 SmallVector<SDValue, 4> Ops;
10956
10957 Ops.push_back(Elt: ZExt);
10958 for (unsigned I = 1; I != NumVals; ++I)
10959 Ops.push_back(Elt: Op.getValue(R: I));
10960
10961 return DAG.getMergeValues(Ops, dl: SL);
10962}
10963
10964SDValue SelectionDAGBuilder::lowerNoFPClassToAssertNoFPClass(
10965 SelectionDAG &DAG, const Instruction &I, SDValue Op) {
10966 FPClassTest Classes = getNoFPClass(I);
10967 if (Classes == fcNone)
10968 return Op;
10969
10970 SDLoc SL = getCurSDLoc();
10971 SDValue TestConst = DAG.getTargetConstant(Val: Classes, DL: SDLoc(), VT: MVT::i32);
10972
10973 if (Op.getOpcode() != ISD::MERGE_VALUES) {
10974 return DAG.getNode(Opcode: ISD::AssertNoFPClass, DL: SL, VT: Op.getValueType(), N1: Op,
10975 N2: TestConst);
10976 }
10977
10978 SmallVector<SDValue, 8> Ops(Op.getNumOperands());
10979 for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
10980 SDValue MergeOp = Op.getOperand(i: I);
10981 Ops[I] = DAG.getNode(Opcode: ISD::AssertNoFPClass, DL: SL, VT: MergeOp.getValueType(),
10982 N1: MergeOp, N2: TestConst);
10983 }
10984
10985 return DAG.getMergeValues(Ops, dl: SL);
10986}
10987
10988/// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10989/// the call being lowered.
10990///
10991/// This is a helper for lowering intrinsics that follow a target calling
10992/// convention or require stack pointer adjustment. Only a subset of the
10993/// intrinsic's operands need to participate in the calling convention.
10994void SelectionDAGBuilder::populateCallLoweringInfo(
10995 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10996 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10997 AttributeSet RetAttrs, bool IsPatchPoint) {
10998 TargetLowering::ArgListTy Args;
10999 Args.reserve(n: NumArgs);
11000
11001 // Populate the argument list.
11002 // Attributes for args start at offset 1, after the return attribute.
11003 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
11004 ArgI != ArgE; ++ArgI) {
11005 const Value *V = Call->getOperand(i_nocapture: ArgI);
11006
11007 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
11008
11009 TargetLowering::ArgListEntry Entry(getValue(V), V->getType());
11010 Entry.setAttributes(Call, ArgIdx: ArgI);
11011 Args.push_back(x: Entry);
11012 }
11013
11014 CLI.setDebugLoc(getCurSDLoc())
11015 .setChain(getRoot())
11016 .setCallee(CC: Call->getCallingConv(), ResultType: ReturnTy, Target: Callee, ArgsList: std::move(Args),
11017 ResultAttrs: RetAttrs)
11018 .setDiscardResult(Call->use_empty())
11019 .setIsPatchPoint(IsPatchPoint)
11020 .setIsPreallocated(
11021 Call->countOperandBundlesOfType(ID: LLVMContext::OB_preallocated) != 0);
11022}
11023
11024/// Add a stack map intrinsic call's live variable operands to a stackmap
11025/// or patchpoint target node's operand list.
11026///
11027/// Constants are converted to TargetConstants purely as an optimization to
11028/// avoid constant materialization and register allocation.
11029///
11030/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
11031/// generate addess computation nodes, and so FinalizeISel can convert the
11032/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
11033/// address materialization and register allocation, but may also be required
11034/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
11035/// alloca in the entry block, then the runtime may assume that the alloca's
11036/// StackMap location can be read immediately after compilation and that the
11037/// location is valid at any point during execution (this is similar to the
11038/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
11039/// only available in a register, then the runtime would need to trap when
11040/// execution reaches the StackMap in order to read the alloca's location.
11041static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
11042 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
11043 SelectionDAGBuilder &Builder) {
11044 SelectionDAG &DAG = Builder.DAG;
11045 for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
11046 SDValue Op = Builder.getValue(V: Call.getArgOperand(i: I));
11047
11048 // Things on the stack are pointer-typed, meaning that they are already
11049 // legal and can be emitted directly to target nodes.
11050 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Val&: Op)) {
11051 Ops.push_back(Elt: DAG.getTargetFrameIndex(FI: FI->getIndex(), VT: Op.getValueType()));
11052 } else {
11053 // Otherwise emit a target independent node to be legalised.
11054 Ops.push_back(Elt: Builder.getValue(V: Call.getArgOperand(i: I)));
11055 }
11056 }
11057}
11058
11059/// Lower llvm.experimental.stackmap.
11060void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
11061 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
11062 // [live variables...])
11063
11064 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
11065
11066 SDValue Chain, InGlue, Callee;
11067 SmallVector<SDValue, 32> Ops;
11068
11069 SDLoc DL = getCurSDLoc();
11070 Callee = getValue(V: CI.getCalledOperand());
11071
11072 // The stackmap intrinsic only records the live variables (the arguments
11073 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
11074 // intrinsic, this won't be lowered to a function call. This means we don't
11075 // have to worry about calling conventions and target specific lowering code.
11076 // Instead we perform the call lowering right here.
11077 //
11078 // chain, flag = CALLSEQ_START(chain, 0, 0)
11079 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
11080 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
11081 //
11082 Chain = DAG.getCALLSEQ_START(Chain: getRoot(), InSize: 0, OutSize: 0, DL);
11083 InGlue = Chain.getValue(R: 1);
11084
11085 // Add the STACKMAP operands, starting with DAG house-keeping.
11086 Ops.push_back(Elt: Chain);
11087 Ops.push_back(Elt: InGlue);
11088
11089 // Add the <id>, <numShadowBytes> operands.
11090 //
11091 // These do not require legalisation, and can be emitted directly to target
11092 // constant nodes.
11093 SDValue ID = getValue(V: CI.getArgOperand(i: 0));
11094 assert(ID.getValueType() == MVT::i64);
11095 SDValue IDConst =
11096 DAG.getTargetConstant(Val: ID->getAsZExtVal(), DL, VT: ID.getValueType());
11097 Ops.push_back(Elt: IDConst);
11098
11099 SDValue Shad = getValue(V: CI.getArgOperand(i: 1));
11100 assert(Shad.getValueType() == MVT::i32);
11101 SDValue ShadConst =
11102 DAG.getTargetConstant(Val: Shad->getAsZExtVal(), DL, VT: Shad.getValueType());
11103 Ops.push_back(Elt: ShadConst);
11104
11105 // Add the live variables.
11106 addStackMapLiveVars(Call: CI, StartIdx: 2, DL, Ops, Builder&: *this);
11107
11108 // Create the STACKMAP node.
11109 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
11110 Chain = DAG.getNode(Opcode: ISD::STACKMAP, DL, VTList: NodeTys, Ops);
11111 InGlue = Chain.getValue(R: 1);
11112
11113 Chain = DAG.getCALLSEQ_END(Chain, Size1: 0, Size2: 0, Glue: InGlue, DL);
11114
11115 // Stackmaps don't generate values, so nothing goes into the NodeMap.
11116
11117 // Set the root to the target-lowered call chain.
11118 DAG.setRoot(Chain);
11119
11120 // Inform the Frame Information that we have a stackmap in this function.
11121 FuncInfo.MF->getFrameInfo().setHasStackMap();
11122}
11123
11124/// Lower llvm.experimental.patchpoint directly to its target opcode.
11125void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
11126 const BasicBlock *EHPadBB) {
11127 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
11128 // i32 <numBytes>,
11129 // i8* <target>,
11130 // i32 <numArgs>,
11131 // [Args...],
11132 // [live variables...])
11133
11134 CallingConv::ID CC = CB.getCallingConv();
11135 bool IsAnyRegCC = CC == CallingConv::AnyReg;
11136 bool HasDef = !CB.getType()->isVoidTy();
11137 SDLoc dl = getCurSDLoc();
11138 SDValue Callee = getValue(V: CB.getArgOperand(i: PatchPointOpers::TargetPos));
11139
11140 // Handle immediate and symbolic callees.
11141 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Val&: Callee))
11142 Callee = DAG.getIntPtrConstant(Val: ConstCallee->getZExtValue(), DL: dl,
11143 /*isTarget=*/true);
11144 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Val&: Callee))
11145 Callee = DAG.getTargetGlobalAddress(GV: SymbolicCallee->getGlobal(),
11146 DL: SDLoc(SymbolicCallee),
11147 VT: SymbolicCallee->getValueType(ResNo: 0));
11148
11149 // Get the real number of arguments participating in the call <numArgs>
11150 SDValue NArgVal = getValue(V: CB.getArgOperand(i: PatchPointOpers::NArgPos));
11151 unsigned NumArgs = NArgVal->getAsZExtVal();
11152
11153 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
11154 // Intrinsics include all meta-operands up to but not including CC.
11155 unsigned NumMetaOpers = PatchPointOpers::CCPos;
11156 assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
11157 "Not enough arguments provided to the patchpoint intrinsic");
11158
11159 // For AnyRegCC the arguments are lowered later on manually.
11160 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
11161 Type *ReturnTy =
11162 IsAnyRegCC ? Type::getVoidTy(C&: *DAG.getContext()) : CB.getType();
11163
11164 TargetLowering::CallLoweringInfo CLI(DAG);
11165 populateCallLoweringInfo(CLI, Call: &CB, ArgIdx: NumMetaOpers, NumArgs: NumCallArgs, Callee,
11166 ReturnTy, RetAttrs: CB.getAttributes().getRetAttrs(), IsPatchPoint: true);
11167 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
11168
11169 SDNode *CallEnd = Result.second.getNode();
11170 if (CallEnd->getOpcode() == ISD::EH_LABEL)
11171 CallEnd = CallEnd->getOperand(Num: 0).getNode();
11172 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
11173 CallEnd = CallEnd->getOperand(Num: 0).getNode();
11174
11175 /// Get a call instruction from the call sequence chain.
11176 /// Tail calls are not allowed.
11177 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
11178 "Expected a callseq node.");
11179 SDNode *Call = CallEnd->getOperand(Num: 0).getNode();
11180 bool HasGlue = Call->getGluedNode();
11181
11182 // Replace the target specific call node with the patchable intrinsic.
11183 SmallVector<SDValue, 8> Ops;
11184
11185 // Push the chain.
11186 Ops.push_back(Elt: *(Call->op_begin()));
11187
11188 // Optionally, push the glue (if any).
11189 if (HasGlue)
11190 Ops.push_back(Elt: *(Call->op_end() - 1));
11191
11192 // Push the register mask info.
11193 if (HasGlue)
11194 Ops.push_back(Elt: *(Call->op_end() - 2));
11195 else
11196 Ops.push_back(Elt: *(Call->op_end() - 1));
11197
11198 // Add the <id> and <numBytes> constants.
11199 SDValue IDVal = getValue(V: CB.getArgOperand(i: PatchPointOpers::IDPos));
11200 Ops.push_back(Elt: DAG.getTargetConstant(Val: IDVal->getAsZExtVal(), DL: dl, VT: MVT::i64));
11201 SDValue NBytesVal = getValue(V: CB.getArgOperand(i: PatchPointOpers::NBytesPos));
11202 Ops.push_back(Elt: DAG.getTargetConstant(Val: NBytesVal->getAsZExtVal(), DL: dl, VT: MVT::i32));
11203
11204 // Add the callee.
11205 Ops.push_back(Elt: Callee);
11206
11207 // Adjust <numArgs> to account for any arguments that have been passed on the
11208 // stack instead.
11209 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
11210 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
11211 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
11212 Ops.push_back(Elt: DAG.getTargetConstant(Val: NumCallRegArgs, DL: dl, VT: MVT::i32));
11213
11214 // Add the calling convention
11215 Ops.push_back(Elt: DAG.getTargetConstant(Val: (unsigned)CC, DL: dl, VT: MVT::i32));
11216
11217 // Add the arguments we omitted previously. The register allocator should
11218 // place these in any free register.
11219 if (IsAnyRegCC)
11220 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
11221 Ops.push_back(Elt: getValue(V: CB.getArgOperand(i)));
11222
11223 // Push the arguments from the call instruction.
11224 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
11225 Ops.append(in_start: Call->op_begin() + 2, in_end: e);
11226
11227 // Push live variables for the stack map.
11228 addStackMapLiveVars(Call: CB, StartIdx: NumMetaOpers + NumArgs, DL: dl, Ops, Builder&: *this);
11229
11230 SDVTList NodeTys;
11231 if (IsAnyRegCC && HasDef) {
11232 // Create the return types based on the intrinsic definition
11233 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11234 SmallVector<EVT, 3> ValueVTs;
11235 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: CB.getType(), ValueVTs);
11236 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
11237
11238 // There is always a chain and a glue type at the end
11239 ValueVTs.push_back(Elt: MVT::Other);
11240 ValueVTs.push_back(Elt: MVT::Glue);
11241 NodeTys = DAG.getVTList(VTs: ValueVTs);
11242 } else
11243 NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
11244
11245 // Replace the target specific call node with a PATCHPOINT node.
11246 SDValue PPV = DAG.getNode(Opcode: ISD::PATCHPOINT, DL: dl, VTList: NodeTys, Ops);
11247
11248 // Update the NodeMap.
11249 if (HasDef) {
11250 if (IsAnyRegCC)
11251 setValue(V: &CB, NewN: SDValue(PPV.getNode(), 0));
11252 else
11253 setValue(V: &CB, NewN: Result.first);
11254 }
11255
11256 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
11257 // call sequence. Furthermore the location of the chain and glue can change
11258 // when the AnyReg calling convention is used and the intrinsic returns a
11259 // value.
11260 if (IsAnyRegCC && HasDef) {
11261 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
11262 SDValue To[] = {PPV.getValue(R: 1), PPV.getValue(R: 2)};
11263 DAG.ReplaceAllUsesOfValuesWith(From, To, Num: 2);
11264 } else
11265 DAG.ReplaceAllUsesWith(From: Call, To: PPV.getNode());
11266 DAG.DeleteNode(N: Call);
11267
11268 // Inform the Frame Information that we have a patchpoint in this function.
11269 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
11270}
11271
11272void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
11273 unsigned Intrinsic) {
11274 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11275 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
11276 SDValue Op2;
11277 if (I.arg_size() > 1)
11278 Op2 = getValue(V: I.getArgOperand(i: 1));
11279 SDLoc dl = getCurSDLoc();
11280 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
11281 SDValue Res;
11282 SDNodeFlags SDFlags;
11283 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &I))
11284 SDFlags.copyFMF(FPMO: *FPMO);
11285
11286 switch (Intrinsic) {
11287 case Intrinsic::vector_reduce_fadd:
11288 if (SDFlags.hasAllowReassociation())
11289 Res = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT, N1: Op1,
11290 N2: DAG.getNode(Opcode: ISD::VECREDUCE_FADD, DL: dl, VT, Operand: Op2, Flags: SDFlags),
11291 Flags: SDFlags);
11292 else
11293 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SEQ_FADD, DL: dl, VT, N1: Op1, N2: Op2, Flags: SDFlags);
11294 break;
11295 case Intrinsic::vector_reduce_fmul:
11296 if (SDFlags.hasAllowReassociation())
11297 Res = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT, N1: Op1,
11298 N2: DAG.getNode(Opcode: ISD::VECREDUCE_FMUL, DL: dl, VT, Operand: Op2, Flags: SDFlags),
11299 Flags: SDFlags);
11300 else
11301 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SEQ_FMUL, DL: dl, VT, N1: Op1, N2: Op2, Flags: SDFlags);
11302 break;
11303 case Intrinsic::vector_reduce_add:
11304 Res = DAG.getNode(Opcode: ISD::VECREDUCE_ADD, DL: dl, VT, Operand: Op1);
11305 break;
11306 case Intrinsic::vector_reduce_mul:
11307 Res = DAG.getNode(Opcode: ISD::VECREDUCE_MUL, DL: dl, VT, Operand: Op1);
11308 break;
11309 case Intrinsic::vector_reduce_and:
11310 Res = DAG.getNode(Opcode: ISD::VECREDUCE_AND, DL: dl, VT, Operand: Op1);
11311 break;
11312 case Intrinsic::vector_reduce_or:
11313 Res = DAG.getNode(Opcode: ISD::VECREDUCE_OR, DL: dl, VT, Operand: Op1);
11314 break;
11315 case Intrinsic::vector_reduce_xor:
11316 Res = DAG.getNode(Opcode: ISD::VECREDUCE_XOR, DL: dl, VT, Operand: Op1);
11317 break;
11318 case Intrinsic::vector_reduce_smax:
11319 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SMAX, DL: dl, VT, Operand: Op1);
11320 break;
11321 case Intrinsic::vector_reduce_smin:
11322 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SMIN, DL: dl, VT, Operand: Op1);
11323 break;
11324 case Intrinsic::vector_reduce_umax:
11325 Res = DAG.getNode(Opcode: ISD::VECREDUCE_UMAX, DL: dl, VT, Operand: Op1);
11326 break;
11327 case Intrinsic::vector_reduce_umin:
11328 Res = DAG.getNode(Opcode: ISD::VECREDUCE_UMIN, DL: dl, VT, Operand: Op1);
11329 break;
11330 case Intrinsic::vector_reduce_fmax:
11331 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMAX, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11332 break;
11333 case Intrinsic::vector_reduce_fmin:
11334 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMIN, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11335 break;
11336 case Intrinsic::vector_reduce_fmaximum:
11337 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMAXIMUM, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11338 break;
11339 case Intrinsic::vector_reduce_fminimum:
11340 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMINIMUM, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11341 break;
11342 default:
11343 llvm_unreachable("Unhandled vector reduce intrinsic");
11344 }
11345 setValue(V: &I, NewN: Res);
11346}
11347
11348/// Returns an AttributeList representing the attributes applied to the return
11349/// value of the given call.
11350static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
11351 SmallVector<Attribute::AttrKind, 2> Attrs;
11352 if (CLI.RetSExt)
11353 Attrs.push_back(Elt: Attribute::SExt);
11354 if (CLI.RetZExt)
11355 Attrs.push_back(Elt: Attribute::ZExt);
11356 if (CLI.IsInReg)
11357 Attrs.push_back(Elt: Attribute::InReg);
11358
11359 return AttributeList::get(C&: CLI.RetTy->getContext(), Index: AttributeList::ReturnIndex,
11360 Kinds: Attrs);
11361}
11362
11363/// TargetLowering::LowerCallTo - This is the default LowerCallTo
11364/// implementation, which just calls LowerCall.
11365/// FIXME: When all targets are
11366/// migrated to using LowerCall, this hook should be integrated into SDISel.
11367std::pair<SDValue, SDValue>
11368TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
11369 LLVMContext &Context = CLI.RetTy->getContext();
11370
11371 // Handle the incoming return values from the call.
11372 CLI.Ins.clear();
11373 SmallVector<Type *, 4> RetOrigTys;
11374 SmallVector<TypeSize, 4> Offsets;
11375 auto &DL = CLI.DAG.getDataLayout();
11376 ComputeValueTypes(DL, Ty: CLI.OrigRetTy, Types&: RetOrigTys, Offsets: &Offsets);
11377
11378 SmallVector<EVT, 4> RetVTs;
11379 if (CLI.RetTy != CLI.OrigRetTy) {
11380 assert(RetOrigTys.size() == 1 &&
11381 "Only supported for non-aggregate returns");
11382 RetVTs.push_back(Elt: getValueType(DL, Ty: CLI.RetTy));
11383 } else {
11384 for (Type *Ty : RetOrigTys)
11385 RetVTs.push_back(Elt: getValueType(DL, Ty));
11386 }
11387
11388 if (CLI.IsPostTypeLegalization) {
11389 // If we are lowering a libcall after legalization, split the return type.
11390 SmallVector<Type *, 4> OldRetOrigTys;
11391 SmallVector<EVT, 4> OldRetVTs;
11392 SmallVector<TypeSize, 4> OldOffsets;
11393 RetOrigTys.swap(RHS&: OldRetOrigTys);
11394 RetVTs.swap(RHS&: OldRetVTs);
11395 Offsets.swap(RHS&: OldOffsets);
11396
11397 for (size_t i = 0, e = OldRetVTs.size(); i != e; ++i) {
11398 EVT RetVT = OldRetVTs[i];
11399 uint64_t Offset = OldOffsets[i];
11400 MVT RegisterVT = getRegisterType(Context, VT: RetVT);
11401 unsigned NumRegs = getNumRegisters(Context, VT: RetVT);
11402 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
11403 RetOrigTys.append(NumInputs: NumRegs, Elt: OldRetOrigTys[i]);
11404 RetVTs.append(NumInputs: NumRegs, Elt: RegisterVT);
11405 for (unsigned j = 0; j != NumRegs; ++j)
11406 Offsets.push_back(Elt: TypeSize::getFixed(ExactSize: Offset + j * RegisterVTByteSZ));
11407 }
11408 }
11409
11410 SmallVector<ISD::OutputArg, 4> Outs;
11411 GetReturnInfo(CC: CLI.CallConv, ReturnType: CLI.RetTy, attr: getReturnAttrs(CLI), Outs, TLI: *this, DL);
11412
11413 bool CanLowerReturn =
11414 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
11415 CLI.IsVarArg, Outs, Context, RetTy: CLI.RetTy);
11416
11417 SDValue DemoteStackSlot;
11418 int DemoteStackIdx = -100;
11419 if (!CanLowerReturn) {
11420 // FIXME: equivalent assert?
11421 // assert(!CS.hasInAllocaArgument() &&
11422 // "sret demotion is incompatible with inalloca");
11423 uint64_t TySize = DL.getTypeAllocSize(Ty: CLI.RetTy);
11424 Align Alignment = DL.getPrefTypeAlign(Ty: CLI.RetTy);
11425 MachineFunction &MF = CLI.DAG.getMachineFunction();
11426 DemoteStackIdx =
11427 MF.getFrameInfo().CreateStackObject(Size: TySize, Alignment, isSpillSlot: false);
11428 Type *StackSlotPtrType = PointerType::get(C&: Context, AddressSpace: DL.getAllocaAddrSpace());
11429
11430 DemoteStackSlot = CLI.DAG.getFrameIndex(FI: DemoteStackIdx, VT: getFrameIndexTy(DL));
11431 ArgListEntry Entry(DemoteStackSlot, StackSlotPtrType);
11432 Entry.IsSRet = true;
11433 Entry.Alignment = Alignment;
11434 CLI.getArgs().insert(position: CLI.getArgs().begin(), x: Entry);
11435 CLI.NumFixedArgs += 1;
11436 CLI.getArgs()[0].IndirectType = CLI.RetTy;
11437 CLI.RetTy = CLI.OrigRetTy = Type::getVoidTy(C&: Context);
11438
11439 // sret demotion isn't compatible with tail-calls, since the sret argument
11440 // points into the callers stack frame.
11441 CLI.IsTailCall = false;
11442 } else {
11443 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11444 Ty: CLI.RetTy, CallConv: CLI.CallConv, isVarArg: CLI.IsVarArg, DL);
11445 for (unsigned I = 0, E = RetVTs.size(); I != E; ++I) {
11446 ISD::ArgFlagsTy Flags;
11447 if (NeedsRegBlock) {
11448 Flags.setInConsecutiveRegs();
11449 if (I == RetVTs.size() - 1)
11450 Flags.setInConsecutiveRegsLast();
11451 }
11452 EVT VT = RetVTs[I];
11453 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CC: CLI.CallConv, VT);
11454 unsigned NumRegs =
11455 getNumRegistersForCallingConv(Context, CC: CLI.CallConv, VT);
11456 for (unsigned i = 0; i != NumRegs; ++i) {
11457 ISD::InputArg Ret(Flags, RegisterVT, VT, RetOrigTys[I],
11458 CLI.IsReturnValueUsed, ISD::InputArg::NoArgIndex, 0);
11459 if (CLI.RetTy->isPointerTy()) {
11460 Ret.Flags.setPointer();
11461 Ret.Flags.setPointerAddrSpace(
11462 cast<PointerType>(Val: CLI.RetTy)->getAddressSpace());
11463 }
11464 if (CLI.RetSExt)
11465 Ret.Flags.setSExt();
11466 if (CLI.RetZExt)
11467 Ret.Flags.setZExt();
11468 if (CLI.IsInReg)
11469 Ret.Flags.setInReg();
11470 CLI.Ins.push_back(Elt: Ret);
11471 }
11472 }
11473 }
11474
11475 // We push in swifterror return as the last element of CLI.Ins.
11476 ArgListTy &Args = CLI.getArgs();
11477 if (supportSwiftError()) {
11478 for (const ArgListEntry &Arg : Args) {
11479 if (Arg.IsSwiftError) {
11480 ISD::ArgFlagsTy Flags;
11481 Flags.setSwiftError();
11482 ISD::InputArg Ret(Flags, getPointerTy(DL), EVT(getPointerTy(DL)),
11483 PointerType::getUnqual(C&: Context),
11484 /*Used=*/true, ISD::InputArg::NoArgIndex, 0);
11485 CLI.Ins.push_back(Elt: Ret);
11486 }
11487 }
11488 }
11489
11490 // Handle all of the outgoing arguments.
11491 CLI.Outs.clear();
11492 CLI.OutVals.clear();
11493 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11494 SmallVector<Type *, 4> OrigArgTys;
11495 ComputeValueTypes(DL, Ty: Args[i].OrigTy, Types&: OrigArgTys);
11496 // FIXME: Split arguments if CLI.IsPostTypeLegalization
11497 Type *FinalType = Args[i].Ty;
11498 if (Args[i].IsByVal)
11499 FinalType = Args[i].IndirectType;
11500 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11501 Ty: FinalType, CallConv: CLI.CallConv, isVarArg: CLI.IsVarArg, DL);
11502 for (unsigned Value = 0, NumValues = OrigArgTys.size(); Value != NumValues;
11503 ++Value) {
11504 Type *OrigArgTy = OrigArgTys[Value];
11505 Type *ArgTy = OrigArgTy;
11506 if (Args[i].Ty != Args[i].OrigTy) {
11507 assert(Value == 0 && "Only supported for non-aggregate arguments");
11508 ArgTy = Args[i].Ty;
11509 }
11510
11511 EVT VT = getValueType(DL, Ty: ArgTy);
11512 SDValue Op = SDValue(Args[i].Node.getNode(),
11513 Args[i].Node.getResNo() + Value);
11514 ISD::ArgFlagsTy Flags;
11515
11516 // Certain targets (such as MIPS), may have a different ABI alignment
11517 // for a type depending on the context. Give the target a chance to
11518 // specify the alignment it wants.
11519 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11520 Flags.setOrigAlign(OriginalAlignment);
11521
11522 if (i >= CLI.NumFixedArgs)
11523 Flags.setVarArg();
11524 if (ArgTy->isPointerTy()) {
11525 Flags.setPointer();
11526 Flags.setPointerAddrSpace(cast<PointerType>(Val: ArgTy)->getAddressSpace());
11527 }
11528 if (Args[i].IsZExt)
11529 Flags.setZExt();
11530 if (Args[i].IsSExt)
11531 Flags.setSExt();
11532 if (Args[i].IsNoExt)
11533 Flags.setNoExt();
11534 if (Args[i].IsInReg) {
11535 // If we are using vectorcall calling convention, a structure that is
11536 // passed InReg - is surely an HVA
11537 if (CLI.CallConv == CallingConv::X86_VectorCall &&
11538 isa<StructType>(Val: FinalType)) {
11539 // The first value of a structure is marked
11540 if (0 == Value)
11541 Flags.setHvaStart();
11542 Flags.setHva();
11543 }
11544 // Set InReg Flag
11545 Flags.setInReg();
11546 }
11547 if (Args[i].IsSRet)
11548 Flags.setSRet();
11549 if (Args[i].IsSwiftSelf)
11550 Flags.setSwiftSelf();
11551 if (Args[i].IsSwiftAsync)
11552 Flags.setSwiftAsync();
11553 if (Args[i].IsSwiftError)
11554 Flags.setSwiftError();
11555 if (Args[i].IsCFGuardTarget)
11556 Flags.setCFGuardTarget();
11557 if (Args[i].IsByVal)
11558 Flags.setByVal();
11559 if (Args[i].IsByRef)
11560 Flags.setByRef();
11561 if (Args[i].IsPreallocated) {
11562 Flags.setPreallocated();
11563 // Set the byval flag for CCAssignFn callbacks that don't know about
11564 // preallocated. This way we can know how many bytes we should've
11565 // allocated and how many bytes a callee cleanup function will pop. If
11566 // we port preallocated to more targets, we'll have to add custom
11567 // preallocated handling in the various CC lowering callbacks.
11568 Flags.setByVal();
11569 }
11570 if (Args[i].IsInAlloca) {
11571 Flags.setInAlloca();
11572 // Set the byval flag for CCAssignFn callbacks that don't know about
11573 // inalloca. This way we can know how many bytes we should've allocated
11574 // and how many bytes a callee cleanup function will pop. If we port
11575 // inalloca to more targets, we'll have to add custom inalloca handling
11576 // in the various CC lowering callbacks.
11577 Flags.setByVal();
11578 }
11579 Align MemAlign;
11580 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11581 unsigned FrameSize = DL.getTypeAllocSize(Ty: Args[i].IndirectType);
11582 Flags.setByValSize(FrameSize);
11583
11584 // info is not there but there are cases it cannot get right.
11585 if (auto MA = Args[i].Alignment)
11586 MemAlign = *MA;
11587 else
11588 MemAlign = getByValTypeAlignment(Ty: Args[i].IndirectType, DL);
11589 } else if (auto MA = Args[i].Alignment) {
11590 MemAlign = *MA;
11591 } else {
11592 MemAlign = OriginalAlignment;
11593 }
11594 Flags.setMemAlign(MemAlign);
11595 if (Args[i].IsNest)
11596 Flags.setNest();
11597 if (NeedsRegBlock)
11598 Flags.setInConsecutiveRegs();
11599
11600 MVT PartVT = getRegisterTypeForCallingConv(Context, CC: CLI.CallConv, VT);
11601 unsigned NumParts =
11602 getNumRegistersForCallingConv(Context, CC: CLI.CallConv, VT);
11603 SmallVector<SDValue, 4> Parts(NumParts);
11604 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11605
11606 if (Args[i].IsSExt)
11607 ExtendKind = ISD::SIGN_EXTEND;
11608 else if (Args[i].IsZExt)
11609 ExtendKind = ISD::ZERO_EXTEND;
11610
11611 // Conservatively only handle 'returned' on non-vectors that can be lowered,
11612 // for now.
11613 if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11614 CanLowerReturn) {
11615 assert((CLI.RetTy == Args[i].Ty ||
11616 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11617 CLI.RetTy->getPointerAddressSpace() ==
11618 Args[i].Ty->getPointerAddressSpace())) &&
11619 RetVTs.size() == NumValues && "unexpected use of 'returned'");
11620 // Before passing 'returned' to the target lowering code, ensure that
11621 // either the register MVT and the actual EVT are the same size or that
11622 // the return value and argument are extended in the same way; in these
11623 // cases it's safe to pass the argument register value unchanged as the
11624 // return register value (although it's at the target's option whether
11625 // to do so)
11626 // TODO: allow code generation to take advantage of partially preserved
11627 // registers rather than clobbering the entire register when the
11628 // parameter extension method is not compatible with the return
11629 // extension method
11630 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11631 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11632 CLI.RetZExt == Args[i].IsZExt))
11633 Flags.setReturned();
11634 }
11635
11636 getCopyToParts(DAG&: CLI.DAG, DL: CLI.DL, Val: Op, Parts: &Parts[0], NumParts, PartVT, V: CLI.CB,
11637 CallConv: CLI.CallConv, ExtendKind);
11638
11639 for (unsigned j = 0; j != NumParts; ++j) {
11640 // if it isn't first piece, alignment must be 1
11641 // For scalable vectors the scalable part is currently handled
11642 // by individual targets, so we just use the known minimum size here.
11643 ISD::OutputArg MyFlags(
11644 Flags, Parts[j].getValueType().getSimpleVT(), VT, OrigArgTy, i,
11645 j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11646 if (NumParts > 1 && j == 0)
11647 MyFlags.Flags.setSplit();
11648 else if (j != 0) {
11649 MyFlags.Flags.setOrigAlign(Align(1));
11650 if (j == NumParts - 1)
11651 MyFlags.Flags.setSplitEnd();
11652 }
11653
11654 CLI.Outs.push_back(Elt: MyFlags);
11655 CLI.OutVals.push_back(Elt: Parts[j]);
11656 }
11657
11658 if (NeedsRegBlock && Value == NumValues - 1)
11659 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11660 }
11661 }
11662
11663 SmallVector<SDValue, 4> InVals;
11664 CLI.Chain = LowerCall(CLI, InVals);
11665
11666 // Update CLI.InVals to use outside of this function.
11667 CLI.InVals = InVals;
11668
11669 // Verify that the target's LowerCall behaved as expected.
11670 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11671 "LowerCall didn't return a valid chain!");
11672 assert((!CLI.IsTailCall || InVals.empty()) &&
11673 "LowerCall emitted a return value for a tail call!");
11674 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11675 "LowerCall didn't emit the correct number of values!");
11676
11677 // For a tail call, the return value is merely live-out and there aren't
11678 // any nodes in the DAG representing it. Return a special value to
11679 // indicate that a tail call has been emitted and no more Instructions
11680 // should be processed in the current block.
11681 if (CLI.IsTailCall) {
11682 CLI.DAG.setRoot(CLI.Chain);
11683 return std::make_pair(x: SDValue(), y: SDValue());
11684 }
11685
11686#ifndef NDEBUG
11687 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11688 assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11689 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11690 "LowerCall emitted a value with the wrong type!");
11691 }
11692#endif
11693
11694 SmallVector<SDValue, 4> ReturnValues;
11695 if (!CanLowerReturn) {
11696 // The instruction result is the result of loading from the
11697 // hidden sret parameter.
11698 MVT PtrVT = getPointerTy(DL, AS: DL.getAllocaAddrSpace());
11699
11700 unsigned NumValues = RetVTs.size();
11701 ReturnValues.resize(N: NumValues);
11702 SmallVector<SDValue, 4> Chains(NumValues);
11703
11704 // An aggregate return value cannot wrap around the address space, so
11705 // offsets to its parts don't wrap either.
11706 MachineFunction &MF = CLI.DAG.getMachineFunction();
11707 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(ObjectIdx: DemoteStackIdx);
11708 for (unsigned i = 0; i < NumValues; ++i) {
11709 SDValue Add = CLI.DAG.getMemBasePlusOffset(
11710 Base: DemoteStackSlot, Offset: CLI.DAG.getConstant(Val: Offsets[i], DL: CLI.DL, VT: PtrVT),
11711 DL: CLI.DL, Flags: SDNodeFlags::NoUnsignedWrap);
11712 SDValue L = CLI.DAG.getLoad(
11713 VT: RetVTs[i], dl: CLI.DL, Chain: CLI.Chain, Ptr: Add,
11714 PtrInfo: MachinePointerInfo::getFixedStack(MF&: CLI.DAG.getMachineFunction(),
11715 FI: DemoteStackIdx, Offset: Offsets[i]),
11716 Alignment: HiddenSRetAlign);
11717 ReturnValues[i] = L;
11718 Chains[i] = L.getValue(R: 1);
11719 }
11720
11721 CLI.Chain = CLI.DAG.getNode(Opcode: ISD::TokenFactor, DL: CLI.DL, VT: MVT::Other, Ops: Chains);
11722 } else {
11723 // Collect the legal value parts into potentially illegal values
11724 // that correspond to the original function's return values.
11725 std::optional<ISD::NodeType> AssertOp;
11726 if (CLI.RetSExt)
11727 AssertOp = ISD::AssertSext;
11728 else if (CLI.RetZExt)
11729 AssertOp = ISD::AssertZext;
11730 unsigned CurReg = 0;
11731 for (EVT VT : RetVTs) {
11732 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CC: CLI.CallConv, VT);
11733 unsigned NumRegs =
11734 getNumRegistersForCallingConv(Context, CC: CLI.CallConv, VT);
11735
11736 ReturnValues.push_back(Elt: getCopyFromParts(
11737 DAG&: CLI.DAG, DL: CLI.DL, Parts: &InVals[CurReg], NumParts: NumRegs, PartVT: RegisterVT, ValueVT: VT, V: nullptr,
11738 InChain: CLI.Chain, CC: CLI.CallConv, AssertOp));
11739 CurReg += NumRegs;
11740 }
11741
11742 // For a function returning void, there is no return value. We can't create
11743 // such a node, so we just return a null return value in that case. In
11744 // that case, nothing will actually look at the value.
11745 if (ReturnValues.empty())
11746 return std::make_pair(x: SDValue(), y&: CLI.Chain);
11747 }
11748
11749 SDValue Res = CLI.DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: CLI.DL,
11750 VTList: CLI.DAG.getVTList(VTs: RetVTs), Ops: ReturnValues);
11751 return std::make_pair(x&: Res, y&: CLI.Chain);
11752}
11753
11754/// Places new result values for the node in Results (their number
11755/// and types must exactly match those of the original return values of
11756/// the node), or leaves Results empty, which indicates that the node is not
11757/// to be custom lowered after all.
11758void TargetLowering::LowerOperationWrapper(SDNode *N,
11759 SmallVectorImpl<SDValue> &Results,
11760 SelectionDAG &DAG) const {
11761 SDValue Res = LowerOperation(Op: SDValue(N, 0), DAG);
11762
11763 if (!Res.getNode())
11764 return;
11765
11766 // If the original node has one result, take the return value from
11767 // LowerOperation as is. It might not be result number 0.
11768 if (N->getNumValues() == 1) {
11769 Results.push_back(Elt: Res);
11770 return;
11771 }
11772
11773 // If the original node has multiple results, then the return node should
11774 // have the same number of results.
11775 assert((N->getNumValues() == Res->getNumValues()) &&
11776 "Lowering returned the wrong number of results!");
11777
11778 // Places new result values base on N result number.
11779 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11780 Results.push_back(Elt: Res.getValue(R: I));
11781}
11782
11783SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11784 llvm_unreachable("LowerOperation not implemented for this target!");
11785}
11786
11787void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11788 Register Reg,
11789 ISD::NodeType ExtendType) {
11790 SDValue Op = getNonRegisterValue(V);
11791 assert((Op.getOpcode() != ISD::CopyFromReg ||
11792 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11793 "Copy from a reg to the same reg!");
11794 assert(!Reg.isPhysical() && "Is a physreg");
11795
11796 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11797 // If this is an InlineAsm we have to match the registers required, not the
11798 // notional registers required by the type.
11799
11800 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11801 std::nullopt); // This is not an ABI copy.
11802 SDValue Chain = DAG.getEntryNode();
11803
11804 if (ExtendType == ISD::ANY_EXTEND) {
11805 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(Val: V);
11806 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11807 ExtendType = PreferredExtendIt->second;
11808 }
11809 RFV.getCopyToRegs(Val: Op, DAG, dl: getCurSDLoc(), Chain, Glue: nullptr, V, PreferredExtendType: ExtendType);
11810 PendingExports.push_back(Elt: Chain);
11811}
11812
11813#include "llvm/CodeGen/SelectionDAGISel.h"
11814
11815/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11816/// entry block, return true. This includes arguments used by switches, since
11817/// the switch may expand into multiple basic blocks.
11818static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11819 // With FastISel active, we may be splitting blocks, so force creation
11820 // of virtual registers for all non-dead arguments.
11821 if (FastISel)
11822 return A->use_empty();
11823
11824 const BasicBlock &Entry = A->getParent()->front();
11825 for (const User *U : A->users())
11826 if (cast<Instruction>(Val: U)->getParent() != &Entry || isa<SwitchInst>(Val: U))
11827 return false; // Use not in entry block.
11828
11829 return true;
11830}
11831
11832using ArgCopyElisionMapTy =
11833 DenseMap<const Argument *,
11834 std::pair<const AllocaInst *, const StoreInst *>>;
11835
11836/// Scan the entry block of the function in FuncInfo for arguments that look
11837/// like copies into a local alloca. Record any copied arguments in
11838/// ArgCopyElisionCandidates.
11839static void
11840findArgumentCopyElisionCandidates(const DataLayout &DL,
11841 FunctionLoweringInfo *FuncInfo,
11842 ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11843 // Record the state of every static alloca used in the entry block. Argument
11844 // allocas are all used in the entry block, so we need approximately as many
11845 // entries as we have arguments.
11846 enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11847 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11848 unsigned NumArgs = FuncInfo->Fn->arg_size();
11849 StaticAllocas.reserve(NumEntries: NumArgs * 2);
11850
11851 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11852 if (!V)
11853 return nullptr;
11854 V = V->stripPointerCasts();
11855 const auto *AI = dyn_cast<AllocaInst>(Val: V);
11856 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(Val: AI))
11857 return nullptr;
11858 auto Iter = StaticAllocas.insert(KV: {AI, Unknown});
11859 return &Iter.first->second;
11860 };
11861
11862 // Look for stores of arguments to static allocas. Look through bitcasts and
11863 // GEPs to handle type coercions, as long as the alloca is fully initialized
11864 // by the store. Any non-store use of an alloca escapes it and any subsequent
11865 // unanalyzed store might write it.
11866 // FIXME: Handle structs initialized with multiple stores.
11867 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11868 // Look for stores, and handle non-store uses conservatively.
11869 const auto *SI = dyn_cast<StoreInst>(Val: &I);
11870 if (!SI) {
11871 // We will look through cast uses, so ignore them completely.
11872 if (I.isCast())
11873 continue;
11874 // Ignore debug info and pseudo op intrinsics, they don't escape or store
11875 // to allocas.
11876 if (I.isDebugOrPseudoInst())
11877 continue;
11878 // This is an unknown instruction. Assume it escapes or writes to all
11879 // static alloca operands.
11880 for (const Use &U : I.operands()) {
11881 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11882 *Info = StaticAllocaInfo::Clobbered;
11883 }
11884 continue;
11885 }
11886
11887 // If the stored value is a static alloca, mark it as escaped.
11888 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11889 *Info = StaticAllocaInfo::Clobbered;
11890
11891 // Check if the destination is a static alloca.
11892 const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11893 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11894 if (!Info)
11895 continue;
11896 const AllocaInst *AI = cast<AllocaInst>(Val: Dst);
11897
11898 // Skip allocas that have been initialized or clobbered.
11899 if (*Info != StaticAllocaInfo::Unknown)
11900 continue;
11901
11902 // Check if the stored value is an argument, and that this store fully
11903 // initializes the alloca.
11904 // If the argument type has padding bits we can't directly forward a pointer
11905 // as the upper bits may contain garbage.
11906 // Don't elide copies from the same argument twice.
11907 const Value *Val = SI->getValueOperand()->stripPointerCasts();
11908 const auto *Arg = dyn_cast<Argument>(Val);
11909 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL);
11910 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11911 Arg->getType()->isEmptyTy() || !AllocaSize ||
11912 DL.getTypeStoreSize(Ty: Arg->getType()) != *AllocaSize ||
11913 !DL.typeSizeEqualsStoreSize(Ty: Arg->getType()) ||
11914 ArgCopyElisionCandidates.count(Val: Arg)) {
11915 *Info = StaticAllocaInfo::Clobbered;
11916 continue;
11917 }
11918
11919 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11920 << '\n');
11921
11922 // Mark this alloca and store for argument copy elision.
11923 *Info = StaticAllocaInfo::Elidable;
11924 ArgCopyElisionCandidates.insert(KV: {Arg, {AI, SI}});
11925
11926 // Stop scanning if we've seen all arguments. This will happen early in -O0
11927 // builds, which is useful, because -O0 builds have large entry blocks and
11928 // many allocas.
11929 if (ArgCopyElisionCandidates.size() == NumArgs)
11930 break;
11931 }
11932}
11933
11934/// Try to elide argument copies from memory into a local alloca. Succeeds if
11935/// ArgVal is a load from a suitable fixed stack object.
11936static void tryToElideArgumentCopy(
11937 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11938 DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11939 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11940 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11941 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11942 // Check if this is a load from a fixed stack object.
11943 auto *LNode = dyn_cast<LoadSDNode>(Val: ArgVals[0]);
11944 if (!LNode)
11945 return;
11946 auto *FINode = dyn_cast<FrameIndexSDNode>(Val: LNode->getBasePtr().getNode());
11947 if (!FINode)
11948 return;
11949
11950 // Check that the fixed stack object is the right size and alignment.
11951 // Look at the alignment that the user wrote on the alloca instead of looking
11952 // at the stack object.
11953 auto ArgCopyIter = ArgCopyElisionCandidates.find(Val: &Arg);
11954 assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11955 const AllocaInst *AI = ArgCopyIter->second.first;
11956 int FixedIndex = FINode->getIndex();
11957 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11958 int OldIndex = AllocaIndex;
11959 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11960 if (MFI.getObjectSize(ObjectIdx: FixedIndex) != MFI.getObjectSize(ObjectIdx: OldIndex)) {
11961 LLVM_DEBUG(
11962 dbgs() << " argument copy elision failed due to bad fixed stack "
11963 "object size\n");
11964 return;
11965 }
11966 Align RequiredAlignment = AI->getAlign();
11967 if (MFI.getObjectAlign(ObjectIdx: FixedIndex) < RequiredAlignment) {
11968 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
11969 "greater than stack argument alignment ("
11970 << DebugStr(RequiredAlignment) << " vs "
11971 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11972 return;
11973 }
11974
11975 // Perform the elision. Delete the old stack object and replace its only use
11976 // in the variable info map. Mark the stack object as mutable and aliased.
11977 LLVM_DEBUG({
11978 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11979 << " Replacing frame index " << OldIndex << " with " << FixedIndex
11980 << '\n';
11981 });
11982 MFI.RemoveStackObject(ObjectIdx: OldIndex);
11983 MFI.setIsImmutableObjectIndex(ObjectIdx: FixedIndex, IsImmutable: false);
11984 MFI.setIsAliasedObjectIndex(ObjectIdx: FixedIndex, IsAliased: true);
11985 AllocaIndex = FixedIndex;
11986 ArgCopyElisionFrameIndexMap.insert(KV: {OldIndex, FixedIndex});
11987 for (SDValue ArgVal : ArgVals)
11988 Chains.push_back(Elt: ArgVal.getValue(R: 1));
11989
11990 // Avoid emitting code for the store implementing the copy.
11991 const StoreInst *SI = ArgCopyIter->second.second;
11992 ElidedArgCopyInstrs.insert(Ptr: SI);
11993
11994 // Check for uses of the argument again so that we can avoid exporting ArgVal
11995 // if it is't used by anything other than the store.
11996 for (const Value *U : Arg.users()) {
11997 if (U != SI) {
11998 ArgHasUses = true;
11999 break;
12000 }
12001 }
12002}
12003
12004void SelectionDAGISel::LowerArguments(const Function &F) {
12005 SelectionDAG &DAG = SDB->DAG;
12006 SDLoc dl = SDB->getCurSDLoc();
12007 const DataLayout &DL = DAG.getDataLayout();
12008 SmallVector<ISD::InputArg, 16> Ins;
12009
12010 // In Naked functions we aren't going to save any registers.
12011 if (F.hasFnAttribute(Kind: Attribute::Naked))
12012 return;
12013
12014 if (!FuncInfo->CanLowerReturn) {
12015 // Put in an sret pointer parameter before all the other parameters.
12016 MVT ValueVT = TLI->getPointerTy(DL, AS: DL.getAllocaAddrSpace());
12017
12018 ISD::ArgFlagsTy Flags;
12019 Flags.setSRet();
12020 MVT RegisterVT = TLI->getRegisterType(Context&: *DAG.getContext(), VT: ValueVT);
12021 ISD::InputArg RetArg(Flags, RegisterVT, ValueVT, F.getReturnType(), true,
12022 ISD::InputArg::NoArgIndex, 0);
12023 Ins.push_back(Elt: RetArg);
12024 }
12025
12026 // Look for stores of arguments to static allocas. Mark such arguments with a
12027 // flag to ask the target to give us the memory location of that argument if
12028 // available.
12029 ArgCopyElisionMapTy ArgCopyElisionCandidates;
12030 findArgumentCopyElisionCandidates(DL, FuncInfo: FuncInfo.get(),
12031 ArgCopyElisionCandidates);
12032
12033 // Set up the incoming argument description vector.
12034 for (const Argument &Arg : F.args()) {
12035 unsigned ArgNo = Arg.getArgNo();
12036 SmallVector<Type *, 4> Types;
12037 ComputeValueTypes(DL: DAG.getDataLayout(), Ty: Arg.getType(), Types);
12038 bool isArgValueUsed = !Arg.use_empty();
12039 Type *FinalType = Arg.getType();
12040 if (Arg.hasAttribute(Kind: Attribute::ByVal))
12041 FinalType = Arg.getParamByValType();
12042 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
12043 Ty: FinalType, CallConv: F.getCallingConv(), isVarArg: F.isVarArg(), DL);
12044 for (unsigned Value = 0, NumValues = Types.size(); Value != NumValues;
12045 ++Value) {
12046 Type *ArgTy = Types[Value];
12047 EVT VT = TLI->getValueType(DL, Ty: ArgTy);
12048 ISD::ArgFlagsTy Flags;
12049
12050 if (ArgTy->isPointerTy()) {
12051 Flags.setPointer();
12052 Flags.setPointerAddrSpace(cast<PointerType>(Val: ArgTy)->getAddressSpace());
12053 }
12054 if (Arg.hasAttribute(Kind: Attribute::ZExt))
12055 Flags.setZExt();
12056 if (Arg.hasAttribute(Kind: Attribute::SExt))
12057 Flags.setSExt();
12058 if (Arg.hasAttribute(Kind: Attribute::InReg)) {
12059 // If we are using vectorcall calling convention, a structure that is
12060 // passed InReg - is surely an HVA
12061 if (F.getCallingConv() == CallingConv::X86_VectorCall &&
12062 isa<StructType>(Val: Arg.getType())) {
12063 // The first value of a structure is marked
12064 if (0 == Value)
12065 Flags.setHvaStart();
12066 Flags.setHva();
12067 }
12068 // Set InReg Flag
12069 Flags.setInReg();
12070 }
12071 if (Arg.hasAttribute(Kind: Attribute::StructRet))
12072 Flags.setSRet();
12073 if (Arg.hasAttribute(Kind: Attribute::SwiftSelf))
12074 Flags.setSwiftSelf();
12075 if (Arg.hasAttribute(Kind: Attribute::SwiftAsync))
12076 Flags.setSwiftAsync();
12077 if (Arg.hasAttribute(Kind: Attribute::SwiftError))
12078 Flags.setSwiftError();
12079 if (Arg.hasAttribute(Kind: Attribute::ByVal))
12080 Flags.setByVal();
12081 if (Arg.hasAttribute(Kind: Attribute::ByRef))
12082 Flags.setByRef();
12083 if (Arg.hasAttribute(Kind: Attribute::InAlloca)) {
12084 Flags.setInAlloca();
12085 // Set the byval flag for CCAssignFn callbacks that don't know about
12086 // inalloca. This way we can know how many bytes we should've allocated
12087 // and how many bytes a callee cleanup function will pop. If we port
12088 // inalloca to more targets, we'll have to add custom inalloca handling
12089 // in the various CC lowering callbacks.
12090 Flags.setByVal();
12091 }
12092 if (Arg.hasAttribute(Kind: Attribute::Preallocated)) {
12093 Flags.setPreallocated();
12094 // Set the byval flag for CCAssignFn callbacks that don't know about
12095 // preallocated. This way we can know how many bytes we should've
12096 // allocated and how many bytes a callee cleanup function will pop. If
12097 // we port preallocated to more targets, we'll have to add custom
12098 // preallocated handling in the various CC lowering callbacks.
12099 Flags.setByVal();
12100 }
12101
12102 // Certain targets (such as MIPS), may have a different ABI alignment
12103 // for a type depending on the context. Give the target a chance to
12104 // specify the alignment it wants.
12105 const Align OriginalAlignment(
12106 TLI->getABIAlignmentForCallingConv(ArgTy, DL));
12107 Flags.setOrigAlign(OriginalAlignment);
12108
12109 Align MemAlign;
12110 Type *ArgMemTy = nullptr;
12111 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
12112 Flags.isByRef()) {
12113 if (!ArgMemTy)
12114 ArgMemTy = Arg.getPointeeInMemoryValueType();
12115
12116 uint64_t MemSize = DL.getTypeAllocSize(Ty: ArgMemTy);
12117
12118 // For in-memory arguments, size and alignment should be passed from FE.
12119 // BE will guess if this info is not there but there are cases it cannot
12120 // get right.
12121 if (auto ParamAlign = Arg.getParamStackAlign())
12122 MemAlign = *ParamAlign;
12123 else if ((ParamAlign = Arg.getParamAlign()))
12124 MemAlign = *ParamAlign;
12125 else
12126 MemAlign = TLI->getByValTypeAlignment(Ty: ArgMemTy, DL);
12127 if (Flags.isByRef())
12128 Flags.setByRefSize(MemSize);
12129 else
12130 Flags.setByValSize(MemSize);
12131 } else if (auto ParamAlign = Arg.getParamStackAlign()) {
12132 MemAlign = *ParamAlign;
12133 } else {
12134 MemAlign = OriginalAlignment;
12135 }
12136 Flags.setMemAlign(MemAlign);
12137
12138 if (Arg.hasAttribute(Kind: Attribute::Nest))
12139 Flags.setNest();
12140 if (NeedsRegBlock)
12141 Flags.setInConsecutiveRegs();
12142 if (ArgCopyElisionCandidates.count(Val: &Arg))
12143 Flags.setCopyElisionCandidate();
12144 if (Arg.hasAttribute(Kind: Attribute::Returned))
12145 Flags.setReturned();
12146
12147 MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
12148 Context&: *CurDAG->getContext(), CC: F.getCallingConv(), VT);
12149 unsigned NumRegs = TLI->getNumRegistersForCallingConv(
12150 Context&: *CurDAG->getContext(), CC: F.getCallingConv(), VT);
12151 for (unsigned i = 0; i != NumRegs; ++i) {
12152 // For scalable vectors, use the minimum size; individual targets
12153 // are responsible for handling scalable vector arguments and
12154 // return values.
12155 ISD::InputArg MyFlags(
12156 Flags, RegisterVT, VT, ArgTy, isArgValueUsed, ArgNo,
12157 i * RegisterVT.getStoreSize().getKnownMinValue());
12158 if (NumRegs > 1 && i == 0)
12159 MyFlags.Flags.setSplit();
12160 // if it isn't first piece, alignment must be 1
12161 else if (i > 0) {
12162 MyFlags.Flags.setOrigAlign(Align(1));
12163 if (i == NumRegs - 1)
12164 MyFlags.Flags.setSplitEnd();
12165 }
12166 Ins.push_back(Elt: MyFlags);
12167 }
12168 if (NeedsRegBlock && Value == NumValues - 1)
12169 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
12170 }
12171 }
12172
12173 // Call the target to set up the argument values.
12174 SmallVector<SDValue, 8> InVals;
12175 SDValue NewRoot = TLI->LowerFormalArguments(
12176 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
12177
12178 // Verify that the target's LowerFormalArguments behaved as expected.
12179 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
12180 "LowerFormalArguments didn't return a valid chain!");
12181 assert(InVals.size() == Ins.size() &&
12182 "LowerFormalArguments didn't emit the correct number of values!");
12183 assert(all_of(InVals, [](SDValue InVal) { return InVal.getNode(); }) &&
12184 "LowerFormalArguments emitted a null value!");
12185
12186 // Update the DAG with the new chain value resulting from argument lowering.
12187 DAG.setRoot(NewRoot);
12188
12189 // Set up the argument values.
12190 unsigned i = 0;
12191 if (!FuncInfo->CanLowerReturn) {
12192 // Create a virtual register for the sret pointer, and put in a copy
12193 // from the sret argument into it.
12194 MVT VT = TLI->getPointerTy(DL, AS: DL.getAllocaAddrSpace());
12195 MVT RegVT = TLI->getRegisterType(Context&: *CurDAG->getContext(), VT);
12196 std::optional<ISD::NodeType> AssertOp;
12197 SDValue ArgValue =
12198 getCopyFromParts(DAG, DL: dl, Parts: &InVals[0], NumParts: 1, PartVT: RegVT, ValueVT: VT, V: nullptr, InChain: NewRoot,
12199 CC: F.getCallingConv(), AssertOp);
12200
12201 MachineFunction& MF = SDB->DAG.getMachineFunction();
12202 MachineRegisterInfo& RegInfo = MF.getRegInfo();
12203 Register SRetReg =
12204 RegInfo.createVirtualRegister(RegClass: TLI->getRegClassFor(VT: RegVT));
12205 FuncInfo->DemoteRegister = SRetReg;
12206 NewRoot =
12207 SDB->DAG.getCopyToReg(Chain: NewRoot, dl: SDB->getCurSDLoc(), Reg: SRetReg, N: ArgValue);
12208 DAG.setRoot(NewRoot);
12209
12210 // i indexes lowered arguments. Bump it past the hidden sret argument.
12211 ++i;
12212 }
12213
12214 SmallVector<SDValue, 4> Chains;
12215 DenseMap<int, int> ArgCopyElisionFrameIndexMap;
12216 for (const Argument &Arg : F.args()) {
12217 SmallVector<SDValue, 4> ArgValues;
12218 SmallVector<EVT, 4> ValueVTs;
12219 ComputeValueVTs(TLI: *TLI, DL: DAG.getDataLayout(), Ty: Arg.getType(), ValueVTs);
12220 unsigned NumValues = ValueVTs.size();
12221 if (NumValues == 0)
12222 continue;
12223
12224 bool ArgHasUses = !Arg.use_empty();
12225
12226 // Elide the copying store if the target loaded this argument from a
12227 // suitable fixed stack object.
12228 if (Ins[i].Flags.isCopyElisionCandidate()) {
12229 unsigned NumParts = 0;
12230 for (EVT VT : ValueVTs)
12231 NumParts += TLI->getNumRegistersForCallingConv(Context&: *CurDAG->getContext(),
12232 CC: F.getCallingConv(), VT);
12233
12234 tryToElideArgumentCopy(FuncInfo&: *FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
12235 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
12236 ArgVals: ArrayRef(&InVals[i], NumParts), ArgHasUses);
12237 }
12238
12239 // If this argument is unused then remember its value. It is used to generate
12240 // debugging information.
12241 bool isSwiftErrorArg =
12242 TLI->supportSwiftError() &&
12243 Arg.hasAttribute(Kind: Attribute::SwiftError);
12244 if (!ArgHasUses && !isSwiftErrorArg) {
12245 SDB->setUnusedArgValue(V: &Arg, NewN: InVals[i]);
12246
12247 // Also remember any frame index for use in FastISel.
12248 if (FrameIndexSDNode *FI =
12249 dyn_cast<FrameIndexSDNode>(Val: InVals[i].getNode()))
12250 FuncInfo->setArgumentFrameIndex(A: &Arg, FI: FI->getIndex());
12251 }
12252
12253 for (unsigned Val = 0; Val != NumValues; ++Val) {
12254 EVT VT = ValueVTs[Val];
12255 MVT PartVT = TLI->getRegisterTypeForCallingConv(Context&: *CurDAG->getContext(),
12256 CC: F.getCallingConv(), VT);
12257 unsigned NumParts = TLI->getNumRegistersForCallingConv(
12258 Context&: *CurDAG->getContext(), CC: F.getCallingConv(), VT);
12259
12260 // Even an apparent 'unused' swifterror argument needs to be returned. So
12261 // we do generate a copy for it that can be used on return from the
12262 // function.
12263 if (ArgHasUses || isSwiftErrorArg) {
12264 std::optional<ISD::NodeType> AssertOp;
12265 if (Arg.hasAttribute(Kind: Attribute::SExt))
12266 AssertOp = ISD::AssertSext;
12267 else if (Arg.hasAttribute(Kind: Attribute::ZExt))
12268 AssertOp = ISD::AssertZext;
12269
12270 SDValue OutVal =
12271 getCopyFromParts(DAG, DL: dl, Parts: &InVals[i], NumParts, PartVT, ValueVT: VT, V: nullptr,
12272 InChain: NewRoot, CC: F.getCallingConv(), AssertOp);
12273
12274 FPClassTest NoFPClass = Arg.getNoFPClass();
12275 if (NoFPClass != fcNone) {
12276 SDValue SDNoFPClass = DAG.getTargetConstant(
12277 Val: static_cast<uint64_t>(NoFPClass), DL: dl, VT: MVT::i32);
12278 OutVal = DAG.getNode(Opcode: ISD::AssertNoFPClass, DL: dl, VT: OutVal.getValueType(),
12279 N1: OutVal, N2: SDNoFPClass);
12280 }
12281 ArgValues.push_back(Elt: OutVal);
12282 }
12283
12284 i += NumParts;
12285 }
12286
12287 // We don't need to do anything else for unused arguments.
12288 if (ArgValues.empty())
12289 continue;
12290
12291 // Note down frame index.
12292 if (FrameIndexSDNode *FI =
12293 dyn_cast<FrameIndexSDNode>(Val: ArgValues[0].getNode()))
12294 FuncInfo->setArgumentFrameIndex(A: &Arg, FI: FI->getIndex());
12295
12296 SDValue Res = DAG.getMergeValues(Ops: ArrayRef(ArgValues.data(), NumValues),
12297 dl: SDB->getCurSDLoc());
12298
12299 SDB->setValue(V: &Arg, NewN: Res);
12300 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
12301 // We want to associate the argument with the frame index, among
12302 // involved operands, that correspond to the lowest address. The
12303 // getCopyFromParts function, called earlier, is swapping the order of
12304 // the operands to BUILD_PAIR depending on endianness. The result of
12305 // that swapping is that the least significant bits of the argument will
12306 // be in the first operand of the BUILD_PAIR node, and the most
12307 // significant bits will be in the second operand.
12308 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
12309 if (LoadSDNode *LNode =
12310 dyn_cast<LoadSDNode>(Val: Res.getOperand(i: LowAddressOp).getNode()))
12311 if (FrameIndexSDNode *FI =
12312 dyn_cast<FrameIndexSDNode>(Val: LNode->getBasePtr().getNode()))
12313 FuncInfo->setArgumentFrameIndex(A: &Arg, FI: FI->getIndex());
12314 }
12315
12316 // Analyses past this point are naive and don't expect an assertion.
12317 if (Res.getOpcode() == ISD::AssertZext)
12318 Res = Res.getOperand(i: 0);
12319
12320 // Update the SwiftErrorVRegDefMap.
12321 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
12322 Register Reg = cast<RegisterSDNode>(Val: Res.getOperand(i: 1))->getReg();
12323 if (Reg.isVirtual())
12324 SwiftError->setCurrentVReg(MBB: FuncInfo->MBB, SwiftError->getFunctionArg(),
12325 Reg);
12326 }
12327
12328 // If this argument is live outside of the entry block, insert a copy from
12329 // wherever we got it to the vreg that other BB's will reference it as.
12330 if (Res.getOpcode() == ISD::CopyFromReg) {
12331 // If we can, though, try to skip creating an unnecessary vreg.
12332 // FIXME: This isn't very clean... it would be nice to make this more
12333 // general.
12334 Register Reg = cast<RegisterSDNode>(Val: Res.getOperand(i: 1))->getReg();
12335 if (Reg.isVirtual()) {
12336 FuncInfo->ValueMap[&Arg] = Reg;
12337 continue;
12338 }
12339 }
12340 if (!isOnlyUsedInEntryBlock(A: &Arg, FastISel: TM.Options.EnableFastISel)) {
12341 FuncInfo->InitializeRegForValue(V: &Arg);
12342 SDB->CopyToExportRegsIfNeeded(V: &Arg);
12343 }
12344 }
12345
12346 if (!Chains.empty()) {
12347 Chains.push_back(Elt: NewRoot);
12348 NewRoot = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: Chains);
12349 }
12350
12351 DAG.setRoot(NewRoot);
12352
12353 assert(i == InVals.size() && "Argument register count mismatch!");
12354
12355 // If any argument copy elisions occurred and we have debug info, update the
12356 // stale frame indices used in the dbg.declare variable info table.
12357 if (!ArgCopyElisionFrameIndexMap.empty()) {
12358 for (MachineFunction::VariableDbgInfo &VI :
12359 MF->getInStackSlotVariableDbgInfo()) {
12360 auto I = ArgCopyElisionFrameIndexMap.find(Val: VI.getStackSlot());
12361 if (I != ArgCopyElisionFrameIndexMap.end())
12362 VI.updateStackSlot(NewSlot: I->second);
12363 }
12364 }
12365
12366 // Finally, if the target has anything special to do, allow it to do so.
12367 emitFunctionEntryCode();
12368}
12369
12370/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
12371/// ensure constants are generated when needed. Remember the virtual registers
12372/// that need to be added to the Machine PHI nodes as input. We cannot just
12373/// directly add them, because expansion might result in multiple MBB's for one
12374/// BB. As such, the start of the BB might correspond to a different MBB than
12375/// the end.
12376void
12377SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
12378 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12379
12380 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
12381
12382 // Check PHI nodes in successors that expect a value to be available from this
12383 // block.
12384 for (const BasicBlock *SuccBB : successors(I: LLVMBB->getTerminator())) {
12385 if (!isa<PHINode>(Val: SuccBB->begin())) continue;
12386 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(BB: SuccBB);
12387
12388 // If this terminator has multiple identical successors (common for
12389 // switches), only handle each succ once.
12390 if (!SuccsHandled.insert(Ptr: SuccMBB).second)
12391 continue;
12392
12393 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
12394
12395 // At this point we know that there is a 1-1 correspondence between LLVM PHI
12396 // nodes and Machine PHI nodes, but the incoming operands have not been
12397 // emitted yet.
12398 for (const PHINode &PN : SuccBB->phis()) {
12399 // Ignore dead phi's.
12400 if (PN.use_empty())
12401 continue;
12402
12403 // Skip empty types
12404 if (PN.getType()->isEmptyTy())
12405 continue;
12406
12407 Register Reg;
12408 const Value *PHIOp = PN.getIncomingValueForBlock(BB: LLVMBB);
12409
12410 if (const auto *C = dyn_cast<Constant>(Val: PHIOp)) {
12411 Register &RegOut = ConstantsOut[C];
12412 if (!RegOut) {
12413 RegOut = FuncInfo.CreateRegs(V: &PN);
12414 // We need to zero/sign extend ConstantInt phi operands to match
12415 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
12416 ISD::NodeType ExtendType = ISD::ANY_EXTEND;
12417 if (auto *CI = dyn_cast<ConstantInt>(Val: C))
12418 ExtendType = TLI.signExtendConstant(C: CI) ? ISD::SIGN_EXTEND
12419 : ISD::ZERO_EXTEND;
12420 CopyValueToVirtualRegister(V: C, Reg: RegOut, ExtendType);
12421 }
12422 Reg = RegOut;
12423 } else {
12424 auto I = FuncInfo.ValueMap.find(Val: PHIOp);
12425 if (I != FuncInfo.ValueMap.end())
12426 Reg = I->second;
12427 else {
12428 assert(isa<AllocaInst>(PHIOp) &&
12429 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
12430 "Didn't codegen value into a register!??");
12431 Reg = FuncInfo.CreateRegs(V: &PN);
12432 CopyValueToVirtualRegister(V: PHIOp, Reg);
12433 }
12434 }
12435
12436 // Remember that this register needs to added to the machine PHI node as
12437 // the input for this MBB.
12438 SmallVector<EVT, 4> ValueVTs;
12439 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: PN.getType(), ValueVTs);
12440 for (EVT VT : ValueVTs) {
12441 const unsigned NumRegisters = TLI.getNumRegisters(Context&: *DAG.getContext(), VT);
12442 for (unsigned i = 0; i != NumRegisters; ++i)
12443 FuncInfo.PHINodesToUpdate.emplace_back(args: &*MBBI++, args: Reg + i);
12444 Reg += NumRegisters;
12445 }
12446 }
12447 }
12448
12449 ConstantsOut.clear();
12450}
12451
12452MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
12453 MachineFunction::iterator I(MBB);
12454 if (++I == FuncInfo.MF->end())
12455 return nullptr;
12456 return &*I;
12457}
12458
12459/// During lowering new call nodes can be created (such as memset, etc.).
12460/// Those will become new roots of the current DAG, but complications arise
12461/// when they are tail calls. In such cases, the call lowering will update
12462/// the root, but the builder still needs to know that a tail call has been
12463/// lowered in order to avoid generating an additional return.
12464void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12465 // If the node is null, we do have a tail call.
12466 if (MaybeTC.getNode() != nullptr)
12467 DAG.setRoot(MaybeTC);
12468 else
12469 HasTailCall = true;
12470}
12471
12472void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12473 MachineBasicBlock *SwitchMBB,
12474 MachineBasicBlock *DefaultMBB) {
12475 MachineFunction *CurMF = FuncInfo.MF;
12476 MachineBasicBlock *NextMBB = nullptr;
12477 MachineFunction::iterator BBI(W.MBB);
12478 if (++BBI != FuncInfo.MF->end())
12479 NextMBB = &*BBI;
12480
12481 unsigned Size = W.LastCluster - W.FirstCluster + 1;
12482
12483 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12484
12485 if (Size == 2 && W.MBB == SwitchMBB) {
12486 // If any two of the cases has the same destination, and if one value
12487 // is the same as the other, but has one bit unset that the other has set,
12488 // use bit manipulation to do two compares at once. For example:
12489 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12490 // TODO: This could be extended to merge any 2 cases in switches with 3
12491 // cases.
12492 // TODO: Handle cases where W.CaseBB != SwitchBB.
12493 CaseCluster &Small = *W.FirstCluster;
12494 CaseCluster &Big = *W.LastCluster;
12495
12496 if (Small.Low == Small.High && Big.Low == Big.High &&
12497 Small.MBB == Big.MBB) {
12498 const APInt &SmallValue = Small.Low->getValue();
12499 const APInt &BigValue = Big.Low->getValue();
12500
12501 // Check that there is only one bit different.
12502 APInt CommonBit = BigValue ^ SmallValue;
12503 if (CommonBit.isPowerOf2()) {
12504 SDValue CondLHS = getValue(V: Cond);
12505 EVT VT = CondLHS.getValueType();
12506 SDLoc DL = getCurSDLoc();
12507
12508 SDValue Or = DAG.getNode(Opcode: ISD::OR, DL, VT, N1: CondLHS,
12509 N2: DAG.getConstant(Val: CommonBit, DL, VT));
12510 SDValue Cond = DAG.getSetCC(
12511 DL, VT: MVT::i1, LHS: Or, RHS: DAG.getConstant(Val: BigValue | SmallValue, DL, VT),
12512 Cond: ISD::SETEQ);
12513
12514 // Update successor info.
12515 // Both Small and Big will jump to Small.BB, so we sum up the
12516 // probabilities.
12517 addSuccessorWithProb(Src: SwitchMBB, Dst: Small.MBB, Prob: Small.Prob + Big.Prob);
12518 if (BPI)
12519 addSuccessorWithProb(
12520 Src: SwitchMBB, Dst: DefaultMBB,
12521 // The default destination is the first successor in IR.
12522 Prob: BPI->getEdgeProbability(Src: SwitchMBB->getBasicBlock(), IndexInSuccessors: (unsigned)0));
12523 else
12524 addSuccessorWithProb(Src: SwitchMBB, Dst: DefaultMBB);
12525
12526 // Insert the true branch.
12527 SDValue BrCond =
12528 DAG.getNode(Opcode: ISD::BRCOND, DL, VT: MVT::Other, N1: getControlRoot(), N2: Cond,
12529 N3: DAG.getBasicBlock(MBB: Small.MBB));
12530 // Insert the false branch.
12531 BrCond = DAG.getNode(Opcode: ISD::BR, DL, VT: MVT::Other, N1: BrCond,
12532 N2: DAG.getBasicBlock(MBB: DefaultMBB));
12533
12534 DAG.setRoot(BrCond);
12535 return;
12536 }
12537 }
12538 }
12539
12540 if (TM.getOptLevel() != CodeGenOptLevel::None) {
12541 // Here, we order cases by probability so the most likely case will be
12542 // checked first. However, two clusters can have the same probability in
12543 // which case their relative ordering is non-deterministic. So we use Low
12544 // as a tie-breaker as clusters are guaranteed to never overlap.
12545 llvm::sort(Start: W.FirstCluster, End: W.LastCluster + 1,
12546 Comp: [](const CaseCluster &a, const CaseCluster &b) {
12547 return a.Prob != b.Prob ?
12548 a.Prob > b.Prob :
12549 a.Low->getValue().slt(RHS: b.Low->getValue());
12550 });
12551
12552 // Rearrange the case blocks so that the last one falls through if possible
12553 // without changing the order of probabilities.
12554 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12555 --I;
12556 if (I->Prob > W.LastCluster->Prob)
12557 break;
12558 if (I->Kind == CC_Range && I->MBB == NextMBB) {
12559 std::swap(a&: *I, b&: *W.LastCluster);
12560 break;
12561 }
12562 }
12563 }
12564
12565 // Compute total probability.
12566 BranchProbability DefaultProb = W.DefaultProb;
12567 BranchProbability UnhandledProbs = DefaultProb;
12568 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12569 UnhandledProbs += I->Prob;
12570
12571 MachineBasicBlock *CurMBB = W.MBB;
12572 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12573 bool FallthroughUnreachable = false;
12574 MachineBasicBlock *Fallthrough;
12575 if (I == W.LastCluster) {
12576 // For the last cluster, fall through to the default destination.
12577 Fallthrough = DefaultMBB;
12578 FallthroughUnreachable = isa<UnreachableInst>(
12579 Val: DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12580 } else {
12581 Fallthrough = CurMF->CreateMachineBasicBlock(BB: CurMBB->getBasicBlock());
12582 CurMF->insert(MBBI: BBI, MBB: Fallthrough);
12583 // Put Cond in a virtual register to make it available from the new blocks.
12584 ExportFromCurrentBlock(V: Cond);
12585 }
12586 UnhandledProbs -= I->Prob;
12587
12588 switch (I->Kind) {
12589 case CC_JumpTable: {
12590 // FIXME: Optimize away range check based on pivot comparisons.
12591 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12592 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12593
12594 // The jump block hasn't been inserted yet; insert it here.
12595 MachineBasicBlock *JumpMBB = JT->MBB;
12596 CurMF->insert(MBBI: BBI, MBB: JumpMBB);
12597
12598 auto JumpProb = I->Prob;
12599 auto FallthroughProb = UnhandledProbs;
12600
12601 // If the default statement is a target of the jump table, we evenly
12602 // distribute the default probability to successors of CurMBB. Also
12603 // update the probability on the edge from JumpMBB to Fallthrough.
12604 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12605 SE = JumpMBB->succ_end();
12606 SI != SE; ++SI) {
12607 if (*SI == DefaultMBB) {
12608 JumpProb += DefaultProb / 2;
12609 FallthroughProb -= DefaultProb / 2;
12610 JumpMBB->setSuccProbability(I: SI, Prob: DefaultProb / 2);
12611 JumpMBB->normalizeSuccProbs();
12612 break;
12613 }
12614 }
12615
12616 // If the default clause is unreachable, propagate that knowledge into
12617 // JTH->FallthroughUnreachable which will use it to suppress the range
12618 // check.
12619 //
12620 // However, don't do this if we're doing branch target enforcement,
12621 // because a table branch _without_ a range check can be a tempting JOP
12622 // gadget - out-of-bounds inputs that are impossible in correct
12623 // execution become possible again if an attacker can influence the
12624 // control flow. So if an attacker doesn't already have a BTI bypass
12625 // available, we don't want them to be able to get one out of this
12626 // table branch.
12627 if (FallthroughUnreachable) {
12628 Function &CurFunc = CurMF->getFunction();
12629 if (!CurFunc.hasFnAttribute(Kind: "branch-target-enforcement"))
12630 JTH->FallthroughUnreachable = true;
12631 }
12632
12633 if (!JTH->FallthroughUnreachable)
12634 addSuccessorWithProb(Src: CurMBB, Dst: Fallthrough, Prob: FallthroughProb);
12635 addSuccessorWithProb(Src: CurMBB, Dst: JumpMBB, Prob: JumpProb);
12636 CurMBB->normalizeSuccProbs();
12637
12638 // The jump table header will be inserted in our current block, do the
12639 // range check, and fall through to our fallthrough block.
12640 JTH->HeaderBB = CurMBB;
12641 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12642
12643 // If we're in the right place, emit the jump table header right now.
12644 if (CurMBB == SwitchMBB) {
12645 visitJumpTableHeader(JT&: *JT, JTH&: *JTH, SwitchBB: SwitchMBB);
12646 JTH->Emitted = true;
12647 }
12648 break;
12649 }
12650 case CC_BitTests: {
12651 // FIXME: Optimize away range check based on pivot comparisons.
12652 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12653
12654 // The bit test blocks haven't been inserted yet; insert them here.
12655 for (BitTestCase &BTC : BTB->Cases)
12656 CurMF->insert(MBBI: BBI, MBB: BTC.ThisBB);
12657
12658 // Fill in fields of the BitTestBlock.
12659 BTB->Parent = CurMBB;
12660 BTB->Default = Fallthrough;
12661
12662 BTB->DefaultProb = UnhandledProbs;
12663 // If the cases in bit test don't form a contiguous range, we evenly
12664 // distribute the probability on the edge to Fallthrough to two
12665 // successors of CurMBB.
12666 if (!BTB->ContiguousRange) {
12667 BTB->Prob += DefaultProb / 2;
12668 BTB->DefaultProb -= DefaultProb / 2;
12669 }
12670
12671 if (FallthroughUnreachable)
12672 BTB->FallthroughUnreachable = true;
12673
12674 // If we're in the right place, emit the bit test header right now.
12675 if (CurMBB == SwitchMBB) {
12676 visitBitTestHeader(B&: *BTB, SwitchBB: SwitchMBB);
12677 BTB->Emitted = true;
12678 }
12679 break;
12680 }
12681 case CC_Range: {
12682 const Value *RHS, *LHS, *MHS;
12683 ISD::CondCode CC;
12684 if (I->Low == I->High) {
12685 // Check Cond == I->Low.
12686 CC = ISD::SETEQ;
12687 LHS = Cond;
12688 RHS=I->Low;
12689 MHS = nullptr;
12690 } else {
12691 // Check I->Low <= Cond <= I->High.
12692 CC = ISD::SETLE;
12693 LHS = I->Low;
12694 MHS = Cond;
12695 RHS = I->High;
12696 }
12697
12698 // If Fallthrough is unreachable, fold away the comparison.
12699 if (FallthroughUnreachable)
12700 CC = ISD::SETTRUE;
12701
12702 // The false probability is the sum of all unhandled cases.
12703 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12704 getCurSDLoc(), I->Prob, UnhandledProbs);
12705
12706 if (CurMBB == SwitchMBB)
12707 visitSwitchCase(CB, SwitchBB: SwitchMBB);
12708 else
12709 SL->SwitchCases.push_back(x: CB);
12710
12711 break;
12712 }
12713 }
12714 CurMBB = Fallthrough;
12715 }
12716}
12717
12718void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12719 const SwitchWorkListItem &W,
12720 Value *Cond,
12721 MachineBasicBlock *SwitchMBB) {
12722 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12723 "Clusters not sorted?");
12724 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12725
12726 auto [LastLeft, FirstRight, LeftProb, RightProb] =
12727 SL->computeSplitWorkItemInfo(W);
12728
12729 // Use the first element on the right as pivot since we will make less-than
12730 // comparisons against it.
12731 CaseClusterIt PivotCluster = FirstRight;
12732 assert(PivotCluster > W.FirstCluster);
12733 assert(PivotCluster <= W.LastCluster);
12734
12735 CaseClusterIt FirstLeft = W.FirstCluster;
12736 CaseClusterIt LastRight = W.LastCluster;
12737
12738 const ConstantInt *Pivot = PivotCluster->Low;
12739
12740 // New blocks will be inserted immediately after the current one.
12741 MachineFunction::iterator BBI(W.MBB);
12742 ++BBI;
12743
12744 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12745 // we can branch to its destination directly if it's squeezed exactly in
12746 // between the known lower bound and Pivot - 1.
12747 MachineBasicBlock *LeftMBB;
12748 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12749 FirstLeft->Low == W.GE &&
12750 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12751 LeftMBB = FirstLeft->MBB;
12752 } else {
12753 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(BB: W.MBB->getBasicBlock());
12754 FuncInfo.MF->insert(MBBI: BBI, MBB: LeftMBB);
12755 WorkList.push_back(
12756 Elt: {.MBB: LeftMBB, .FirstCluster: FirstLeft, .LastCluster: LastLeft, .GE: W.GE, .LT: Pivot, .DefaultProb: W.DefaultProb / 2});
12757 // Put Cond in a virtual register to make it available from the new blocks.
12758 ExportFromCurrentBlock(V: Cond);
12759 }
12760
12761 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12762 // single cluster, RHS.Low == Pivot, and we can branch to its destination
12763 // directly if RHS.High equals the current upper bound.
12764 MachineBasicBlock *RightMBB;
12765 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12766 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12767 RightMBB = FirstRight->MBB;
12768 } else {
12769 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(BB: W.MBB->getBasicBlock());
12770 FuncInfo.MF->insert(MBBI: BBI, MBB: RightMBB);
12771 WorkList.push_back(
12772 Elt: {.MBB: RightMBB, .FirstCluster: FirstRight, .LastCluster: LastRight, .GE: Pivot, .LT: W.LT, .DefaultProb: W.DefaultProb / 2});
12773 // Put Cond in a virtual register to make it available from the new blocks.
12774 ExportFromCurrentBlock(V: Cond);
12775 }
12776
12777 // Create the CaseBlock record that will be used to lower the branch.
12778 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12779 getCurSDLoc(), LeftProb, RightProb);
12780
12781 if (W.MBB == SwitchMBB)
12782 visitSwitchCase(CB, SwitchBB: SwitchMBB);
12783 else
12784 SL->SwitchCases.push_back(x: CB);
12785}
12786
12787// Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12788// from the swith statement.
12789static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12790 BranchProbability PeeledCaseProb) {
12791 if (PeeledCaseProb == BranchProbability::getOne())
12792 return BranchProbability::getZero();
12793 BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12794
12795 uint32_t Numerator = CaseProb.getNumerator();
12796 uint32_t Denominator = SwitchProb.scale(Num: CaseProb.getDenominator());
12797 return BranchProbability(Numerator, std::max(a: Numerator, b: Denominator));
12798}
12799
12800// Try to peel the top probability case if it exceeds the threshold.
12801// Return current MachineBasicBlock for the switch statement if the peeling
12802// does not occur.
12803// If the peeling is performed, return the newly created MachineBasicBlock
12804// for the peeled switch statement. Also update Clusters to remove the peeled
12805// case. PeeledCaseProb is the BranchProbability for the peeled case.
12806MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12807 const SwitchInst &SI, CaseClusterVector &Clusters,
12808 BranchProbability &PeeledCaseProb) {
12809 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12810 // Don't perform if there is only one cluster or optimizing for size.
12811 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12812 TM.getOptLevel() == CodeGenOptLevel::None ||
12813 SwitchMBB->getParent()->getFunction().hasMinSize())
12814 return SwitchMBB;
12815
12816 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12817 unsigned PeeledCaseIndex = 0;
12818 bool SwitchPeeled = false;
12819 for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12820 CaseCluster &CC = Clusters[Index];
12821 if (CC.Prob < TopCaseProb)
12822 continue;
12823 TopCaseProb = CC.Prob;
12824 PeeledCaseIndex = Index;
12825 SwitchPeeled = true;
12826 }
12827 if (!SwitchPeeled)
12828 return SwitchMBB;
12829
12830 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12831 << TopCaseProb << "\n");
12832
12833 // Record the MBB for the peeled switch statement.
12834 MachineFunction::iterator BBI(SwitchMBB);
12835 ++BBI;
12836 MachineBasicBlock *PeeledSwitchMBB =
12837 FuncInfo.MF->CreateMachineBasicBlock(BB: SwitchMBB->getBasicBlock());
12838 FuncInfo.MF->insert(MBBI: BBI, MBB: PeeledSwitchMBB);
12839
12840 ExportFromCurrentBlock(V: SI.getCondition());
12841 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12842 SwitchWorkListItem W = {.MBB: SwitchMBB, .FirstCluster: PeeledCaseIt, .LastCluster: PeeledCaseIt,
12843 .GE: nullptr, .LT: nullptr, .DefaultProb: TopCaseProb.getCompl()};
12844 lowerWorkItem(W, Cond: SI.getCondition(), SwitchMBB, DefaultMBB: PeeledSwitchMBB);
12845
12846 Clusters.erase(position: PeeledCaseIt);
12847 for (CaseCluster &CC : Clusters) {
12848 LLVM_DEBUG(
12849 dbgs() << "Scale the probablity for one cluster, before scaling: "
12850 << CC.Prob << "\n");
12851 CC.Prob = scaleCaseProbality(CaseProb: CC.Prob, PeeledCaseProb: TopCaseProb);
12852 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12853 }
12854 PeeledCaseProb = TopCaseProb;
12855 return PeeledSwitchMBB;
12856}
12857
12858void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12859 // Extract cases from the switch.
12860 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12861 CaseClusterVector Clusters;
12862 Clusters.reserve(n: SI.getNumCases());
12863 for (auto I : SI.cases()) {
12864 MachineBasicBlock *Succ = FuncInfo.getMBB(BB: I.getCaseSuccessor());
12865 const ConstantInt *CaseVal = I.getCaseValue();
12866 BranchProbability Prob =
12867 BPI ? BPI->getEdgeProbability(Src: SI.getParent(), IndexInSuccessors: I.getSuccessorIndex())
12868 : BranchProbability(1, SI.getNumCases() + 1);
12869 Clusters.push_back(x: CaseCluster::range(Low: CaseVal, High: CaseVal, MBB: Succ, Prob));
12870 }
12871
12872 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(BB: SI.getDefaultDest());
12873
12874 // Cluster adjacent cases with the same destination. We do this at all
12875 // optimization levels because it's cheap to do and will make codegen faster
12876 // if there are many clusters.
12877 sortAndRangeify(Clusters);
12878
12879 // The branch probablity of the peeled case.
12880 BranchProbability PeeledCaseProb = BranchProbability::getZero();
12881 MachineBasicBlock *PeeledSwitchMBB =
12882 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12883
12884 // If there is only the default destination, jump there directly.
12885 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12886 if (Clusters.empty()) {
12887 assert(PeeledSwitchMBB == SwitchMBB);
12888 SwitchMBB->addSuccessor(Succ: DefaultMBB);
12889 if (DefaultMBB != NextBlock(MBB: SwitchMBB)) {
12890 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other,
12891 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: DefaultMBB)));
12892 }
12893 return;
12894 }
12895
12896 SL->findJumpTables(Clusters, SI: &SI, SL: getCurSDLoc(), DefaultMBB, PSI: DAG.getPSI(),
12897 BFI: DAG.getBFI());
12898 SL->findBitTestClusters(Clusters, SI: &SI);
12899
12900 LLVM_DEBUG({
12901 dbgs() << "Case clusters: ";
12902 for (const CaseCluster &C : Clusters) {
12903 if (C.Kind == CC_JumpTable)
12904 dbgs() << "JT:";
12905 if (C.Kind == CC_BitTests)
12906 dbgs() << "BT:";
12907
12908 C.Low->getValue().print(dbgs(), true);
12909 if (C.Low != C.High) {
12910 dbgs() << '-';
12911 C.High->getValue().print(dbgs(), true);
12912 }
12913 dbgs() << ' ';
12914 }
12915 dbgs() << '\n';
12916 });
12917
12918 assert(!Clusters.empty());
12919 SwitchWorkList WorkList;
12920 CaseClusterIt First = Clusters.begin();
12921 CaseClusterIt Last = Clusters.end() - 1;
12922 auto DefaultProb = getEdgeProbability(Src: PeeledSwitchMBB, Dst: DefaultMBB);
12923 // Scale the branchprobability for DefaultMBB if the peel occurs and
12924 // DefaultMBB is not replaced.
12925 if (PeeledCaseProb != BranchProbability::getZero() &&
12926 DefaultMBB == FuncInfo.getMBB(BB: SI.getDefaultDest()))
12927 DefaultProb = scaleCaseProbality(CaseProb: DefaultProb, PeeledCaseProb);
12928 WorkList.push_back(
12929 Elt: {.MBB: PeeledSwitchMBB, .FirstCluster: First, .LastCluster: Last, .GE: nullptr, .LT: nullptr, .DefaultProb: DefaultProb});
12930
12931 while (!WorkList.empty()) {
12932 SwitchWorkListItem W = WorkList.pop_back_val();
12933 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12934
12935 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12936 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12937 // For optimized builds, lower large range as a balanced binary tree.
12938 splitWorkItem(WorkList, W, Cond: SI.getCondition(), SwitchMBB);
12939 continue;
12940 }
12941
12942 lowerWorkItem(W, Cond: SI.getCondition(), SwitchMBB, DefaultMBB);
12943 }
12944}
12945
12946void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12947 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12948 auto DL = getCurSDLoc();
12949 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
12950 setValue(V: &I, NewN: DAG.getStepVector(DL, ResVT: ResultVT));
12951}
12952
12953void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12954 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12955 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
12956
12957 SDLoc DL = getCurSDLoc();
12958 SDValue V = getValue(V: I.getOperand(i_nocapture: 0));
12959 assert(VT == V.getValueType() && "Malformed vector.reverse!");
12960
12961 if (VT.isScalableVector()) {
12962 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::VECTOR_REVERSE, DL, VT, Operand: V));
12963 return;
12964 }
12965
12966 // Use VECTOR_SHUFFLE for the fixed-length vector
12967 // to maintain existing behavior.
12968 SmallVector<int, 8> Mask;
12969 unsigned NumElts = VT.getVectorMinNumElements();
12970 for (unsigned i = 0; i != NumElts; ++i)
12971 Mask.push_back(Elt: NumElts - 1 - i);
12972
12973 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: V, N2: DAG.getUNDEF(VT), Mask));
12974}
12975
12976void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I,
12977 unsigned Factor) {
12978 auto DL = getCurSDLoc();
12979 SDValue InVec = getValue(V: I.getOperand(i_nocapture: 0));
12980
12981 SmallVector<EVT, 4> ValueVTs;
12982 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty: I.getType(),
12983 ValueVTs);
12984
12985 EVT OutVT = ValueVTs[0];
12986 unsigned OutNumElts = OutVT.getVectorMinNumElements();
12987
12988 SmallVector<SDValue, 4> SubVecs(Factor);
12989 for (unsigned i = 0; i != Factor; ++i) {
12990 assert(ValueVTs[i] == OutVT && "Expected VTs to be the same");
12991 SubVecs[i] = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: OutVT, N1: InVec,
12992 N2: DAG.getVectorIdxConstant(Val: OutNumElts * i, DL));
12993 }
12994
12995 // Use VECTOR_SHUFFLE for fixed-length vectors with factor of 2 to benefit
12996 // from existing legalisation and combines.
12997 if (OutVT.isFixedLengthVector() && Factor == 2) {
12998 SDValue Even = DAG.getVectorShuffle(VT: OutVT, dl: DL, N1: SubVecs[0], N2: SubVecs[1],
12999 Mask: createStrideMask(Start: 0, Stride: 2, VF: OutNumElts));
13000 SDValue Odd = DAG.getVectorShuffle(VT: OutVT, dl: DL, N1: SubVecs[0], N2: SubVecs[1],
13001 Mask: createStrideMask(Start: 1, Stride: 2, VF: OutNumElts));
13002 SDValue Res = DAG.getMergeValues(Ops: {Even, Odd}, dl: getCurSDLoc());
13003 setValue(V: &I, NewN: Res);
13004 return;
13005 }
13006
13007 SDValue Res = DAG.getNode(Opcode: ISD::VECTOR_DEINTERLEAVE, DL,
13008 VTList: DAG.getVTList(VTs: ValueVTs), Ops: SubVecs);
13009 setValue(V: &I, NewN: Res);
13010}
13011
13012void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I,
13013 unsigned Factor) {
13014 auto DL = getCurSDLoc();
13015 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13016 EVT InVT = getValue(V: I.getOperand(i_nocapture: 0)).getValueType();
13017 EVT OutVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
13018
13019 SmallVector<SDValue, 8> InVecs(Factor);
13020 for (unsigned i = 0; i < Factor; ++i) {
13021 InVecs[i] = getValue(V: I.getOperand(i_nocapture: i));
13022 assert(InVecs[i].getValueType() == InVecs[0].getValueType() &&
13023 "Expected VTs to be the same");
13024 }
13025
13026 // Use VECTOR_SHUFFLE for fixed-length vectors with factor of 2 to benefit
13027 // from existing legalisation and combines.
13028 if (OutVT.isFixedLengthVector() && Factor == 2) {
13029 unsigned NumElts = InVT.getVectorMinNumElements();
13030 SDValue V = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: OutVT, Ops: InVecs);
13031 setValue(V: &I, NewN: DAG.getVectorShuffle(VT: OutVT, dl: DL, N1: V, N2: DAG.getUNDEF(VT: OutVT),
13032 Mask: createInterleaveMask(VF: NumElts, NumVecs: 2)));
13033 return;
13034 }
13035
13036 SmallVector<EVT, 8> ValueVTs(Factor, InVT);
13037 SDValue Res =
13038 DAG.getNode(Opcode: ISD::VECTOR_INTERLEAVE, DL, VTList: DAG.getVTList(VTs: ValueVTs), Ops: InVecs);
13039
13040 SmallVector<SDValue, 8> Results(Factor);
13041 for (unsigned i = 0; i < Factor; ++i)
13042 Results[i] = Res.getValue(R: i);
13043
13044 Res = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: OutVT, Ops: Results);
13045 setValue(V: &I, NewN: Res);
13046}
13047
13048void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
13049 SmallVector<EVT, 4> ValueVTs;
13050 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty: I.getType(),
13051 ValueVTs);
13052 unsigned NumValues = ValueVTs.size();
13053 if (NumValues == 0) return;
13054
13055 SmallVector<SDValue, 4> Values(NumValues);
13056 SDValue Op = getValue(V: I.getOperand(i_nocapture: 0));
13057
13058 for (unsigned i = 0; i != NumValues; ++i)
13059 Values[i] = DAG.getNode(Opcode: ISD::FREEZE, DL: getCurSDLoc(), VT: ValueVTs[i],
13060 Operand: SDValue(Op.getNode(), Op.getResNo() + i));
13061
13062 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
13063 VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values));
13064}
13065
13066void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
13067 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13068 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
13069
13070 SDLoc DL = getCurSDLoc();
13071 SDValue V1 = getValue(V: I.getOperand(i_nocapture: 0));
13072 SDValue V2 = getValue(V: I.getOperand(i_nocapture: 1));
13073 const bool IsLeft = I.getIntrinsicID() == Intrinsic::vector_splice_left;
13074
13075 // VECTOR_SHUFFLE doesn't support a scalable or non-constant mask.
13076 if (VT.isScalableVector() || !isa<ConstantInt>(Val: I.getOperand(i_nocapture: 2))) {
13077 SDValue Offset = DAG.getZExtOrTrunc(
13078 Op: getValue(V: I.getOperand(i_nocapture: 2)), DL, VT: TLI.getVectorIdxTy(DL: DAG.getDataLayout()));
13079 setValue(V: &I, NewN: DAG.getNode(Opcode: IsLeft ? ISD::VECTOR_SPLICE_LEFT
13080 : ISD::VECTOR_SPLICE_RIGHT,
13081 DL, VT, N1: V1, N2: V2, N3: Offset));
13082 return;
13083 }
13084 uint64_t Imm = cast<ConstantInt>(Val: I.getOperand(i_nocapture: 2))->getZExtValue();
13085
13086 unsigned NumElts = VT.getVectorNumElements();
13087
13088 uint64_t Idx = IsLeft ? Imm : NumElts - Imm;
13089
13090 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
13091 SmallVector<int, 8> Mask;
13092 for (unsigned i = 0; i < NumElts; ++i)
13093 Mask.push_back(Elt: Idx + i);
13094 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: V1, N2: V2, Mask));
13095}
13096
13097// Consider the following MIR after SelectionDAG, which produces output in
13098// phyregs in the first case or virtregs in the second case.
13099//
13100// INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
13101// %5:gr32 = COPY $ebx
13102// %6:gr32 = COPY $edx
13103// %1:gr32 = COPY %6:gr32
13104// %0:gr32 = COPY %5:gr32
13105//
13106// INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
13107// %1:gr32 = COPY %6:gr32
13108// %0:gr32 = COPY %5:gr32
13109//
13110// Given %0, we'd like to return $ebx in the first case and %5 in the second.
13111// Given %1, we'd like to return $edx in the first case and %6 in the second.
13112//
13113// If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
13114// to a single virtreg (such as %0). The remaining outputs monotonically
13115// increase in virtreg number from there. If a callbr has no outputs, then it
13116// should not have a corresponding callbr landingpad; in fact, the callbr
13117// landingpad would not even be able to refer to such a callbr.
13118static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
13119 MachineInstr *MI = MRI.def_begin(RegNo: Reg)->getParent();
13120 // There is definitely at least one copy.
13121 assert(MI->getOpcode() == TargetOpcode::COPY &&
13122 "start of copy chain MUST be COPY");
13123 Reg = MI->getOperand(i: 1).getReg();
13124
13125 // If the copied register in the first copy must be virtual.
13126 assert(Reg.isVirtual() && "expected COPY of virtual register");
13127 MI = MRI.def_begin(RegNo: Reg)->getParent();
13128
13129 // There may be an optional second copy.
13130 if (MI->getOpcode() == TargetOpcode::COPY) {
13131 assert(Reg.isVirtual() && "expected COPY of virtual register");
13132 Reg = MI->getOperand(i: 1).getReg();
13133 assert(Reg.isPhysical() && "expected COPY of physical register");
13134 } else {
13135 // The start of the chain must be an INLINEASM_BR.
13136 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
13137 "end of copy chain MUST be INLINEASM_BR");
13138 }
13139
13140 return Reg;
13141}
13142
13143// We must do this walk rather than the simpler
13144// setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
13145// otherwise we will end up with copies of virtregs only valid along direct
13146// edges.
13147void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
13148 SmallVector<EVT, 8> ResultVTs;
13149 SmallVector<SDValue, 8> ResultValues;
13150 const auto *CBR =
13151 cast<CallBrInst>(Val: I.getParent()->getUniquePredecessor()->getTerminator());
13152
13153 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13154 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
13155 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
13156
13157 Register InitialDef = FuncInfo.ValueMap[CBR];
13158 SDValue Chain = DAG.getRoot();
13159
13160 // Re-parse the asm constraints string.
13161 TargetLowering::AsmOperandInfoVector TargetConstraints =
13162 TLI.ParseConstraints(DL: DAG.getDataLayout(), TRI, Call: *CBR);
13163 for (auto &T : TargetConstraints) {
13164 SDISelAsmOperandInfo OpInfo(T);
13165 if (OpInfo.Type != InlineAsm::isOutput)
13166 continue;
13167
13168 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
13169 // individual constraint.
13170 TLI.ComputeConstraintToUse(OpInfo, Op: OpInfo.CallOperand, DAG: &DAG);
13171
13172 switch (OpInfo.ConstraintType) {
13173 case TargetLowering::C_Register:
13174 case TargetLowering::C_RegisterClass: {
13175 // Fill in OpInfo.AssignedRegs.Regs.
13176 getRegistersForValue(DAG, DL: getCurSDLoc(), OpInfo, RefOpInfo&: OpInfo);
13177
13178 // getRegistersForValue may produce 1 to many registers based on whether
13179 // the OpInfo.ConstraintVT is legal on the target or not.
13180 for (Register &Reg : OpInfo.AssignedRegs.Regs) {
13181 Register OriginalDef = FollowCopyChain(MRI, Reg: InitialDef++);
13182 if (OriginalDef.isPhysical())
13183 FuncInfo.MBB->addLiveIn(PhysReg: OriginalDef);
13184 // Update the assigned registers to use the original defs.
13185 Reg = OriginalDef;
13186 }
13187
13188 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
13189 DAG, FuncInfo, dl: getCurSDLoc(), Chain, Glue: nullptr, V: CBR);
13190 ResultValues.push_back(Elt: V);
13191 ResultVTs.push_back(Elt: OpInfo.ConstraintVT);
13192 break;
13193 }
13194 case TargetLowering::C_Other: {
13195 SDValue Flag;
13196 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Glue&: Flag, DL: getCurSDLoc(),
13197 OpInfo, DAG);
13198 ++InitialDef;
13199 ResultValues.push_back(Elt: V);
13200 ResultVTs.push_back(Elt: OpInfo.ConstraintVT);
13201 break;
13202 }
13203 default:
13204 break;
13205 }
13206 }
13207 SDValue V = DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
13208 VTList: DAG.getVTList(VTs: ResultVTs), Ops: ResultValues);
13209 setValue(V: &I, NewN: V);
13210}
13211