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 && TLI.isZExtFree(Val, VT2: RegisterVT))
997 ExtendKind = ISD::ZERO_EXTEND;
998
999 getCopyToParts(DAG, DL: dl, Val: Val.getValue(R: Val.getResNo() + Value), Parts: &Parts[Part],
1000 NumParts, PartVT: RegisterVT, V, CallConv, ExtendKind);
1001 Part += NumParts;
1002 }
1003
1004 // Copy the parts into the registers.
1005 SmallVector<SDValue, 8> Chains(NumRegs);
1006 for (unsigned i = 0; i != NumRegs; ++i) {
1007 SDValue Part;
1008 if (!Glue) {
1009 Part = DAG.getCopyToReg(Chain, dl, Reg: Regs[i], N: Parts[i]);
1010 } else {
1011 Part = DAG.getCopyToReg(Chain, dl, Reg: Regs[i], N: Parts[i], Glue: *Glue);
1012 *Glue = Part.getValue(R: 1);
1013 }
1014
1015 Chains[i] = Part.getValue(R: 0);
1016 }
1017
1018 if (NumRegs == 1 || Glue)
1019 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1020 // flagged to it. That is the CopyToReg nodes and the user are considered
1021 // a single scheduling unit. If we create a TokenFactor and return it as
1022 // chain, then the TokenFactor is both a predecessor (operand) of the
1023 // user as well as a successor (the TF operands are flagged to the user).
1024 // c1, f1 = CopyToReg
1025 // c2, f2 = CopyToReg
1026 // c3 = TokenFactor c1, c2
1027 // ...
1028 // = op c3, ..., f2
1029 Chain = Chains[NumRegs-1];
1030 else
1031 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: Chains);
1032}
1033
1034void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1035 unsigned MatchingIdx, const SDLoc &dl,
1036 SelectionDAG &DAG,
1037 std::vector<SDValue> &Ops) const {
1038 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1039
1040 InlineAsm::Flag Flag(Code, Regs.size());
1041 if (HasMatching)
1042 Flag.setMatchingOp(MatchingIdx);
1043 else if (!Regs.empty() && Regs.front().isVirtual()) {
1044 // Put the register class of the virtual registers in the flag word. That
1045 // way, later passes can recompute register class constraints for inline
1046 // assembly as well as normal instructions.
1047 // Don't do this for tied operands that can use the regclass information
1048 // from the def.
1049 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1050 const TargetRegisterClass *RC = MRI.getRegClass(Reg: Regs.front());
1051 Flag.setRegClass(RC->getID());
1052 }
1053
1054 SDValue Res = DAG.getTargetConstant(Val: Flag, DL: dl, VT: MVT::i32);
1055 Ops.push_back(x: Res);
1056
1057 if (Code == InlineAsm::Kind::Clobber) {
1058 // Clobbers should always have a 1:1 mapping with registers, and may
1059 // reference registers that have illegal (e.g. vector) types. Hence, we
1060 // shouldn't try to apply any sort of splitting logic to them.
1061 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1062 "No 1:1 mapping from clobbers to regs?");
1063 Register SP = TLI.getStackPointerRegisterToSaveRestore();
1064 (void)SP;
1065 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1066 Ops.push_back(x: DAG.getRegister(Reg: Regs[I], VT: RegVTs[I]));
1067 assert(
1068 (Regs[I] != SP ||
1069 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1070 "If we clobbered the stack pointer, MFI should know about it.");
1071 }
1072 return;
1073 }
1074
1075 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1076 MVT RegisterVT = RegVTs[Value];
1077 unsigned NumRegs = TLI.getNumRegisters(Context&: *DAG.getContext(), VT: ValueVTs[Value],
1078 RegisterVT);
1079 for (unsigned i = 0; i != NumRegs; ++i) {
1080 assert(Reg < Regs.size() && "Mismatch in # registers expected");
1081 Register TheReg = Regs[Reg++];
1082 Ops.push_back(x: DAG.getRegister(Reg: TheReg, VT: RegisterVT));
1083 }
1084 }
1085}
1086
1087SmallVector<std::pair<Register, TypeSize>, 4>
1088RegsForValue::getRegsAndSizes() const {
1089 SmallVector<std::pair<Register, TypeSize>, 4> OutVec;
1090 unsigned I = 0;
1091 for (auto CountAndVT : zip_first(t: RegCount, u: RegVTs)) {
1092 unsigned RegCount = std::get<0>(t&: CountAndVT);
1093 MVT RegisterVT = std::get<1>(t&: CountAndVT);
1094 TypeSize RegisterSize = RegisterVT.getSizeInBits();
1095 for (unsigned E = I + RegCount; I != E; ++I)
1096 OutVec.push_back(Elt: std::make_pair(x: Regs[I], y&: RegisterSize));
1097 }
1098 return OutVec;
1099}
1100
1101void SelectionDAGBuilder::init(GCFunctionInfo *gfi, BatchAAResults *aa,
1102 AssumptionCache *ac, const TargetLibraryInfo *li,
1103 const TargetTransformInfo &TTI) {
1104 BatchAA = aa;
1105 AC = ac;
1106 GFI = gfi;
1107 LibInfo = li;
1108 Context = DAG.getContext();
1109 LPadToCallSiteMap.clear();
1110 this->TTI = &TTI;
1111 SL->init(tli: DAG.getTargetLoweringInfo(), tm: TM, dl: DAG.getDataLayout());
1112 AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1113 M: *DAG.getMachineFunction().getFunction().getParent());
1114}
1115
1116void SelectionDAGBuilder::clear() {
1117 NodeMap.clear();
1118 UnusedArgNodeMap.clear();
1119 PendingLoads.clear();
1120 PendingExports.clear();
1121 PendingConstrainedFP.clear();
1122 PendingConstrainedFPStrict.clear();
1123 CurInst = nullptr;
1124 HasTailCall = false;
1125 SDNodeOrder = LowestSDNodeOrder;
1126 StatepointLowering.clear();
1127}
1128
1129void SelectionDAGBuilder::clearDanglingDebugInfo() {
1130 DanglingDebugInfoMap.clear();
1131}
1132
1133// Update DAG root to include dependencies on Pending chains.
1134SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1135 SDValue Root = DAG.getRoot();
1136
1137 if (Pending.empty())
1138 return Root;
1139
1140 // Add current root to PendingChains, unless we already indirectly
1141 // depend on it.
1142 if (Root.getOpcode() != ISD::EntryToken) {
1143 unsigned i = 0, e = Pending.size();
1144 for (; i != e; ++i) {
1145 assert(Pending[i].getNode()->getNumOperands() > 1);
1146 if (Pending[i].getNode()->getOperand(Num: 0) == Root)
1147 break; // Don't add the root if we already indirectly depend on it.
1148 }
1149
1150 if (i == e)
1151 Pending.push_back(Elt: Root);
1152 }
1153
1154 if (Pending.size() == 1)
1155 Root = Pending[0];
1156 else
1157 Root = DAG.getTokenFactor(DL: getCurSDLoc(), Vals&: Pending);
1158
1159 DAG.setRoot(Root);
1160 Pending.clear();
1161 return Root;
1162}
1163
1164SDValue SelectionDAGBuilder::getMemoryRoot() {
1165 return updateRoot(Pending&: PendingLoads);
1166}
1167
1168SDValue SelectionDAGBuilder::getFPOperationRoot(fp::ExceptionBehavior EB) {
1169 // If the new exception behavior differs from that of the pending
1170 // ones, chain up them and update the root.
1171 switch (EB) {
1172 case fp::ExceptionBehavior::ebMayTrap:
1173 case fp::ExceptionBehavior::ebIgnore:
1174 // Floating-point exceptions produced by such operations are not intended
1175 // to be observed, so the sequence of these operations does not need to be
1176 // preserved.
1177 //
1178 // They however must not be mixed with the instructions that have strict
1179 // exception behavior. Placing an operation with 'ebIgnore' behavior between
1180 // 'ebStrict' operations could distort the observed exception behavior.
1181 if (!PendingConstrainedFPStrict.empty()) {
1182 assert(PendingConstrainedFP.empty());
1183 updateRoot(Pending&: PendingConstrainedFPStrict);
1184 }
1185 break;
1186 case fp::ExceptionBehavior::ebStrict:
1187 // Floating-point exception produced by these operations may be observed, so
1188 // they must be correctly chained. If trapping on FP exceptions is
1189 // disabled, the exceptions can be observed only by functions that read
1190 // exception flags, like 'llvm.get_fpenv' or 'fetestexcept'. It means that
1191 // the order of operations is not significant between barriers.
1192 //
1193 // If trapping is enabled, each operation becomes an implicit observation
1194 // point, so the operations must be sequenced according their original
1195 // source order.
1196 if (!PendingConstrainedFP.empty()) {
1197 assert(PendingConstrainedFPStrict.empty());
1198 updateRoot(Pending&: PendingConstrainedFP);
1199 }
1200 // TODO: Add support for trapping-enabled scenarios.
1201 }
1202 return DAG.getRoot();
1203}
1204
1205SDValue SelectionDAGBuilder::getRoot() {
1206 // Chain up all pending constrained intrinsics together with all
1207 // pending loads, by simply appending them to PendingLoads and
1208 // then calling getMemoryRoot().
1209 PendingLoads.reserve(N: PendingLoads.size() +
1210 PendingConstrainedFP.size() +
1211 PendingConstrainedFPStrict.size());
1212 PendingLoads.append(in_start: PendingConstrainedFP.begin(),
1213 in_end: PendingConstrainedFP.end());
1214 PendingLoads.append(in_start: PendingConstrainedFPStrict.begin(),
1215 in_end: PendingConstrainedFPStrict.end());
1216 PendingConstrainedFP.clear();
1217 PendingConstrainedFPStrict.clear();
1218 return getMemoryRoot();
1219}
1220
1221SDValue SelectionDAGBuilder::getControlRoot() {
1222 // We need to emit pending fpexcept.strict constrained intrinsics,
1223 // so append them to the PendingExports list.
1224 PendingExports.append(in_start: PendingConstrainedFPStrict.begin(),
1225 in_end: PendingConstrainedFPStrict.end());
1226 PendingConstrainedFPStrict.clear();
1227 return updateRoot(Pending&: PendingExports);
1228}
1229
1230void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1231 DILocalVariable *Variable,
1232 DIExpression *Expression,
1233 DebugLoc DL) {
1234 assert(Variable && "Missing variable");
1235
1236 // Check if address has undef value.
1237 if (!Address || isa<UndefValue>(Val: Address) ||
1238 (Address->use_empty() && !isa<Argument>(Val: Address))) {
1239 LLVM_DEBUG(
1240 dbgs()
1241 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1242 return;
1243 }
1244
1245 bool IsParameter = Variable->isParameter() || isa<Argument>(Val: Address);
1246
1247 SDValue &N = NodeMap[Address];
1248 if (!N.getNode() && isa<Argument>(Val: Address))
1249 // Check unused arguments map.
1250 N = UnusedArgNodeMap[Address];
1251 SDDbgValue *SDV;
1252 if (N.getNode()) {
1253 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Val: Address))
1254 Address = BCI->getOperand(i_nocapture: 0);
1255 // Parameters are handled specially.
1256 auto *FINode = dyn_cast<FrameIndexSDNode>(Val: N.getNode());
1257 if (IsParameter && FINode) {
1258 // Byval parameter. We have a frame index at this point.
1259 SDV = DAG.getFrameIndexDbgValue(Var: Variable, Expr: Expression, FI: FINode->getIndex(),
1260 /*IsIndirect*/ true, DL, O: SDNodeOrder);
1261 } else if (isa<Argument>(Val: Address)) {
1262 // Address is an argument, so try to emit its dbg value using
1263 // virtual register info from the FuncInfo.ValueMap.
1264 EmitFuncArgumentDbgValue(V: Address, Variable, Expr: Expression, DL,
1265 Kind: FuncArgumentDbgValueKind::Declare, N);
1266 return;
1267 } else {
1268 SDV = DAG.getDbgValue(Var: Variable, Expr: Expression, N: N.getNode(), R: N.getResNo(),
1269 IsIndirect: true, DL, O: SDNodeOrder);
1270 }
1271 DAG.AddDbgValue(DB: SDV, isParameter: IsParameter);
1272 } else {
1273 // If Address is an argument then try to emit its dbg value using
1274 // virtual register info from the FuncInfo.ValueMap.
1275 if (!EmitFuncArgumentDbgValue(V: Address, Variable, Expr: Expression, DL,
1276 Kind: FuncArgumentDbgValueKind::Declare, N)) {
1277 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1278 << " (could not emit func-arg dbg_value)\n");
1279 }
1280 }
1281}
1282
1283void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1284 // Add SDDbgValue nodes for any var locs here. Do so before updating
1285 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1286 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1287 // Add SDDbgValue nodes for any var locs here. Do so before updating
1288 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1289 for (auto It = FnVarLocs->locs_begin(Before: &I), End = FnVarLocs->locs_end(Before: &I);
1290 It != End; ++It) {
1291 auto *Var = FnVarLocs->getDILocalVariable(ID: It->VariableID);
1292 dropDanglingDebugInfo(Variable: Var, Expr: It->Expr);
1293 if (It->Values.isKillLocation(Expression: It->Expr)) {
1294 handleKillDebugValue(Var, Expr: It->Expr, DbgLoc: It->DL, Order: SDNodeOrder);
1295 continue;
1296 }
1297 SmallVector<Value *> Values(It->Values.location_ops());
1298 if (!handleDebugValue(Values, Var, Expr: It->Expr, DbgLoc: It->DL, Order: SDNodeOrder,
1299 IsVariadic: It->Values.hasArgList())) {
1300 SmallVector<Value *, 4> Vals(It->Values.location_ops());
1301 addDanglingDebugInfo(Values&: Vals,
1302 Var: FnVarLocs->getDILocalVariable(ID: It->VariableID),
1303 Expr: It->Expr, IsVariadic: Vals.size() > 1, DL: It->DL, Order: SDNodeOrder);
1304 }
1305 }
1306 }
1307
1308 // We must skip DbgVariableRecords if they've already been processed above as
1309 // we have just emitted the debug values resulting from assignment tracking
1310 // analysis, making any existing DbgVariableRecords redundant (and probably
1311 // less correct). We still need to process DbgLabelRecords. This does sink
1312 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1313 // be important as it does so deterministcally and ordering between
1314 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1315 // printing).
1316 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1317 // Is there is any debug-info attached to this instruction, in the form of
1318 // DbgRecord non-instruction debug-info records.
1319 for (DbgRecord &DR : I.getDbgRecordRange()) {
1320 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(Val: &DR)) {
1321 assert(DLR->getLabel() && "Missing label");
1322 SDDbgLabel *SDV =
1323 DAG.getDbgLabel(Label: DLR->getLabel(), DL: DLR->getDebugLoc(), O: SDNodeOrder);
1324 DAG.AddDbgLabel(DB: SDV);
1325 continue;
1326 }
1327
1328 if (SkipDbgVariableRecords)
1329 continue;
1330 DbgVariableRecord &DVR = cast<DbgVariableRecord>(Val&: DR);
1331 DILocalVariable *Variable = DVR.getVariable();
1332 DIExpression *Expression = DVR.getExpression();
1333 dropDanglingDebugInfo(Variable, Expr: Expression);
1334
1335 if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1336 if (FuncInfo.PreprocessedDVRDeclares.contains(Ptr: &DVR))
1337 continue;
1338 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1339 << "\n");
1340 handleDebugDeclare(Address: DVR.getVariableLocationOp(OpIdx: 0), Variable, Expression,
1341 DL: DVR.getDebugLoc());
1342 continue;
1343 }
1344
1345 // A DbgVariableRecord with no locations is a kill location.
1346 SmallVector<Value *, 4> Values(DVR.location_ops());
1347 if (Values.empty()) {
1348 handleKillDebugValue(Var: Variable, Expr: Expression, DbgLoc: DVR.getDebugLoc(),
1349 Order: SDNodeOrder);
1350 continue;
1351 }
1352
1353 // A DbgVariableRecord with an undef or absent location is also a kill
1354 // location.
1355 if (llvm::any_of(Range&: Values,
1356 P: [](Value *V) { return !V || isa<UndefValue>(Val: V); })) {
1357 handleKillDebugValue(Var: Variable, Expr: Expression, DbgLoc: DVR.getDebugLoc(),
1358 Order: SDNodeOrder);
1359 continue;
1360 }
1361
1362 bool IsVariadic = DVR.hasArgList();
1363 if (!handleDebugValue(Values, Var: Variable, Expr: Expression, DbgLoc: DVR.getDebugLoc(),
1364 Order: SDNodeOrder, IsVariadic)) {
1365 addDanglingDebugInfo(Values, Var: Variable, Expr: Expression, IsVariadic,
1366 DL: DVR.getDebugLoc(), Order: SDNodeOrder);
1367 }
1368 }
1369}
1370
1371void SelectionDAGBuilder::visit(const Instruction &I) {
1372 visitDbgInfo(I);
1373
1374 // Set up outgoing PHI node register values before emitting the terminator.
1375 if (I.isTerminator()) {
1376 HandlePHINodesInSuccessorBlocks(LLVMBB: I.getParent());
1377 }
1378
1379 ++SDNodeOrder;
1380 CurInst = &I;
1381
1382 // Set inserted listener only if required.
1383 bool NodeInserted = false;
1384 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1385 MDNode *PCSectionsMD = I.getMetadata(KindID: LLVMContext::MD_pcsections);
1386 MDNode *MMRA = I.getMetadata(KindID: LLVMContext::MD_mmra);
1387 if (PCSectionsMD || MMRA) {
1388 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1389 args&: DAG, args: [&](SDNode *) { NodeInserted = true; });
1390 }
1391
1392 visit(Opcode: I.getOpcode(), I);
1393
1394 if (!I.isTerminator() && !HasTailCall &&
1395 !isa<GCStatepointInst>(Val: I)) // statepoints handle their exports internally
1396 CopyToExportRegsIfNeeded(V: &I);
1397
1398 // Handle metadata.
1399 if (PCSectionsMD || MMRA) {
1400 auto It = NodeMap.find(Val: &I);
1401 if (It != NodeMap.end()) {
1402 if (PCSectionsMD)
1403 DAG.addPCSections(Node: It->second.getNode(), MD: PCSectionsMD);
1404 if (MMRA)
1405 DAG.addMMRAMetadata(Node: It->second.getNode(), MMRA);
1406 } else if (NodeInserted) {
1407 // This should not happen; if it does, don't let it go unnoticed so we can
1408 // fix it. Relevant visit*() function is probably missing a setValue().
1409 errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1410 << I.getModule()->getName() << "]\n";
1411 LLVM_DEBUG(I.dump());
1412 assert(false);
1413 }
1414 }
1415
1416 CurInst = nullptr;
1417}
1418
1419void SelectionDAGBuilder::visitPHI(const PHINode &) {
1420 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1421}
1422
1423void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1424 // Note: this doesn't use InstVisitor, because it has to work with
1425 // ConstantExpr's in addition to instructions.
1426 switch (Opcode) {
1427 default: llvm_unreachable("Unknown instruction type encountered!");
1428 // Build the switch statement using the Instruction.def file.
1429#define HANDLE_INST(NUM, OPCODE, CLASS) \
1430 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1431#include "llvm/IR/Instruction.def"
1432 }
1433}
1434
1435static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1436 DILocalVariable *Variable,
1437 DebugLoc DL, unsigned Order,
1438 SmallVectorImpl<Value *> &Values,
1439 DIExpression *Expression) {
1440 // For variadic dbg_values we will now insert poison.
1441 // FIXME: We can potentially recover these!
1442 SmallVector<SDDbgOperand, 2> Locs;
1443 for (const Value *V : Values) {
1444 auto *Poison = PoisonValue::get(T: V->getType());
1445 Locs.push_back(Elt: SDDbgOperand::fromConst(Const: Poison));
1446 }
1447 SDDbgValue *SDV = DAG.getDbgValueList(Var: Variable, Expr: Expression, Locs, Dependencies: {},
1448 /*IsIndirect=*/false, DL, O: Order,
1449 /*IsVariadic=*/true);
1450 DAG.AddDbgValue(DB: SDV, /*isParameter=*/false);
1451 return true;
1452}
1453
1454void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1455 DILocalVariable *Var,
1456 DIExpression *Expr,
1457 bool IsVariadic, DebugLoc DL,
1458 unsigned Order) {
1459 if (IsVariadic) {
1460 handleDanglingVariadicDebugInfo(DAG, Variable: Var, DL, Order, Values, Expression: Expr);
1461 return;
1462 }
1463 // TODO: Dangling debug info will eventually either be resolved or produce
1464 // a poison DBG_VALUE. However in the resolution case, a gap may appear
1465 // between the original dbg.value location and its resolved DBG_VALUE,
1466 // which we should ideally fill with an extra poison DBG_VALUE.
1467 assert(Values.size() == 1);
1468 DanglingDebugInfoMap[Values[0]].emplace_back(args&: Var, args&: Expr, args&: DL, args&: Order);
1469}
1470
1471void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1472 const DIExpression *Expr) {
1473 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1474 DIVariable *DanglingVariable = DDI.getVariable();
1475 DIExpression *DanglingExpr = DDI.getExpression();
1476 if (DanglingVariable == Variable && Expr->fragmentsOverlap(Other: DanglingExpr)) {
1477 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1478 << printDDI(nullptr, DDI) << "\n");
1479 return true;
1480 }
1481 return false;
1482 };
1483
1484 for (auto &DDIMI : DanglingDebugInfoMap) {
1485 DanglingDebugInfoVector &DDIV = DDIMI.second;
1486
1487 // If debug info is to be dropped, run it through final checks to see
1488 // whether it can be salvaged.
1489 for (auto &DDI : DDIV)
1490 if (isMatchingDbgValue(DDI))
1491 salvageUnresolvedDbgValue(V: DDIMI.first, DDI);
1492
1493 erase_if(C&: DDIV, P: isMatchingDbgValue);
1494 }
1495}
1496
1497// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1498// generate the debug data structures now that we've seen its definition.
1499void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1500 SDValue Val) {
1501 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(Key: V);
1502 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1503 return;
1504
1505 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1506 for (auto &DDI : DDIV) {
1507 DebugLoc DL = DDI.getDebugLoc();
1508 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1509 DILocalVariable *Variable = DDI.getVariable();
1510 DIExpression *Expr = DDI.getExpression();
1511 assert(Variable->isValidLocationForIntrinsic(DL) &&
1512 "Expected inlined-at fields to agree");
1513 SDDbgValue *SDV;
1514 if (Val.getNode()) {
1515 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1516 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1517 // we couldn't resolve it directly when examining the DbgValue intrinsic
1518 // in the first place we should not be more successful here). Unless we
1519 // have some test case that prove this to be correct we should avoid
1520 // calling EmitFuncArgumentDbgValue here.
1521 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1522 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1523 Kind: FuncArgumentDbgValueKind::Value, N: Val)) {
1524 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1525 << printDDI(V, DDI) << "\n");
1526 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1527 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1528 // inserted after the definition of Val when emitting the instructions
1529 // after ISel. An alternative could be to teach
1530 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1531 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1532 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1533 << ValSDNodeOrder << "\n");
1534 SDV = getDbgValue(N: Val, Variable, Expr, dl: DL,
1535 DbgSDNodeOrder: std::max(a: DbgSDNodeOrder, b: ValSDNodeOrder));
1536 DAG.AddDbgValue(DB: SDV, isParameter: false);
1537 } else
1538 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1539 << printDDI(V, DDI)
1540 << " in EmitFuncArgumentDbgValue\n");
1541 } else {
1542 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1543 << "\n");
1544 auto Poison = PoisonValue::get(T: V->getType());
1545 auto SDV =
1546 DAG.getConstantDbgValue(Var: Variable, Expr, C: Poison, DL, O: DbgSDNodeOrder);
1547 DAG.AddDbgValue(DB: SDV, isParameter: false);
1548 }
1549 }
1550 DDIV.clear();
1551}
1552
1553void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1554 DanglingDebugInfo &DDI) {
1555 // TODO: For the variadic implementation, instead of only checking the fail
1556 // state of `handleDebugValue`, we need know specifically which values were
1557 // invalid, so that we attempt to salvage only those values when processing
1558 // a DIArgList.
1559 const Value *OrigV = V;
1560 DILocalVariable *Var = DDI.getVariable();
1561 DIExpression *Expr = DDI.getExpression();
1562 DebugLoc DL = DDI.getDebugLoc();
1563 unsigned SDOrder = DDI.getSDNodeOrder();
1564
1565 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1566 // that DW_OP_stack_value is desired.
1567 bool StackValue = true;
1568
1569 // Can this Value can be encoded without any further work?
1570 if (handleDebugValue(Values: V, Var, Expr, DbgLoc: DL, Order: SDOrder, /*IsVariadic=*/false))
1571 return;
1572
1573 // Attempt to salvage back through as many instructions as possible. Bail if
1574 // a non-instruction is seen, such as a constant expression or global
1575 // variable. FIXME: Further work could recover those too.
1576 while (isa<Instruction>(Val: V)) {
1577 const Instruction &VAsInst = *cast<const Instruction>(Val: V);
1578 // Temporary "0", awaiting real implementation.
1579 SmallVector<uint64_t, 16> Ops;
1580 SmallVector<Value *, 4> AdditionalValues;
1581 V = salvageDebugInfoImpl(I&: const_cast<Instruction &>(VAsInst),
1582 CurrentLocOps: Expr->getNumLocationOperands(), Ops,
1583 AdditionalValues);
1584 // If we cannot salvage any further, and haven't yet found a suitable debug
1585 // expression, bail out.
1586 if (!V)
1587 break;
1588
1589 // TODO: If AdditionalValues isn't empty, then the salvage can only be
1590 // represented with a DBG_VALUE_LIST, so we give up. When we have support
1591 // here for variadic dbg_values, remove that condition.
1592 if (!AdditionalValues.empty())
1593 break;
1594
1595 // New value and expr now represent this debuginfo.
1596 Expr = DIExpression::appendOpsToArg(Expr, Ops, ArgNo: 0, StackValue);
1597
1598 // Some kind of simplification occurred: check whether the operand of the
1599 // salvaged debug expression can be encoded in this DAG.
1600 if (handleDebugValue(Values: V, Var, Expr, DbgLoc: DL, Order: SDOrder, /*IsVariadic=*/false)) {
1601 LLVM_DEBUG(
1602 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n"
1603 << *OrigV << "\nBy stripping back to:\n " << *V << "\n");
1604 return;
1605 }
1606 }
1607
1608 // This was the final opportunity to salvage this debug information, and it
1609 // couldn't be done. Place a poison DBG_VALUE at this location to terminate
1610 // any earlier variable location.
1611 assert(OrigV && "V shouldn't be null");
1612 auto *Poison = PoisonValue::get(T: OrigV->getType());
1613 auto *SDV = DAG.getConstantDbgValue(Var, Expr, C: Poison, DL, O: SDNodeOrder);
1614 DAG.AddDbgValue(DB: SDV, isParameter: false);
1615 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n "
1616 << printDDI(OrigV, DDI) << "\n");
1617}
1618
1619void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1620 DIExpression *Expr,
1621 DebugLoc DbgLoc,
1622 unsigned Order) {
1623 Value *Poison = PoisonValue::get(T: Type::getInt1Ty(C&: *Context));
1624 DIExpression *NewExpr =
1625 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1626 handleDebugValue(Values: Poison, Var, Expr: NewExpr, DbgLoc, Order,
1627 /*IsVariadic*/ false);
1628}
1629
1630bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1631 DILocalVariable *Var,
1632 DIExpression *Expr, DebugLoc DbgLoc,
1633 unsigned Order, bool IsVariadic) {
1634 if (Values.empty())
1635 return true;
1636
1637 // Filter EntryValue locations out early.
1638 if (visitEntryValueDbgValue(Values, Variable: Var, Expr, DbgLoc))
1639 return true;
1640
1641 SmallVector<SDDbgOperand> LocationOps;
1642 SmallVector<SDNode *> Dependencies;
1643 for (const Value *V : Values) {
1644 // Constant value.
1645 if (isa<ConstantInt>(Val: V) || isa<ConstantFP>(Val: V) || isa<UndefValue>(Val: V) ||
1646 isa<ConstantPointerNull>(Val: V)) {
1647 LocationOps.emplace_back(Args: SDDbgOperand::fromConst(Const: V));
1648 continue;
1649 }
1650
1651 // Look through IntToPtr constants.
1652 if (auto *CE = dyn_cast<ConstantExpr>(Val: V))
1653 if (CE->getOpcode() == Instruction::IntToPtr) {
1654 LocationOps.emplace_back(Args: SDDbgOperand::fromConst(Const: CE->getOperand(i_nocapture: 0)));
1655 continue;
1656 }
1657
1658 // If the Value is a frame index, we can create a FrameIndex debug value
1659 // without relying on the DAG at all.
1660 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Val: V)) {
1661 auto SI = FuncInfo.StaticAllocaMap.find(Val: AI);
1662 if (SI != FuncInfo.StaticAllocaMap.end()) {
1663 LocationOps.emplace_back(Args: SDDbgOperand::fromFrameIdx(FrameIdx: SI->second));
1664 continue;
1665 }
1666 }
1667
1668 // Do not use getValue() in here; we don't want to generate code at
1669 // this point if it hasn't been done yet.
1670 SDValue N = NodeMap[V];
1671 if (!N.getNode() && isa<Argument>(Val: V)) // Check unused arguments map.
1672 N = UnusedArgNodeMap[V];
1673
1674 if (N.getNode()) {
1675 // Only emit func arg dbg value for non-variadic dbg.values for now.
1676 if (!IsVariadic &&
1677 EmitFuncArgumentDbgValue(V, Variable: Var, Expr, DL: DbgLoc,
1678 Kind: FuncArgumentDbgValueKind::Value, N))
1679 return true;
1680 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Val: N.getNode())) {
1681 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1682 // describe stack slot locations.
1683 //
1684 // Consider "int x = 0; int *px = &x;". There are two kinds of
1685 // interesting debug values here after optimization:
1686 //
1687 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
1688 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1689 //
1690 // Both describe the direct values of their associated variables.
1691 Dependencies.push_back(Elt: N.getNode());
1692 LocationOps.emplace_back(Args: SDDbgOperand::fromFrameIdx(FrameIdx: FISDN->getIndex()));
1693 continue;
1694 }
1695 LocationOps.emplace_back(
1696 Args: SDDbgOperand::fromNode(Node: N.getNode(), ResNo: N.getResNo()));
1697 continue;
1698 }
1699
1700 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1701 // Special rules apply for the first dbg.values of parameter variables in a
1702 // function. Identify them by the fact they reference Argument Values, that
1703 // they're parameters, and they are parameters of the current function. We
1704 // need to let them dangle until they get an SDNode.
1705 bool IsParamOfFunc =
1706 isa<Argument>(Val: V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1707 if (IsParamOfFunc)
1708 return false;
1709
1710 // The value is not used in this block yet (or it would have an SDNode).
1711 // We still want the value to appear for the user if possible -- if it has
1712 // an associated VReg, we can refer to that instead.
1713 auto VMI = FuncInfo.ValueMap.find(Val: V);
1714 if (VMI != FuncInfo.ValueMap.end()) {
1715 Register Reg = VMI->second;
1716 // If this is a PHI node, it may be split up into several MI PHI nodes
1717 // (in FunctionLoweringInfo::set).
1718 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1719 V->getType(), std::nullopt);
1720 if (RFV.occupiesMultipleRegs()) {
1721 // FIXME: We could potentially support variadic dbg_values here.
1722 if (IsVariadic)
1723 return false;
1724 unsigned Offset = 0;
1725 unsigned BitsToDescribe = 0;
1726 if (auto VarSize = Var->getSizeInBits())
1727 BitsToDescribe = *VarSize;
1728 if (auto Fragment = Expr->getFragmentInfo())
1729 BitsToDescribe = Fragment->SizeInBits;
1730 for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1731 // Bail out if all bits are described already.
1732 if (Offset >= BitsToDescribe)
1733 break;
1734 // TODO: handle scalable vectors.
1735 unsigned RegisterSize = RegAndSize.second;
1736 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1737 ? BitsToDescribe - Offset
1738 : RegisterSize;
1739 auto FragmentExpr = DIExpression::createFragmentExpression(
1740 Expr, OffsetInBits: Offset, SizeInBits: FragmentSize);
1741 if (!FragmentExpr)
1742 continue;
1743 SDDbgValue *SDV = DAG.getVRegDbgValue(
1744 Var, Expr: *FragmentExpr, VReg: RegAndSize.first, IsIndirect: false, DL: DbgLoc, O: Order);
1745 DAG.AddDbgValue(DB: SDV, isParameter: false);
1746 Offset += RegisterSize;
1747 }
1748 return true;
1749 }
1750 // We can use simple vreg locations for variadic dbg_values as well.
1751 LocationOps.emplace_back(Args: SDDbgOperand::fromVReg(VReg: Reg));
1752 continue;
1753 }
1754 // We failed to create a SDDbgOperand for V.
1755 return false;
1756 }
1757
1758 // We have created a SDDbgOperand for each Value in Values.
1759 assert(!LocationOps.empty());
1760 SDDbgValue *SDV =
1761 DAG.getDbgValueList(Var, Expr, Locs: LocationOps, Dependencies,
1762 /*IsIndirect=*/false, DL: DbgLoc, O: Order, IsVariadic);
1763 DAG.AddDbgValue(DB: SDV, /*isParameter=*/false);
1764 return true;
1765}
1766
1767void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1768 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1769 for (auto &Pair : DanglingDebugInfoMap)
1770 for (auto &DDI : Pair.second)
1771 salvageUnresolvedDbgValue(V: const_cast<Value *>(Pair.first), DDI);
1772 clearDanglingDebugInfo();
1773}
1774
1775/// getCopyFromRegs - If there was virtual register allocated for the value V
1776/// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1777SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1778 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(Val: V);
1779 SDValue Result;
1780
1781 if (It != FuncInfo.ValueMap.end()) {
1782 Register InReg = It->second;
1783
1784 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1785 DAG.getDataLayout(), InReg, Ty,
1786 std::nullopt); // This is not an ABI copy.
1787 SDValue Chain = DAG.getEntryNode();
1788 Result = RFV.getCopyFromRegs(DAG, FuncInfo, dl: getCurSDLoc(), Chain, Glue: nullptr,
1789 V);
1790 resolveDanglingDebugInfo(V, Val: Result);
1791 }
1792
1793 return Result;
1794}
1795
1796/// getValue - Return an SDValue for the given Value.
1797SDValue SelectionDAGBuilder::getValue(const Value *V) {
1798 // If we already have an SDValue for this value, use it. It's important
1799 // to do this first, so that we don't create a CopyFromReg if we already
1800 // have a regular SDValue.
1801 SDValue &N = NodeMap[V];
1802 if (N.getNode()) return N;
1803
1804 // If there's a virtual register allocated and initialized for this
1805 // value, use it.
1806 if (SDValue copyFromReg = getCopyFromRegs(V, Ty: V->getType()))
1807 return copyFromReg;
1808
1809 // Otherwise create a new SDValue and remember it.
1810 SDValue Val = getValueImpl(V);
1811 NodeMap[V] = Val;
1812 resolveDanglingDebugInfo(V, Val);
1813 return Val;
1814}
1815
1816/// getNonRegisterValue - Return an SDValue for the given Value, but
1817/// don't look in FuncInfo.ValueMap for a virtual register.
1818SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1819 // If we already have an SDValue for this value, use it.
1820 SDValue &N = NodeMap[V];
1821 if (N.getNode()) {
1822 if (isIntOrFPConstant(V: N)) {
1823 // Remove the debug location from the node as the node is about to be used
1824 // in a location which may differ from the original debug location. This
1825 // is relevant to Constant and ConstantFP nodes because they can appear
1826 // as constant expressions inside PHI nodes.
1827 N->setDebugLoc(DebugLoc());
1828 }
1829 return N;
1830 }
1831
1832 // Otherwise create a new SDValue and remember it.
1833 SDValue Val = getValueImpl(V);
1834 NodeMap[V] = Val;
1835 resolveDanglingDebugInfo(V, Val);
1836 return Val;
1837}
1838
1839/// getValueImpl - Helper function for getValue and getNonRegisterValue.
1840/// Create an SDValue for the given value.
1841SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1842 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1843
1844 if (const Constant *C = dyn_cast<Constant>(Val: V)) {
1845 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: V->getType(), AllowUnknown: true);
1846
1847 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: C)) {
1848 SDLoc DL = getCurSDLoc();
1849
1850 // DAG.getConstant() may attempt to legalise the vector constant which can
1851 // significantly change the combines applied to the DAG. To reduce the
1852 // divergence when enabling ConstantInt based vectors we try to construct
1853 // the DAG in the same way as shufflevector based splats. TODO: The
1854 // divergence sometimes leads to better optimisations. Ideally we should
1855 // prevent DAG.getConstant() from legalising too early but there are some
1856 // degradations preventing this.
1857 if (VT.isScalableVector())
1858 return DAG.getNode(
1859 Opcode: ISD::SPLAT_VECTOR, DL, VT,
1860 Operand: DAG.getConstant(Val: CI->getValue(), DL, VT: VT.getVectorElementType()));
1861 if (VT.isFixedLengthVector())
1862 return DAG.getSplatBuildVector(
1863 VT, DL,
1864 Op: DAG.getConstant(Val: CI->getValue(), DL, VT: VT.getVectorElementType()));
1865 return DAG.getConstant(Val: *CI, DL, VT);
1866 }
1867
1868 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Val: C))
1869 return DAG.getGlobalAddress(GV, DL: getCurSDLoc(), VT);
1870
1871 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(Val: C)) {
1872 return DAG.getNode(Opcode: ISD::PtrAuthGlobalAddress, DL: getCurSDLoc(), VT,
1873 N1: getValue(V: CPA->getPointer()), N2: getValue(V: CPA->getKey()),
1874 N3: getValue(V: CPA->getAddrDiscriminator()),
1875 N4: getValue(V: CPA->getDiscriminator()));
1876 }
1877
1878 if (isa<ConstantPointerNull>(Val: C))
1879 return DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT);
1880
1881 if (match(V: C, P: m_VScale()))
1882 return DAG.getVScale(DL: getCurSDLoc(), VT, MulImm: APInt(VT.getSizeInBits(), 1));
1883
1884 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Val: C))
1885 return DAG.getConstantFP(V: *CFP, DL: getCurSDLoc(), VT);
1886
1887 if (isa<UndefValue>(Val: C) && !V->getType()->isAggregateType())
1888 return isa<PoisonValue>(Val: C) ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
1889
1890 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: C)) {
1891 visit(Opcode: CE->getOpcode(), I: *CE);
1892 SDValue N1 = NodeMap[V];
1893 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1894 return N1;
1895 }
1896
1897 if (isa<ConstantStruct>(Val: C) || isa<ConstantArray>(Val: C)) {
1898 SmallVector<SDValue, 4> Constants;
1899 for (const Use &U : C->operands()) {
1900 SDNode *Val = getValue(V: U).getNode();
1901 // If the operand is an empty aggregate, there are no values.
1902 if (!Val) continue;
1903 // Add each leaf value from the operand to the Constants list
1904 // to form a flattened list of all the values.
1905 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1906 Constants.push_back(Elt: SDValue(Val, i));
1907 }
1908
1909 return DAG.getMergeValues(Ops: Constants, dl: getCurSDLoc());
1910 }
1911
1912 if (const ConstantDataSequential *CDS =
1913 dyn_cast<ConstantDataSequential>(Val: C)) {
1914 SmallVector<SDValue, 4> Ops;
1915 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i) {
1916 SDNode *Val = getValue(V: CDS->getElementAsConstant(i)).getNode();
1917 // Add each leaf value from the operand to the Constants list
1918 // to form a flattened list of all the values.
1919 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1920 Ops.push_back(Elt: SDValue(Val, i));
1921 }
1922
1923 if (isa<ArrayType>(Val: CDS->getType()))
1924 return DAG.getMergeValues(Ops, dl: getCurSDLoc());
1925 return DAG.getBuildVector(VT, DL: getCurSDLoc(), Ops);
1926 }
1927
1928 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1929 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1930 "Unknown struct or array constant!");
1931
1932 SmallVector<EVT, 4> ValueVTs;
1933 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: C->getType(), ValueVTs);
1934 unsigned NumElts = ValueVTs.size();
1935 if (NumElts == 0)
1936 return SDValue(); // empty struct
1937 SmallVector<SDValue, 4> Constants(NumElts);
1938 for (unsigned i = 0; i != NumElts; ++i) {
1939 EVT EltVT = ValueVTs[i];
1940 if (isa<UndefValue>(Val: C))
1941 Constants[i] = DAG.getUNDEF(VT: EltVT);
1942 else if (EltVT.isFloatingPoint())
1943 Constants[i] = DAG.getConstantFP(Val: 0, DL: getCurSDLoc(), VT: EltVT);
1944 else
1945 Constants[i] = DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: EltVT);
1946 }
1947
1948 return DAG.getMergeValues(Ops: Constants, dl: getCurSDLoc());
1949 }
1950
1951 if (const BlockAddress *BA = dyn_cast<BlockAddress>(Val: C))
1952 return DAG.getBlockAddress(BA, VT);
1953
1954 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(Val: C))
1955 return getValue(V: Equiv->getGlobalValue());
1956
1957 if (const auto *NC = dyn_cast<NoCFIValue>(Val: C))
1958 return getValue(V: NC->getGlobalValue());
1959
1960 if (VT == MVT::aarch64svcount) {
1961 assert(C->isNullValue() && "Can only zero this target type!");
1962 return DAG.getNode(Opcode: ISD::BITCAST, DL: getCurSDLoc(), VT,
1963 Operand: DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: MVT::nxv16i1));
1964 }
1965
1966 if (VT.isRISCVVectorTuple()) {
1967 assert(C->isNullValue() && "Can only zero this target type!");
1968 return DAG.getNode(
1969 Opcode: ISD::BITCAST, DL: getCurSDLoc(), VT,
1970 Operand: DAG.getNode(
1971 Opcode: ISD::SPLAT_VECTOR, DL: getCurSDLoc(),
1972 VT: EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::i8,
1973 NumElements: VT.getSizeInBits().getKnownMinValue() / 8, IsScalable: true),
1974 Operand: DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: MVT::getIntegerVT(BitWidth: 8))));
1975 }
1976
1977 VectorType *VecTy = cast<VectorType>(Val: V->getType());
1978
1979 // Now that we know the number and type of the elements, get that number of
1980 // elements into the Ops array based on what kind of constant it is.
1981 if (const ConstantVector *CV = dyn_cast<ConstantVector>(Val: C)) {
1982 SmallVector<SDValue, 16> Ops;
1983 unsigned NumElements = cast<FixedVectorType>(Val: VecTy)->getNumElements();
1984 for (unsigned i = 0; i != NumElements; ++i)
1985 Ops.push_back(Elt: getValue(V: CV->getOperand(i_nocapture: i)));
1986
1987 return DAG.getBuildVector(VT, DL: getCurSDLoc(), Ops);
1988 }
1989
1990 if (isa<ConstantAggregateZero>(Val: C)) {
1991 EVT EltVT =
1992 TLI.getValueType(DL: DAG.getDataLayout(), Ty: VecTy->getElementType());
1993
1994 SDValue Op;
1995 if (EltVT.isFloatingPoint())
1996 Op = DAG.getConstantFP(Val: 0, DL: getCurSDLoc(), VT: EltVT);
1997 else
1998 Op = DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: EltVT);
1999
2000 return DAG.getSplat(VT, DL: getCurSDLoc(), Op);
2001 }
2002
2003 llvm_unreachable("Unknown vector constant");
2004 }
2005
2006 // If this is a static alloca, generate it as the frameindex instead of
2007 // computation.
2008 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Val: V)) {
2009 DenseMap<const AllocaInst*, int>::iterator SI =
2010 FuncInfo.StaticAllocaMap.find(Val: AI);
2011 if (SI != FuncInfo.StaticAllocaMap.end())
2012 return DAG.getFrameIndex(
2013 FI: SI->second, VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: AI->getType()));
2014 }
2015
2016 // If this is an instruction which fast-isel has deferred, select it now.
2017 if (const Instruction *Inst = dyn_cast<Instruction>(Val: V)) {
2018 Register InReg = FuncInfo.InitializeRegForValue(V: Inst);
2019
2020 std::optional<CallingConv::ID> CallConv;
2021 auto *CB = dyn_cast<CallBase>(Val: Inst);
2022 if (CB && !CB->isInlineAsm())
2023 CallConv = CB->getCallingConv();
2024
2025 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
2026 Inst->getType(), CallConv);
2027 SDValue Chain = DAG.getEntryNode();
2028 return RFV.getCopyFromRegs(DAG, FuncInfo, dl: getCurSDLoc(), Chain, Glue: nullptr, V);
2029 }
2030
2031 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(Val: V))
2032 return DAG.getMDNode(MD: cast<MDNode>(Val: MD->getMetadata()));
2033
2034 if (const auto *BB = dyn_cast<BasicBlock>(Val: V))
2035 return DAG.getBasicBlock(MBB: FuncInfo.getMBB(BB));
2036
2037 llvm_unreachable("Can't get register for value!");
2038}
2039
2040void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
2041 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2042 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
2043 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
2044 bool IsSEH = isAsynchronousEHPersonality(Pers);
2045 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
2046 if (IsSEH) {
2047 // For SEH, EHCont Guard needs to know that this catchpad is a target.
2048 CatchPadMBB->setIsEHContTarget(true);
2049 DAG.getMachineFunction().setHasEHContTarget(true);
2050 } else
2051 CatchPadMBB->setIsEHScopeEntry();
2052 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
2053 if (IsMSVCCXX || IsCoreCLR)
2054 CatchPadMBB->setIsEHFuncletEntry();
2055}
2056
2057void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
2058 // Update machine-CFG edge.
2059 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(BB: I.getSuccessor());
2060 FuncInfo.MBB->addSuccessor(Succ: TargetMBB);
2061
2062 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2063 bool IsSEH = isAsynchronousEHPersonality(Pers);
2064 if (IsSEH) {
2065 // If this is not a fall-through branch or optimizations are switched off,
2066 // emit the branch.
2067 if (TargetMBB != NextBlock(MBB: FuncInfo.MBB) ||
2068 TM.getOptLevel() == CodeGenOptLevel::None)
2069 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other,
2070 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: TargetMBB)));
2071 return;
2072 }
2073
2074 // For non-SEH, EHCont Guard needs to know that this catchret is a target.
2075 TargetMBB->setIsEHContTarget(true);
2076 DAG.getMachineFunction().setHasEHContTarget(true);
2077
2078 // Figure out the funclet membership for the catchret's successor.
2079 // This will be used by the FuncletLayout pass to determine how to order the
2080 // BB's.
2081 // A 'catchret' returns to the outer scope's color.
2082 Value *ParentPad = I.getCatchSwitchParentPad();
2083 const BasicBlock *SuccessorColor;
2084 if (isa<ConstantTokenNone>(Val: ParentPad))
2085 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2086 else
2087 SuccessorColor = cast<Instruction>(Val: ParentPad)->getParent();
2088 assert(SuccessorColor && "No parent funclet for catchret!");
2089 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(BB: SuccessorColor);
2090 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2091
2092 // Create the terminator node.
2093 SDValue Ret = DAG.getNode(Opcode: ISD::CATCHRET, DL: getCurSDLoc(), VT: MVT::Other,
2094 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: TargetMBB),
2095 N3: DAG.getBasicBlock(MBB: SuccessorColorMBB));
2096 DAG.setRoot(Ret);
2097}
2098
2099void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2100 // Don't emit any special code for the cleanuppad instruction. It just marks
2101 // the start of an EH scope/funclet.
2102 FuncInfo.MBB->setIsEHScopeEntry();
2103 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2104 if (Pers != EHPersonality::Wasm_CXX) {
2105 FuncInfo.MBB->setIsEHFuncletEntry();
2106 FuncInfo.MBB->setIsCleanupFuncletEntry();
2107 }
2108}
2109
2110/// When an invoke or a cleanupret unwinds to the next EH pad, there are
2111/// many places it could ultimately go. In the IR, we have a single unwind
2112/// destination, but in the machine CFG, we enumerate all the possible blocks.
2113/// This function skips over imaginary basic blocks that hold catchswitch
2114/// instructions, and finds all the "real" machine
2115/// basic block destinations. As those destinations may not be successors of
2116/// EHPadBB, here we also calculate the edge probability to those destinations.
2117/// The passed-in Prob is the edge probability to EHPadBB.
2118static void findUnwindDestinations(
2119 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2120 BranchProbability Prob,
2121 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2122 &UnwindDests) {
2123 EHPersonality Personality =
2124 classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2125 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2126 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2127 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2128 bool IsSEH = isAsynchronousEHPersonality(Pers: Personality);
2129
2130 while (EHPadBB) {
2131 BasicBlock::const_iterator Pad = EHPadBB->getFirstNonPHIIt();
2132 BasicBlock *NewEHPadBB = nullptr;
2133 if (isa<LandingPadInst>(Val: Pad)) {
2134 // Stop on landingpads. They are not funclets.
2135 UnwindDests.emplace_back(Args: FuncInfo.getMBB(BB: EHPadBB), Args&: Prob);
2136 break;
2137 } else if (isa<CleanupPadInst>(Val: Pad)) {
2138 // Stop on cleanup pads. Cleanups are always funclet entries for all known
2139 // personalities except Wasm. And in Wasm this becomes a catch_all(_ref),
2140 // which always catches an exception.
2141 UnwindDests.emplace_back(Args: FuncInfo.getMBB(BB: EHPadBB), Args&: Prob);
2142 UnwindDests.back().first->setIsEHScopeEntry();
2143 // In Wasm, EH scopes are not funclets
2144 if (!IsWasmCXX)
2145 UnwindDests.back().first->setIsEHFuncletEntry();
2146 break;
2147 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Val&: Pad)) {
2148 // Add the catchpad handlers to the possible destinations.
2149 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2150 UnwindDests.emplace_back(Args: FuncInfo.getMBB(BB: CatchPadBB), Args&: Prob);
2151 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2152 if (IsMSVCCXX || IsCoreCLR)
2153 UnwindDests.back().first->setIsEHFuncletEntry();
2154 if (!IsSEH)
2155 UnwindDests.back().first->setIsEHScopeEntry();
2156 }
2157 NewEHPadBB = CatchSwitch->getUnwindDest();
2158 } else {
2159 continue;
2160 }
2161
2162 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2163 if (BPI && NewEHPadBB)
2164 Prob *= BPI->getEdgeProbability(Src: EHPadBB, Dst: NewEHPadBB);
2165 EHPadBB = NewEHPadBB;
2166 }
2167}
2168
2169void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2170 // Update successor info.
2171 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2172 auto UnwindDest = I.getUnwindDest();
2173 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2174 BranchProbability UnwindDestProb =
2175 (BPI && UnwindDest)
2176 ? BPI->getEdgeProbability(Src: FuncInfo.MBB->getBasicBlock(), Dst: UnwindDest)
2177 : BranchProbability::getZero();
2178 findUnwindDestinations(FuncInfo, EHPadBB: UnwindDest, Prob: UnwindDestProb, UnwindDests);
2179 for (auto &UnwindDest : UnwindDests) {
2180 UnwindDest.first->setIsEHPad();
2181 addSuccessorWithProb(Src: FuncInfo.MBB, Dst: UnwindDest.first, Prob: UnwindDest.second);
2182 }
2183 FuncInfo.MBB->normalizeSuccProbs();
2184
2185 // Create the terminator node.
2186 MachineBasicBlock *CleanupPadMBB =
2187 FuncInfo.getMBB(BB: I.getCleanupPad()->getParent());
2188 SDValue Ret = DAG.getNode(Opcode: ISD::CLEANUPRET, DL: getCurSDLoc(), VT: MVT::Other,
2189 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: CleanupPadMBB));
2190 DAG.setRoot(Ret);
2191}
2192
2193void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2194 report_fatal_error(reason: "visitCatchSwitch not yet implemented!");
2195}
2196
2197void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2198 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2199 auto &DL = DAG.getDataLayout();
2200 SDValue Chain = getControlRoot();
2201 SmallVector<ISD::OutputArg, 8> Outs;
2202 SmallVector<SDValue, 8> OutVals;
2203
2204 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2205 // lower
2206 //
2207 // %val = call <ty> @llvm.experimental.deoptimize()
2208 // ret <ty> %val
2209 //
2210 // differently.
2211 if (I.getParent()->getTerminatingDeoptimizeCall()) {
2212 LowerDeoptimizingReturn();
2213 return;
2214 }
2215
2216 if (!FuncInfo.CanLowerReturn) {
2217 Register DemoteReg = FuncInfo.DemoteRegister;
2218
2219 // Emit a store of the return value through the virtual register.
2220 // Leave Outs empty so that LowerReturn won't try to load return
2221 // registers the usual way.
2222 MVT PtrValueVT = TLI.getPointerTy(DL, AS: DL.getAllocaAddrSpace());
2223 SDValue RetPtr =
2224 DAG.getCopyFromReg(Chain, dl: getCurSDLoc(), Reg: DemoteReg, VT: PtrValueVT);
2225 SDValue RetOp = getValue(V: I.getOperand(i_nocapture: 0));
2226
2227 SmallVector<EVT, 4> ValueVTs, MemVTs;
2228 SmallVector<uint64_t, 4> Offsets;
2229 ComputeValueVTs(TLI, DL, Ty: I.getOperand(i_nocapture: 0)->getType(), ValueVTs, MemVTs: &MemVTs,
2230 FixedOffsets: &Offsets, StartingOffset: 0);
2231 unsigned NumValues = ValueVTs.size();
2232
2233 SmallVector<SDValue, 4> Chains(NumValues);
2234 Align BaseAlign = DL.getPrefTypeAlign(Ty: I.getOperand(i_nocapture: 0)->getType());
2235 for (unsigned i = 0; i != NumValues; ++i) {
2236 // An aggregate return value cannot wrap around the address space, so
2237 // offsets to its parts don't wrap either.
2238 SDValue Ptr = DAG.getObjectPtrOffset(SL: getCurSDLoc(), Ptr: RetPtr,
2239 Offset: TypeSize::getFixed(ExactSize: Offsets[i]));
2240
2241 SDValue Val = RetOp.getValue(R: RetOp.getResNo() + i);
2242 if (MemVTs[i] != ValueVTs[i])
2243 Val = DAG.getPtrExtOrTrunc(Op: Val, DL: getCurSDLoc(), VT: MemVTs[i]);
2244 Chains[i] = DAG.getStore(
2245 Chain, dl: getCurSDLoc(), Val,
2246 // FIXME: better loc info would be nice.
2247 Ptr, PtrInfo: MachinePointerInfo::getUnknownStack(MF&: DAG.getMachineFunction()),
2248 Alignment: commonAlignment(A: BaseAlign, Offset: Offsets[i]));
2249 }
2250
2251 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: getCurSDLoc(),
2252 VT: MVT::Other, Ops: Chains);
2253 } else if (I.getNumOperands() != 0) {
2254 SmallVector<Type *, 4> Types;
2255 ComputeValueTypes(DL, Ty: I.getOperand(i_nocapture: 0)->getType(), Types);
2256 unsigned NumValues = Types.size();
2257 if (NumValues) {
2258 SDValue RetOp = getValue(V: I.getOperand(i_nocapture: 0));
2259
2260 const Function *F = I.getParent()->getParent();
2261
2262 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2263 Ty: I.getOperand(i_nocapture: 0)->getType(), CallConv: F->getCallingConv(),
2264 /*IsVarArg*/ isVarArg: false, DL);
2265
2266 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2267 if (F->getAttributes().hasRetAttr(Kind: Attribute::SExt))
2268 ExtendKind = ISD::SIGN_EXTEND;
2269 else if (F->getAttributes().hasRetAttr(Kind: Attribute::ZExt))
2270 ExtendKind = ISD::ZERO_EXTEND;
2271
2272 LLVMContext &Context = F->getContext();
2273 bool RetInReg = F->getAttributes().hasRetAttr(Kind: Attribute::InReg);
2274
2275 for (unsigned j = 0; j != NumValues; ++j) {
2276 EVT VT = TLI.getValueType(DL, Ty: Types[j]);
2277
2278 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2279 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2280
2281 CallingConv::ID CC = F->getCallingConv();
2282
2283 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2284 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2285 SmallVector<SDValue, 4> Parts(NumParts);
2286 getCopyToParts(DAG, DL: getCurSDLoc(),
2287 Val: SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2288 Parts: &Parts[0], NumParts, PartVT, V: &I, CallConv: CC, ExtendKind);
2289
2290 // 'inreg' on function refers to return value
2291 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2292 if (RetInReg)
2293 Flags.setInReg();
2294
2295 if (I.getOperand(i_nocapture: 0)->getType()->isPointerTy()) {
2296 Flags.setPointer();
2297 Flags.setPointerAddrSpace(
2298 cast<PointerType>(Val: I.getOperand(i_nocapture: 0)->getType())->getAddressSpace());
2299 }
2300
2301 if (NeedsRegBlock) {
2302 Flags.setInConsecutiveRegs();
2303 if (j == NumValues - 1)
2304 Flags.setInConsecutiveRegsLast();
2305 }
2306
2307 // Propagate extension type if any
2308 if (ExtendKind == ISD::SIGN_EXTEND)
2309 Flags.setSExt();
2310 else if (ExtendKind == ISD::ZERO_EXTEND)
2311 Flags.setZExt();
2312 else if (F->getAttributes().hasRetAttr(Kind: Attribute::NoExt))
2313 Flags.setNoExt();
2314
2315 for (unsigned i = 0; i < NumParts; ++i) {
2316 Outs.push_back(Elt: ISD::OutputArg(Flags,
2317 Parts[i].getValueType().getSimpleVT(),
2318 VT, Types[j], 0, 0));
2319 OutVals.push_back(Elt: Parts[i]);
2320 }
2321 }
2322 }
2323 }
2324
2325 // Push in swifterror virtual register as the last element of Outs. This makes
2326 // sure swifterror virtual register will be returned in the swifterror
2327 // physical register.
2328 const Function *F = I.getParent()->getParent();
2329 if (TLI.supportSwiftError() &&
2330 F->getAttributes().hasAttrSomewhere(Kind: Attribute::SwiftError)) {
2331 assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2332 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2333 Flags.setSwiftError();
2334 Outs.push_back(Elt: ISD::OutputArg(Flags, /*vt=*/TLI.getPointerTy(DL),
2335 /*argvt=*/EVT(TLI.getPointerTy(DL)),
2336 PointerType::getUnqual(C&: *DAG.getContext()),
2337 /*origidx=*/1, /*partOffs=*/0));
2338 // Create SDNode for the swifterror virtual register.
2339 OutVals.push_back(
2340 Elt: DAG.getRegister(Reg: SwiftError.getOrCreateVRegUseAt(
2341 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2342 VT: EVT(TLI.getPointerTy(DL))));
2343 }
2344
2345 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2346 CallingConv::ID CallConv =
2347 DAG.getMachineFunction().getFunction().getCallingConv();
2348 Chain = DAG.getTargetLoweringInfo().LowerReturn(
2349 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2350
2351 // Verify that the target's LowerReturn behaved as expected.
2352 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2353 "LowerReturn didn't return a valid chain!");
2354
2355 // Update the DAG with the new chain value resulting from return lowering.
2356 DAG.setRoot(Chain);
2357}
2358
2359/// CopyToExportRegsIfNeeded - If the given value has virtual registers
2360/// created for it, emit nodes to copy the value into the virtual
2361/// registers.
2362void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2363 // Skip empty types
2364 if (V->getType()->isEmptyTy())
2365 return;
2366
2367 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(Val: V);
2368 if (VMI != FuncInfo.ValueMap.end()) {
2369 assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2370 "Unused value assigned virtual registers!");
2371 CopyValueToVirtualRegister(V, Reg: VMI->second);
2372 }
2373}
2374
2375/// ExportFromCurrentBlock - If this condition isn't known to be exported from
2376/// the current basic block, add it to ValueMap now so that we'll get a
2377/// CopyTo/FromReg.
2378void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2379 // No need to export constants.
2380 if (!isa<Instruction>(Val: V) && !isa<Argument>(Val: V)) return;
2381
2382 // Already exported?
2383 if (FuncInfo.isExportedInst(V)) return;
2384
2385 Register Reg = FuncInfo.InitializeRegForValue(V);
2386 CopyValueToVirtualRegister(V, Reg);
2387}
2388
2389bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2390 const BasicBlock *FromBB) {
2391 // The operands of the setcc have to be in this block. We don't know
2392 // how to export them from some other block.
2393 if (const Instruction *VI = dyn_cast<Instruction>(Val: V)) {
2394 // Can export from current BB.
2395 if (VI->getParent() == FromBB)
2396 return true;
2397
2398 // Is already exported, noop.
2399 return FuncInfo.isExportedInst(V);
2400 }
2401
2402 // If this is an argument, we can export it if the BB is the entry block or
2403 // if it is already exported.
2404 if (isa<Argument>(Val: V)) {
2405 if (FromBB->isEntryBlock())
2406 return true;
2407
2408 // Otherwise, can only export this if it is already exported.
2409 return FuncInfo.isExportedInst(V);
2410 }
2411
2412 // Otherwise, constants can always be exported.
2413 return true;
2414}
2415
2416/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2417BranchProbability
2418SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2419 const MachineBasicBlock *Dst) const {
2420 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2421 const BasicBlock *SrcBB = Src->getBasicBlock();
2422 const BasicBlock *DstBB = Dst->getBasicBlock();
2423 if (!BPI) {
2424 // If BPI is not available, set the default probability as 1 / N, where N is
2425 // the number of successors.
2426 auto SuccSize = std::max<uint32_t>(a: succ_size(BB: SrcBB), b: 1);
2427 return BranchProbability(1, SuccSize);
2428 }
2429 return BPI->getEdgeProbability(Src: SrcBB, Dst: DstBB);
2430}
2431
2432void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2433 MachineBasicBlock *Dst,
2434 BranchProbability Prob) {
2435 if (!FuncInfo.BPI)
2436 Src->addSuccessorWithoutProb(Succ: Dst);
2437 else {
2438 if (Prob.isUnknown())
2439 Prob = getEdgeProbability(Src, Dst);
2440 Src->addSuccessor(Succ: Dst, Prob);
2441 }
2442}
2443
2444static bool InBlock(const Value *V, const BasicBlock *BB) {
2445 if (const Instruction *I = dyn_cast<Instruction>(Val: V))
2446 return I->getParent() == BB;
2447 return true;
2448}
2449
2450/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2451/// This function emits a branch and is used at the leaves of an OR or an
2452/// AND operator tree.
2453void
2454SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2455 MachineBasicBlock *TBB,
2456 MachineBasicBlock *FBB,
2457 MachineBasicBlock *CurBB,
2458 MachineBasicBlock *SwitchBB,
2459 BranchProbability TProb,
2460 BranchProbability FProb,
2461 bool InvertCond) {
2462 const BasicBlock *BB = CurBB->getBasicBlock();
2463
2464 // If the leaf of the tree is a comparison, merge the condition into
2465 // the caseblock.
2466 if (const CmpInst *BOp = dyn_cast<CmpInst>(Val: Cond)) {
2467 // The operands of the cmp have to be in this block. We don't know
2468 // how to export them from some other block. If this is the first block
2469 // of the sequence, no exporting is needed.
2470 if (CurBB == SwitchBB ||
2471 (isExportableFromCurrentBlock(V: BOp->getOperand(i_nocapture: 0), FromBB: BB) &&
2472 isExportableFromCurrentBlock(V: BOp->getOperand(i_nocapture: 1), FromBB: BB))) {
2473 ISD::CondCode Condition;
2474 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Val: Cond)) {
2475 ICmpInst::Predicate Pred =
2476 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2477 Condition = getICmpCondCode(Pred);
2478 } else {
2479 const FCmpInst *FC = cast<FCmpInst>(Val: Cond);
2480 FCmpInst::Predicate Pred =
2481 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2482 Condition = getFCmpCondCode(Pred);
2483 if (FC->hasNoNaNs() ||
2484 (isKnownNeverNaN(V: FC->getOperand(i_nocapture: 0),
2485 SQ: SimplifyQuery(DAG.getDataLayout(), FC)) &&
2486 isKnownNeverNaN(V: FC->getOperand(i_nocapture: 1),
2487 SQ: SimplifyQuery(DAG.getDataLayout(), FC))))
2488 Condition = getFCmpCodeWithoutNaN(CC: Condition);
2489 }
2490
2491 CaseBlock CB(Condition, BOp->getOperand(i_nocapture: 0), BOp->getOperand(i_nocapture: 1), nullptr,
2492 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2493 SL->SwitchCases.push_back(x: CB);
2494 return;
2495 }
2496 }
2497
2498 // Create a CaseBlock record representing this branch.
2499 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2500 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(Context&: *DAG.getContext()),
2501 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2502 SL->SwitchCases.push_back(x: CB);
2503}
2504
2505// Collect dependencies on V recursively. This is used for the cost analysis in
2506// `shouldKeepJumpConditionsTogether`.
2507static bool collectInstructionDeps(
2508 SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2509 SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2510 unsigned Depth = 0) {
2511 // Return false if we have an incomplete count.
2512 if (Depth >= SelectionDAG::MaxRecursionDepth)
2513 return false;
2514
2515 auto *I = dyn_cast<Instruction>(Val: V);
2516 if (I == nullptr)
2517 return true;
2518
2519 if (Necessary != nullptr) {
2520 // This instruction is necessary for the other side of the condition so
2521 // don't count it.
2522 if (Necessary->contains(Key: I))
2523 return true;
2524 }
2525
2526 // Already added this dep.
2527 if (!Deps->try_emplace(Key: I, Args: false).second)
2528 return true;
2529
2530 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2531 if (!collectInstructionDeps(Deps, V: I->getOperand(i: OpIdx), Necessary,
2532 Depth: Depth + 1))
2533 return false;
2534 return true;
2535}
2536
2537bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2538 const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2539 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2540 TargetLoweringBase::CondMergingParams Params) const {
2541 if (I.getNumSuccessors() != 2)
2542 return false;
2543
2544 if (!I.isConditional())
2545 return false;
2546
2547 if (Params.BaseCost < 0)
2548 return false;
2549
2550 // Baseline cost.
2551 InstructionCost CostThresh = Params.BaseCost;
2552
2553 BranchProbabilityInfo *BPI = nullptr;
2554 if (Params.LikelyBias || Params.UnlikelyBias)
2555 BPI = FuncInfo.BPI;
2556 if (BPI != nullptr) {
2557 // See if we are either likely to get an early out or compute both lhs/rhs
2558 // of the condition.
2559 BasicBlock *IfFalse = I.getSuccessor(i: 0);
2560 BasicBlock *IfTrue = I.getSuccessor(i: 1);
2561
2562 std::optional<bool> Likely;
2563 if (BPI->isEdgeHot(Src: I.getParent(), Dst: IfTrue))
2564 Likely = true;
2565 else if (BPI->isEdgeHot(Src: I.getParent(), Dst: IfFalse))
2566 Likely = false;
2567
2568 if (Likely) {
2569 if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2570 // Its likely we will have to compute both lhs and rhs of condition
2571 CostThresh += Params.LikelyBias;
2572 else {
2573 if (Params.UnlikelyBias < 0)
2574 return false;
2575 // Its likely we will get an early out.
2576 CostThresh -= Params.UnlikelyBias;
2577 }
2578 }
2579 }
2580
2581 if (CostThresh <= 0)
2582 return false;
2583
2584 // Collect "all" instructions that lhs condition is dependent on.
2585 // Use map for stable iteration (to avoid non-determanism of iteration of
2586 // SmallPtrSet). The `bool` value is just a dummy.
2587 SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2588 collectInstructionDeps(Deps: &LhsDeps, V: Lhs);
2589 // Collect "all" instructions that rhs condition is dependent on AND are
2590 // dependencies of lhs. This gives us an estimate on which instructions we
2591 // stand to save by splitting the condition.
2592 if (!collectInstructionDeps(Deps: &RhsDeps, V: Rhs, Necessary: &LhsDeps))
2593 return false;
2594 // Add the compare instruction itself unless its a dependency on the LHS.
2595 if (const auto *RhsI = dyn_cast<Instruction>(Val: Rhs))
2596 if (!LhsDeps.contains(Key: RhsI))
2597 RhsDeps.try_emplace(Key: RhsI, Args: false);
2598
2599 InstructionCost CostOfIncluding = 0;
2600 // See if this instruction will need to computed independently of whether RHS
2601 // is.
2602 Value *BrCond = I.getCondition();
2603 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2604 for (const auto *U : Ins->users()) {
2605 // If user is independent of RHS calculation we don't need to count it.
2606 if (auto *UIns = dyn_cast<Instruction>(Val: U))
2607 if (UIns != BrCond && !RhsDeps.contains(Key: UIns))
2608 return false;
2609 }
2610 return true;
2611 };
2612
2613 // Prune instructions from RHS Deps that are dependencies of unrelated
2614 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2615 // arbitrary and just meant to cap the how much time we spend in the pruning
2616 // loop. Its highly unlikely to come into affect.
2617 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2618 // Stop after a certain point. No incorrectness from including too many
2619 // instructions.
2620 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2621 const Instruction *ToDrop = nullptr;
2622 for (const auto &InsPair : RhsDeps) {
2623 if (!ShouldCountInsn(InsPair.first)) {
2624 ToDrop = InsPair.first;
2625 break;
2626 }
2627 }
2628 if (ToDrop == nullptr)
2629 break;
2630 RhsDeps.erase(Key: ToDrop);
2631 }
2632
2633 for (const auto &InsPair : RhsDeps) {
2634 // Finally accumulate latency that we can only attribute to computing the
2635 // RHS condition. Use latency because we are essentially trying to calculate
2636 // the cost of the dependency chain.
2637 // Possible TODO: We could try to estimate ILP and make this more precise.
2638 CostOfIncluding += TTI->getInstructionCost(
2639 U: InsPair.first, CostKind: TargetTransformInfo::TCK_Latency);
2640
2641 if (CostOfIncluding > CostThresh)
2642 return false;
2643 }
2644 return true;
2645}
2646
2647void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2648 MachineBasicBlock *TBB,
2649 MachineBasicBlock *FBB,
2650 MachineBasicBlock *CurBB,
2651 MachineBasicBlock *SwitchBB,
2652 Instruction::BinaryOps Opc,
2653 BranchProbability TProb,
2654 BranchProbability FProb,
2655 bool InvertCond) {
2656 // Skip over not part of the tree and remember to invert op and operands at
2657 // next level.
2658 Value *NotCond;
2659 if (match(V: Cond, P: m_OneUse(SubPattern: m_Not(V: m_Value(V&: NotCond)))) &&
2660 InBlock(V: NotCond, BB: CurBB->getBasicBlock())) {
2661 FindMergedConditions(Cond: NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2662 InvertCond: !InvertCond);
2663 return;
2664 }
2665
2666 const Instruction *BOp = dyn_cast<Instruction>(Val: Cond);
2667 const Value *BOpOp0, *BOpOp1;
2668 // Compute the effective opcode for Cond, taking into account whether it needs
2669 // to be inverted, e.g.
2670 // and (not (or A, B)), C
2671 // gets lowered as
2672 // and (and (not A, not B), C)
2673 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2674 if (BOp) {
2675 BOpc = match(V: BOp, P: m_LogicalAnd(L: m_Value(V&: BOpOp0), R: m_Value(V&: BOpOp1)))
2676 ? Instruction::And
2677 : (match(V: BOp, P: m_LogicalOr(L: m_Value(V&: BOpOp0), R: m_Value(V&: BOpOp1)))
2678 ? Instruction::Or
2679 : (Instruction::BinaryOps)0);
2680 if (InvertCond) {
2681 if (BOpc == Instruction::And)
2682 BOpc = Instruction::Or;
2683 else if (BOpc == Instruction::Or)
2684 BOpc = Instruction::And;
2685 }
2686 }
2687
2688 // If this node is not part of the or/and tree, emit it as a branch.
2689 // Note that all nodes in the tree should have same opcode.
2690 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2691 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2692 !InBlock(V: BOpOp0, BB: CurBB->getBasicBlock()) ||
2693 !InBlock(V: BOpOp1, BB: CurBB->getBasicBlock())) {
2694 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2695 TProb, FProb, InvertCond);
2696 return;
2697 }
2698
2699 // Create TmpBB after CurBB.
2700 MachineFunction::iterator BBI(CurBB);
2701 MachineFunction &MF = DAG.getMachineFunction();
2702 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(BB: CurBB->getBasicBlock());
2703 CurBB->getParent()->insert(MBBI: ++BBI, MBB: TmpBB);
2704
2705 if (Opc == Instruction::Or) {
2706 // Codegen X | Y as:
2707 // BB1:
2708 // jmp_if_X TBB
2709 // jmp TmpBB
2710 // TmpBB:
2711 // jmp_if_Y TBB
2712 // jmp FBB
2713 //
2714
2715 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2716 // The requirement is that
2717 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2718 // = TrueProb for original BB.
2719 // Assuming the original probabilities are A and B, one choice is to set
2720 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2721 // A/(1+B) and 2B/(1+B). This choice assumes that
2722 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2723 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2724 // TmpBB, but the math is more complicated.
2725
2726 auto NewTrueProb = TProb / 2;
2727 auto NewFalseProb = TProb / 2 + FProb;
2728 // Emit the LHS condition.
2729 FindMergedConditions(Cond: BOpOp0, TBB, FBB: TmpBB, CurBB, SwitchBB, Opc, TProb: NewTrueProb,
2730 FProb: NewFalseProb, InvertCond);
2731
2732 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2733 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2734 BranchProbability::normalizeProbabilities(Begin: Probs.begin(), End: Probs.end());
2735 // Emit the RHS condition into TmpBB.
2736 FindMergedConditions(Cond: BOpOp1, TBB, FBB, CurBB: TmpBB, SwitchBB, Opc, TProb: Probs[0],
2737 FProb: Probs[1], InvertCond);
2738 } else {
2739 assert(Opc == Instruction::And && "Unknown merge op!");
2740 // Codegen X & Y as:
2741 // BB1:
2742 // jmp_if_X TmpBB
2743 // jmp FBB
2744 // TmpBB:
2745 // jmp_if_Y TBB
2746 // jmp FBB
2747 //
2748 // This requires creation of TmpBB after CurBB.
2749
2750 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2751 // The requirement is that
2752 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2753 // = FalseProb for original BB.
2754 // Assuming the original probabilities are A and B, one choice is to set
2755 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2756 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2757 // TrueProb for BB1 * FalseProb for TmpBB.
2758
2759 auto NewTrueProb = TProb + FProb / 2;
2760 auto NewFalseProb = FProb / 2;
2761 // Emit the LHS condition.
2762 FindMergedConditions(Cond: BOpOp0, TBB: TmpBB, FBB, CurBB, SwitchBB, Opc, TProb: NewTrueProb,
2763 FProb: NewFalseProb, InvertCond);
2764
2765 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2766 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2767 BranchProbability::normalizeProbabilities(Begin: Probs.begin(), End: Probs.end());
2768 // Emit the RHS condition into TmpBB.
2769 FindMergedConditions(Cond: BOpOp1, TBB, FBB, CurBB: TmpBB, SwitchBB, Opc, TProb: Probs[0],
2770 FProb: Probs[1], InvertCond);
2771 }
2772}
2773
2774/// If the set of cases should be emitted as a series of branches, return true.
2775/// If we should emit this as a bunch of and/or'd together conditions, return
2776/// false.
2777bool
2778SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2779 if (Cases.size() != 2) return true;
2780
2781 // If this is two comparisons of the same values or'd or and'd together, they
2782 // will get folded into a single comparison, so don't emit two blocks.
2783 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2784 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2785 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2786 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2787 return false;
2788 }
2789
2790 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2791 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2792 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2793 Cases[0].CC == Cases[1].CC &&
2794 isa<Constant>(Val: Cases[0].CmpRHS) &&
2795 cast<Constant>(Val: Cases[0].CmpRHS)->isNullValue()) {
2796 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2797 return false;
2798 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2799 return false;
2800 }
2801
2802 return true;
2803}
2804
2805void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2806 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2807
2808 // Update machine-CFG edges.
2809 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(BB: I.getSuccessor(i: 0));
2810
2811 if (I.isUnconditional()) {
2812 // Update machine-CFG edges.
2813 BrMBB->addSuccessor(Succ: Succ0MBB);
2814
2815 // If this is not a fall-through branch or optimizations are switched off,
2816 // emit the branch.
2817 if (Succ0MBB != NextBlock(MBB: BrMBB) ||
2818 TM.getOptLevel() == CodeGenOptLevel::None) {
2819 auto Br = DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other,
2820 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: Succ0MBB));
2821 setValue(V: &I, NewN: Br);
2822 DAG.setRoot(Br);
2823 }
2824
2825 return;
2826 }
2827
2828 // If this condition is one of the special cases we handle, do special stuff
2829 // now.
2830 const Value *CondVal = I.getCondition();
2831 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(BB: I.getSuccessor(i: 1));
2832
2833 // If this is a series of conditions that are or'd or and'd together, emit
2834 // this as a sequence of branches instead of setcc's with and/or operations.
2835 // As long as jumps are not expensive (exceptions for multi-use logic ops,
2836 // unpredictable branches, and vector extracts because those jumps are likely
2837 // expensive for any target), this should improve performance.
2838 // For example, instead of something like:
2839 // cmp A, B
2840 // C = seteq
2841 // cmp D, E
2842 // F = setle
2843 // or C, F
2844 // jnz foo
2845 // Emit:
2846 // cmp A, B
2847 // je foo
2848 // cmp D, E
2849 // jle foo
2850 bool IsUnpredictable = I.hasMetadata(KindID: LLVMContext::MD_unpredictable);
2851 const Instruction *BOp = dyn_cast<Instruction>(Val: CondVal);
2852 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2853 BOp->hasOneUse() && !IsUnpredictable) {
2854 Value *Vec;
2855 const Value *BOp0, *BOp1;
2856 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2857 if (match(V: BOp, P: m_LogicalAnd(L: m_Value(V&: BOp0), R: m_Value(V&: BOp1))))
2858 Opcode = Instruction::And;
2859 else if (match(V: BOp, P: m_LogicalOr(L: m_Value(V&: BOp0), R: m_Value(V&: BOp1))))
2860 Opcode = Instruction::Or;
2861
2862 if (Opcode &&
2863 !(match(V: BOp0, P: m_ExtractElt(Val: m_Value(V&: Vec), Idx: m_Value())) &&
2864 match(V: BOp1, P: m_ExtractElt(Val: m_Specific(V: Vec), Idx: m_Value()))) &&
2865 !shouldKeepJumpConditionsTogether(
2866 FuncInfo, I, Opc: Opcode, Lhs: BOp0, Rhs: BOp1,
2867 Params: DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2868 Opcode, BOp0, BOp1))) {
2869 FindMergedConditions(Cond: BOp, TBB: Succ0MBB, FBB: Succ1MBB, CurBB: BrMBB, SwitchBB: BrMBB, Opc: Opcode,
2870 TProb: getEdgeProbability(Src: BrMBB, Dst: Succ0MBB),
2871 FProb: getEdgeProbability(Src: BrMBB, Dst: Succ1MBB),
2872 /*InvertCond=*/false);
2873 // If the compares in later blocks need to use values not currently
2874 // exported from this block, export them now. This block should always
2875 // be the first entry.
2876 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2877
2878 // Allow some cases to be rejected.
2879 if (ShouldEmitAsBranches(Cases: SL->SwitchCases)) {
2880 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2881 ExportFromCurrentBlock(V: SL->SwitchCases[i].CmpLHS);
2882 ExportFromCurrentBlock(V: SL->SwitchCases[i].CmpRHS);
2883 }
2884
2885 // Emit the branch for this block.
2886 visitSwitchCase(CB&: SL->SwitchCases[0], SwitchBB: BrMBB);
2887 SL->SwitchCases.erase(position: SL->SwitchCases.begin());
2888 return;
2889 }
2890
2891 // Okay, we decided not to do this, remove any inserted MBB's and clear
2892 // SwitchCases.
2893 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2894 FuncInfo.MF->erase(MBBI: SL->SwitchCases[i].ThisBB);
2895
2896 SL->SwitchCases.clear();
2897 }
2898 }
2899
2900 // Create a CaseBlock record representing this branch.
2901 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(Context&: *DAG.getContext()),
2902 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2903 BranchProbability::getUnknown(), BranchProbability::getUnknown(),
2904 IsUnpredictable);
2905
2906 // Use visitSwitchCase to actually insert the fast branch sequence for this
2907 // cond branch.
2908 visitSwitchCase(CB, SwitchBB: BrMBB);
2909}
2910
2911/// visitSwitchCase - Emits the necessary code to represent a single node in
2912/// the binary search tree resulting from lowering a switch instruction.
2913void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2914 MachineBasicBlock *SwitchBB) {
2915 SDValue Cond;
2916 SDValue CondLHS = getValue(V: CB.CmpLHS);
2917 SDLoc dl = CB.DL;
2918
2919 if (CB.CC == ISD::SETTRUE) {
2920 // Branch or fall through to TrueBB.
2921 addSuccessorWithProb(Src: SwitchBB, Dst: CB.TrueBB, Prob: CB.TrueProb);
2922 SwitchBB->normalizeSuccProbs();
2923 if (CB.TrueBB != NextBlock(MBB: SwitchBB)) {
2924 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: getControlRoot(),
2925 N2: DAG.getBasicBlock(MBB: CB.TrueBB)));
2926 }
2927 return;
2928 }
2929
2930 auto &TLI = DAG.getTargetLoweringInfo();
2931 EVT MemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: CB.CmpLHS->getType());
2932
2933 // Build the setcc now.
2934 if (!CB.CmpMHS) {
2935 // Fold "(X == true)" to X and "(X == false)" to !X to
2936 // handle common cases produced by branch lowering.
2937 if (CB.CmpRHS == ConstantInt::getTrue(Context&: *DAG.getContext()) &&
2938 CB.CC == ISD::SETEQ)
2939 Cond = CondLHS;
2940 else if (CB.CmpRHS == ConstantInt::getFalse(Context&: *DAG.getContext()) &&
2941 CB.CC == ISD::SETEQ) {
2942 SDValue True = DAG.getConstant(Val: 1, DL: dl, VT: CondLHS.getValueType());
2943 Cond = DAG.getNode(Opcode: ISD::XOR, DL: dl, VT: CondLHS.getValueType(), N1: CondLHS, N2: True);
2944 } else {
2945 SDValue CondRHS = getValue(V: CB.CmpRHS);
2946
2947 // If a pointer's DAG type is larger than its memory type then the DAG
2948 // values are zero-extended. This breaks signed comparisons so truncate
2949 // back to the underlying type before doing the compare.
2950 if (CondLHS.getValueType() != MemVT) {
2951 CondLHS = DAG.getPtrExtOrTrunc(Op: CondLHS, DL: getCurSDLoc(), VT: MemVT);
2952 CondRHS = DAG.getPtrExtOrTrunc(Op: CondRHS, DL: getCurSDLoc(), VT: MemVT);
2953 }
2954 Cond = DAG.getSetCC(DL: dl, VT: MVT::i1, LHS: CondLHS, RHS: CondRHS, Cond: CB.CC);
2955 }
2956 } else {
2957 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2958
2959 const APInt& Low = cast<ConstantInt>(Val: CB.CmpLHS)->getValue();
2960 const APInt& High = cast<ConstantInt>(Val: CB.CmpRHS)->getValue();
2961
2962 SDValue CmpOp = getValue(V: CB.CmpMHS);
2963 EVT VT = CmpOp.getValueType();
2964
2965 if (cast<ConstantInt>(Val: CB.CmpLHS)->isMinValue(IsSigned: true)) {
2966 Cond = DAG.getSetCC(DL: dl, VT: MVT::i1, LHS: CmpOp, RHS: DAG.getConstant(Val: High, DL: dl, VT),
2967 Cond: ISD::SETLE);
2968 } else {
2969 SDValue SUB = DAG.getNode(Opcode: ISD::SUB, DL: dl,
2970 VT, N1: CmpOp, N2: DAG.getConstant(Val: Low, DL: dl, VT));
2971 Cond = DAG.getSetCC(DL: dl, VT: MVT::i1, LHS: SUB,
2972 RHS: DAG.getConstant(Val: High-Low, DL: dl, VT), Cond: ISD::SETULE);
2973 }
2974 }
2975
2976 // Update successor info
2977 addSuccessorWithProb(Src: SwitchBB, Dst: CB.TrueBB, Prob: CB.TrueProb);
2978 // TrueBB and FalseBB are always different unless the incoming IR is
2979 // degenerate. This only happens when running llc on weird IR.
2980 if (CB.TrueBB != CB.FalseBB)
2981 addSuccessorWithProb(Src: SwitchBB, Dst: CB.FalseBB, Prob: CB.FalseProb);
2982 SwitchBB->normalizeSuccProbs();
2983
2984 // If the lhs block is the next block, invert the condition so that we can
2985 // fall through to the lhs instead of the rhs block.
2986 if (CB.TrueBB == NextBlock(MBB: SwitchBB)) {
2987 std::swap(a&: CB.TrueBB, b&: CB.FalseBB);
2988 SDValue True = DAG.getConstant(Val: 1, DL: dl, VT: Cond.getValueType());
2989 Cond = DAG.getNode(Opcode: ISD::XOR, DL: dl, VT: Cond.getValueType(), N1: Cond, N2: True);
2990 }
2991
2992 SDNodeFlags Flags;
2993 Flags.setUnpredictable(CB.IsUnpredictable);
2994 SDValue BrCond = DAG.getNode(Opcode: ISD::BRCOND, DL: dl, VT: MVT::Other, N1: getControlRoot(),
2995 N2: Cond, N3: DAG.getBasicBlock(MBB: CB.TrueBB), Flags);
2996
2997 setValue(V: CurInst, NewN: BrCond);
2998
2999 // Insert the false branch. Do this even if it's a fall through branch,
3000 // this makes it easier to do DAG optimizations which require inverting
3001 // the branch condition.
3002 BrCond = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: BrCond,
3003 N2: DAG.getBasicBlock(MBB: CB.FalseBB));
3004
3005 DAG.setRoot(BrCond);
3006}
3007
3008/// visitJumpTable - Emit JumpTable node in the current MBB
3009void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
3010 // Emit the code for the jump table
3011 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3012 assert(JT.Reg && "Should lower JT Header first!");
3013 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DL: DAG.getDataLayout());
3014 SDValue Index = DAG.getCopyFromReg(Chain: getControlRoot(), dl: *JT.SL, Reg: JT.Reg, VT: PTy);
3015 SDValue Table = DAG.getJumpTable(JTI: JT.JTI, VT: PTy);
3016 SDValue BrJumpTable = DAG.getNode(Opcode: ISD::BR_JT, DL: *JT.SL, VT: MVT::Other,
3017 N1: Index.getValue(R: 1), N2: Table, N3: Index);
3018 DAG.setRoot(BrJumpTable);
3019}
3020
3021/// visitJumpTableHeader - This function emits necessary code to produce index
3022/// in the JumpTable from switch case.
3023void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
3024 JumpTableHeader &JTH,
3025 MachineBasicBlock *SwitchBB) {
3026 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3027 const SDLoc &dl = *JT.SL;
3028
3029 // Subtract the lowest switch case value from the value being switched on.
3030 SDValue SwitchOp = getValue(V: JTH.SValue);
3031 EVT VT = SwitchOp.getValueType();
3032 SDValue Sub = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: SwitchOp,
3033 N2: DAG.getConstant(Val: JTH.First, DL: dl, VT));
3034
3035 // The SDNode we just created, which holds the value being switched on minus
3036 // the smallest case value, needs to be copied to a virtual register so it
3037 // can be used as an index into the jump table in a subsequent basic block.
3038 // This value may be smaller or larger than the target's pointer type, and
3039 // therefore require extension or truncating.
3040 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3041 SwitchOp =
3042 DAG.getZExtOrTrunc(Op: Sub, DL: dl, VT: TLI.getJumpTableRegTy(DL: DAG.getDataLayout()));
3043
3044 Register JumpTableReg =
3045 FuncInfo.CreateReg(VT: TLI.getJumpTableRegTy(DL: DAG.getDataLayout()));
3046 SDValue CopyTo =
3047 DAG.getCopyToReg(Chain: getControlRoot(), dl, Reg: JumpTableReg, N: SwitchOp);
3048 JT.Reg = JumpTableReg;
3049
3050 if (!JTH.FallthroughUnreachable) {
3051 // Emit the range check for the jump table, and branch to the default block
3052 // for the switch statement if the value being switched on exceeds the
3053 // largest case in the switch.
3054 SDValue CMP = DAG.getSetCC(
3055 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(),
3056 VT: Sub.getValueType()),
3057 LHS: Sub, RHS: DAG.getConstant(Val: JTH.Last - JTH.First, DL: dl, VT), Cond: ISD::SETUGT);
3058
3059 SDValue BrCond = DAG.getNode(Opcode: ISD::BRCOND, DL: dl,
3060 VT: MVT::Other, N1: CopyTo, N2: CMP,
3061 N3: DAG.getBasicBlock(MBB: JT.Default));
3062
3063 // Avoid emitting unnecessary branches to the next block.
3064 if (JT.MBB != NextBlock(MBB: SwitchBB))
3065 BrCond = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: BrCond,
3066 N2: DAG.getBasicBlock(MBB: JT.MBB));
3067
3068 DAG.setRoot(BrCond);
3069 } else {
3070 // Avoid emitting unnecessary branches to the next block.
3071 if (JT.MBB != NextBlock(MBB: SwitchBB))
3072 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: CopyTo,
3073 N2: DAG.getBasicBlock(MBB: JT.MBB)));
3074 else
3075 DAG.setRoot(CopyTo);
3076 }
3077}
3078
3079/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3080/// variable if there exists one.
3081static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3082 SDValue &Chain) {
3083 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3084 EVT PtrTy = TLI.getPointerTy(DL: DAG.getDataLayout());
3085 EVT PtrMemTy = TLI.getPointerMemTy(DL: DAG.getDataLayout());
3086 MachineFunction &MF = DAG.getMachineFunction();
3087 Value *Global =
3088 TLI.getSDagStackGuard(M: *MF.getFunction().getParent(), Libcalls: DAG.getLibcalls());
3089 MachineSDNode *Node =
3090 DAG.getMachineNode(Opcode: TargetOpcode::LOAD_STACK_GUARD, dl: DL, VT: PtrTy, Op1: Chain);
3091 if (Global) {
3092 MachinePointerInfo MPInfo(Global);
3093 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3094 MachineMemOperand::MODereferenceable;
3095 MachineMemOperand *MemRef = MF.getMachineMemOperand(
3096 PtrInfo: MPInfo, F: Flags, Size: PtrTy.getSizeInBits() / 8, BaseAlignment: DAG.getEVTAlign(MemoryVT: PtrTy));
3097 DAG.setNodeMemRefs(N: Node, NewMemRefs: {MemRef});
3098 }
3099 if (PtrTy != PtrMemTy)
3100 return DAG.getPtrExtOrTrunc(Op: SDValue(Node, 0), DL, VT: PtrMemTy);
3101 return SDValue(Node, 0);
3102}
3103
3104/// Codegen a new tail for a stack protector check ParentMBB which has had its
3105/// tail spliced into a stack protector check success bb.
3106///
3107/// For a high level explanation of how this fits into the stack protector
3108/// generation see the comment on the declaration of class
3109/// StackProtectorDescriptor.
3110void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3111 MachineBasicBlock *ParentBB) {
3112
3113 // First create the loads to the guard/stack slot for the comparison.
3114 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3115 auto &DL = DAG.getDataLayout();
3116 EVT PtrTy = TLI.getFrameIndexTy(DL);
3117 EVT PtrMemTy = TLI.getPointerMemTy(DL, AS: DL.getAllocaAddrSpace());
3118
3119 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3120 int FI = MFI.getStackProtectorIndex();
3121
3122 SDValue Guard;
3123 SDLoc dl = getCurSDLoc();
3124 SDValue StackSlotPtr = DAG.getFrameIndex(FI, VT: PtrTy);
3125 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3126 Align Align = DL.getPrefTypeAlign(
3127 Ty: PointerType::get(C&: M.getContext(), AddressSpace: DL.getAllocaAddrSpace()));
3128
3129 // Generate code to load the content of the guard slot.
3130 SDValue GuardVal = DAG.getLoad(
3131 VT: PtrMemTy, dl, Chain: DAG.getEntryNode(), Ptr: StackSlotPtr,
3132 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI), Alignment: Align,
3133 MMOFlags: MachineMemOperand::MOVolatile);
3134
3135 if (TLI.useStackGuardXorFP())
3136 GuardVal = TLI.emitStackGuardXorFP(DAG, Val: GuardVal, DL: dl);
3137
3138 // If we're using function-based instrumentation, call the guard check
3139 // function
3140 if (SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3141 // Get the guard check function from the target and verify it exists since
3142 // we're using function-based instrumentation
3143 const Function *GuardCheckFn =
3144 TLI.getSSPStackGuardCheck(M, Libcalls: DAG.getLibcalls());
3145 assert(GuardCheckFn && "Guard check function is null");
3146
3147 // The target provides a guard check function to validate the guard value.
3148 // Generate a call to that function with the content of the guard slot as
3149 // argument.
3150 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3151 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3152
3153 TargetLowering::ArgListTy Args;
3154 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(i: 0));
3155 if (GuardCheckFn->hasParamAttribute(ArgNo: 0, Kind: Attribute::AttrKind::InReg))
3156 Entry.IsInReg = true;
3157 Args.push_back(x: Entry);
3158
3159 TargetLowering::CallLoweringInfo CLI(DAG);
3160 CLI.setDebugLoc(getCurSDLoc())
3161 .setChain(DAG.getEntryNode())
3162 .setCallee(CC: GuardCheckFn->getCallingConv(), ResultType: FnTy->getReturnType(),
3163 Target: getValue(V: GuardCheckFn), ArgsList: std::move(Args));
3164
3165 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3166 DAG.setRoot(Result.second);
3167 return;
3168 }
3169
3170 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3171 // Otherwise, emit a volatile load to retrieve the stack guard value.
3172 SDValue Chain = DAG.getEntryNode();
3173 if (TLI.useLoadStackGuardNode(M)) {
3174 Guard = getLoadStackGuard(DAG, DL: dl, Chain);
3175 } else {
3176 if (const Value *IRGuard = TLI.getSDagStackGuard(M, Libcalls: DAG.getLibcalls())) {
3177 SDValue GuardPtr = getValue(V: IRGuard);
3178 Guard = DAG.getLoad(VT: PtrMemTy, dl, Chain, Ptr: GuardPtr,
3179 PtrInfo: MachinePointerInfo(IRGuard, 0), Alignment: Align,
3180 MMOFlags: MachineMemOperand::MOVolatile);
3181 } else {
3182 LLVMContext &Ctx = *DAG.getContext();
3183 Ctx.diagnose(DI: DiagnosticInfoGeneric("unable to lower stackguard"));
3184 Guard = DAG.getPOISON(VT: PtrMemTy);
3185 }
3186 }
3187
3188 // Perform the comparison via a getsetcc.
3189 SDValue Cmp = DAG.getSetCC(
3190 DL: dl, VT: TLI.getSetCCResultType(DL, Context&: *DAG.getContext(), VT: Guard.getValueType()),
3191 LHS: Guard, RHS: GuardVal, Cond: ISD::SETNE);
3192
3193 // If the guard/stackslot do not equal, branch to failure MBB.
3194 SDValue BrCond = DAG.getNode(Opcode: ISD::BRCOND, DL: dl, VT: MVT::Other, N1: getControlRoot(),
3195 N2: Cmp, N3: DAG.getBasicBlock(MBB: SPD.getFailureMBB()));
3196 // Otherwise branch to success MBB.
3197 SDValue Br = DAG.getNode(Opcode: ISD::BR, DL: dl,
3198 VT: MVT::Other, N1: BrCond,
3199 N2: DAG.getBasicBlock(MBB: SPD.getSuccessMBB()));
3200
3201 DAG.setRoot(Br);
3202}
3203
3204/// Codegen the failure basic block for a stack protector check.
3205///
3206/// A failure stack protector machine basic block consists simply of a call to
3207/// __stack_chk_fail().
3208///
3209/// For a high level explanation of how this fits into the stack protector
3210/// generation see the comment on the declaration of class
3211/// StackProtectorDescriptor.
3212void SelectionDAGBuilder::visitSPDescriptorFailure(
3213 StackProtectorDescriptor &SPD) {
3214
3215 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3216 MachineBasicBlock *ParentBB = SPD.getParentMBB();
3217 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3218 SDValue Chain;
3219
3220 // For -Oz builds with a guard check function, we use function-based
3221 // instrumentation. Otherwise, if we have a guard check function, we call it
3222 // in the failure block.
3223 auto *GuardCheckFn = TLI.getSSPStackGuardCheck(M, Libcalls: DAG.getLibcalls());
3224 if (GuardCheckFn && !SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3225 // First create the loads to the guard/stack slot for the comparison.
3226 auto &DL = DAG.getDataLayout();
3227 EVT PtrTy = TLI.getFrameIndexTy(DL);
3228 EVT PtrMemTy = TLI.getPointerMemTy(DL, AS: DL.getAllocaAddrSpace());
3229
3230 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3231 int FI = MFI.getStackProtectorIndex();
3232
3233 SDLoc dl = getCurSDLoc();
3234 SDValue StackSlotPtr = DAG.getFrameIndex(FI, VT: PtrTy);
3235 Align Align = DL.getPrefTypeAlign(
3236 Ty: PointerType::get(C&: M.getContext(), AddressSpace: DL.getAllocaAddrSpace()));
3237
3238 // Generate code to load the content of the guard slot.
3239 SDValue GuardVal = DAG.getLoad(
3240 VT: PtrMemTy, dl, Chain: DAG.getEntryNode(), Ptr: StackSlotPtr,
3241 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI), Alignment: Align,
3242 MMOFlags: MachineMemOperand::MOVolatile);
3243
3244 if (TLI.useStackGuardXorFP())
3245 GuardVal = TLI.emitStackGuardXorFP(DAG, Val: GuardVal, DL: dl);
3246
3247 // The target provides a guard check function to validate the guard value.
3248 // Generate a call to that function with the content of the guard slot as
3249 // argument.
3250 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3251 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3252
3253 TargetLowering::ArgListTy Args;
3254 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(i: 0));
3255 if (GuardCheckFn->hasParamAttribute(ArgNo: 0, Kind: Attribute::AttrKind::InReg))
3256 Entry.IsInReg = true;
3257 Args.push_back(x: Entry);
3258
3259 TargetLowering::CallLoweringInfo CLI(DAG);
3260 CLI.setDebugLoc(getCurSDLoc())
3261 .setChain(DAG.getEntryNode())
3262 .setCallee(CC: GuardCheckFn->getCallingConv(), ResultType: FnTy->getReturnType(),
3263 Target: getValue(V: GuardCheckFn), ArgsList: std::move(Args));
3264
3265 Chain = TLI.LowerCallTo(CLI).second;
3266 } else {
3267 TargetLowering::MakeLibCallOptions CallOptions;
3268 CallOptions.setDiscardResult(true);
3269 Chain = TLI.makeLibCall(DAG, LC: RTLIB::STACKPROTECTOR_CHECK_FAIL, RetVT: MVT::isVoid,
3270 Ops: {}, CallOptions, dl: getCurSDLoc())
3271 .second;
3272 }
3273
3274 // Emit a trap instruction if we are required to do so.
3275 const TargetOptions &TargetOpts = DAG.getTarget().Options;
3276 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3277 Chain = DAG.getNode(Opcode: ISD::TRAP, DL: getCurSDLoc(), VT: MVT::Other, Operand: Chain);
3278
3279 DAG.setRoot(Chain);
3280}
3281
3282/// visitBitTestHeader - This function emits necessary code to produce value
3283/// suitable for "bit tests"
3284void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3285 MachineBasicBlock *SwitchBB) {
3286 SDLoc dl = getCurSDLoc();
3287
3288 // Subtract the minimum value.
3289 SDValue SwitchOp = getValue(V: B.SValue);
3290 EVT VT = SwitchOp.getValueType();
3291 SDValue RangeSub =
3292 DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: SwitchOp, N2: DAG.getConstant(Val: B.First, DL: dl, VT));
3293
3294 // Determine the type of the test operands.
3295 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3296 bool UsePtrType = false;
3297 if (!TLI.isTypeLegal(VT)) {
3298 UsePtrType = true;
3299 } else {
3300 for (const BitTestCase &Case : B.Cases)
3301 if (!isUIntN(N: VT.getSizeInBits(), x: Case.Mask)) {
3302 // Switch table case range are encoded into series of masks.
3303 // Just use pointer type, it's guaranteed to fit.
3304 UsePtrType = true;
3305 break;
3306 }
3307 }
3308 SDValue Sub = RangeSub;
3309 if (UsePtrType) {
3310 VT = TLI.getPointerTy(DL: DAG.getDataLayout());
3311 Sub = DAG.getZExtOrTrunc(Op: Sub, DL: dl, VT);
3312 }
3313
3314 B.RegVT = VT.getSimpleVT();
3315 B.Reg = FuncInfo.CreateReg(VT: B.RegVT);
3316 SDValue CopyTo = DAG.getCopyToReg(Chain: getControlRoot(), dl, Reg: B.Reg, N: Sub);
3317
3318 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3319
3320 if (!B.FallthroughUnreachable)
3321 addSuccessorWithProb(Src: SwitchBB, Dst: B.Default, Prob: B.DefaultProb);
3322 addSuccessorWithProb(Src: SwitchBB, Dst: MBB, Prob: B.Prob);
3323 SwitchBB->normalizeSuccProbs();
3324
3325 SDValue Root = CopyTo;
3326 if (!B.FallthroughUnreachable) {
3327 // Conditional branch to the default block.
3328 SDValue RangeCmp = DAG.getSetCC(DL: dl,
3329 VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(),
3330 VT: RangeSub.getValueType()),
3331 LHS: RangeSub, RHS: DAG.getConstant(Val: B.Range, DL: dl, VT: RangeSub.getValueType()),
3332 Cond: ISD::SETUGT);
3333
3334 Root = DAG.getNode(Opcode: ISD::BRCOND, DL: dl, VT: MVT::Other, N1: Root, N2: RangeCmp,
3335 N3: DAG.getBasicBlock(MBB: B.Default));
3336 }
3337
3338 // Avoid emitting unnecessary branches to the next block.
3339 if (MBB != NextBlock(MBB: SwitchBB))
3340 Root = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: Root, N2: DAG.getBasicBlock(MBB));
3341
3342 DAG.setRoot(Root);
3343}
3344
3345/// visitBitTestCase - this function produces one "bit test"
3346void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3347 MachineBasicBlock *NextMBB,
3348 BranchProbability BranchProbToNext,
3349 Register Reg, BitTestCase &B,
3350 MachineBasicBlock *SwitchBB) {
3351 SDLoc dl = getCurSDLoc();
3352 MVT VT = BB.RegVT;
3353 SDValue ShiftOp = DAG.getCopyFromReg(Chain: getControlRoot(), dl, Reg, VT);
3354 SDValue Cmp;
3355 unsigned PopCount = llvm::popcount(Value: B.Mask);
3356 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3357 if (PopCount == 1) {
3358 // Testing for a single bit; just compare the shift count with what it
3359 // would need to be to shift a 1 bit in that position.
3360 Cmp = DAG.getSetCC(
3361 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(), VT),
3362 LHS: ShiftOp, RHS: DAG.getConstant(Val: llvm::countr_zero(Val: B.Mask), DL: dl, VT),
3363 Cond: ISD::SETEQ);
3364 } else if (PopCount == BB.Range) {
3365 // There is only one zero bit in the range, test for it directly.
3366 Cmp = DAG.getSetCC(
3367 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(), VT),
3368 LHS: ShiftOp, RHS: DAG.getConstant(Val: llvm::countr_one(Value: B.Mask), DL: dl, VT), Cond: ISD::SETNE);
3369 } else {
3370 // Make desired shift
3371 SDValue SwitchVal = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT,
3372 N1: DAG.getConstant(Val: 1, DL: dl, VT), N2: ShiftOp);
3373
3374 // Emit bit tests and jumps
3375 SDValue AndOp = DAG.getNode(Opcode: ISD::AND, DL: dl,
3376 VT, N1: SwitchVal, N2: DAG.getConstant(Val: B.Mask, DL: dl, VT));
3377 Cmp = DAG.getSetCC(
3378 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(), VT),
3379 LHS: AndOp, RHS: DAG.getConstant(Val: 0, DL: dl, VT), Cond: ISD::SETNE);
3380 }
3381
3382 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3383 addSuccessorWithProb(Src: SwitchBB, Dst: B.TargetBB, Prob: B.ExtraProb);
3384 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3385 addSuccessorWithProb(Src: SwitchBB, Dst: NextMBB, Prob: BranchProbToNext);
3386 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3387 // one as they are relative probabilities (and thus work more like weights),
3388 // and hence we need to normalize them to let the sum of them become one.
3389 SwitchBB->normalizeSuccProbs();
3390
3391 SDValue BrAnd = DAG.getNode(Opcode: ISD::BRCOND, DL: dl,
3392 VT: MVT::Other, N1: getControlRoot(),
3393 N2: Cmp, N3: DAG.getBasicBlock(MBB: B.TargetBB));
3394
3395 // Avoid emitting unnecessary branches to the next block.
3396 if (NextMBB != NextBlock(MBB: SwitchBB))
3397 BrAnd = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: BrAnd,
3398 N2: DAG.getBasicBlock(MBB: NextMBB));
3399
3400 DAG.setRoot(BrAnd);
3401}
3402
3403void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3404 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3405
3406 // Retrieve successors. Look through artificial IR level blocks like
3407 // catchswitch for successors.
3408 MachineBasicBlock *Return = FuncInfo.getMBB(BB: I.getSuccessor(i: 0));
3409 const BasicBlock *EHPadBB = I.getSuccessor(i: 1);
3410 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(BB: EHPadBB);
3411
3412 // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3413 // have to do anything here to lower funclet bundles.
3414 failForInvalidBundles(I, Name: "invokes",
3415 AllowedBundles: {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3416 LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3417 LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3418 LLVMContext::OB_clang_arc_attachedcall,
3419 LLVMContext::OB_kcfi});
3420
3421 const Value *Callee(I.getCalledOperand());
3422 const Function *Fn = dyn_cast<Function>(Val: Callee);
3423 if (isa<InlineAsm>(Val: Callee))
3424 visitInlineAsm(Call: I, EHPadBB);
3425 else if (Fn && Fn->isIntrinsic()) {
3426 switch (Fn->getIntrinsicID()) {
3427 default:
3428 llvm_unreachable("Cannot invoke this intrinsic");
3429 case Intrinsic::donothing:
3430 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3431 case Intrinsic::seh_try_begin:
3432 case Intrinsic::seh_scope_begin:
3433 case Intrinsic::seh_try_end:
3434 case Intrinsic::seh_scope_end:
3435 if (EHPadMBB)
3436 // a block referenced by EH table
3437 // so dtor-funclet not removed by opts
3438 EHPadMBB->setMachineBlockAddressTaken();
3439 break;
3440 case Intrinsic::experimental_patchpoint_void:
3441 case Intrinsic::experimental_patchpoint:
3442 visitPatchpoint(CB: I, EHPadBB);
3443 break;
3444 case Intrinsic::experimental_gc_statepoint:
3445 LowerStatepoint(I: cast<GCStatepointInst>(Val: I), EHPadBB);
3446 break;
3447 // wasm_throw, wasm_rethrow: This is usually done in visitTargetIntrinsic,
3448 // but these intrinsics are special because they can be invoked, so we
3449 // manually lower it to a DAG node here.
3450 case Intrinsic::wasm_throw: {
3451 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3452 std::array<SDValue, 4> Ops = {
3453 getControlRoot(), // inchain for the terminator node
3454 DAG.getTargetConstant(Val: Intrinsic::wasm_throw, DL: getCurSDLoc(),
3455 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
3456 getValue(V: I.getArgOperand(i: 0)), // tag
3457 getValue(V: I.getArgOperand(i: 1)) // thrown value
3458 };
3459 SDVTList VTs = DAG.getVTList(VTs: ArrayRef<EVT>({MVT::Other})); // outchain
3460 DAG.setRoot(DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL: getCurSDLoc(), VTList: VTs, Ops));
3461 break;
3462 }
3463 case Intrinsic::wasm_rethrow: {
3464 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3465 std::array<SDValue, 2> Ops = {
3466 getControlRoot(), // inchain for the terminator node
3467 DAG.getTargetConstant(Val: Intrinsic::wasm_rethrow, DL: getCurSDLoc(),
3468 VT: TLI.getPointerTy(DL: DAG.getDataLayout()))};
3469 SDVTList VTs = DAG.getVTList(VTs: ArrayRef<EVT>({MVT::Other})); // outchain
3470 DAG.setRoot(DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL: getCurSDLoc(), VTList: VTs, Ops));
3471 break;
3472 }
3473 }
3474 } else if (I.hasDeoptState()) {
3475 // Currently we do not lower any intrinsic calls with deopt operand bundles.
3476 // Eventually we will support lowering the @llvm.experimental.deoptimize
3477 // intrinsic, and right now there are no plans to support other intrinsics
3478 // with deopt state.
3479 LowerCallSiteWithDeoptBundle(Call: &I, Callee: getValue(V: Callee), EHPadBB);
3480 } else if (I.countOperandBundlesOfType(ID: LLVMContext::OB_ptrauth)) {
3481 LowerCallSiteWithPtrAuthBundle(CB: cast<CallBase>(Val: I), EHPadBB);
3482 } else {
3483 LowerCallTo(CB: I, Callee: getValue(V: Callee), IsTailCall: false, IsMustTailCall: false, EHPadBB);
3484 }
3485
3486 // If the value of the invoke is used outside of its defining block, make it
3487 // available as a virtual register.
3488 // We already took care of the exported value for the statepoint instruction
3489 // during call to the LowerStatepoint.
3490 if (!isa<GCStatepointInst>(Val: I)) {
3491 CopyToExportRegsIfNeeded(V: &I);
3492 }
3493
3494 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3495 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3496 BranchProbability EHPadBBProb =
3497 BPI ? BPI->getEdgeProbability(Src: InvokeMBB->getBasicBlock(), Dst: EHPadBB)
3498 : BranchProbability::getZero();
3499 findUnwindDestinations(FuncInfo, EHPadBB, Prob: EHPadBBProb, UnwindDests);
3500
3501 // Update successor info.
3502 addSuccessorWithProb(Src: InvokeMBB, Dst: Return);
3503 for (auto &UnwindDest : UnwindDests) {
3504 UnwindDest.first->setIsEHPad();
3505 addSuccessorWithProb(Src: InvokeMBB, Dst: UnwindDest.first, Prob: UnwindDest.second);
3506 }
3507 InvokeMBB->normalizeSuccProbs();
3508
3509 // Drop into normal successor.
3510 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other, N1: getControlRoot(),
3511 N2: DAG.getBasicBlock(MBB: Return)));
3512}
3513
3514/// The intrinsics currently supported by callbr are implicit control flow
3515/// intrinsics such as amdgcn.kill.
3516/// - they should be called (no "dontcall-" attributes)
3517/// - they do not touch memory on the target (= !TLI.getTgtMemIntrinsic())
3518/// - they do not need custom argument handling (no
3519/// TLI.CollectTargetIntrinsicOperands())
3520void SelectionDAGBuilder::visitCallBrIntrinsic(const CallBrInst &I) {
3521#ifndef NDEBUG
3522 SmallVector<TargetLowering::IntrinsicInfo, 2> Infos;
3523 DAG.getTargetLoweringInfo().getTgtMemIntrinsic(
3524 Infos, I, DAG.getMachineFunction(), I.getIntrinsicID());
3525 assert(Infos.empty() && "Intrinsic touches memory");
3526#endif
3527
3528 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
3529
3530 SmallVector<SDValue, 8> Ops =
3531 getTargetIntrinsicOperands(I, HasChain, OnlyLoad);
3532 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
3533
3534 // Create the node.
3535 SDValue Result =
3536 getTargetNonMemIntrinsicNode(IntrinsicVT: *I.getType(), HasChain, Ops, VTs);
3537 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
3538
3539 setValue(V: &I, NewN: Result);
3540}
3541
3542void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3543 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3544
3545 if (I.isInlineAsm()) {
3546 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3547 // have to do anything here to lower funclet bundles.
3548 failForInvalidBundles(I, Name: "callbrs",
3549 AllowedBundles: {LLVMContext::OB_deopt, LLVMContext::OB_funclet});
3550 visitInlineAsm(Call: I);
3551 } else {
3552 assert(!I.hasOperandBundles() &&
3553 "Can't have operand bundles for intrinsics");
3554 visitCallBrIntrinsic(I);
3555 }
3556 CopyToExportRegsIfNeeded(V: &I);
3557
3558 // Retrieve successors.
3559 SmallPtrSet<BasicBlock *, 8> Dests;
3560 Dests.insert(Ptr: I.getDefaultDest());
3561 MachineBasicBlock *Return = FuncInfo.getMBB(BB: I.getDefaultDest());
3562
3563 // Update successor info.
3564 addSuccessorWithProb(Src: CallBrMBB, Dst: Return, Prob: BranchProbability::getOne());
3565 // TODO: For most of the cases where there is an intrinsic callbr, we're
3566 // having exactly one indirect target, which will be unreachable. As soon as
3567 // this changes, we might need to enhance
3568 // Target->setIsInlineAsmBrIndirectTarget or add something similar for
3569 // intrinsic indirect branches.
3570 if (I.isInlineAsm()) {
3571 for (BasicBlock *Dest : I.getIndirectDests()) {
3572 MachineBasicBlock *Target = FuncInfo.getMBB(BB: Dest);
3573 Target->setIsInlineAsmBrIndirectTarget();
3574 // If we introduce a type of asm goto statement that is permitted to use
3575 // an indirect call instruction to jump to its labels, then we should add
3576 // a call to Target->setMachineBlockAddressTaken() here, to mark the
3577 // target block as requiring a BTI.
3578
3579 Target->setLabelMustBeEmitted();
3580 // Don't add duplicate machine successors.
3581 if (Dests.insert(Ptr: Dest).second)
3582 addSuccessorWithProb(Src: CallBrMBB, Dst: Target, Prob: BranchProbability::getZero());
3583 }
3584 }
3585 CallBrMBB->normalizeSuccProbs();
3586
3587 // Drop into default successor.
3588 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(),
3589 VT: MVT::Other, N1: getControlRoot(),
3590 N2: DAG.getBasicBlock(MBB: Return)));
3591}
3592
3593void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3594 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3595}
3596
3597void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3598 assert(FuncInfo.MBB->isEHPad() &&
3599 "Call to landingpad not in landing pad!");
3600
3601 // If there aren't registers to copy the values into (e.g., during SjLj
3602 // exceptions), then don't bother to create these DAG nodes.
3603 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3604 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3605 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3606 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3607 return;
3608
3609 // If landingpad's return type is token type, we don't create DAG nodes
3610 // for its exception pointer and selector value. The extraction of exception
3611 // pointer or selector value from token type landingpads is not currently
3612 // supported.
3613 if (LP.getType()->isTokenTy())
3614 return;
3615
3616 SmallVector<EVT, 2> ValueVTs;
3617 SDLoc dl = getCurSDLoc();
3618 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: LP.getType(), ValueVTs);
3619 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3620
3621 // Get the two live-in registers as SDValues. The physregs have already been
3622 // copied into virtual registers.
3623 SDValue Ops[2];
3624 if (FuncInfo.ExceptionPointerVirtReg) {
3625 Ops[0] = DAG.getZExtOrTrunc(
3626 Op: DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl,
3627 Reg: FuncInfo.ExceptionPointerVirtReg,
3628 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
3629 DL: dl, VT: ValueVTs[0]);
3630 } else {
3631 Ops[0] = DAG.getConstant(Val: 0, DL: dl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
3632 }
3633 Ops[1] = DAG.getZExtOrTrunc(
3634 Op: DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl,
3635 Reg: FuncInfo.ExceptionSelectorVirtReg,
3636 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
3637 DL: dl, VT: ValueVTs[1]);
3638
3639 // Merge into one.
3640 SDValue Res = DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl,
3641 VTList: DAG.getVTList(VTs: ValueVTs), Ops);
3642 setValue(V: &LP, NewN: Res);
3643}
3644
3645void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3646 MachineBasicBlock *Last) {
3647 // Update JTCases.
3648 for (JumpTableBlock &JTB : SL->JTCases)
3649 if (JTB.first.HeaderBB == First)
3650 JTB.first.HeaderBB = Last;
3651
3652 // Update BitTestCases.
3653 for (BitTestBlock &BTB : SL->BitTestCases)
3654 if (BTB.Parent == First)
3655 BTB.Parent = Last;
3656}
3657
3658void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3659 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3660
3661 // Update machine-CFG edges with unique successors.
3662 SmallPtrSet<BasicBlock *, 32> Done;
3663 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3664 BasicBlock *BB = I.getSuccessor(i);
3665 bool Inserted = Done.insert(Ptr: BB).second;
3666 if (!Inserted)
3667 continue;
3668
3669 MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3670 addSuccessorWithProb(Src: IndirectBrMBB, Dst: Succ);
3671 }
3672 IndirectBrMBB->normalizeSuccProbs();
3673
3674 DAG.setRoot(DAG.getNode(Opcode: ISD::BRIND, DL: getCurSDLoc(),
3675 VT: MVT::Other, N1: getControlRoot(),
3676 N2: getValue(V: I.getAddress())));
3677}
3678
3679void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3680 if (!I.shouldLowerToTrap(TrapUnreachable: DAG.getTarget().Options.TrapUnreachable,
3681 NoTrapAfterNoreturn: DAG.getTarget().Options.NoTrapAfterNoreturn))
3682 return;
3683
3684 DAG.setRoot(DAG.getNode(Opcode: ISD::TRAP, DL: getCurSDLoc(), VT: MVT::Other, Operand: DAG.getRoot()));
3685}
3686
3687void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3688 SDNodeFlags Flags;
3689 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
3690 Flags.copyFMF(FPMO: *FPOp);
3691
3692 SDValue Op = getValue(V: I.getOperand(i: 0));
3693 SDValue UnNodeValue = DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Op.getValueType(),
3694 Operand: Op, Flags);
3695 setValue(V: &I, NewN: UnNodeValue);
3696}
3697
3698void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3699 SDNodeFlags Flags;
3700 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(Val: &I)) {
3701 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3702 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3703 }
3704 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(Val: &I))
3705 Flags.setExact(ExactOp->isExact());
3706 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(Val: &I))
3707 Flags.setDisjoint(DisjointOp->isDisjoint());
3708 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
3709 Flags.copyFMF(FPMO: *FPOp);
3710
3711 SDValue Op1 = getValue(V: I.getOperand(i: 0));
3712 SDValue Op2 = getValue(V: I.getOperand(i: 1));
3713 SDValue BinNodeValue = DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Op1.getValueType(),
3714 N1: Op1, N2: Op2, Flags);
3715 setValue(V: &I, NewN: BinNodeValue);
3716}
3717
3718void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3719 SDValue Op1 = getValue(V: I.getOperand(i: 0));
3720 SDValue Op2 = getValue(V: I.getOperand(i: 1));
3721
3722 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3723 LHSTy: Op1.getValueType(), DL: DAG.getDataLayout());
3724
3725 // Coerce the shift amount to the right type if we can. This exposes the
3726 // truncate or zext to optimization early.
3727 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3728 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3729 "Unexpected shift type");
3730 Op2 = DAG.getZExtOrTrunc(Op: Op2, DL: getCurSDLoc(), VT: ShiftTy);
3731 }
3732
3733 bool nuw = false;
3734 bool nsw = false;
3735 bool exact = false;
3736
3737 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3738
3739 if (const OverflowingBinaryOperator *OFBinOp =
3740 dyn_cast<const OverflowingBinaryOperator>(Val: &I)) {
3741 nuw = OFBinOp->hasNoUnsignedWrap();
3742 nsw = OFBinOp->hasNoSignedWrap();
3743 }
3744 if (const PossiblyExactOperator *ExactOp =
3745 dyn_cast<const PossiblyExactOperator>(Val: &I))
3746 exact = ExactOp->isExact();
3747 }
3748 SDNodeFlags Flags;
3749 Flags.setExact(exact);
3750 Flags.setNoSignedWrap(nsw);
3751 Flags.setNoUnsignedWrap(nuw);
3752 SDValue Res = DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Op1.getValueType(), N1: Op1, N2: Op2,
3753 Flags);
3754 setValue(V: &I, NewN: Res);
3755}
3756
3757void SelectionDAGBuilder::visitSDiv(const User &I) {
3758 SDValue Op1 = getValue(V: I.getOperand(i: 0));
3759 SDValue Op2 = getValue(V: I.getOperand(i: 1));
3760
3761 SDNodeFlags Flags;
3762 Flags.setExact(isa<PossiblyExactOperator>(Val: &I) &&
3763 cast<PossiblyExactOperator>(Val: &I)->isExact());
3764 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SDIV, DL: getCurSDLoc(), VT: Op1.getValueType(), N1: Op1,
3765 N2: Op2, Flags));
3766}
3767
3768void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3769 ICmpInst::Predicate predicate = I.getPredicate();
3770 SDValue Op1 = getValue(V: I.getOperand(i_nocapture: 0));
3771 SDValue Op2 = getValue(V: I.getOperand(i_nocapture: 1));
3772 ISD::CondCode Opcode = getICmpCondCode(Pred: predicate);
3773
3774 auto &TLI = DAG.getTargetLoweringInfo();
3775 EVT MemVT =
3776 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i_nocapture: 0)->getType());
3777
3778 // If a pointer's DAG type is larger than its memory type then the DAG values
3779 // are zero-extended. This breaks signed comparisons so truncate back to the
3780 // underlying type before doing the compare.
3781 if (Op1.getValueType() != MemVT) {
3782 Op1 = DAG.getPtrExtOrTrunc(Op: Op1, DL: getCurSDLoc(), VT: MemVT);
3783 Op2 = DAG.getPtrExtOrTrunc(Op: Op2, DL: getCurSDLoc(), VT: MemVT);
3784 }
3785
3786 SDNodeFlags Flags;
3787 Flags.setSameSign(I.hasSameSign());
3788 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3789
3790 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
3791 Ty: I.getType());
3792 setValue(V: &I, NewN: DAG.getSetCC(DL: getCurSDLoc(), VT: DestVT, LHS: Op1, RHS: Op2, Cond: Opcode));
3793}
3794
3795void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3796 FCmpInst::Predicate predicate = I.getPredicate();
3797 SDValue Op1 = getValue(V: I.getOperand(i_nocapture: 0));
3798 SDValue Op2 = getValue(V: I.getOperand(i_nocapture: 1));
3799
3800 ISD::CondCode Condition = getFCmpCondCode(Pred: predicate);
3801 auto *FPMO = cast<FPMathOperator>(Val: &I);
3802 if (FPMO->hasNoNaNs() ||
3803 (DAG.isKnownNeverNaN(Op: Op1) && DAG.isKnownNeverNaN(Op: Op2)))
3804 Condition = getFCmpCodeWithoutNaN(CC: Condition);
3805
3806 SDNodeFlags Flags;
3807 Flags.copyFMF(FPMO: *FPMO);
3808 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3809
3810 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
3811 Ty: I.getType());
3812 setValue(V: &I, NewN: DAG.getSetCC(DL: getCurSDLoc(), VT: DestVT, LHS: Op1, RHS: Op2, Cond: Condition,
3813 /*Chian=*/Chain: {}, /*IsSignaling=*/false, Flags));
3814}
3815
3816// Check if the condition of the select has one use or two users that are both
3817// selects with the same condition.
3818static bool hasOnlySelectUsers(const Value *Cond) {
3819 return llvm::all_of(Range: Cond->users(), P: [](const Value *V) {
3820 return isa<SelectInst>(Val: V);
3821 });
3822}
3823
3824void SelectionDAGBuilder::visitSelect(const User &I) {
3825 SmallVector<EVT, 4> ValueVTs;
3826 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty: I.getType(),
3827 ValueVTs);
3828 unsigned NumValues = ValueVTs.size();
3829 if (NumValues == 0) return;
3830
3831 SmallVector<SDValue, 4> Values(NumValues);
3832 SDValue Cond = getValue(V: I.getOperand(i: 0));
3833 SDValue LHSVal = getValue(V: I.getOperand(i: 1));
3834 SDValue RHSVal = getValue(V: I.getOperand(i: 2));
3835 SmallVector<SDValue, 1> BaseOps(1, Cond);
3836 ISD::NodeType OpCode =
3837 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3838
3839 bool IsUnaryAbs = false;
3840 bool Negate = false;
3841
3842 SDNodeFlags Flags;
3843 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
3844 Flags.copyFMF(FPMO: *FPOp);
3845
3846 Flags.setUnpredictable(
3847 cast<SelectInst>(Val: I).getMetadata(KindID: LLVMContext::MD_unpredictable));
3848
3849 // Min/max matching is only viable if all output VTs are the same.
3850 if (all_equal(Range&: ValueVTs)) {
3851 EVT VT = ValueVTs[0];
3852 LLVMContext &Ctx = *DAG.getContext();
3853 auto &TLI = DAG.getTargetLoweringInfo();
3854
3855 // We care about the legality of the operation after it has been type
3856 // legalized.
3857 while (TLI.getTypeAction(Context&: Ctx, VT) != TargetLoweringBase::TypeLegal)
3858 VT = TLI.getTypeToTransformTo(Context&: Ctx, VT);
3859
3860 // If the vselect is legal, assume we want to leave this as a vector setcc +
3861 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3862 // min/max is legal on the scalar type.
3863 bool UseScalarMinMax = VT.isVector() &&
3864 !TLI.isOperationLegalOrCustom(Op: ISD::VSELECT, VT);
3865
3866 // ValueTracking's select pattern matching does not account for -0.0,
3867 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3868 // -0.0 is less than +0.0.
3869 const Value *LHS, *RHS;
3870 auto SPR = matchSelectPattern(V: &I, LHS, RHS);
3871 ISD::NodeType Opc = ISD::DELETED_NODE;
3872 switch (SPR.Flavor) {
3873 case SPF_UMAX: Opc = ISD::UMAX; break;
3874 case SPF_UMIN: Opc = ISD::UMIN; break;
3875 case SPF_SMAX: Opc = ISD::SMAX; break;
3876 case SPF_SMIN: Opc = ISD::SMIN; break;
3877 case SPF_FMINNUM:
3878 switch (SPR.NaNBehavior) {
3879 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3880 case SPNB_RETURNS_NAN: break;
3881 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3882 case SPNB_RETURNS_ANY:
3883 if (TLI.isOperationLegalOrCustom(Op: ISD::FMINNUM, VT) ||
3884 (UseScalarMinMax &&
3885 TLI.isOperationLegalOrCustom(Op: ISD::FMINNUM, VT: VT.getScalarType())))
3886 Opc = ISD::FMINNUM;
3887 break;
3888 }
3889 break;
3890 case SPF_FMAXNUM:
3891 switch (SPR.NaNBehavior) {
3892 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3893 case SPNB_RETURNS_NAN: break;
3894 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3895 case SPNB_RETURNS_ANY:
3896 if (TLI.isOperationLegalOrCustom(Op: ISD::FMAXNUM, VT) ||
3897 (UseScalarMinMax &&
3898 TLI.isOperationLegalOrCustom(Op: ISD::FMAXNUM, VT: VT.getScalarType())))
3899 Opc = ISD::FMAXNUM;
3900 break;
3901 }
3902 break;
3903 case SPF_NABS:
3904 Negate = true;
3905 [[fallthrough]];
3906 case SPF_ABS:
3907 IsUnaryAbs = true;
3908 Opc = ISD::ABS;
3909 break;
3910 default: break;
3911 }
3912
3913 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3914 (TLI.isOperationLegalOrCustom(Op: Opc, VT) ||
3915 (UseScalarMinMax &&
3916 TLI.isOperationLegalOrCustom(Op: Opc, VT: VT.getScalarType()))) &&
3917 // If the underlying comparison instruction is used by any other
3918 // instruction, the consumed instructions won't be destroyed, so it is
3919 // not profitable to convert to a min/max.
3920 hasOnlySelectUsers(Cond: cast<SelectInst>(Val: I).getCondition())) {
3921 OpCode = Opc;
3922 LHSVal = getValue(V: LHS);
3923 RHSVal = getValue(V: RHS);
3924 BaseOps.clear();
3925 }
3926
3927 if (IsUnaryAbs) {
3928 OpCode = Opc;
3929 LHSVal = getValue(V: LHS);
3930 BaseOps.clear();
3931 }
3932 }
3933
3934 if (IsUnaryAbs) {
3935 for (unsigned i = 0; i != NumValues; ++i) {
3936 SDLoc dl = getCurSDLoc();
3937 EVT VT = LHSVal.getNode()->getValueType(ResNo: LHSVal.getResNo() + i);
3938 Values[i] =
3939 DAG.getNode(Opcode: OpCode, DL: dl, VT, Operand: LHSVal.getValue(R: LHSVal.getResNo() + i));
3940 if (Negate)
3941 Values[i] = DAG.getNegative(Val: Values[i], DL: dl, VT);
3942 }
3943 } else {
3944 for (unsigned i = 0; i != NumValues; ++i) {
3945 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3946 Ops.push_back(Elt: SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3947 Ops.push_back(Elt: SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3948 Values[i] = DAG.getNode(
3949 Opcode: OpCode, DL: getCurSDLoc(),
3950 VT: LHSVal.getNode()->getValueType(ResNo: LHSVal.getResNo() + i), Ops, Flags);
3951 }
3952 }
3953
3954 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
3955 VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values));
3956}
3957
3958void SelectionDAGBuilder::visitTrunc(const User &I) {
3959 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3960 SDValue N = getValue(V: I.getOperand(i: 0));
3961 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
3962 Ty: I.getType());
3963 SDNodeFlags Flags;
3964 if (auto *Trunc = dyn_cast<TruncInst>(Val: &I)) {
3965 Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
3966 Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
3967 }
3968
3969 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::TRUNCATE, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
3970}
3971
3972void SelectionDAGBuilder::visitZExt(const User &I) {
3973 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3974 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3975 SDValue N = getValue(V: I.getOperand(i: 0));
3976 auto &TLI = DAG.getTargetLoweringInfo();
3977 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
3978
3979 SDNodeFlags Flags;
3980 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(Val: &I))
3981 Flags.setNonNeg(PNI->hasNonNeg());
3982
3983 // Eagerly use nonneg information to canonicalize towards sign_extend if
3984 // that is the target's preference.
3985 // TODO: Let the target do this later.
3986 if (Flags.hasNonNeg() &&
3987 TLI.isSExtCheaperThanZExt(FromTy: N.getValueType(), ToTy: DestVT)) {
3988 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N));
3989 return;
3990 }
3991
3992 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
3993}
3994
3995void SelectionDAGBuilder::visitSExt(const User &I) {
3996 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3997 // SExt also can't be a cast to bool for same reason. So, nothing much to do
3998 SDValue N = getValue(V: I.getOperand(i: 0));
3999 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4000 Ty: I.getType());
4001 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4002}
4003
4004void SelectionDAGBuilder::visitFPTrunc(const User &I) {
4005 // FPTrunc is never a no-op cast, no need to check
4006 SDValue N = getValue(V: I.getOperand(i: 0));
4007 SDLoc dl = getCurSDLoc();
4008 SDNodeFlags Flags;
4009 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
4010 Flags.copyFMF(FPMO: *FPOp);
4011 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4012 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4013 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_ROUND, DL: dl, VT: DestVT, N1: N,
4014 N2: DAG.getTargetConstant(
4015 Val: 0, DL: dl, VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
4016 Flags));
4017}
4018
4019void SelectionDAGBuilder::visitFPExt(const User &I) {
4020 // FPExt is never a no-op cast, no need to check
4021 SDValue N = getValue(V: I.getOperand(i: 0));
4022 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4023 Ty: I.getType());
4024 SDNodeFlags Flags;
4025 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
4026 Flags.copyFMF(FPMO: *FPOp);
4027 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
4028}
4029
4030void SelectionDAGBuilder::visitFPToUI(const User &I) {
4031 // FPToUI is never a no-op cast, no need to check
4032 SDValue N = getValue(V: I.getOperand(i: 0));
4033 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4034 Ty: I.getType());
4035 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_UINT, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4036}
4037
4038void SelectionDAGBuilder::visitFPToSI(const User &I) {
4039 // FPToSI is never a no-op cast, no need to check
4040 SDValue N = getValue(V: I.getOperand(i: 0));
4041 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4042 Ty: I.getType());
4043 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_SINT, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4044}
4045
4046void SelectionDAGBuilder::visitUIToFP(const User &I) {
4047 // UIToFP is never a no-op cast, no need to check
4048 SDValue N = getValue(V: I.getOperand(i: 0));
4049 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4050 Ty: I.getType());
4051 SDNodeFlags Flags;
4052 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(Val: &I))
4053 Flags.setNonNeg(PNI->hasNonNeg());
4054
4055 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UINT_TO_FP, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
4056}
4057
4058void SelectionDAGBuilder::visitSIToFP(const User &I) {
4059 // SIToFP is never a no-op cast, no need to check
4060 SDValue N = getValue(V: I.getOperand(i: 0));
4061 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4062 Ty: I.getType());
4063 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4064}
4065
4066void SelectionDAGBuilder::visitPtrToAddr(const User &I) {
4067 SDValue N = getValue(V: I.getOperand(i: 0));
4068 // By definition the type of the ptrtoaddr must be equal to the address type.
4069 const auto &TLI = DAG.getTargetLoweringInfo();
4070 EVT AddrVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4071 // The address width must be smaller or equal to the pointer representation
4072 // width, so we lower ptrtoaddr as a truncate (possibly folded to a no-op).
4073 N = DAG.getNode(Opcode: ISD::TRUNCATE, DL: getCurSDLoc(), VT: AddrVT, Operand: N);
4074 setValue(V: &I, NewN: N);
4075}
4076
4077void SelectionDAGBuilder::visitPtrToInt(const User &I) {
4078 // What to do depends on the size of the integer and the size of the pointer.
4079 // We can either truncate, zero extend, or no-op, accordingly.
4080 SDValue N = getValue(V: I.getOperand(i: 0));
4081 auto &TLI = DAG.getTargetLoweringInfo();
4082 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4083 Ty: I.getType());
4084 EVT PtrMemVT =
4085 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i: 0)->getType());
4086 N = DAG.getPtrExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: PtrMemVT);
4087 N = DAG.getZExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: DestVT);
4088 setValue(V: &I, NewN: N);
4089}
4090
4091void SelectionDAGBuilder::visitIntToPtr(const User &I) {
4092 // What to do depends on the size of the integer and the size of the pointer.
4093 // We can either truncate, zero extend, or no-op, accordingly.
4094 SDValue N = getValue(V: I.getOperand(i: 0));
4095 auto &TLI = DAG.getTargetLoweringInfo();
4096 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4097 EVT PtrMemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4098 N = DAG.getZExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: PtrMemVT);
4099 N = DAG.getPtrExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: DestVT);
4100 setValue(V: &I, NewN: N);
4101}
4102
4103void SelectionDAGBuilder::visitBitCast(const User &I) {
4104 SDValue N = getValue(V: I.getOperand(i: 0));
4105 SDLoc dl = getCurSDLoc();
4106 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4107 Ty: I.getType());
4108
4109 // BitCast assures us that source and destination are the same size so this is
4110 // either a BITCAST or a no-op.
4111 if (DestVT != N.getValueType())
4112 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::BITCAST, DL: dl,
4113 VT: DestVT, Operand: N)); // convert types.
4114 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
4115 // might fold any kind of constant expression to an integer constant and that
4116 // is not what we are looking for. Only recognize a bitcast of a genuine
4117 // constant integer as an opaque constant.
4118 else if(ConstantInt *C = dyn_cast<ConstantInt>(Val: I.getOperand(i: 0)))
4119 setValue(V: &I, NewN: DAG.getConstant(Val: C->getValue(), DL: dl, VT: DestVT, /*isTarget=*/false,
4120 /*isOpaque*/true));
4121 else
4122 setValue(V: &I, NewN: N); // noop cast.
4123}
4124
4125void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
4126 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4127 const Value *SV = I.getOperand(i: 0);
4128 SDValue N = getValue(V: SV);
4129 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4130
4131 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
4132 unsigned DestAS = I.getType()->getPointerAddressSpace();
4133
4134 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
4135 N = DAG.getAddrSpaceCast(dl: getCurSDLoc(), VT: DestVT, Ptr: N, SrcAS, DestAS);
4136
4137 setValue(V: &I, NewN: N);
4138}
4139
4140void SelectionDAGBuilder::visitInsertElement(const User &I) {
4141 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4142 SDValue InVec = getValue(V: I.getOperand(i: 0));
4143 SDValue InVal = getValue(V: I.getOperand(i: 1));
4144 SDValue InIdx = DAG.getZExtOrTrunc(Op: getValue(V: I.getOperand(i: 2)), DL: getCurSDLoc(),
4145 VT: TLI.getVectorIdxTy(DL: DAG.getDataLayout()));
4146 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: getCurSDLoc(),
4147 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
4148 N1: InVec, N2: InVal, N3: InIdx));
4149}
4150
4151void SelectionDAGBuilder::visitExtractElement(const User &I) {
4152 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4153 SDValue InVec = getValue(V: I.getOperand(i: 0));
4154 SDValue InIdx = DAG.getZExtOrTrunc(Op: getValue(V: I.getOperand(i: 1)), DL: getCurSDLoc(),
4155 VT: TLI.getVectorIdxTy(DL: DAG.getDataLayout()));
4156 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: getCurSDLoc(),
4157 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
4158 N1: InVec, N2: InIdx));
4159}
4160
4161void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4162 SDValue Src1 = getValue(V: I.getOperand(i: 0));
4163 SDValue Src2 = getValue(V: I.getOperand(i: 1));
4164 ArrayRef<int> Mask;
4165 if (auto *SVI = dyn_cast<ShuffleVectorInst>(Val: &I))
4166 Mask = SVI->getShuffleMask();
4167 else
4168 Mask = cast<ConstantExpr>(Val: I).getShuffleMask();
4169 SDLoc DL = getCurSDLoc();
4170 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4171 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4172 EVT SrcVT = Src1.getValueType();
4173
4174 if (all_of(Range&: Mask, P: equal_to(Arg: 0)) && VT.isScalableVector()) {
4175 // Canonical splat form of first element of first input vector.
4176 SDValue FirstElt =
4177 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: SrcVT.getScalarType(), N1: Src1,
4178 N2: DAG.getVectorIdxConstant(Val: 0, DL));
4179 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SPLAT_VECTOR, DL, VT, Operand: FirstElt));
4180 return;
4181 }
4182
4183 // For now, we only handle splats for scalable vectors.
4184 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4185 // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4186 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4187
4188 unsigned SrcNumElts = SrcVT.getVectorNumElements();
4189 unsigned MaskNumElts = Mask.size();
4190
4191 if (SrcNumElts == MaskNumElts) {
4192 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: Src1, N2: Src2, Mask));
4193 return;
4194 }
4195
4196 // Normalize the shuffle vector since mask and vector length don't match.
4197 if (SrcNumElts < MaskNumElts) {
4198 // Mask is longer than the source vectors. We can use concatenate vector to
4199 // make the mask and vectors lengths match.
4200
4201 if (MaskNumElts % SrcNumElts == 0) {
4202 // Mask length is a multiple of the source vector length.
4203 // Check if the shuffle is some kind of concatenation of the input
4204 // vectors.
4205 unsigned NumConcat = MaskNumElts / SrcNumElts;
4206 bool IsConcat = true;
4207 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4208 for (unsigned i = 0; i != MaskNumElts; ++i) {
4209 int Idx = Mask[i];
4210 if (Idx < 0)
4211 continue;
4212 // Ensure the indices in each SrcVT sized piece are sequential and that
4213 // the same source is used for the whole piece.
4214 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4215 (ConcatSrcs[i / SrcNumElts] >= 0 &&
4216 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4217 IsConcat = false;
4218 break;
4219 }
4220 // Remember which source this index came from.
4221 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4222 }
4223
4224 // The shuffle is concatenating multiple vectors together. Just emit
4225 // a CONCAT_VECTORS operation.
4226 if (IsConcat) {
4227 SmallVector<SDValue, 8> ConcatOps;
4228 for (auto Src : ConcatSrcs) {
4229 if (Src < 0)
4230 ConcatOps.push_back(Elt: DAG.getUNDEF(VT: SrcVT));
4231 else if (Src == 0)
4232 ConcatOps.push_back(Elt: Src1);
4233 else
4234 ConcatOps.push_back(Elt: Src2);
4235 }
4236 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT, Ops: ConcatOps));
4237 return;
4238 }
4239 }
4240
4241 unsigned PaddedMaskNumElts = alignTo(Value: MaskNumElts, Align: SrcNumElts);
4242 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4243 EVT PaddedVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: VT.getScalarType(),
4244 NumElements: PaddedMaskNumElts);
4245
4246 // Pad both vectors with undefs to make them the same length as the mask.
4247 SDValue UndefVal = DAG.getUNDEF(VT: SrcVT);
4248
4249 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4250 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4251 MOps1[0] = Src1;
4252 MOps2[0] = Src2;
4253
4254 Src1 = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: PaddedVT, Ops: MOps1);
4255 Src2 = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: PaddedVT, Ops: MOps2);
4256
4257 // Readjust mask for new input vector length.
4258 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4259 for (unsigned i = 0; i != MaskNumElts; ++i) {
4260 int Idx = Mask[i];
4261 if (Idx >= (int)SrcNumElts)
4262 Idx -= SrcNumElts - PaddedMaskNumElts;
4263 MappedOps[i] = Idx;
4264 }
4265
4266 SDValue Result = DAG.getVectorShuffle(VT: PaddedVT, dl: DL, N1: Src1, N2: Src2, Mask: MappedOps);
4267
4268 // If the concatenated vector was padded, extract a subvector with the
4269 // correct number of elements.
4270 if (MaskNumElts != PaddedMaskNumElts)
4271 Result = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT, N1: Result,
4272 N2: DAG.getVectorIdxConstant(Val: 0, DL));
4273
4274 setValue(V: &I, NewN: Result);
4275 return;
4276 }
4277
4278 assert(SrcNumElts > MaskNumElts);
4279
4280 // Analyze the access pattern of the vector to see if we can extract
4281 // two subvectors and do the shuffle.
4282 int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4283 bool CanExtract = true;
4284 for (int Idx : Mask) {
4285 unsigned Input = 0;
4286 if (Idx < 0)
4287 continue;
4288
4289 if (Idx >= (int)SrcNumElts) {
4290 Input = 1;
4291 Idx -= SrcNumElts;
4292 }
4293
4294 // If all the indices come from the same MaskNumElts sized portion of
4295 // the sources we can use extract. Also make sure the extract wouldn't
4296 // extract past the end of the source.
4297 int NewStartIdx = alignDown(Value: Idx, Align: MaskNumElts);
4298 if (NewStartIdx + MaskNumElts > SrcNumElts ||
4299 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4300 CanExtract = false;
4301 // Make sure we always update StartIdx as we use it to track if all
4302 // elements are undef.
4303 StartIdx[Input] = NewStartIdx;
4304 }
4305
4306 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4307 setValue(V: &I, NewN: DAG.getUNDEF(VT)); // Vectors are not used.
4308 return;
4309 }
4310 if (CanExtract) {
4311 // Extract appropriate subvector and generate a vector shuffle
4312 for (unsigned Input = 0; Input < 2; ++Input) {
4313 SDValue &Src = Input == 0 ? Src1 : Src2;
4314 if (StartIdx[Input] < 0)
4315 Src = DAG.getUNDEF(VT);
4316 else {
4317 Src = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT, N1: Src,
4318 N2: DAG.getVectorIdxConstant(Val: StartIdx[Input], DL));
4319 }
4320 }
4321
4322 // Calculate new mask.
4323 SmallVector<int, 8> MappedOps(Mask);
4324 for (int &Idx : MappedOps) {
4325 if (Idx >= (int)SrcNumElts)
4326 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4327 else if (Idx >= 0)
4328 Idx -= StartIdx[0];
4329 }
4330
4331 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: Src1, N2: Src2, Mask: MappedOps));
4332 return;
4333 }
4334
4335 // We can't use either concat vectors or extract subvectors so fall back to
4336 // replacing the shuffle with extract and build vector.
4337 // to insert and build vector.
4338 EVT EltVT = VT.getVectorElementType();
4339 SmallVector<SDValue,8> Ops;
4340 for (int Idx : Mask) {
4341 SDValue Res;
4342
4343 if (Idx < 0) {
4344 Res = DAG.getUNDEF(VT: EltVT);
4345 } else {
4346 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4347 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4348
4349 Res = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: EltVT, N1: Src,
4350 N2: DAG.getVectorIdxConstant(Val: Idx, DL));
4351 }
4352
4353 Ops.push_back(Elt: Res);
4354 }
4355
4356 setValue(V: &I, NewN: DAG.getBuildVector(VT, DL, Ops));
4357}
4358
4359void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4360 ArrayRef<unsigned> Indices = I.getIndices();
4361 const Value *Op0 = I.getOperand(i_nocapture: 0);
4362 const Value *Op1 = I.getOperand(i_nocapture: 1);
4363 Type *AggTy = I.getType();
4364 Type *ValTy = Op1->getType();
4365 bool IntoUndef = isa<UndefValue>(Val: Op0);
4366 bool FromUndef = isa<UndefValue>(Val: Op1);
4367
4368 unsigned LinearIndex = ComputeLinearIndex(Ty: AggTy, Indices);
4369
4370 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4371 SmallVector<EVT, 4> AggValueVTs;
4372 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: AggTy, ValueVTs&: AggValueVTs);
4373 SmallVector<EVT, 4> ValValueVTs;
4374 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: ValTy, ValueVTs&: ValValueVTs);
4375
4376 unsigned NumAggValues = AggValueVTs.size();
4377 unsigned NumValValues = ValValueVTs.size();
4378 SmallVector<SDValue, 4> Values(NumAggValues);
4379
4380 // Ignore an insertvalue that produces an empty object
4381 if (!NumAggValues) {
4382 setValue(V: &I, NewN: DAG.getUNDEF(VT: MVT(MVT::Other)));
4383 return;
4384 }
4385
4386 SDValue Agg = getValue(V: Op0);
4387 unsigned i = 0;
4388 // Copy the beginning value(s) from the original aggregate.
4389 for (; i != LinearIndex; ++i)
4390 Values[i] = IntoUndef ? DAG.getUNDEF(VT: AggValueVTs[i]) :
4391 SDValue(Agg.getNode(), Agg.getResNo() + i);
4392 // Copy values from the inserted value(s).
4393 if (NumValValues) {
4394 SDValue Val = getValue(V: Op1);
4395 for (; i != LinearIndex + NumValValues; ++i)
4396 Values[i] = FromUndef ? DAG.getUNDEF(VT: AggValueVTs[i]) :
4397 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4398 }
4399 // Copy remaining value(s) from the original aggregate.
4400 for (; i != NumAggValues; ++i)
4401 Values[i] = IntoUndef ? DAG.getUNDEF(VT: AggValueVTs[i]) :
4402 SDValue(Agg.getNode(), Agg.getResNo() + i);
4403
4404 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
4405 VTList: DAG.getVTList(VTs: AggValueVTs), Ops: Values));
4406}
4407
4408void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4409 ArrayRef<unsigned> Indices = I.getIndices();
4410 const Value *Op0 = I.getOperand(i_nocapture: 0);
4411 Type *AggTy = Op0->getType();
4412 Type *ValTy = I.getType();
4413 bool OutOfUndef = isa<UndefValue>(Val: Op0);
4414
4415 unsigned LinearIndex = ComputeLinearIndex(Ty: AggTy, Indices);
4416
4417 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4418 SmallVector<EVT, 4> ValValueVTs;
4419 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: ValTy, ValueVTs&: ValValueVTs);
4420
4421 unsigned NumValValues = ValValueVTs.size();
4422
4423 // Ignore a extractvalue that produces an empty object
4424 if (!NumValValues) {
4425 setValue(V: &I, NewN: DAG.getUNDEF(VT: MVT(MVT::Other)));
4426 return;
4427 }
4428
4429 SmallVector<SDValue, 4> Values(NumValValues);
4430
4431 SDValue Agg = getValue(V: Op0);
4432 // Copy out the selected value(s).
4433 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4434 Values[i - LinearIndex] =
4435 OutOfUndef ?
4436 DAG.getUNDEF(VT: Agg.getNode()->getValueType(ResNo: Agg.getResNo() + i)) :
4437 SDValue(Agg.getNode(), Agg.getResNo() + i);
4438
4439 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
4440 VTList: DAG.getVTList(VTs: ValValueVTs), Ops: Values));
4441}
4442
4443void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4444 Value *Op0 = I.getOperand(i: 0);
4445 // Note that the pointer operand may be a vector of pointers. Take the scalar
4446 // element which holds a pointer.
4447 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4448 SDValue N = getValue(V: Op0);
4449 SDLoc dl = getCurSDLoc();
4450 auto &TLI = DAG.getTargetLoweringInfo();
4451 GEPNoWrapFlags NW = cast<GEPOperator>(Val: I).getNoWrapFlags();
4452
4453 // For a vector GEP, keep the prefix scalar as long as possible, then
4454 // convert any scalars encountered after the first vector operand to vectors.
4455 bool IsVectorGEP = I.getType()->isVectorTy();
4456 ElementCount VectorElementCount =
4457 IsVectorGEP ? cast<VectorType>(Val: I.getType())->getElementCount()
4458 : ElementCount::getFixed(MinVal: 0);
4459
4460 for (gep_type_iterator GTI = gep_type_begin(GEP: &I), E = gep_type_end(GEP: &I);
4461 GTI != E; ++GTI) {
4462 const Value *Idx = GTI.getOperand();
4463 if (StructType *StTy = GTI.getStructTypeOrNull()) {
4464 unsigned Field = cast<Constant>(Val: Idx)->getUniqueInteger().getZExtValue();
4465 if (Field) {
4466 // N = N + Offset
4467 uint64_t Offset =
4468 DAG.getDataLayout().getStructLayout(Ty: StTy)->getElementOffset(Idx: Field);
4469
4470 // In an inbounds GEP with an offset that is nonnegative even when
4471 // interpreted as signed, assume there is no unsigned overflow.
4472 SDNodeFlags Flags;
4473 if (NW.hasNoUnsignedWrap() ||
4474 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4475 Flags |= SDNodeFlags::NoUnsignedWrap;
4476 Flags.setInBounds(NW.isInBounds());
4477
4478 N = DAG.getMemBasePlusOffset(
4479 Base: N, Offset: DAG.getConstant(Val: Offset, DL: dl, VT: N.getValueType()), DL: dl, Flags);
4480 }
4481 } else {
4482 // IdxSize is the width of the arithmetic according to IR semantics.
4483 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4484 // (and fix up the result later).
4485 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4486 MVT IdxTy = MVT::getIntegerVT(BitWidth: IdxSize);
4487 TypeSize ElementSize =
4488 GTI.getSequentialElementStride(DL: DAG.getDataLayout());
4489 // We intentionally mask away the high bits here; ElementSize may not
4490 // fit in IdxTy.
4491 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4492 /*isSigned=*/false, /*implicitTrunc=*/true);
4493 bool ElementScalable = ElementSize.isScalable();
4494
4495 // If this is a scalar constant or a splat vector of constants,
4496 // handle it quickly.
4497 const auto *C = dyn_cast<Constant>(Val: Idx);
4498 if (C && isa<VectorType>(Val: C->getType()))
4499 C = C->getSplatValue();
4500
4501 const auto *CI = dyn_cast_or_null<ConstantInt>(Val: C);
4502 if (CI && CI->isZero())
4503 continue;
4504 if (CI && !ElementScalable) {
4505 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(width: IdxSize);
4506 LLVMContext &Context = *DAG.getContext();
4507 SDValue OffsVal;
4508 if (N.getValueType().isVector())
4509 OffsVal = DAG.getConstant(
4510 Val: Offs, DL: dl, VT: EVT::getVectorVT(Context, VT: IdxTy, EC: VectorElementCount));
4511 else
4512 OffsVal = DAG.getConstant(Val: Offs, DL: dl, VT: IdxTy);
4513
4514 // In an inbounds GEP with an offset that is nonnegative even when
4515 // interpreted as signed, assume there is no unsigned overflow.
4516 SDNodeFlags Flags;
4517 if (NW.hasNoUnsignedWrap() ||
4518 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4519 Flags.setNoUnsignedWrap(true);
4520 Flags.setInBounds(NW.isInBounds());
4521
4522 OffsVal = DAG.getSExtOrTrunc(Op: OffsVal, DL: dl, VT: N.getValueType());
4523
4524 N = DAG.getMemBasePlusOffset(Base: N, Offset: OffsVal, DL: dl, Flags);
4525 continue;
4526 }
4527
4528 // N = N + Idx * ElementMul;
4529 SDValue IdxN = getValue(V: Idx);
4530
4531 if (IdxN.getValueType().isVector() != N.getValueType().isVector()) {
4532 if (N.getValueType().isVector()) {
4533 EVT VT = EVT::getVectorVT(Context&: *Context, VT: IdxN.getValueType(),
4534 EC: VectorElementCount);
4535 IdxN = DAG.getSplat(VT, DL: dl, Op: IdxN);
4536 } else {
4537 EVT VT =
4538 EVT::getVectorVT(Context&: *Context, VT: N.getValueType(), EC: VectorElementCount);
4539 N = DAG.getSplat(VT, DL: dl, Op: N);
4540 }
4541 }
4542
4543 // If the index is smaller or larger than intptr_t, truncate or extend
4544 // it.
4545 IdxN = DAG.getSExtOrTrunc(Op: IdxN, DL: dl, VT: N.getValueType());
4546
4547 SDNodeFlags ScaleFlags;
4548 // The multiplication of an index by the type size does not wrap the
4549 // pointer index type in a signed sense (mul nsw).
4550 ScaleFlags.setNoSignedWrap(NW.hasNoUnsignedSignedWrap());
4551
4552 // The multiplication of an index by the type size does not wrap the
4553 // pointer index type in an unsigned sense (mul nuw).
4554 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4555
4556 if (ElementScalable) {
4557 EVT VScaleTy = N.getValueType().getScalarType();
4558 SDValue VScale = DAG.getNode(
4559 Opcode: ISD::VSCALE, DL: dl, VT: VScaleTy,
4560 Operand: DAG.getConstant(Val: ElementMul.getZExtValue(), DL: dl, VT: VScaleTy));
4561 if (N.getValueType().isVector())
4562 VScale = DAG.getSplatVector(VT: N.getValueType(), DL: dl, Op: VScale);
4563 IdxN = DAG.getNode(Opcode: ISD::MUL, DL: dl, VT: N.getValueType(), N1: IdxN, N2: VScale,
4564 Flags: ScaleFlags);
4565 } else {
4566 // If this is a multiply by a power of two, turn it into a shl
4567 // immediately. This is a very common case.
4568 if (ElementMul != 1) {
4569 if (ElementMul.isPowerOf2()) {
4570 unsigned Amt = ElementMul.logBase2();
4571 IdxN = DAG.getNode(
4572 Opcode: ISD::SHL, DL: dl, VT: N.getValueType(), N1: IdxN,
4573 N2: DAG.getShiftAmountConstant(Val: Amt, VT: N.getValueType(), DL: dl),
4574 Flags: ScaleFlags);
4575 } else {
4576 SDValue Scale = DAG.getConstant(Val: ElementMul.getZExtValue(), DL: dl,
4577 VT: IdxN.getValueType());
4578 IdxN = DAG.getNode(Opcode: ISD::MUL, DL: dl, VT: N.getValueType(), N1: IdxN, N2: Scale,
4579 Flags: ScaleFlags);
4580 }
4581 }
4582 }
4583
4584 // The successive addition of the current address, truncated to the
4585 // pointer index type and interpreted as an unsigned number, and each
4586 // offset, also interpreted as an unsigned number, does not wrap the
4587 // pointer index type (add nuw).
4588 SDNodeFlags AddFlags;
4589 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4590 AddFlags.setInBounds(NW.isInBounds());
4591
4592 N = DAG.getMemBasePlusOffset(Base: N, Offset: IdxN, DL: dl, Flags: AddFlags);
4593 }
4594 }
4595
4596 if (IsVectorGEP && !N.getValueType().isVector()) {
4597 EVT VT = EVT::getVectorVT(Context&: *Context, VT: N.getValueType(), EC: VectorElementCount);
4598 N = DAG.getSplat(VT, DL: dl, Op: N);
4599 }
4600
4601 MVT PtrTy = TLI.getPointerTy(DL: DAG.getDataLayout(), AS);
4602 MVT PtrMemTy = TLI.getPointerMemTy(DL: DAG.getDataLayout(), AS);
4603 if (IsVectorGEP) {
4604 PtrTy = MVT::getVectorVT(VT: PtrTy, EC: VectorElementCount);
4605 PtrMemTy = MVT::getVectorVT(VT: PtrMemTy, EC: VectorElementCount);
4606 }
4607
4608 if (PtrMemTy != PtrTy && !cast<GEPOperator>(Val: I).isInBounds())
4609 N = DAG.getPtrExtendInReg(Op: N, DL: dl, VT: PtrMemTy);
4610
4611 setValue(V: &I, NewN: N);
4612}
4613
4614void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4615 // If this is a fixed sized alloca in the entry block of the function,
4616 // allocate it statically on the stack.
4617 if (FuncInfo.StaticAllocaMap.count(Val: &I))
4618 return; // getValue will auto-populate this.
4619
4620 SDLoc dl = getCurSDLoc();
4621 Type *Ty = I.getAllocatedType();
4622 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4623 auto &DL = DAG.getDataLayout();
4624 TypeSize TySize = DL.getTypeAllocSize(Ty);
4625 MaybeAlign Alignment = I.getAlign();
4626
4627 SDValue AllocSize = getValue(V: I.getArraySize());
4628
4629 EVT IntPtr = TLI.getPointerTy(DL, AS: I.getAddressSpace());
4630 if (AllocSize.getValueType() != IntPtr)
4631 AllocSize = DAG.getZExtOrTrunc(Op: AllocSize, DL: dl, VT: IntPtr);
4632
4633 AllocSize = DAG.getNode(
4634 Opcode: ISD::MUL, DL: dl, VT: IntPtr, N1: AllocSize,
4635 N2: DAG.getZExtOrTrunc(Op: DAG.getTypeSize(DL: dl, VT: MVT::i64, TS: TySize), DL: dl, VT: IntPtr));
4636
4637 // Handle alignment. If the requested alignment is less than or equal to
4638 // the stack alignment, ignore it. If the size is greater than or equal to
4639 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4640 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4641 if (*Alignment <= StackAlign)
4642 Alignment = std::nullopt;
4643
4644 const uint64_t StackAlignMask = StackAlign.value() - 1U;
4645 // Round the size of the allocation up to the stack alignment size
4646 // by add SA-1 to the size. This doesn't overflow because we're computing
4647 // an address inside an alloca.
4648 AllocSize = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: AllocSize.getValueType(), N1: AllocSize,
4649 N2: DAG.getConstant(Val: StackAlignMask, DL: dl, VT: IntPtr),
4650 Flags: SDNodeFlags::NoUnsignedWrap);
4651
4652 // Mask out the low bits for alignment purposes.
4653 AllocSize = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: AllocSize.getValueType(), N1: AllocSize,
4654 N2: DAG.getSignedConstant(Val: ~StackAlignMask, DL: dl, VT: IntPtr));
4655
4656 SDValue Ops[] = {
4657 getRoot(), AllocSize,
4658 DAG.getConstant(Val: Alignment ? Alignment->value() : 0, DL: dl, VT: IntPtr)};
4659 SDVTList VTs = DAG.getVTList(VT1: AllocSize.getValueType(), VT2: MVT::Other);
4660 SDValue DSA = DAG.getNode(Opcode: ISD::DYNAMIC_STACKALLOC, DL: dl, VTList: VTs, Ops);
4661 setValue(V: &I, NewN: DSA);
4662 DAG.setRoot(DSA.getValue(R: 1));
4663
4664 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4665}
4666
4667static const MDNode *getRangeMetadata(const Instruction &I) {
4668 return I.getMetadata(KindID: LLVMContext::MD_range);
4669}
4670
4671static std::optional<ConstantRange> getRange(const Instruction &I) {
4672 if (const auto *CB = dyn_cast<CallBase>(Val: &I))
4673 if (std::optional<ConstantRange> CR = CB->getRange())
4674 return CR;
4675 if (const MDNode *Range = getRangeMetadata(I))
4676 return getConstantRangeFromMetadata(RangeMD: *Range);
4677 return std::nullopt;
4678}
4679
4680static FPClassTest getNoFPClass(const Instruction &I) {
4681 if (const auto *CB = dyn_cast<CallBase>(Val: &I))
4682 return CB->getRetNoFPClass();
4683 return fcNone;
4684}
4685
4686void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4687 if (I.isAtomic())
4688 return visitAtomicLoad(I);
4689
4690 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4691 const Value *SV = I.getOperand(i_nocapture: 0);
4692 if (TLI.supportSwiftError()) {
4693 // Swifterror values can come from either a function parameter with
4694 // swifterror attribute or an alloca with swifterror attribute.
4695 if (const Argument *Arg = dyn_cast<Argument>(Val: SV)) {
4696 if (Arg->hasSwiftErrorAttr())
4697 return visitLoadFromSwiftError(I);
4698 }
4699
4700 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(Val: SV)) {
4701 if (Alloca->isSwiftError())
4702 return visitLoadFromSwiftError(I);
4703 }
4704 }
4705
4706 SDValue Ptr = getValue(V: SV);
4707
4708 Type *Ty = I.getType();
4709 SmallVector<EVT, 4> ValueVTs, MemVTs;
4710 SmallVector<TypeSize, 4> Offsets;
4711 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty, ValueVTs, MemVTs: &MemVTs, Offsets: &Offsets);
4712 unsigned NumValues = ValueVTs.size();
4713 if (NumValues == 0)
4714 return;
4715
4716 Align Alignment = I.getAlign();
4717 AAMDNodes AAInfo = I.getAAMetadata();
4718 const MDNode *Ranges = getRangeMetadata(I);
4719 bool isVolatile = I.isVolatile();
4720 MachineMemOperand::Flags MMOFlags =
4721 TLI.getLoadMemOperandFlags(LI: I, DL: DAG.getDataLayout(), AC, LibInfo);
4722
4723 SDValue Root;
4724 bool ConstantMemory = false;
4725 if (isVolatile)
4726 // Serialize volatile loads with other side effects.
4727 Root = getRoot();
4728 else if (NumValues > MaxParallelChains)
4729 Root = getMemoryRoot();
4730 else if (BatchAA &&
4731 BatchAA->pointsToConstantMemory(Loc: MemoryLocation(
4732 SV,
4733 LocationSize::precise(Value: DAG.getDataLayout().getTypeStoreSize(Ty)),
4734 AAInfo))) {
4735 // Do not serialize (non-volatile) loads of constant memory with anything.
4736 Root = DAG.getEntryNode();
4737 ConstantMemory = true;
4738 MMOFlags |= MachineMemOperand::MOInvariant;
4739 } else {
4740 // Do not serialize non-volatile loads against each other.
4741 Root = DAG.getRoot();
4742 }
4743
4744 SDLoc dl = getCurSDLoc();
4745
4746 if (isVolatile)
4747 Root = TLI.prepareVolatileOrAtomicLoad(Chain: Root, DL: dl, DAG);
4748
4749 SmallVector<SDValue, 4> Values(NumValues);
4750 SmallVector<SDValue, 4> Chains(std::min(a: MaxParallelChains, b: NumValues));
4751
4752 unsigned ChainI = 0;
4753 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4754 // Serializing loads here may result in excessive register pressure, and
4755 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4756 // could recover a bit by hoisting nodes upward in the chain by recognizing
4757 // they are side-effect free or do not alias. The optimizer should really
4758 // avoid this case by converting large object/array copies to llvm.memcpy
4759 // (MaxParallelChains should always remain as failsafe).
4760 if (ChainI == MaxParallelChains) {
4761 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4762 SDValue Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4763 Ops: ArrayRef(Chains.data(), ChainI));
4764 Root = Chain;
4765 ChainI = 0;
4766 }
4767
4768 // TODO: MachinePointerInfo only supports a fixed length offset.
4769 MachinePointerInfo PtrInfo =
4770 !Offsets[i].isScalable() || Offsets[i].isZero()
4771 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4772 : MachinePointerInfo();
4773
4774 SDValue A = DAG.getObjectPtrOffset(SL: dl, Ptr, Offset: Offsets[i]);
4775 SDValue L = DAG.getLoad(VT: MemVTs[i], dl, Chain: Root, Ptr: A, PtrInfo, Alignment,
4776 MMOFlags, AAInfo, Ranges);
4777 Chains[ChainI] = L.getValue(R: 1);
4778
4779 if (MemVTs[i] != ValueVTs[i])
4780 L = DAG.getPtrExtOrTrunc(Op: L, DL: dl, VT: ValueVTs[i]);
4781
4782 Values[i] = L;
4783 }
4784
4785 if (!ConstantMemory) {
4786 SDValue Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4787 Ops: ArrayRef(Chains.data(), ChainI));
4788 if (isVolatile)
4789 DAG.setRoot(Chain);
4790 else
4791 PendingLoads.push_back(Elt: Chain);
4792 }
4793
4794 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl,
4795 VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values));
4796}
4797
4798void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4799 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4800 "call visitStoreToSwiftError when backend supports swifterror");
4801
4802 SmallVector<EVT, 4> ValueVTs;
4803 SmallVector<uint64_t, 4> Offsets;
4804 const Value *SrcV = I.getOperand(i_nocapture: 0);
4805 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(),
4806 Ty: SrcV->getType(), ValueVTs, /*MemVTs=*/nullptr, FixedOffsets: &Offsets, StartingOffset: 0);
4807 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4808 "expect a single EVT for swifterror");
4809
4810 SDValue Src = getValue(V: SrcV);
4811 // Create a virtual register, then update the virtual register.
4812 Register VReg =
4813 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4814 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4815 // Chain can be getRoot or getControlRoot.
4816 SDValue CopyNode = DAG.getCopyToReg(Chain: getRoot(), dl: getCurSDLoc(), Reg: VReg,
4817 N: SDValue(Src.getNode(), Src.getResNo()));
4818 DAG.setRoot(CopyNode);
4819}
4820
4821void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4822 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4823 "call visitLoadFromSwiftError when backend supports swifterror");
4824
4825 assert(!I.isVolatile() &&
4826 !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4827 !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4828 "Support volatile, non temporal, invariant for load_from_swift_error");
4829
4830 const Value *SV = I.getOperand(i_nocapture: 0);
4831 Type *Ty = I.getType();
4832 assert(
4833 (!BatchAA ||
4834 !BatchAA->pointsToConstantMemory(MemoryLocation(
4835 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4836 I.getAAMetadata()))) &&
4837 "load_from_swift_error should not be constant memory");
4838
4839 SmallVector<EVT, 4> ValueVTs;
4840 SmallVector<uint64_t, 4> Offsets;
4841 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty,
4842 ValueVTs, /*MemVTs=*/nullptr, FixedOffsets: &Offsets, StartingOffset: 0);
4843 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4844 "expect a single EVT for swifterror");
4845
4846 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4847 SDValue L = DAG.getCopyFromReg(
4848 Chain: getRoot(), dl: getCurSDLoc(),
4849 Reg: SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), VT: ValueVTs[0]);
4850
4851 setValue(V: &I, NewN: L);
4852}
4853
4854void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4855 if (I.isAtomic())
4856 return visitAtomicStore(I);
4857
4858 const Value *SrcV = I.getOperand(i_nocapture: 0);
4859 const Value *PtrV = I.getOperand(i_nocapture: 1);
4860
4861 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4862 if (TLI.supportSwiftError()) {
4863 // Swifterror values can come from either a function parameter with
4864 // swifterror attribute or an alloca with swifterror attribute.
4865 if (const Argument *Arg = dyn_cast<Argument>(Val: PtrV)) {
4866 if (Arg->hasSwiftErrorAttr())
4867 return visitStoreToSwiftError(I);
4868 }
4869
4870 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(Val: PtrV)) {
4871 if (Alloca->isSwiftError())
4872 return visitStoreToSwiftError(I);
4873 }
4874 }
4875
4876 SmallVector<EVT, 4> ValueVTs, MemVTs;
4877 SmallVector<TypeSize, 4> Offsets;
4878 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(),
4879 Ty: SrcV->getType(), ValueVTs, MemVTs: &MemVTs, Offsets: &Offsets);
4880 unsigned NumValues = ValueVTs.size();
4881 if (NumValues == 0)
4882 return;
4883
4884 // Get the lowered operands. Note that we do this after
4885 // checking if NumResults is zero, because with zero results
4886 // the operands won't have values in the map.
4887 SDValue Src = getValue(V: SrcV);
4888 SDValue Ptr = getValue(V: PtrV);
4889
4890 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4891 SmallVector<SDValue, 4> Chains(std::min(a: MaxParallelChains, b: NumValues));
4892 SDLoc dl = getCurSDLoc();
4893 Align Alignment = I.getAlign();
4894 AAMDNodes AAInfo = I.getAAMetadata();
4895
4896 auto MMOFlags = TLI.getStoreMemOperandFlags(SI: I, DL: DAG.getDataLayout());
4897
4898 unsigned ChainI = 0;
4899 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4900 // See visitLoad comments.
4901 if (ChainI == MaxParallelChains) {
4902 SDValue Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4903 Ops: ArrayRef(Chains.data(), ChainI));
4904 Root = Chain;
4905 ChainI = 0;
4906 }
4907
4908 // TODO: MachinePointerInfo only supports a fixed length offset.
4909 MachinePointerInfo PtrInfo =
4910 !Offsets[i].isScalable() || Offsets[i].isZero()
4911 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4912 : MachinePointerInfo();
4913
4914 SDValue Add = DAG.getObjectPtrOffset(SL: dl, Ptr, Offset: Offsets[i]);
4915 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4916 if (MemVTs[i] != ValueVTs[i])
4917 Val = DAG.getPtrExtOrTrunc(Op: Val, DL: dl, VT: MemVTs[i]);
4918 SDValue St =
4919 DAG.getStore(Chain: Root, dl, Val, Ptr: Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4920 Chains[ChainI] = St;
4921 }
4922
4923 SDValue StoreNode = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4924 Ops: ArrayRef(Chains.data(), ChainI));
4925 setValue(V: &I, NewN: StoreNode);
4926 DAG.setRoot(StoreNode);
4927}
4928
4929void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4930 bool IsCompressing) {
4931 SDLoc sdl = getCurSDLoc();
4932
4933 Value *Src0Operand = I.getArgOperand(i: 0);
4934 Value *PtrOperand = I.getArgOperand(i: 1);
4935 Value *MaskOperand = I.getArgOperand(i: 2);
4936 Align Alignment = I.getParamAlign(ArgNo: 1).valueOrOne();
4937
4938 SDValue Ptr = getValue(V: PtrOperand);
4939 SDValue Src0 = getValue(V: Src0Operand);
4940 SDValue Mask = getValue(V: MaskOperand);
4941 SDValue Offset = DAG.getUNDEF(VT: Ptr.getValueType());
4942
4943 EVT VT = Src0.getValueType();
4944
4945 auto MMOFlags = MachineMemOperand::MOStore;
4946 if (I.hasMetadata(KindID: LLVMContext::MD_nontemporal))
4947 MMOFlags |= MachineMemOperand::MONonTemporal;
4948
4949 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4950 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
4951 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: Alignment, AAInfo: I.getAAMetadata());
4952
4953 const auto &TLI = DAG.getTargetLoweringInfo();
4954
4955 SDValue StoreNode =
4956 !IsCompressing && TTI->hasConditionalLoadStoreForType(
4957 Ty: I.getArgOperand(i: 0)->getType(), /*IsStore=*/true)
4958 ? TLI.visitMaskedStore(DAG, DL: sdl, Chain: getMemoryRoot(), MMO, Ptr, Val: Src0,
4959 Mask)
4960 : DAG.getMaskedStore(Chain: getMemoryRoot(), dl: sdl, Val: Src0, Base: Ptr, Offset, Mask,
4961 MemVT: VT, MMO, AM: ISD::UNINDEXED, /*Truncating=*/IsTruncating: false,
4962 IsCompressing);
4963 DAG.setRoot(StoreNode);
4964 setValue(V: &I, NewN: StoreNode);
4965}
4966
4967// Get a uniform base for the Gather/Scatter intrinsic.
4968// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4969// We try to represent it as a base pointer + vector of indices.
4970// Usually, the vector of pointers comes from a 'getelementptr' instruction.
4971// The first operand of the GEP may be a single pointer or a vector of pointers
4972// Example:
4973// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4974// or
4975// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
4976// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4977//
4978// When the first GEP operand is a single pointer - it is the uniform base we
4979// are looking for. If first operand of the GEP is a splat vector - we
4980// extract the splat value and use it as a uniform base.
4981// In all other cases the function returns 'false'.
4982static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4983 SDValue &Scale, SelectionDAGBuilder *SDB,
4984 const BasicBlock *CurBB, uint64_t ElemSize) {
4985 SelectionDAG& DAG = SDB->DAG;
4986 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4987 const DataLayout &DL = DAG.getDataLayout();
4988
4989 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4990
4991 // Handle splat constant pointer.
4992 if (auto *C = dyn_cast<Constant>(Val: Ptr)) {
4993 C = C->getSplatValue();
4994 if (!C)
4995 return false;
4996
4997 Base = SDB->getValue(V: C);
4998
4999 ElementCount NumElts = cast<VectorType>(Val: Ptr->getType())->getElementCount();
5000 EVT VT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: TLI.getPointerTy(DL), EC: NumElts);
5001 Index = DAG.getConstant(Val: 0, DL: SDB->getCurSDLoc(), VT);
5002 Scale = DAG.getTargetConstant(Val: 1, DL: SDB->getCurSDLoc(), VT: TLI.getPointerTy(DL));
5003 return true;
5004 }
5005
5006 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Val: Ptr);
5007 if (!GEP || GEP->getParent() != CurBB)
5008 return false;
5009
5010 if (GEP->getNumOperands() != 2)
5011 return false;
5012
5013 const Value *BasePtr = GEP->getPointerOperand();
5014 const Value *IndexVal = GEP->getOperand(i_nocapture: GEP->getNumOperands() - 1);
5015
5016 // Make sure the base is scalar and the index is a vector.
5017 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
5018 return false;
5019
5020 TypeSize ScaleVal = DL.getTypeAllocSize(Ty: GEP->getResultElementType());
5021 if (ScaleVal.isScalable())
5022 return false;
5023
5024 // Target may not support the required addressing mode.
5025 if (ScaleVal != 1 &&
5026 !TLI.isLegalScaleForGatherScatter(Scale: ScaleVal.getFixedValue(), ElemSize))
5027 return false;
5028
5029 Base = SDB->getValue(V: BasePtr);
5030 Index = SDB->getValue(V: IndexVal);
5031
5032 Scale =
5033 DAG.getTargetConstant(Val: ScaleVal, DL: SDB->getCurSDLoc(), VT: TLI.getPointerTy(DL));
5034 return true;
5035}
5036
5037void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
5038 SDLoc sdl = getCurSDLoc();
5039
5040 // llvm.masked.scatter.*(Src0, Ptrs, Mask)
5041 const Value *Ptr = I.getArgOperand(i: 1);
5042 SDValue Src0 = getValue(V: I.getArgOperand(i: 0));
5043 SDValue Mask = getValue(V: I.getArgOperand(i: 2));
5044 EVT VT = Src0.getValueType();
5045 Align Alignment = I.getParamAlign(ArgNo: 1).valueOrOne();
5046 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5047
5048 SDValue Base;
5049 SDValue Index;
5050 SDValue Scale;
5051 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, SDB: this,
5052 CurBB: I.getParent(), ElemSize: VT.getScalarStoreSize());
5053
5054 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5055 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5056 PtrInfo: MachinePointerInfo(AS), F: MachineMemOperand::MOStore,
5057 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: Alignment, AAInfo: I.getAAMetadata());
5058 if (!UniformBase) {
5059 Base = DAG.getConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5060 Index = getValue(V: Ptr);
5061 Scale =
5062 DAG.getTargetConstant(Val: 1, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5063 }
5064
5065 EVT IdxVT = Index.getValueType();
5066 EVT EltTy = IdxVT.getVectorElementType();
5067 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
5068 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
5069 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: sdl, VT: NewIdxVT, Operand: Index);
5070 }
5071
5072 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
5073 SDValue Scatter = DAG.getMaskedScatter(VTs: DAG.getVTList(VT: MVT::Other), MemVT: VT, dl: sdl,
5074 Ops, MMO, IndexType: ISD::SIGNED_SCALED, IsTruncating: false);
5075 DAG.setRoot(Scatter);
5076 setValue(V: &I, NewN: Scatter);
5077}
5078
5079void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
5080 SDLoc sdl = getCurSDLoc();
5081
5082 Value *PtrOperand = I.getArgOperand(i: 0);
5083 Value *MaskOperand = I.getArgOperand(i: 1);
5084 Value *Src0Operand = I.getArgOperand(i: 2);
5085 Align Alignment = I.getParamAlign(ArgNo: 0).valueOrOne();
5086
5087 SDValue Ptr = getValue(V: PtrOperand);
5088 SDValue Src0 = getValue(V: Src0Operand);
5089 SDValue Mask = getValue(V: MaskOperand);
5090 SDValue Offset = DAG.getUNDEF(VT: Ptr.getValueType());
5091
5092 EVT VT = Src0.getValueType();
5093 AAMDNodes AAInfo = I.getAAMetadata();
5094 const MDNode *Ranges = getRangeMetadata(I);
5095
5096 // Do not serialize masked loads of constant memory with anything.
5097 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
5098 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
5099
5100 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
5101
5102 auto MMOFlags = MachineMemOperand::MOLoad;
5103 if (I.hasMetadata(KindID: LLVMContext::MD_nontemporal))
5104 MMOFlags |= MachineMemOperand::MONonTemporal;
5105 if (I.hasMetadata(KindID: LLVMContext::MD_invariant_load))
5106 MMOFlags |= MachineMemOperand::MOInvariant;
5107
5108 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5109 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
5110 Size: VT.getStoreSize(), BaseAlignment: Alignment, AAInfo, Ranges);
5111
5112 const auto &TLI = DAG.getTargetLoweringInfo();
5113
5114 // The Load/Res may point to different values and both of them are output
5115 // variables.
5116 SDValue Load;
5117 SDValue Res;
5118 if (!IsExpanding &&
5119 TTI->hasConditionalLoadStoreForType(Ty: Src0Operand->getType(),
5120 /*IsStore=*/false))
5121 Res = TLI.visitMaskedLoad(DAG, DL: sdl, Chain: InChain, MMO, NewLoad&: Load, Ptr, PassThru: Src0, Mask);
5122 else
5123 Res = Load =
5124 DAG.getMaskedLoad(VT, dl: sdl, Chain: InChain, Base: Ptr, Offset, Mask, Src0, MemVT: VT, MMO,
5125 AM: ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5126 if (AddToChain)
5127 PendingLoads.push_back(Elt: Load.getValue(R: 1));
5128 setValue(V: &I, NewN: Res);
5129}
5130
5131void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5132 SDLoc sdl = getCurSDLoc();
5133
5134 // @llvm.masked.gather.*(Ptrs, Mask, Src0)
5135 const Value *Ptr = I.getArgOperand(i: 0);
5136 SDValue Src0 = getValue(V: I.getArgOperand(i: 2));
5137 SDValue Mask = getValue(V: I.getArgOperand(i: 1));
5138
5139 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5140 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
5141 Align Alignment = I.getParamAlign(ArgNo: 0).valueOrOne();
5142
5143 const MDNode *Ranges = getRangeMetadata(I);
5144
5145 SDValue Root = DAG.getRoot();
5146 SDValue Base;
5147 SDValue Index;
5148 SDValue Scale;
5149 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, SDB: this,
5150 CurBB: I.getParent(), ElemSize: VT.getScalarStoreSize());
5151 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5152 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5153 PtrInfo: MachinePointerInfo(AS), F: MachineMemOperand::MOLoad,
5154 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: Alignment, AAInfo: I.getAAMetadata(),
5155 Ranges);
5156
5157 if (!UniformBase) {
5158 Base = DAG.getConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5159 Index = getValue(V: Ptr);
5160 Scale =
5161 DAG.getTargetConstant(Val: 1, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5162 }
5163
5164 EVT IdxVT = Index.getValueType();
5165 EVT EltTy = IdxVT.getVectorElementType();
5166 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
5167 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
5168 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: sdl, VT: NewIdxVT, Operand: Index);
5169 }
5170
5171 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5172 SDValue Gather =
5173 DAG.getMaskedGather(VTs: DAG.getVTList(VT1: VT, VT2: MVT::Other), MemVT: VT, dl: sdl, Ops, MMO,
5174 IndexType: ISD::SIGNED_SCALED, ExtTy: ISD::NON_EXTLOAD);
5175
5176 PendingLoads.push_back(Elt: Gather.getValue(R: 1));
5177 setValue(V: &I, NewN: Gather);
5178}
5179
5180void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5181 SDLoc dl = getCurSDLoc();
5182 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5183 AtomicOrdering FailureOrdering = I.getFailureOrdering();
5184 SyncScope::ID SSID = I.getSyncScopeID();
5185
5186 SDValue InChain = getRoot();
5187
5188 MVT MemVT = getValue(V: I.getCompareOperand()).getSimpleValueType();
5189 SDVTList VTs = DAG.getVTList(VT1: MemVT, VT2: MVT::i1, VT3: MVT::Other);
5190
5191 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5192 auto Flags = TLI.getAtomicMemOperandFlags(AI: I, DL: DAG.getDataLayout());
5193
5194 MachineFunction &MF = DAG.getMachineFunction();
5195 MachineMemOperand *MMO = MF.getMachineMemOperand(
5196 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5197 BaseAlignment: DAG.getEVTAlign(MemoryVT: MemVT), AAInfo: AAMDNodes(), Ranges: nullptr, SSID, Ordering: SuccessOrdering,
5198 FailureOrdering);
5199
5200 SDValue L = DAG.getAtomicCmpSwap(Opcode: ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5201 dl, MemVT, VTs, Chain: InChain,
5202 Ptr: getValue(V: I.getPointerOperand()),
5203 Cmp: getValue(V: I.getCompareOperand()),
5204 Swp: getValue(V: I.getNewValOperand()), MMO);
5205
5206 SDValue OutChain = L.getValue(R: 2);
5207
5208 setValue(V: &I, NewN: L);
5209 DAG.setRoot(OutChain);
5210}
5211
5212void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5213 SDLoc dl = getCurSDLoc();
5214 ISD::NodeType NT;
5215 switch (I.getOperation()) {
5216 default: llvm_unreachable("Unknown atomicrmw operation");
5217 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5218 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
5219 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
5220 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
5221 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5222 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
5223 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
5224 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
5225 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
5226 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5227 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5228 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5229 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5230 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5231 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5232 case AtomicRMWInst::FMaximum:
5233 NT = ISD::ATOMIC_LOAD_FMAXIMUM;
5234 break;
5235 case AtomicRMWInst::FMinimum:
5236 NT = ISD::ATOMIC_LOAD_FMINIMUM;
5237 break;
5238 case AtomicRMWInst::UIncWrap:
5239 NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5240 break;
5241 case AtomicRMWInst::UDecWrap:
5242 NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5243 break;
5244 case AtomicRMWInst::USubCond:
5245 NT = ISD::ATOMIC_LOAD_USUB_COND;
5246 break;
5247 case AtomicRMWInst::USubSat:
5248 NT = ISD::ATOMIC_LOAD_USUB_SAT;
5249 break;
5250 }
5251 AtomicOrdering Ordering = I.getOrdering();
5252 SyncScope::ID SSID = I.getSyncScopeID();
5253
5254 SDValue InChain = getRoot();
5255
5256 auto MemVT = getValue(V: I.getValOperand()).getSimpleValueType();
5257 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5258 auto Flags = TLI.getAtomicMemOperandFlags(AI: I, DL: DAG.getDataLayout());
5259
5260 MachineFunction &MF = DAG.getMachineFunction();
5261 MachineMemOperand *MMO = MF.getMachineMemOperand(
5262 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5263 BaseAlignment: DAG.getEVTAlign(MemoryVT: MemVT), AAInfo: AAMDNodes(), Ranges: nullptr, SSID, Ordering);
5264
5265 SDValue L =
5266 DAG.getAtomic(Opcode: NT, dl, MemVT, Chain: InChain,
5267 Ptr: getValue(V: I.getPointerOperand()), Val: getValue(V: I.getValOperand()),
5268 MMO);
5269
5270 SDValue OutChain = L.getValue(R: 1);
5271
5272 setValue(V: &I, NewN: L);
5273 DAG.setRoot(OutChain);
5274}
5275
5276void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5277 SDLoc dl = getCurSDLoc();
5278 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5279 SDValue Ops[3];
5280 Ops[0] = getRoot();
5281 Ops[1] = DAG.getTargetConstant(Val: (unsigned)I.getOrdering(), DL: dl,
5282 VT: TLI.getFenceOperandTy(DL: DAG.getDataLayout()));
5283 Ops[2] = DAG.getTargetConstant(Val: I.getSyncScopeID(), DL: dl,
5284 VT: TLI.getFenceOperandTy(DL: DAG.getDataLayout()));
5285 SDValue N = DAG.getNode(Opcode: ISD::ATOMIC_FENCE, DL: dl, VT: MVT::Other, Ops);
5286 setValue(V: &I, NewN: N);
5287 DAG.setRoot(N);
5288}
5289
5290void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5291 SDLoc dl = getCurSDLoc();
5292 AtomicOrdering Order = I.getOrdering();
5293 SyncScope::ID SSID = I.getSyncScopeID();
5294
5295 SDValue InChain = getRoot();
5296
5297 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5298 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
5299 EVT MemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getType());
5300
5301 if (!TLI.supportsUnalignedAtomics() &&
5302 I.getAlign().value() < MemVT.getSizeInBits() / 8)
5303 report_fatal_error(reason: "Cannot generate unaligned atomic load");
5304
5305 auto Flags = TLI.getLoadMemOperandFlags(LI: I, DL: DAG.getDataLayout(), AC, LibInfo);
5306
5307 const MDNode *Ranges = getRangeMetadata(I);
5308 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5309 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5310 BaseAlignment: I.getAlign(), AAInfo: AAMDNodes(), Ranges, SSID, Ordering: Order);
5311
5312 InChain = TLI.prepareVolatileOrAtomicLoad(Chain: InChain, DL: dl, DAG);
5313
5314 SDValue Ptr = getValue(V: I.getPointerOperand());
5315 SDValue L =
5316 DAG.getAtomicLoad(ExtType: ISD::NON_EXTLOAD, dl, MemVT, VT: MemVT, Chain: InChain, Ptr, MMO);
5317
5318 SDValue OutChain = L.getValue(R: 1);
5319 if (MemVT != VT)
5320 L = DAG.getPtrExtOrTrunc(Op: L, DL: dl, VT);
5321
5322 setValue(V: &I, NewN: L);
5323 DAG.setRoot(OutChain);
5324}
5325
5326void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5327 SDLoc dl = getCurSDLoc();
5328
5329 AtomicOrdering Ordering = I.getOrdering();
5330 SyncScope::ID SSID = I.getSyncScopeID();
5331
5332 SDValue InChain = getRoot();
5333
5334 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5335 EVT MemVT =
5336 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getValueOperand()->getType());
5337
5338 if (!TLI.supportsUnalignedAtomics() &&
5339 I.getAlign().value() < MemVT.getSizeInBits() / 8)
5340 report_fatal_error(reason: "Cannot generate unaligned atomic store");
5341
5342 auto Flags = TLI.getStoreMemOperandFlags(SI: I, DL: DAG.getDataLayout());
5343
5344 MachineFunction &MF = DAG.getMachineFunction();
5345 MachineMemOperand *MMO = MF.getMachineMemOperand(
5346 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5347 BaseAlignment: I.getAlign(), AAInfo: AAMDNodes(), Ranges: nullptr, SSID, Ordering);
5348
5349 SDValue Val = getValue(V: I.getValueOperand());
5350 if (Val.getValueType() != MemVT)
5351 Val = DAG.getPtrExtOrTrunc(Op: Val, DL: dl, VT: MemVT);
5352 SDValue Ptr = getValue(V: I.getPointerOperand());
5353
5354 SDValue OutChain =
5355 DAG.getAtomic(Opcode: ISD::ATOMIC_STORE, dl, MemVT, Chain: InChain, Ptr: Val, Val: Ptr, MMO);
5356
5357 setValue(V: &I, NewN: OutChain);
5358 DAG.setRoot(OutChain);
5359}
5360
5361/// Check if this intrinsic call depends on the chain (1st return value)
5362/// and if it only *loads* memory.
5363/// Ignore the callsite's attributes. A specific call site may be marked with
5364/// readnone, but the lowering code will expect the chain based on the
5365/// definition.
5366std::pair<bool, bool>
5367SelectionDAGBuilder::getTargetIntrinsicCallProperties(const CallBase &I) {
5368 const Function *F = I.getCalledFunction();
5369 bool HasChain = !F->doesNotAccessMemory();
5370 bool OnlyLoad =
5371 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5372
5373 return {HasChain, OnlyLoad};
5374}
5375
5376SmallVector<SDValue, 8> SelectionDAGBuilder::getTargetIntrinsicOperands(
5377 const CallBase &I, bool HasChain, bool OnlyLoad,
5378 TargetLowering::IntrinsicInfo *TgtMemIntrinsicInfo) {
5379 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5380
5381 // Build the operand list.
5382 SmallVector<SDValue, 8> Ops;
5383 if (HasChain) { // If this intrinsic has side-effects, chainify it.
5384 if (OnlyLoad) {
5385 // We don't need to serialize loads against other loads.
5386 Ops.push_back(Elt: DAG.getRoot());
5387 } else {
5388 Ops.push_back(Elt: getRoot());
5389 }
5390 }
5391
5392 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5393 if (!TgtMemIntrinsicInfo || TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_VOID ||
5394 TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_W_CHAIN)
5395 Ops.push_back(Elt: DAG.getTargetConstant(Val: I.getIntrinsicID(), DL: getCurSDLoc(),
5396 VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
5397
5398 // Add all operands of the call to the operand list.
5399 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5400 const Value *Arg = I.getArgOperand(i);
5401 if (!I.paramHasAttr(ArgNo: i, Kind: Attribute::ImmArg)) {
5402 Ops.push_back(Elt: getValue(V: Arg));
5403 continue;
5404 }
5405
5406 // Use TargetConstant instead of a regular constant for immarg.
5407 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: Arg->getType(), AllowUnknown: true);
5408 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: Arg)) {
5409 assert(CI->getBitWidth() <= 64 &&
5410 "large intrinsic immediates not handled");
5411 Ops.push_back(Elt: DAG.getTargetConstant(Val: *CI, DL: SDLoc(), VT));
5412 } else {
5413 Ops.push_back(
5414 Elt: DAG.getTargetConstantFP(Val: *cast<ConstantFP>(Val: Arg), DL: SDLoc(), VT));
5415 }
5416 }
5417
5418 if (std::optional<OperandBundleUse> Bundle =
5419 I.getOperandBundle(ID: LLVMContext::OB_deactivation_symbol)) {
5420 auto *Sym = Bundle->Inputs[0].get();
5421 SDValue SDSym = getValue(V: Sym);
5422 SDSym = DAG.getDeactivationSymbol(GV: cast<GlobalValue>(Val: Sym));
5423 Ops.push_back(Elt: SDSym);
5424 }
5425
5426 if (std::optional<OperandBundleUse> Bundle =
5427 I.getOperandBundle(ID: LLVMContext::OB_convergencectrl)) {
5428 Value *Token = Bundle->Inputs[0].get();
5429 SDValue ConvControlToken = getValue(V: Token);
5430 assert(Ops.back().getValueType() != MVT::Glue &&
5431 "Did not expect another glue node here.");
5432 ConvControlToken =
5433 DAG.getNode(Opcode: ISD::CONVERGENCECTRL_GLUE, DL: {}, VT: MVT::Glue, Operand: ConvControlToken);
5434 Ops.push_back(Elt: ConvControlToken);
5435 }
5436
5437 return Ops;
5438}
5439
5440SDVTList SelectionDAGBuilder::getTargetIntrinsicVTList(const CallBase &I,
5441 bool HasChain) {
5442 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5443
5444 SmallVector<EVT, 4> ValueVTs;
5445 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: I.getType(), ValueVTs);
5446
5447 if (HasChain)
5448 ValueVTs.push_back(Elt: MVT::Other);
5449
5450 return DAG.getVTList(VTs: ValueVTs);
5451}
5452
5453/// Get an INTRINSIC node for a target intrinsic which does not touch memory.
5454SDValue SelectionDAGBuilder::getTargetNonMemIntrinsicNode(
5455 const Type &IntrinsicVT, bool HasChain, ArrayRef<SDValue> Ops,
5456 const SDVTList &VTs) {
5457 if (!HasChain)
5458 return DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: getCurSDLoc(), VTList: VTs, Ops);
5459 if (!IntrinsicVT.isVoidTy())
5460 return DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL: getCurSDLoc(), VTList: VTs, Ops);
5461 return DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL: getCurSDLoc(), VTList: VTs, Ops);
5462}
5463
5464/// Set root, convert return type if necessary and check alignment.
5465SDValue SelectionDAGBuilder::handleTargetIntrinsicRet(const CallBase &I,
5466 bool HasChain,
5467 bool OnlyLoad,
5468 SDValue Result) {
5469 if (HasChain) {
5470 SDValue Chain = Result.getValue(R: Result.getNode()->getNumValues() - 1);
5471 if (OnlyLoad)
5472 PendingLoads.push_back(Elt: Chain);
5473 else
5474 DAG.setRoot(Chain);
5475 }
5476
5477 if (I.getType()->isVoidTy())
5478 return Result;
5479
5480 if (MaybeAlign Alignment = I.getRetAlign(); InsertAssertAlign && Alignment) {
5481 // Insert `assertalign` node if there's an alignment.
5482 Result = DAG.getAssertAlign(DL: getCurSDLoc(), V: Result, A: Alignment.valueOrOne());
5483 } else if (!isa<VectorType>(Val: I.getType())) {
5484 Result = lowerRangeToAssertZExt(DAG, I, Op: Result);
5485 }
5486
5487 return Result;
5488}
5489
5490/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5491/// node.
5492void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5493 unsigned Intrinsic) {
5494 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
5495
5496 // Infos is set by getTgtMemIntrinsic.
5497 SmallVector<TargetLowering::IntrinsicInfo> Infos;
5498 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5499 TLI.getTgtMemIntrinsic(Infos, I, MF&: DAG.getMachineFunction(), Intrinsic);
5500 // Use the first (primary) info determines the node opcode.
5501 TargetLowering::IntrinsicInfo *Info = !Infos.empty() ? &Infos[0] : nullptr;
5502
5503 SmallVector<SDValue, 8> Ops =
5504 getTargetIntrinsicOperands(I, HasChain, OnlyLoad, TgtMemIntrinsicInfo: Info);
5505 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
5506
5507 // Propagate fast-math-flags from IR to node(s).
5508 SDNodeFlags Flags;
5509 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &I))
5510 Flags.copyFMF(FPMO: *FPMO);
5511 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5512
5513 // Create the node.
5514 SDValue Result;
5515
5516 // In some cases, custom collection of operands from CallInst I may be needed.
5517 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5518 if (!Infos.empty()) {
5519 // This is target intrinsic that touches memory
5520 // Create MachineMemOperands for each memory access described by the target.
5521 MachineFunction &MF = DAG.getMachineFunction();
5522 SmallVector<MachineMemOperand *> MMOs;
5523 for (const auto &Info : Infos) {
5524 // TODO: We currently just fallback to address space 0 if
5525 // getTgtMemIntrinsic didn't yield anything useful.
5526 MachinePointerInfo MPI;
5527 if (Info.ptrVal)
5528 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5529 else if (Info.fallbackAddressSpace)
5530 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5531 EVT MemVT = Info.memVT;
5532 LocationSize Size = LocationSize::precise(Value: Info.size);
5533 if (Size.hasValue() && !Size.getValue())
5534 Size = LocationSize::precise(Value: MemVT.getStoreSize());
5535 Align Alignment = Info.align.value_or(u: DAG.getEVTAlign(MemoryVT: MemVT));
5536 MachineMemOperand *MMO = MF.getMachineMemOperand(
5537 PtrInfo: MPI, F: Info.flags, Size, BaseAlignment: Alignment, AAInfo: I.getAAMetadata(),
5538 /*Ranges=*/nullptr, SSID: Info.ssid, Ordering: Info.order, FailureOrdering: Info.failureOrder);
5539 MMOs.push_back(Elt: MMO);
5540 }
5541
5542 Result = DAG.getMemIntrinsicNode(Opcode: Info->opc, dl: getCurSDLoc(), VTList: VTs, Ops,
5543 MemVT: Info->memVT, MMOs);
5544 } else {
5545 Result = getTargetNonMemIntrinsicNode(IntrinsicVT: *I.getType(), HasChain, Ops, VTs);
5546 }
5547
5548 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
5549
5550 setValue(V: &I, NewN: Result);
5551}
5552
5553/// GetSignificand - Get the significand and build it into a floating-point
5554/// number with exponent of 1:
5555///
5556/// Op = (Op & 0x007fffff) | 0x3f800000;
5557///
5558/// where Op is the hexadecimal representation of floating point value.
5559static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5560 SDValue t1 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: Op,
5561 N2: DAG.getConstant(Val: 0x007fffff, DL: dl, VT: MVT::i32));
5562 SDValue t2 = DAG.getNode(Opcode: ISD::OR, DL: dl, VT: MVT::i32, N1: t1,
5563 N2: DAG.getConstant(Val: 0x3f800000, DL: dl, VT: MVT::i32));
5564 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f32, Operand: t2);
5565}
5566
5567/// GetExponent - Get the exponent:
5568///
5569/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5570///
5571/// where Op is the hexadecimal representation of floating point value.
5572static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5573 const TargetLowering &TLI, const SDLoc &dl) {
5574 SDValue t0 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: Op,
5575 N2: DAG.getConstant(Val: 0x7f800000, DL: dl, VT: MVT::i32));
5576 SDValue t1 = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32, N1: t0,
5577 N2: DAG.getShiftAmountConstant(Val: 23, VT: MVT::i32, DL: dl));
5578 SDValue t2 = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32, N1: t1,
5579 N2: DAG.getConstant(Val: 127, DL: dl, VT: MVT::i32));
5580 return DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::f32, Operand: t2);
5581}
5582
5583/// getF32Constant - Get 32-bit floating point constant.
5584static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5585 const SDLoc &dl) {
5586 return DAG.getConstantFP(Val: APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), DL: dl,
5587 VT: MVT::f32);
5588}
5589
5590static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5591 SelectionDAG &DAG) {
5592 // TODO: What fast-math-flags should be set on the floating-point nodes?
5593
5594 // IntegerPartOfX = ((int32_t)(t0);
5595 SDValue IntegerPartOfX = DAG.getNode(Opcode: ISD::FP_TO_SINT, DL: dl, VT: MVT::i32, Operand: t0);
5596
5597 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
5598 SDValue t1 = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::f32, Operand: IntegerPartOfX);
5599 SDValue X = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t0, N2: t1);
5600
5601 // IntegerPartOfX <<= 23;
5602 IntegerPartOfX = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT: MVT::i32, N1: IntegerPartOfX,
5603 N2: DAG.getShiftAmountConstant(Val: 23, VT: MVT::i32, DL: dl));
5604
5605 SDValue TwoToFractionalPartOfX;
5606 if (LimitFloatPrecision <= 6) {
5607 // For floating-point precision of 6:
5608 //
5609 // TwoToFractionalPartOfX =
5610 // 0.997535578f +
5611 // (0.735607626f + 0.252464424f * x) * x;
5612 //
5613 // error 0.0144103317, which is 6 bits
5614 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5615 N2: getF32Constant(DAG, Flt: 0x3e814304, dl));
5616 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5617 N2: getF32Constant(DAG, Flt: 0x3f3c50c8, dl));
5618 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5619 TwoToFractionalPartOfX = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5620 N2: getF32Constant(DAG, Flt: 0x3f7f5e7e, dl));
5621 } else if (LimitFloatPrecision <= 12) {
5622 // For floating-point precision of 12:
5623 //
5624 // TwoToFractionalPartOfX =
5625 // 0.999892986f +
5626 // (0.696457318f +
5627 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
5628 //
5629 // error 0.000107046256, which is 13 to 14 bits
5630 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5631 N2: getF32Constant(DAG, Flt: 0x3da235e3, dl));
5632 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5633 N2: getF32Constant(DAG, Flt: 0x3e65b8f3, dl));
5634 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5635 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5636 N2: getF32Constant(DAG, Flt: 0x3f324b07, dl));
5637 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5638 TwoToFractionalPartOfX = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t6,
5639 N2: getF32Constant(DAG, Flt: 0x3f7ff8fd, dl));
5640 } else { // LimitFloatPrecision <= 18
5641 // For floating-point precision of 18:
5642 //
5643 // TwoToFractionalPartOfX =
5644 // 0.999999982f +
5645 // (0.693148872f +
5646 // (0.240227044f +
5647 // (0.554906021e-1f +
5648 // (0.961591928e-2f +
5649 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5650 // error 2.47208000*10^(-7), which is better than 18 bits
5651 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5652 N2: getF32Constant(DAG, Flt: 0x3924b03e, dl));
5653 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5654 N2: getF32Constant(DAG, Flt: 0x3ab24b87, dl));
5655 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5656 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5657 N2: getF32Constant(DAG, Flt: 0x3c1d8c17, dl));
5658 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5659 SDValue t7 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t6,
5660 N2: getF32Constant(DAG, Flt: 0x3d634a1d, dl));
5661 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
5662 SDValue t9 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t8,
5663 N2: getF32Constant(DAG, Flt: 0x3e75fe14, dl));
5664 SDValue t10 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t9, N2: X);
5665 SDValue t11 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t10,
5666 N2: getF32Constant(DAG, Flt: 0x3f317234, dl));
5667 SDValue t12 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t11, N2: X);
5668 TwoToFractionalPartOfX = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t12,
5669 N2: getF32Constant(DAG, Flt: 0x3f800000, dl));
5670 }
5671
5672 // Add the exponent into the result in integer domain.
5673 SDValue t13 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: TwoToFractionalPartOfX);
5674 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f32,
5675 Operand: DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: t13, N2: IntegerPartOfX));
5676}
5677
5678/// expandExp - Lower an exp intrinsic. Handles the special sequences for
5679/// limited-precision mode.
5680static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5681 const TargetLowering &TLI, SDNodeFlags Flags) {
5682 if (Op.getValueType() == MVT::f32 &&
5683 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5684
5685 // Put the exponent in the right bit position for later addition to the
5686 // final result:
5687 //
5688 // t0 = Op * log2(e)
5689
5690 // TODO: What fast-math-flags should be set here?
5691 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: Op,
5692 N2: DAG.getConstantFP(Val: numbers::log2ef, DL: dl, VT: MVT::f32));
5693 return getLimitedPrecisionExp2(t0, dl, DAG);
5694 }
5695
5696 // No special expansion.
5697 return DAG.getNode(Opcode: ISD::FEXP, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5698}
5699
5700/// expandLog - Lower a log intrinsic. Handles the special sequences for
5701/// limited-precision mode.
5702static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5703 const TargetLowering &TLI, SDNodeFlags Flags) {
5704 // TODO: What fast-math-flags should be set on the floating-point nodes?
5705
5706 if (Op.getValueType() == MVT::f32 &&
5707 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5708 SDValue Op1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Op);
5709
5710 // Scale the exponent by log(2).
5711 SDValue Exp = GetExponent(DAG, Op: Op1, TLI, dl);
5712 SDValue LogOfExponent =
5713 DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: Exp,
5714 N2: DAG.getConstantFP(Val: numbers::ln2f, DL: dl, VT: MVT::f32));
5715
5716 // Get the significand and build it into a floating-point number with
5717 // exponent of 1.
5718 SDValue X = GetSignificand(DAG, Op: Op1, dl);
5719
5720 SDValue LogOfMantissa;
5721 if (LimitFloatPrecision <= 6) {
5722 // For floating-point precision of 6:
5723 //
5724 // LogofMantissa =
5725 // -1.1609546f +
5726 // (1.4034025f - 0.23903021f * x) * x;
5727 //
5728 // error 0.0034276066, which is better than 8 bits
5729 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5730 N2: getF32Constant(DAG, Flt: 0xbe74c456, dl));
5731 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5732 N2: getF32Constant(DAG, Flt: 0x3fb3a2b1, dl));
5733 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5734 LogOfMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5735 N2: getF32Constant(DAG, Flt: 0x3f949a29, dl));
5736 } else if (LimitFloatPrecision <= 12) {
5737 // For floating-point precision of 12:
5738 //
5739 // LogOfMantissa =
5740 // -1.7417939f +
5741 // (2.8212026f +
5742 // (-1.4699568f +
5743 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5744 //
5745 // error 0.000061011436, which is 14 bits
5746 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5747 N2: getF32Constant(DAG, Flt: 0xbd67b6d6, dl));
5748 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5749 N2: getF32Constant(DAG, Flt: 0x3ee4f4b8, dl));
5750 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5751 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5752 N2: getF32Constant(DAG, Flt: 0x3fbc278b, dl));
5753 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5754 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5755 N2: getF32Constant(DAG, Flt: 0x40348e95, dl));
5756 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5757 LogOfMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5758 N2: getF32Constant(DAG, Flt: 0x3fdef31a, dl));
5759 } else { // LimitFloatPrecision <= 18
5760 // For floating-point precision of 18:
5761 //
5762 // LogOfMantissa =
5763 // -2.1072184f +
5764 // (4.2372794f +
5765 // (-3.7029485f +
5766 // (2.2781945f +
5767 // (-0.87823314f +
5768 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5769 //
5770 // error 0.0000023660568, which is better than 18 bits
5771 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5772 N2: getF32Constant(DAG, Flt: 0xbc91e5ac, dl));
5773 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5774 N2: getF32Constant(DAG, Flt: 0x3e4350aa, dl));
5775 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5776 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5777 N2: getF32Constant(DAG, Flt: 0x3f60d3e3, dl));
5778 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5779 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5780 N2: getF32Constant(DAG, Flt: 0x4011cdf0, dl));
5781 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5782 SDValue t7 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5783 N2: getF32Constant(DAG, Flt: 0x406cfd1c, dl));
5784 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
5785 SDValue t9 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t8,
5786 N2: getF32Constant(DAG, Flt: 0x408797cb, dl));
5787 SDValue t10 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t9, N2: X);
5788 LogOfMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t10,
5789 N2: getF32Constant(DAG, Flt: 0x4006dcab, dl));
5790 }
5791
5792 return DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: LogOfExponent, N2: LogOfMantissa);
5793 }
5794
5795 // No special expansion.
5796 return DAG.getNode(Opcode: ISD::FLOG, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5797}
5798
5799/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5800/// limited-precision mode.
5801static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5802 const TargetLowering &TLI, SDNodeFlags Flags) {
5803 // TODO: What fast-math-flags should be set on the floating-point nodes?
5804
5805 if (Op.getValueType() == MVT::f32 &&
5806 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5807 SDValue Op1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Op);
5808
5809 // Get the exponent.
5810 SDValue LogOfExponent = GetExponent(DAG, Op: Op1, TLI, dl);
5811
5812 // Get the significand and build it into a floating-point number with
5813 // exponent of 1.
5814 SDValue X = GetSignificand(DAG, Op: Op1, dl);
5815
5816 // Different possible minimax approximations of significand in
5817 // floating-point for various degrees of accuracy over [1,2].
5818 SDValue Log2ofMantissa;
5819 if (LimitFloatPrecision <= 6) {
5820 // For floating-point precision of 6:
5821 //
5822 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5823 //
5824 // error 0.0049451742, which is more than 7 bits
5825 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5826 N2: getF32Constant(DAG, Flt: 0xbeb08fe0, dl));
5827 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5828 N2: getF32Constant(DAG, Flt: 0x40019463, dl));
5829 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5830 Log2ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5831 N2: getF32Constant(DAG, Flt: 0x3fd6633d, dl));
5832 } else if (LimitFloatPrecision <= 12) {
5833 // For floating-point precision of 12:
5834 //
5835 // Log2ofMantissa =
5836 // -2.51285454f +
5837 // (4.07009056f +
5838 // (-2.12067489f +
5839 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5840 //
5841 // error 0.0000876136000, which is better than 13 bits
5842 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5843 N2: getF32Constant(DAG, Flt: 0xbda7262e, dl));
5844 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5845 N2: getF32Constant(DAG, Flt: 0x3f25280b, dl));
5846 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5847 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5848 N2: getF32Constant(DAG, Flt: 0x4007b923, dl));
5849 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5850 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5851 N2: getF32Constant(DAG, Flt: 0x40823e2f, dl));
5852 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5853 Log2ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5854 N2: getF32Constant(DAG, Flt: 0x4020d29c, dl));
5855 } else { // LimitFloatPrecision <= 18
5856 // For floating-point precision of 18:
5857 //
5858 // Log2ofMantissa =
5859 // -3.0400495f +
5860 // (6.1129976f +
5861 // (-5.3420409f +
5862 // (3.2865683f +
5863 // (-1.2669343f +
5864 // (0.27515199f -
5865 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5866 //
5867 // error 0.0000018516, which is better than 18 bits
5868 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5869 N2: getF32Constant(DAG, Flt: 0xbcd2769e, dl));
5870 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5871 N2: getF32Constant(DAG, Flt: 0x3e8ce0b9, dl));
5872 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5873 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5874 N2: getF32Constant(DAG, Flt: 0x3fa22ae7, dl));
5875 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5876 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5877 N2: getF32Constant(DAG, Flt: 0x40525723, dl));
5878 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5879 SDValue t7 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5880 N2: getF32Constant(DAG, Flt: 0x40aaf200, dl));
5881 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
5882 SDValue t9 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t8,
5883 N2: getF32Constant(DAG, Flt: 0x40c39dad, dl));
5884 SDValue t10 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t9, N2: X);
5885 Log2ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t10,
5886 N2: getF32Constant(DAG, Flt: 0x4042902c, dl));
5887 }
5888
5889 return DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: LogOfExponent, N2: Log2ofMantissa);
5890 }
5891
5892 // No special expansion.
5893 return DAG.getNode(Opcode: ISD::FLOG2, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5894}
5895
5896/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5897/// limited-precision mode.
5898static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5899 const TargetLowering &TLI, SDNodeFlags Flags) {
5900 // TODO: What fast-math-flags should be set on the floating-point nodes?
5901
5902 if (Op.getValueType() == MVT::f32 &&
5903 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5904 SDValue Op1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Op);
5905
5906 // Scale the exponent by log10(2) [0.30102999f].
5907 SDValue Exp = GetExponent(DAG, Op: Op1, TLI, dl);
5908 SDValue LogOfExponent = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: Exp,
5909 N2: getF32Constant(DAG, Flt: 0x3e9a209a, dl));
5910
5911 // Get the significand and build it into a floating-point number with
5912 // exponent of 1.
5913 SDValue X = GetSignificand(DAG, Op: Op1, dl);
5914
5915 SDValue Log10ofMantissa;
5916 if (LimitFloatPrecision <= 6) {
5917 // For floating-point precision of 6:
5918 //
5919 // Log10ofMantissa =
5920 // -0.50419619f +
5921 // (0.60948995f - 0.10380950f * x) * x;
5922 //
5923 // error 0.0014886165, which is 6 bits
5924 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5925 N2: getF32Constant(DAG, Flt: 0xbdd49a13, dl));
5926 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5927 N2: getF32Constant(DAG, Flt: 0x3f1c0789, dl));
5928 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5929 Log10ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5930 N2: getF32Constant(DAG, Flt: 0x3f011300, dl));
5931 } else if (LimitFloatPrecision <= 12) {
5932 // For floating-point precision of 12:
5933 //
5934 // Log10ofMantissa =
5935 // -0.64831180f +
5936 // (0.91751397f +
5937 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5938 //
5939 // error 0.00019228036, which is better than 12 bits
5940 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5941 N2: getF32Constant(DAG, Flt: 0x3d431f31, dl));
5942 SDValue t1 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t0,
5943 N2: getF32Constant(DAG, Flt: 0x3ea21fb2, dl));
5944 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5945 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5946 N2: getF32Constant(DAG, Flt: 0x3f6ae232, dl));
5947 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5948 Log10ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t4,
5949 N2: getF32Constant(DAG, Flt: 0x3f25f7c3, dl));
5950 } else { // LimitFloatPrecision <= 18
5951 // For floating-point precision of 18:
5952 //
5953 // Log10ofMantissa =
5954 // -0.84299375f +
5955 // (1.5327582f +
5956 // (-1.0688956f +
5957 // (0.49102474f +
5958 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5959 //
5960 // error 0.0000037995730, which is better than 18 bits
5961 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5962 N2: getF32Constant(DAG, Flt: 0x3c5d51ce, dl));
5963 SDValue t1 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t0,
5964 N2: getF32Constant(DAG, Flt: 0x3e00685a, dl));
5965 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5966 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5967 N2: getF32Constant(DAG, Flt: 0x3efb6798, dl));
5968 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5969 SDValue t5 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t4,
5970 N2: getF32Constant(DAG, Flt: 0x3f88d192, dl));
5971 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5972 SDValue t7 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t6,
5973 N2: getF32Constant(DAG, Flt: 0x3fc4316c, dl));
5974 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
5975 Log10ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t8,
5976 N2: getF32Constant(DAG, Flt: 0x3f57ce70, dl));
5977 }
5978
5979 return DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: LogOfExponent, N2: Log10ofMantissa);
5980 }
5981
5982 // No special expansion.
5983 return DAG.getNode(Opcode: ISD::FLOG10, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5984}
5985
5986/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5987/// limited-precision mode.
5988static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5989 const TargetLowering &TLI, SDNodeFlags Flags) {
5990 if (Op.getValueType() == MVT::f32 &&
5991 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5992 return getLimitedPrecisionExp2(t0: Op, dl, DAG);
5993
5994 // No special expansion.
5995 return DAG.getNode(Opcode: ISD::FEXP2, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5996}
5997
5998/// visitPow - Lower a pow intrinsic. Handles the special sequences for
5999/// limited-precision mode with x == 10.0f.
6000static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
6001 SelectionDAG &DAG, const TargetLowering &TLI,
6002 SDNodeFlags Flags) {
6003 bool IsExp10 = false;
6004 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
6005 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
6006 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(Val&: LHS)) {
6007 APFloat Ten(10.0f);
6008 IsExp10 = LHSC->isExactlyValue(V: Ten);
6009 }
6010 }
6011
6012 // TODO: What fast-math-flags should be set on the FMUL node?
6013 if (IsExp10) {
6014 // Put the exponent in the right bit position for later addition to the
6015 // final result:
6016 //
6017 // #define LOG2OF10 3.3219281f
6018 // t0 = Op * LOG2OF10;
6019 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: RHS,
6020 N2: getF32Constant(DAG, Flt: 0x40549a78, dl));
6021 return getLimitedPrecisionExp2(t0, dl, DAG);
6022 }
6023
6024 // No special expansion.
6025 return DAG.getNode(Opcode: ISD::FPOW, DL: dl, VT: LHS.getValueType(), N1: LHS, N2: RHS, Flags);
6026}
6027
6028/// ExpandPowI - Expand a llvm.powi intrinsic.
6029static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
6030 SelectionDAG &DAG) {
6031 // If RHS is a constant, we can expand this out to a multiplication tree if
6032 // it's beneficial on the target, otherwise we end up lowering to a call to
6033 // __powidf2 (for example).
6034 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Val&: RHS)) {
6035 unsigned Val = RHSC->getSExtValue();
6036
6037 // powi(x, 0) -> 1.0
6038 if (Val == 0)
6039 return DAG.getConstantFP(Val: 1.0, DL, VT: LHS.getValueType());
6040
6041 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
6042 Exponent: Val, OptForSize: DAG.shouldOptForSize())) {
6043 // Get the exponent as a positive value.
6044 if ((int)Val < 0)
6045 Val = -Val;
6046 // We use the simple binary decomposition method to generate the multiply
6047 // sequence. There are more optimal ways to do this (for example,
6048 // powi(x,15) generates one more multiply than it should), but this has
6049 // the benefit of being both really simple and much better than a libcall.
6050 SDValue Res; // Logically starts equal to 1.0
6051 SDValue CurSquare = LHS;
6052 // TODO: Intrinsics should have fast-math-flags that propagate to these
6053 // nodes.
6054 while (Val) {
6055 if (Val & 1) {
6056 if (Res.getNode())
6057 Res =
6058 DAG.getNode(Opcode: ISD::FMUL, DL, VT: Res.getValueType(), N1: Res, N2: CurSquare);
6059 else
6060 Res = CurSquare; // 1.0*CurSquare.
6061 }
6062
6063 CurSquare = DAG.getNode(Opcode: ISD::FMUL, DL, VT: CurSquare.getValueType(),
6064 N1: CurSquare, N2: CurSquare);
6065 Val >>= 1;
6066 }
6067
6068 // If the original was negative, invert the result, producing 1/(x*x*x).
6069 if (RHSC->getSExtValue() < 0)
6070 Res = DAG.getNode(Opcode: ISD::FDIV, DL, VT: LHS.getValueType(),
6071 N1: DAG.getConstantFP(Val: 1.0, DL, VT: LHS.getValueType()), N2: Res);
6072 return Res;
6073 }
6074 }
6075
6076 // Otherwise, expand to a libcall.
6077 return DAG.getNode(Opcode: ISD::FPOWI, DL, VT: LHS.getValueType(), N1: LHS, N2: RHS);
6078}
6079
6080static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
6081 SDValue LHS, SDValue RHS, SDValue Scale,
6082 SelectionDAG &DAG, const TargetLowering &TLI) {
6083 EVT VT = LHS.getValueType();
6084 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
6085 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
6086 LLVMContext &Ctx = *DAG.getContext();
6087
6088 // If the type is legal but the operation isn't, this node might survive all
6089 // the way to operation legalization. If we end up there and we do not have
6090 // the ability to widen the type (if VT*2 is not legal), we cannot expand the
6091 // node.
6092
6093 // Coax the legalizer into expanding the node during type legalization instead
6094 // by bumping the size by one bit. This will force it to Promote, enabling the
6095 // early expansion and avoiding the need to expand later.
6096
6097 // We don't have to do this if Scale is 0; that can always be expanded, unless
6098 // it's a saturating signed operation. Those can experience true integer
6099 // division overflow, a case which we must avoid.
6100
6101 // FIXME: We wouldn't have to do this (or any of the early
6102 // expansion/promotion) if it was possible to expand a libcall of an
6103 // illegal type during operation legalization. But it's not, so things
6104 // get a bit hacky.
6105 unsigned ScaleInt = Scale->getAsZExtVal();
6106 if ((ScaleInt > 0 || (Saturating && Signed)) &&
6107 (TLI.isTypeLegal(VT) ||
6108 (VT.isVector() && TLI.isTypeLegal(VT: VT.getVectorElementType())))) {
6109 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
6110 Op: Opcode, VT, Scale: ScaleInt);
6111 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
6112 EVT PromVT;
6113 if (VT.isScalarInteger())
6114 PromVT = EVT::getIntegerVT(Context&: Ctx, BitWidth: VT.getSizeInBits() + 1);
6115 else if (VT.isVector()) {
6116 PromVT = VT.getVectorElementType();
6117 PromVT = EVT::getIntegerVT(Context&: Ctx, BitWidth: PromVT.getSizeInBits() + 1);
6118 PromVT = EVT::getVectorVT(Context&: Ctx, VT: PromVT, EC: VT.getVectorElementCount());
6119 } else
6120 llvm_unreachable("Wrong VT for DIVFIX?");
6121 LHS = DAG.getExtOrTrunc(IsSigned: Signed, Op: LHS, DL, VT: PromVT);
6122 RHS = DAG.getExtOrTrunc(IsSigned: Signed, Op: RHS, DL, VT: PromVT);
6123 EVT ShiftTy = TLI.getShiftAmountTy(LHSTy: PromVT, DL: DAG.getDataLayout());
6124 // For saturating operations, we need to shift up the LHS to get the
6125 // proper saturation width, and then shift down again afterwards.
6126 if (Saturating)
6127 LHS = DAG.getNode(Opcode: ISD::SHL, DL, VT: PromVT, N1: LHS,
6128 N2: DAG.getConstant(Val: 1, DL, VT: ShiftTy));
6129 SDValue Res = DAG.getNode(Opcode, DL, VT: PromVT, N1: LHS, N2: RHS, N3: Scale);
6130 if (Saturating)
6131 Res = DAG.getNode(Opcode: Signed ? ISD::SRA : ISD::SRL, DL, VT: PromVT, N1: Res,
6132 N2: DAG.getConstant(Val: 1, DL, VT: ShiftTy));
6133 return DAG.getZExtOrTrunc(Op: Res, DL, VT);
6134 }
6135 }
6136
6137 return DAG.getNode(Opcode, DL, VT, N1: LHS, N2: RHS, N3: Scale);
6138}
6139
6140// getUnderlyingArgRegs - Find underlying registers used for a truncated,
6141// bitcasted, or split argument. Returns a list of <Register, size in bits>
6142static void
6143getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
6144 const SDValue &N) {
6145 switch (N.getOpcode()) {
6146 case ISD::CopyFromReg: {
6147 SDValue Op = N.getOperand(i: 1);
6148 Regs.emplace_back(Args: cast<RegisterSDNode>(Val&: Op)->getReg(),
6149 Args: Op.getValueType().getSizeInBits());
6150 return;
6151 }
6152 case ISD::BITCAST:
6153 case ISD::AssertZext:
6154 case ISD::AssertSext:
6155 case ISD::TRUNCATE:
6156 getUnderlyingArgRegs(Regs, N: N.getOperand(i: 0));
6157 return;
6158 case ISD::BUILD_PAIR:
6159 case ISD::BUILD_VECTOR:
6160 case ISD::CONCAT_VECTORS:
6161 for (SDValue Op : N->op_values())
6162 getUnderlyingArgRegs(Regs, N: Op);
6163 return;
6164 default:
6165 return;
6166 }
6167}
6168
6169/// If the DbgValueInst is a dbg_value of a function argument, create the
6170/// corresponding DBG_VALUE machine instruction for it now. At the end of
6171/// instruction selection, they will be inserted to the entry BB.
6172/// We don't currently support this for variadic dbg_values, as they shouldn't
6173/// appear for function arguments or in the prologue.
6174bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6175 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6176 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6177 const Argument *Arg = dyn_cast<Argument>(Val: V);
6178 if (!Arg)
6179 return false;
6180
6181 MachineFunction &MF = DAG.getMachineFunction();
6182 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6183
6184 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6185 // we've been asked to pursue.
6186 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6187 bool Indirect) {
6188 if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6189 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6190 // pointing at the VReg, which will be patched up later.
6191 auto &Inst = TII->get(Opcode: TargetOpcode::DBG_INSTR_REF);
6192 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
6193 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6194 /* isKill */ false, /* isDead */ false,
6195 /* isUndef */ false, /* isEarlyClobber */ false,
6196 /* SubReg */ 0, /* isDebug */ true)});
6197
6198 auto *NewDIExpr = FragExpr;
6199 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6200 // the DIExpression.
6201 if (Indirect)
6202 NewDIExpr = DIExpression::prepend(Expr: FragExpr, Flags: DIExpression::DerefBefore);
6203 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6204 NewDIExpr = DIExpression::prependOpcodes(Expr: NewDIExpr, Ops);
6205 return BuildMI(MF, DL, MCID: Inst, IsIndirect: false, MOs, Variable, Expr: NewDIExpr);
6206 } else {
6207 // Create a completely standard DBG_VALUE.
6208 auto &Inst = TII->get(Opcode: TargetOpcode::DBG_VALUE);
6209 return BuildMI(MF, DL, MCID: Inst, IsIndirect: Indirect, Reg, Variable, Expr: FragExpr);
6210 }
6211 };
6212
6213 if (Kind == FuncArgumentDbgValueKind::Value) {
6214 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6215 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6216 // the entry block.
6217 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6218 if (!IsInEntryBlock)
6219 return false;
6220
6221 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6222 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6223 // variable that also is a param.
6224 //
6225 // Although, if we are at the top of the entry block already, we can still
6226 // emit using ArgDbgValue. This might catch some situations when the
6227 // dbg.value refers to an argument that isn't used in the entry block, so
6228 // any CopyToReg node would be optimized out and the only way to express
6229 // this DBG_VALUE is by using the physical reg (or FI) as done in this
6230 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
6231 // we should only emit as ArgDbgValue if the Variable is an argument to the
6232 // current function, and the dbg.value intrinsic is found in the entry
6233 // block.
6234 bool VariableIsFunctionInputArg = Variable->isParameter() &&
6235 !DL->getInlinedAt();
6236 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6237 if (!IsInPrologue && !VariableIsFunctionInputArg)
6238 return false;
6239
6240 // Here we assume that a function argument on IR level only can be used to
6241 // describe one input parameter on source level. If we for example have
6242 // source code like this
6243 //
6244 // struct A { long x, y; };
6245 // void foo(struct A a, long b) {
6246 // ...
6247 // b = a.x;
6248 // ...
6249 // }
6250 //
6251 // and IR like this
6252 //
6253 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
6254 // entry:
6255 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6256 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6257 // call void @llvm.dbg.value(metadata i32 %b, "b",
6258 // ...
6259 // call void @llvm.dbg.value(metadata i32 %a1, "b"
6260 // ...
6261 //
6262 // then the last dbg.value is describing a parameter "b" using a value that
6263 // is an argument. But since we already has used %a1 to describe a parameter
6264 // we should not handle that last dbg.value here (that would result in an
6265 // incorrect hoisting of the DBG_VALUE to the function entry).
6266 // Notice that we allow one dbg.value per IR level argument, to accommodate
6267 // for the situation with fragments above.
6268 // If there is no node for the value being handled, we return true to skip
6269 // the normal generation of debug info, as it would kill existing debug
6270 // info for the parameter in case of duplicates.
6271 if (VariableIsFunctionInputArg) {
6272 unsigned ArgNo = Arg->getArgNo();
6273 if (ArgNo >= FuncInfo.DescribedArgs.size())
6274 FuncInfo.DescribedArgs.resize(N: ArgNo + 1, t: false);
6275 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(Idx: ArgNo))
6276 return !NodeMap[V].getNode();
6277 FuncInfo.DescribedArgs.set(ArgNo);
6278 }
6279 }
6280
6281 bool IsIndirect = false;
6282 std::optional<MachineOperand> Op;
6283 // Some arguments' frame index is recorded during argument lowering.
6284 int FI = FuncInfo.getArgumentFrameIndex(A: Arg);
6285 if (FI != std::numeric_limits<int>::max())
6286 Op = MachineOperand::CreateFI(Idx: FI);
6287
6288 SmallVector<std::pair<Register, TypeSize>, 8> ArgRegsAndSizes;
6289 if (!Op && N.getNode()) {
6290 getUnderlyingArgRegs(Regs&: ArgRegsAndSizes, N);
6291 Register Reg;
6292 if (ArgRegsAndSizes.size() == 1)
6293 Reg = ArgRegsAndSizes.front().first;
6294
6295 if (Reg && Reg.isVirtual()) {
6296 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6297 Register PR = RegInfo.getLiveInPhysReg(VReg: Reg);
6298 if (PR)
6299 Reg = PR;
6300 }
6301 if (Reg) {
6302 Op = MachineOperand::CreateReg(Reg, isDef: false);
6303 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6304 }
6305 }
6306
6307 if (!Op && N.getNode()) {
6308 // Check if frame index is available.
6309 SDValue LCandidate = peekThroughBitcasts(V: N);
6310 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(Val: LCandidate.getNode()))
6311 if (FrameIndexSDNode *FINode =
6312 dyn_cast<FrameIndexSDNode>(Val: LNode->getBasePtr().getNode()))
6313 Op = MachineOperand::CreateFI(Idx: FINode->getIndex());
6314 }
6315
6316 if (!Op) {
6317 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6318 auto splitMultiRegDbgValue =
6319 [&](ArrayRef<std::pair<Register, TypeSize>> SplitRegs) -> bool {
6320 unsigned Offset = 0;
6321 for (const auto &[Reg, RegSizeInBits] : SplitRegs) {
6322 // FIXME: Scalable sizes are not supported in fragment expressions.
6323 if (RegSizeInBits.isScalable())
6324 return false;
6325
6326 // If the expression is already a fragment, the current register
6327 // offset+size might extend beyond the fragment. In this case, only
6328 // the register bits that are inside the fragment are relevant.
6329 int RegFragmentSizeInBits = RegSizeInBits.getFixedValue();
6330 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6331 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6332 // The register is entirely outside the expression fragment,
6333 // so is irrelevant for debug info.
6334 if (Offset >= ExprFragmentSizeInBits)
6335 break;
6336 // The register is partially outside the expression fragment, only
6337 // the low bits within the fragment are relevant for debug info.
6338 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6339 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6340 }
6341 }
6342
6343 auto FragmentExpr = DIExpression::createFragmentExpression(
6344 Expr, OffsetInBits: Offset, SizeInBits: RegFragmentSizeInBits);
6345 Offset += RegSizeInBits.getFixedValue();
6346 // If a valid fragment expression cannot be created, the variable's
6347 // correct value cannot be determined and so it is set as poison.
6348 if (!FragmentExpr) {
6349 SDDbgValue *SDV = DAG.getConstantDbgValue(
6350 Var: Variable, Expr, C: PoisonValue::get(T: V->getType()), DL, O: SDNodeOrder);
6351 DAG.AddDbgValue(DB: SDV, isParameter: false);
6352 continue;
6353 }
6354 MachineInstr *NewMI = MakeVRegDbgValue(
6355 Reg, *FragmentExpr, Kind != FuncArgumentDbgValueKind::Value);
6356 FuncInfo.ArgDbgValues.push_back(Elt: NewMI);
6357 }
6358
6359 return true;
6360 };
6361
6362 // Check if ValueMap has reg number.
6363 DenseMap<const Value *, Register>::const_iterator
6364 VMI = FuncInfo.ValueMap.find(Val: V);
6365 if (VMI != FuncInfo.ValueMap.end()) {
6366 const auto &TLI = DAG.getTargetLoweringInfo();
6367 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6368 V->getType(), std::nullopt);
6369 if (RFV.occupiesMultipleRegs())
6370 return splitMultiRegDbgValue(RFV.getRegsAndSizes());
6371
6372 Op = MachineOperand::CreateReg(Reg: VMI->second, isDef: false);
6373 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6374 } else if (ArgRegsAndSizes.size() > 1) {
6375 // This was split due to the calling convention, and no virtual register
6376 // mapping exists for the value.
6377 return splitMultiRegDbgValue(ArgRegsAndSizes);
6378 }
6379 }
6380
6381 if (!Op)
6382 return false;
6383
6384 assert(Variable->isValidLocationForIntrinsic(DL) &&
6385 "Expected inlined-at fields to agree");
6386 MachineInstr *NewMI = nullptr;
6387
6388 if (Op->isReg())
6389 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6390 else
6391 NewMI = BuildMI(MF, DL, MCID: TII->get(Opcode: TargetOpcode::DBG_VALUE), IsIndirect: true, MOs: *Op,
6392 Variable, Expr);
6393
6394 // Otherwise, use ArgDbgValues.
6395 FuncInfo.ArgDbgValues.push_back(Elt: NewMI);
6396 return true;
6397}
6398
6399/// Return the appropriate SDDbgValue based on N.
6400SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6401 DILocalVariable *Variable,
6402 DIExpression *Expr,
6403 const DebugLoc &dl,
6404 unsigned DbgSDNodeOrder) {
6405 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Val: N.getNode())) {
6406 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6407 // stack slot locations.
6408 //
6409 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6410 // debug values here after optimization:
6411 //
6412 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
6413 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6414 //
6415 // Both describe the direct values of their associated variables.
6416 return DAG.getFrameIndexDbgValue(Var: Variable, Expr, FI: FISDN->getIndex(),
6417 /*IsIndirect*/ false, DL: dl, O: DbgSDNodeOrder);
6418 }
6419 return DAG.getDbgValue(Var: Variable, Expr, N: N.getNode(), R: N.getResNo(),
6420 /*IsIndirect*/ false, DL: dl, O: DbgSDNodeOrder);
6421}
6422
6423static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6424 switch (Intrinsic) {
6425 case Intrinsic::smul_fix:
6426 return ISD::SMULFIX;
6427 case Intrinsic::umul_fix:
6428 return ISD::UMULFIX;
6429 case Intrinsic::smul_fix_sat:
6430 return ISD::SMULFIXSAT;
6431 case Intrinsic::umul_fix_sat:
6432 return ISD::UMULFIXSAT;
6433 case Intrinsic::sdiv_fix:
6434 return ISD::SDIVFIX;
6435 case Intrinsic::udiv_fix:
6436 return ISD::UDIVFIX;
6437 case Intrinsic::sdiv_fix_sat:
6438 return ISD::SDIVFIXSAT;
6439 case Intrinsic::udiv_fix_sat:
6440 return ISD::UDIVFIXSAT;
6441 default:
6442 llvm_unreachable("Unhandled fixed point intrinsic");
6443 }
6444}
6445
6446/// Given a @llvm.call.preallocated.setup, return the corresponding
6447/// preallocated call.
6448static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6449 assert(cast<CallBase>(PreallocatedSetup)
6450 ->getCalledFunction()
6451 ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6452 "expected call_preallocated_setup Value");
6453 for (const auto *U : PreallocatedSetup->users()) {
6454 auto *UseCall = cast<CallBase>(Val: U);
6455 const Function *Fn = UseCall->getCalledFunction();
6456 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6457 return UseCall;
6458 }
6459 }
6460 llvm_unreachable("expected corresponding call to preallocated setup/arg");
6461}
6462
6463/// If DI is a debug value with an EntryValue expression, lower it using the
6464/// corresponding physical register of the associated Argument value
6465/// (guaranteed to exist by the verifier).
6466bool SelectionDAGBuilder::visitEntryValueDbgValue(
6467 ArrayRef<const Value *> Values, DILocalVariable *Variable,
6468 DIExpression *Expr, DebugLoc DbgLoc) {
6469 if (!Expr->isEntryValue() || !hasSingleElement(C&: Values))
6470 return false;
6471
6472 // These properties are guaranteed by the verifier.
6473 const Argument *Arg = cast<Argument>(Val: Values[0]);
6474 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6475
6476 auto ArgIt = FuncInfo.ValueMap.find(Val: Arg);
6477 if (ArgIt == FuncInfo.ValueMap.end()) {
6478 LLVM_DEBUG(
6479 dbgs() << "Dropping dbg.value: expression is entry_value but "
6480 "couldn't find an associated register for the Argument\n");
6481 return true;
6482 }
6483 Register ArgVReg = ArgIt->getSecond();
6484
6485 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6486 if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6487 SDDbgValue *SDV = DAG.getVRegDbgValue(
6488 Var: Variable, Expr, VReg: PhysReg, IsIndirect: false /*IsIndidrect*/, DL: DbgLoc, O: SDNodeOrder);
6489 DAG.AddDbgValue(DB: SDV, isParameter: false /*treat as dbg.declare byval parameter*/);
6490 return true;
6491 }
6492 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6493 "couldn't find a physical register\n");
6494 return true;
6495}
6496
6497/// Lower the call to the specified intrinsic function.
6498void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6499 unsigned Intrinsic) {
6500 SDLoc sdl = getCurSDLoc();
6501 switch (Intrinsic) {
6502 case Intrinsic::experimental_convergence_anchor:
6503 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERGENCECTRL_ANCHOR, DL: sdl, VT: MVT::Untyped));
6504 break;
6505 case Intrinsic::experimental_convergence_entry:
6506 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERGENCECTRL_ENTRY, DL: sdl, VT: MVT::Untyped));
6507 break;
6508 case Intrinsic::experimental_convergence_loop: {
6509 auto Bundle = I.getOperandBundle(ID: LLVMContext::OB_convergencectrl);
6510 auto *Token = Bundle->Inputs[0].get();
6511 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERGENCECTRL_LOOP, DL: sdl, VT: MVT::Untyped,
6512 Operand: getValue(V: Token)));
6513 break;
6514 }
6515 }
6516}
6517
6518void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6519 unsigned IntrinsicID) {
6520 // For now, we're only lowering an 'add' histogram.
6521 // We can add others later, e.g. saturating adds, min/max.
6522 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6523 "Tried to lower unsupported histogram type");
6524 SDLoc sdl = getCurSDLoc();
6525 Value *Ptr = I.getOperand(i_nocapture: 0);
6526 SDValue Inc = getValue(V: I.getOperand(i_nocapture: 1));
6527 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 2));
6528
6529 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6530 DataLayout TargetDL = DAG.getDataLayout();
6531 EVT VT = Inc.getValueType();
6532 Align Alignment = DAG.getEVTAlign(MemoryVT: VT);
6533
6534 const MDNode *Ranges = getRangeMetadata(I);
6535
6536 SDValue Root = DAG.getRoot();
6537 SDValue Base;
6538 SDValue Index;
6539 SDValue Scale;
6540 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, SDB: this,
6541 CurBB: I.getParent(), ElemSize: VT.getScalarStoreSize());
6542
6543 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6544
6545 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6546 PtrInfo: MachinePointerInfo(AS),
6547 F: MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6548 Size: MemoryLocation::UnknownSize, BaseAlignment: Alignment, AAInfo: I.getAAMetadata(), Ranges);
6549
6550 if (!UniformBase) {
6551 Base = DAG.getConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
6552 Index = getValue(V: Ptr);
6553 Scale =
6554 DAG.getTargetConstant(Val: 1, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
6555 }
6556
6557 EVT IdxVT = Index.getValueType();
6558
6559 // Avoid using e.g. i32 as index type when the increment must be performed
6560 // on i64's.
6561 bool MustExtendIndex = VT.getScalarSizeInBits() > IdxVT.getScalarSizeInBits();
6562 EVT EltTy = MustExtendIndex ? VT : IdxVT.getVectorElementType();
6563 if (MustExtendIndex || TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
6564 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
6565 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: sdl, VT: NewIdxVT, Operand: Index);
6566 }
6567
6568 SDValue ID = DAG.getTargetConstant(Val: IntrinsicID, DL: sdl, VT: MVT::i32);
6569
6570 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6571 SDValue Histogram = DAG.getMaskedHistogram(VTs: DAG.getVTList(VT: MVT::Other), MemVT: VT, dl: sdl,
6572 Ops, MMO, IndexType: ISD::SIGNED_SCALED);
6573
6574 setValue(V: &I, NewN: Histogram);
6575 DAG.setRoot(Histogram);
6576}
6577
6578void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6579 unsigned Intrinsic) {
6580 assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6581 "Tried lowering invalid vector extract last");
6582 SDLoc sdl = getCurSDLoc();
6583 const DataLayout &Layout = DAG.getDataLayout();
6584 SDValue Data = getValue(V: I.getOperand(i_nocapture: 0));
6585 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 1));
6586
6587 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6588 EVT ResVT = TLI.getValueType(DL: Layout, Ty: I.getType());
6589
6590 EVT ExtVT = TLI.getVectorIdxTy(DL: Layout);
6591 SDValue Idx = DAG.getNode(Opcode: ISD::VECTOR_FIND_LAST_ACTIVE, DL: sdl, VT: ExtVT, Operand: Mask);
6592 SDValue Result = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: sdl, VT: ResVT, N1: Data, N2: Idx);
6593
6594 Value *Default = I.getOperand(i_nocapture: 2);
6595 if (!isa<PoisonValue>(Val: Default) && !isa<UndefValue>(Val: Default)) {
6596 SDValue PassThru = getValue(V: Default);
6597 EVT BoolVT = Mask.getValueType().getScalarType();
6598 SDValue AnyActive = DAG.getNode(Opcode: ISD::VECREDUCE_OR, DL: sdl, VT: BoolVT, Operand: Mask);
6599 Result = DAG.getSelect(DL: sdl, VT: ResVT, Cond: AnyActive, LHS: Result, RHS: PassThru);
6600 }
6601
6602 setValue(V: &I, NewN: Result);
6603}
6604
6605/// Lower the call to the specified intrinsic function.
6606void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6607 unsigned Intrinsic) {
6608 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6609 SDLoc sdl = getCurSDLoc();
6610 DebugLoc dl = getCurDebugLoc();
6611 SDValue Res;
6612
6613 SDNodeFlags Flags;
6614 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
6615 Flags.copyFMF(FPMO: *FPOp);
6616
6617 switch (Intrinsic) {
6618 default:
6619 // By default, turn this into a target intrinsic node.
6620 visitTargetIntrinsic(I, Intrinsic);
6621 return;
6622 case Intrinsic::vscale: {
6623 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
6624 setValue(V: &I, NewN: DAG.getVScale(DL: sdl, VT, MulImm: APInt(VT.getSizeInBits(), 1)));
6625 return;
6626 }
6627 case Intrinsic::vastart: visitVAStart(I); return;
6628 case Intrinsic::vaend: visitVAEnd(I); return;
6629 case Intrinsic::vacopy: visitVACopy(I); return;
6630 case Intrinsic::returnaddress:
6631 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::RETURNADDR, DL: sdl,
6632 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
6633 Operand: getValue(V: I.getArgOperand(i: 0))));
6634 return;
6635 case Intrinsic::addressofreturnaddress:
6636 setValue(V: &I,
6637 NewN: DAG.getNode(Opcode: ISD::ADDROFRETURNADDR, DL: sdl,
6638 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType())));
6639 return;
6640 case Intrinsic::sponentry:
6641 setValue(V: &I,
6642 NewN: DAG.getNode(Opcode: ISD::SPONENTRY, DL: sdl,
6643 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType())));
6644 return;
6645 case Intrinsic::frameaddress:
6646 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FRAMEADDR, DL: sdl,
6647 VT: TLI.getFrameIndexTy(DL: DAG.getDataLayout()),
6648 Operand: getValue(V: I.getArgOperand(i: 0))));
6649 return;
6650 case Intrinsic::read_volatile_register:
6651 case Intrinsic::read_register: {
6652 Value *Reg = I.getArgOperand(i: 0);
6653 SDValue Chain = getRoot();
6654 SDValue RegName =
6655 DAG.getMDNode(MD: cast<MDNode>(Val: cast<MetadataAsValue>(Val: Reg)->getMetadata()));
6656 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
6657 Res = DAG.getNode(Opcode: ISD::READ_REGISTER, DL: sdl,
6658 VTList: DAG.getVTList(VT1: VT, VT2: MVT::Other), N1: Chain, N2: RegName);
6659 setValue(V: &I, NewN: Res);
6660 DAG.setRoot(Res.getValue(R: 1));
6661 return;
6662 }
6663 case Intrinsic::write_register: {
6664 Value *Reg = I.getArgOperand(i: 0);
6665 Value *RegValue = I.getArgOperand(i: 1);
6666 SDValue Chain = getRoot();
6667 SDValue RegName =
6668 DAG.getMDNode(MD: cast<MDNode>(Val: cast<MetadataAsValue>(Val: Reg)->getMetadata()));
6669 DAG.setRoot(DAG.getNode(Opcode: ISD::WRITE_REGISTER, DL: sdl, VT: MVT::Other, N1: Chain,
6670 N2: RegName, N3: getValue(V: RegValue)));
6671 return;
6672 }
6673 case Intrinsic::memcpy:
6674 case Intrinsic::memcpy_inline: {
6675 const auto &MCI = cast<MemCpyInst>(Val: I);
6676 SDValue Dst = getValue(V: I.getArgOperand(i: 0));
6677 SDValue Src = getValue(V: I.getArgOperand(i: 1));
6678 SDValue Size = getValue(V: I.getArgOperand(i: 2));
6679 assert((!MCI.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6680 "memcpy_inline needs constant size");
6681 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6682 Align DstAlign = MCI.getDestAlign().valueOrOne();
6683 Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6684 Align Alignment = std::min(a: DstAlign, b: SrcAlign);
6685 bool isVol = MCI.isVolatile();
6686 // FIXME: Support passing different dest/src alignments to the memcpy DAG
6687 // node.
6688 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6689 SDValue MC = DAG.getMemcpy(Chain: Root, dl: sdl, Dst, Src, Size, Alignment, isVol,
6690 AlwaysInline: MCI.isForceInlined(), CI: &I, OverrideTailCall: std::nullopt,
6691 DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
6692 SrcPtrInfo: MachinePointerInfo(I.getArgOperand(i: 1)),
6693 AAInfo: I.getAAMetadata(), BatchAA);
6694 updateDAGForMaybeTailCall(MaybeTC: MC);
6695 return;
6696 }
6697 case Intrinsic::memset:
6698 case Intrinsic::memset_inline: {
6699 const auto &MSII = cast<MemSetInst>(Val: I);
6700 SDValue Dst = getValue(V: I.getArgOperand(i: 0));
6701 SDValue Value = getValue(V: I.getArgOperand(i: 1));
6702 SDValue Size = getValue(V: I.getArgOperand(i: 2));
6703 assert((!MSII.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6704 "memset_inline needs constant size");
6705 // @llvm.memset defines 0 and 1 to both mean no alignment.
6706 Align DstAlign = MSII.getDestAlign().valueOrOne();
6707 bool isVol = MSII.isVolatile();
6708 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6709 SDValue MC = DAG.getMemset(
6710 Chain: Root, dl: sdl, Dst, Src: Value, Size, Alignment: DstAlign, isVol, AlwaysInline: MSII.isForceInlined(),
6711 CI: &I, DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)), AAInfo: I.getAAMetadata());
6712 updateDAGForMaybeTailCall(MaybeTC: MC);
6713 return;
6714 }
6715 case Intrinsic::memmove: {
6716 const auto &MMI = cast<MemMoveInst>(Val: I);
6717 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
6718 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
6719 SDValue Op3 = getValue(V: I.getArgOperand(i: 2));
6720 // @llvm.memmove defines 0 and 1 to both mean no alignment.
6721 Align DstAlign = MMI.getDestAlign().valueOrOne();
6722 Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6723 Align Alignment = std::min(a: DstAlign, b: SrcAlign);
6724 bool isVol = MMI.isVolatile();
6725 // FIXME: Support passing different dest/src alignments to the memmove DAG
6726 // node.
6727 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6728 SDValue MM = DAG.getMemmove(Chain: Root, dl: sdl, Dst: Op1, Src: Op2, Size: Op3, Alignment, isVol, CI: &I,
6729 /* OverrideTailCall */ std::nullopt,
6730 DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
6731 SrcPtrInfo: MachinePointerInfo(I.getArgOperand(i: 1)),
6732 AAInfo: I.getAAMetadata(), BatchAA);
6733 updateDAGForMaybeTailCall(MaybeTC: MM);
6734 return;
6735 }
6736 case Intrinsic::memcpy_element_unordered_atomic: {
6737 auto &MI = cast<AnyMemCpyInst>(Val: I);
6738 SDValue Dst = getValue(V: MI.getRawDest());
6739 SDValue Src = getValue(V: MI.getRawSource());
6740 SDValue Length = getValue(V: MI.getLength());
6741
6742 Type *LengthTy = MI.getLength()->getType();
6743 unsigned ElemSz = MI.getElementSizeInBytes();
6744 bool isTC = I.isTailCall() && isInTailCallPosition(Call: I, TM: DAG.getTarget());
6745 SDValue MC =
6746 DAG.getAtomicMemcpy(Chain: getRoot(), dl: sdl, Dst, Src, Size: Length, SizeTy: LengthTy, ElemSz,
6747 isTailCall: isTC, DstPtrInfo: MachinePointerInfo(MI.getRawDest()),
6748 SrcPtrInfo: MachinePointerInfo(MI.getRawSource()));
6749 updateDAGForMaybeTailCall(MaybeTC: MC);
6750 return;
6751 }
6752 case Intrinsic::memmove_element_unordered_atomic: {
6753 auto &MI = cast<AnyMemMoveInst>(Val: I);
6754 SDValue Dst = getValue(V: MI.getRawDest());
6755 SDValue Src = getValue(V: MI.getRawSource());
6756 SDValue Length = getValue(V: MI.getLength());
6757
6758 Type *LengthTy = MI.getLength()->getType();
6759 unsigned ElemSz = MI.getElementSizeInBytes();
6760 bool isTC = I.isTailCall() && isInTailCallPosition(Call: I, TM: DAG.getTarget());
6761 SDValue MC =
6762 DAG.getAtomicMemmove(Chain: getRoot(), dl: sdl, Dst, Src, Size: Length, SizeTy: LengthTy, ElemSz,
6763 isTailCall: isTC, DstPtrInfo: MachinePointerInfo(MI.getRawDest()),
6764 SrcPtrInfo: MachinePointerInfo(MI.getRawSource()));
6765 updateDAGForMaybeTailCall(MaybeTC: MC);
6766 return;
6767 }
6768 case Intrinsic::memset_element_unordered_atomic: {
6769 auto &MI = cast<AnyMemSetInst>(Val: I);
6770 SDValue Dst = getValue(V: MI.getRawDest());
6771 SDValue Val = getValue(V: MI.getValue());
6772 SDValue Length = getValue(V: MI.getLength());
6773
6774 Type *LengthTy = MI.getLength()->getType();
6775 unsigned ElemSz = MI.getElementSizeInBytes();
6776 bool isTC = I.isTailCall() && isInTailCallPosition(Call: I, TM: DAG.getTarget());
6777 SDValue MC =
6778 DAG.getAtomicMemset(Chain: getRoot(), dl: sdl, Dst, Value: Val, Size: Length, SizeTy: LengthTy, ElemSz,
6779 isTailCall: isTC, DstPtrInfo: MachinePointerInfo(MI.getRawDest()));
6780 updateDAGForMaybeTailCall(MaybeTC: MC);
6781 return;
6782 }
6783 case Intrinsic::call_preallocated_setup: {
6784 const CallBase *PreallocatedCall = FindPreallocatedCall(PreallocatedSetup: &I);
6785 SDValue SrcValue = DAG.getSrcValue(v: PreallocatedCall);
6786 SDValue Res = DAG.getNode(Opcode: ISD::PREALLOCATED_SETUP, DL: sdl, VT: MVT::Other,
6787 N1: getRoot(), N2: SrcValue);
6788 setValue(V: &I, NewN: Res);
6789 DAG.setRoot(Res);
6790 return;
6791 }
6792 case Intrinsic::call_preallocated_arg: {
6793 const CallBase *PreallocatedCall = FindPreallocatedCall(PreallocatedSetup: I.getOperand(i_nocapture: 0));
6794 SDValue SrcValue = DAG.getSrcValue(v: PreallocatedCall);
6795 SDValue Ops[3];
6796 Ops[0] = getRoot();
6797 Ops[1] = SrcValue;
6798 Ops[2] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 1)), DL: sdl,
6799 VT: MVT::i32); // arg index
6800 SDValue Res = DAG.getNode(
6801 Opcode: ISD::PREALLOCATED_ARG, DL: sdl,
6802 VTList: DAG.getVTList(VT1: TLI.getPointerTy(DL: DAG.getDataLayout()), VT2: MVT::Other), Ops);
6803 setValue(V: &I, NewN: Res);
6804 DAG.setRoot(Res.getValue(R: 1));
6805 return;
6806 }
6807
6808 case Intrinsic::eh_typeid_for: {
6809 // Find the type id for the given typeinfo.
6810 GlobalValue *GV = ExtractTypeInfo(V: I.getArgOperand(i: 0));
6811 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(TI: GV);
6812 Res = DAG.getConstant(Val: TypeID, DL: sdl, VT: MVT::i32);
6813 setValue(V: &I, NewN: Res);
6814 return;
6815 }
6816
6817 case Intrinsic::eh_return_i32:
6818 case Intrinsic::eh_return_i64:
6819 DAG.getMachineFunction().setCallsEHReturn(true);
6820 DAG.setRoot(DAG.getNode(Opcode: ISD::EH_RETURN, DL: sdl,
6821 VT: MVT::Other,
6822 N1: getControlRoot(),
6823 N2: getValue(V: I.getArgOperand(i: 0)),
6824 N3: getValue(V: I.getArgOperand(i: 1))));
6825 return;
6826 case Intrinsic::eh_unwind_init:
6827 DAG.getMachineFunction().setCallsUnwindInit(true);
6828 return;
6829 case Intrinsic::eh_dwarf_cfa:
6830 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::EH_DWARF_CFA, DL: sdl,
6831 VT: TLI.getPointerTy(DL: DAG.getDataLayout()),
6832 Operand: getValue(V: I.getArgOperand(i: 0))));
6833 return;
6834 case Intrinsic::eh_sjlj_callsite: {
6835 ConstantInt *CI = cast<ConstantInt>(Val: I.getArgOperand(i: 0));
6836 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6837
6838 FuncInfo.setCurrentCallSite(CI->getZExtValue());
6839 return;
6840 }
6841 case Intrinsic::eh_sjlj_functioncontext: {
6842 // Get and store the index of the function context.
6843 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6844 AllocaInst *FnCtx =
6845 cast<AllocaInst>(Val: I.getArgOperand(i: 0)->stripPointerCasts());
6846 int FI = FuncInfo.StaticAllocaMap[FnCtx];
6847 MFI.setFunctionContextIndex(FI);
6848 return;
6849 }
6850 case Intrinsic::eh_sjlj_setjmp: {
6851 SDValue Ops[2];
6852 Ops[0] = getRoot();
6853 Ops[1] = getValue(V: I.getArgOperand(i: 0));
6854 SDValue Op = DAG.getNode(Opcode: ISD::EH_SJLJ_SETJMP, DL: sdl,
6855 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::Other), Ops);
6856 setValue(V: &I, NewN: Op.getValue(R: 0));
6857 DAG.setRoot(Op.getValue(R: 1));
6858 return;
6859 }
6860 case Intrinsic::eh_sjlj_longjmp:
6861 DAG.setRoot(DAG.getNode(Opcode: ISD::EH_SJLJ_LONGJMP, DL: sdl, VT: MVT::Other,
6862 N1: getRoot(), N2: getValue(V: I.getArgOperand(i: 0))));
6863 return;
6864 case Intrinsic::eh_sjlj_setup_dispatch:
6865 DAG.setRoot(DAG.getNode(Opcode: ISD::EH_SJLJ_SETUP_DISPATCH, DL: sdl, VT: MVT::Other,
6866 Operand: getRoot()));
6867 return;
6868 case Intrinsic::masked_gather:
6869 visitMaskedGather(I);
6870 return;
6871 case Intrinsic::masked_load:
6872 visitMaskedLoad(I);
6873 return;
6874 case Intrinsic::masked_scatter:
6875 visitMaskedScatter(I);
6876 return;
6877 case Intrinsic::masked_store:
6878 visitMaskedStore(I);
6879 return;
6880 case Intrinsic::masked_expandload:
6881 visitMaskedLoad(I, IsExpanding: true /* IsExpanding */);
6882 return;
6883 case Intrinsic::masked_compressstore:
6884 visitMaskedStore(I, IsCompressing: true /* IsCompressing */);
6885 return;
6886 case Intrinsic::powi:
6887 setValue(V: &I, NewN: ExpandPowI(DL: sdl, LHS: getValue(V: I.getArgOperand(i: 0)),
6888 RHS: getValue(V: I.getArgOperand(i: 1)), DAG));
6889 return;
6890 case Intrinsic::log:
6891 setValue(V: &I, NewN: expandLog(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6892 return;
6893 case Intrinsic::log2:
6894 setValue(V: &I,
6895 NewN: expandLog2(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6896 return;
6897 case Intrinsic::log10:
6898 setValue(V: &I,
6899 NewN: expandLog10(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6900 return;
6901 case Intrinsic::exp:
6902 setValue(V: &I, NewN: expandExp(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6903 return;
6904 case Intrinsic::exp2:
6905 setValue(V: &I,
6906 NewN: expandExp2(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6907 return;
6908 case Intrinsic::pow:
6909 setValue(V: &I, NewN: expandPow(dl: sdl, LHS: getValue(V: I.getArgOperand(i: 0)),
6910 RHS: getValue(V: I.getArgOperand(i: 1)), DAG, TLI, Flags));
6911 return;
6912 case Intrinsic::sqrt:
6913 case Intrinsic::fabs:
6914 case Intrinsic::sin:
6915 case Intrinsic::cos:
6916 case Intrinsic::tan:
6917 case Intrinsic::asin:
6918 case Intrinsic::acos:
6919 case Intrinsic::atan:
6920 case Intrinsic::sinh:
6921 case Intrinsic::cosh:
6922 case Intrinsic::tanh:
6923 case Intrinsic::exp10:
6924 case Intrinsic::floor:
6925 case Intrinsic::ceil:
6926 case Intrinsic::trunc:
6927 case Intrinsic::rint:
6928 case Intrinsic::nearbyint:
6929 case Intrinsic::round:
6930 case Intrinsic::roundeven:
6931 case Intrinsic::canonicalize: {
6932 unsigned Opcode;
6933 // clang-format off
6934 switch (Intrinsic) {
6935 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6936 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
6937 case Intrinsic::fabs: Opcode = ISD::FABS; break;
6938 case Intrinsic::sin: Opcode = ISD::FSIN; break;
6939 case Intrinsic::cos: Opcode = ISD::FCOS; break;
6940 case Intrinsic::tan: Opcode = ISD::FTAN; break;
6941 case Intrinsic::asin: Opcode = ISD::FASIN; break;
6942 case Intrinsic::acos: Opcode = ISD::FACOS; break;
6943 case Intrinsic::atan: Opcode = ISD::FATAN; break;
6944 case Intrinsic::sinh: Opcode = ISD::FSINH; break;
6945 case Intrinsic::cosh: Opcode = ISD::FCOSH; break;
6946 case Intrinsic::tanh: Opcode = ISD::FTANH; break;
6947 case Intrinsic::exp10: Opcode = ISD::FEXP10; break;
6948 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
6949 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
6950 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
6951 case Intrinsic::rint: Opcode = ISD::FRINT; break;
6952 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6953 case Intrinsic::round: Opcode = ISD::FROUND; break;
6954 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6955 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6956 }
6957 // clang-format on
6958
6959 setValue(V: &I, NewN: DAG.getNode(Opcode, DL: sdl,
6960 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
6961 Operand: getValue(V: I.getArgOperand(i: 0)), Flags));
6962 return;
6963 }
6964 case Intrinsic::atan2:
6965 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FATAN2, DL: sdl,
6966 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
6967 N1: getValue(V: I.getArgOperand(i: 0)),
6968 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
6969 return;
6970 case Intrinsic::lround:
6971 case Intrinsic::llround:
6972 case Intrinsic::lrint:
6973 case Intrinsic::llrint: {
6974 unsigned Opcode;
6975 // clang-format off
6976 switch (Intrinsic) {
6977 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6978 case Intrinsic::lround: Opcode = ISD::LROUND; break;
6979 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6980 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
6981 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
6982 }
6983 // clang-format on
6984
6985 EVT RetVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
6986 setValue(V: &I, NewN: DAG.getNode(Opcode, DL: sdl, VT: RetVT,
6987 Operand: getValue(V: I.getArgOperand(i: 0))));
6988 return;
6989 }
6990 case Intrinsic::minnum:
6991 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMINNUM, DL: sdl,
6992 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
6993 N1: getValue(V: I.getArgOperand(i: 0)),
6994 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
6995 return;
6996 case Intrinsic::maxnum:
6997 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMAXNUM, DL: sdl,
6998 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
6999 N1: getValue(V: I.getArgOperand(i: 0)),
7000 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7001 return;
7002 case Intrinsic::minimum:
7003 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMINIMUM, DL: sdl,
7004 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7005 N1: getValue(V: I.getArgOperand(i: 0)),
7006 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7007 return;
7008 case Intrinsic::maximum:
7009 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMAXIMUM, DL: sdl,
7010 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7011 N1: getValue(V: I.getArgOperand(i: 0)),
7012 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7013 return;
7014 case Intrinsic::minimumnum:
7015 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMINIMUMNUM, DL: sdl,
7016 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7017 N1: getValue(V: I.getArgOperand(i: 0)),
7018 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7019 return;
7020 case Intrinsic::maximumnum:
7021 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMAXIMUMNUM, DL: sdl,
7022 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7023 N1: getValue(V: I.getArgOperand(i: 0)),
7024 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7025 return;
7026 case Intrinsic::copysign:
7027 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FCOPYSIGN, DL: sdl,
7028 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7029 N1: getValue(V: I.getArgOperand(i: 0)),
7030 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7031 return;
7032 case Intrinsic::ldexp:
7033 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FLDEXP, DL: sdl,
7034 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7035 N1: getValue(V: I.getArgOperand(i: 0)),
7036 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7037 return;
7038 case Intrinsic::modf:
7039 case Intrinsic::sincos:
7040 case Intrinsic::sincospi:
7041 case Intrinsic::frexp: {
7042 unsigned Opcode;
7043 switch (Intrinsic) {
7044 default:
7045 llvm_unreachable("unexpected intrinsic");
7046 case Intrinsic::sincos:
7047 Opcode = ISD::FSINCOS;
7048 break;
7049 case Intrinsic::sincospi:
7050 Opcode = ISD::FSINCOSPI;
7051 break;
7052 case Intrinsic::modf:
7053 Opcode = ISD::FMODF;
7054 break;
7055 case Intrinsic::frexp:
7056 Opcode = ISD::FFREXP;
7057 break;
7058 }
7059 SmallVector<EVT, 2> ValueVTs;
7060 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: I.getType(), ValueVTs);
7061 SDVTList VTs = DAG.getVTList(VTs: ValueVTs);
7062 setValue(
7063 V: &I, NewN: DAG.getNode(Opcode, DL: sdl, VTList: VTs, Ops: getValue(V: I.getArgOperand(i: 0)), Flags));
7064 return;
7065 }
7066 case Intrinsic::arithmetic_fence: {
7067 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::ARITH_FENCE, DL: sdl,
7068 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7069 Operand: getValue(V: I.getArgOperand(i: 0)), Flags));
7070 return;
7071 }
7072 case Intrinsic::fma:
7073 setValue(V: &I, NewN: DAG.getNode(
7074 Opcode: ISD::FMA, DL: sdl, VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7075 N1: getValue(V: I.getArgOperand(i: 0)), N2: getValue(V: I.getArgOperand(i: 1)),
7076 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
7077 return;
7078#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
7079 case Intrinsic::INTRINSIC:
7080#include "llvm/IR/ConstrainedOps.def"
7081 visitConstrainedFPIntrinsic(FPI: cast<ConstrainedFPIntrinsic>(Val: I));
7082 return;
7083#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7084#include "llvm/IR/VPIntrinsics.def"
7085 visitVectorPredicationIntrinsic(VPIntrin: cast<VPIntrinsic>(Val: I));
7086 return;
7087 case Intrinsic::fptrunc_round: {
7088 // Get the last argument, the metadata and convert it to an integer in the
7089 // call
7090 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 1))->getMetadata();
7091 std::optional<RoundingMode> RoundMode =
7092 convertStrToRoundingMode(cast<MDString>(Val: MD)->getString());
7093
7094 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7095
7096 // Propagate fast-math-flags from IR to node(s).
7097 SDNodeFlags Flags;
7098 Flags.copyFMF(FPMO: *cast<FPMathOperator>(Val: &I));
7099 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7100
7101 SDValue Result;
7102 Result = DAG.getNode(
7103 Opcode: ISD::FPTRUNC_ROUND, DL: sdl, VT, N1: getValue(V: I.getArgOperand(i: 0)),
7104 N2: DAG.getTargetConstant(Val: (int)*RoundMode, DL: sdl, VT: MVT::i32));
7105 setValue(V: &I, NewN: Result);
7106
7107 return;
7108 }
7109 case Intrinsic::fmuladd: {
7110 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7111 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7112 TLI.isFMAFasterThanFMulAndFAdd(MF: DAG.getMachineFunction(), VT)) {
7113 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMA, DL: sdl,
7114 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7115 N1: getValue(V: I.getArgOperand(i: 0)),
7116 N2: getValue(V: I.getArgOperand(i: 1)),
7117 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
7118 } else if (TLI.isOperationLegalOrCustom(Op: ISD::FMULADD, VT)) {
7119 // TODO: Support splitting the vector.
7120 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMULADD, DL: sdl,
7121 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7122 N1: getValue(V: I.getArgOperand(i: 0)),
7123 N2: getValue(V: I.getArgOperand(i: 1)),
7124 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
7125 } else {
7126 // TODO: Intrinsic calls should have fast-math-flags.
7127 SDValue Mul = DAG.getNode(
7128 Opcode: ISD::FMUL, DL: sdl, VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7129 N1: getValue(V: I.getArgOperand(i: 0)), N2: getValue(V: I.getArgOperand(i: 1)), Flags);
7130 SDValue Add = DAG.getNode(Opcode: ISD::FADD, DL: sdl,
7131 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7132 N1: Mul, N2: getValue(V: I.getArgOperand(i: 2)), Flags);
7133 setValue(V: &I, NewN: Add);
7134 }
7135 return;
7136 }
7137 case Intrinsic::fptosi_sat: {
7138 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7139 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_SINT_SAT, DL: sdl, VT,
7140 N1: getValue(V: I.getArgOperand(i: 0)),
7141 N2: DAG.getValueType(VT.getScalarType())));
7142 return;
7143 }
7144 case Intrinsic::fptoui_sat: {
7145 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7146 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_UINT_SAT, DL: sdl, VT,
7147 N1: getValue(V: I.getArgOperand(i: 0)),
7148 N2: DAG.getValueType(VT.getScalarType())));
7149 return;
7150 }
7151 case Intrinsic::set_rounding:
7152 Res = DAG.getNode(Opcode: ISD::SET_ROUNDING, DL: sdl, VT: MVT::Other,
7153 Ops: {getRoot(), getValue(V: I.getArgOperand(i: 0))});
7154 setValue(V: &I, NewN: Res);
7155 DAG.setRoot(Res.getValue(R: 0));
7156 return;
7157 case Intrinsic::is_fpclass: {
7158 const DataLayout DLayout = DAG.getDataLayout();
7159 EVT DestVT = TLI.getValueType(DL: DLayout, Ty: I.getType());
7160 EVT ArgVT = TLI.getValueType(DL: DLayout, Ty: I.getArgOperand(i: 0)->getType());
7161 FPClassTest Test = static_cast<FPClassTest>(
7162 cast<ConstantInt>(Val: I.getArgOperand(i: 1))->getZExtValue());
7163 MachineFunction &MF = DAG.getMachineFunction();
7164 const Function &F = MF.getFunction();
7165 SDValue Op = getValue(V: I.getArgOperand(i: 0));
7166 SDNodeFlags Flags;
7167 Flags.setNoFPExcept(
7168 !F.getAttributes().hasFnAttr(Kind: llvm::Attribute::StrictFP));
7169 // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7170 // expansion can use illegal types. Making expansion early allows
7171 // legalizing these types prior to selection.
7172 if (!TLI.isOperationLegal(Op: ISD::IS_FPCLASS, VT: ArgVT) &&
7173 !TLI.isOperationCustom(Op: ISD::IS_FPCLASS, VT: ArgVT)) {
7174 SDValue Result = TLI.expandIS_FPCLASS(ResultVT: DestVT, Op, Test, Flags, DL: sdl, DAG);
7175 setValue(V: &I, NewN: Result);
7176 return;
7177 }
7178
7179 SDValue Check = DAG.getTargetConstant(Val: Test, DL: sdl, VT: MVT::i32);
7180 SDValue V = DAG.getNode(Opcode: ISD::IS_FPCLASS, DL: sdl, VT: DestVT, Ops: {Op, Check}, Flags);
7181 setValue(V: &I, NewN: V);
7182 return;
7183 }
7184 case Intrinsic::get_fpenv: {
7185 const DataLayout DLayout = DAG.getDataLayout();
7186 EVT EnvVT = TLI.getValueType(DL: DLayout, Ty: I.getType());
7187 Align TempAlign = DAG.getEVTAlign(MemoryVT: EnvVT);
7188 SDValue Chain = getRoot();
7189 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7190 // and temporary storage in stack.
7191 if (TLI.isOperationLegalOrCustom(Op: ISD::GET_FPENV, VT: EnvVT)) {
7192 Res = DAG.getNode(
7193 Opcode: ISD::GET_FPENV, DL: sdl,
7194 VTList: DAG.getVTList(VT1: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
7195 VT2: MVT::Other),
7196 N: Chain);
7197 } else {
7198 SDValue Temp = DAG.CreateStackTemporary(VT: EnvVT, minAlign: TempAlign.value());
7199 int SPFI = cast<FrameIndexSDNode>(Val: Temp.getNode())->getIndex();
7200 auto MPI =
7201 MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI: SPFI);
7202 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7203 PtrInfo: MPI, F: MachineMemOperand::MOStore, Size: LocationSize::beforeOrAfterPointer(),
7204 BaseAlignment: TempAlign);
7205 Chain = DAG.getGetFPEnv(Chain, dl: sdl, Ptr: Temp, MemVT: EnvVT, MMO);
7206 Res = DAG.getLoad(VT: EnvVT, dl: sdl, Chain, Ptr: Temp, PtrInfo: MPI);
7207 }
7208 setValue(V: &I, NewN: Res);
7209 DAG.setRoot(Res.getValue(R: 1));
7210 return;
7211 }
7212 case Intrinsic::set_fpenv: {
7213 const DataLayout DLayout = DAG.getDataLayout();
7214 SDValue Env = getValue(V: I.getArgOperand(i: 0));
7215 EVT EnvVT = Env.getValueType();
7216 Align TempAlign = DAG.getEVTAlign(MemoryVT: EnvVT);
7217 SDValue Chain = getRoot();
7218 // If SET_FPENV is custom or legal, use it. Otherwise use loading
7219 // environment from memory.
7220 if (TLI.isOperationLegalOrCustom(Op: ISD::SET_FPENV, VT: EnvVT)) {
7221 Chain = DAG.getNode(Opcode: ISD::SET_FPENV, DL: sdl, VT: MVT::Other, N1: Chain, N2: Env);
7222 } else {
7223 // Allocate space in stack, copy environment bits into it and use this
7224 // memory in SET_FPENV_MEM.
7225 SDValue Temp = DAG.CreateStackTemporary(VT: EnvVT, minAlign: TempAlign.value());
7226 int SPFI = cast<FrameIndexSDNode>(Val: Temp.getNode())->getIndex();
7227 auto MPI =
7228 MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI: SPFI);
7229 Chain = DAG.getStore(Chain, dl: sdl, Val: Env, Ptr: Temp, PtrInfo: MPI, Alignment: TempAlign,
7230 MMOFlags: MachineMemOperand::MOStore);
7231 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7232 PtrInfo: MPI, F: MachineMemOperand::MOLoad, Size: LocationSize::beforeOrAfterPointer(),
7233 BaseAlignment: TempAlign);
7234 Chain = DAG.getSetFPEnv(Chain, dl: sdl, Ptr: Temp, MemVT: EnvVT, MMO);
7235 }
7236 DAG.setRoot(Chain);
7237 return;
7238 }
7239 case Intrinsic::reset_fpenv:
7240 DAG.setRoot(DAG.getNode(Opcode: ISD::RESET_FPENV, DL: sdl, VT: MVT::Other, Operand: getRoot()));
7241 return;
7242 case Intrinsic::get_fpmode:
7243 Res = DAG.getNode(
7244 Opcode: ISD::GET_FPMODE, DL: sdl,
7245 VTList: DAG.getVTList(VT1: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
7246 VT2: MVT::Other),
7247 N: DAG.getRoot());
7248 setValue(V: &I, NewN: Res);
7249 DAG.setRoot(Res.getValue(R: 1));
7250 return;
7251 case Intrinsic::set_fpmode:
7252 Res = DAG.getNode(Opcode: ISD::SET_FPMODE, DL: sdl, VT: MVT::Other, N1: {DAG.getRoot()},
7253 N2: getValue(V: I.getArgOperand(i: 0)));
7254 DAG.setRoot(Res);
7255 return;
7256 case Intrinsic::reset_fpmode: {
7257 Res = DAG.getNode(Opcode: ISD::RESET_FPMODE, DL: sdl, VT: MVT::Other, Operand: getRoot());
7258 DAG.setRoot(Res);
7259 return;
7260 }
7261 case Intrinsic::pcmarker: {
7262 SDValue Tmp = getValue(V: I.getArgOperand(i: 0));
7263 DAG.setRoot(DAG.getNode(Opcode: ISD::PCMARKER, DL: sdl, VT: MVT::Other, N1: getRoot(), N2: Tmp));
7264 return;
7265 }
7266 case Intrinsic::readcyclecounter: {
7267 SDValue Op = getRoot();
7268 Res = DAG.getNode(Opcode: ISD::READCYCLECOUNTER, DL: sdl,
7269 VTList: DAG.getVTList(VT1: MVT::i64, VT2: MVT::Other), N: Op);
7270 setValue(V: &I, NewN: Res);
7271 DAG.setRoot(Res.getValue(R: 1));
7272 return;
7273 }
7274 case Intrinsic::readsteadycounter: {
7275 SDValue Op = getRoot();
7276 Res = DAG.getNode(Opcode: ISD::READSTEADYCOUNTER, DL: sdl,
7277 VTList: DAG.getVTList(VT1: MVT::i64, VT2: MVT::Other), N: Op);
7278 setValue(V: &I, NewN: Res);
7279 DAG.setRoot(Res.getValue(R: 1));
7280 return;
7281 }
7282 case Intrinsic::bitreverse:
7283 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::BITREVERSE, DL: sdl,
7284 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7285 Operand: getValue(V: I.getArgOperand(i: 0))));
7286 return;
7287 case Intrinsic::bswap:
7288 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::BSWAP, DL: sdl,
7289 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7290 Operand: getValue(V: I.getArgOperand(i: 0))));
7291 return;
7292 case Intrinsic::cttz: {
7293 SDValue Arg = getValue(V: I.getArgOperand(i: 0));
7294 ConstantInt *CI = cast<ConstantInt>(Val: I.getArgOperand(i: 1));
7295 EVT Ty = Arg.getValueType();
7296 setValue(V: &I, NewN: DAG.getNode(Opcode: CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7297 DL: sdl, VT: Ty, Operand: Arg));
7298 return;
7299 }
7300 case Intrinsic::ctlz: {
7301 SDValue Arg = getValue(V: I.getArgOperand(i: 0));
7302 ConstantInt *CI = cast<ConstantInt>(Val: I.getArgOperand(i: 1));
7303 EVT Ty = Arg.getValueType();
7304 setValue(V: &I, NewN: DAG.getNode(Opcode: CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7305 DL: sdl, VT: Ty, Operand: Arg));
7306 return;
7307 }
7308 case Intrinsic::ctpop: {
7309 SDValue Arg = getValue(V: I.getArgOperand(i: 0));
7310 EVT Ty = Arg.getValueType();
7311 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CTPOP, DL: sdl, VT: Ty, Operand: Arg));
7312 return;
7313 }
7314 case Intrinsic::fshl:
7315 case Intrinsic::fshr: {
7316 bool IsFSHL = Intrinsic == Intrinsic::fshl;
7317 SDValue X = getValue(V: I.getArgOperand(i: 0));
7318 SDValue Y = getValue(V: I.getArgOperand(i: 1));
7319 SDValue Z = getValue(V: I.getArgOperand(i: 2));
7320 EVT VT = X.getValueType();
7321
7322 if (X == Y) {
7323 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7324 setValue(V: &I, NewN: DAG.getNode(Opcode: RotateOpcode, DL: sdl, VT, N1: X, N2: Z));
7325 } else {
7326 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7327 setValue(V: &I, NewN: DAG.getNode(Opcode: FunnelOpcode, DL: sdl, VT, N1: X, N2: Y, N3: Z));
7328 }
7329 return;
7330 }
7331 case Intrinsic::clmul: {
7332 SDValue X = getValue(V: I.getArgOperand(i: 0));
7333 SDValue Y = getValue(V: I.getArgOperand(i: 1));
7334 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CLMUL, DL: sdl, VT: X.getValueType(), N1: X, N2: Y));
7335 return;
7336 }
7337 case Intrinsic::sadd_sat: {
7338 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7339 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7340 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SADDSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7341 return;
7342 }
7343 case Intrinsic::uadd_sat: {
7344 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7345 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7346 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UADDSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7347 return;
7348 }
7349 case Intrinsic::ssub_sat: {
7350 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7351 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7352 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SSUBSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7353 return;
7354 }
7355 case Intrinsic::usub_sat: {
7356 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7357 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7358 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::USUBSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7359 return;
7360 }
7361 case Intrinsic::sshl_sat:
7362 case Intrinsic::ushl_sat: {
7363 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7364 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7365
7366 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
7367 LHSTy: Op1.getValueType(), DL: DAG.getDataLayout());
7368
7369 // Coerce the shift amount to the right type if we can. This exposes the
7370 // truncate or zext to optimization early.
7371 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
7372 assert(ShiftTy.getSizeInBits() >=
7373 Log2_32_Ceil(Op1.getValueSizeInBits()) &&
7374 "Unexpected shift type");
7375 Op2 = DAG.getZExtOrTrunc(Op: Op2, DL: getCurSDLoc(), VT: ShiftTy);
7376 }
7377
7378 unsigned Opc =
7379 Intrinsic == Intrinsic::sshl_sat ? ISD::SSHLSAT : ISD::USHLSAT;
7380 setValue(V: &I, NewN: DAG.getNode(Opcode: Opc, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7381 return;
7382 }
7383 case Intrinsic::smul_fix:
7384 case Intrinsic::umul_fix:
7385 case Intrinsic::smul_fix_sat:
7386 case Intrinsic::umul_fix_sat: {
7387 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7388 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7389 SDValue Op3 = getValue(V: I.getArgOperand(i: 2));
7390 setValue(V: &I, NewN: DAG.getNode(Opcode: FixedPointIntrinsicToOpcode(Intrinsic), DL: sdl,
7391 VT: Op1.getValueType(), N1: Op1, N2: Op2, N3: Op3));
7392 return;
7393 }
7394 case Intrinsic::sdiv_fix:
7395 case Intrinsic::udiv_fix:
7396 case Intrinsic::sdiv_fix_sat:
7397 case Intrinsic::udiv_fix_sat: {
7398 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7399 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7400 SDValue Op3 = getValue(V: I.getArgOperand(i: 2));
7401 setValue(V: &I, NewN: expandDivFix(Opcode: FixedPointIntrinsicToOpcode(Intrinsic), DL: sdl,
7402 LHS: Op1, RHS: Op2, Scale: Op3, DAG, TLI));
7403 return;
7404 }
7405 case Intrinsic::smax: {
7406 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7407 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7408 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SMAX, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7409 return;
7410 }
7411 case Intrinsic::smin: {
7412 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7413 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7414 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SMIN, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7415 return;
7416 }
7417 case Intrinsic::umax: {
7418 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7419 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7420 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UMAX, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7421 return;
7422 }
7423 case Intrinsic::umin: {
7424 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7425 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7426 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UMIN, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7427 return;
7428 }
7429 case Intrinsic::abs: {
7430 // TODO: Preserve "int min is poison" arg in SDAG?
7431 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7432 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::ABS, DL: sdl, VT: Op1.getValueType(), Operand: Op1));
7433 return;
7434 }
7435 case Intrinsic::scmp: {
7436 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7437 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7438 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7439 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SCMP, DL: sdl, VT: DestVT, N1: Op1, N2: Op2));
7440 break;
7441 }
7442 case Intrinsic::ucmp: {
7443 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7444 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7445 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7446 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UCMP, DL: sdl, VT: DestVT, N1: Op1, N2: Op2));
7447 break;
7448 }
7449 case Intrinsic::stackaddress:
7450 case Intrinsic::stacksave: {
7451 unsigned SDOpcode = Intrinsic == Intrinsic::stackaddress ? ISD::STACKADDRESS
7452 : ISD::STACKSAVE;
7453 SDValue Op = getRoot();
7454 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7455 Res = DAG.getNode(Opcode: SDOpcode, DL: sdl, VTList: DAG.getVTList(VT1: VT, VT2: MVT::Other), N: Op);
7456 setValue(V: &I, NewN: Res);
7457 DAG.setRoot(Res.getValue(R: 1));
7458 return;
7459 }
7460 case Intrinsic::stackrestore:
7461 Res = getValue(V: I.getArgOperand(i: 0));
7462 DAG.setRoot(DAG.getNode(Opcode: ISD::STACKRESTORE, DL: sdl, VT: MVT::Other, N1: getRoot(), N2: Res));
7463 return;
7464 case Intrinsic::get_dynamic_area_offset: {
7465 SDValue Op = getRoot();
7466 EVT ResTy = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7467 Res = DAG.getNode(Opcode: ISD::GET_DYNAMIC_AREA_OFFSET, DL: sdl, VTList: DAG.getVTList(VT: ResTy),
7468 N: Op);
7469 DAG.setRoot(Op);
7470 setValue(V: &I, NewN: Res);
7471 return;
7472 }
7473 case Intrinsic::stackguard: {
7474 MachineFunction &MF = DAG.getMachineFunction();
7475 const Module &M = *MF.getFunction().getParent();
7476 EVT PtrTy = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7477 SDValue Chain = getRoot();
7478 if (TLI.useLoadStackGuardNode(M)) {
7479 Res = getLoadStackGuard(DAG, DL: sdl, Chain);
7480 Res = DAG.getPtrExtOrTrunc(Op: Res, DL: sdl, VT: PtrTy);
7481 } else {
7482 const Value *Global = TLI.getSDagStackGuard(M, Libcalls: DAG.getLibcalls());
7483 if (!Global) {
7484 LLVMContext &Ctx = *DAG.getContext();
7485 Ctx.diagnose(DI: DiagnosticInfoGeneric("unable to lower stackguard"));
7486 setValue(V: &I, NewN: DAG.getPOISON(VT: PtrTy));
7487 return;
7488 }
7489
7490 Align Align = DAG.getDataLayout().getPrefTypeAlign(Ty: Global->getType());
7491 Res = DAG.getLoad(VT: PtrTy, dl: sdl, Chain, Ptr: getValue(V: Global),
7492 PtrInfo: MachinePointerInfo(Global, 0), Alignment: Align,
7493 MMOFlags: MachineMemOperand::MOVolatile);
7494 }
7495 if (TLI.useStackGuardXorFP())
7496 Res = TLI.emitStackGuardXorFP(DAG, Val: Res, DL: sdl);
7497 DAG.setRoot(Chain);
7498 setValue(V: &I, NewN: Res);
7499 return;
7500 }
7501 case Intrinsic::stackprotector: {
7502 // Emit code into the DAG to store the stack guard onto the stack.
7503 MachineFunction &MF = DAG.getMachineFunction();
7504 MachineFrameInfo &MFI = MF.getFrameInfo();
7505 const Module &M = *MF.getFunction().getParent();
7506 SDValue Src, Chain = getRoot();
7507
7508 if (TLI.useLoadStackGuardNode(M))
7509 Src = getLoadStackGuard(DAG, DL: sdl, Chain);
7510 else
7511 Src = getValue(V: I.getArgOperand(i: 0)); // The guard's value.
7512
7513 AllocaInst *Slot = cast<AllocaInst>(Val: I.getArgOperand(i: 1));
7514
7515 int FI = FuncInfo.StaticAllocaMap[Slot];
7516 MFI.setStackProtectorIndex(FI);
7517 EVT PtrTy = TLI.getFrameIndexTy(DL: DAG.getDataLayout());
7518
7519 SDValue FIN = DAG.getFrameIndex(FI, VT: PtrTy);
7520
7521 // Store the stack protector onto the stack.
7522 Res = DAG.getStore(
7523 Chain, dl: sdl, Val: Src, Ptr: FIN,
7524 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI),
7525 Alignment: MaybeAlign(), MMOFlags: MachineMemOperand::MOVolatile);
7526 setValue(V: &I, NewN: Res);
7527 DAG.setRoot(Res);
7528 return;
7529 }
7530 case Intrinsic::objectsize:
7531 llvm_unreachable("llvm.objectsize.* should have been lowered already");
7532
7533 case Intrinsic::is_constant:
7534 llvm_unreachable("llvm.is.constant.* should have been lowered already");
7535
7536 case Intrinsic::annotation:
7537 case Intrinsic::ptr_annotation:
7538 case Intrinsic::launder_invariant_group:
7539 case Intrinsic::strip_invariant_group:
7540 // Drop the intrinsic, but forward the value
7541 setValue(V: &I, NewN: getValue(V: I.getOperand(i_nocapture: 0)));
7542 return;
7543
7544 case Intrinsic::type_test:
7545 case Intrinsic::public_type_test:
7546 reportFatalUsageError(reason: "llvm.type.test intrinsic must be lowered by the "
7547 "LowerTypeTests pass before code generation");
7548 return;
7549
7550 case Intrinsic::assume:
7551 case Intrinsic::experimental_noalias_scope_decl:
7552 case Intrinsic::var_annotation:
7553 case Intrinsic::sideeffect:
7554 // Discard annotate attributes, noalias scope declarations, assumptions, and
7555 // artificial side-effects.
7556 return;
7557
7558 case Intrinsic::codeview_annotation: {
7559 // Emit a label associated with this metadata.
7560 MachineFunction &MF = DAG.getMachineFunction();
7561 MCSymbol *Label = MF.getContext().createTempSymbol(Name: "annotation", AlwaysAddSuffix: true);
7562 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 0))->getMetadata();
7563 MF.addCodeViewAnnotation(Label, MD: cast<MDNode>(Val: MD));
7564 Res = DAG.getLabelNode(Opcode: ISD::ANNOTATION_LABEL, dl: sdl, Root: getRoot(), Label);
7565 DAG.setRoot(Res);
7566 return;
7567 }
7568
7569 case Intrinsic::init_trampoline: {
7570 const Function *F = cast<Function>(Val: I.getArgOperand(i: 1)->stripPointerCasts());
7571
7572 SDValue Ops[6];
7573 Ops[0] = getRoot();
7574 Ops[1] = getValue(V: I.getArgOperand(i: 0));
7575 Ops[2] = getValue(V: I.getArgOperand(i: 1));
7576 Ops[3] = getValue(V: I.getArgOperand(i: 2));
7577 Ops[4] = DAG.getSrcValue(v: I.getArgOperand(i: 0));
7578 Ops[5] = DAG.getSrcValue(v: F);
7579
7580 Res = DAG.getNode(Opcode: ISD::INIT_TRAMPOLINE, DL: sdl, VT: MVT::Other, Ops);
7581
7582 DAG.setRoot(Res);
7583 return;
7584 }
7585 case Intrinsic::adjust_trampoline:
7586 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::ADJUST_TRAMPOLINE, DL: sdl,
7587 VT: TLI.getPointerTy(DL: DAG.getDataLayout()),
7588 Operand: getValue(V: I.getArgOperand(i: 0))));
7589 return;
7590 case Intrinsic::gcroot: {
7591 assert(DAG.getMachineFunction().getFunction().hasGC() &&
7592 "only valid in functions with gc specified, enforced by Verifier");
7593 assert(GFI && "implied by previous");
7594 const Value *Alloca = I.getArgOperand(i: 0)->stripPointerCasts();
7595 const Constant *TypeMap = cast<Constant>(Val: I.getArgOperand(i: 1));
7596
7597 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(Val: getValue(V: Alloca).getNode());
7598 GFI->addStackRoot(Num: FI->getIndex(), Metadata: TypeMap);
7599 return;
7600 }
7601 case Intrinsic::gcread:
7602 case Intrinsic::gcwrite:
7603 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7604 case Intrinsic::get_rounding:
7605 Res = DAG.getNode(Opcode: ISD::GET_ROUNDING, DL: sdl, ResultTys: {MVT::i32, MVT::Other}, Ops: getRoot());
7606 setValue(V: &I, NewN: Res);
7607 DAG.setRoot(Res.getValue(R: 1));
7608 return;
7609
7610 case Intrinsic::expect:
7611 case Intrinsic::expect_with_probability:
7612 // Just replace __builtin_expect(exp, c) and
7613 // __builtin_expect_with_probability(exp, c, p) with EXP.
7614 setValue(V: &I, NewN: getValue(V: I.getArgOperand(i: 0)));
7615 return;
7616
7617 case Intrinsic::ubsantrap:
7618 case Intrinsic::debugtrap:
7619 case Intrinsic::trap: {
7620 StringRef TrapFuncName =
7621 I.getAttributes().getFnAttr(Kind: "trap-func-name").getValueAsString();
7622 if (TrapFuncName.empty()) {
7623 switch (Intrinsic) {
7624 case Intrinsic::trap:
7625 DAG.setRoot(DAG.getNode(Opcode: ISD::TRAP, DL: sdl, VT: MVT::Other, Operand: getRoot()));
7626 break;
7627 case Intrinsic::debugtrap:
7628 DAG.setRoot(DAG.getNode(Opcode: ISD::DEBUGTRAP, DL: sdl, VT: MVT::Other, Operand: getRoot()));
7629 break;
7630 case Intrinsic::ubsantrap:
7631 DAG.setRoot(DAG.getNode(
7632 Opcode: ISD::UBSANTRAP, DL: sdl, VT: MVT::Other, N1: getRoot(),
7633 N2: DAG.getTargetConstant(
7634 Val: cast<ConstantInt>(Val: I.getArgOperand(i: 0))->getZExtValue(), DL: sdl,
7635 VT: MVT::i32)));
7636 break;
7637 default: llvm_unreachable("unknown trap intrinsic");
7638 }
7639 DAG.addNoMergeSiteInfo(Node: DAG.getRoot().getNode(),
7640 NoMerge: I.hasFnAttr(Kind: Attribute::NoMerge));
7641 return;
7642 }
7643 TargetLowering::ArgListTy Args;
7644 if (Intrinsic == Intrinsic::ubsantrap) {
7645 Value *Arg = I.getArgOperand(i: 0);
7646 Args.emplace_back(args&: Arg, args: getValue(V: Arg));
7647 }
7648
7649 TargetLowering::CallLoweringInfo CLI(DAG);
7650 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7651 CC: CallingConv::C, ResultType: I.getType(),
7652 Target: DAG.getExternalSymbol(Sym: TrapFuncName.data(),
7653 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
7654 ArgsList: std::move(Args));
7655 CLI.NoMerge = I.hasFnAttr(Kind: Attribute::NoMerge);
7656 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7657 DAG.setRoot(Result.second);
7658 return;
7659 }
7660
7661 case Intrinsic::allow_runtime_check:
7662 case Intrinsic::allow_ubsan_check:
7663 setValue(V: &I, NewN: getValue(V: ConstantInt::getTrue(Ty: I.getType())));
7664 return;
7665
7666 case Intrinsic::uadd_with_overflow:
7667 case Intrinsic::sadd_with_overflow:
7668 case Intrinsic::usub_with_overflow:
7669 case Intrinsic::ssub_with_overflow:
7670 case Intrinsic::umul_with_overflow:
7671 case Intrinsic::smul_with_overflow: {
7672 ISD::NodeType Op;
7673 switch (Intrinsic) {
7674 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7675 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7676 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7677 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7678 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7679 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7680 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7681 }
7682 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7683 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7684
7685 EVT ResultVT = Op1.getValueType();
7686 EVT OverflowVT = ResultVT.changeElementType(Context&: *Context, EltVT: MVT::i1);
7687
7688 SDVTList VTs = DAG.getVTList(VT1: ResultVT, VT2: OverflowVT);
7689 setValue(V: &I, NewN: DAG.getNode(Opcode: Op, DL: sdl, VTList: VTs, N1: Op1, N2: Op2));
7690 return;
7691 }
7692 case Intrinsic::prefetch: {
7693 SDValue Ops[5];
7694 unsigned rw = cast<ConstantInt>(Val: I.getArgOperand(i: 1))->getZExtValue();
7695 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7696 Ops[0] = DAG.getRoot();
7697 Ops[1] = getValue(V: I.getArgOperand(i: 0));
7698 Ops[2] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 1)), DL: sdl,
7699 VT: MVT::i32);
7700 Ops[3] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 2)), DL: sdl,
7701 VT: MVT::i32);
7702 Ops[4] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 3)), DL: sdl,
7703 VT: MVT::i32);
7704 SDValue Result = DAG.getMemIntrinsicNode(
7705 Opcode: ISD::PREFETCH, dl: sdl, VTList: DAG.getVTList(VT: MVT::Other), Ops,
7706 MemVT: EVT::getIntegerVT(Context&: *Context, BitWidth: 8), PtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
7707 /* align */ Alignment: std::nullopt, Flags);
7708
7709 // Chain the prefetch in parallel with any pending loads, to stay out of
7710 // the way of later optimizations.
7711 PendingLoads.push_back(Elt: Result);
7712 Result = getRoot();
7713 DAG.setRoot(Result);
7714 return;
7715 }
7716 case Intrinsic::lifetime_start:
7717 case Intrinsic::lifetime_end: {
7718 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7719 // Stack coloring is not enabled in O0, discard region information.
7720 if (TM.getOptLevel() == CodeGenOptLevel::None)
7721 return;
7722
7723 const AllocaInst *LifetimeObject = dyn_cast<AllocaInst>(Val: I.getArgOperand(i: 0));
7724 if (!LifetimeObject)
7725 return;
7726
7727 // First check that the Alloca is static, otherwise it won't have a
7728 // valid frame index.
7729 auto SI = FuncInfo.StaticAllocaMap.find(Val: LifetimeObject);
7730 if (SI == FuncInfo.StaticAllocaMap.end())
7731 return;
7732
7733 const int FrameIndex = SI->second;
7734 Res = DAG.getLifetimeNode(IsStart, dl: sdl, Chain: getRoot(), FrameIndex);
7735 DAG.setRoot(Res);
7736 return;
7737 }
7738 case Intrinsic::pseudoprobe: {
7739 auto Guid = cast<ConstantInt>(Val: I.getArgOperand(i: 0))->getZExtValue();
7740 auto Index = cast<ConstantInt>(Val: I.getArgOperand(i: 1))->getZExtValue();
7741 auto Attr = cast<ConstantInt>(Val: I.getArgOperand(i: 2))->getZExtValue();
7742 Res = DAG.getPseudoProbeNode(Dl: sdl, Chain: getRoot(), Guid, Index, Attr);
7743 DAG.setRoot(Res);
7744 return;
7745 }
7746 case Intrinsic::invariant_start:
7747 // Discard region information.
7748 setValue(V: &I,
7749 NewN: DAG.getUNDEF(VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType())));
7750 return;
7751 case Intrinsic::invariant_end:
7752 // Discard region information.
7753 return;
7754 case Intrinsic::clear_cache: {
7755 SDValue InputChain = DAG.getRoot();
7756 SDValue StartVal = getValue(V: I.getArgOperand(i: 0));
7757 SDValue EndVal = getValue(V: I.getArgOperand(i: 1));
7758 Res = DAG.getNode(Opcode: ISD::CLEAR_CACHE, DL: sdl, VTList: DAG.getVTList(VT: MVT::Other),
7759 Ops: {InputChain, StartVal, EndVal});
7760 setValue(V: &I, NewN: Res);
7761 DAG.setRoot(Res);
7762 return;
7763 }
7764 case Intrinsic::donothing:
7765 case Intrinsic::seh_try_begin:
7766 case Intrinsic::seh_scope_begin:
7767 case Intrinsic::seh_try_end:
7768 case Intrinsic::seh_scope_end:
7769 // ignore
7770 return;
7771 case Intrinsic::experimental_stackmap:
7772 visitStackmap(I);
7773 return;
7774 case Intrinsic::experimental_patchpoint_void:
7775 case Intrinsic::experimental_patchpoint:
7776 visitPatchpoint(CB: I);
7777 return;
7778 case Intrinsic::experimental_gc_statepoint:
7779 LowerStatepoint(I: cast<GCStatepointInst>(Val: I));
7780 return;
7781 case Intrinsic::experimental_gc_result:
7782 visitGCResult(I: cast<GCResultInst>(Val: I));
7783 return;
7784 case Intrinsic::experimental_gc_relocate:
7785 visitGCRelocate(Relocate: cast<GCRelocateInst>(Val: I));
7786 return;
7787 case Intrinsic::instrprof_cover:
7788 llvm_unreachable("instrprof failed to lower a cover");
7789 case Intrinsic::instrprof_increment:
7790 llvm_unreachable("instrprof failed to lower an increment");
7791 case Intrinsic::instrprof_timestamp:
7792 llvm_unreachable("instrprof failed to lower a timestamp");
7793 case Intrinsic::instrprof_value_profile:
7794 llvm_unreachable("instrprof failed to lower a value profiling call");
7795 case Intrinsic::instrprof_mcdc_parameters:
7796 llvm_unreachable("instrprof failed to lower mcdc parameters");
7797 case Intrinsic::instrprof_mcdc_tvbitmap_update:
7798 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7799 case Intrinsic::localescape: {
7800 MachineFunction &MF = DAG.getMachineFunction();
7801 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7802
7803 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7804 // is the same on all targets.
7805 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7806 Value *Arg = I.getArgOperand(i: Idx)->stripPointerCasts();
7807 if (isa<ConstantPointerNull>(Val: Arg))
7808 continue; // Skip null pointers. They represent a hole in index space.
7809 AllocaInst *Slot = cast<AllocaInst>(Val: Arg);
7810 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7811 "can only escape static allocas");
7812 int FI = FuncInfo.StaticAllocaMap[Slot];
7813 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7814 FuncName: GlobalValue::dropLLVMManglingEscape(Name: MF.getName()), Idx);
7815 BuildMI(BB&: *FuncInfo.MBB, I: FuncInfo.InsertPt, MIMD: dl,
7816 MCID: TII->get(Opcode: TargetOpcode::LOCAL_ESCAPE))
7817 .addSym(Sym: FrameAllocSym)
7818 .addFrameIndex(Idx: FI);
7819 }
7820
7821 return;
7822 }
7823
7824 case Intrinsic::localrecover: {
7825 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7826 MachineFunction &MF = DAG.getMachineFunction();
7827
7828 // Get the symbol that defines the frame offset.
7829 auto *Fn = cast<Function>(Val: I.getArgOperand(i: 0)->stripPointerCasts());
7830 auto *Idx = cast<ConstantInt>(Val: I.getArgOperand(i: 2));
7831 unsigned IdxVal =
7832 unsigned(Idx->getLimitedValue(Limit: std::numeric_limits<int>::max()));
7833 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7834 FuncName: GlobalValue::dropLLVMManglingEscape(Name: Fn->getName()), Idx: IdxVal);
7835
7836 Value *FP = I.getArgOperand(i: 1);
7837 SDValue FPVal = getValue(V: FP);
7838 EVT PtrVT = FPVal.getValueType();
7839
7840 // Create a MCSymbol for the label to avoid any target lowering
7841 // that would make this PC relative.
7842 SDValue OffsetSym = DAG.getMCSymbol(Sym: FrameAllocSym, VT: PtrVT);
7843 SDValue OffsetVal =
7844 DAG.getNode(Opcode: ISD::LOCAL_RECOVER, DL: sdl, VT: PtrVT, Operand: OffsetSym);
7845
7846 // Add the offset to the FP.
7847 SDValue Add = DAG.getMemBasePlusOffset(Base: FPVal, Offset: OffsetVal, DL: sdl);
7848 setValue(V: &I, NewN: Add);
7849
7850 return;
7851 }
7852
7853 case Intrinsic::fake_use: {
7854 Value *V = I.getArgOperand(i: 0);
7855 SDValue Ops[2];
7856 // For Values not declared or previously used in this basic block, the
7857 // NodeMap will not have an entry, and `getValue` will assert if V has no
7858 // valid register value.
7859 auto FakeUseValue = [&]() -> SDValue {
7860 SDValue &N = NodeMap[V];
7861 if (N.getNode())
7862 return N;
7863
7864 // If there's a virtual register allocated and initialized for this
7865 // value, use it.
7866 if (SDValue copyFromReg = getCopyFromRegs(V, Ty: V->getType()))
7867 return copyFromReg;
7868 // FIXME: Do we want to preserve constants? It seems pointless.
7869 if (isa<Constant>(Val: V))
7870 return getValue(V);
7871 return SDValue();
7872 }();
7873 if (!FakeUseValue || FakeUseValue.isUndef())
7874 return;
7875 Ops[0] = getRoot();
7876 Ops[1] = FakeUseValue;
7877 // Also, do not translate a fake use with an undef operand, or any other
7878 // empty SDValues.
7879 if (!Ops[1] || Ops[1].isUndef())
7880 return;
7881 DAG.setRoot(DAG.getNode(Opcode: ISD::FAKE_USE, DL: sdl, VT: MVT::Other, Ops));
7882 return;
7883 }
7884
7885 case Intrinsic::reloc_none: {
7886 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 0))->getMetadata();
7887 StringRef SymbolName = cast<MDString>(Val: MD)->getString();
7888 SDValue Ops[2] = {
7889 getRoot(),
7890 DAG.getTargetExternalSymbol(
7891 Sym: SymbolName.data(), VT: TLI.getProgramPointerTy(DL: DAG.getDataLayout()))};
7892 DAG.setRoot(DAG.getNode(Opcode: ISD::RELOC_NONE, DL: sdl, VT: MVT::Other, Ops));
7893 return;
7894 }
7895
7896 case Intrinsic::cond_loop: {
7897 SDValue InputChain = DAG.getRoot();
7898 SDValue P = getValue(V: I.getArgOperand(i: 0));
7899 Res = DAG.getNode(Opcode: ISD::COND_LOOP, DL: sdl, VTList: DAG.getVTList(VT: MVT::Other),
7900 Ops: {InputChain, P});
7901 setValue(V: &I, NewN: Res);
7902 DAG.setRoot(Res);
7903 return;
7904 }
7905
7906 case Intrinsic::eh_exceptionpointer:
7907 case Intrinsic::eh_exceptioncode: {
7908 // Get the exception pointer vreg, copy from it, and resize it to fit.
7909 const auto *CPI = cast<CatchPadInst>(Val: I.getArgOperand(i: 0));
7910 MVT PtrVT = TLI.getPointerTy(DL: DAG.getDataLayout());
7911 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(VT: PtrVT);
7912 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, RC: PtrRC);
7913 SDValue N = DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl: sdl, Reg: VReg, VT: PtrVT);
7914 if (Intrinsic == Intrinsic::eh_exceptioncode)
7915 N = DAG.getZExtOrTrunc(Op: N, DL: sdl, VT: MVT::i32);
7916 setValue(V: &I, NewN: N);
7917 return;
7918 }
7919 case Intrinsic::xray_customevent: {
7920 // Here we want to make sure that the intrinsic behaves as if it has a
7921 // specific calling convention.
7922 const auto &Triple = DAG.getTarget().getTargetTriple();
7923 if (!Triple.isAArch64(PointerWidth: 64) && Triple.getArch() != Triple::x86_64)
7924 return;
7925
7926 SmallVector<SDValue, 8> Ops;
7927
7928 // We want to say that we always want the arguments in registers.
7929 SDValue LogEntryVal = getValue(V: I.getArgOperand(i: 0));
7930 SDValue StrSizeVal = getValue(V: I.getArgOperand(i: 1));
7931 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
7932 SDValue Chain = getRoot();
7933 Ops.push_back(Elt: LogEntryVal);
7934 Ops.push_back(Elt: StrSizeVal);
7935 Ops.push_back(Elt: Chain);
7936
7937 // We need to enforce the calling convention for the callsite, so that
7938 // argument ordering is enforced correctly, and that register allocation can
7939 // see that some registers may be assumed clobbered and have to preserve
7940 // them across calls to the intrinsic.
7941 MachineSDNode *MN = DAG.getMachineNode(Opcode: TargetOpcode::PATCHABLE_EVENT_CALL,
7942 dl: sdl, VTs: NodeTys, Ops);
7943 SDValue patchableNode = SDValue(MN, 0);
7944 DAG.setRoot(patchableNode);
7945 setValue(V: &I, NewN: patchableNode);
7946 return;
7947 }
7948 case Intrinsic::xray_typedevent: {
7949 // Here we want to make sure that the intrinsic behaves as if it has a
7950 // specific calling convention.
7951 const auto &Triple = DAG.getTarget().getTargetTriple();
7952 if (!Triple.isAArch64(PointerWidth: 64) && Triple.getArch() != Triple::x86_64)
7953 return;
7954
7955 SmallVector<SDValue, 8> Ops;
7956
7957 // We want to say that we always want the arguments in registers.
7958 // It's unclear to me how manipulating the selection DAG here forces callers
7959 // to provide arguments in registers instead of on the stack.
7960 SDValue LogTypeId = getValue(V: I.getArgOperand(i: 0));
7961 SDValue LogEntryVal = getValue(V: I.getArgOperand(i: 1));
7962 SDValue StrSizeVal = getValue(V: I.getArgOperand(i: 2));
7963 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
7964 SDValue Chain = getRoot();
7965 Ops.push_back(Elt: LogTypeId);
7966 Ops.push_back(Elt: LogEntryVal);
7967 Ops.push_back(Elt: StrSizeVal);
7968 Ops.push_back(Elt: Chain);
7969
7970 // We need to enforce the calling convention for the callsite, so that
7971 // argument ordering is enforced correctly, and that register allocation can
7972 // see that some registers may be assumed clobbered and have to preserve
7973 // them across calls to the intrinsic.
7974 MachineSDNode *MN = DAG.getMachineNode(
7975 Opcode: TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, dl: sdl, VTs: NodeTys, Ops);
7976 SDValue patchableNode = SDValue(MN, 0);
7977 DAG.setRoot(patchableNode);
7978 setValue(V: &I, NewN: patchableNode);
7979 return;
7980 }
7981 case Intrinsic::experimental_deoptimize:
7982 LowerDeoptimizeCall(CI: &I);
7983 return;
7984 case Intrinsic::stepvector:
7985 visitStepVector(I);
7986 return;
7987 case Intrinsic::vector_reduce_fadd:
7988 case Intrinsic::vector_reduce_fmul:
7989 case Intrinsic::vector_reduce_add:
7990 case Intrinsic::vector_reduce_mul:
7991 case Intrinsic::vector_reduce_and:
7992 case Intrinsic::vector_reduce_or:
7993 case Intrinsic::vector_reduce_xor:
7994 case Intrinsic::vector_reduce_smax:
7995 case Intrinsic::vector_reduce_smin:
7996 case Intrinsic::vector_reduce_umax:
7997 case Intrinsic::vector_reduce_umin:
7998 case Intrinsic::vector_reduce_fmax:
7999 case Intrinsic::vector_reduce_fmin:
8000 case Intrinsic::vector_reduce_fmaximum:
8001 case Intrinsic::vector_reduce_fminimum:
8002 visitVectorReduce(I, Intrinsic);
8003 return;
8004
8005 case Intrinsic::icall_branch_funnel: {
8006 SmallVector<SDValue, 16> Ops;
8007 Ops.push_back(Elt: getValue(V: I.getArgOperand(i: 0)));
8008
8009 int64_t Offset;
8010 auto *Base = dyn_cast<GlobalObject>(Val: GetPointerBaseWithConstantOffset(
8011 Ptr: I.getArgOperand(i: 1), Offset, DL: DAG.getDataLayout()));
8012 if (!Base)
8013 report_fatal_error(
8014 reason: "llvm.icall.branch.funnel operand must be a GlobalValue");
8015 Ops.push_back(Elt: DAG.getTargetGlobalAddress(GV: Base, DL: sdl, VT: MVT::i64, offset: 0));
8016
8017 struct BranchFunnelTarget {
8018 int64_t Offset;
8019 SDValue Target;
8020 };
8021 SmallVector<BranchFunnelTarget, 8> Targets;
8022
8023 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
8024 auto *ElemBase = dyn_cast<GlobalObject>(Val: GetPointerBaseWithConstantOffset(
8025 Ptr: I.getArgOperand(i: Op), Offset, DL: DAG.getDataLayout()));
8026 if (ElemBase != Base)
8027 report_fatal_error(reason: "all llvm.icall.branch.funnel operands must refer "
8028 "to the same GlobalValue");
8029
8030 SDValue Val = getValue(V: I.getArgOperand(i: Op + 1));
8031 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
8032 if (!GA)
8033 report_fatal_error(
8034 reason: "llvm.icall.branch.funnel operand must be a GlobalValue");
8035 Targets.push_back(Elt: {.Offset: Offset, .Target: DAG.getTargetGlobalAddress(
8036 GV: GA->getGlobal(), DL: sdl, VT: Val.getValueType(),
8037 offset: GA->getOffset())});
8038 }
8039 llvm::sort(C&: Targets,
8040 Comp: [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
8041 return T1.Offset < T2.Offset;
8042 });
8043
8044 for (auto &T : Targets) {
8045 Ops.push_back(Elt: DAG.getTargetConstant(Val: T.Offset, DL: sdl, VT: MVT::i32));
8046 Ops.push_back(Elt: T.Target);
8047 }
8048
8049 Ops.push_back(Elt: DAG.getRoot()); // Chain
8050 SDValue N(DAG.getMachineNode(Opcode: TargetOpcode::ICALL_BRANCH_FUNNEL, dl: sdl,
8051 VT: MVT::Other, Ops),
8052 0);
8053 DAG.setRoot(N);
8054 setValue(V: &I, NewN: N);
8055 HasTailCall = true;
8056 return;
8057 }
8058
8059 case Intrinsic::wasm_landingpad_index:
8060 // Information this intrinsic contained has been transferred to
8061 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
8062 // delete it now.
8063 return;
8064
8065 case Intrinsic::aarch64_settag:
8066 case Intrinsic::aarch64_settag_zero: {
8067 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8068 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
8069 SDValue Val = TSI.EmitTargetCodeForSetTag(
8070 DAG, dl: sdl, Chain: getRoot(), Addr: getValue(V: I.getArgOperand(i: 0)),
8071 Size: getValue(V: I.getArgOperand(i: 1)), DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
8072 ZeroData: ZeroMemory);
8073 DAG.setRoot(Val);
8074 setValue(V: &I, NewN: Val);
8075 return;
8076 }
8077 case Intrinsic::amdgcn_cs_chain: {
8078 // At this point we don't care if it's amdgpu_cs_chain or
8079 // amdgpu_cs_chain_preserve.
8080 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
8081
8082 Type *RetTy = I.getType();
8083 assert(RetTy->isVoidTy() && "Should not return");
8084
8085 SDValue Callee = getValue(V: I.getOperand(i_nocapture: 0));
8086
8087 // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8088 // We'll also tack the value of the EXEC mask at the end.
8089 TargetLowering::ArgListTy Args;
8090 Args.reserve(n: 3);
8091
8092 for (unsigned Idx : {2, 3, 1}) {
8093 TargetLowering::ArgListEntry Arg(getValue(V: I.getOperand(i_nocapture: Idx)),
8094 I.getOperand(i_nocapture: Idx)->getType());
8095 Arg.setAttributes(Call: &I, ArgIdx: Idx);
8096 Args.push_back(x: Arg);
8097 }
8098
8099 assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8100 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8101 Args[2].IsInReg = true; // EXEC should be inreg
8102
8103 // Forward the flags and any additional arguments.
8104 for (unsigned Idx = 4; Idx < I.arg_size(); ++Idx) {
8105 TargetLowering::ArgListEntry Arg(getValue(V: I.getOperand(i_nocapture: Idx)),
8106 I.getOperand(i_nocapture: Idx)->getType());
8107 Arg.setAttributes(Call: &I, ArgIdx: Idx);
8108 Args.push_back(x: Arg);
8109 }
8110
8111 TargetLowering::CallLoweringInfo CLI(DAG);
8112 CLI.setDebugLoc(getCurSDLoc())
8113 .setChain(getRoot())
8114 .setCallee(CC, ResultType: RetTy, Target: Callee, ArgsList: std::move(Args))
8115 .setNoReturn(true)
8116 .setTailCall(true)
8117 .setConvergent(I.isConvergent());
8118 CLI.CB = &I;
8119 std::pair<SDValue, SDValue> Result =
8120 lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8121 (void)Result;
8122 assert(!Result.first.getNode() && !Result.second.getNode() &&
8123 "Should've lowered as tail call");
8124
8125 HasTailCall = true;
8126 return;
8127 }
8128 case Intrinsic::amdgcn_call_whole_wave: {
8129 TargetLowering::ArgListTy Args;
8130 bool isTailCall = I.isTailCall();
8131
8132 // The first argument is the callee. Skip it when assembling the call args.
8133 for (unsigned Idx = 1; Idx < I.arg_size(); ++Idx) {
8134 TargetLowering::ArgListEntry Arg(getValue(V: I.getArgOperand(i: Idx)),
8135 I.getArgOperand(i: Idx)->getType());
8136 Arg.setAttributes(Call: &I, ArgIdx: Idx);
8137
8138 // If we have an explicit sret argument that is an Instruction, (i.e., it
8139 // might point to function-local memory), we can't meaningfully tail-call.
8140 if (Arg.IsSRet && isa<Instruction>(Val: I.getArgOperand(i: Idx)))
8141 isTailCall = false;
8142
8143 Args.push_back(x: Arg);
8144 }
8145
8146 SDValue ConvControlToken;
8147 if (auto Bundle = I.getOperandBundle(ID: LLVMContext::OB_convergencectrl)) {
8148 auto *Token = Bundle->Inputs[0].get();
8149 ConvControlToken = getValue(V: Token);
8150 }
8151
8152 TargetLowering::CallLoweringInfo CLI(DAG);
8153 CLI.setDebugLoc(getCurSDLoc())
8154 .setChain(getRoot())
8155 .setCallee(CC: CallingConv::AMDGPU_Gfx_WholeWave, ResultType: I.getType(),
8156 Target: getValue(V: I.getArgOperand(i: 0)), ArgsList: std::move(Args))
8157 .setTailCall(isTailCall && canTailCall(CB: I))
8158 .setIsPreallocated(
8159 I.countOperandBundlesOfType(ID: LLVMContext::OB_preallocated) != 0)
8160 .setConvergent(I.isConvergent())
8161 .setConvergenceControlToken(ConvControlToken);
8162 CLI.CB = &I;
8163
8164 std::pair<SDValue, SDValue> Result =
8165 lowerInvokable(CLI, /*EHPadBB=*/nullptr);
8166
8167 if (Result.first.getNode())
8168 setValue(V: &I, NewN: Result.first);
8169 return;
8170 }
8171 case Intrinsic::ptrmask: {
8172 SDValue Ptr = getValue(V: I.getOperand(i_nocapture: 0));
8173 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 1));
8174
8175 // On arm64_32, pointers are 32 bits when stored in memory, but
8176 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to
8177 // match the index type, but the pointer is 64 bits, so the mask must be
8178 // zero-extended up to 64 bits to match the pointer.
8179 EVT PtrVT =
8180 TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i_nocapture: 0)->getType());
8181 EVT MemVT =
8182 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i_nocapture: 0)->getType());
8183 assert(PtrVT == Ptr.getValueType());
8184 if (Mask.getValueType().getFixedSizeInBits() < MemVT.getFixedSizeInBits()) {
8185 // For AMDGPU buffer descriptors the mask is 48 bits, but the pointer is
8186 // 128-bit, so we have to pad the mask with ones for unused bits.
8187 auto HighOnes = DAG.getNode(
8188 Opcode: ISD::SHL, DL: sdl, VT: PtrVT, N1: DAG.getAllOnesConstant(DL: sdl, VT: PtrVT),
8189 N2: DAG.getShiftAmountConstant(Val: Mask.getValueType().getFixedSizeInBits(),
8190 VT: PtrVT, DL: sdl));
8191 Mask = DAG.getNode(Opcode: ISD::OR, DL: sdl, VT: PtrVT,
8192 N1: DAG.getZExtOrTrunc(Op: Mask, DL: sdl, VT: PtrVT), N2: HighOnes);
8193 } else if (Mask.getValueType() != PtrVT)
8194 Mask = DAG.getPtrExtOrTrunc(Op: Mask, DL: sdl, VT: PtrVT);
8195
8196 assert(Mask.getValueType() == PtrVT);
8197 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::AND, DL: sdl, VT: PtrVT, N1: Ptr, N2: Mask));
8198 return;
8199 }
8200 case Intrinsic::threadlocal_address: {
8201 setValue(V: &I, NewN: getValue(V: I.getOperand(i_nocapture: 0)));
8202 return;
8203 }
8204 case Intrinsic::get_active_lane_mask: {
8205 EVT CCVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8206 SDValue Index = getValue(V: I.getOperand(i_nocapture: 0));
8207 SDValue TripCount = getValue(V: I.getOperand(i_nocapture: 1));
8208 EVT ElementVT = Index.getValueType();
8209
8210 if (!TLI.shouldExpandGetActiveLaneMask(VT: CCVT, OpVT: ElementVT)) {
8211 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::GET_ACTIVE_LANE_MASK, DL: sdl, VT: CCVT, N1: Index,
8212 N2: TripCount));
8213 return;
8214 }
8215
8216 EVT VecTy = EVT::getVectorVT(Context&: *DAG.getContext(), VT: ElementVT,
8217 EC: CCVT.getVectorElementCount());
8218
8219 SDValue VectorIndex = DAG.getSplat(VT: VecTy, DL: sdl, Op: Index);
8220 SDValue VectorTripCount = DAG.getSplat(VT: VecTy, DL: sdl, Op: TripCount);
8221 SDValue VectorStep = DAG.getStepVector(DL: sdl, ResVT: VecTy);
8222 SDValue VectorInduction = DAG.getNode(
8223 Opcode: ISD::UADDSAT, DL: sdl, VT: VecTy, N1: VectorIndex, N2: VectorStep);
8224 SDValue SetCC = DAG.getSetCC(DL: sdl, VT: CCVT, LHS: VectorInduction,
8225 RHS: VectorTripCount, Cond: ISD::CondCode::SETULT);
8226 setValue(V: &I, NewN: SetCC);
8227 return;
8228 }
8229 case Intrinsic::experimental_get_vector_length: {
8230 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8231 "Expected positive VF");
8232 unsigned VF = cast<ConstantInt>(Val: I.getOperand(i_nocapture: 1))->getZExtValue();
8233 bool IsScalable = cast<ConstantInt>(Val: I.getOperand(i_nocapture: 2))->isOne();
8234
8235 SDValue Count = getValue(V: I.getOperand(i_nocapture: 0));
8236 EVT CountVT = Count.getValueType();
8237
8238 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8239 visitTargetIntrinsic(I, Intrinsic);
8240 return;
8241 }
8242
8243 // Expand to a umin between the trip count and the maximum elements the type
8244 // can hold.
8245 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8246
8247 // Extend the trip count to at least the result VT.
8248 if (CountVT.bitsLT(VT)) {
8249 Count = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: sdl, VT, Operand: Count);
8250 CountVT = VT;
8251 }
8252
8253 SDValue MaxEVL = DAG.getElementCount(DL: sdl, VT: CountVT,
8254 EC: ElementCount::get(MinVal: VF, Scalable: IsScalable));
8255
8256 SDValue UMin = DAG.getNode(Opcode: ISD::UMIN, DL: sdl, VT: CountVT, N1: Count, N2: MaxEVL);
8257 // Clip to the result type if needed.
8258 SDValue Trunc = DAG.getNode(Opcode: ISD::TRUNCATE, DL: sdl, VT, Operand: UMin);
8259
8260 setValue(V: &I, NewN: Trunc);
8261 return;
8262 }
8263 case Intrinsic::vector_partial_reduce_add: {
8264 SDValue Acc = getValue(V: I.getOperand(i_nocapture: 0));
8265 SDValue Input = getValue(V: I.getOperand(i_nocapture: 1));
8266 setValue(V: &I,
8267 NewN: DAG.getNode(Opcode: ISD::PARTIAL_REDUCE_UMLA, DL: sdl, VT: Acc.getValueType(), N1: Acc,
8268 N2: Input, N3: DAG.getConstant(Val: 1, DL: sdl, VT: Input.getValueType())));
8269 return;
8270 }
8271 case Intrinsic::vector_partial_reduce_fadd: {
8272 SDValue Acc = getValue(V: I.getOperand(i_nocapture: 0));
8273 SDValue Input = getValue(V: I.getOperand(i_nocapture: 1));
8274 setValue(V: &I, NewN: DAG.getNode(
8275 Opcode: ISD::PARTIAL_REDUCE_FMLA, DL: sdl, VT: Acc.getValueType(), N1: Acc,
8276 N2: Input, N3: DAG.getConstantFP(Val: 1.0, DL: sdl, VT: Input.getValueType())));
8277 return;
8278 }
8279 case Intrinsic::experimental_cttz_elts: {
8280 auto DL = getCurSDLoc();
8281 SDValue Op = getValue(V: I.getOperand(i_nocapture: 0));
8282 EVT OpVT = Op.getValueType();
8283
8284 if (!TLI.shouldExpandCttzElements(VT: OpVT)) {
8285 visitTargetIntrinsic(I, Intrinsic);
8286 return;
8287 }
8288
8289 if (OpVT.getScalarType() != MVT::i1) {
8290 // Compare the input vector elements to zero & use to count trailing zeros
8291 SDValue AllZero = DAG.getConstant(Val: 0, DL, VT: OpVT);
8292 OpVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::i1,
8293 EC: OpVT.getVectorElementCount());
8294 Op = DAG.getSetCC(DL, VT: OpVT, LHS: Op, RHS: AllZero, Cond: ISD::SETNE);
8295 }
8296
8297 // If the zero-is-poison flag is set, we can assume the upper limit
8298 // of the result is VF-1.
8299 bool ZeroIsPoison =
8300 !cast<ConstantSDNode>(Val: getValue(V: I.getOperand(i_nocapture: 1)))->isZero();
8301 ConstantRange VScaleRange(1, true); // Dummy value.
8302 if (isa<ScalableVectorType>(Val: I.getOperand(i_nocapture: 0)->getType()))
8303 VScaleRange = getVScaleRange(F: I.getCaller(), BitWidth: 64);
8304 unsigned EltWidth = TLI.getBitWidthForCttzElements(
8305 RetTy: I.getType(), EC: OpVT.getVectorElementCount(), ZeroIsPoison, VScaleRange: &VScaleRange);
8306
8307 MVT NewEltTy = MVT::getIntegerVT(BitWidth: EltWidth);
8308
8309 // Create the new vector type & get the vector length
8310 EVT NewVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: NewEltTy,
8311 EC: OpVT.getVectorElementCount());
8312
8313 SDValue VL =
8314 DAG.getElementCount(DL, VT: NewEltTy, EC: OpVT.getVectorElementCount());
8315
8316 SDValue StepVec = DAG.getStepVector(DL, ResVT: NewVT);
8317 SDValue SplatVL = DAG.getSplat(VT: NewVT, DL, Op: VL);
8318 SDValue StepVL = DAG.getNode(Opcode: ISD::SUB, DL, VT: NewVT, N1: SplatVL, N2: StepVec);
8319 SDValue Ext = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT: NewVT, Operand: Op);
8320 SDValue And = DAG.getNode(Opcode: ISD::AND, DL, VT: NewVT, N1: StepVL, N2: Ext);
8321 SDValue Max = DAG.getNode(Opcode: ISD::VECREDUCE_UMAX, DL, VT: NewEltTy, Operand: And);
8322 SDValue Sub = DAG.getNode(Opcode: ISD::SUB, DL, VT: NewEltTy, N1: VL, N2: Max);
8323
8324 EVT RetTy = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8325 SDValue Ret = DAG.getZExtOrTrunc(Op: Sub, DL, VT: RetTy);
8326
8327 setValue(V: &I, NewN: Ret);
8328 return;
8329 }
8330 case Intrinsic::vector_insert: {
8331 SDValue Vec = getValue(V: I.getOperand(i_nocapture: 0));
8332 SDValue SubVec = getValue(V: I.getOperand(i_nocapture: 1));
8333 SDValue Index = getValue(V: I.getOperand(i_nocapture: 2));
8334
8335 // The intrinsic's index type is i64, but the SDNode requires an index type
8336 // suitable for the target. Convert the index as required.
8337 MVT VectorIdxTy = TLI.getVectorIdxTy(DL: DAG.getDataLayout());
8338 if (Index.getValueType() != VectorIdxTy)
8339 Index = DAG.getVectorIdxConstant(Val: Index->getAsZExtVal(), DL: sdl);
8340
8341 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8342 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::INSERT_SUBVECTOR, DL: sdl, VT: ResultVT, N1: Vec, N2: SubVec,
8343 N3: Index));
8344 return;
8345 }
8346 case Intrinsic::vector_extract: {
8347 SDValue Vec = getValue(V: I.getOperand(i_nocapture: 0));
8348 SDValue Index = getValue(V: I.getOperand(i_nocapture: 1));
8349 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8350
8351 // The intrinsic's index type is i64, but the SDNode requires an index type
8352 // suitable for the target. Convert the index as required.
8353 MVT VectorIdxTy = TLI.getVectorIdxTy(DL: DAG.getDataLayout());
8354 if (Index.getValueType() != VectorIdxTy)
8355 Index = DAG.getVectorIdxConstant(Val: Index->getAsZExtVal(), DL: sdl);
8356
8357 setValue(V: &I,
8358 NewN: DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: sdl, VT: ResultVT, N1: Vec, N2: Index));
8359 return;
8360 }
8361 case Intrinsic::experimental_vector_match: {
8362 SDValue Op1 = getValue(V: I.getOperand(i_nocapture: 0));
8363 SDValue Op2 = getValue(V: I.getOperand(i_nocapture: 1));
8364 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 2));
8365 EVT Op1VT = Op1.getValueType();
8366 EVT Op2VT = Op2.getValueType();
8367 EVT ResVT = Mask.getValueType();
8368 unsigned SearchSize = Op2VT.getVectorNumElements();
8369
8370 // If the target has native support for this vector match operation, lower
8371 // the intrinsic untouched; otherwise, expand it below.
8372 if (!TLI.shouldExpandVectorMatch(VT: Op1VT, SearchSize)) {
8373 visitTargetIntrinsic(I, Intrinsic);
8374 return;
8375 }
8376
8377 SDValue Ret = DAG.getConstant(Val: 0, DL: sdl, VT: ResVT);
8378
8379 for (unsigned i = 0; i < SearchSize; ++i) {
8380 SDValue Op2Elem = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: sdl,
8381 VT: Op2VT.getVectorElementType(), N1: Op2,
8382 N2: DAG.getVectorIdxConstant(Val: i, DL: sdl));
8383 SDValue Splat = DAG.getNode(Opcode: ISD::SPLAT_VECTOR, DL: sdl, VT: Op1VT, Operand: Op2Elem);
8384 SDValue Cmp = DAG.getSetCC(DL: sdl, VT: ResVT, LHS: Op1, RHS: Splat, Cond: ISD::SETEQ);
8385 Ret = DAG.getNode(Opcode: ISD::OR, DL: sdl, VT: ResVT, N1: Ret, N2: Cmp);
8386 }
8387
8388 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::AND, DL: sdl, VT: ResVT, N1: Ret, N2: Mask));
8389 return;
8390 }
8391 case Intrinsic::vector_reverse:
8392 visitVectorReverse(I);
8393 return;
8394 case Intrinsic::vector_splice_left:
8395 case Intrinsic::vector_splice_right:
8396 visitVectorSplice(I);
8397 return;
8398 case Intrinsic::callbr_landingpad:
8399 visitCallBrLandingPad(I);
8400 return;
8401 case Intrinsic::vector_interleave2:
8402 visitVectorInterleave(I, Factor: 2);
8403 return;
8404 case Intrinsic::vector_interleave3:
8405 visitVectorInterleave(I, Factor: 3);
8406 return;
8407 case Intrinsic::vector_interleave4:
8408 visitVectorInterleave(I, Factor: 4);
8409 return;
8410 case Intrinsic::vector_interleave5:
8411 visitVectorInterleave(I, Factor: 5);
8412 return;
8413 case Intrinsic::vector_interleave6:
8414 visitVectorInterleave(I, Factor: 6);
8415 return;
8416 case Intrinsic::vector_interleave7:
8417 visitVectorInterleave(I, Factor: 7);
8418 return;
8419 case Intrinsic::vector_interleave8:
8420 visitVectorInterleave(I, Factor: 8);
8421 return;
8422 case Intrinsic::vector_deinterleave2:
8423 visitVectorDeinterleave(I, Factor: 2);
8424 return;
8425 case Intrinsic::vector_deinterleave3:
8426 visitVectorDeinterleave(I, Factor: 3);
8427 return;
8428 case Intrinsic::vector_deinterleave4:
8429 visitVectorDeinterleave(I, Factor: 4);
8430 return;
8431 case Intrinsic::vector_deinterleave5:
8432 visitVectorDeinterleave(I, Factor: 5);
8433 return;
8434 case Intrinsic::vector_deinterleave6:
8435 visitVectorDeinterleave(I, Factor: 6);
8436 return;
8437 case Intrinsic::vector_deinterleave7:
8438 visitVectorDeinterleave(I, Factor: 7);
8439 return;
8440 case Intrinsic::vector_deinterleave8:
8441 visitVectorDeinterleave(I, Factor: 8);
8442 return;
8443 case Intrinsic::experimental_vector_compress:
8444 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::VECTOR_COMPRESS, DL: sdl,
8445 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
8446 N1: getValue(V: I.getArgOperand(i: 0)),
8447 N2: getValue(V: I.getArgOperand(i: 1)),
8448 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
8449 return;
8450 case Intrinsic::experimental_convergence_anchor:
8451 case Intrinsic::experimental_convergence_entry:
8452 case Intrinsic::experimental_convergence_loop:
8453 visitConvergenceControl(I, Intrinsic);
8454 return;
8455 case Intrinsic::experimental_vector_histogram_add: {
8456 visitVectorHistogram(I, IntrinsicID: Intrinsic);
8457 return;
8458 }
8459 case Intrinsic::experimental_vector_extract_last_active: {
8460 visitVectorExtractLastActive(I, Intrinsic);
8461 return;
8462 }
8463 case Intrinsic::loop_dependence_war_mask:
8464 setValue(V: &I,
8465 NewN: DAG.getNode(Opcode: ISD::LOOP_DEPENDENCE_WAR_MASK, DL: sdl,
8466 VT: EVT::getEVT(Ty: I.getType()), N1: getValue(V: I.getOperand(i_nocapture: 0)),
8467 N2: getValue(V: I.getOperand(i_nocapture: 1)), N3: getValue(V: I.getOperand(i_nocapture: 2)),
8468 N4: DAG.getConstant(Val: 0, DL: sdl, VT: MVT::i64)));
8469 return;
8470 case Intrinsic::loop_dependence_raw_mask:
8471 setValue(V: &I,
8472 NewN: DAG.getNode(Opcode: ISD::LOOP_DEPENDENCE_RAW_MASK, DL: sdl,
8473 VT: EVT::getEVT(Ty: I.getType()), N1: getValue(V: I.getOperand(i_nocapture: 0)),
8474 N2: getValue(V: I.getOperand(i_nocapture: 1)), N3: getValue(V: I.getOperand(i_nocapture: 2)),
8475 N4: DAG.getConstant(Val: 0, DL: sdl, VT: MVT::i64)));
8476 return;
8477 }
8478}
8479
8480void SelectionDAGBuilder::pushFPOpOutChain(SDValue Result,
8481 fp::ExceptionBehavior EB) {
8482 assert(Result.getNode()->getNumValues() == 2);
8483 SDValue OutChain = Result.getValue(R: 1);
8484 assert(OutChain.getValueType() == MVT::Other);
8485
8486 // Instead of updating the root immediately, push the produced chain to the
8487 // appropriate list, deferring the update until the root is requested. In this
8488 // case, the nodes from the lists are chained using TokenFactor, indicating
8489 // that the operations are independent.
8490 //
8491 // In particular, the root is updated before any call that might access the
8492 // floating-point environment, except for constrained intrinsics.
8493 switch (EB) {
8494 case fp::ExceptionBehavior::ebMayTrap:
8495 case fp::ExceptionBehavior::ebIgnore:
8496 PendingConstrainedFP.push_back(Elt: OutChain);
8497 break;
8498 case fp::ExceptionBehavior::ebStrict:
8499 PendingConstrainedFPStrict.push_back(Elt: OutChain);
8500 break;
8501 }
8502}
8503
8504void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8505 const ConstrainedFPIntrinsic &FPI) {
8506 SDLoc sdl = getCurSDLoc();
8507
8508 // We do not need to serialize constrained FP intrinsics against
8509 // each other or against (nonvolatile) loads, so they can be
8510 // chained like loads.
8511 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8512 SDValue Chain = getFPOperationRoot(EB);
8513 SmallVector<SDValue, 4> Opers;
8514 Opers.push_back(Elt: Chain);
8515 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8516 Opers.push_back(Elt: getValue(V: FPI.getArgOperand(i: I)));
8517
8518 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8519 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: FPI.getType());
8520 SDVTList VTs = DAG.getVTList(VT1: VT, VT2: MVT::Other);
8521
8522 SDNodeFlags Flags;
8523 if (EB == fp::ExceptionBehavior::ebIgnore)
8524 Flags.setNoFPExcept(true);
8525
8526 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &FPI))
8527 Flags.copyFMF(FPMO: *FPOp);
8528
8529 unsigned Opcode;
8530 switch (FPI.getIntrinsicID()) {
8531 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8532#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8533 case Intrinsic::INTRINSIC: \
8534 Opcode = ISD::STRICT_##DAGN; \
8535 break;
8536#include "llvm/IR/ConstrainedOps.def"
8537 case Intrinsic::experimental_constrained_fmuladd: {
8538 Opcode = ISD::STRICT_FMA;
8539 // Break fmuladd into fmul and fadd.
8540 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8541 !TLI.isFMAFasterThanFMulAndFAdd(MF: DAG.getMachineFunction(), VT)) {
8542 Opers.pop_back();
8543 SDValue Mul = DAG.getNode(Opcode: ISD::STRICT_FMUL, DL: sdl, VTList: VTs, Ops: Opers, Flags);
8544 pushFPOpOutChain(Result: Mul, EB);
8545 Opcode = ISD::STRICT_FADD;
8546 Opers.clear();
8547 Opers.push_back(Elt: Mul.getValue(R: 1));
8548 Opers.push_back(Elt: Mul.getValue(R: 0));
8549 Opers.push_back(Elt: getValue(V: FPI.getArgOperand(i: 2)));
8550 }
8551 break;
8552 }
8553 }
8554
8555 // A few strict DAG nodes carry additional operands that are not
8556 // set up by the default code above.
8557 switch (Opcode) {
8558 default: break;
8559 case ISD::STRICT_FP_ROUND:
8560 Opers.push_back(
8561 Elt: DAG.getTargetConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
8562 break;
8563 case ISD::STRICT_FSETCC:
8564 case ISD::STRICT_FSETCCS: {
8565 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(Val: &FPI);
8566 ISD::CondCode Condition = getFCmpCondCode(Pred: FPCmp->getPredicate());
8567 if (DAG.isKnownNeverNaN(Op: Opers[1]) && DAG.isKnownNeverNaN(Op: Opers[2]))
8568 Condition = getFCmpCodeWithoutNaN(CC: Condition);
8569 Opers.push_back(Elt: DAG.getCondCode(Cond: Condition));
8570 break;
8571 }
8572 }
8573
8574 SDValue Result = DAG.getNode(Opcode, DL: sdl, VTList: VTs, Ops: Opers, Flags);
8575 pushFPOpOutChain(Result, EB);
8576
8577 SDValue FPResult = Result.getValue(R: 0);
8578 setValue(V: &FPI, NewN: FPResult);
8579}
8580
8581static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8582 std::optional<unsigned> ResOPC;
8583 switch (VPIntrin.getIntrinsicID()) {
8584 case Intrinsic::vp_ctlz: {
8585 bool IsZeroUndef = cast<ConstantInt>(Val: VPIntrin.getArgOperand(i: 1))->isOne();
8586 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8587 break;
8588 }
8589 case Intrinsic::vp_cttz: {
8590 bool IsZeroUndef = cast<ConstantInt>(Val: VPIntrin.getArgOperand(i: 1))->isOne();
8591 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8592 break;
8593 }
8594 case Intrinsic::vp_cttz_elts: {
8595 bool IsZeroPoison = cast<ConstantInt>(Val: VPIntrin.getArgOperand(i: 1))->isOne();
8596 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8597 break;
8598 }
8599#define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \
8600 case Intrinsic::VPID: \
8601 ResOPC = ISD::VPSD; \
8602 break;
8603#include "llvm/IR/VPIntrinsics.def"
8604 }
8605
8606 if (!ResOPC)
8607 llvm_unreachable(
8608 "Inconsistency: no SDNode available for this VPIntrinsic!");
8609
8610 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8611 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8612 if (VPIntrin.getFastMathFlags().allowReassoc())
8613 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8614 : ISD::VP_REDUCE_FMUL;
8615 }
8616
8617 return *ResOPC;
8618}
8619
8620void SelectionDAGBuilder::visitVPLoad(
8621 const VPIntrinsic &VPIntrin, EVT VT,
8622 const SmallVectorImpl<SDValue> &OpValues) {
8623 SDLoc DL = getCurSDLoc();
8624 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8625 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8626 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8627 const MDNode *Ranges = getRangeMetadata(I: VPIntrin);
8628 SDValue LD;
8629 // Do not serialize variable-length loads of constant memory with
8630 // anything.
8631 if (!Alignment)
8632 Alignment = DAG.getEVTAlign(MemoryVT: VT);
8633 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
8634 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
8635 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8636 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8637 MachineMemOperand::Flags MMOFlags =
8638 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8639 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8640 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
8641 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: *Alignment, AAInfo, Ranges);
8642 LD = DAG.getLoadVP(VT, dl: DL, Chain: InChain, Ptr: OpValues[0], Mask: OpValues[1], EVL: OpValues[2],
8643 MMO, IsExpanding: false /*IsExpanding */);
8644 if (AddToChain)
8645 PendingLoads.push_back(Elt: LD.getValue(R: 1));
8646 setValue(V: &VPIntrin, NewN: LD);
8647}
8648
8649void SelectionDAGBuilder::visitVPLoadFF(
8650 const VPIntrinsic &VPIntrin, EVT VT, EVT EVLVT,
8651 const SmallVectorImpl<SDValue> &OpValues) {
8652 assert(OpValues.size() == 3 && "Unexpected number of operands");
8653 SDLoc DL = getCurSDLoc();
8654 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8655 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8656 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8657 const MDNode *Ranges = VPIntrin.getMetadata(KindID: LLVMContext::MD_range);
8658 SDValue LD;
8659 // Do not serialize variable-length loads of constant memory with
8660 // anything.
8661 if (!Alignment)
8662 Alignment = DAG.getEVTAlign(MemoryVT: VT);
8663 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
8664 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
8665 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8666 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8667 PtrInfo: MachinePointerInfo(PtrOperand), F: MachineMemOperand::MOLoad,
8668 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: *Alignment, AAInfo, Ranges);
8669 LD = DAG.getLoadFFVP(VT, DL, Chain: InChain, Ptr: OpValues[0], Mask: OpValues[1], EVL: OpValues[2],
8670 MMO);
8671 SDValue Trunc = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: EVLVT, Operand: LD.getValue(R: 1));
8672 if (AddToChain)
8673 PendingLoads.push_back(Elt: LD.getValue(R: 2));
8674 setValue(V: &VPIntrin, NewN: DAG.getMergeValues(Ops: {LD.getValue(R: 0), Trunc}, dl: DL));
8675}
8676
8677void SelectionDAGBuilder::visitVPGather(
8678 const VPIntrinsic &VPIntrin, EVT VT,
8679 const SmallVectorImpl<SDValue> &OpValues) {
8680 SDLoc DL = getCurSDLoc();
8681 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8682 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8683 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8684 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8685 const MDNode *Ranges = getRangeMetadata(I: VPIntrin);
8686 SDValue LD;
8687 if (!Alignment)
8688 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
8689 unsigned AS =
8690 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8691 MachineMemOperand::Flags MMOFlags =
8692 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8693 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8694 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
8695 BaseAlignment: *Alignment, AAInfo, Ranges);
8696 SDValue Base, Index, Scale;
8697 bool UniformBase =
8698 getUniformBase(Ptr: PtrOperand, Base, Index, Scale, SDB: this, CurBB: VPIntrin.getParent(),
8699 ElemSize: VT.getScalarStoreSize());
8700 if (!UniformBase) {
8701 Base = DAG.getConstant(Val: 0, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8702 Index = getValue(V: PtrOperand);
8703 Scale = DAG.getTargetConstant(Val: 1, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8704 }
8705 EVT IdxVT = Index.getValueType();
8706 EVT EltTy = IdxVT.getVectorElementType();
8707 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
8708 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
8709 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT: NewIdxVT, Operand: Index);
8710 }
8711 LD = DAG.getGatherVP(
8712 VTs: DAG.getVTList(VT1: VT, VT2: MVT::Other), VT, dl: DL,
8713 Ops: {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8714 IndexType: ISD::SIGNED_SCALED);
8715 PendingLoads.push_back(Elt: LD.getValue(R: 1));
8716 setValue(V: &VPIntrin, NewN: LD);
8717}
8718
8719void SelectionDAGBuilder::visitVPStore(
8720 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8721 SDLoc DL = getCurSDLoc();
8722 Value *PtrOperand = VPIntrin.getArgOperand(i: 1);
8723 EVT VT = OpValues[0].getValueType();
8724 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8725 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8726 SDValue ST;
8727 if (!Alignment)
8728 Alignment = DAG.getEVTAlign(MemoryVT: VT);
8729 SDValue Ptr = OpValues[1];
8730 SDValue Offset = DAG.getUNDEF(VT: Ptr.getValueType());
8731 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8732 MachineMemOperand::Flags MMOFlags =
8733 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8734 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8735 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
8736 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: *Alignment, AAInfo);
8737 ST = DAG.getStoreVP(Chain: getMemoryRoot(), dl: DL, Val: OpValues[0], Ptr, Offset,
8738 Mask: OpValues[2], EVL: OpValues[3], MemVT: VT, MMO, AM: ISD::UNINDEXED,
8739 /* IsTruncating */ false, /*IsCompressing*/ false);
8740 DAG.setRoot(ST);
8741 setValue(V: &VPIntrin, NewN: ST);
8742}
8743
8744void SelectionDAGBuilder::visitVPScatter(
8745 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8746 SDLoc DL = getCurSDLoc();
8747 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8748 Value *PtrOperand = VPIntrin.getArgOperand(i: 1);
8749 EVT VT = OpValues[0].getValueType();
8750 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8751 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8752 SDValue ST;
8753 if (!Alignment)
8754 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
8755 unsigned AS =
8756 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8757 MachineMemOperand::Flags MMOFlags =
8758 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8759 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8760 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
8761 BaseAlignment: *Alignment, AAInfo);
8762 SDValue Base, Index, Scale;
8763 bool UniformBase =
8764 getUniformBase(Ptr: PtrOperand, Base, Index, Scale, SDB: this, CurBB: VPIntrin.getParent(),
8765 ElemSize: VT.getScalarStoreSize());
8766 if (!UniformBase) {
8767 Base = DAG.getConstant(Val: 0, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8768 Index = getValue(V: PtrOperand);
8769 Scale = DAG.getTargetConstant(Val: 1, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8770 }
8771 EVT IdxVT = Index.getValueType();
8772 EVT EltTy = IdxVT.getVectorElementType();
8773 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
8774 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
8775 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT: NewIdxVT, Operand: Index);
8776 }
8777 ST = DAG.getScatterVP(VTs: DAG.getVTList(VT: MVT::Other), VT, dl: DL,
8778 Ops: {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8779 OpValues[2], OpValues[3]},
8780 MMO, IndexType: ISD::SIGNED_SCALED);
8781 DAG.setRoot(ST);
8782 setValue(V: &VPIntrin, NewN: ST);
8783}
8784
8785void SelectionDAGBuilder::visitVPStridedLoad(
8786 const VPIntrinsic &VPIntrin, EVT VT,
8787 const SmallVectorImpl<SDValue> &OpValues) {
8788 SDLoc DL = getCurSDLoc();
8789 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8790 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8791 if (!Alignment)
8792 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
8793 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8794 const MDNode *Ranges = getRangeMetadata(I: VPIntrin);
8795 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
8796 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
8797 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8798 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8799 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8800 MachineMemOperand::Flags MMOFlags =
8801 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8802 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8803 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
8804 BaseAlignment: *Alignment, AAInfo, Ranges);
8805
8806 SDValue LD = DAG.getStridedLoadVP(VT, DL, Chain: InChain, Ptr: OpValues[0], Stride: OpValues[1],
8807 Mask: OpValues[2], EVL: OpValues[3], MMO,
8808 IsExpanding: false /*IsExpanding*/);
8809
8810 if (AddToChain)
8811 PendingLoads.push_back(Elt: LD.getValue(R: 1));
8812 setValue(V: &VPIntrin, NewN: LD);
8813}
8814
8815void SelectionDAGBuilder::visitVPStridedStore(
8816 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8817 SDLoc DL = getCurSDLoc();
8818 Value *PtrOperand = VPIntrin.getArgOperand(i: 1);
8819 EVT VT = OpValues[0].getValueType();
8820 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8821 if (!Alignment)
8822 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
8823 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8824 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8825 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8826 MachineMemOperand::Flags MMOFlags =
8827 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8828 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8829 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
8830 BaseAlignment: *Alignment, AAInfo);
8831
8832 SDValue ST = DAG.getStridedStoreVP(
8833 Chain: getMemoryRoot(), DL, Val: OpValues[0], Ptr: OpValues[1],
8834 Offset: DAG.getUNDEF(VT: OpValues[1].getValueType()), Stride: OpValues[2], Mask: OpValues[3],
8835 EVL: OpValues[4], MemVT: VT, MMO, AM: ISD::UNINDEXED, /*IsTruncating*/ false,
8836 /*IsCompressing*/ false);
8837
8838 DAG.setRoot(ST);
8839 setValue(V: &VPIntrin, NewN: ST);
8840}
8841
8842void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8843 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8844 SDLoc DL = getCurSDLoc();
8845
8846 ISD::CondCode Condition;
8847 CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8848 bool IsFP = VPIntrin.getOperand(i_nocapture: 0)->getType()->isFPOrFPVectorTy();
8849 Condition = IsFP ? getFCmpCondCode(Pred: CondCode) : getICmpCondCode(Pred: CondCode);
8850
8851 SDValue Op1 = getValue(V: VPIntrin.getOperand(i_nocapture: 0));
8852 SDValue Op2 = getValue(V: VPIntrin.getOperand(i_nocapture: 1));
8853 // #2 is the condition code
8854 SDValue MaskOp = getValue(V: VPIntrin.getOperand(i_nocapture: 3));
8855 SDValue EVL = getValue(V: VPIntrin.getOperand(i_nocapture: 4));
8856 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8857 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8858 "Unexpected target EVL type");
8859 EVL = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL, VT: EVLParamVT, Operand: EVL);
8860
8861 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
8862 Ty: VPIntrin.getType());
8863 if (DAG.isKnownNeverNaN(Op: Op1) && DAG.isKnownNeverNaN(Op: Op2))
8864 Condition = getFCmpCodeWithoutNaN(CC: Condition);
8865 setValue(V: &VPIntrin,
8866 NewN: DAG.getSetCCVP(DL, VT: DestVT, LHS: Op1, RHS: Op2, Cond: Condition, Mask: MaskOp, EVL));
8867}
8868
8869void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8870 const VPIntrinsic &VPIntrin) {
8871 SDLoc DL = getCurSDLoc();
8872 unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8873
8874 auto IID = VPIntrin.getIntrinsicID();
8875
8876 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(Val: &VPIntrin))
8877 return visitVPCmp(VPIntrin: *CmpI);
8878
8879 SmallVector<EVT, 4> ValueVTs;
8880 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8881 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: VPIntrin.getType(), ValueVTs);
8882 SDVTList VTs = DAG.getVTList(VTs: ValueVTs);
8883
8884 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IntrinsicID: IID);
8885
8886 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8887 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8888 "Unexpected target EVL type");
8889
8890 // Request operands.
8891 SmallVector<SDValue, 7> OpValues;
8892 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8893 auto Op = getValue(V: VPIntrin.getArgOperand(i: I));
8894 if (I == EVLParamPos)
8895 Op = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL, VT: EVLParamVT, Operand: Op);
8896 OpValues.push_back(Elt: Op);
8897 }
8898
8899 switch (Opcode) {
8900 default: {
8901 SDNodeFlags SDFlags;
8902 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &VPIntrin))
8903 SDFlags.copyFMF(FPMO: *FPMO);
8904 SDValue Result = DAG.getNode(Opcode, DL, VTList: VTs, Ops: OpValues, Flags: SDFlags);
8905 setValue(V: &VPIntrin, NewN: Result);
8906 break;
8907 }
8908 case ISD::VP_LOAD:
8909 visitVPLoad(VPIntrin, VT: ValueVTs[0], OpValues);
8910 break;
8911 case ISD::VP_LOAD_FF:
8912 visitVPLoadFF(VPIntrin, VT: ValueVTs[0], EVLVT: ValueVTs[1], OpValues);
8913 break;
8914 case ISD::VP_GATHER:
8915 visitVPGather(VPIntrin, VT: ValueVTs[0], OpValues);
8916 break;
8917 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8918 visitVPStridedLoad(VPIntrin, VT: ValueVTs[0], OpValues);
8919 break;
8920 case ISD::VP_STORE:
8921 visitVPStore(VPIntrin, OpValues);
8922 break;
8923 case ISD::VP_SCATTER:
8924 visitVPScatter(VPIntrin, OpValues);
8925 break;
8926 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8927 visitVPStridedStore(VPIntrin, OpValues);
8928 break;
8929 case ISD::VP_FMULADD: {
8930 assert(OpValues.size() == 5 && "Unexpected number of operands");
8931 SDNodeFlags SDFlags;
8932 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &VPIntrin))
8933 SDFlags.copyFMF(FPMO: *FPMO);
8934 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8935 TLI.isFMAFasterThanFMulAndFAdd(MF: DAG.getMachineFunction(), ValueVTs[0])) {
8936 setValue(V: &VPIntrin, NewN: DAG.getNode(Opcode: ISD::VP_FMA, DL, VTList: VTs, Ops: OpValues, Flags: SDFlags));
8937 } else {
8938 SDValue Mul = DAG.getNode(
8939 Opcode: ISD::VP_FMUL, DL, VTList: VTs,
8940 Ops: {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, Flags: SDFlags);
8941 SDValue Add =
8942 DAG.getNode(Opcode: ISD::VP_FADD, DL, VTList: VTs,
8943 Ops: {Mul, OpValues[2], OpValues[3], OpValues[4]}, Flags: SDFlags);
8944 setValue(V: &VPIntrin, NewN: Add);
8945 }
8946 break;
8947 }
8948 case ISD::VP_IS_FPCLASS: {
8949 const DataLayout DLayout = DAG.getDataLayout();
8950 EVT DestVT = TLI.getValueType(DL: DLayout, Ty: VPIntrin.getType());
8951 auto Constant = OpValues[1]->getAsZExtVal();
8952 SDValue Check = DAG.getTargetConstant(Val: Constant, DL, VT: MVT::i32);
8953 SDValue V = DAG.getNode(Opcode: ISD::VP_IS_FPCLASS, DL, VT: DestVT,
8954 Ops: {OpValues[0], Check, OpValues[2], OpValues[3]});
8955 setValue(V: &VPIntrin, NewN: V);
8956 return;
8957 }
8958 case ISD::VP_INTTOPTR: {
8959 SDValue N = OpValues[0];
8960 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: VPIntrin.getType());
8961 EVT PtrMemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: VPIntrin.getType());
8962 N = DAG.getVPPtrExtOrTrunc(DL: getCurSDLoc(), VT: DestVT, Op: N, Mask: OpValues[1],
8963 EVL: OpValues[2]);
8964 N = DAG.getVPZExtOrTrunc(DL: getCurSDLoc(), VT: PtrMemVT, Op: N, Mask: OpValues[1],
8965 EVL: OpValues[2]);
8966 setValue(V: &VPIntrin, NewN: N);
8967 break;
8968 }
8969 case ISD::VP_PTRTOINT: {
8970 SDValue N = OpValues[0];
8971 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
8972 Ty: VPIntrin.getType());
8973 EVT PtrMemVT = TLI.getMemValueType(DL: DAG.getDataLayout(),
8974 Ty: VPIntrin.getOperand(i_nocapture: 0)->getType());
8975 N = DAG.getVPPtrExtOrTrunc(DL: getCurSDLoc(), VT: PtrMemVT, Op: N, Mask: OpValues[1],
8976 EVL: OpValues[2]);
8977 N = DAG.getVPZExtOrTrunc(DL: getCurSDLoc(), VT: DestVT, Op: N, Mask: OpValues[1],
8978 EVL: OpValues[2]);
8979 setValue(V: &VPIntrin, NewN: N);
8980 break;
8981 }
8982 case ISD::VP_ABS:
8983 case ISD::VP_CTLZ:
8984 case ISD::VP_CTLZ_ZERO_UNDEF:
8985 case ISD::VP_CTTZ:
8986 case ISD::VP_CTTZ_ZERO_UNDEF:
8987 case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8988 case ISD::VP_CTTZ_ELTS: {
8989 SDValue Result =
8990 DAG.getNode(Opcode, DL, VTList: VTs, Ops: {OpValues[0], OpValues[2], OpValues[3]});
8991 setValue(V: &VPIntrin, NewN: Result);
8992 break;
8993 }
8994 }
8995}
8996
8997SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8998 const BasicBlock *EHPadBB,
8999 MCSymbol *&BeginLabel) {
9000 MachineFunction &MF = DAG.getMachineFunction();
9001
9002 // Insert a label before the invoke call to mark the try range. This can be
9003 // used to detect deletion of the invoke via the MachineModuleInfo.
9004 BeginLabel = MF.getContext().createTempSymbol();
9005
9006 // For SjLj, keep track of which landing pads go with which invokes
9007 // so as to maintain the ordering of pads in the LSDA.
9008 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
9009 if (CallSiteIndex) {
9010 MF.setCallSiteBeginLabel(BeginLabel, Site: CallSiteIndex);
9011 LPadToCallSiteMap[FuncInfo.getMBB(BB: EHPadBB)].push_back(Elt: CallSiteIndex);
9012
9013 // Now that the call site is handled, stop tracking it.
9014 FuncInfo.setCurrentCallSite(0);
9015 }
9016
9017 return DAG.getEHLabel(dl: getCurSDLoc(), Root: Chain, Label: BeginLabel);
9018}
9019
9020SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
9021 const BasicBlock *EHPadBB,
9022 MCSymbol *BeginLabel) {
9023 assert(BeginLabel && "BeginLabel should've been set");
9024
9025 MachineFunction &MF = DAG.getMachineFunction();
9026
9027 // Insert a label at the end of the invoke call to mark the try range. This
9028 // can be used to detect deletion of the invoke via the MachineModuleInfo.
9029 MCSymbol *EndLabel = MF.getContext().createTempSymbol();
9030 Chain = DAG.getEHLabel(dl: getCurSDLoc(), Root: Chain, Label: EndLabel);
9031
9032 // Inform MachineModuleInfo of range.
9033 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
9034 // There is a platform (e.g. wasm) that uses funclet style IR but does not
9035 // actually use outlined funclets and their LSDA info style.
9036 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
9037 assert(II && "II should've been set");
9038 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
9039 EHInfo->addIPToStateRange(II, InvokeBegin: BeginLabel, InvokeEnd: EndLabel);
9040 } else if (!isScopedEHPersonality(Pers)) {
9041 assert(EHPadBB);
9042 MF.addInvoke(LandingPad: FuncInfo.getMBB(BB: EHPadBB), BeginLabel, EndLabel);
9043 }
9044
9045 return Chain;
9046}
9047
9048std::pair<SDValue, SDValue>
9049SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
9050 const BasicBlock *EHPadBB) {
9051 MCSymbol *BeginLabel = nullptr;
9052
9053 if (EHPadBB) {
9054 // Both PendingLoads and PendingExports must be flushed here;
9055 // this call might not return.
9056 (void)getRoot();
9057 DAG.setRoot(lowerStartEH(Chain: getControlRoot(), EHPadBB, BeginLabel));
9058 CLI.setChain(getRoot());
9059 }
9060
9061 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9062 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
9063
9064 assert((CLI.IsTailCall || Result.second.getNode()) &&
9065 "Non-null chain expected with non-tail call!");
9066 assert((Result.second.getNode() || !Result.first.getNode()) &&
9067 "Null value expected with tail call!");
9068
9069 if (!Result.second.getNode()) {
9070 // As a special case, a null chain means that a tail call has been emitted
9071 // and the DAG root is already updated.
9072 HasTailCall = true;
9073
9074 // Since there's no actual continuation from this block, nothing can be
9075 // relying on us setting vregs for them.
9076 PendingExports.clear();
9077 } else {
9078 DAG.setRoot(Result.second);
9079 }
9080
9081 if (EHPadBB) {
9082 DAG.setRoot(lowerEndEH(Chain: getRoot(), II: cast_or_null<InvokeInst>(Val: CLI.CB), EHPadBB,
9083 BeginLabel));
9084 Result.second = getRoot();
9085 }
9086
9087 return Result;
9088}
9089
9090bool SelectionDAGBuilder::canTailCall(const CallBase &CB) const {
9091 bool isMustTailCall = CB.isMustTailCall();
9092
9093 // Avoid emitting tail calls in functions with the disable-tail-calls
9094 // attribute.
9095 const Function *Caller = CB.getParent()->getParent();
9096 if (!isMustTailCall &&
9097 Caller->getFnAttribute(Kind: "disable-tail-calls").getValueAsBool())
9098 return false;
9099
9100 // We can't tail call inside a function with a swifterror argument. Lowering
9101 // does not support this yet. It would have to move into the swifterror
9102 // register before the call.
9103 if (DAG.getTargetLoweringInfo().supportSwiftError() &&
9104 Caller->getAttributes().hasAttrSomewhere(Kind: Attribute::SwiftError))
9105 return false;
9106
9107 // Check if target-independent constraints permit a tail call here.
9108 // Target-dependent constraints are checked within TLI->LowerCallTo.
9109 return isInTailCallPosition(Call: CB, TM: DAG.getTarget());
9110}
9111
9112void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
9113 bool isTailCall, bool isMustTailCall,
9114 const BasicBlock *EHPadBB,
9115 const TargetLowering::PtrAuthInfo *PAI) {
9116 auto &DL = DAG.getDataLayout();
9117 FunctionType *FTy = CB.getFunctionType();
9118 Type *RetTy = CB.getType();
9119
9120 TargetLowering::ArgListTy Args;
9121 Args.reserve(n: CB.arg_size());
9122
9123 const Value *SwiftErrorVal = nullptr;
9124 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9125
9126 if (isTailCall)
9127 isTailCall = canTailCall(CB);
9128
9129 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
9130 const Value *V = *I;
9131
9132 // Skip empty types
9133 if (V->getType()->isEmptyTy())
9134 continue;
9135
9136 SDValue ArgNode = getValue(V);
9137 TargetLowering::ArgListEntry Entry(ArgNode, V->getType());
9138 Entry.setAttributes(Call: &CB, ArgIdx: I - CB.arg_begin());
9139
9140 // Use swifterror virtual register as input to the call.
9141 if (Entry.IsSwiftError && TLI.supportSwiftError()) {
9142 SwiftErrorVal = V;
9143 // We find the virtual register for the actual swifterror argument.
9144 // Instead of using the Value, we use the virtual register instead.
9145 Entry.Node =
9146 DAG.getRegister(Reg: SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
9147 VT: EVT(TLI.getPointerTy(DL)));
9148 }
9149
9150 Args.push_back(x: Entry);
9151
9152 // If we have an explicit sret argument that is an Instruction, (i.e., it
9153 // might point to function-local memory), we can't meaningfully tail-call.
9154 if (Entry.IsSRet && isa<Instruction>(Val: V))
9155 isTailCall = false;
9156 }
9157
9158 // If call site has a cfguardtarget operand bundle, create and add an
9159 // additional ArgListEntry.
9160 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_cfguardtarget)) {
9161 Value *V = Bundle->Inputs[0];
9162 TargetLowering::ArgListEntry Entry(V, getValue(V));
9163 Entry.IsCFGuardTarget = true;
9164 Args.push_back(x: Entry);
9165 }
9166
9167 // Disable tail calls if there is an swifterror argument. Targets have not
9168 // been updated to support tail calls.
9169 if (TLI.supportSwiftError() && SwiftErrorVal)
9170 isTailCall = false;
9171
9172 ConstantInt *CFIType = nullptr;
9173 if (CB.isIndirectCall()) {
9174 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_kcfi)) {
9175 if (!TLI.supportKCFIBundles())
9176 report_fatal_error(
9177 reason: "Target doesn't support calls with kcfi operand bundles.");
9178 CFIType = cast<ConstantInt>(Val: Bundle->Inputs[0]);
9179 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
9180 }
9181 }
9182
9183 SDValue ConvControlToken;
9184 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_convergencectrl)) {
9185 auto *Token = Bundle->Inputs[0].get();
9186 ConvControlToken = getValue(V: Token);
9187 }
9188
9189 GlobalValue *DeactivationSymbol = nullptr;
9190 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_deactivation_symbol)) {
9191 DeactivationSymbol = cast<GlobalValue>(Val: Bundle->Inputs[0].get());
9192 }
9193
9194 TargetLowering::CallLoweringInfo CLI(DAG);
9195 CLI.setDebugLoc(getCurSDLoc())
9196 .setChain(getRoot())
9197 .setCallee(ResultType: RetTy, FTy, Target: Callee, ArgsList: std::move(Args), Call: CB)
9198 .setTailCall(isTailCall)
9199 .setConvergent(CB.isConvergent())
9200 .setIsPreallocated(
9201 CB.countOperandBundlesOfType(ID: LLVMContext::OB_preallocated) != 0)
9202 .setCFIType(CFIType)
9203 .setConvergenceControlToken(ConvControlToken)
9204 .setDeactivationSymbol(DeactivationSymbol);
9205
9206 // Set the pointer authentication info if we have it.
9207 if (PAI) {
9208 if (!TLI.supportPtrAuthBundles())
9209 report_fatal_error(
9210 reason: "This target doesn't support calls with ptrauth operand bundles.");
9211 CLI.setPtrAuth(*PAI);
9212 }
9213
9214 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9215
9216 if (Result.first.getNode()) {
9217 Result.first = lowerRangeToAssertZExt(DAG, I: CB, Op: Result.first);
9218 Result.first = lowerNoFPClassToAssertNoFPClass(DAG, I: CB, Op: Result.first);
9219 setValue(V: &CB, NewN: Result.first);
9220 }
9221
9222 // The last element of CLI.InVals has the SDValue for swifterror return.
9223 // Here we copy it to a virtual register and update SwiftErrorMap for
9224 // book-keeping.
9225 if (SwiftErrorVal && TLI.supportSwiftError()) {
9226 // Get the last element of InVals.
9227 SDValue Src = CLI.InVals.back();
9228 Register VReg =
9229 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
9230 SDValue CopyNode = CLI.DAG.getCopyToReg(Chain: Result.second, dl: CLI.DL, Reg: VReg, N: Src);
9231 DAG.setRoot(CopyNode);
9232 }
9233}
9234
9235static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
9236 SelectionDAGBuilder &Builder) {
9237 // Check to see if this load can be trivially constant folded, e.g. if the
9238 // input is from a string literal.
9239 if (const Constant *LoadInput = dyn_cast<Constant>(Val: PtrVal)) {
9240 // Cast pointer to the type we really want to load.
9241 Type *LoadTy =
9242 Type::getIntNTy(C&: PtrVal->getContext(), N: LoadVT.getScalarSizeInBits());
9243 if (LoadVT.isVector())
9244 LoadTy = FixedVectorType::get(ElementType: LoadTy, NumElts: LoadVT.getVectorNumElements());
9245 if (const Constant *LoadCst =
9246 ConstantFoldLoadFromConstPtr(C: const_cast<Constant *>(LoadInput),
9247 Ty: LoadTy, DL: Builder.DAG.getDataLayout()))
9248 return Builder.getValue(V: LoadCst);
9249 }
9250
9251 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
9252 // still constant memory, the input chain can be the entry node.
9253 SDValue Root;
9254 bool ConstantMemory = false;
9255
9256 // Do not serialize (non-volatile) loads of constant memory with anything.
9257 if (Builder.BatchAA && Builder.BatchAA->pointsToConstantMemory(P: PtrVal)) {
9258 Root = Builder.DAG.getEntryNode();
9259 ConstantMemory = true;
9260 } else {
9261 // Do not serialize non-volatile loads against each other.
9262 Root = Builder.DAG.getRoot();
9263 }
9264
9265 SDValue Ptr = Builder.getValue(V: PtrVal);
9266 SDValue LoadVal =
9267 Builder.DAG.getLoad(VT: LoadVT, dl: Builder.getCurSDLoc(), Chain: Root, Ptr,
9268 PtrInfo: MachinePointerInfo(PtrVal), Alignment: Align(1));
9269
9270 if (!ConstantMemory)
9271 Builder.PendingLoads.push_back(Elt: LoadVal.getValue(R: 1));
9272 return LoadVal;
9273}
9274
9275/// Record the value for an instruction that produces an integer result,
9276/// converting the type where necessary.
9277void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
9278 SDValue Value,
9279 bool IsSigned) {
9280 EVT VT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
9281 Ty: I.getType(), AllowUnknown: true);
9282 Value = DAG.getExtOrTrunc(IsSigned, Op: Value, DL: getCurSDLoc(), VT);
9283 setValue(V: &I, NewN: Value);
9284}
9285
9286/// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
9287/// true and lower it. Otherwise return false, and it will be lowered like a
9288/// normal call.
9289/// The caller already checked that \p I calls the appropriate LibFunc with a
9290/// correct prototype.
9291bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
9292 const Value *LHS = I.getArgOperand(i: 0), *RHS = I.getArgOperand(i: 1);
9293 const Value *Size = I.getArgOperand(i: 2);
9294 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(Val: getValue(V: Size));
9295 if (CSize && CSize->getZExtValue() == 0) {
9296 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
9297 Ty: I.getType(), AllowUnknown: true);
9298 setValue(V: &I, NewN: DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: CallVT));
9299 return true;
9300 }
9301
9302 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9303 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9304 DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(), Op1: getValue(V: LHS), Op2: getValue(V: RHS),
9305 Op3: getValue(V: Size), CI: &I);
9306 if (Res.first.getNode()) {
9307 processIntegerCallValue(I, Value: Res.first, IsSigned: true);
9308 PendingLoads.push_back(Elt: Res.second);
9309 return true;
9310 }
9311
9312 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
9313 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
9314 if (!CSize || !isOnlyUsedInZeroEqualityComparison(CxtI: &I))
9315 return false;
9316
9317 // If the target has a fast compare for the given size, it will return a
9318 // preferred load type for that size. Require that the load VT is legal and
9319 // that the target supports unaligned loads of that type. Otherwise, return
9320 // INVALID.
9321 auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9322 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9323 MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9324 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9325 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9326 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9327 // TODO: Check alignment of src and dest ptrs.
9328 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9329 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9330 if (!TLI.isTypeLegal(VT: LVT) ||
9331 !TLI.allowsMisalignedMemoryAccesses(LVT, AddrSpace: SrcAS) ||
9332 !TLI.allowsMisalignedMemoryAccesses(LVT, AddrSpace: DstAS))
9333 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
9334 }
9335
9336 return LVT;
9337 };
9338
9339 // This turns into unaligned loads. We only do this if the target natively
9340 // supports the MVT we'll be loading or if it is small enough (<= 4) that
9341 // we'll only produce a small number of byte loads.
9342 MVT LoadVT;
9343 unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9344 switch (NumBitsToCompare) {
9345 default:
9346 return false;
9347 case 16:
9348 LoadVT = MVT::i16;
9349 break;
9350 case 32:
9351 LoadVT = MVT::i32;
9352 break;
9353 case 64:
9354 case 128:
9355 case 256:
9356 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9357 break;
9358 }
9359
9360 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9361 return false;
9362
9363 SDValue LoadL = getMemCmpLoad(PtrVal: LHS, LoadVT, Builder&: *this);
9364 SDValue LoadR = getMemCmpLoad(PtrVal: RHS, LoadVT, Builder&: *this);
9365
9366 // Bitcast to a wide integer type if the loads are vectors.
9367 if (LoadVT.isVector()) {
9368 EVT CmpVT = EVT::getIntegerVT(Context&: LHS->getContext(), BitWidth: LoadVT.getSizeInBits());
9369 LoadL = DAG.getBitcast(VT: CmpVT, V: LoadL);
9370 LoadR = DAG.getBitcast(VT: CmpVT, V: LoadR);
9371 }
9372
9373 SDValue Cmp = DAG.getSetCC(DL: getCurSDLoc(), VT: MVT::i1, LHS: LoadL, RHS: LoadR, Cond: ISD::SETNE);
9374 processIntegerCallValue(I, Value: Cmp, IsSigned: false);
9375 return true;
9376}
9377
9378/// See if we can lower a memchr call into an optimized form. If so, return
9379/// true and lower it. Otherwise return false, and it will be lowered like a
9380/// normal call.
9381/// The caller already checked that \p I calls the appropriate LibFunc with a
9382/// correct prototype.
9383bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9384 const Value *Src = I.getArgOperand(i: 0);
9385 const Value *Char = I.getArgOperand(i: 1);
9386 const Value *Length = I.getArgOperand(i: 2);
9387
9388 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9389 std::pair<SDValue, SDValue> Res =
9390 TSI.EmitTargetCodeForMemchr(DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(),
9391 Src: getValue(V: Src), Char: getValue(V: Char), Length: getValue(V: Length),
9392 SrcPtrInfo: MachinePointerInfo(Src));
9393 if (Res.first.getNode()) {
9394 setValue(V: &I, NewN: Res.first);
9395 PendingLoads.push_back(Elt: Res.second);
9396 return true;
9397 }
9398
9399 return false;
9400}
9401
9402/// See if we can lower a mempcpy call into an optimized form. If so, return
9403/// true and lower it. Otherwise return false, and it will be lowered like a
9404/// normal call.
9405/// The caller already checked that \p I calls the appropriate LibFunc with a
9406/// correct prototype.
9407bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9408 SDValue Dst = getValue(V: I.getArgOperand(i: 0));
9409 SDValue Src = getValue(V: I.getArgOperand(i: 1));
9410 SDValue Size = getValue(V: I.getArgOperand(i: 2));
9411
9412 Align DstAlign = DAG.InferPtrAlign(Ptr: Dst).valueOrOne();
9413 Align SrcAlign = DAG.InferPtrAlign(Ptr: Src).valueOrOne();
9414 // DAG::getMemcpy needs Alignment to be defined.
9415 Align Alignment = std::min(a: DstAlign, b: SrcAlign);
9416
9417 SDLoc sdl = getCurSDLoc();
9418
9419 // In the mempcpy context we need to pass in a false value for isTailCall
9420 // because the return pointer needs to be adjusted by the size of
9421 // the copied memory.
9422 SDValue Root = getMemoryRoot();
9423 SDValue MC = DAG.getMemcpy(
9424 Chain: Root, dl: sdl, Dst, Src, Size, Alignment, isVol: false, AlwaysInline: false, /*CI=*/nullptr,
9425 OverrideTailCall: std::nullopt, DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
9426 SrcPtrInfo: MachinePointerInfo(I.getArgOperand(i: 1)), AAInfo: I.getAAMetadata());
9427 assert(MC.getNode() != nullptr &&
9428 "** memcpy should not be lowered as TailCall in mempcpy context **");
9429 DAG.setRoot(MC);
9430
9431 // Check if Size needs to be truncated or extended.
9432 Size = DAG.getSExtOrTrunc(Op: Size, DL: sdl, VT: Dst.getValueType());
9433
9434 // Adjust return pointer to point just past the last dst byte.
9435 SDValue DstPlusSize = DAG.getMemBasePlusOffset(Base: Dst, Offset: Size, DL: sdl);
9436 setValue(V: &I, NewN: DstPlusSize);
9437 return true;
9438}
9439
9440/// See if we can lower a strcpy call into an optimized form. If so, return
9441/// true and lower it, otherwise return false and it will be lowered like a
9442/// normal call.
9443/// The caller already checked that \p I calls the appropriate LibFunc with a
9444/// correct prototype.
9445bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9446 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9447
9448 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9449 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcpy(
9450 DAG, DL: getCurSDLoc(), Chain: getRoot(), Dest: getValue(V: Arg0), Src: getValue(V: Arg1),
9451 DestPtrInfo: MachinePointerInfo(Arg0), SrcPtrInfo: MachinePointerInfo(Arg1), isStpcpy, CI: &I);
9452 if (Res.first.getNode()) {
9453 setValue(V: &I, NewN: Res.first);
9454 DAG.setRoot(Res.second);
9455 return true;
9456 }
9457
9458 return false;
9459}
9460
9461/// See if we can lower a strcmp call into an optimized form. If so, return
9462/// true and lower it, otherwise return false and it will be lowered like a
9463/// normal call.
9464/// The caller already checked that \p I calls the appropriate LibFunc with a
9465/// correct prototype.
9466bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9467 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9468
9469 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9470 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcmp(
9471 DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(), Op1: getValue(V: Arg0), Op2: getValue(V: Arg1),
9472 Op1PtrInfo: MachinePointerInfo(Arg0), Op2PtrInfo: MachinePointerInfo(Arg1), CI: &I);
9473 if (Res.first.getNode()) {
9474 processIntegerCallValue(I, Value: Res.first, IsSigned: true);
9475 PendingLoads.push_back(Elt: Res.second);
9476 return true;
9477 }
9478
9479 return false;
9480}
9481
9482/// See if we can lower a strlen call into an optimized form. If so, return
9483/// true and lower it, otherwise return false and it will be lowered like a
9484/// normal call.
9485/// The caller already checked that \p I calls the appropriate LibFunc with a
9486/// correct prototype.
9487bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9488 const Value *Arg0 = I.getArgOperand(i: 0);
9489
9490 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9491 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrlen(
9492 DAG, DL: getCurSDLoc(), Chain: DAG.getRoot(), Src: getValue(V: Arg0), CI: &I);
9493 if (Res.first.getNode()) {
9494 processIntegerCallValue(I, Value: Res.first, IsSigned: false);
9495 PendingLoads.push_back(Elt: Res.second);
9496 return true;
9497 }
9498
9499 return false;
9500}
9501
9502/// See if we can lower a strnlen call into an optimized form. If so, return
9503/// true and lower it, otherwise return false and it will be lowered like a
9504/// normal call.
9505/// The caller already checked that \p I calls the appropriate LibFunc with a
9506/// correct prototype.
9507bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9508 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9509
9510 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9511 std::pair<SDValue, SDValue> Res =
9512 TSI.EmitTargetCodeForStrnlen(DAG, DL: getCurSDLoc(), Chain: DAG.getRoot(),
9513 Src: getValue(V: Arg0), MaxLength: getValue(V: Arg1),
9514 SrcPtrInfo: MachinePointerInfo(Arg0));
9515 if (Res.first.getNode()) {
9516 processIntegerCallValue(I, Value: Res.first, IsSigned: false);
9517 PendingLoads.push_back(Elt: Res.second);
9518 return true;
9519 }
9520
9521 return false;
9522}
9523
9524/// See if we can lower a Strstr call into an optimized form. If so, return
9525/// true and lower it, otherwise return false and it will be lowered like a
9526/// normal call.
9527/// The caller already checked that \p I calls the appropriate LibFunc with a
9528/// correct prototype.
9529bool SelectionDAGBuilder::visitStrstrCall(const CallInst &I) {
9530 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9531 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9532 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrstr(
9533 DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(), Op1: getValue(V: Arg0), Op2: getValue(V: Arg1), CI: &I);
9534 if (Res.first) {
9535 processIntegerCallValue(I, Value: Res.first, IsSigned: false);
9536 PendingLoads.push_back(Elt: Res.second);
9537 return true;
9538 }
9539 return false;
9540}
9541
9542/// See if we can lower a unary floating-point operation into an SDNode with
9543/// the specified Opcode. If so, return true and lower it, otherwise return
9544/// false and it will be lowered like a normal call.
9545/// The caller already checked that \p I calls the appropriate LibFunc with a
9546/// correct prototype.
9547bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9548 unsigned Opcode) {
9549 // We already checked this call's prototype; verify it doesn't modify errno.
9550 // Do not perform optimizations for call sites that require strict
9551 // floating-point semantics.
9552 if (!I.onlyReadsMemory() || I.isStrictFP())
9553 return false;
9554
9555 SDNodeFlags Flags;
9556 Flags.copyFMF(FPMO: cast<FPMathOperator>(Val: I));
9557
9558 SDValue Tmp = getValue(V: I.getArgOperand(i: 0));
9559 setValue(V: &I,
9560 NewN: DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Tmp.getValueType(), Operand: Tmp, Flags));
9561 return true;
9562}
9563
9564/// See if we can lower a binary floating-point operation into an SDNode with
9565/// the specified Opcode. If so, return true and lower it. Otherwise return
9566/// false, and it will be lowered like a normal call.
9567/// The caller already checked that \p I calls the appropriate LibFunc with a
9568/// correct prototype.
9569bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9570 unsigned Opcode) {
9571 // We already checked this call's prototype; verify it doesn't modify errno.
9572 // Do not perform optimizations for call sites that require strict
9573 // floating-point semantics.
9574 if (!I.onlyReadsMemory() || I.isStrictFP())
9575 return false;
9576
9577 SDNodeFlags Flags;
9578 Flags.copyFMF(FPMO: cast<FPMathOperator>(Val: I));
9579
9580 SDValue Tmp0 = getValue(V: I.getArgOperand(i: 0));
9581 SDValue Tmp1 = getValue(V: I.getArgOperand(i: 1));
9582 EVT VT = Tmp0.getValueType();
9583 setValue(V: &I, NewN: DAG.getNode(Opcode, DL: getCurSDLoc(), VT, N1: Tmp0, N2: Tmp1, Flags));
9584 return true;
9585}
9586
9587void SelectionDAGBuilder::visitCall(const CallInst &I) {
9588 // Handle inline assembly differently.
9589 if (I.isInlineAsm()) {
9590 visitInlineAsm(Call: I);
9591 return;
9592 }
9593
9594 diagnoseDontCall(CI: I);
9595
9596 if (Function *F = I.getCalledFunction()) {
9597 if (F->isDeclaration()) {
9598 // Is this an LLVM intrinsic?
9599 if (unsigned IID = F->getIntrinsicID()) {
9600 visitIntrinsicCall(I, Intrinsic: IID);
9601 return;
9602 }
9603 }
9604
9605 // Check for well-known libc/libm calls. If the function is internal, it
9606 // can't be a library call. Don't do the check if marked as nobuiltin for
9607 // some reason.
9608 // This code should not handle libcalls that are already canonicalized to
9609 // intrinsics by the middle-end.
9610 LibFunc Func;
9611 if (!I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName() &&
9612 LibInfo->getLibFunc(FDecl: *F, F&: Func) && LibInfo->hasOptimizedCodeGen(F: Func)) {
9613 switch (Func) {
9614 default: break;
9615 case LibFunc_bcmp:
9616 if (visitMemCmpBCmpCall(I))
9617 return;
9618 break;
9619 case LibFunc_copysign:
9620 case LibFunc_copysignf:
9621 case LibFunc_copysignl:
9622 // We already checked this call's prototype; verify it doesn't modify
9623 // errno.
9624 if (I.onlyReadsMemory()) {
9625 SDValue LHS = getValue(V: I.getArgOperand(i: 0));
9626 SDValue RHS = getValue(V: I.getArgOperand(i: 1));
9627 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FCOPYSIGN, DL: getCurSDLoc(),
9628 VT: LHS.getValueType(), N1: LHS, N2: RHS));
9629 return;
9630 }
9631 break;
9632 case LibFunc_sin:
9633 case LibFunc_sinf:
9634 case LibFunc_sinl:
9635 if (visitUnaryFloatCall(I, Opcode: ISD::FSIN))
9636 return;
9637 break;
9638 case LibFunc_cos:
9639 case LibFunc_cosf:
9640 case LibFunc_cosl:
9641 if (visitUnaryFloatCall(I, Opcode: ISD::FCOS))
9642 return;
9643 break;
9644 case LibFunc_tan:
9645 case LibFunc_tanf:
9646 case LibFunc_tanl:
9647 if (visitUnaryFloatCall(I, Opcode: ISD::FTAN))
9648 return;
9649 break;
9650 case LibFunc_asin:
9651 case LibFunc_asinf:
9652 case LibFunc_asinl:
9653 if (visitUnaryFloatCall(I, Opcode: ISD::FASIN))
9654 return;
9655 break;
9656 case LibFunc_acos:
9657 case LibFunc_acosf:
9658 case LibFunc_acosl:
9659 if (visitUnaryFloatCall(I, Opcode: ISD::FACOS))
9660 return;
9661 break;
9662 case LibFunc_atan:
9663 case LibFunc_atanf:
9664 case LibFunc_atanl:
9665 if (visitUnaryFloatCall(I, Opcode: ISD::FATAN))
9666 return;
9667 break;
9668 case LibFunc_atan2:
9669 case LibFunc_atan2f:
9670 case LibFunc_atan2l:
9671 if (visitBinaryFloatCall(I, Opcode: ISD::FATAN2))
9672 return;
9673 break;
9674 case LibFunc_sinh:
9675 case LibFunc_sinhf:
9676 case LibFunc_sinhl:
9677 if (visitUnaryFloatCall(I, Opcode: ISD::FSINH))
9678 return;
9679 break;
9680 case LibFunc_cosh:
9681 case LibFunc_coshf:
9682 case LibFunc_coshl:
9683 if (visitUnaryFloatCall(I, Opcode: ISD::FCOSH))
9684 return;
9685 break;
9686 case LibFunc_tanh:
9687 case LibFunc_tanhf:
9688 case LibFunc_tanhl:
9689 if (visitUnaryFloatCall(I, Opcode: ISD::FTANH))
9690 return;
9691 break;
9692 case LibFunc_sqrt:
9693 case LibFunc_sqrtf:
9694 case LibFunc_sqrtl:
9695 case LibFunc_sqrt_finite:
9696 case LibFunc_sqrtf_finite:
9697 case LibFunc_sqrtl_finite:
9698 if (visitUnaryFloatCall(I, Opcode: ISD::FSQRT))
9699 return;
9700 break;
9701 case LibFunc_log2:
9702 case LibFunc_log2f:
9703 case LibFunc_log2l:
9704 if (visitUnaryFloatCall(I, Opcode: ISD::FLOG2))
9705 return;
9706 break;
9707 case LibFunc_exp2:
9708 case LibFunc_exp2f:
9709 case LibFunc_exp2l:
9710 if (visitUnaryFloatCall(I, Opcode: ISD::FEXP2))
9711 return;
9712 break;
9713 case LibFunc_exp10:
9714 case LibFunc_exp10f:
9715 case LibFunc_exp10l:
9716 if (visitUnaryFloatCall(I, Opcode: ISD::FEXP10))
9717 return;
9718 break;
9719 case LibFunc_ldexp:
9720 case LibFunc_ldexpf:
9721 case LibFunc_ldexpl:
9722 if (visitBinaryFloatCall(I, Opcode: ISD::FLDEXP))
9723 return;
9724 break;
9725 case LibFunc_strstr:
9726 if (visitStrstrCall(I))
9727 return;
9728 break;
9729 case LibFunc_memcmp:
9730 if (visitMemCmpBCmpCall(I))
9731 return;
9732 break;
9733 case LibFunc_mempcpy:
9734 if (visitMemPCpyCall(I))
9735 return;
9736 break;
9737 case LibFunc_memchr:
9738 if (visitMemChrCall(I))
9739 return;
9740 break;
9741 case LibFunc_strcpy:
9742 if (visitStrCpyCall(I, isStpcpy: false))
9743 return;
9744 break;
9745 case LibFunc_stpcpy:
9746 if (visitStrCpyCall(I, isStpcpy: true))
9747 return;
9748 break;
9749 case LibFunc_strcmp:
9750 if (visitStrCmpCall(I))
9751 return;
9752 break;
9753 case LibFunc_strlen:
9754 if (visitStrLenCall(I))
9755 return;
9756 break;
9757 case LibFunc_strnlen:
9758 if (visitStrNLenCall(I))
9759 return;
9760 break;
9761 }
9762 }
9763 }
9764
9765 if (I.countOperandBundlesOfType(ID: LLVMContext::OB_ptrauth)) {
9766 LowerCallSiteWithPtrAuthBundle(CB: cast<CallBase>(Val: I), /*EHPadBB=*/nullptr);
9767 return;
9768 }
9769
9770 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9771 // have to do anything here to lower funclet bundles.
9772 // CFGuardTarget bundles are lowered in LowerCallTo.
9773 failForInvalidBundles(
9774 I, Name: "calls",
9775 AllowedBundles: {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9776 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9777 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9778 LLVMContext::OB_convergencectrl, LLVMContext::OB_deactivation_symbol});
9779
9780 SDValue Callee = getValue(V: I.getCalledOperand());
9781
9782 if (I.hasDeoptState())
9783 LowerCallSiteWithDeoptBundle(Call: &I, Callee, EHPadBB: nullptr);
9784 else
9785 // Check if we can potentially perform a tail call. More detailed checking
9786 // is be done within LowerCallTo, after more information about the call is
9787 // known.
9788 LowerCallTo(CB: I, Callee, isTailCall: I.isTailCall(), isMustTailCall: I.isMustTailCall());
9789}
9790
9791void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9792 const CallBase &CB, const BasicBlock *EHPadBB) {
9793 auto PAB = CB.getOperandBundle(Name: "ptrauth");
9794 const Value *CalleeV = CB.getCalledOperand();
9795
9796 // Gather the call ptrauth data from the operand bundle:
9797 // [ i32 <key>, i64 <discriminator> ]
9798 const auto *Key = cast<ConstantInt>(Val: PAB->Inputs[0]);
9799 const Value *Discriminator = PAB->Inputs[1];
9800
9801 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9802 assert(Discriminator->getType()->isIntegerTy(64) &&
9803 "Invalid ptrauth discriminator");
9804
9805 // Look through ptrauth constants to find the raw callee.
9806 // Do a direct unauthenticated call if we found it and everything matches.
9807 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(Val: CalleeV))
9808 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9809 DL: DAG.getDataLayout()))
9810 return LowerCallTo(CB, Callee: getValue(V: CalleeCPA->getPointer()), isTailCall: CB.isTailCall(),
9811 isMustTailCall: CB.isMustTailCall(), EHPadBB);
9812
9813 // Functions should never be ptrauth-called directly.
9814 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9815
9816 // Otherwise, do an authenticated indirect call.
9817 TargetLowering::PtrAuthInfo PAI = {.Key: Key->getZExtValue(),
9818 .Discriminator: getValue(V: Discriminator)};
9819
9820 LowerCallTo(CB, Callee: getValue(V: CalleeV), isTailCall: CB.isTailCall(), isMustTailCall: CB.isMustTailCall(),
9821 EHPadBB, PAI: &PAI);
9822}
9823
9824namespace {
9825
9826/// AsmOperandInfo - This contains information for each constraint that we are
9827/// lowering.
9828class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9829public:
9830 /// CallOperand - If this is the result output operand or a clobber
9831 /// this is null, otherwise it is the incoming operand to the CallInst.
9832 /// This gets modified as the asm is processed.
9833 SDValue CallOperand;
9834
9835 /// AssignedRegs - If this is a register or register class operand, this
9836 /// contains the set of register corresponding to the operand.
9837 RegsForValue AssignedRegs;
9838
9839 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9840 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9841 }
9842
9843 /// Whether or not this operand accesses memory
9844 bool hasMemory(const TargetLowering &TLI) const {
9845 // Indirect operand accesses access memory.
9846 if (isIndirect)
9847 return true;
9848
9849 for (const auto &Code : Codes)
9850 if (TLI.getConstraintType(Constraint: Code) == TargetLowering::C_Memory)
9851 return true;
9852
9853 return false;
9854 }
9855};
9856
9857
9858} // end anonymous namespace
9859
9860/// Make sure that the output operand \p OpInfo and its corresponding input
9861/// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9862/// out).
9863static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9864 SDISelAsmOperandInfo &MatchingOpInfo,
9865 SelectionDAG &DAG) {
9866 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9867 return;
9868
9869 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9870 const auto &TLI = DAG.getTargetLoweringInfo();
9871
9872 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9873 TLI.getRegForInlineAsmConstraint(TRI, Constraint: OpInfo.ConstraintCode,
9874 VT: OpInfo.ConstraintVT);
9875 std::pair<unsigned, const TargetRegisterClass *> InputRC =
9876 TLI.getRegForInlineAsmConstraint(TRI, Constraint: MatchingOpInfo.ConstraintCode,
9877 VT: MatchingOpInfo.ConstraintVT);
9878 const bool OutOpIsIntOrFP =
9879 OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
9880 const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
9881 MatchingOpInfo.ConstraintVT.isFloatingPoint();
9882 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
9883 // FIXME: error out in a more elegant fashion
9884 report_fatal_error(reason: "Unsupported asm: input constraint"
9885 " with a matching output constraint of"
9886 " incompatible type!");
9887 }
9888 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9889}
9890
9891/// Get a direct memory input to behave well as an indirect operand.
9892/// This may introduce stores, hence the need for a \p Chain.
9893/// \return The (possibly updated) chain.
9894static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9895 SDISelAsmOperandInfo &OpInfo,
9896 SelectionDAG &DAG) {
9897 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9898
9899 // If we don't have an indirect input, put it in the constpool if we can,
9900 // otherwise spill it to a stack slot.
9901 // TODO: This isn't quite right. We need to handle these according to
9902 // the addressing mode that the constraint wants. Also, this may take
9903 // an additional register for the computation and we don't want that
9904 // either.
9905
9906 // If the operand is a float, integer, or vector constant, spill to a
9907 // constant pool entry to get its address.
9908 const Value *OpVal = OpInfo.CallOperandVal;
9909 if (isa<ConstantFP>(Val: OpVal) || isa<ConstantInt>(Val: OpVal) ||
9910 isa<ConstantVector>(Val: OpVal) || isa<ConstantDataVector>(Val: OpVal)) {
9911 OpInfo.CallOperand = DAG.getConstantPool(
9912 C: cast<Constant>(Val: OpVal), VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
9913 return Chain;
9914 }
9915
9916 // Otherwise, create a stack slot and emit a store to it before the asm.
9917 Type *Ty = OpVal->getType();
9918 auto &DL = DAG.getDataLayout();
9919 TypeSize TySize = DL.getTypeAllocSize(Ty);
9920 MachineFunction &MF = DAG.getMachineFunction();
9921 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
9922 int StackID = 0;
9923 if (TySize.isScalable())
9924 StackID = TFI->getStackIDForScalableVectors();
9925 int SSFI = MF.getFrameInfo().CreateStackObject(Size: TySize.getKnownMinValue(),
9926 Alignment: DL.getPrefTypeAlign(Ty), isSpillSlot: false,
9927 Alloca: nullptr, ID: StackID);
9928 SDValue StackSlot = DAG.getFrameIndex(FI: SSFI, VT: TLI.getFrameIndexTy(DL));
9929 Chain = DAG.getTruncStore(Chain, dl: Location, Val: OpInfo.CallOperand, Ptr: StackSlot,
9930 PtrInfo: MachinePointerInfo::getFixedStack(MF, FI: SSFI),
9931 SVT: TLI.getMemValueType(DL, Ty));
9932 OpInfo.CallOperand = StackSlot;
9933
9934 return Chain;
9935}
9936
9937/// GetRegistersForValue - Assign registers (virtual or physical) for the
9938/// specified operand. We prefer to assign virtual registers, to allow the
9939/// register allocator to handle the assignment process. However, if the asm
9940/// uses features that we can't model on machineinstrs, we have SDISel do the
9941/// allocation. This produces generally horrible, but correct, code.
9942///
9943/// OpInfo describes the operand
9944/// RefOpInfo describes the matching operand if any, the operand otherwise
9945static std::optional<unsigned>
9946getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9947 SDISelAsmOperandInfo &OpInfo,
9948 SDISelAsmOperandInfo &RefOpInfo) {
9949 LLVMContext &Context = *DAG.getContext();
9950 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9951
9952 MachineFunction &MF = DAG.getMachineFunction();
9953 SmallVector<Register, 4> Regs;
9954 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9955
9956 // No work to do for memory/address operands.
9957 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9958 OpInfo.ConstraintType == TargetLowering::C_Address)
9959 return std::nullopt;
9960
9961 // If this is a constraint for a single physreg, or a constraint for a
9962 // register class, find it.
9963 unsigned AssignedReg;
9964 const TargetRegisterClass *RC;
9965 std::tie(args&: AssignedReg, args&: RC) = TLI.getRegForInlineAsmConstraint(
9966 TRI: &TRI, Constraint: RefOpInfo.ConstraintCode, VT: RefOpInfo.ConstraintVT);
9967 // RC is unset only on failure. Return immediately.
9968 if (!RC)
9969 return std::nullopt;
9970
9971 // Get the actual register value type. This is important, because the user
9972 // may have asked for (e.g.) the AX register in i32 type. We need to
9973 // remember that AX is actually i16 to get the right extension.
9974 const MVT RegVT = *TRI.legalclasstypes_begin(RC: *RC);
9975
9976 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9977 // If this is an FP operand in an integer register (or visa versa), or more
9978 // generally if the operand value disagrees with the register class we plan
9979 // to stick it in, fix the operand type.
9980 //
9981 // If this is an input value, the bitcast to the new type is done now.
9982 // Bitcast for output value is done at the end of visitInlineAsm().
9983 if ((OpInfo.Type == InlineAsm::isOutput ||
9984 OpInfo.Type == InlineAsm::isInput) &&
9985 !TRI.isTypeLegalForClass(RC: *RC, T: OpInfo.ConstraintVT)) {
9986 // Try to convert to the first EVT that the reg class contains. If the
9987 // types are identical size, use a bitcast to convert (e.g. two differing
9988 // vector types). Note: output bitcast is done at the end of
9989 // visitInlineAsm().
9990 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9991 // Exclude indirect inputs while they are unsupported because the code
9992 // to perform the load is missing and thus OpInfo.CallOperand still
9993 // refers to the input address rather than the pointed-to value.
9994 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9995 OpInfo.CallOperand =
9996 DAG.getNode(Opcode: ISD::BITCAST, DL, VT: RegVT, Operand: OpInfo.CallOperand);
9997 OpInfo.ConstraintVT = RegVT;
9998 // If the operand is an FP value and we want it in integer registers,
9999 // use the corresponding integer type. This turns an f64 value into
10000 // i64, which can be passed with two i32 values on a 32-bit machine.
10001 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
10002 MVT VT = MVT::getIntegerVT(BitWidth: OpInfo.ConstraintVT.getSizeInBits());
10003 if (OpInfo.Type == InlineAsm::isInput)
10004 OpInfo.CallOperand =
10005 DAG.getNode(Opcode: ISD::BITCAST, DL, VT, Operand: OpInfo.CallOperand);
10006 OpInfo.ConstraintVT = VT;
10007 }
10008 }
10009 }
10010
10011 // No need to allocate a matching input constraint since the constraint it's
10012 // matching to has already been allocated.
10013 if (OpInfo.isMatchingInputConstraint())
10014 return std::nullopt;
10015
10016 EVT ValueVT = OpInfo.ConstraintVT;
10017 if (OpInfo.ConstraintVT == MVT::Other)
10018 ValueVT = RegVT;
10019
10020 // Initialize NumRegs.
10021 unsigned NumRegs = 1;
10022 if (OpInfo.ConstraintVT != MVT::Other)
10023 NumRegs = TLI.getNumRegisters(Context, VT: OpInfo.ConstraintVT, RegisterVT: RegVT);
10024
10025 // If this is a constraint for a specific physical register, like {r17},
10026 // assign it now.
10027
10028 // If this associated to a specific register, initialize iterator to correct
10029 // place. If virtual, make sure we have enough registers
10030
10031 // Initialize iterator if necessary
10032 TargetRegisterClass::iterator I = RC->begin();
10033 MachineRegisterInfo &RegInfo = MF.getRegInfo();
10034
10035 // Do not check for single registers.
10036 if (AssignedReg) {
10037 I = std::find(first: I, last: RC->end(), val: AssignedReg);
10038 if (I == RC->end()) {
10039 // RC does not contain the selected register, which indicates a
10040 // mismatch between the register and the required type/bitwidth.
10041 return {AssignedReg};
10042 }
10043 }
10044
10045 for (; NumRegs; --NumRegs, ++I) {
10046 assert(I != RC->end() && "Ran out of registers to allocate!");
10047 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RegClass: RC);
10048 Regs.push_back(Elt: R);
10049 }
10050
10051 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
10052 return std::nullopt;
10053}
10054
10055static unsigned
10056findMatchingInlineAsmOperand(unsigned OperandNo,
10057 const std::vector<SDValue> &AsmNodeOperands) {
10058 // Scan until we find the definition we already emitted of this operand.
10059 unsigned CurOp = InlineAsm::Op_FirstOperand;
10060 for (; OperandNo; --OperandNo) {
10061 // Advance to the next operand.
10062 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
10063 const InlineAsm::Flag F(OpFlag);
10064 assert(
10065 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
10066 "Skipped past definitions?");
10067 CurOp += F.getNumOperandRegisters() + 1;
10068 }
10069 return CurOp;
10070}
10071
10072namespace {
10073
10074class ExtraFlags {
10075 unsigned Flags = 0;
10076
10077public:
10078 explicit ExtraFlags(const CallBase &Call) {
10079 const InlineAsm *IA = cast<InlineAsm>(Val: Call.getCalledOperand());
10080 if (IA->hasSideEffects())
10081 Flags |= InlineAsm::Extra_HasSideEffects;
10082 if (IA->isAlignStack())
10083 Flags |= InlineAsm::Extra_IsAlignStack;
10084 if (IA->canThrow())
10085 Flags |= InlineAsm::Extra_MayUnwind;
10086 if (Call.isConvergent())
10087 Flags |= InlineAsm::Extra_IsConvergent;
10088 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
10089 }
10090
10091 void update(const TargetLowering::AsmOperandInfo &OpInfo) {
10092 // Ideally, we would only check against memory constraints. However, the
10093 // meaning of an Other constraint can be target-specific and we can't easily
10094 // reason about it. Therefore, be conservative and set MayLoad/MayStore
10095 // for Other constraints as well.
10096 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
10097 OpInfo.ConstraintType == TargetLowering::C_Other) {
10098 if (OpInfo.Type == InlineAsm::isInput)
10099 Flags |= InlineAsm::Extra_MayLoad;
10100 else if (OpInfo.Type == InlineAsm::isOutput)
10101 Flags |= InlineAsm::Extra_MayStore;
10102 else if (OpInfo.Type == InlineAsm::isClobber)
10103 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
10104 }
10105 }
10106
10107 unsigned get() const { return Flags; }
10108};
10109
10110} // end anonymous namespace
10111
10112static bool isFunction(SDValue Op) {
10113 if (Op && Op.getOpcode() == ISD::GlobalAddress) {
10114 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Val&: Op)) {
10115 auto Fn = dyn_cast_or_null<Function>(Val: GA->getGlobal());
10116
10117 // In normal "call dllimport func" instruction (non-inlineasm) it force
10118 // indirect access by specifing call opcode. And usually specially print
10119 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
10120 // not do in this way now. (In fact, this is similar with "Data Access"
10121 // action). So here we ignore dllimport function.
10122 if (Fn && !Fn->hasDLLImportStorageClass())
10123 return true;
10124 }
10125 }
10126 return false;
10127}
10128
10129/// visitInlineAsm - Handle a call to an InlineAsm object.
10130void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
10131 const BasicBlock *EHPadBB) {
10132 const InlineAsm *IA = cast<InlineAsm>(Val: Call.getCalledOperand());
10133
10134 /// ConstraintOperands - Information about all of the constraints.
10135 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
10136
10137 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10138 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
10139 DL: DAG.getDataLayout(), TRI: DAG.getSubtarget().getRegisterInfo(), Call);
10140
10141 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
10142 // AsmDialect, MayLoad, MayStore).
10143 bool HasSideEffect = IA->hasSideEffects();
10144 ExtraFlags ExtraInfo(Call);
10145
10146 for (auto &T : TargetConstraints) {
10147 ConstraintOperands.push_back(Elt: SDISelAsmOperandInfo(T));
10148 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
10149
10150 if (OpInfo.CallOperandVal)
10151 OpInfo.CallOperand = getValue(V: OpInfo.CallOperandVal);
10152
10153 if (!HasSideEffect)
10154 HasSideEffect = OpInfo.hasMemory(TLI);
10155
10156 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
10157 // FIXME: Could we compute this on OpInfo rather than T?
10158
10159 // Compute the constraint code and ConstraintType to use.
10160 TLI.ComputeConstraintToUse(OpInfo&: T, Op: SDValue());
10161
10162 if (T.ConstraintType == TargetLowering::C_Immediate &&
10163 OpInfo.CallOperand && !isa<ConstantSDNode>(Val: OpInfo.CallOperand))
10164 // We've delayed emitting a diagnostic like the "n" constraint because
10165 // inlining could cause an integer showing up.
10166 return emitInlineAsmError(Call, Message: "constraint '" + Twine(T.ConstraintCode) +
10167 "' expects an integer constant "
10168 "expression");
10169
10170 ExtraInfo.update(OpInfo: T);
10171 }
10172
10173 // We won't need to flush pending loads if this asm doesn't touch
10174 // memory and is nonvolatile.
10175 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
10176
10177 bool EmitEHLabels = isa<InvokeInst>(Val: Call);
10178 if (EmitEHLabels) {
10179 assert(EHPadBB && "InvokeInst must have an EHPadBB");
10180 }
10181 bool IsCallBr = isa<CallBrInst>(Val: Call);
10182
10183 if (IsCallBr || EmitEHLabels) {
10184 // If this is a callbr or invoke we need to flush pending exports since
10185 // inlineasm_br and invoke are terminators.
10186 // We need to do this before nodes are glued to the inlineasm_br node.
10187 Chain = getControlRoot();
10188 }
10189
10190 MCSymbol *BeginLabel = nullptr;
10191 if (EmitEHLabels) {
10192 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
10193 }
10194
10195 int OpNo = -1;
10196 SmallVector<StringRef> AsmStrs;
10197 IA->collectAsmStrs(AsmStrs);
10198
10199 // Second pass over the constraints: compute which constraint option to use.
10200 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10201 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
10202 OpNo++;
10203
10204 // If this is an output operand with a matching input operand, look up the
10205 // matching input. If their types mismatch, e.g. one is an integer, the
10206 // other is floating point, or their sizes are different, flag it as an
10207 // error.
10208 if (OpInfo.hasMatchingInput()) {
10209 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
10210 patchMatchingInput(OpInfo, MatchingOpInfo&: Input, DAG);
10211 }
10212
10213 // Compute the constraint code and ConstraintType to use.
10214 TLI.ComputeConstraintToUse(OpInfo, Op: OpInfo.CallOperand, DAG: &DAG);
10215
10216 if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
10217 OpInfo.Type == InlineAsm::isClobber) ||
10218 OpInfo.ConstraintType == TargetLowering::C_Address)
10219 continue;
10220
10221 // In Linux PIC model, there are 4 cases about value/label addressing:
10222 //
10223 // 1: Function call or Label jmp inside the module.
10224 // 2: Data access (such as global variable, static variable) inside module.
10225 // 3: Function call or Label jmp outside the module.
10226 // 4: Data access (such as global variable) outside the module.
10227 //
10228 // Due to current llvm inline asm architecture designed to not "recognize"
10229 // the asm code, there are quite troubles for us to treat mem addressing
10230 // differently for same value/adress used in different instuctions.
10231 // For example, in pic model, call a func may in plt way or direclty
10232 // pc-related, but lea/mov a function adress may use got.
10233 //
10234 // Here we try to "recognize" function call for the case 1 and case 3 in
10235 // inline asm. And try to adjust the constraint for them.
10236 //
10237 // TODO: Due to current inline asm didn't encourage to jmp to the outsider
10238 // label, so here we don't handle jmp function label now, but we need to
10239 // enhance it (especilly in PIC model) if we meet meaningful requirements.
10240 if (OpInfo.isIndirect && isFunction(Op: OpInfo.CallOperand) &&
10241 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
10242 TM.getCodeModel() != CodeModel::Large) {
10243 OpInfo.isIndirect = false;
10244 OpInfo.ConstraintType = TargetLowering::C_Address;
10245 }
10246
10247 // If this is a memory input, and if the operand is not indirect, do what we
10248 // need to provide an address for the memory input.
10249 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
10250 !OpInfo.isIndirect) {
10251 assert((OpInfo.isMultipleAlternative ||
10252 (OpInfo.Type == InlineAsm::isInput)) &&
10253 "Can only indirectify direct input operands!");
10254
10255 // Memory operands really want the address of the value.
10256 Chain = getAddressForMemoryInput(Chain, Location: getCurSDLoc(), OpInfo, DAG);
10257
10258 // There is no longer a Value* corresponding to this operand.
10259 OpInfo.CallOperandVal = nullptr;
10260
10261 // It is now an indirect operand.
10262 OpInfo.isIndirect = true;
10263 }
10264
10265 }
10266
10267 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10268 std::vector<SDValue> AsmNodeOperands;
10269 AsmNodeOperands.push_back(x: SDValue()); // reserve space for input chain
10270 AsmNodeOperands.push_back(x: DAG.getTargetExternalSymbol(
10271 Sym: IA->getAsmString().data(), VT: TLI.getProgramPointerTy(DL: DAG.getDataLayout())));
10272
10273 // If we have a !srcloc metadata node associated with it, we want to attach
10274 // this to the ultimately generated inline asm machineinstr. To do this, we
10275 // pass in the third operand as this (potentially null) inline asm MDNode.
10276 const MDNode *SrcLoc = Call.getMetadata(Kind: "srcloc");
10277 AsmNodeOperands.push_back(x: DAG.getMDNode(MD: SrcLoc));
10278
10279 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10280 // bits as operand 3.
10281 AsmNodeOperands.push_back(x: DAG.getTargetConstant(
10282 Val: ExtraInfo.get(), DL: getCurSDLoc(), VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
10283
10284 // Third pass: Loop over operands to prepare DAG-level operands.. As part of
10285 // this, assign virtual and physical registers for inputs and otput.
10286 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10287 // Assign Registers.
10288 SDISelAsmOperandInfo &RefOpInfo =
10289 OpInfo.isMatchingInputConstraint()
10290 ? ConstraintOperands[OpInfo.getMatchedOperand()]
10291 : OpInfo;
10292 const auto RegError =
10293 getRegistersForValue(DAG, DL: getCurSDLoc(), OpInfo, RefOpInfo);
10294 if (RegError) {
10295 const MachineFunction &MF = DAG.getMachineFunction();
10296 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10297 const char *RegName = TRI.getName(RegNo: *RegError);
10298 emitInlineAsmError(Call, Message: "register '" + Twine(RegName) +
10299 "' allocated for constraint '" +
10300 Twine(OpInfo.ConstraintCode) +
10301 "' does not match required type");
10302 return;
10303 }
10304
10305 auto DetectWriteToReservedRegister = [&]() {
10306 const MachineFunction &MF = DAG.getMachineFunction();
10307 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10308 for (Register Reg : OpInfo.AssignedRegs.Regs) {
10309 if (Reg.isPhysical() && TRI.isInlineAsmReadOnlyReg(MF, PhysReg: Reg)) {
10310 const char *RegName = TRI.getName(RegNo: Reg);
10311 emitInlineAsmError(Call, Message: "write to reserved register '" +
10312 Twine(RegName) + "'");
10313 return true;
10314 }
10315 }
10316 return false;
10317 };
10318 assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10319 (OpInfo.Type == InlineAsm::isInput &&
10320 !OpInfo.isMatchingInputConstraint())) &&
10321 "Only address as input operand is allowed.");
10322
10323 switch (OpInfo.Type) {
10324 case InlineAsm::isOutput:
10325 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10326 const InlineAsm::ConstraintCode ConstraintID =
10327 TLI.getInlineAsmMemConstraint(ConstraintCode: OpInfo.ConstraintCode);
10328 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10329 "Failed to convert memory constraint code to constraint id.");
10330
10331 // Add information to the INLINEASM node to know about this output.
10332 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
10333 OpFlags.setMemConstraint(ConstraintID);
10334 AsmNodeOperands.push_back(x: DAG.getTargetConstant(Val: OpFlags, DL: getCurSDLoc(),
10335 VT: MVT::i32));
10336 AsmNodeOperands.push_back(x: OpInfo.CallOperand);
10337 } else {
10338 // Otherwise, this outputs to a register (directly for C_Register /
10339 // C_RegisterClass, and a target-defined fashion for
10340 // C_Immediate/C_Other). Find a register that we can use.
10341 if (OpInfo.AssignedRegs.Regs.empty()) {
10342 emitInlineAsmError(
10343 Call, Message: "couldn't allocate output register for constraint '" +
10344 Twine(OpInfo.ConstraintCode) + "'");
10345 return;
10346 }
10347
10348 if (DetectWriteToReservedRegister())
10349 return;
10350
10351 // Add information to the INLINEASM node to know that this register is
10352 // set.
10353 OpInfo.AssignedRegs.AddInlineAsmOperands(
10354 Code: OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10355 : InlineAsm::Kind::RegDef,
10356 HasMatching: false, MatchingIdx: 0, dl: getCurSDLoc(), DAG, Ops&: AsmNodeOperands);
10357 }
10358 break;
10359
10360 case InlineAsm::isInput:
10361 case InlineAsm::isLabel: {
10362 SDValue InOperandVal = OpInfo.CallOperand;
10363
10364 if (OpInfo.isMatchingInputConstraint()) {
10365 // If this is required to match an output register we have already set,
10366 // just use its register.
10367 auto CurOp = findMatchingInlineAsmOperand(OperandNo: OpInfo.getMatchedOperand(),
10368 AsmNodeOperands);
10369 InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
10370 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10371 if (OpInfo.isIndirect) {
10372 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10373 emitInlineAsmError(Call, Message: "inline asm not supported yet: "
10374 "don't know how to handle tied "
10375 "indirect register inputs");
10376 return;
10377 }
10378
10379 SmallVector<Register, 4> Regs;
10380 MachineFunction &MF = DAG.getMachineFunction();
10381 MachineRegisterInfo &MRI = MF.getRegInfo();
10382 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10383 auto *R = cast<RegisterSDNode>(Val&: AsmNodeOperands[CurOp+1]);
10384 Register TiedReg = R->getReg();
10385 MVT RegVT = R->getSimpleValueType(ResNo: 0);
10386 const TargetRegisterClass *RC =
10387 TiedReg.isVirtual() ? MRI.getRegClass(Reg: TiedReg)
10388 : RegVT != MVT::Untyped ? TLI.getRegClassFor(VT: RegVT)
10389 : TRI.getMinimalPhysRegClass(Reg: TiedReg);
10390 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
10391 Regs.push_back(Elt: MRI.createVirtualRegister(RegClass: RC));
10392
10393 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10394
10395 SDLoc dl = getCurSDLoc();
10396 // Use the produced MatchedRegs object to
10397 MatchedRegs.getCopyToRegs(Val: InOperandVal, DAG, dl, Chain, Glue: &Glue, V: &Call);
10398 MatchedRegs.AddInlineAsmOperands(Code: InlineAsm::Kind::RegUse, HasMatching: true,
10399 MatchingIdx: OpInfo.getMatchedOperand(), dl, DAG,
10400 Ops&: AsmNodeOperands);
10401 break;
10402 }
10403
10404 assert(Flag.isMemKind() && "Unknown matching constraint!");
10405 assert(Flag.getNumOperandRegisters() == 1 &&
10406 "Unexpected number of operands");
10407 // Add information to the INLINEASM node to know about this input.
10408 // See InlineAsm.h isUseOperandTiedToDef.
10409 Flag.clearMemConstraint();
10410 Flag.setMatchingOp(OpInfo.getMatchedOperand());
10411 AsmNodeOperands.push_back(x: DAG.getTargetConstant(
10412 Val: Flag, DL: getCurSDLoc(), VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
10413 AsmNodeOperands.push_back(x: AsmNodeOperands[CurOp+1]);
10414 break;
10415 }
10416
10417 // Treat indirect 'X' constraint as memory.
10418 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10419 OpInfo.isIndirect)
10420 OpInfo.ConstraintType = TargetLowering::C_Memory;
10421
10422 if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10423 OpInfo.ConstraintType == TargetLowering::C_Other) {
10424 std::vector<SDValue> Ops;
10425 TLI.LowerAsmOperandForConstraint(Op: InOperandVal, Constraint: OpInfo.ConstraintCode,
10426 Ops, DAG);
10427 if (Ops.empty()) {
10428 if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10429 if (isa<ConstantSDNode>(Val: InOperandVal)) {
10430 emitInlineAsmError(Call, Message: "value out of range for constraint '" +
10431 Twine(OpInfo.ConstraintCode) + "'");
10432 return;
10433 }
10434
10435 emitInlineAsmError(Call,
10436 Message: "invalid operand for inline asm constraint '" +
10437 Twine(OpInfo.ConstraintCode) + "'");
10438 return;
10439 }
10440
10441 // Add information to the INLINEASM node to know about this input.
10442 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10443 AsmNodeOperands.push_back(x: DAG.getTargetConstant(
10444 Val: ResOpType, DL: getCurSDLoc(), VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
10445 llvm::append_range(C&: AsmNodeOperands, R&: Ops);
10446 break;
10447 }
10448
10449 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10450 assert((OpInfo.isIndirect ||
10451 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10452 "Operand must be indirect to be a mem!");
10453 assert(InOperandVal.getValueType() ==
10454 TLI.getPointerTy(DAG.getDataLayout()) &&
10455 "Memory operands expect pointer values");
10456
10457 const InlineAsm::ConstraintCode ConstraintID =
10458 TLI.getInlineAsmMemConstraint(ConstraintCode: OpInfo.ConstraintCode);
10459 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10460 "Failed to convert memory constraint code to constraint id.");
10461
10462 // Add information to the INLINEASM node to know about this input.
10463 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10464 ResOpType.setMemConstraint(ConstraintID);
10465 AsmNodeOperands.push_back(x: DAG.getTargetConstant(Val: ResOpType,
10466 DL: getCurSDLoc(),
10467 VT: MVT::i32));
10468 AsmNodeOperands.push_back(x: InOperandVal);
10469 break;
10470 }
10471
10472 if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10473 const InlineAsm::ConstraintCode ConstraintID =
10474 TLI.getInlineAsmMemConstraint(ConstraintCode: OpInfo.ConstraintCode);
10475 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10476 "Failed to convert memory constraint code to constraint id.");
10477
10478 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10479
10480 SDValue AsmOp = InOperandVal;
10481 if (isFunction(Op: InOperandVal)) {
10482 auto *GA = cast<GlobalAddressSDNode>(Val&: InOperandVal);
10483 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10484 AsmOp = DAG.getTargetGlobalAddress(GV: GA->getGlobal(), DL: getCurSDLoc(),
10485 VT: InOperandVal.getValueType(),
10486 offset: GA->getOffset());
10487 }
10488
10489 // Add information to the INLINEASM node to know about this input.
10490 ResOpType.setMemConstraint(ConstraintID);
10491
10492 AsmNodeOperands.push_back(
10493 x: DAG.getTargetConstant(Val: ResOpType, DL: getCurSDLoc(), VT: MVT::i32));
10494
10495 AsmNodeOperands.push_back(x: AsmOp);
10496 break;
10497 }
10498
10499 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10500 OpInfo.ConstraintType != TargetLowering::C_Register) {
10501 emitInlineAsmError(Call, Message: "unknown asm constraint '" +
10502 Twine(OpInfo.ConstraintCode) + "'");
10503 return;
10504 }
10505
10506 // TODO: Support this.
10507 if (OpInfo.isIndirect) {
10508 emitInlineAsmError(
10509 Call, Message: "Don't know how to handle indirect register inputs yet "
10510 "for constraint '" +
10511 Twine(OpInfo.ConstraintCode) + "'");
10512 return;
10513 }
10514
10515 // Copy the input into the appropriate registers.
10516 if (OpInfo.AssignedRegs.Regs.empty()) {
10517 emitInlineAsmError(Call,
10518 Message: "couldn't allocate input reg for constraint '" +
10519 Twine(OpInfo.ConstraintCode) + "'");
10520 return;
10521 }
10522
10523 if (DetectWriteToReservedRegister())
10524 return;
10525
10526 SDLoc dl = getCurSDLoc();
10527
10528 OpInfo.AssignedRegs.getCopyToRegs(Val: InOperandVal, DAG, dl, Chain, Glue: &Glue,
10529 V: &Call);
10530
10531 OpInfo.AssignedRegs.AddInlineAsmOperands(Code: InlineAsm::Kind::RegUse, HasMatching: false,
10532 MatchingIdx: 0, dl, DAG, Ops&: AsmNodeOperands);
10533 break;
10534 }
10535 case InlineAsm::isClobber:
10536 // Add the clobbered value to the operand list, so that the register
10537 // allocator is aware that the physreg got clobbered.
10538 if (!OpInfo.AssignedRegs.Regs.empty())
10539 OpInfo.AssignedRegs.AddInlineAsmOperands(Code: InlineAsm::Kind::Clobber,
10540 HasMatching: false, MatchingIdx: 0, dl: getCurSDLoc(), DAG,
10541 Ops&: AsmNodeOperands);
10542 break;
10543 }
10544 }
10545
10546 // Finish up input operands. Set the input chain and add the flag last.
10547 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10548 if (Glue.getNode()) AsmNodeOperands.push_back(x: Glue);
10549
10550 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10551 Chain = DAG.getNode(Opcode: ISDOpc, DL: getCurSDLoc(),
10552 VTList: DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue), Ops: AsmNodeOperands);
10553 Glue = Chain.getValue(R: 1);
10554
10555 // Do additional work to generate outputs.
10556
10557 SmallVector<EVT, 1> ResultVTs;
10558 SmallVector<SDValue, 1> ResultValues;
10559 SmallVector<SDValue, 8> OutChains;
10560
10561 llvm::Type *CallResultType = Call.getType();
10562 ArrayRef<Type *> ResultTypes;
10563 if (StructType *StructResult = dyn_cast<StructType>(Val: CallResultType))
10564 ResultTypes = StructResult->elements();
10565 else if (!CallResultType->isVoidTy())
10566 ResultTypes = ArrayRef(CallResultType);
10567
10568 auto CurResultType = ResultTypes.begin();
10569 auto handleRegAssign = [&](SDValue V) {
10570 assert(CurResultType != ResultTypes.end() && "Unexpected value");
10571 assert((*CurResultType)->isSized() && "Unexpected unsized type");
10572 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: *CurResultType);
10573 ++CurResultType;
10574 // If the type of the inline asm call site return value is different but has
10575 // same size as the type of the asm output bitcast it. One example of this
10576 // is for vectors with different width / number of elements. This can
10577 // happen for register classes that can contain multiple different value
10578 // types. The preg or vreg allocated may not have the same VT as was
10579 // expected.
10580 //
10581 // This can also happen for a return value that disagrees with the register
10582 // class it is put in, eg. a double in a general-purpose register on a
10583 // 32-bit machine.
10584 if (ResultVT != V.getValueType() &&
10585 ResultVT.getSizeInBits() == V.getValueSizeInBits())
10586 V = DAG.getNode(Opcode: ISD::BITCAST, DL: getCurSDLoc(), VT: ResultVT, Operand: V);
10587 else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10588 V.getValueType().isInteger()) {
10589 // If a result value was tied to an input value, the computed result
10590 // may have a wider width than the expected result. Extract the
10591 // relevant portion.
10592 V = DAG.getNode(Opcode: ISD::TRUNCATE, DL: getCurSDLoc(), VT: ResultVT, Operand: V);
10593 }
10594 assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10595 ResultVTs.push_back(Elt: ResultVT);
10596 ResultValues.push_back(Elt: V);
10597 };
10598
10599 // Deal with output operands.
10600 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10601 if (OpInfo.Type == InlineAsm::isOutput) {
10602 SDValue Val;
10603 // Skip trivial output operands.
10604 if (OpInfo.AssignedRegs.Regs.empty())
10605 continue;
10606
10607 switch (OpInfo.ConstraintType) {
10608 case TargetLowering::C_Register:
10609 case TargetLowering::C_RegisterClass:
10610 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, dl: getCurSDLoc(),
10611 Chain, Glue: &Glue, V: &Call);
10612 break;
10613 case TargetLowering::C_Immediate:
10614 case TargetLowering::C_Other:
10615 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, DL: getCurSDLoc(),
10616 OpInfo, DAG);
10617 break;
10618 case TargetLowering::C_Memory:
10619 break; // Already handled.
10620 case TargetLowering::C_Address:
10621 break; // Silence warning.
10622 case TargetLowering::C_Unknown:
10623 assert(false && "Unexpected unknown constraint");
10624 }
10625
10626 // Indirect output manifest as stores. Record output chains.
10627 if (OpInfo.isIndirect) {
10628 const Value *Ptr = OpInfo.CallOperandVal;
10629 assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10630 SDValue Store = DAG.getStore(Chain, dl: getCurSDLoc(), Val, Ptr: getValue(V: Ptr),
10631 PtrInfo: MachinePointerInfo(Ptr));
10632 OutChains.push_back(Elt: Store);
10633 } else {
10634 // generate CopyFromRegs to associated registers.
10635 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10636 if (Val.getOpcode() == ISD::MERGE_VALUES) {
10637 for (const SDValue &V : Val->op_values())
10638 handleRegAssign(V);
10639 } else
10640 handleRegAssign(Val);
10641 }
10642 }
10643 }
10644
10645 // Set results.
10646 if (!ResultValues.empty()) {
10647 assert(CurResultType == ResultTypes.end() &&
10648 "Mismatch in number of ResultTypes");
10649 assert(ResultValues.size() == ResultTypes.size() &&
10650 "Mismatch in number of output operands in asm result");
10651
10652 SDValue V = DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
10653 VTList: DAG.getVTList(VTs: ResultVTs), Ops: ResultValues);
10654 setValue(V: &Call, NewN: V);
10655 }
10656
10657 // Collect store chains.
10658 if (!OutChains.empty())
10659 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: getCurSDLoc(), VT: MVT::Other, Ops: OutChains);
10660
10661 if (EmitEHLabels) {
10662 Chain = lowerEndEH(Chain, II: cast<InvokeInst>(Val: &Call), EHPadBB, BeginLabel);
10663 }
10664
10665 // Only Update Root if inline assembly has a memory effect.
10666 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10667 EmitEHLabels)
10668 DAG.setRoot(Chain);
10669}
10670
10671void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10672 const Twine &Message) {
10673 LLVMContext &Ctx = *DAG.getContext();
10674 Ctx.diagnose(DI: DiagnosticInfoInlineAsm(Call, Message));
10675
10676 // Make sure we leave the DAG in a valid state
10677 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10678 SmallVector<EVT, 1> ValueVTs;
10679 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: Call.getType(), ValueVTs);
10680
10681 if (ValueVTs.empty())
10682 return;
10683
10684 SmallVector<SDValue, 1> Ops;
10685 for (const EVT &VT : ValueVTs)
10686 Ops.push_back(Elt: DAG.getUNDEF(VT));
10687
10688 setValue(V: &Call, NewN: DAG.getMergeValues(Ops, dl: getCurSDLoc()));
10689}
10690
10691void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10692 DAG.setRoot(DAG.getNode(Opcode: ISD::VASTART, DL: getCurSDLoc(),
10693 VT: MVT::Other, N1: getRoot(),
10694 N2: getValue(V: I.getArgOperand(i: 0)),
10695 N3: DAG.getSrcValue(v: I.getArgOperand(i: 0))));
10696}
10697
10698void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10699 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10700 const DataLayout &DL = DAG.getDataLayout();
10701 SDValue V = DAG.getVAArg(
10702 VT: TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getType()), dl: getCurSDLoc(),
10703 Chain: getRoot(), Ptr: getValue(V: I.getOperand(i_nocapture: 0)), SV: DAG.getSrcValue(v: I.getOperand(i_nocapture: 0)),
10704 Align: DL.getABITypeAlign(Ty: I.getType()).value());
10705 DAG.setRoot(V.getValue(R: 1));
10706
10707 if (I.getType()->isPointerTy())
10708 V = DAG.getPtrExtOrTrunc(
10709 Op: V, DL: getCurSDLoc(), VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()));
10710 setValue(V: &I, NewN: V);
10711}
10712
10713void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10714 DAG.setRoot(DAG.getNode(Opcode: ISD::VAEND, DL: getCurSDLoc(),
10715 VT: MVT::Other, N1: getRoot(),
10716 N2: getValue(V: I.getArgOperand(i: 0)),
10717 N3: DAG.getSrcValue(v: I.getArgOperand(i: 0))));
10718}
10719
10720void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10721 DAG.setRoot(DAG.getNode(Opcode: ISD::VACOPY, DL: getCurSDLoc(),
10722 VT: MVT::Other, N1: getRoot(),
10723 N2: getValue(V: I.getArgOperand(i: 0)),
10724 N3: getValue(V: I.getArgOperand(i: 1)),
10725 N4: DAG.getSrcValue(v: I.getArgOperand(i: 0)),
10726 N5: DAG.getSrcValue(v: I.getArgOperand(i: 1))));
10727}
10728
10729SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10730 const Instruction &I,
10731 SDValue Op) {
10732 std::optional<ConstantRange> CR = getRange(I);
10733
10734 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10735 return Op;
10736
10737 APInt Lo = CR->getUnsignedMin();
10738 if (!Lo.isMinValue())
10739 return Op;
10740
10741 APInt Hi = CR->getUnsignedMax();
10742 unsigned Bits = std::max(a: Hi.getActiveBits(),
10743 b: static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10744
10745 EVT SmallVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: Bits);
10746
10747 SDLoc SL = getCurSDLoc();
10748
10749 SDValue ZExt = DAG.getNode(Opcode: ISD::AssertZext, DL: SL, VT: Op.getValueType(), N1: Op,
10750 N2: DAG.getValueType(SmallVT));
10751 unsigned NumVals = Op.getNode()->getNumValues();
10752 if (NumVals == 1)
10753 return ZExt;
10754
10755 SmallVector<SDValue, 4> Ops;
10756
10757 Ops.push_back(Elt: ZExt);
10758 for (unsigned I = 1; I != NumVals; ++I)
10759 Ops.push_back(Elt: Op.getValue(R: I));
10760
10761 return DAG.getMergeValues(Ops, dl: SL);
10762}
10763
10764SDValue SelectionDAGBuilder::lowerNoFPClassToAssertNoFPClass(
10765 SelectionDAG &DAG, const Instruction &I, SDValue Op) {
10766 FPClassTest Classes = getNoFPClass(I);
10767 if (Classes == fcNone)
10768 return Op;
10769
10770 SDLoc SL = getCurSDLoc();
10771 SDValue TestConst = DAG.getTargetConstant(Val: Classes, DL: SDLoc(), VT: MVT::i32);
10772
10773 if (Op.getOpcode() != ISD::MERGE_VALUES) {
10774 return DAG.getNode(Opcode: ISD::AssertNoFPClass, DL: SL, VT: Op.getValueType(), N1: Op,
10775 N2: TestConst);
10776 }
10777
10778 SmallVector<SDValue, 8> Ops(Op.getNumOperands());
10779 for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
10780 SDValue MergeOp = Op.getOperand(i: I);
10781 Ops[I] = DAG.getNode(Opcode: ISD::AssertNoFPClass, DL: SL, VT: MergeOp.getValueType(),
10782 N1: MergeOp, N2: TestConst);
10783 }
10784
10785 return DAG.getMergeValues(Ops, dl: SL);
10786}
10787
10788/// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10789/// the call being lowered.
10790///
10791/// This is a helper for lowering intrinsics that follow a target calling
10792/// convention or require stack pointer adjustment. Only a subset of the
10793/// intrinsic's operands need to participate in the calling convention.
10794void SelectionDAGBuilder::populateCallLoweringInfo(
10795 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10796 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10797 AttributeSet RetAttrs, bool IsPatchPoint) {
10798 TargetLowering::ArgListTy Args;
10799 Args.reserve(n: NumArgs);
10800
10801 // Populate the argument list.
10802 // Attributes for args start at offset 1, after the return attribute.
10803 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10804 ArgI != ArgE; ++ArgI) {
10805 const Value *V = Call->getOperand(i_nocapture: ArgI);
10806
10807 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10808
10809 TargetLowering::ArgListEntry Entry(getValue(V), V->getType());
10810 Entry.setAttributes(Call, ArgIdx: ArgI);
10811 Args.push_back(x: Entry);
10812 }
10813
10814 CLI.setDebugLoc(getCurSDLoc())
10815 .setChain(getRoot())
10816 .setCallee(CC: Call->getCallingConv(), ResultType: ReturnTy, Target: Callee, ArgsList: std::move(Args),
10817 ResultAttrs: RetAttrs)
10818 .setDiscardResult(Call->use_empty())
10819 .setIsPatchPoint(IsPatchPoint)
10820 .setIsPreallocated(
10821 Call->countOperandBundlesOfType(ID: LLVMContext::OB_preallocated) != 0);
10822}
10823
10824/// Add a stack map intrinsic call's live variable operands to a stackmap
10825/// or patchpoint target node's operand list.
10826///
10827/// Constants are converted to TargetConstants purely as an optimization to
10828/// avoid constant materialization and register allocation.
10829///
10830/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10831/// generate addess computation nodes, and so FinalizeISel can convert the
10832/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10833/// address materialization and register allocation, but may also be required
10834/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10835/// alloca in the entry block, then the runtime may assume that the alloca's
10836/// StackMap location can be read immediately after compilation and that the
10837/// location is valid at any point during execution (this is similar to the
10838/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10839/// only available in a register, then the runtime would need to trap when
10840/// execution reaches the StackMap in order to read the alloca's location.
10841static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10842 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10843 SelectionDAGBuilder &Builder) {
10844 SelectionDAG &DAG = Builder.DAG;
10845 for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10846 SDValue Op = Builder.getValue(V: Call.getArgOperand(i: I));
10847
10848 // Things on the stack are pointer-typed, meaning that they are already
10849 // legal and can be emitted directly to target nodes.
10850 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Val&: Op)) {
10851 Ops.push_back(Elt: DAG.getTargetFrameIndex(FI: FI->getIndex(), VT: Op.getValueType()));
10852 } else {
10853 // Otherwise emit a target independent node to be legalised.
10854 Ops.push_back(Elt: Builder.getValue(V: Call.getArgOperand(i: I)));
10855 }
10856 }
10857}
10858
10859/// Lower llvm.experimental.stackmap.
10860void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10861 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10862 // [live variables...])
10863
10864 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10865
10866 SDValue Chain, InGlue, Callee;
10867 SmallVector<SDValue, 32> Ops;
10868
10869 SDLoc DL = getCurSDLoc();
10870 Callee = getValue(V: CI.getCalledOperand());
10871
10872 // The stackmap intrinsic only records the live variables (the arguments
10873 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10874 // intrinsic, this won't be lowered to a function call. This means we don't
10875 // have to worry about calling conventions and target specific lowering code.
10876 // Instead we perform the call lowering right here.
10877 //
10878 // chain, flag = CALLSEQ_START(chain, 0, 0)
10879 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10880 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10881 //
10882 Chain = DAG.getCALLSEQ_START(Chain: getRoot(), InSize: 0, OutSize: 0, DL);
10883 InGlue = Chain.getValue(R: 1);
10884
10885 // Add the STACKMAP operands, starting with DAG house-keeping.
10886 Ops.push_back(Elt: Chain);
10887 Ops.push_back(Elt: InGlue);
10888
10889 // Add the <id>, <numShadowBytes> operands.
10890 //
10891 // These do not require legalisation, and can be emitted directly to target
10892 // constant nodes.
10893 SDValue ID = getValue(V: CI.getArgOperand(i: 0));
10894 assert(ID.getValueType() == MVT::i64);
10895 SDValue IDConst =
10896 DAG.getTargetConstant(Val: ID->getAsZExtVal(), DL, VT: ID.getValueType());
10897 Ops.push_back(Elt: IDConst);
10898
10899 SDValue Shad = getValue(V: CI.getArgOperand(i: 1));
10900 assert(Shad.getValueType() == MVT::i32);
10901 SDValue ShadConst =
10902 DAG.getTargetConstant(Val: Shad->getAsZExtVal(), DL, VT: Shad.getValueType());
10903 Ops.push_back(Elt: ShadConst);
10904
10905 // Add the live variables.
10906 addStackMapLiveVars(Call: CI, StartIdx: 2, DL, Ops, Builder&: *this);
10907
10908 // Create the STACKMAP node.
10909 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
10910 Chain = DAG.getNode(Opcode: ISD::STACKMAP, DL, VTList: NodeTys, Ops);
10911 InGlue = Chain.getValue(R: 1);
10912
10913 Chain = DAG.getCALLSEQ_END(Chain, Size1: 0, Size2: 0, Glue: InGlue, DL);
10914
10915 // Stackmaps don't generate values, so nothing goes into the NodeMap.
10916
10917 // Set the root to the target-lowered call chain.
10918 DAG.setRoot(Chain);
10919
10920 // Inform the Frame Information that we have a stackmap in this function.
10921 FuncInfo.MF->getFrameInfo().setHasStackMap();
10922}
10923
10924/// Lower llvm.experimental.patchpoint directly to its target opcode.
10925void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10926 const BasicBlock *EHPadBB) {
10927 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10928 // i32 <numBytes>,
10929 // i8* <target>,
10930 // i32 <numArgs>,
10931 // [Args...],
10932 // [live variables...])
10933
10934 CallingConv::ID CC = CB.getCallingConv();
10935 bool IsAnyRegCC = CC == CallingConv::AnyReg;
10936 bool HasDef = !CB.getType()->isVoidTy();
10937 SDLoc dl = getCurSDLoc();
10938 SDValue Callee = getValue(V: CB.getArgOperand(i: PatchPointOpers::TargetPos));
10939
10940 // Handle immediate and symbolic callees.
10941 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Val&: Callee))
10942 Callee = DAG.getIntPtrConstant(Val: ConstCallee->getZExtValue(), DL: dl,
10943 /*isTarget=*/true);
10944 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Val&: Callee))
10945 Callee = DAG.getTargetGlobalAddress(GV: SymbolicCallee->getGlobal(),
10946 DL: SDLoc(SymbolicCallee),
10947 VT: SymbolicCallee->getValueType(ResNo: 0));
10948
10949 // Get the real number of arguments participating in the call <numArgs>
10950 SDValue NArgVal = getValue(V: CB.getArgOperand(i: PatchPointOpers::NArgPos));
10951 unsigned NumArgs = NArgVal->getAsZExtVal();
10952
10953 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10954 // Intrinsics include all meta-operands up to but not including CC.
10955 unsigned NumMetaOpers = PatchPointOpers::CCPos;
10956 assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10957 "Not enough arguments provided to the patchpoint intrinsic");
10958
10959 // For AnyRegCC the arguments are lowered later on manually.
10960 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10961 Type *ReturnTy =
10962 IsAnyRegCC ? Type::getVoidTy(C&: *DAG.getContext()) : CB.getType();
10963
10964 TargetLowering::CallLoweringInfo CLI(DAG);
10965 populateCallLoweringInfo(CLI, Call: &CB, ArgIdx: NumMetaOpers, NumArgs: NumCallArgs, Callee,
10966 ReturnTy, RetAttrs: CB.getAttributes().getRetAttrs(), IsPatchPoint: true);
10967 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10968
10969 SDNode *CallEnd = Result.second.getNode();
10970 if (CallEnd->getOpcode() == ISD::EH_LABEL)
10971 CallEnd = CallEnd->getOperand(Num: 0).getNode();
10972 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10973 CallEnd = CallEnd->getOperand(Num: 0).getNode();
10974
10975 /// Get a call instruction from the call sequence chain.
10976 /// Tail calls are not allowed.
10977 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10978 "Expected a callseq node.");
10979 SDNode *Call = CallEnd->getOperand(Num: 0).getNode();
10980 bool HasGlue = Call->getGluedNode();
10981
10982 // Replace the target specific call node with the patchable intrinsic.
10983 SmallVector<SDValue, 8> Ops;
10984
10985 // Push the chain.
10986 Ops.push_back(Elt: *(Call->op_begin()));
10987
10988 // Optionally, push the glue (if any).
10989 if (HasGlue)
10990 Ops.push_back(Elt: *(Call->op_end() - 1));
10991
10992 // Push the register mask info.
10993 if (HasGlue)
10994 Ops.push_back(Elt: *(Call->op_end() - 2));
10995 else
10996 Ops.push_back(Elt: *(Call->op_end() - 1));
10997
10998 // Add the <id> and <numBytes> constants.
10999 SDValue IDVal = getValue(V: CB.getArgOperand(i: PatchPointOpers::IDPos));
11000 Ops.push_back(Elt: DAG.getTargetConstant(Val: IDVal->getAsZExtVal(), DL: dl, VT: MVT::i64));
11001 SDValue NBytesVal = getValue(V: CB.getArgOperand(i: PatchPointOpers::NBytesPos));
11002 Ops.push_back(Elt: DAG.getTargetConstant(Val: NBytesVal->getAsZExtVal(), DL: dl, VT: MVT::i32));
11003
11004 // Add the callee.
11005 Ops.push_back(Elt: Callee);
11006
11007 // Adjust <numArgs> to account for any arguments that have been passed on the
11008 // stack instead.
11009 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
11010 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
11011 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
11012 Ops.push_back(Elt: DAG.getTargetConstant(Val: NumCallRegArgs, DL: dl, VT: MVT::i32));
11013
11014 // Add the calling convention
11015 Ops.push_back(Elt: DAG.getTargetConstant(Val: (unsigned)CC, DL: dl, VT: MVT::i32));
11016
11017 // Add the arguments we omitted previously. The register allocator should
11018 // place these in any free register.
11019 if (IsAnyRegCC)
11020 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
11021 Ops.push_back(Elt: getValue(V: CB.getArgOperand(i)));
11022
11023 // Push the arguments from the call instruction.
11024 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
11025 Ops.append(in_start: Call->op_begin() + 2, in_end: e);
11026
11027 // Push live variables for the stack map.
11028 addStackMapLiveVars(Call: CB, StartIdx: NumMetaOpers + NumArgs, DL: dl, Ops, Builder&: *this);
11029
11030 SDVTList NodeTys;
11031 if (IsAnyRegCC && HasDef) {
11032 // Create the return types based on the intrinsic definition
11033 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11034 SmallVector<EVT, 3> ValueVTs;
11035 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: CB.getType(), ValueVTs);
11036 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
11037
11038 // There is always a chain and a glue type at the end
11039 ValueVTs.push_back(Elt: MVT::Other);
11040 ValueVTs.push_back(Elt: MVT::Glue);
11041 NodeTys = DAG.getVTList(VTs: ValueVTs);
11042 } else
11043 NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
11044
11045 // Replace the target specific call node with a PATCHPOINT node.
11046 SDValue PPV = DAG.getNode(Opcode: ISD::PATCHPOINT, DL: dl, VTList: NodeTys, Ops);
11047
11048 // Update the NodeMap.
11049 if (HasDef) {
11050 if (IsAnyRegCC)
11051 setValue(V: &CB, NewN: SDValue(PPV.getNode(), 0));
11052 else
11053 setValue(V: &CB, NewN: Result.first);
11054 }
11055
11056 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
11057 // call sequence. Furthermore the location of the chain and glue can change
11058 // when the AnyReg calling convention is used and the intrinsic returns a
11059 // value.
11060 if (IsAnyRegCC && HasDef) {
11061 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
11062 SDValue To[] = {PPV.getValue(R: 1), PPV.getValue(R: 2)};
11063 DAG.ReplaceAllUsesOfValuesWith(From, To, Num: 2);
11064 } else
11065 DAG.ReplaceAllUsesWith(From: Call, To: PPV.getNode());
11066 DAG.DeleteNode(N: Call);
11067
11068 // Inform the Frame Information that we have a patchpoint in this function.
11069 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
11070}
11071
11072void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
11073 unsigned Intrinsic) {
11074 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11075 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
11076 SDValue Op2;
11077 if (I.arg_size() > 1)
11078 Op2 = getValue(V: I.getArgOperand(i: 1));
11079 SDLoc dl = getCurSDLoc();
11080 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
11081 SDValue Res;
11082 SDNodeFlags SDFlags;
11083 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &I))
11084 SDFlags.copyFMF(FPMO: *FPMO);
11085
11086 switch (Intrinsic) {
11087 case Intrinsic::vector_reduce_fadd:
11088 if (SDFlags.hasAllowReassociation())
11089 Res = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT, N1: Op1,
11090 N2: DAG.getNode(Opcode: ISD::VECREDUCE_FADD, DL: dl, VT, Operand: Op2, Flags: SDFlags),
11091 Flags: SDFlags);
11092 else
11093 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SEQ_FADD, DL: dl, VT, N1: Op1, N2: Op2, Flags: SDFlags);
11094 break;
11095 case Intrinsic::vector_reduce_fmul:
11096 if (SDFlags.hasAllowReassociation())
11097 Res = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT, N1: Op1,
11098 N2: DAG.getNode(Opcode: ISD::VECREDUCE_FMUL, DL: dl, VT, Operand: Op2, Flags: SDFlags),
11099 Flags: SDFlags);
11100 else
11101 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SEQ_FMUL, DL: dl, VT, N1: Op1, N2: Op2, Flags: SDFlags);
11102 break;
11103 case Intrinsic::vector_reduce_add:
11104 Res = DAG.getNode(Opcode: ISD::VECREDUCE_ADD, DL: dl, VT, Operand: Op1);
11105 break;
11106 case Intrinsic::vector_reduce_mul:
11107 Res = DAG.getNode(Opcode: ISD::VECREDUCE_MUL, DL: dl, VT, Operand: Op1);
11108 break;
11109 case Intrinsic::vector_reduce_and:
11110 Res = DAG.getNode(Opcode: ISD::VECREDUCE_AND, DL: dl, VT, Operand: Op1);
11111 break;
11112 case Intrinsic::vector_reduce_or:
11113 Res = DAG.getNode(Opcode: ISD::VECREDUCE_OR, DL: dl, VT, Operand: Op1);
11114 break;
11115 case Intrinsic::vector_reduce_xor:
11116 Res = DAG.getNode(Opcode: ISD::VECREDUCE_XOR, DL: dl, VT, Operand: Op1);
11117 break;
11118 case Intrinsic::vector_reduce_smax:
11119 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SMAX, DL: dl, VT, Operand: Op1);
11120 break;
11121 case Intrinsic::vector_reduce_smin:
11122 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SMIN, DL: dl, VT, Operand: Op1);
11123 break;
11124 case Intrinsic::vector_reduce_umax:
11125 Res = DAG.getNode(Opcode: ISD::VECREDUCE_UMAX, DL: dl, VT, Operand: Op1);
11126 break;
11127 case Intrinsic::vector_reduce_umin:
11128 Res = DAG.getNode(Opcode: ISD::VECREDUCE_UMIN, DL: dl, VT, Operand: Op1);
11129 break;
11130 case Intrinsic::vector_reduce_fmax:
11131 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMAX, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11132 break;
11133 case Intrinsic::vector_reduce_fmin:
11134 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMIN, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11135 break;
11136 case Intrinsic::vector_reduce_fmaximum:
11137 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMAXIMUM, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11138 break;
11139 case Intrinsic::vector_reduce_fminimum:
11140 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMINIMUM, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11141 break;
11142 default:
11143 llvm_unreachable("Unhandled vector reduce intrinsic");
11144 }
11145 setValue(V: &I, NewN: Res);
11146}
11147
11148/// Returns an AttributeList representing the attributes applied to the return
11149/// value of the given call.
11150static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
11151 SmallVector<Attribute::AttrKind, 2> Attrs;
11152 if (CLI.RetSExt)
11153 Attrs.push_back(Elt: Attribute::SExt);
11154 if (CLI.RetZExt)
11155 Attrs.push_back(Elt: Attribute::ZExt);
11156 if (CLI.IsInReg)
11157 Attrs.push_back(Elt: Attribute::InReg);
11158
11159 return AttributeList::get(C&: CLI.RetTy->getContext(), Index: AttributeList::ReturnIndex,
11160 Kinds: Attrs);
11161}
11162
11163/// TargetLowering::LowerCallTo - This is the default LowerCallTo
11164/// implementation, which just calls LowerCall.
11165/// FIXME: When all targets are
11166/// migrated to using LowerCall, this hook should be integrated into SDISel.
11167std::pair<SDValue, SDValue>
11168TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
11169 LLVMContext &Context = CLI.RetTy->getContext();
11170
11171 // Handle the incoming return values from the call.
11172 CLI.Ins.clear();
11173 SmallVector<Type *, 4> RetOrigTys;
11174 SmallVector<TypeSize, 4> Offsets;
11175 auto &DL = CLI.DAG.getDataLayout();
11176 ComputeValueTypes(DL, Ty: CLI.OrigRetTy, Types&: RetOrigTys, Offsets: &Offsets);
11177
11178 SmallVector<EVT, 4> RetVTs;
11179 if (CLI.RetTy != CLI.OrigRetTy) {
11180 assert(RetOrigTys.size() == 1 &&
11181 "Only supported for non-aggregate returns");
11182 RetVTs.push_back(Elt: getValueType(DL, Ty: CLI.RetTy));
11183 } else {
11184 for (Type *Ty : RetOrigTys)
11185 RetVTs.push_back(Elt: getValueType(DL, Ty));
11186 }
11187
11188 if (CLI.IsPostTypeLegalization) {
11189 // If we are lowering a libcall after legalization, split the return type.
11190 SmallVector<Type *, 4> OldRetOrigTys;
11191 SmallVector<EVT, 4> OldRetVTs;
11192 SmallVector<TypeSize, 4> OldOffsets;
11193 RetOrigTys.swap(RHS&: OldRetOrigTys);
11194 RetVTs.swap(RHS&: OldRetVTs);
11195 Offsets.swap(RHS&: OldOffsets);
11196
11197 for (size_t i = 0, e = OldRetVTs.size(); i != e; ++i) {
11198 EVT RetVT = OldRetVTs[i];
11199 uint64_t Offset = OldOffsets[i];
11200 MVT RegisterVT = getRegisterType(Context, VT: RetVT);
11201 unsigned NumRegs = getNumRegisters(Context, VT: RetVT);
11202 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
11203 RetOrigTys.append(NumInputs: NumRegs, Elt: OldRetOrigTys[i]);
11204 RetVTs.append(NumInputs: NumRegs, Elt: RegisterVT);
11205 for (unsigned j = 0; j != NumRegs; ++j)
11206 Offsets.push_back(Elt: TypeSize::getFixed(ExactSize: Offset + j * RegisterVTByteSZ));
11207 }
11208 }
11209
11210 SmallVector<ISD::OutputArg, 4> Outs;
11211 GetReturnInfo(CC: CLI.CallConv, ReturnType: CLI.RetTy, attr: getReturnAttrs(CLI), Outs, TLI: *this, DL);
11212
11213 bool CanLowerReturn =
11214 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
11215 CLI.IsVarArg, Outs, Context, RetTy: CLI.RetTy);
11216
11217 SDValue DemoteStackSlot;
11218 int DemoteStackIdx = -100;
11219 if (!CanLowerReturn) {
11220 // FIXME: equivalent assert?
11221 // assert(!CS.hasInAllocaArgument() &&
11222 // "sret demotion is incompatible with inalloca");
11223 uint64_t TySize = DL.getTypeAllocSize(Ty: CLI.RetTy);
11224 Align Alignment = DL.getPrefTypeAlign(Ty: CLI.RetTy);
11225 MachineFunction &MF = CLI.DAG.getMachineFunction();
11226 DemoteStackIdx =
11227 MF.getFrameInfo().CreateStackObject(Size: TySize, Alignment, isSpillSlot: false);
11228 Type *StackSlotPtrType = PointerType::get(C&: Context, AddressSpace: DL.getAllocaAddrSpace());
11229
11230 DemoteStackSlot = CLI.DAG.getFrameIndex(FI: DemoteStackIdx, VT: getFrameIndexTy(DL));
11231 ArgListEntry Entry(DemoteStackSlot, StackSlotPtrType);
11232 Entry.IsSRet = true;
11233 Entry.Alignment = Alignment;
11234 CLI.getArgs().insert(position: CLI.getArgs().begin(), x: Entry);
11235 CLI.NumFixedArgs += 1;
11236 CLI.getArgs()[0].IndirectType = CLI.RetTy;
11237 CLI.RetTy = CLI.OrigRetTy = Type::getVoidTy(C&: Context);
11238
11239 // sret demotion isn't compatible with tail-calls, since the sret argument
11240 // points into the callers stack frame.
11241 CLI.IsTailCall = false;
11242 } else {
11243 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11244 Ty: CLI.RetTy, CallConv: CLI.CallConv, isVarArg: CLI.IsVarArg, DL);
11245 for (unsigned I = 0, E = RetVTs.size(); I != E; ++I) {
11246 ISD::ArgFlagsTy Flags;
11247 if (NeedsRegBlock) {
11248 Flags.setInConsecutiveRegs();
11249 if (I == RetVTs.size() - 1)
11250 Flags.setInConsecutiveRegsLast();
11251 }
11252 EVT VT = RetVTs[I];
11253 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CC: CLI.CallConv, VT);
11254 unsigned NumRegs =
11255 getNumRegistersForCallingConv(Context, CC: CLI.CallConv, VT);
11256 for (unsigned i = 0; i != NumRegs; ++i) {
11257 ISD::InputArg Ret(Flags, RegisterVT, VT, RetOrigTys[I],
11258 CLI.IsReturnValueUsed, ISD::InputArg::NoArgIndex, 0);
11259 if (CLI.RetTy->isPointerTy()) {
11260 Ret.Flags.setPointer();
11261 Ret.Flags.setPointerAddrSpace(
11262 cast<PointerType>(Val: CLI.RetTy)->getAddressSpace());
11263 }
11264 if (CLI.RetSExt)
11265 Ret.Flags.setSExt();
11266 if (CLI.RetZExt)
11267 Ret.Flags.setZExt();
11268 if (CLI.IsInReg)
11269 Ret.Flags.setInReg();
11270 CLI.Ins.push_back(Elt: Ret);
11271 }
11272 }
11273 }
11274
11275 // We push in swifterror return as the last element of CLI.Ins.
11276 ArgListTy &Args = CLI.getArgs();
11277 if (supportSwiftError()) {
11278 for (const ArgListEntry &Arg : Args) {
11279 if (Arg.IsSwiftError) {
11280 ISD::ArgFlagsTy Flags;
11281 Flags.setSwiftError();
11282 ISD::InputArg Ret(Flags, getPointerTy(DL), EVT(getPointerTy(DL)),
11283 PointerType::getUnqual(C&: Context),
11284 /*Used=*/true, ISD::InputArg::NoArgIndex, 0);
11285 CLI.Ins.push_back(Elt: Ret);
11286 }
11287 }
11288 }
11289
11290 // Handle all of the outgoing arguments.
11291 CLI.Outs.clear();
11292 CLI.OutVals.clear();
11293 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11294 SmallVector<Type *, 4> OrigArgTys;
11295 ComputeValueTypes(DL, Ty: Args[i].OrigTy, Types&: OrigArgTys);
11296 // FIXME: Split arguments if CLI.IsPostTypeLegalization
11297 Type *FinalType = Args[i].Ty;
11298 if (Args[i].IsByVal)
11299 FinalType = Args[i].IndirectType;
11300 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11301 Ty: FinalType, CallConv: CLI.CallConv, isVarArg: CLI.IsVarArg, DL);
11302 for (unsigned Value = 0, NumValues = OrigArgTys.size(); Value != NumValues;
11303 ++Value) {
11304 Type *OrigArgTy = OrigArgTys[Value];
11305 Type *ArgTy = OrigArgTy;
11306 if (Args[i].Ty != Args[i].OrigTy) {
11307 assert(Value == 0 && "Only supported for non-aggregate arguments");
11308 ArgTy = Args[i].Ty;
11309 }
11310
11311 EVT VT = getValueType(DL, Ty: ArgTy);
11312 SDValue Op = SDValue(Args[i].Node.getNode(),
11313 Args[i].Node.getResNo() + Value);
11314 ISD::ArgFlagsTy Flags;
11315
11316 // Certain targets (such as MIPS), may have a different ABI alignment
11317 // for a type depending on the context. Give the target a chance to
11318 // specify the alignment it wants.
11319 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11320 Flags.setOrigAlign(OriginalAlignment);
11321
11322 if (i >= CLI.NumFixedArgs)
11323 Flags.setVarArg();
11324 if (ArgTy->isPointerTy()) {
11325 Flags.setPointer();
11326 Flags.setPointerAddrSpace(cast<PointerType>(Val: ArgTy)->getAddressSpace());
11327 }
11328 if (Args[i].IsZExt)
11329 Flags.setZExt();
11330 if (Args[i].IsSExt)
11331 Flags.setSExt();
11332 if (Args[i].IsNoExt)
11333 Flags.setNoExt();
11334 if (Args[i].IsInReg) {
11335 // If we are using vectorcall calling convention, a structure that is
11336 // passed InReg - is surely an HVA
11337 if (CLI.CallConv == CallingConv::X86_VectorCall &&
11338 isa<StructType>(Val: FinalType)) {
11339 // The first value of a structure is marked
11340 if (0 == Value)
11341 Flags.setHvaStart();
11342 Flags.setHva();
11343 }
11344 // Set InReg Flag
11345 Flags.setInReg();
11346 }
11347 if (Args[i].IsSRet)
11348 Flags.setSRet();
11349 if (Args[i].IsSwiftSelf)
11350 Flags.setSwiftSelf();
11351 if (Args[i].IsSwiftAsync)
11352 Flags.setSwiftAsync();
11353 if (Args[i].IsSwiftError)
11354 Flags.setSwiftError();
11355 if (Args[i].IsCFGuardTarget)
11356 Flags.setCFGuardTarget();
11357 if (Args[i].IsByVal)
11358 Flags.setByVal();
11359 if (Args[i].IsByRef)
11360 Flags.setByRef();
11361 if (Args[i].IsPreallocated) {
11362 Flags.setPreallocated();
11363 // Set the byval flag for CCAssignFn callbacks that don't know about
11364 // preallocated. This way we can know how many bytes we should've
11365 // allocated and how many bytes a callee cleanup function will pop. If
11366 // we port preallocated to more targets, we'll have to add custom
11367 // preallocated handling in the various CC lowering callbacks.
11368 Flags.setByVal();
11369 }
11370 if (Args[i].IsInAlloca) {
11371 Flags.setInAlloca();
11372 // Set the byval flag for CCAssignFn callbacks that don't know about
11373 // inalloca. This way we can know how many bytes we should've allocated
11374 // and how many bytes a callee cleanup function will pop. If we port
11375 // inalloca to more targets, we'll have to add custom inalloca handling
11376 // in the various CC lowering callbacks.
11377 Flags.setByVal();
11378 }
11379 Align MemAlign;
11380 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11381 unsigned FrameSize = DL.getTypeAllocSize(Ty: Args[i].IndirectType);
11382 Flags.setByValSize(FrameSize);
11383
11384 // info is not there but there are cases it cannot get right.
11385 if (auto MA = Args[i].Alignment)
11386 MemAlign = *MA;
11387 else
11388 MemAlign = getByValTypeAlignment(Ty: Args[i].IndirectType, DL);
11389 } else if (auto MA = Args[i].Alignment) {
11390 MemAlign = *MA;
11391 } else {
11392 MemAlign = OriginalAlignment;
11393 }
11394 Flags.setMemAlign(MemAlign);
11395 if (Args[i].IsNest)
11396 Flags.setNest();
11397 if (NeedsRegBlock)
11398 Flags.setInConsecutiveRegs();
11399
11400 MVT PartVT = getRegisterTypeForCallingConv(Context, CC: CLI.CallConv, VT);
11401 unsigned NumParts =
11402 getNumRegistersForCallingConv(Context, CC: CLI.CallConv, VT);
11403 SmallVector<SDValue, 4> Parts(NumParts);
11404 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11405
11406 if (Args[i].IsSExt)
11407 ExtendKind = ISD::SIGN_EXTEND;
11408 else if (Args[i].IsZExt)
11409 ExtendKind = ISD::ZERO_EXTEND;
11410
11411 // Conservatively only handle 'returned' on non-vectors that can be lowered,
11412 // for now.
11413 if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11414 CanLowerReturn) {
11415 assert((CLI.RetTy == Args[i].Ty ||
11416 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11417 CLI.RetTy->getPointerAddressSpace() ==
11418 Args[i].Ty->getPointerAddressSpace())) &&
11419 RetVTs.size() == NumValues && "unexpected use of 'returned'");
11420 // Before passing 'returned' to the target lowering code, ensure that
11421 // either the register MVT and the actual EVT are the same size or that
11422 // the return value and argument are extended in the same way; in these
11423 // cases it's safe to pass the argument register value unchanged as the
11424 // return register value (although it's at the target's option whether
11425 // to do so)
11426 // TODO: allow code generation to take advantage of partially preserved
11427 // registers rather than clobbering the entire register when the
11428 // parameter extension method is not compatible with the return
11429 // extension method
11430 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11431 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11432 CLI.RetZExt == Args[i].IsZExt))
11433 Flags.setReturned();
11434 }
11435
11436 getCopyToParts(DAG&: CLI.DAG, DL: CLI.DL, Val: Op, Parts: &Parts[0], NumParts, PartVT, V: CLI.CB,
11437 CallConv: CLI.CallConv, ExtendKind);
11438
11439 for (unsigned j = 0; j != NumParts; ++j) {
11440 // if it isn't first piece, alignment must be 1
11441 // For scalable vectors the scalable part is currently handled
11442 // by individual targets, so we just use the known minimum size here.
11443 ISD::OutputArg MyFlags(
11444 Flags, Parts[j].getValueType().getSimpleVT(), VT, OrigArgTy, i,
11445 j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11446 if (NumParts > 1 && j == 0)
11447 MyFlags.Flags.setSplit();
11448 else if (j != 0) {
11449 MyFlags.Flags.setOrigAlign(Align(1));
11450 if (j == NumParts - 1)
11451 MyFlags.Flags.setSplitEnd();
11452 }
11453
11454 CLI.Outs.push_back(Elt: MyFlags);
11455 CLI.OutVals.push_back(Elt: Parts[j]);
11456 }
11457
11458 if (NeedsRegBlock && Value == NumValues - 1)
11459 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11460 }
11461 }
11462
11463 SmallVector<SDValue, 4> InVals;
11464 CLI.Chain = LowerCall(CLI, InVals);
11465
11466 // Update CLI.InVals to use outside of this function.
11467 CLI.InVals = InVals;
11468
11469 // Verify that the target's LowerCall behaved as expected.
11470 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11471 "LowerCall didn't return a valid chain!");
11472 assert((!CLI.IsTailCall || InVals.empty()) &&
11473 "LowerCall emitted a return value for a tail call!");
11474 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11475 "LowerCall didn't emit the correct number of values!");
11476
11477 // For a tail call, the return value is merely live-out and there aren't
11478 // any nodes in the DAG representing it. Return a special value to
11479 // indicate that a tail call has been emitted and no more Instructions
11480 // should be processed in the current block.
11481 if (CLI.IsTailCall) {
11482 CLI.DAG.setRoot(CLI.Chain);
11483 return std::make_pair(x: SDValue(), y: SDValue());
11484 }
11485
11486#ifndef NDEBUG
11487 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11488 assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11489 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11490 "LowerCall emitted a value with the wrong type!");
11491 }
11492#endif
11493
11494 SmallVector<SDValue, 4> ReturnValues;
11495 if (!CanLowerReturn) {
11496 // The instruction result is the result of loading from the
11497 // hidden sret parameter.
11498 MVT PtrVT = getPointerTy(DL, AS: DL.getAllocaAddrSpace());
11499
11500 unsigned NumValues = RetVTs.size();
11501 ReturnValues.resize(N: NumValues);
11502 SmallVector<SDValue, 4> Chains(NumValues);
11503
11504 // An aggregate return value cannot wrap around the address space, so
11505 // offsets to its parts don't wrap either.
11506 MachineFunction &MF = CLI.DAG.getMachineFunction();
11507 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(ObjectIdx: DemoteStackIdx);
11508 for (unsigned i = 0; i < NumValues; ++i) {
11509 SDValue Add = CLI.DAG.getMemBasePlusOffset(
11510 Base: DemoteStackSlot, Offset: CLI.DAG.getConstant(Val: Offsets[i], DL: CLI.DL, VT: PtrVT),
11511 DL: CLI.DL, Flags: SDNodeFlags::NoUnsignedWrap);
11512 SDValue L = CLI.DAG.getLoad(
11513 VT: RetVTs[i], dl: CLI.DL, Chain: CLI.Chain, Ptr: Add,
11514 PtrInfo: MachinePointerInfo::getFixedStack(MF&: CLI.DAG.getMachineFunction(),
11515 FI: DemoteStackIdx, Offset: Offsets[i]),
11516 Alignment: HiddenSRetAlign);
11517 ReturnValues[i] = L;
11518 Chains[i] = L.getValue(R: 1);
11519 }
11520
11521 CLI.Chain = CLI.DAG.getNode(Opcode: ISD::TokenFactor, DL: CLI.DL, VT: MVT::Other, Ops: Chains);
11522 } else {
11523 // Collect the legal value parts into potentially illegal values
11524 // that correspond to the original function's return values.
11525 std::optional<ISD::NodeType> AssertOp;
11526 if (CLI.RetSExt)
11527 AssertOp = ISD::AssertSext;
11528 else if (CLI.RetZExt)
11529 AssertOp = ISD::AssertZext;
11530 unsigned CurReg = 0;
11531 for (EVT VT : RetVTs) {
11532 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CC: CLI.CallConv, VT);
11533 unsigned NumRegs =
11534 getNumRegistersForCallingConv(Context, CC: CLI.CallConv, VT);
11535
11536 ReturnValues.push_back(Elt: getCopyFromParts(
11537 DAG&: CLI.DAG, DL: CLI.DL, Parts: &InVals[CurReg], NumParts: NumRegs, PartVT: RegisterVT, ValueVT: VT, V: nullptr,
11538 InChain: CLI.Chain, CC: CLI.CallConv, AssertOp));
11539 CurReg += NumRegs;
11540 }
11541
11542 // For a function returning void, there is no return value. We can't create
11543 // such a node, so we just return a null return value in that case. In
11544 // that case, nothing will actually look at the value.
11545 if (ReturnValues.empty())
11546 return std::make_pair(x: SDValue(), y&: CLI.Chain);
11547 }
11548
11549 SDValue Res = CLI.DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: CLI.DL,
11550 VTList: CLI.DAG.getVTList(VTs: RetVTs), Ops: ReturnValues);
11551 return std::make_pair(x&: Res, y&: CLI.Chain);
11552}
11553
11554/// Places new result values for the node in Results (their number
11555/// and types must exactly match those of the original return values of
11556/// the node), or leaves Results empty, which indicates that the node is not
11557/// to be custom lowered after all.
11558void TargetLowering::LowerOperationWrapper(SDNode *N,
11559 SmallVectorImpl<SDValue> &Results,
11560 SelectionDAG &DAG) const {
11561 SDValue Res = LowerOperation(Op: SDValue(N, 0), DAG);
11562
11563 if (!Res.getNode())
11564 return;
11565
11566 // If the original node has one result, take the return value from
11567 // LowerOperation as is. It might not be result number 0.
11568 if (N->getNumValues() == 1) {
11569 Results.push_back(Elt: Res);
11570 return;
11571 }
11572
11573 // If the original node has multiple results, then the return node should
11574 // have the same number of results.
11575 assert((N->getNumValues() == Res->getNumValues()) &&
11576 "Lowering returned the wrong number of results!");
11577
11578 // Places new result values base on N result number.
11579 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11580 Results.push_back(Elt: Res.getValue(R: I));
11581}
11582
11583SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11584 llvm_unreachable("LowerOperation not implemented for this target!");
11585}
11586
11587void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11588 Register Reg,
11589 ISD::NodeType ExtendType) {
11590 SDValue Op = getNonRegisterValue(V);
11591 assert((Op.getOpcode() != ISD::CopyFromReg ||
11592 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11593 "Copy from a reg to the same reg!");
11594 assert(!Reg.isPhysical() && "Is a physreg");
11595
11596 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11597 // If this is an InlineAsm we have to match the registers required, not the
11598 // notional registers required by the type.
11599
11600 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11601 std::nullopt); // This is not an ABI copy.
11602 SDValue Chain = DAG.getEntryNode();
11603
11604 if (ExtendType == ISD::ANY_EXTEND) {
11605 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(Val: V);
11606 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11607 ExtendType = PreferredExtendIt->second;
11608 }
11609 RFV.getCopyToRegs(Val: Op, DAG, dl: getCurSDLoc(), Chain, Glue: nullptr, V, PreferredExtendType: ExtendType);
11610 PendingExports.push_back(Elt: Chain);
11611}
11612
11613#include "llvm/CodeGen/SelectionDAGISel.h"
11614
11615/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11616/// entry block, return true. This includes arguments used by switches, since
11617/// the switch may expand into multiple basic blocks.
11618static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11619 // With FastISel active, we may be splitting blocks, so force creation
11620 // of virtual registers for all non-dead arguments.
11621 if (FastISel)
11622 return A->use_empty();
11623
11624 const BasicBlock &Entry = A->getParent()->front();
11625 for (const User *U : A->users())
11626 if (cast<Instruction>(Val: U)->getParent() != &Entry || isa<SwitchInst>(Val: U))
11627 return false; // Use not in entry block.
11628
11629 return true;
11630}
11631
11632using ArgCopyElisionMapTy =
11633 DenseMap<const Argument *,
11634 std::pair<const AllocaInst *, const StoreInst *>>;
11635
11636/// Scan the entry block of the function in FuncInfo for arguments that look
11637/// like copies into a local alloca. Record any copied arguments in
11638/// ArgCopyElisionCandidates.
11639static void
11640findArgumentCopyElisionCandidates(const DataLayout &DL,
11641 FunctionLoweringInfo *FuncInfo,
11642 ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11643 // Record the state of every static alloca used in the entry block. Argument
11644 // allocas are all used in the entry block, so we need approximately as many
11645 // entries as we have arguments.
11646 enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11647 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11648 unsigned NumArgs = FuncInfo->Fn->arg_size();
11649 StaticAllocas.reserve(NumEntries: NumArgs * 2);
11650
11651 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11652 if (!V)
11653 return nullptr;
11654 V = V->stripPointerCasts();
11655 const auto *AI = dyn_cast<AllocaInst>(Val: V);
11656 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(Val: AI))
11657 return nullptr;
11658 auto Iter = StaticAllocas.insert(KV: {AI, Unknown});
11659 return &Iter.first->second;
11660 };
11661
11662 // Look for stores of arguments to static allocas. Look through bitcasts and
11663 // GEPs to handle type coercions, as long as the alloca is fully initialized
11664 // by the store. Any non-store use of an alloca escapes it and any subsequent
11665 // unanalyzed store might write it.
11666 // FIXME: Handle structs initialized with multiple stores.
11667 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11668 // Look for stores, and handle non-store uses conservatively.
11669 const auto *SI = dyn_cast<StoreInst>(Val: &I);
11670 if (!SI) {
11671 // We will look through cast uses, so ignore them completely.
11672 if (I.isCast())
11673 continue;
11674 // Ignore debug info and pseudo op intrinsics, they don't escape or store
11675 // to allocas.
11676 if (I.isDebugOrPseudoInst())
11677 continue;
11678 // This is an unknown instruction. Assume it escapes or writes to all
11679 // static alloca operands.
11680 for (const Use &U : I.operands()) {
11681 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11682 *Info = StaticAllocaInfo::Clobbered;
11683 }
11684 continue;
11685 }
11686
11687 // If the stored value is a static alloca, mark it as escaped.
11688 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11689 *Info = StaticAllocaInfo::Clobbered;
11690
11691 // Check if the destination is a static alloca.
11692 const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11693 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11694 if (!Info)
11695 continue;
11696 const AllocaInst *AI = cast<AllocaInst>(Val: Dst);
11697
11698 // Skip allocas that have been initialized or clobbered.
11699 if (*Info != StaticAllocaInfo::Unknown)
11700 continue;
11701
11702 // Check if the stored value is an argument, and that this store fully
11703 // initializes the alloca.
11704 // If the argument type has padding bits we can't directly forward a pointer
11705 // as the upper bits may contain garbage.
11706 // Don't elide copies from the same argument twice.
11707 const Value *Val = SI->getValueOperand()->stripPointerCasts();
11708 const auto *Arg = dyn_cast<Argument>(Val);
11709 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL);
11710 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11711 Arg->getType()->isEmptyTy() || !AllocaSize ||
11712 DL.getTypeStoreSize(Ty: Arg->getType()) != *AllocaSize ||
11713 !DL.typeSizeEqualsStoreSize(Ty: Arg->getType()) ||
11714 ArgCopyElisionCandidates.count(Val: Arg)) {
11715 *Info = StaticAllocaInfo::Clobbered;
11716 continue;
11717 }
11718
11719 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11720 << '\n');
11721
11722 // Mark this alloca and store for argument copy elision.
11723 *Info = StaticAllocaInfo::Elidable;
11724 ArgCopyElisionCandidates.insert(KV: {Arg, {AI, SI}});
11725
11726 // Stop scanning if we've seen all arguments. This will happen early in -O0
11727 // builds, which is useful, because -O0 builds have large entry blocks and
11728 // many allocas.
11729 if (ArgCopyElisionCandidates.size() == NumArgs)
11730 break;
11731 }
11732}
11733
11734/// Try to elide argument copies from memory into a local alloca. Succeeds if
11735/// ArgVal is a load from a suitable fixed stack object.
11736static void tryToElideArgumentCopy(
11737 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11738 DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11739 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11740 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11741 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11742 // Check if this is a load from a fixed stack object.
11743 auto *LNode = dyn_cast<LoadSDNode>(Val: ArgVals[0]);
11744 if (!LNode)
11745 return;
11746 auto *FINode = dyn_cast<FrameIndexSDNode>(Val: LNode->getBasePtr().getNode());
11747 if (!FINode)
11748 return;
11749
11750 // Check that the fixed stack object is the right size and alignment.
11751 // Look at the alignment that the user wrote on the alloca instead of looking
11752 // at the stack object.
11753 auto ArgCopyIter = ArgCopyElisionCandidates.find(Val: &Arg);
11754 assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11755 const AllocaInst *AI = ArgCopyIter->second.first;
11756 int FixedIndex = FINode->getIndex();
11757 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11758 int OldIndex = AllocaIndex;
11759 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11760 if (MFI.getObjectSize(ObjectIdx: FixedIndex) != MFI.getObjectSize(ObjectIdx: OldIndex)) {
11761 LLVM_DEBUG(
11762 dbgs() << " argument copy elision failed due to bad fixed stack "
11763 "object size\n");
11764 return;
11765 }
11766 Align RequiredAlignment = AI->getAlign();
11767 if (MFI.getObjectAlign(ObjectIdx: FixedIndex) < RequiredAlignment) {
11768 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
11769 "greater than stack argument alignment ("
11770 << DebugStr(RequiredAlignment) << " vs "
11771 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11772 return;
11773 }
11774
11775 // Perform the elision. Delete the old stack object and replace its only use
11776 // in the variable info map. Mark the stack object as mutable and aliased.
11777 LLVM_DEBUG({
11778 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11779 << " Replacing frame index " << OldIndex << " with " << FixedIndex
11780 << '\n';
11781 });
11782 MFI.RemoveStackObject(ObjectIdx: OldIndex);
11783 MFI.setIsImmutableObjectIndex(ObjectIdx: FixedIndex, IsImmutable: false);
11784 MFI.setIsAliasedObjectIndex(ObjectIdx: FixedIndex, IsAliased: true);
11785 AllocaIndex = FixedIndex;
11786 ArgCopyElisionFrameIndexMap.insert(KV: {OldIndex, FixedIndex});
11787 for (SDValue ArgVal : ArgVals)
11788 Chains.push_back(Elt: ArgVal.getValue(R: 1));
11789
11790 // Avoid emitting code for the store implementing the copy.
11791 const StoreInst *SI = ArgCopyIter->second.second;
11792 ElidedArgCopyInstrs.insert(Ptr: SI);
11793
11794 // Check for uses of the argument again so that we can avoid exporting ArgVal
11795 // if it is't used by anything other than the store.
11796 for (const Value *U : Arg.users()) {
11797 if (U != SI) {
11798 ArgHasUses = true;
11799 break;
11800 }
11801 }
11802}
11803
11804void SelectionDAGISel::LowerArguments(const Function &F) {
11805 SelectionDAG &DAG = SDB->DAG;
11806 SDLoc dl = SDB->getCurSDLoc();
11807 const DataLayout &DL = DAG.getDataLayout();
11808 SmallVector<ISD::InputArg, 16> Ins;
11809
11810 // In Naked functions we aren't going to save any registers.
11811 if (F.hasFnAttribute(Kind: Attribute::Naked))
11812 return;
11813
11814 if (!FuncInfo->CanLowerReturn) {
11815 // Put in an sret pointer parameter before all the other parameters.
11816 MVT ValueVT = TLI->getPointerTy(DL, AS: DL.getAllocaAddrSpace());
11817
11818 ISD::ArgFlagsTy Flags;
11819 Flags.setSRet();
11820 MVT RegisterVT = TLI->getRegisterType(Context&: *DAG.getContext(), VT: ValueVT);
11821 ISD::InputArg RetArg(Flags, RegisterVT, ValueVT, F.getReturnType(), true,
11822 ISD::InputArg::NoArgIndex, 0);
11823 Ins.push_back(Elt: RetArg);
11824 }
11825
11826 // Look for stores of arguments to static allocas. Mark such arguments with a
11827 // flag to ask the target to give us the memory location of that argument if
11828 // available.
11829 ArgCopyElisionMapTy ArgCopyElisionCandidates;
11830 findArgumentCopyElisionCandidates(DL, FuncInfo: FuncInfo.get(),
11831 ArgCopyElisionCandidates);
11832
11833 // Set up the incoming argument description vector.
11834 for (const Argument &Arg : F.args()) {
11835 unsigned ArgNo = Arg.getArgNo();
11836 SmallVector<Type *, 4> Types;
11837 ComputeValueTypes(DL: DAG.getDataLayout(), Ty: Arg.getType(), Types);
11838 bool isArgValueUsed = !Arg.use_empty();
11839 Type *FinalType = Arg.getType();
11840 if (Arg.hasAttribute(Kind: Attribute::ByVal))
11841 FinalType = Arg.getParamByValType();
11842 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11843 Ty: FinalType, CallConv: F.getCallingConv(), isVarArg: F.isVarArg(), DL);
11844 for (unsigned Value = 0, NumValues = Types.size(); Value != NumValues;
11845 ++Value) {
11846 Type *ArgTy = Types[Value];
11847 EVT VT = TLI->getValueType(DL, Ty: ArgTy);
11848 ISD::ArgFlagsTy Flags;
11849
11850 if (ArgTy->isPointerTy()) {
11851 Flags.setPointer();
11852 Flags.setPointerAddrSpace(cast<PointerType>(Val: ArgTy)->getAddressSpace());
11853 }
11854 if (Arg.hasAttribute(Kind: Attribute::ZExt))
11855 Flags.setZExt();
11856 if (Arg.hasAttribute(Kind: Attribute::SExt))
11857 Flags.setSExt();
11858 if (Arg.hasAttribute(Kind: Attribute::InReg)) {
11859 // If we are using vectorcall calling convention, a structure that is
11860 // passed InReg - is surely an HVA
11861 if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11862 isa<StructType>(Val: Arg.getType())) {
11863 // The first value of a structure is marked
11864 if (0 == Value)
11865 Flags.setHvaStart();
11866 Flags.setHva();
11867 }
11868 // Set InReg Flag
11869 Flags.setInReg();
11870 }
11871 if (Arg.hasAttribute(Kind: Attribute::StructRet))
11872 Flags.setSRet();
11873 if (Arg.hasAttribute(Kind: Attribute::SwiftSelf))
11874 Flags.setSwiftSelf();
11875 if (Arg.hasAttribute(Kind: Attribute::SwiftAsync))
11876 Flags.setSwiftAsync();
11877 if (Arg.hasAttribute(Kind: Attribute::SwiftError))
11878 Flags.setSwiftError();
11879 if (Arg.hasAttribute(Kind: Attribute::ByVal))
11880 Flags.setByVal();
11881 if (Arg.hasAttribute(Kind: Attribute::ByRef))
11882 Flags.setByRef();
11883 if (Arg.hasAttribute(Kind: Attribute::InAlloca)) {
11884 Flags.setInAlloca();
11885 // Set the byval flag for CCAssignFn callbacks that don't know about
11886 // inalloca. This way we can know how many bytes we should've allocated
11887 // and how many bytes a callee cleanup function will pop. If we port
11888 // inalloca to more targets, we'll have to add custom inalloca handling
11889 // in the various CC lowering callbacks.
11890 Flags.setByVal();
11891 }
11892 if (Arg.hasAttribute(Kind: Attribute::Preallocated)) {
11893 Flags.setPreallocated();
11894 // Set the byval flag for CCAssignFn callbacks that don't know about
11895 // preallocated. This way we can know how many bytes we should've
11896 // allocated and how many bytes a callee cleanup function will pop. If
11897 // we port preallocated to more targets, we'll have to add custom
11898 // preallocated handling in the various CC lowering callbacks.
11899 Flags.setByVal();
11900 }
11901
11902 // Certain targets (such as MIPS), may have a different ABI alignment
11903 // for a type depending on the context. Give the target a chance to
11904 // specify the alignment it wants.
11905 const Align OriginalAlignment(
11906 TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11907 Flags.setOrigAlign(OriginalAlignment);
11908
11909 Align MemAlign;
11910 Type *ArgMemTy = nullptr;
11911 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11912 Flags.isByRef()) {
11913 if (!ArgMemTy)
11914 ArgMemTy = Arg.getPointeeInMemoryValueType();
11915
11916 uint64_t MemSize = DL.getTypeAllocSize(Ty: ArgMemTy);
11917
11918 // For in-memory arguments, size and alignment should be passed from FE.
11919 // BE will guess if this info is not there but there are cases it cannot
11920 // get right.
11921 if (auto ParamAlign = Arg.getParamStackAlign())
11922 MemAlign = *ParamAlign;
11923 else if ((ParamAlign = Arg.getParamAlign()))
11924 MemAlign = *ParamAlign;
11925 else
11926 MemAlign = TLI->getByValTypeAlignment(Ty: ArgMemTy, DL);
11927 if (Flags.isByRef())
11928 Flags.setByRefSize(MemSize);
11929 else
11930 Flags.setByValSize(MemSize);
11931 } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11932 MemAlign = *ParamAlign;
11933 } else {
11934 MemAlign = OriginalAlignment;
11935 }
11936 Flags.setMemAlign(MemAlign);
11937
11938 if (Arg.hasAttribute(Kind: Attribute::Nest))
11939 Flags.setNest();
11940 if (NeedsRegBlock)
11941 Flags.setInConsecutiveRegs();
11942 if (ArgCopyElisionCandidates.count(Val: &Arg))
11943 Flags.setCopyElisionCandidate();
11944 if (Arg.hasAttribute(Kind: Attribute::Returned))
11945 Flags.setReturned();
11946
11947 MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11948 Context&: *CurDAG->getContext(), CC: F.getCallingConv(), VT);
11949 unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11950 Context&: *CurDAG->getContext(), CC: F.getCallingConv(), VT);
11951 for (unsigned i = 0; i != NumRegs; ++i) {
11952 // For scalable vectors, use the minimum size; individual targets
11953 // are responsible for handling scalable vector arguments and
11954 // return values.
11955 ISD::InputArg MyFlags(
11956 Flags, RegisterVT, VT, ArgTy, isArgValueUsed, ArgNo,
11957 i * RegisterVT.getStoreSize().getKnownMinValue());
11958 if (NumRegs > 1 && i == 0)
11959 MyFlags.Flags.setSplit();
11960 // if it isn't first piece, alignment must be 1
11961 else if (i > 0) {
11962 MyFlags.Flags.setOrigAlign(Align(1));
11963 if (i == NumRegs - 1)
11964 MyFlags.Flags.setSplitEnd();
11965 }
11966 Ins.push_back(Elt: MyFlags);
11967 }
11968 if (NeedsRegBlock && Value == NumValues - 1)
11969 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11970 }
11971 }
11972
11973 // Call the target to set up the argument values.
11974 SmallVector<SDValue, 8> InVals;
11975 SDValue NewRoot = TLI->LowerFormalArguments(
11976 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11977
11978 // Verify that the target's LowerFormalArguments behaved as expected.
11979 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11980 "LowerFormalArguments didn't return a valid chain!");
11981 assert(InVals.size() == Ins.size() &&
11982 "LowerFormalArguments didn't emit the correct number of values!");
11983 LLVM_DEBUG({
11984 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11985 assert(InVals[i].getNode() &&
11986 "LowerFormalArguments emitted a null value!");
11987 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11988 "LowerFormalArguments emitted a value with the wrong type!");
11989 }
11990 });
11991
11992 // Update the DAG with the new chain value resulting from argument lowering.
11993 DAG.setRoot(NewRoot);
11994
11995 // Set up the argument values.
11996 unsigned i = 0;
11997 if (!FuncInfo->CanLowerReturn) {
11998 // Create a virtual register for the sret pointer, and put in a copy
11999 // from the sret argument into it.
12000 MVT VT = TLI->getPointerTy(DL, AS: DL.getAllocaAddrSpace());
12001 MVT RegVT = TLI->getRegisterType(Context&: *CurDAG->getContext(), VT);
12002 std::optional<ISD::NodeType> AssertOp;
12003 SDValue ArgValue =
12004 getCopyFromParts(DAG, DL: dl, Parts: &InVals[0], NumParts: 1, PartVT: RegVT, ValueVT: VT, V: nullptr, InChain: NewRoot,
12005 CC: F.getCallingConv(), AssertOp);
12006
12007 MachineFunction& MF = SDB->DAG.getMachineFunction();
12008 MachineRegisterInfo& RegInfo = MF.getRegInfo();
12009 Register SRetReg =
12010 RegInfo.createVirtualRegister(RegClass: TLI->getRegClassFor(VT: RegVT));
12011 FuncInfo->DemoteRegister = SRetReg;
12012 NewRoot =
12013 SDB->DAG.getCopyToReg(Chain: NewRoot, dl: SDB->getCurSDLoc(), Reg: SRetReg, N: ArgValue);
12014 DAG.setRoot(NewRoot);
12015
12016 // i indexes lowered arguments. Bump it past the hidden sret argument.
12017 ++i;
12018 }
12019
12020 SmallVector<SDValue, 4> Chains;
12021 DenseMap<int, int> ArgCopyElisionFrameIndexMap;
12022 for (const Argument &Arg : F.args()) {
12023 SmallVector<SDValue, 4> ArgValues;
12024 SmallVector<EVT, 4> ValueVTs;
12025 ComputeValueVTs(TLI: *TLI, DL: DAG.getDataLayout(), Ty: Arg.getType(), ValueVTs);
12026 unsigned NumValues = ValueVTs.size();
12027 if (NumValues == 0)
12028 continue;
12029
12030 bool ArgHasUses = !Arg.use_empty();
12031
12032 // Elide the copying store if the target loaded this argument from a
12033 // suitable fixed stack object.
12034 if (Ins[i].Flags.isCopyElisionCandidate()) {
12035 unsigned NumParts = 0;
12036 for (EVT VT : ValueVTs)
12037 NumParts += TLI->getNumRegistersForCallingConv(Context&: *CurDAG->getContext(),
12038 CC: F.getCallingConv(), VT);
12039
12040 tryToElideArgumentCopy(FuncInfo&: *FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
12041 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
12042 ArgVals: ArrayRef(&InVals[i], NumParts), ArgHasUses);
12043 }
12044
12045 // If this argument is unused then remember its value. It is used to generate
12046 // debugging information.
12047 bool isSwiftErrorArg =
12048 TLI->supportSwiftError() &&
12049 Arg.hasAttribute(Kind: Attribute::SwiftError);
12050 if (!ArgHasUses && !isSwiftErrorArg) {
12051 SDB->setUnusedArgValue(V: &Arg, NewN: InVals[i]);
12052
12053 // Also remember any frame index for use in FastISel.
12054 if (FrameIndexSDNode *FI =
12055 dyn_cast<FrameIndexSDNode>(Val: InVals[i].getNode()))
12056 FuncInfo->setArgumentFrameIndex(A: &Arg, FI: FI->getIndex());
12057 }
12058
12059 for (unsigned Val = 0; Val != NumValues; ++Val) {
12060 EVT VT = ValueVTs[Val];
12061 MVT PartVT = TLI->getRegisterTypeForCallingConv(Context&: *CurDAG->getContext(),
12062 CC: F.getCallingConv(), VT);
12063 unsigned NumParts = TLI->getNumRegistersForCallingConv(
12064 Context&: *CurDAG->getContext(), CC: F.getCallingConv(), VT);
12065
12066 // Even an apparent 'unused' swifterror argument needs to be returned. So
12067 // we do generate a copy for it that can be used on return from the
12068 // function.
12069 if (ArgHasUses || isSwiftErrorArg) {
12070 std::optional<ISD::NodeType> AssertOp;
12071 if (Arg.hasAttribute(Kind: Attribute::SExt))
12072 AssertOp = ISD::AssertSext;
12073 else if (Arg.hasAttribute(Kind: Attribute::ZExt))
12074 AssertOp = ISD::AssertZext;
12075
12076 SDValue OutVal =
12077 getCopyFromParts(DAG, DL: dl, Parts: &InVals[i], NumParts, PartVT, ValueVT: VT, V: nullptr,
12078 InChain: NewRoot, CC: F.getCallingConv(), AssertOp);
12079
12080 FPClassTest NoFPClass = Arg.getNoFPClass();
12081 if (NoFPClass != fcNone) {
12082 SDValue SDNoFPClass = DAG.getTargetConstant(
12083 Val: static_cast<uint64_t>(NoFPClass), DL: dl, VT: MVT::i32);
12084 OutVal = DAG.getNode(Opcode: ISD::AssertNoFPClass, DL: dl, VT: OutVal.getValueType(),
12085 N1: OutVal, N2: SDNoFPClass);
12086 }
12087 ArgValues.push_back(Elt: OutVal);
12088 }
12089
12090 i += NumParts;
12091 }
12092
12093 // We don't need to do anything else for unused arguments.
12094 if (ArgValues.empty())
12095 continue;
12096
12097 // Note down frame index.
12098 if (FrameIndexSDNode *FI =
12099 dyn_cast<FrameIndexSDNode>(Val: ArgValues[0].getNode()))
12100 FuncInfo->setArgumentFrameIndex(A: &Arg, FI: FI->getIndex());
12101
12102 SDValue Res = DAG.getMergeValues(Ops: ArrayRef(ArgValues.data(), NumValues),
12103 dl: SDB->getCurSDLoc());
12104
12105 SDB->setValue(V: &Arg, NewN: Res);
12106 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
12107 // We want to associate the argument with the frame index, among
12108 // involved operands, that correspond to the lowest address. The
12109 // getCopyFromParts function, called earlier, is swapping the order of
12110 // the operands to BUILD_PAIR depending on endianness. The result of
12111 // that swapping is that the least significant bits of the argument will
12112 // be in the first operand of the BUILD_PAIR node, and the most
12113 // significant bits will be in the second operand.
12114 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
12115 if (LoadSDNode *LNode =
12116 dyn_cast<LoadSDNode>(Val: Res.getOperand(i: LowAddressOp).getNode()))
12117 if (FrameIndexSDNode *FI =
12118 dyn_cast<FrameIndexSDNode>(Val: LNode->getBasePtr().getNode()))
12119 FuncInfo->setArgumentFrameIndex(A: &Arg, FI: FI->getIndex());
12120 }
12121
12122 // Analyses past this point are naive and don't expect an assertion.
12123 if (Res.getOpcode() == ISD::AssertZext)
12124 Res = Res.getOperand(i: 0);
12125
12126 // Update the SwiftErrorVRegDefMap.
12127 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
12128 Register Reg = cast<RegisterSDNode>(Val: Res.getOperand(i: 1))->getReg();
12129 if (Reg.isVirtual())
12130 SwiftError->setCurrentVReg(MBB: FuncInfo->MBB, SwiftError->getFunctionArg(),
12131 Reg);
12132 }
12133
12134 // If this argument is live outside of the entry block, insert a copy from
12135 // wherever we got it to the vreg that other BB's will reference it as.
12136 if (Res.getOpcode() == ISD::CopyFromReg) {
12137 // If we can, though, try to skip creating an unnecessary vreg.
12138 // FIXME: This isn't very clean... it would be nice to make this more
12139 // general.
12140 Register Reg = cast<RegisterSDNode>(Val: Res.getOperand(i: 1))->getReg();
12141 if (Reg.isVirtual()) {
12142 FuncInfo->ValueMap[&Arg] = Reg;
12143 continue;
12144 }
12145 }
12146 if (!isOnlyUsedInEntryBlock(A: &Arg, FastISel: TM.Options.EnableFastISel)) {
12147 FuncInfo->InitializeRegForValue(V: &Arg);
12148 SDB->CopyToExportRegsIfNeeded(V: &Arg);
12149 }
12150 }
12151
12152 if (!Chains.empty()) {
12153 Chains.push_back(Elt: NewRoot);
12154 NewRoot = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: Chains);
12155 }
12156
12157 DAG.setRoot(NewRoot);
12158
12159 assert(i == InVals.size() && "Argument register count mismatch!");
12160
12161 // If any argument copy elisions occurred and we have debug info, update the
12162 // stale frame indices used in the dbg.declare variable info table.
12163 if (!ArgCopyElisionFrameIndexMap.empty()) {
12164 for (MachineFunction::VariableDbgInfo &VI :
12165 MF->getInStackSlotVariableDbgInfo()) {
12166 auto I = ArgCopyElisionFrameIndexMap.find(Val: VI.getStackSlot());
12167 if (I != ArgCopyElisionFrameIndexMap.end())
12168 VI.updateStackSlot(NewSlot: I->second);
12169 }
12170 }
12171
12172 // Finally, if the target has anything special to do, allow it to do so.
12173 emitFunctionEntryCode();
12174}
12175
12176/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
12177/// ensure constants are generated when needed. Remember the virtual registers
12178/// that need to be added to the Machine PHI nodes as input. We cannot just
12179/// directly add them, because expansion might result in multiple MBB's for one
12180/// BB. As such, the start of the BB might correspond to a different MBB than
12181/// the end.
12182void
12183SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
12184 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12185
12186 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
12187
12188 // Check PHI nodes in successors that expect a value to be available from this
12189 // block.
12190 for (const BasicBlock *SuccBB : successors(I: LLVMBB->getTerminator())) {
12191 if (!isa<PHINode>(Val: SuccBB->begin())) continue;
12192 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(BB: SuccBB);
12193
12194 // If this terminator has multiple identical successors (common for
12195 // switches), only handle each succ once.
12196 if (!SuccsHandled.insert(Ptr: SuccMBB).second)
12197 continue;
12198
12199 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
12200
12201 // At this point we know that there is a 1-1 correspondence between LLVM PHI
12202 // nodes and Machine PHI nodes, but the incoming operands have not been
12203 // emitted yet.
12204 for (const PHINode &PN : SuccBB->phis()) {
12205 // Ignore dead phi's.
12206 if (PN.use_empty())
12207 continue;
12208
12209 // Skip empty types
12210 if (PN.getType()->isEmptyTy())
12211 continue;
12212
12213 Register Reg;
12214 const Value *PHIOp = PN.getIncomingValueForBlock(BB: LLVMBB);
12215
12216 if (const auto *C = dyn_cast<Constant>(Val: PHIOp)) {
12217 Register &RegOut = ConstantsOut[C];
12218 if (!RegOut) {
12219 RegOut = FuncInfo.CreateRegs(V: &PN);
12220 // We need to zero/sign extend ConstantInt phi operands to match
12221 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
12222 ISD::NodeType ExtendType = ISD::ANY_EXTEND;
12223 if (auto *CI = dyn_cast<ConstantInt>(Val: C))
12224 ExtendType = TLI.signExtendConstant(C: CI) ? ISD::SIGN_EXTEND
12225 : ISD::ZERO_EXTEND;
12226 CopyValueToVirtualRegister(V: C, Reg: RegOut, ExtendType);
12227 }
12228 Reg = RegOut;
12229 } else {
12230 DenseMap<const Value *, Register>::iterator I =
12231 FuncInfo.ValueMap.find(Val: PHIOp);
12232 if (I != FuncInfo.ValueMap.end())
12233 Reg = I->second;
12234 else {
12235 assert(isa<AllocaInst>(PHIOp) &&
12236 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
12237 "Didn't codegen value into a register!??");
12238 Reg = FuncInfo.CreateRegs(V: &PN);
12239 CopyValueToVirtualRegister(V: PHIOp, Reg);
12240 }
12241 }
12242
12243 // Remember that this register needs to added to the machine PHI node as
12244 // the input for this MBB.
12245 SmallVector<EVT, 4> ValueVTs;
12246 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: PN.getType(), ValueVTs);
12247 for (EVT VT : ValueVTs) {
12248 const unsigned NumRegisters = TLI.getNumRegisters(Context&: *DAG.getContext(), VT);
12249 for (unsigned i = 0; i != NumRegisters; ++i)
12250 FuncInfo.PHINodesToUpdate.emplace_back(args: &*MBBI++, args: Reg + i);
12251 Reg += NumRegisters;
12252 }
12253 }
12254 }
12255
12256 ConstantsOut.clear();
12257}
12258
12259MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
12260 MachineFunction::iterator I(MBB);
12261 if (++I == FuncInfo.MF->end())
12262 return nullptr;
12263 return &*I;
12264}
12265
12266/// During lowering new call nodes can be created (such as memset, etc.).
12267/// Those will become new roots of the current DAG, but complications arise
12268/// when they are tail calls. In such cases, the call lowering will update
12269/// the root, but the builder still needs to know that a tail call has been
12270/// lowered in order to avoid generating an additional return.
12271void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12272 // If the node is null, we do have a tail call.
12273 if (MaybeTC.getNode() != nullptr)
12274 DAG.setRoot(MaybeTC);
12275 else
12276 HasTailCall = true;
12277}
12278
12279void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12280 MachineBasicBlock *SwitchMBB,
12281 MachineBasicBlock *DefaultMBB) {
12282 MachineFunction *CurMF = FuncInfo.MF;
12283 MachineBasicBlock *NextMBB = nullptr;
12284 MachineFunction::iterator BBI(W.MBB);
12285 if (++BBI != FuncInfo.MF->end())
12286 NextMBB = &*BBI;
12287
12288 unsigned Size = W.LastCluster - W.FirstCluster + 1;
12289
12290 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12291
12292 if (Size == 2 && W.MBB == SwitchMBB) {
12293 // If any two of the cases has the same destination, and if one value
12294 // is the same as the other, but has one bit unset that the other has set,
12295 // use bit manipulation to do two compares at once. For example:
12296 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12297 // TODO: This could be extended to merge any 2 cases in switches with 3
12298 // cases.
12299 // TODO: Handle cases where W.CaseBB != SwitchBB.
12300 CaseCluster &Small = *W.FirstCluster;
12301 CaseCluster &Big = *W.LastCluster;
12302
12303 if (Small.Low == Small.High && Big.Low == Big.High &&
12304 Small.MBB == Big.MBB) {
12305 const APInt &SmallValue = Small.Low->getValue();
12306 const APInt &BigValue = Big.Low->getValue();
12307
12308 // Check that there is only one bit different.
12309 APInt CommonBit = BigValue ^ SmallValue;
12310 if (CommonBit.isPowerOf2()) {
12311 SDValue CondLHS = getValue(V: Cond);
12312 EVT VT = CondLHS.getValueType();
12313 SDLoc DL = getCurSDLoc();
12314
12315 SDValue Or = DAG.getNode(Opcode: ISD::OR, DL, VT, N1: CondLHS,
12316 N2: DAG.getConstant(Val: CommonBit, DL, VT));
12317 SDValue Cond = DAG.getSetCC(
12318 DL, VT: MVT::i1, LHS: Or, RHS: DAG.getConstant(Val: BigValue | SmallValue, DL, VT),
12319 Cond: ISD::SETEQ);
12320
12321 // Update successor info.
12322 // Both Small and Big will jump to Small.BB, so we sum up the
12323 // probabilities.
12324 addSuccessorWithProb(Src: SwitchMBB, Dst: Small.MBB, Prob: Small.Prob + Big.Prob);
12325 if (BPI)
12326 addSuccessorWithProb(
12327 Src: SwitchMBB, Dst: DefaultMBB,
12328 // The default destination is the first successor in IR.
12329 Prob: BPI->getEdgeProbability(Src: SwitchMBB->getBasicBlock(), IndexInSuccessors: (unsigned)0));
12330 else
12331 addSuccessorWithProb(Src: SwitchMBB, Dst: DefaultMBB);
12332
12333 // Insert the true branch.
12334 SDValue BrCond =
12335 DAG.getNode(Opcode: ISD::BRCOND, DL, VT: MVT::Other, N1: getControlRoot(), N2: Cond,
12336 N3: DAG.getBasicBlock(MBB: Small.MBB));
12337 // Insert the false branch.
12338 BrCond = DAG.getNode(Opcode: ISD::BR, DL, VT: MVT::Other, N1: BrCond,
12339 N2: DAG.getBasicBlock(MBB: DefaultMBB));
12340
12341 DAG.setRoot(BrCond);
12342 return;
12343 }
12344 }
12345 }
12346
12347 if (TM.getOptLevel() != CodeGenOptLevel::None) {
12348 // Here, we order cases by probability so the most likely case will be
12349 // checked first. However, two clusters can have the same probability in
12350 // which case their relative ordering is non-deterministic. So we use Low
12351 // as a tie-breaker as clusters are guaranteed to never overlap.
12352 llvm::sort(Start: W.FirstCluster, End: W.LastCluster + 1,
12353 Comp: [](const CaseCluster &a, const CaseCluster &b) {
12354 return a.Prob != b.Prob ?
12355 a.Prob > b.Prob :
12356 a.Low->getValue().slt(RHS: b.Low->getValue());
12357 });
12358
12359 // Rearrange the case blocks so that the last one falls through if possible
12360 // without changing the order of probabilities.
12361 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12362 --I;
12363 if (I->Prob > W.LastCluster->Prob)
12364 break;
12365 if (I->Kind == CC_Range && I->MBB == NextMBB) {
12366 std::swap(a&: *I, b&: *W.LastCluster);
12367 break;
12368 }
12369 }
12370 }
12371
12372 // Compute total probability.
12373 BranchProbability DefaultProb = W.DefaultProb;
12374 BranchProbability UnhandledProbs = DefaultProb;
12375 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12376 UnhandledProbs += I->Prob;
12377
12378 MachineBasicBlock *CurMBB = W.MBB;
12379 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12380 bool FallthroughUnreachable = false;
12381 MachineBasicBlock *Fallthrough;
12382 if (I == W.LastCluster) {
12383 // For the last cluster, fall through to the default destination.
12384 Fallthrough = DefaultMBB;
12385 FallthroughUnreachable = isa<UnreachableInst>(
12386 Val: DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12387 } else {
12388 Fallthrough = CurMF->CreateMachineBasicBlock(BB: CurMBB->getBasicBlock());
12389 CurMF->insert(MBBI: BBI, MBB: Fallthrough);
12390 // Put Cond in a virtual register to make it available from the new blocks.
12391 ExportFromCurrentBlock(V: Cond);
12392 }
12393 UnhandledProbs -= I->Prob;
12394
12395 switch (I->Kind) {
12396 case CC_JumpTable: {
12397 // FIXME: Optimize away range check based on pivot comparisons.
12398 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12399 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12400
12401 // The jump block hasn't been inserted yet; insert it here.
12402 MachineBasicBlock *JumpMBB = JT->MBB;
12403 CurMF->insert(MBBI: BBI, MBB: JumpMBB);
12404
12405 auto JumpProb = I->Prob;
12406 auto FallthroughProb = UnhandledProbs;
12407
12408 // If the default statement is a target of the jump table, we evenly
12409 // distribute the default probability to successors of CurMBB. Also
12410 // update the probability on the edge from JumpMBB to Fallthrough.
12411 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12412 SE = JumpMBB->succ_end();
12413 SI != SE; ++SI) {
12414 if (*SI == DefaultMBB) {
12415 JumpProb += DefaultProb / 2;
12416 FallthroughProb -= DefaultProb / 2;
12417 JumpMBB->setSuccProbability(I: SI, Prob: DefaultProb / 2);
12418 JumpMBB->normalizeSuccProbs();
12419 break;
12420 }
12421 }
12422
12423 // If the default clause is unreachable, propagate that knowledge into
12424 // JTH->FallthroughUnreachable which will use it to suppress the range
12425 // check.
12426 //
12427 // However, don't do this if we're doing branch target enforcement,
12428 // because a table branch _without_ a range check can be a tempting JOP
12429 // gadget - out-of-bounds inputs that are impossible in correct
12430 // execution become possible again if an attacker can influence the
12431 // control flow. So if an attacker doesn't already have a BTI bypass
12432 // available, we don't want them to be able to get one out of this
12433 // table branch.
12434 if (FallthroughUnreachable) {
12435 Function &CurFunc = CurMF->getFunction();
12436 if (!CurFunc.hasFnAttribute(Kind: "branch-target-enforcement"))
12437 JTH->FallthroughUnreachable = true;
12438 }
12439
12440 if (!JTH->FallthroughUnreachable)
12441 addSuccessorWithProb(Src: CurMBB, Dst: Fallthrough, Prob: FallthroughProb);
12442 addSuccessorWithProb(Src: CurMBB, Dst: JumpMBB, Prob: JumpProb);
12443 CurMBB->normalizeSuccProbs();
12444
12445 // The jump table header will be inserted in our current block, do the
12446 // range check, and fall through to our fallthrough block.
12447 JTH->HeaderBB = CurMBB;
12448 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12449
12450 // If we're in the right place, emit the jump table header right now.
12451 if (CurMBB == SwitchMBB) {
12452 visitJumpTableHeader(JT&: *JT, JTH&: *JTH, SwitchBB: SwitchMBB);
12453 JTH->Emitted = true;
12454 }
12455 break;
12456 }
12457 case CC_BitTests: {
12458 // FIXME: Optimize away range check based on pivot comparisons.
12459 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12460
12461 // The bit test blocks haven't been inserted yet; insert them here.
12462 for (BitTestCase &BTC : BTB->Cases)
12463 CurMF->insert(MBBI: BBI, MBB: BTC.ThisBB);
12464
12465 // Fill in fields of the BitTestBlock.
12466 BTB->Parent = CurMBB;
12467 BTB->Default = Fallthrough;
12468
12469 BTB->DefaultProb = UnhandledProbs;
12470 // If the cases in bit test don't form a contiguous range, we evenly
12471 // distribute the probability on the edge to Fallthrough to two
12472 // successors of CurMBB.
12473 if (!BTB->ContiguousRange) {
12474 BTB->Prob += DefaultProb / 2;
12475 BTB->DefaultProb -= DefaultProb / 2;
12476 }
12477
12478 if (FallthroughUnreachable)
12479 BTB->FallthroughUnreachable = true;
12480
12481 // If we're in the right place, emit the bit test header right now.
12482 if (CurMBB == SwitchMBB) {
12483 visitBitTestHeader(B&: *BTB, SwitchBB: SwitchMBB);
12484 BTB->Emitted = true;
12485 }
12486 break;
12487 }
12488 case CC_Range: {
12489 const Value *RHS, *LHS, *MHS;
12490 ISD::CondCode CC;
12491 if (I->Low == I->High) {
12492 // Check Cond == I->Low.
12493 CC = ISD::SETEQ;
12494 LHS = Cond;
12495 RHS=I->Low;
12496 MHS = nullptr;
12497 } else {
12498 // Check I->Low <= Cond <= I->High.
12499 CC = ISD::SETLE;
12500 LHS = I->Low;
12501 MHS = Cond;
12502 RHS = I->High;
12503 }
12504
12505 // If Fallthrough is unreachable, fold away the comparison.
12506 if (FallthroughUnreachable)
12507 CC = ISD::SETTRUE;
12508
12509 // The false probability is the sum of all unhandled cases.
12510 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12511 getCurSDLoc(), I->Prob, UnhandledProbs);
12512
12513 if (CurMBB == SwitchMBB)
12514 visitSwitchCase(CB, SwitchBB: SwitchMBB);
12515 else
12516 SL->SwitchCases.push_back(x: CB);
12517
12518 break;
12519 }
12520 }
12521 CurMBB = Fallthrough;
12522 }
12523}
12524
12525void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12526 const SwitchWorkListItem &W,
12527 Value *Cond,
12528 MachineBasicBlock *SwitchMBB) {
12529 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12530 "Clusters not sorted?");
12531 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12532
12533 auto [LastLeft, FirstRight, LeftProb, RightProb] =
12534 SL->computeSplitWorkItemInfo(W);
12535
12536 // Use the first element on the right as pivot since we will make less-than
12537 // comparisons against it.
12538 CaseClusterIt PivotCluster = FirstRight;
12539 assert(PivotCluster > W.FirstCluster);
12540 assert(PivotCluster <= W.LastCluster);
12541
12542 CaseClusterIt FirstLeft = W.FirstCluster;
12543 CaseClusterIt LastRight = W.LastCluster;
12544
12545 const ConstantInt *Pivot = PivotCluster->Low;
12546
12547 // New blocks will be inserted immediately after the current one.
12548 MachineFunction::iterator BBI(W.MBB);
12549 ++BBI;
12550
12551 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12552 // we can branch to its destination directly if it's squeezed exactly in
12553 // between the known lower bound and Pivot - 1.
12554 MachineBasicBlock *LeftMBB;
12555 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12556 FirstLeft->Low == W.GE &&
12557 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12558 LeftMBB = FirstLeft->MBB;
12559 } else {
12560 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(BB: W.MBB->getBasicBlock());
12561 FuncInfo.MF->insert(MBBI: BBI, MBB: LeftMBB);
12562 WorkList.push_back(
12563 Elt: {.MBB: LeftMBB, .FirstCluster: FirstLeft, .LastCluster: LastLeft, .GE: W.GE, .LT: Pivot, .DefaultProb: W.DefaultProb / 2});
12564 // Put Cond in a virtual register to make it available from the new blocks.
12565 ExportFromCurrentBlock(V: Cond);
12566 }
12567
12568 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12569 // single cluster, RHS.Low == Pivot, and we can branch to its destination
12570 // directly if RHS.High equals the current upper bound.
12571 MachineBasicBlock *RightMBB;
12572 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12573 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12574 RightMBB = FirstRight->MBB;
12575 } else {
12576 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(BB: W.MBB->getBasicBlock());
12577 FuncInfo.MF->insert(MBBI: BBI, MBB: RightMBB);
12578 WorkList.push_back(
12579 Elt: {.MBB: RightMBB, .FirstCluster: FirstRight, .LastCluster: LastRight, .GE: Pivot, .LT: W.LT, .DefaultProb: W.DefaultProb / 2});
12580 // Put Cond in a virtual register to make it available from the new blocks.
12581 ExportFromCurrentBlock(V: Cond);
12582 }
12583
12584 // Create the CaseBlock record that will be used to lower the branch.
12585 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12586 getCurSDLoc(), LeftProb, RightProb);
12587
12588 if (W.MBB == SwitchMBB)
12589 visitSwitchCase(CB, SwitchBB: SwitchMBB);
12590 else
12591 SL->SwitchCases.push_back(x: CB);
12592}
12593
12594// Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12595// from the swith statement.
12596static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12597 BranchProbability PeeledCaseProb) {
12598 if (PeeledCaseProb == BranchProbability::getOne())
12599 return BranchProbability::getZero();
12600 BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12601
12602 uint32_t Numerator = CaseProb.getNumerator();
12603 uint32_t Denominator = SwitchProb.scale(Num: CaseProb.getDenominator());
12604 return BranchProbability(Numerator, std::max(a: Numerator, b: Denominator));
12605}
12606
12607// Try to peel the top probability case if it exceeds the threshold.
12608// Return current MachineBasicBlock for the switch statement if the peeling
12609// does not occur.
12610// If the peeling is performed, return the newly created MachineBasicBlock
12611// for the peeled switch statement. Also update Clusters to remove the peeled
12612// case. PeeledCaseProb is the BranchProbability for the peeled case.
12613MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12614 const SwitchInst &SI, CaseClusterVector &Clusters,
12615 BranchProbability &PeeledCaseProb) {
12616 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12617 // Don't perform if there is only one cluster or optimizing for size.
12618 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12619 TM.getOptLevel() == CodeGenOptLevel::None ||
12620 SwitchMBB->getParent()->getFunction().hasMinSize())
12621 return SwitchMBB;
12622
12623 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12624 unsigned PeeledCaseIndex = 0;
12625 bool SwitchPeeled = false;
12626 for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12627 CaseCluster &CC = Clusters[Index];
12628 if (CC.Prob < TopCaseProb)
12629 continue;
12630 TopCaseProb = CC.Prob;
12631 PeeledCaseIndex = Index;
12632 SwitchPeeled = true;
12633 }
12634 if (!SwitchPeeled)
12635 return SwitchMBB;
12636
12637 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12638 << TopCaseProb << "\n");
12639
12640 // Record the MBB for the peeled switch statement.
12641 MachineFunction::iterator BBI(SwitchMBB);
12642 ++BBI;
12643 MachineBasicBlock *PeeledSwitchMBB =
12644 FuncInfo.MF->CreateMachineBasicBlock(BB: SwitchMBB->getBasicBlock());
12645 FuncInfo.MF->insert(MBBI: BBI, MBB: PeeledSwitchMBB);
12646
12647 ExportFromCurrentBlock(V: SI.getCondition());
12648 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12649 SwitchWorkListItem W = {.MBB: SwitchMBB, .FirstCluster: PeeledCaseIt, .LastCluster: PeeledCaseIt,
12650 .GE: nullptr, .LT: nullptr, .DefaultProb: TopCaseProb.getCompl()};
12651 lowerWorkItem(W, Cond: SI.getCondition(), SwitchMBB, DefaultMBB: PeeledSwitchMBB);
12652
12653 Clusters.erase(position: PeeledCaseIt);
12654 for (CaseCluster &CC : Clusters) {
12655 LLVM_DEBUG(
12656 dbgs() << "Scale the probablity for one cluster, before scaling: "
12657 << CC.Prob << "\n");
12658 CC.Prob = scaleCaseProbality(CaseProb: CC.Prob, PeeledCaseProb: TopCaseProb);
12659 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12660 }
12661 PeeledCaseProb = TopCaseProb;
12662 return PeeledSwitchMBB;
12663}
12664
12665void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12666 // Extract cases from the switch.
12667 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12668 CaseClusterVector Clusters;
12669 Clusters.reserve(n: SI.getNumCases());
12670 for (auto I : SI.cases()) {
12671 MachineBasicBlock *Succ = FuncInfo.getMBB(BB: I.getCaseSuccessor());
12672 const ConstantInt *CaseVal = I.getCaseValue();
12673 BranchProbability Prob =
12674 BPI ? BPI->getEdgeProbability(Src: SI.getParent(), IndexInSuccessors: I.getSuccessorIndex())
12675 : BranchProbability(1, SI.getNumCases() + 1);
12676 Clusters.push_back(x: CaseCluster::range(Low: CaseVal, High: CaseVal, MBB: Succ, Prob));
12677 }
12678
12679 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(BB: SI.getDefaultDest());
12680
12681 // Cluster adjacent cases with the same destination. We do this at all
12682 // optimization levels because it's cheap to do and will make codegen faster
12683 // if there are many clusters.
12684 sortAndRangeify(Clusters);
12685
12686 // The branch probablity of the peeled case.
12687 BranchProbability PeeledCaseProb = BranchProbability::getZero();
12688 MachineBasicBlock *PeeledSwitchMBB =
12689 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12690
12691 // If there is only the default destination, jump there directly.
12692 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12693 if (Clusters.empty()) {
12694 assert(PeeledSwitchMBB == SwitchMBB);
12695 SwitchMBB->addSuccessor(Succ: DefaultMBB);
12696 if (DefaultMBB != NextBlock(MBB: SwitchMBB)) {
12697 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other,
12698 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: DefaultMBB)));
12699 }
12700 return;
12701 }
12702
12703 SL->findJumpTables(Clusters, SI: &SI, SL: getCurSDLoc(), DefaultMBB, PSI: DAG.getPSI(),
12704 BFI: DAG.getBFI());
12705 SL->findBitTestClusters(Clusters, SI: &SI);
12706
12707 LLVM_DEBUG({
12708 dbgs() << "Case clusters: ";
12709 for (const CaseCluster &C : Clusters) {
12710 if (C.Kind == CC_JumpTable)
12711 dbgs() << "JT:";
12712 if (C.Kind == CC_BitTests)
12713 dbgs() << "BT:";
12714
12715 C.Low->getValue().print(dbgs(), true);
12716 if (C.Low != C.High) {
12717 dbgs() << '-';
12718 C.High->getValue().print(dbgs(), true);
12719 }
12720 dbgs() << ' ';
12721 }
12722 dbgs() << '\n';
12723 });
12724
12725 assert(!Clusters.empty());
12726 SwitchWorkList WorkList;
12727 CaseClusterIt First = Clusters.begin();
12728 CaseClusterIt Last = Clusters.end() - 1;
12729 auto DefaultProb = getEdgeProbability(Src: PeeledSwitchMBB, Dst: DefaultMBB);
12730 // Scale the branchprobability for DefaultMBB if the peel occurs and
12731 // DefaultMBB is not replaced.
12732 if (PeeledCaseProb != BranchProbability::getZero() &&
12733 DefaultMBB == FuncInfo.getMBB(BB: SI.getDefaultDest()))
12734 DefaultProb = scaleCaseProbality(CaseProb: DefaultProb, PeeledCaseProb);
12735 WorkList.push_back(
12736 Elt: {.MBB: PeeledSwitchMBB, .FirstCluster: First, .LastCluster: Last, .GE: nullptr, .LT: nullptr, .DefaultProb: DefaultProb});
12737
12738 while (!WorkList.empty()) {
12739 SwitchWorkListItem W = WorkList.pop_back_val();
12740 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12741
12742 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12743 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12744 // For optimized builds, lower large range as a balanced binary tree.
12745 splitWorkItem(WorkList, W, Cond: SI.getCondition(), SwitchMBB);
12746 continue;
12747 }
12748
12749 lowerWorkItem(W, Cond: SI.getCondition(), SwitchMBB, DefaultMBB);
12750 }
12751}
12752
12753void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12754 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12755 auto DL = getCurSDLoc();
12756 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
12757 setValue(V: &I, NewN: DAG.getStepVector(DL, ResVT: ResultVT));
12758}
12759
12760void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12761 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12762 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
12763
12764 SDLoc DL = getCurSDLoc();
12765 SDValue V = getValue(V: I.getOperand(i_nocapture: 0));
12766 assert(VT == V.getValueType() && "Malformed vector.reverse!");
12767
12768 if (VT.isScalableVector()) {
12769 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::VECTOR_REVERSE, DL, VT, Operand: V));
12770 return;
12771 }
12772
12773 // Use VECTOR_SHUFFLE for the fixed-length vector
12774 // to maintain existing behavior.
12775 SmallVector<int, 8> Mask;
12776 unsigned NumElts = VT.getVectorMinNumElements();
12777 for (unsigned i = 0; i != NumElts; ++i)
12778 Mask.push_back(Elt: NumElts - 1 - i);
12779
12780 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: V, N2: DAG.getUNDEF(VT), Mask));
12781}
12782
12783void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I,
12784 unsigned Factor) {
12785 auto DL = getCurSDLoc();
12786 SDValue InVec = getValue(V: I.getOperand(i_nocapture: 0));
12787
12788 SmallVector<EVT, 4> ValueVTs;
12789 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty: I.getType(),
12790 ValueVTs);
12791
12792 EVT OutVT = ValueVTs[0];
12793 unsigned OutNumElts = OutVT.getVectorMinNumElements();
12794
12795 SmallVector<SDValue, 4> SubVecs(Factor);
12796 for (unsigned i = 0; i != Factor; ++i) {
12797 assert(ValueVTs[i] == OutVT && "Expected VTs to be the same");
12798 SubVecs[i] = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: OutVT, N1: InVec,
12799 N2: DAG.getVectorIdxConstant(Val: OutNumElts * i, DL));
12800 }
12801
12802 // Use VECTOR_SHUFFLE for fixed-length vectors with factor of 2 to benefit
12803 // from existing legalisation and combines.
12804 if (OutVT.isFixedLengthVector() && Factor == 2) {
12805 SDValue Even = DAG.getVectorShuffle(VT: OutVT, dl: DL, N1: SubVecs[0], N2: SubVecs[1],
12806 Mask: createStrideMask(Start: 0, Stride: 2, VF: OutNumElts));
12807 SDValue Odd = DAG.getVectorShuffle(VT: OutVT, dl: DL, N1: SubVecs[0], N2: SubVecs[1],
12808 Mask: createStrideMask(Start: 1, Stride: 2, VF: OutNumElts));
12809 SDValue Res = DAG.getMergeValues(Ops: {Even, Odd}, dl: getCurSDLoc());
12810 setValue(V: &I, NewN: Res);
12811 return;
12812 }
12813
12814 SDValue Res = DAG.getNode(Opcode: ISD::VECTOR_DEINTERLEAVE, DL,
12815 VTList: DAG.getVTList(VTs: ValueVTs), Ops: SubVecs);
12816 setValue(V: &I, NewN: Res);
12817}
12818
12819void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I,
12820 unsigned Factor) {
12821 auto DL = getCurSDLoc();
12822 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12823 EVT InVT = getValue(V: I.getOperand(i_nocapture: 0)).getValueType();
12824 EVT OutVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
12825
12826 SmallVector<SDValue, 8> InVecs(Factor);
12827 for (unsigned i = 0; i < Factor; ++i) {
12828 InVecs[i] = getValue(V: I.getOperand(i_nocapture: i));
12829 assert(InVecs[i].getValueType() == InVecs[0].getValueType() &&
12830 "Expected VTs to be the same");
12831 }
12832
12833 // Use VECTOR_SHUFFLE for fixed-length vectors with factor of 2 to benefit
12834 // from existing legalisation and combines.
12835 if (OutVT.isFixedLengthVector() && Factor == 2) {
12836 unsigned NumElts = InVT.getVectorMinNumElements();
12837 SDValue V = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: OutVT, Ops: InVecs);
12838 setValue(V: &I, NewN: DAG.getVectorShuffle(VT: OutVT, dl: DL, N1: V, N2: DAG.getUNDEF(VT: OutVT),
12839 Mask: createInterleaveMask(VF: NumElts, NumVecs: 2)));
12840 return;
12841 }
12842
12843 SmallVector<EVT, 8> ValueVTs(Factor, InVT);
12844 SDValue Res =
12845 DAG.getNode(Opcode: ISD::VECTOR_INTERLEAVE, DL, VTList: DAG.getVTList(VTs: ValueVTs), Ops: InVecs);
12846
12847 SmallVector<SDValue, 8> Results(Factor);
12848 for (unsigned i = 0; i < Factor; ++i)
12849 Results[i] = Res.getValue(R: i);
12850
12851 Res = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: OutVT, Ops: Results);
12852 setValue(V: &I, NewN: Res);
12853}
12854
12855void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12856 SmallVector<EVT, 4> ValueVTs;
12857 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty: I.getType(),
12858 ValueVTs);
12859 unsigned NumValues = ValueVTs.size();
12860 if (NumValues == 0) return;
12861
12862 SmallVector<SDValue, 4> Values(NumValues);
12863 SDValue Op = getValue(V: I.getOperand(i_nocapture: 0));
12864
12865 for (unsigned i = 0; i != NumValues; ++i)
12866 Values[i] = DAG.getNode(Opcode: ISD::FREEZE, DL: getCurSDLoc(), VT: ValueVTs[i],
12867 Operand: SDValue(Op.getNode(), Op.getResNo() + i));
12868
12869 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
12870 VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values));
12871}
12872
12873void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12874 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12875 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
12876
12877 SDLoc DL = getCurSDLoc();
12878 SDValue V1 = getValue(V: I.getOperand(i_nocapture: 0));
12879 SDValue V2 = getValue(V: I.getOperand(i_nocapture: 1));
12880 const bool IsLeft = I.getIntrinsicID() == Intrinsic::vector_splice_left;
12881
12882 // VECTOR_SHUFFLE doesn't support a scalable or non-constant mask.
12883 if (VT.isScalableVector() || !isa<ConstantInt>(Val: I.getOperand(i_nocapture: 2))) {
12884 SDValue Offset = DAG.getZExtOrTrunc(
12885 Op: getValue(V: I.getOperand(i_nocapture: 2)), DL, VT: TLI.getVectorIdxTy(DL: DAG.getDataLayout()));
12886 setValue(V: &I, NewN: DAG.getNode(Opcode: IsLeft ? ISD::VECTOR_SPLICE_LEFT
12887 : ISD::VECTOR_SPLICE_RIGHT,
12888 DL, VT, N1: V1, N2: V2, N3: Offset));
12889 return;
12890 }
12891 uint64_t Imm = cast<ConstantInt>(Val: I.getOperand(i_nocapture: 2))->getZExtValue();
12892
12893 unsigned NumElts = VT.getVectorNumElements();
12894
12895 uint64_t Idx = IsLeft ? Imm : NumElts - Imm;
12896
12897 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12898 SmallVector<int, 8> Mask;
12899 for (unsigned i = 0; i < NumElts; ++i)
12900 Mask.push_back(Elt: Idx + i);
12901 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: V1, N2: V2, Mask));
12902}
12903
12904// Consider the following MIR after SelectionDAG, which produces output in
12905// phyregs in the first case or virtregs in the second case.
12906//
12907// INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12908// %5:gr32 = COPY $ebx
12909// %6:gr32 = COPY $edx
12910// %1:gr32 = COPY %6:gr32
12911// %0:gr32 = COPY %5:gr32
12912//
12913// INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12914// %1:gr32 = COPY %6:gr32
12915// %0:gr32 = COPY %5:gr32
12916//
12917// Given %0, we'd like to return $ebx in the first case and %5 in the second.
12918// Given %1, we'd like to return $edx in the first case and %6 in the second.
12919//
12920// If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12921// to a single virtreg (such as %0). The remaining outputs monotonically
12922// increase in virtreg number from there. If a callbr has no outputs, then it
12923// should not have a corresponding callbr landingpad; in fact, the callbr
12924// landingpad would not even be able to refer to such a callbr.
12925static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12926 MachineInstr *MI = MRI.def_begin(RegNo: Reg)->getParent();
12927 // There is definitely at least one copy.
12928 assert(MI->getOpcode() == TargetOpcode::COPY &&
12929 "start of copy chain MUST be COPY");
12930 Reg = MI->getOperand(i: 1).getReg();
12931
12932 // If the copied register in the first copy must be virtual.
12933 assert(Reg.isVirtual() && "expected COPY of virtual register");
12934 MI = MRI.def_begin(RegNo: Reg)->getParent();
12935
12936 // There may be an optional second copy.
12937 if (MI->getOpcode() == TargetOpcode::COPY) {
12938 assert(Reg.isVirtual() && "expected COPY of virtual register");
12939 Reg = MI->getOperand(i: 1).getReg();
12940 assert(Reg.isPhysical() && "expected COPY of physical register");
12941 } else {
12942 // The start of the chain must be an INLINEASM_BR.
12943 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12944 "end of copy chain MUST be INLINEASM_BR");
12945 }
12946
12947 return Reg;
12948}
12949
12950// We must do this walk rather than the simpler
12951// setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12952// otherwise we will end up with copies of virtregs only valid along direct
12953// edges.
12954void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12955 SmallVector<EVT, 8> ResultVTs;
12956 SmallVector<SDValue, 8> ResultValues;
12957 const auto *CBR =
12958 cast<CallBrInst>(Val: I.getParent()->getUniquePredecessor()->getTerminator());
12959
12960 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12961 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12962 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12963
12964 Register InitialDef = FuncInfo.ValueMap[CBR];
12965 SDValue Chain = DAG.getRoot();
12966
12967 // Re-parse the asm constraints string.
12968 TargetLowering::AsmOperandInfoVector TargetConstraints =
12969 TLI.ParseConstraints(DL: DAG.getDataLayout(), TRI, Call: *CBR);
12970 for (auto &T : TargetConstraints) {
12971 SDISelAsmOperandInfo OpInfo(T);
12972 if (OpInfo.Type != InlineAsm::isOutput)
12973 continue;
12974
12975 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12976 // individual constraint.
12977 TLI.ComputeConstraintToUse(OpInfo, Op: OpInfo.CallOperand, DAG: &DAG);
12978
12979 switch (OpInfo.ConstraintType) {
12980 case TargetLowering::C_Register:
12981 case TargetLowering::C_RegisterClass: {
12982 // Fill in OpInfo.AssignedRegs.Regs.
12983 getRegistersForValue(DAG, DL: getCurSDLoc(), OpInfo, RefOpInfo&: OpInfo);
12984
12985 // getRegistersForValue may produce 1 to many registers based on whether
12986 // the OpInfo.ConstraintVT is legal on the target or not.
12987 for (Register &Reg : OpInfo.AssignedRegs.Regs) {
12988 Register OriginalDef = FollowCopyChain(MRI, Reg: InitialDef++);
12989 if (OriginalDef.isPhysical())
12990 FuncInfo.MBB->addLiveIn(PhysReg: OriginalDef);
12991 // Update the assigned registers to use the original defs.
12992 Reg = OriginalDef;
12993 }
12994
12995 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12996 DAG, FuncInfo, dl: getCurSDLoc(), Chain, Glue: nullptr, V: CBR);
12997 ResultValues.push_back(Elt: V);
12998 ResultVTs.push_back(Elt: OpInfo.ConstraintVT);
12999 break;
13000 }
13001 case TargetLowering::C_Other: {
13002 SDValue Flag;
13003 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Glue&: Flag, DL: getCurSDLoc(),
13004 OpInfo, DAG);
13005 ++InitialDef;
13006 ResultValues.push_back(Elt: V);
13007 ResultVTs.push_back(Elt: OpInfo.ConstraintVT);
13008 break;
13009 }
13010 default:
13011 break;
13012 }
13013 }
13014 SDValue V = DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
13015 VTList: DAG.getVTList(VTs: ResultVTs), Ops: ResultValues);
13016 setValue(V: &I, NewN: V);
13017}
13018