1//===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements routines for translating from LLVM IR into SelectionDAG IR.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SelectionDAGBuilder.h"
14#include "SDNodeDbgValue.h"
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/Analysis/BranchProbabilityInfo.h"
25#include "llvm/Analysis/ConstantFolding.h"
26#include "llvm/Analysis/Loads.h"
27#include "llvm/Analysis/MemoryLocation.h"
28#include "llvm/Analysis/TargetLibraryInfo.h"
29#include "llvm/Analysis/TargetTransformInfo.h"
30#include "llvm/Analysis/ValueTracking.h"
31#include "llvm/Analysis/VectorUtils.h"
32#include "llvm/CodeGen/Analysis.h"
33#include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
34#include "llvm/CodeGen/CodeGenCommonISel.h"
35#include "llvm/CodeGen/FunctionLoweringInfo.h"
36#include "llvm/CodeGen/GCMetadata.h"
37#include "llvm/CodeGen/ISDOpcodes.h"
38#include "llvm/CodeGen/MachineBasicBlock.h"
39#include "llvm/CodeGen/MachineFrameInfo.h"
40#include "llvm/CodeGen/MachineFunction.h"
41#include "llvm/CodeGen/MachineInstrBuilder.h"
42#include "llvm/CodeGen/MachineInstrBundleIterator.h"
43#include "llvm/CodeGen/MachineMemOperand.h"
44#include "llvm/CodeGen/MachineModuleInfo.h"
45#include "llvm/CodeGen/MachineOperand.h"
46#include "llvm/CodeGen/MachineRegisterInfo.h"
47#include "llvm/CodeGen/SelectionDAG.h"
48#include "llvm/CodeGen/SelectionDAGNodes.h"
49#include "llvm/CodeGen/SelectionDAGTargetInfo.h"
50#include "llvm/CodeGen/StackMaps.h"
51#include "llvm/CodeGen/SwiftErrorValueTracking.h"
52#include "llvm/CodeGen/TargetFrameLowering.h"
53#include "llvm/CodeGen/TargetInstrInfo.h"
54#include "llvm/CodeGen/TargetOpcodes.h"
55#include "llvm/CodeGen/TargetRegisterInfo.h"
56#include "llvm/CodeGen/TargetSubtargetInfo.h"
57#include "llvm/CodeGen/WinEHFuncInfo.h"
58#include "llvm/IR/Argument.h"
59#include "llvm/IR/Attributes.h"
60#include "llvm/IR/BasicBlock.h"
61#include "llvm/IR/CFG.h"
62#include "llvm/IR/CallingConv.h"
63#include "llvm/IR/Constant.h"
64#include "llvm/IR/ConstantRange.h"
65#include "llvm/IR/Constants.h"
66#include "llvm/IR/DataLayout.h"
67#include "llvm/IR/DebugInfo.h"
68#include "llvm/IR/DebugInfoMetadata.h"
69#include "llvm/IR/DerivedTypes.h"
70#include "llvm/IR/DiagnosticInfo.h"
71#include "llvm/IR/EHPersonalities.h"
72#include "llvm/IR/Function.h"
73#include "llvm/IR/GetElementPtrTypeIterator.h"
74#include "llvm/IR/InlineAsm.h"
75#include "llvm/IR/InstrTypes.h"
76#include "llvm/IR/Instructions.h"
77#include "llvm/IR/IntrinsicInst.h"
78#include "llvm/IR/Intrinsics.h"
79#include "llvm/IR/IntrinsicsAArch64.h"
80#include "llvm/IR/IntrinsicsAMDGPU.h"
81#include "llvm/IR/IntrinsicsWebAssembly.h"
82#include "llvm/IR/LLVMContext.h"
83#include "llvm/IR/MemoryModelRelaxationAnnotations.h"
84#include "llvm/IR/Metadata.h"
85#include "llvm/IR/Module.h"
86#include "llvm/IR/Operator.h"
87#include "llvm/IR/PatternMatch.h"
88#include "llvm/IR/Statepoint.h"
89#include "llvm/IR/Type.h"
90#include "llvm/IR/User.h"
91#include "llvm/IR/Value.h"
92#include "llvm/MC/MCContext.h"
93#include "llvm/Support/AtomicOrdering.h"
94#include "llvm/Support/Casting.h"
95#include "llvm/Support/CommandLine.h"
96#include "llvm/Support/Compiler.h"
97#include "llvm/Support/Debug.h"
98#include "llvm/Support/InstructionCost.h"
99#include "llvm/Support/MathExtras.h"
100#include "llvm/Support/raw_ostream.h"
101#include "llvm/Target/TargetMachine.h"
102#include "llvm/Target/TargetOptions.h"
103#include "llvm/TargetParser/Triple.h"
104#include "llvm/Transforms/Utils/Local.h"
105#include <cstddef>
106#include <limits>
107#include <optional>
108#include <tuple>
109
110using namespace llvm;
111using namespace PatternMatch;
112using namespace SwitchCG;
113
114#define DEBUG_TYPE "isel"
115
116/// LimitFloatPrecision - Generate low-precision inline sequences for
117/// some float libcalls (6, 8 or 12 bits).
118static unsigned LimitFloatPrecision;
119
120static cl::opt<bool>
121 InsertAssertAlign("insert-assert-align", cl::init(Val: true),
122 cl::desc("Insert the experimental `assertalign` node."),
123 cl::ReallyHidden);
124
125static cl::opt<unsigned, true>
126 LimitFPPrecision("limit-float-precision",
127 cl::desc("Generate low-precision inline sequences "
128 "for some float libcalls"),
129 cl::location(L&: LimitFloatPrecision), cl::Hidden,
130 cl::init(Val: 0));
131
132static cl::opt<unsigned> SwitchPeelThreshold(
133 "switch-peel-threshold", cl::Hidden, cl::init(Val: 66),
134 cl::desc("Set the case probability threshold for peeling the case from a "
135 "switch statement. A value greater than 100 will void this "
136 "optimization"));
137
138// Limit the width of DAG chains. This is important in general to prevent
139// DAG-based analysis from blowing up. For example, alias analysis and
140// load clustering may not complete in reasonable time. It is difficult to
141// recognize and avoid this situation within each individual analysis, and
142// future analyses are likely to have the same behavior. Limiting DAG width is
143// the safe approach and will be especially important with global DAGs.
144//
145// MaxParallelChains default is arbitrarily high to avoid affecting
146// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
147// sequence over this should have been converted to llvm.memcpy by the
148// frontend. It is easy to induce this behavior with .ll code such as:
149// %buffer = alloca [4096 x i8]
150// %data = load [4096 x i8]* %argPtr
151// store [4096 x i8] %data, [4096 x i8]* %buffer
152static const unsigned MaxParallelChains = 64;
153
154static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
155 const SDValue *Parts, unsigned NumParts,
156 MVT PartVT, EVT ValueVT, const Value *V,
157 SDValue InChain,
158 std::optional<CallingConv::ID> CC);
159
160/// getCopyFromParts - Create a value that contains the specified legal parts
161/// combined into the value they represent. If the parts combine to a type
162/// larger than ValueVT then AssertOp can be used to specify whether the extra
163/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
164/// (ISD::AssertSext).
165static SDValue
166getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
167 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
168 SDValue InChain,
169 std::optional<CallingConv::ID> CC = std::nullopt,
170 std::optional<ISD::NodeType> AssertOp = std::nullopt) {
171 // Let the target assemble the parts if it wants to
172 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
173 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
174 PartVT, ValueVT, CC))
175 return Val;
176
177 if (ValueVT.isVector())
178 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
179 InChain, CC);
180
181 assert(NumParts > 0 && "No parts to assemble!");
182 SDValue Val = Parts[0];
183
184 if (NumParts > 1) {
185 // Assemble the value from multiple parts.
186 if (ValueVT.isInteger()) {
187 unsigned PartBits = PartVT.getSizeInBits();
188 unsigned ValueBits = ValueVT.getSizeInBits();
189
190 // Assemble the power of 2 part.
191 unsigned RoundParts = llvm::bit_floor(Value: NumParts);
192 unsigned RoundBits = PartBits * RoundParts;
193 EVT RoundVT = RoundBits == ValueBits ?
194 ValueVT : EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: RoundBits);
195 SDValue Lo, Hi;
196
197 EVT HalfVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: RoundBits/2);
198
199 if (RoundParts > 2) {
200 Lo = getCopyFromParts(DAG, DL, Parts, NumParts: RoundParts / 2, PartVT, ValueVT: HalfVT, V,
201 InChain);
202 Hi = getCopyFromParts(DAG, DL, Parts: Parts + RoundParts / 2, NumParts: RoundParts / 2,
203 PartVT, ValueVT: HalfVT, V, InChain);
204 } else {
205 Lo = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: HalfVT, Operand: Parts[0]);
206 Hi = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: HalfVT, Operand: Parts[1]);
207 }
208
209 if (DAG.getDataLayout().isBigEndian())
210 std::swap(a&: Lo, b&: Hi);
211
212 Val = DAG.getNode(Opcode: ISD::BUILD_PAIR, DL, VT: RoundVT, N1: Lo, N2: Hi);
213
214 if (RoundParts < NumParts) {
215 // Assemble the trailing non-power-of-2 part.
216 unsigned OddParts = NumParts - RoundParts;
217 EVT OddVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: OddParts * PartBits);
218 Hi = getCopyFromParts(DAG, DL, Parts: Parts + RoundParts, NumParts: OddParts, PartVT,
219 ValueVT: OddVT, V, InChain, CC);
220
221 // Combine the round and odd parts.
222 Lo = Val;
223 if (DAG.getDataLayout().isBigEndian())
224 std::swap(a&: Lo, b&: Hi);
225 EVT TotalVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: NumParts * PartBits);
226 Hi = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: TotalVT, Operand: Hi);
227 Hi = DAG.getNode(
228 Opcode: ISD::SHL, DL, VT: TotalVT, N1: Hi,
229 N2: DAG.getShiftAmountConstant(Val: Lo.getValueSizeInBits(), VT: TotalVT, DL));
230 Lo = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL, VT: TotalVT, Operand: Lo);
231 Val = DAG.getNode(Opcode: ISD::OR, DL, VT: TotalVT, N1: Lo, N2: Hi);
232 }
233 } else if (PartVT.isFloatingPoint()) {
234 // FP split into multiple FP parts (for ppcf128)
235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
236 "Unexpected split");
237 SDValue Lo, Hi;
238 Lo = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: EVT(MVT::f64), Operand: Parts[0]);
239 Hi = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: EVT(MVT::f64), Operand: Parts[1]);
240 if (TLI.hasBigEndianPartOrdering(VT: ValueVT, DL: DAG.getDataLayout()))
241 std::swap(a&: Lo, b&: Hi);
242 Val = DAG.getNode(Opcode: ISD::BUILD_PAIR, DL, VT: ValueVT, N1: Lo, N2: Hi);
243 } else {
244 // FP split into integer parts (soft fp)
245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
246 !PartVT.isVector() && "Unexpected split");
247 EVT IntVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueVT.getSizeInBits());
248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, ValueVT: IntVT, V,
249 InChain, CC);
250 }
251 }
252
253 // There is now one part, held in Val. Correct it to match ValueVT.
254 // PartEVT is the type of the register class that holds the value.
255 // ValueVT is the type of the inline asm operation.
256 EVT PartEVT = Val.getValueType();
257
258 if (PartEVT == ValueVT)
259 return Val;
260
261 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
262 ValueVT.bitsLT(VT: PartEVT)) {
263 // For an FP value in an integer part, we need to truncate to the right
264 // width first.
265 PartEVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueVT.getSizeInBits());
266 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: PartEVT, Operand: Val);
267 }
268
269 // Handle types that have the same size.
270 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
271 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
272
273 // Handle types with different sizes.
274 if (PartEVT.isInteger() && ValueVT.isInteger()) {
275 if (ValueVT.bitsLT(VT: PartEVT)) {
276 // For a truncate, see if we have any information to
277 // indicate whether the truncated bits will always be
278 // zero or sign-extension.
279 if (AssertOp)
280 Val = DAG.getNode(Opcode: *AssertOp, DL, VT: PartEVT, N1: Val,
281 N2: DAG.getValueType(ValueVT));
282 return DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: ValueVT, Operand: Val);
283 }
284 return DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: ValueVT, Operand: Val);
285 }
286
287 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
288 // FP_ROUND's are always exact here.
289 if (ValueVT.bitsLT(VT: Val.getValueType())) {
290
291 SDValue NoChange =
292 DAG.getTargetConstant(Val: 1, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
293
294 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
295 Kind: llvm::Attribute::StrictFP)) {
296 return DAG.getNode(Opcode: ISD::STRICT_FP_ROUND, DL,
297 VTList: DAG.getVTList(VT1: ValueVT, VT2: MVT::Other), N1: InChain, N2: Val,
298 N3: NoChange);
299 }
300
301 return DAG.getNode(Opcode: ISD::FP_ROUND, DL, VT: ValueVT, N1: Val, N2: NoChange);
302 }
303
304 return DAG.getNode(Opcode: ISD::FP_EXTEND, DL, VT: ValueVT, Operand: Val);
305 }
306
307 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
308 // then truncating.
309 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
310 ValueVT.bitsLT(VT: PartEVT)) {
311 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::i64, Operand: Val);
312 return DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: ValueVT, Operand: Val);
313 }
314
315 report_fatal_error(reason: "Unknown mismatch in getCopyFromParts!");
316}
317
318static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
319 const Twine &ErrMsg) {
320 const Instruction *I = dyn_cast_or_null<Instruction>(Val: V);
321 if (!I)
322 return Ctx.emitError(ErrorStr: ErrMsg);
323
324 if (const CallInst *CI = dyn_cast<CallInst>(Val: I))
325 if (CI->isInlineAsm()) {
326 return Ctx.diagnose(DI: DiagnosticInfoInlineAsm(
327 *CI, ErrMsg + ", possible invalid constraint for vector type"));
328 }
329
330 return Ctx.emitError(I, ErrorStr: ErrMsg);
331}
332
333/// getCopyFromPartsVector - Create a value that contains the specified legal
334/// parts combined into the value they represent. If the parts combine to a
335/// type larger than ValueVT then AssertOp can be used to specify whether the
336/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
337/// ValueVT (ISD::AssertSext).
338static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
339 const SDValue *Parts, unsigned NumParts,
340 MVT PartVT, EVT ValueVT, const Value *V,
341 SDValue InChain,
342 std::optional<CallingConv::ID> CallConv) {
343 assert(ValueVT.isVector() && "Not a vector value");
344 assert(NumParts > 0 && "No parts to assemble!");
345 const bool IsABIRegCopy = CallConv.has_value();
346
347 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
348 SDValue Val = Parts[0];
349
350 // Handle a multi-element vector.
351 if (NumParts > 1) {
352 EVT IntermediateVT;
353 MVT RegisterVT;
354 unsigned NumIntermediates;
355 unsigned NumRegs;
356
357 if (IsABIRegCopy) {
358 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
359 Context&: *DAG.getContext(), CC: *CallConv, VT: ValueVT, IntermediateVT,
360 NumIntermediates, RegisterVT);
361 } else {
362 NumRegs =
363 TLI.getVectorTypeBreakdown(Context&: *DAG.getContext(), VT: ValueVT, IntermediateVT,
364 NumIntermediates, RegisterVT);
365 }
366
367 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
368 NumParts = NumRegs; // Silence a compiler warning.
369 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
370 assert(RegisterVT.getSizeInBits() ==
371 Parts[0].getSimpleValueType().getSizeInBits() &&
372 "Part type sizes don't match!");
373
374 // Assemble the parts into intermediate operands.
375 SmallVector<SDValue, 8> Ops(NumIntermediates);
376 if (NumIntermediates == NumParts) {
377 // If the register was not expanded, truncate or copy the value,
378 // as appropriate.
379 for (unsigned i = 0; i != NumParts; ++i)
380 Ops[i] = getCopyFromParts(DAG, DL, Parts: &Parts[i], NumParts: 1, PartVT, ValueVT: IntermediateVT,
381 V, InChain, CC: CallConv);
382 } else if (NumParts > 0) {
383 // If the intermediate type was expanded, build the intermediate
384 // operands from the parts.
385 assert(NumParts % NumIntermediates == 0 &&
386 "Must expand into a divisible number of parts!");
387 unsigned Factor = NumParts / NumIntermediates;
388 for (unsigned i = 0; i != NumIntermediates; ++i)
389 Ops[i] = getCopyFromParts(DAG, DL, Parts: &Parts[i * Factor], NumParts: Factor, PartVT,
390 ValueVT: IntermediateVT, V, InChain, CC: CallConv);
391 }
392
393 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
394 // intermediate operands.
395 EVT BuiltVectorTy =
396 IntermediateVT.isVector()
397 ? EVT::getVectorVT(
398 Context&: *DAG.getContext(), VT: IntermediateVT.getScalarType(),
399 EC: IntermediateVT.getVectorElementCount() * NumParts)
400 : EVT::getVectorVT(Context&: *DAG.getContext(),
401 VT: IntermediateVT.getScalarType(),
402 NumElements: NumIntermediates);
403 Val = DAG.getNode(Opcode: IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
404 : ISD::BUILD_VECTOR,
405 DL, VT: BuiltVectorTy, Ops);
406 }
407
408 // There is now one part, held in Val. Correct it to match ValueVT.
409 EVT PartEVT = Val.getValueType();
410
411 if (PartEVT == ValueVT)
412 return Val;
413
414 if (PartEVT.isVector()) {
415 // Vector/Vector bitcast.
416 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
417 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
418
419 // If the parts vector has more elements than the value vector, then we
420 // have a vector widening case (e.g. <2 x float> -> <4 x float>).
421 // Extract the elements we want.
422 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
423 assert((PartEVT.getVectorElementCount().getKnownMinValue() >
424 ValueVT.getVectorElementCount().getKnownMinValue()) &&
425 (PartEVT.getVectorElementCount().isScalable() ==
426 ValueVT.getVectorElementCount().isScalable()) &&
427 "Cannot narrow, it would be a lossy transformation");
428 PartEVT =
429 EVT::getVectorVT(Context&: *DAG.getContext(), VT: PartEVT.getVectorElementType(),
430 EC: ValueVT.getVectorElementCount());
431 Val = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: PartEVT, N1: Val,
432 N2: DAG.getVectorIdxConstant(Val: 0, DL));
433 if (PartEVT == ValueVT)
434 return Val;
435 if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
436 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
437
438 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
439 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
440 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
441 }
442
443 // Promoted vector extract
444 return DAG.getAnyExtOrTrunc(Op: Val, DL, VT: ValueVT);
445 }
446
447 // Trivial bitcast if the types are the same size and the destination
448 // vector type is legal.
449 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
450 TLI.isTypeLegal(VT: ValueVT))
451 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
452
453 if (ValueVT.getVectorNumElements() != 1) {
454 // Certain ABIs require that vectors are passed as integers. For vectors
455 // are the same size, this is an obvious bitcast.
456 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
457 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
458 } else if (ValueVT.bitsLT(VT: PartEVT)) {
459 const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
460 EVT IntermediateType = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueSize);
461 // Drop the extra bits.
462 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: IntermediateType, Operand: Val);
463 return DAG.getBitcast(VT: ValueVT, V: Val);
464 }
465
466 diagnosePossiblyInvalidConstraint(
467 Ctx&: *DAG.getContext(), V, ErrMsg: "non-trivial scalar-to-vector conversion");
468 return DAG.getUNDEF(VT: ValueVT);
469 }
470
471 // Handle cases such as i8 -> <1 x i1>
472 EVT ValueSVT = ValueVT.getVectorElementType();
473 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
474 unsigned ValueSize = ValueSVT.getSizeInBits();
475 if (ValueSize == PartEVT.getSizeInBits()) {
476 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueSVT, Operand: Val);
477 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
478 // It's possible a scalar floating point type gets softened to integer and
479 // then promoted to a larger integer. If PartEVT is the larger integer
480 // we need to truncate it and then bitcast to the FP type.
481 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
482 EVT IntermediateType = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueSize);
483 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: IntermediateType, Operand: Val);
484 Val = DAG.getBitcast(VT: ValueSVT, V: Val);
485 } else {
486 Val = ValueVT.isFloatingPoint()
487 ? DAG.getFPExtendOrRound(Op: Val, DL, VT: ValueSVT)
488 : DAG.getAnyExtOrTrunc(Op: Val, DL, VT: ValueSVT);
489 }
490 }
491
492 return DAG.getBuildVector(VT: ValueVT, DL, Ops: Val);
493}
494
495static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
496 SDValue Val, SDValue *Parts, unsigned NumParts,
497 MVT PartVT, const Value *V,
498 std::optional<CallingConv::ID> CallConv);
499
500/// getCopyToParts - Create a series of nodes that contain the specified value
501/// split into legal parts. If the parts contain more bits than Val, then, for
502/// integers, ExtendKind can be used to specify how to generate the extra bits.
503static void
504getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
505 unsigned NumParts, MVT PartVT, const Value *V,
506 std::optional<CallingConv::ID> CallConv = std::nullopt,
507 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
508 // Let the target split the parts if it wants to
509 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
510 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
511 CC: CallConv))
512 return;
513 EVT ValueVT = Val.getValueType();
514
515 // Handle the vector case separately.
516 if (ValueVT.isVector())
517 return getCopyToPartsVector(DAG, dl: DL, Val, Parts, NumParts, PartVT, V,
518 CallConv);
519
520 unsigned OrigNumParts = NumParts;
521 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
522 "Copying to an illegal type!");
523
524 if (NumParts == 0)
525 return;
526
527 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
528 EVT PartEVT = PartVT;
529 if (PartEVT == ValueVT) {
530 assert(NumParts == 1 && "No-op copy with multiple parts!");
531 Parts[0] = Val;
532 return;
533 }
534
535 unsigned PartBits = PartVT.getSizeInBits();
536 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
537 // If the parts cover more bits than the value has, promote the value.
538 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
539 assert(NumParts == 1 && "Do not know what to promote to!");
540 Val = DAG.getNode(Opcode: ISD::FP_EXTEND, DL, VT: PartVT, Operand: Val);
541 } else {
542 if (ValueVT.isFloatingPoint()) {
543 // FP values need to be bitcast, then extended if they are being put
544 // into a larger container.
545 ValueVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueVT.getSizeInBits());
546 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
547 }
548 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
549 ValueVT.isInteger() &&
550 "Unknown mismatch!");
551 ValueVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: NumParts * PartBits);
552 Val = DAG.getNode(Opcode: ExtendKind, DL, VT: ValueVT, Operand: Val);
553 if (PartVT == MVT::x86mmx)
554 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
555 }
556 } else if (PartBits == ValueVT.getSizeInBits()) {
557 // Different types of the same size.
558 assert(NumParts == 1 && PartEVT != ValueVT);
559 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
560 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
561 // If the parts cover less bits than value has, truncate the value.
562 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
563 ValueVT.isInteger() &&
564 "Unknown mismatch!");
565 ValueVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: NumParts * PartBits);
566 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: ValueVT, Operand: Val);
567 if (PartVT == MVT::x86mmx)
568 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
569 }
570
571 // The value may have changed - recompute ValueVT.
572 ValueVT = Val.getValueType();
573 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
574 "Failed to tile the value with PartVT!");
575
576 if (NumParts == 1) {
577 if (PartEVT != ValueVT) {
578 diagnosePossiblyInvalidConstraint(Ctx&: *DAG.getContext(), V,
579 ErrMsg: "scalar-to-vector conversion failed");
580 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
581 }
582
583 Parts[0] = Val;
584 return;
585 }
586
587 // Expand the value into multiple parts.
588 if (NumParts & (NumParts - 1)) {
589 // The number of parts is not a power of 2. Split off and copy the tail.
590 assert(PartVT.isInteger() && ValueVT.isInteger() &&
591 "Do not know what to expand to!");
592 unsigned RoundParts = llvm::bit_floor(Value: NumParts);
593 unsigned RoundBits = RoundParts * PartBits;
594 unsigned OddParts = NumParts - RoundParts;
595 SDValue OddVal = DAG.getNode(Opcode: ISD::SRL, DL, VT: ValueVT, N1: Val,
596 N2: DAG.getShiftAmountConstant(Val: RoundBits, VT: ValueVT, DL));
597
598 getCopyToParts(DAG, DL, Val: OddVal, Parts: Parts + RoundParts, NumParts: OddParts, PartVT, V,
599 CallConv);
600
601 if (DAG.getDataLayout().isBigEndian())
602 // The odd parts were reversed by getCopyToParts - unreverse them.
603 std::reverse(first: Parts + RoundParts, last: Parts + NumParts);
604
605 NumParts = RoundParts;
606 ValueVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: NumParts * PartBits);
607 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: ValueVT, Operand: Val);
608 }
609
610 // The number of parts is a power of 2. Repeatedly bisect the value using
611 // EXTRACT_ELEMENT.
612 Parts[0] = DAG.getNode(Opcode: ISD::BITCAST, DL,
613 VT: EVT::getIntegerVT(Context&: *DAG.getContext(),
614 BitWidth: ValueVT.getSizeInBits()),
615 Operand: Val);
616
617 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
618 for (unsigned i = 0; i < NumParts; i += StepSize) {
619 unsigned ThisBits = StepSize * PartBits / 2;
620 EVT ThisVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ThisBits);
621 SDValue &Part0 = Parts[i];
622 SDValue &Part1 = Parts[i+StepSize/2];
623
624 Part1 = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL,
625 VT: ThisVT, N1: Part0, N2: DAG.getIntPtrConstant(Val: 1, DL));
626 Part0 = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL,
627 VT: ThisVT, N1: Part0, N2: DAG.getIntPtrConstant(Val: 0, DL));
628
629 if (ThisBits == PartBits && ThisVT != PartVT) {
630 Part0 = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Part0);
631 Part1 = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Part1);
632 }
633 }
634 }
635
636 if (DAG.getDataLayout().isBigEndian())
637 std::reverse(first: Parts, last: Parts + OrigNumParts);
638}
639
640static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
641 const SDLoc &DL, EVT PartVT) {
642 if (!PartVT.isVector())
643 return SDValue();
644
645 EVT ValueVT = Val.getValueType();
646 EVT PartEVT = PartVT.getVectorElementType();
647 EVT ValueEVT = ValueVT.getVectorElementType();
648 ElementCount PartNumElts = PartVT.getVectorElementCount();
649 ElementCount ValueNumElts = ValueVT.getVectorElementCount();
650
651 // We only support widening vectors with equivalent element types and
652 // fixed/scalable properties. If a target needs to widen a fixed-length type
653 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
654 if (ElementCount::isKnownLE(LHS: PartNumElts, RHS: ValueNumElts) ||
655 PartNumElts.isScalable() != ValueNumElts.isScalable())
656 return SDValue();
657
658 // Have a try for bf16 because some targets share its ABI with fp16.
659 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
660 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
661 "Cannot widen to illegal type");
662 Val = DAG.getNode(
663 Opcode: ISD::BITCAST, DL,
664 VT: ValueVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: MVT::f16), Operand: Val);
665 } else if (PartEVT != ValueEVT) {
666 return SDValue();
667 }
668
669 // Widening a scalable vector to another scalable vector is done by inserting
670 // the vector into a larger undef one.
671 if (PartNumElts.isScalable())
672 return DAG.getNode(Opcode: ISD::INSERT_SUBVECTOR, DL, VT: PartVT, N1: DAG.getUNDEF(VT: PartVT),
673 N2: Val, N3: DAG.getVectorIdxConstant(Val: 0, DL));
674
675 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
676 // undef elements.
677 SmallVector<SDValue, 16> Ops;
678 DAG.ExtractVectorElements(Op: Val, Args&: Ops);
679 SDValue EltUndef = DAG.getUNDEF(VT: PartEVT);
680 Ops.append(NumInputs: (PartNumElts - ValueNumElts).getFixedValue(), Elt: EltUndef);
681
682 // FIXME: Use CONCAT for 2x -> 4x.
683 return DAG.getBuildVector(VT: PartVT, DL, Ops);
684}
685
686/// getCopyToPartsVector - Create a series of nodes that contain the specified
687/// value split into legal parts.
688static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
689 SDValue Val, SDValue *Parts, unsigned NumParts,
690 MVT PartVT, const Value *V,
691 std::optional<CallingConv::ID> CallConv) {
692 EVT ValueVT = Val.getValueType();
693 assert(ValueVT.isVector() && "Not a vector");
694 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
695 const bool IsABIRegCopy = CallConv.has_value();
696
697 if (NumParts == 1) {
698 EVT PartEVT = PartVT;
699 if (PartEVT == ValueVT) {
700 // Nothing to do.
701 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
702 // Bitconvert vector->vector case.
703 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
704 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
705 Val = Widened;
706 } else if (PartVT.isVector() &&
707 PartEVT.getVectorElementType().bitsGE(
708 VT: ValueVT.getVectorElementType()) &&
709 PartEVT.getVectorElementCount() ==
710 ValueVT.getVectorElementCount()) {
711
712 // Promoted vector extract
713 Val = DAG.getAnyExtOrTrunc(Op: Val, DL, VT: PartVT);
714 } else if (PartEVT.isVector() &&
715 PartEVT.getVectorElementType() !=
716 ValueVT.getVectorElementType() &&
717 TLI.getTypeAction(Context&: *DAG.getContext(), VT: ValueVT) ==
718 TargetLowering::TypeWidenVector) {
719 // Combination of widening and promotion.
720 EVT WidenVT =
721 EVT::getVectorVT(Context&: *DAG.getContext(), VT: ValueVT.getVectorElementType(),
722 EC: PartVT.getVectorElementCount());
723 SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT: WidenVT);
724 Val = DAG.getAnyExtOrTrunc(Op: Widened, DL, VT: PartVT);
725 } else {
726 // Don't extract an integer from a float vector. This can happen if the
727 // FP type gets softened to integer and then promoted. The promotion
728 // prevents it from being picked up by the earlier bitcast case.
729 if (ValueVT.getVectorElementCount().isScalar() &&
730 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
731 // If we reach this condition and PartVT is FP, this means that
732 // ValueVT is also FP and both have a different size, otherwise we
733 // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
734 // would be invalid since that would mean the smaller FP type has to
735 // be extended to the larger one.
736 if (PartVT.isFloatingPoint()) {
737 Val = DAG.getBitcast(VT: ValueVT.getScalarType(), V: Val);
738 Val = DAG.getNode(Opcode: ISD::FP_EXTEND, DL, VT: PartVT, Operand: Val);
739 } else
740 Val = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: PartVT, N1: Val,
741 N2: DAG.getVectorIdxConstant(Val: 0, DL));
742 } else {
743 uint64_t ValueSize = ValueVT.getFixedSizeInBits();
744 assert(PartVT.getFixedSizeInBits() > ValueSize &&
745 "lossy conversion of vector to scalar type");
746 EVT IntermediateType = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueSize);
747 Val = DAG.getBitcast(VT: IntermediateType, V: Val);
748 Val = DAG.getAnyExtOrTrunc(Op: Val, DL, VT: PartVT);
749 }
750 }
751
752 assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
753 Parts[0] = Val;
754 return;
755 }
756
757 // Handle a multi-element vector.
758 EVT IntermediateVT;
759 MVT RegisterVT;
760 unsigned NumIntermediates;
761 unsigned NumRegs;
762 if (IsABIRegCopy) {
763 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
764 Context&: *DAG.getContext(), CC: *CallConv, VT: ValueVT, IntermediateVT, NumIntermediates,
765 RegisterVT);
766 } else {
767 NumRegs =
768 TLI.getVectorTypeBreakdown(Context&: *DAG.getContext(), VT: ValueVT, IntermediateVT,
769 NumIntermediates, RegisterVT);
770 }
771
772 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
773 NumParts = NumRegs; // Silence a compiler warning.
774 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
775
776 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
777 "Mixing scalable and fixed vectors when copying in parts");
778
779 std::optional<ElementCount> DestEltCnt;
780
781 if (IntermediateVT.isVector())
782 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
783 else
784 DestEltCnt = ElementCount::getFixed(MinVal: NumIntermediates);
785
786 EVT BuiltVectorTy = EVT::getVectorVT(
787 Context&: *DAG.getContext(), VT: IntermediateVT.getScalarType(), EC: *DestEltCnt);
788
789 if (ValueVT == BuiltVectorTy) {
790 // Nothing to do.
791 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
792 // Bitconvert vector->vector case.
793 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: BuiltVectorTy, Operand: Val);
794 } else {
795 if (BuiltVectorTy.getVectorElementType().bitsGT(
796 VT: ValueVT.getVectorElementType())) {
797 // Integer promotion.
798 ValueVT = EVT::getVectorVT(Context&: *DAG.getContext(),
799 VT: BuiltVectorTy.getVectorElementType(),
800 EC: ValueVT.getVectorElementCount());
801 Val = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: ValueVT, Operand: Val);
802 }
803
804 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT: BuiltVectorTy)) {
805 Val = Widened;
806 }
807 }
808
809 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
810
811 // Split the vector into intermediate operands.
812 SmallVector<SDValue, 8> Ops(NumIntermediates);
813 for (unsigned i = 0; i != NumIntermediates; ++i) {
814 if (IntermediateVT.isVector()) {
815 // This does something sensible for scalable vectors - see the
816 // definition of EXTRACT_SUBVECTOR for further details.
817 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
818 Ops[i] =
819 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: IntermediateVT, N1: Val,
820 N2: DAG.getVectorIdxConstant(Val: i * IntermediateNumElts, DL));
821 } else {
822 Ops[i] = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: IntermediateVT, N1: Val,
823 N2: DAG.getVectorIdxConstant(Val: i, DL));
824 }
825 }
826
827 // Split the intermediate operands into legal parts.
828 if (NumParts == NumIntermediates) {
829 // If the register was not expanded, promote or copy the value,
830 // as appropriate.
831 for (unsigned i = 0; i != NumParts; ++i)
832 getCopyToParts(DAG, DL, Val: Ops[i], Parts: &Parts[i], NumParts: 1, PartVT, V, CallConv);
833 } else if (NumParts > 0) {
834 // If the intermediate type was expanded, split each the value into
835 // legal parts.
836 assert(NumIntermediates != 0 && "division by zero");
837 assert(NumParts % NumIntermediates == 0 &&
838 "Must expand into a divisible number of parts!");
839 unsigned Factor = NumParts / NumIntermediates;
840 for (unsigned i = 0; i != NumIntermediates; ++i)
841 getCopyToParts(DAG, DL, Val: Ops[i], Parts: &Parts[i * Factor], NumParts: Factor, PartVT, V,
842 CallConv);
843 }
844}
845
846static void failForInvalidBundles(const CallBase &I, StringRef Name,
847 ArrayRef<uint32_t> AllowedBundles) {
848 if (I.hasOperandBundlesOtherThan(IDs: AllowedBundles)) {
849 ListSeparator LS;
850 std::string Error;
851 raw_string_ostream OS(Error);
852 for (unsigned i = 0, e = I.getNumOperandBundles(); i != e; ++i) {
853 OperandBundleUse U = I.getOperandBundleAt(Index: i);
854 if (!is_contained(Range&: AllowedBundles, Element: U.getTagID()))
855 OS << LS << U.getTagName();
856 }
857 reportFatalUsageError(
858 reason: Twine("cannot lower ", Name)
859 .concat(Suffix: Twine(" with arbitrary operand bundles: ", Error)));
860 }
861}
862
863RegsForValue::RegsForValue(const SmallVector<Register, 4> &regs, MVT regvt,
864 EVT valuevt, std::optional<CallingConv::ID> CC)
865 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
866 RegCount(1, regs.size()), CallConv(CC) {}
867
868RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
869 const DataLayout &DL, Register Reg, Type *Ty,
870 std::optional<CallingConv::ID> CC) {
871 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
872
873 CallConv = CC;
874
875 for (EVT ValueVT : ValueVTs) {
876 unsigned NumRegs =
877 isABIMangled()
878 ? TLI.getNumRegistersForCallingConv(Context, CC: *CC, VT: ValueVT)
879 : TLI.getNumRegisters(Context, VT: ValueVT);
880 MVT RegisterVT =
881 isABIMangled()
882 ? TLI.getRegisterTypeForCallingConv(Context, CC: *CC, VT: ValueVT)
883 : TLI.getRegisterType(Context, VT: ValueVT);
884 for (unsigned i = 0; i != NumRegs; ++i)
885 Regs.push_back(Elt: Reg + i);
886 RegVTs.push_back(Elt: RegisterVT);
887 RegCount.push_back(Elt: NumRegs);
888 Reg = Reg.id() + NumRegs;
889 }
890}
891
892SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
893 FunctionLoweringInfo &FuncInfo,
894 const SDLoc &dl, SDValue &Chain,
895 SDValue *Glue, const Value *V) const {
896 // A Value with type {} or [0 x %t] needs no registers.
897 if (ValueVTs.empty())
898 return SDValue();
899
900 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
901
902 // Assemble the legal parts into the final values.
903 SmallVector<SDValue, 4> Values(ValueVTs.size());
904 SmallVector<SDValue, 8> Parts;
905 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
906 // Copy the legal parts from the registers.
907 EVT ValueVT = ValueVTs[Value];
908 unsigned NumRegs = RegCount[Value];
909 MVT RegisterVT = isABIMangled()
910 ? TLI.getRegisterTypeForCallingConv(
911 Context&: *DAG.getContext(), CC: *CallConv, VT: RegVTs[Value])
912 : RegVTs[Value];
913
914 Parts.resize(N: NumRegs);
915 for (unsigned i = 0; i != NumRegs; ++i) {
916 SDValue P;
917 if (!Glue) {
918 P = DAG.getCopyFromReg(Chain, dl, Reg: Regs[Part+i], VT: RegisterVT);
919 } else {
920 P = DAG.getCopyFromReg(Chain, dl, Reg: Regs[Part+i], VT: RegisterVT, Glue: *Glue);
921 *Glue = P.getValue(R: 2);
922 }
923
924 Chain = P.getValue(R: 1);
925 Parts[i] = P;
926
927 // If the source register was virtual and if we know something about it,
928 // add an assert node.
929 if (!Regs[Part + i].isVirtual() || !RegisterVT.isInteger())
930 continue;
931
932 const FunctionLoweringInfo::LiveOutInfo *LOI =
933 FuncInfo.GetLiveOutRegInfo(Reg: Regs[Part+i]);
934 if (!LOI)
935 continue;
936
937 unsigned RegSize = RegisterVT.getScalarSizeInBits();
938 unsigned NumSignBits = LOI->NumSignBits;
939 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
940
941 if (NumZeroBits == RegSize) {
942 // The current value is a zero.
943 // Explicitly express that as it would be easier for
944 // optimizations to kick in.
945 Parts[i] = DAG.getConstant(Val: 0, DL: dl, VT: RegisterVT);
946 continue;
947 }
948
949 // FIXME: We capture more information than the dag can represent. For
950 // now, just use the tightest assertzext/assertsext possible.
951 bool isSExt;
952 EVT FromVT(MVT::Other);
953 if (NumZeroBits) {
954 FromVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: RegSize - NumZeroBits);
955 isSExt = false;
956 } else if (NumSignBits > 1) {
957 FromVT =
958 EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: RegSize - NumSignBits + 1);
959 isSExt = true;
960 } else {
961 continue;
962 }
963 // Add an assertion node.
964 assert(FromVT != MVT::Other);
965 Parts[i] = DAG.getNode(Opcode: isSExt ? ISD::AssertSext : ISD::AssertZext, DL: dl,
966 VT: RegisterVT, N1: P, N2: DAG.getValueType(FromVT));
967 }
968
969 Values[Value] = getCopyFromParts(DAG, DL: dl, Parts: Parts.begin(), NumParts: NumRegs,
970 PartVT: RegisterVT, ValueVT, V, InChain: Chain, CC: CallConv);
971 Part += NumRegs;
972 Parts.clear();
973 }
974
975 return DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl, VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values);
976}
977
978void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
979 const SDLoc &dl, SDValue &Chain, SDValue *Glue,
980 const Value *V,
981 ISD::NodeType PreferredExtendType) const {
982 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
983 ISD::NodeType ExtendKind = PreferredExtendType;
984
985 // Get the list of the values's legal parts.
986 unsigned NumRegs = Regs.size();
987 SmallVector<SDValue, 8> Parts(NumRegs);
988 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
989 unsigned NumParts = RegCount[Value];
990
991 MVT RegisterVT = isABIMangled()
992 ? TLI.getRegisterTypeForCallingConv(
993 Context&: *DAG.getContext(), CC: *CallConv, VT: RegVTs[Value])
994 : RegVTs[Value];
995
996 if (ExtendKind == ISD::ANY_EXTEND)
997 if (TLI.isZExtFree(Val: peekThroughFreeze(V: Val), VT2: RegisterVT))
998 ExtendKind = ISD::ZERO_EXTEND;
999
1000 getCopyToParts(DAG, DL: dl, Val: Val.getValue(R: Val.getResNo() + Value), Parts: &Parts[Part],
1001 NumParts, PartVT: RegisterVT, V, CallConv, ExtendKind);
1002 Part += NumParts;
1003 }
1004
1005 // Copy the parts into the registers.
1006 SmallVector<SDValue, 8> Chains(NumRegs);
1007 for (unsigned i = 0; i != NumRegs; ++i) {
1008 SDValue Part;
1009 if (!Glue) {
1010 Part = DAG.getCopyToReg(Chain, dl, Reg: Regs[i], N: Parts[i]);
1011 } else {
1012 Part = DAG.getCopyToReg(Chain, dl, Reg: Regs[i], N: Parts[i], Glue: *Glue);
1013 *Glue = Part.getValue(R: 1);
1014 }
1015
1016 Chains[i] = Part.getValue(R: 0);
1017 }
1018
1019 if (NumRegs == 1 || Glue)
1020 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1021 // flagged to it. That is the CopyToReg nodes and the user are considered
1022 // a single scheduling unit. If we create a TokenFactor and return it as
1023 // chain, then the TokenFactor is both a predecessor (operand) of the
1024 // user as well as a successor (the TF operands are flagged to the user).
1025 // c1, f1 = CopyToReg
1026 // c2, f2 = CopyToReg
1027 // c3 = TokenFactor c1, c2
1028 // ...
1029 // = op c3, ..., f2
1030 Chain = Chains[NumRegs-1];
1031 else
1032 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: Chains);
1033}
1034
1035void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1036 unsigned MatchingIdx, const SDLoc &dl,
1037 SelectionDAG &DAG,
1038 std::vector<SDValue> &Ops) const {
1039 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1040
1041 InlineAsm::Flag Flag(Code, Regs.size());
1042 if (HasMatching)
1043 Flag.setMatchingOp(MatchingIdx);
1044 else if (!Regs.empty() && Regs.front().isVirtual()) {
1045 // Put the register class of the virtual registers in the flag word. That
1046 // way, later passes can recompute register class constraints for inline
1047 // assembly as well as normal instructions.
1048 // Don't do this for tied operands that can use the regclass information
1049 // from the def.
1050 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1051 const TargetRegisterClass *RC = MRI.getRegClass(Reg: Regs.front());
1052 Flag.setRegClass(RC->getID());
1053 }
1054
1055 SDValue Res = DAG.getTargetConstant(Val: Flag, DL: dl, VT: MVT::i32);
1056 Ops.push_back(x: Res);
1057
1058 if (Code == InlineAsm::Kind::Clobber) {
1059 // Clobbers should always have a 1:1 mapping with registers, and may
1060 // reference registers that have illegal (e.g. vector) types. Hence, we
1061 // shouldn't try to apply any sort of splitting logic to them.
1062 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1063 "No 1:1 mapping from clobbers to regs?");
1064 Register SP = TLI.getStackPointerRegisterToSaveRestore();
1065 (void)SP;
1066 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1067 Ops.push_back(x: DAG.getRegister(Reg: Regs[I], VT: RegVTs[I]));
1068 assert(
1069 (Regs[I] != SP ||
1070 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1071 "If we clobbered the stack pointer, MFI should know about it.");
1072 }
1073 return;
1074 }
1075
1076 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1077 MVT RegisterVT = RegVTs[Value];
1078 unsigned NumRegs = TLI.getNumRegisters(Context&: *DAG.getContext(), VT: ValueVTs[Value],
1079 RegisterVT);
1080 for (unsigned i = 0; i != NumRegs; ++i) {
1081 assert(Reg < Regs.size() && "Mismatch in # registers expected");
1082 Register TheReg = Regs[Reg++];
1083 Ops.push_back(x: DAG.getRegister(Reg: TheReg, VT: RegisterVT));
1084 }
1085 }
1086}
1087
1088SmallVector<std::pair<Register, TypeSize>, 4>
1089RegsForValue::getRegsAndSizes() const {
1090 SmallVector<std::pair<Register, TypeSize>, 4> OutVec;
1091 unsigned I = 0;
1092 for (auto CountAndVT : zip_first(t: RegCount, u: RegVTs)) {
1093 unsigned RegCount = std::get<0>(t&: CountAndVT);
1094 MVT RegisterVT = std::get<1>(t&: CountAndVT);
1095 TypeSize RegisterSize = RegisterVT.getSizeInBits();
1096 for (unsigned E = I + RegCount; I != E; ++I)
1097 OutVec.push_back(Elt: std::make_pair(x: Regs[I], y&: RegisterSize));
1098 }
1099 return OutVec;
1100}
1101
1102void SelectionDAGBuilder::init(GCFunctionInfo *gfi, BatchAAResults *aa,
1103 AssumptionCache *ac, const TargetLibraryInfo *li,
1104 const TargetTransformInfo &TTI) {
1105 BatchAA = aa;
1106 AC = ac;
1107 GFI = gfi;
1108 LibInfo = li;
1109 Context = DAG.getContext();
1110 LPadToCallSiteMap.clear();
1111 this->TTI = &TTI;
1112 SL->init(tli: DAG.getTargetLoweringInfo(), tm: TM, dl: DAG.getDataLayout());
1113 AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1114 M: *DAG.getMachineFunction().getFunction().getParent());
1115}
1116
1117void SelectionDAGBuilder::clear() {
1118 NodeMap.clear();
1119 UnusedArgNodeMap.clear();
1120 PendingLoads.clear();
1121 PendingExports.clear();
1122 PendingConstrainedFP.clear();
1123 PendingConstrainedFPStrict.clear();
1124 CurInst = nullptr;
1125 HasTailCall = false;
1126 SDNodeOrder = LowestSDNodeOrder;
1127 StatepointLowering.clear();
1128}
1129
1130void SelectionDAGBuilder::clearDanglingDebugInfo() {
1131 DanglingDebugInfoMap.clear();
1132}
1133
1134// Update DAG root to include dependencies on Pending chains.
1135SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1136 SDValue Root = DAG.getRoot();
1137
1138 if (Pending.empty())
1139 return Root;
1140
1141 // Add current root to PendingChains, unless we already indirectly
1142 // depend on it.
1143 if (Root.getOpcode() != ISD::EntryToken) {
1144 unsigned i = 0, e = Pending.size();
1145 for (; i != e; ++i) {
1146 assert(Pending[i].getNode()->getNumOperands() > 1);
1147 if (Pending[i].getNode()->getOperand(Num: 0) == Root)
1148 break; // Don't add the root if we already indirectly depend on it.
1149 }
1150
1151 if (i == e)
1152 Pending.push_back(Elt: Root);
1153 }
1154
1155 if (Pending.size() == 1)
1156 Root = Pending[0];
1157 else
1158 Root = DAG.getTokenFactor(DL: getCurSDLoc(), Vals&: Pending);
1159
1160 DAG.setRoot(Root);
1161 Pending.clear();
1162 return Root;
1163}
1164
1165SDValue SelectionDAGBuilder::getMemoryRoot() {
1166 return updateRoot(Pending&: PendingLoads);
1167}
1168
1169SDValue SelectionDAGBuilder::getFPOperationRoot(fp::ExceptionBehavior EB) {
1170 // If the new exception behavior differs from that of the pending
1171 // ones, chain up them and update the root.
1172 switch (EB) {
1173 case fp::ExceptionBehavior::ebMayTrap:
1174 case fp::ExceptionBehavior::ebIgnore:
1175 // Floating-point exceptions produced by such operations are not intended
1176 // to be observed, so the sequence of these operations does not need to be
1177 // preserved.
1178 //
1179 // They however must not be mixed with the instructions that have strict
1180 // exception behavior. Placing an operation with 'ebIgnore' behavior between
1181 // 'ebStrict' operations could distort the observed exception behavior.
1182 if (!PendingConstrainedFPStrict.empty()) {
1183 assert(PendingConstrainedFP.empty());
1184 updateRoot(Pending&: PendingConstrainedFPStrict);
1185 }
1186 break;
1187 case fp::ExceptionBehavior::ebStrict:
1188 // Floating-point exception produced by these operations may be observed, so
1189 // they must be correctly chained. If trapping on FP exceptions is
1190 // disabled, the exceptions can be observed only by functions that read
1191 // exception flags, like 'llvm.get_fpenv' or 'fetestexcept'. It means that
1192 // the order of operations is not significant between barriers.
1193 //
1194 // If trapping is enabled, each operation becomes an implicit observation
1195 // point, so the operations must be sequenced according their original
1196 // source order.
1197 if (!PendingConstrainedFP.empty()) {
1198 assert(PendingConstrainedFPStrict.empty());
1199 updateRoot(Pending&: PendingConstrainedFP);
1200 }
1201 // TODO: Add support for trapping-enabled scenarios.
1202 }
1203 return DAG.getRoot();
1204}
1205
1206SDValue SelectionDAGBuilder::getRoot() {
1207 // Chain up all pending constrained intrinsics together with all
1208 // pending loads, by simply appending them to PendingLoads and
1209 // then calling getMemoryRoot().
1210 PendingLoads.reserve(N: PendingLoads.size() +
1211 PendingConstrainedFP.size() +
1212 PendingConstrainedFPStrict.size());
1213 PendingLoads.append(in_start: PendingConstrainedFP.begin(),
1214 in_end: PendingConstrainedFP.end());
1215 PendingLoads.append(in_start: PendingConstrainedFPStrict.begin(),
1216 in_end: PendingConstrainedFPStrict.end());
1217 PendingConstrainedFP.clear();
1218 PendingConstrainedFPStrict.clear();
1219 return getMemoryRoot();
1220}
1221
1222SDValue SelectionDAGBuilder::getControlRoot() {
1223 // We need to emit pending fpexcept.strict constrained intrinsics,
1224 // so append them to the PendingExports list.
1225 PendingExports.append(in_start: PendingConstrainedFPStrict.begin(),
1226 in_end: PendingConstrainedFPStrict.end());
1227 PendingConstrainedFPStrict.clear();
1228 return updateRoot(Pending&: PendingExports);
1229}
1230
1231void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1232 DILocalVariable *Variable,
1233 DIExpression *Expression,
1234 DebugLoc DL) {
1235 assert(Variable && "Missing variable");
1236
1237 // Check if address has undef value.
1238 if (!Address || isa<UndefValue>(Val: Address) ||
1239 (Address->use_empty() && !isa<Argument>(Val: Address))) {
1240 LLVM_DEBUG(
1241 dbgs()
1242 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1243 return;
1244 }
1245
1246 bool IsParameter = Variable->isParameter() || isa<Argument>(Val: Address);
1247
1248 SDValue &N = NodeMap[Address];
1249 if (!N.getNode() && isa<Argument>(Val: Address))
1250 // Check unused arguments map.
1251 N = UnusedArgNodeMap[Address];
1252 SDDbgValue *SDV;
1253 if (N.getNode()) {
1254 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Val: Address))
1255 Address = BCI->getOperand(i_nocapture: 0);
1256 // Parameters are handled specially.
1257 auto *FINode = dyn_cast<FrameIndexSDNode>(Val: N.getNode());
1258 if (IsParameter && FINode) {
1259 // Byval parameter. We have a frame index at this point.
1260 SDV = DAG.getFrameIndexDbgValue(Var: Variable, Expr: Expression, FI: FINode->getIndex(),
1261 /*IsIndirect*/ true, DL, O: SDNodeOrder);
1262 } else if (isa<Argument>(Val: Address)) {
1263 // Address is an argument, so try to emit its dbg value using
1264 // virtual register info from the FuncInfo.ValueMap.
1265 EmitFuncArgumentDbgValue(V: Address, Variable, Expr: Expression, DL,
1266 Kind: FuncArgumentDbgValueKind::Declare, N);
1267 return;
1268 } else {
1269 SDV = DAG.getDbgValue(Var: Variable, Expr: Expression, N: N.getNode(), R: N.getResNo(),
1270 IsIndirect: true, DL, O: SDNodeOrder);
1271 }
1272 DAG.AddDbgValue(DB: SDV, isParameter: IsParameter);
1273 } else {
1274 // If Address is an argument then try to emit its dbg value using
1275 // virtual register info from the FuncInfo.ValueMap.
1276 if (!EmitFuncArgumentDbgValue(V: Address, Variable, Expr: Expression, DL,
1277 Kind: FuncArgumentDbgValueKind::Declare, N)) {
1278 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1279 << " (could not emit func-arg dbg_value)\n");
1280 }
1281 }
1282}
1283
1284void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1285 // Add SDDbgValue nodes for any var locs here. Do so before updating
1286 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1287 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1288 // Add SDDbgValue nodes for any var locs here. Do so before updating
1289 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1290 for (auto It = FnVarLocs->locs_begin(Before: &I), End = FnVarLocs->locs_end(Before: &I);
1291 It != End; ++It) {
1292 auto *Var = FnVarLocs->getDILocalVariable(ID: It->VariableID);
1293 dropDanglingDebugInfo(Variable: Var, Expr: It->Expr);
1294 if (It->Values.isKillLocation(Expression: It->Expr)) {
1295 handleKillDebugValue(Var, Expr: It->Expr, DbgLoc: It->DL, Order: SDNodeOrder);
1296 continue;
1297 }
1298 SmallVector<Value *> Values(It->Values.location_ops());
1299 if (!handleDebugValue(Values, Var, Expr: It->Expr, DbgLoc: It->DL, Order: SDNodeOrder,
1300 IsVariadic: It->Values.hasArgList())) {
1301 SmallVector<Value *, 4> Vals(It->Values.location_ops());
1302 addDanglingDebugInfo(Values&: Vals,
1303 Var: FnVarLocs->getDILocalVariable(ID: It->VariableID),
1304 Expr: It->Expr, IsVariadic: Vals.size() > 1, DL: It->DL, Order: SDNodeOrder);
1305 }
1306 }
1307 }
1308
1309 // We must skip DbgVariableRecords if they've already been processed above as
1310 // we have just emitted the debug values resulting from assignment tracking
1311 // analysis, making any existing DbgVariableRecords redundant (and probably
1312 // less correct). We still need to process DbgLabelRecords. This does sink
1313 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1314 // be important as it does so deterministcally and ordering between
1315 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1316 // printing).
1317 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1318 // Is there is any debug-info attached to this instruction, in the form of
1319 // DbgRecord non-instruction debug-info records.
1320 for (DbgRecord &DR : I.getDbgRecordRange()) {
1321 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(Val: &DR)) {
1322 assert(DLR->getLabel() && "Missing label");
1323 SDDbgLabel *SDV =
1324 DAG.getDbgLabel(Label: DLR->getLabel(), DL: DLR->getDebugLoc(), O: SDNodeOrder);
1325 DAG.AddDbgLabel(DB: SDV);
1326 continue;
1327 }
1328
1329 if (SkipDbgVariableRecords)
1330 continue;
1331 DbgVariableRecord &DVR = cast<DbgVariableRecord>(Val&: DR);
1332 DILocalVariable *Variable = DVR.getVariable();
1333 DIExpression *Expression = DVR.getExpression();
1334 dropDanglingDebugInfo(Variable, Expr: Expression);
1335
1336 if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1337 if (FuncInfo.PreprocessedDVRDeclares.contains(Ptr: &DVR))
1338 continue;
1339 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1340 << "\n");
1341 handleDebugDeclare(Address: DVR.getVariableLocationOp(OpIdx: 0), Variable, Expression,
1342 DL: DVR.getDebugLoc());
1343 continue;
1344 }
1345
1346 // A DbgVariableRecord with no locations is a kill location.
1347 SmallVector<Value *, 4> Values(DVR.location_ops());
1348 if (Values.empty()) {
1349 handleKillDebugValue(Var: Variable, Expr: Expression, DbgLoc: DVR.getDebugLoc(),
1350 Order: SDNodeOrder);
1351 continue;
1352 }
1353
1354 // A DbgVariableRecord with an undef or absent location is also a kill
1355 // location.
1356 if (llvm::any_of(Range&: Values,
1357 P: [](Value *V) { return !V || isa<UndefValue>(Val: V); })) {
1358 handleKillDebugValue(Var: Variable, Expr: Expression, DbgLoc: DVR.getDebugLoc(),
1359 Order: SDNodeOrder);
1360 continue;
1361 }
1362
1363 bool IsVariadic = DVR.hasArgList();
1364 if (!handleDebugValue(Values, Var: Variable, Expr: Expression, DbgLoc: DVR.getDebugLoc(),
1365 Order: SDNodeOrder, IsVariadic)) {
1366 addDanglingDebugInfo(Values, Var: Variable, Expr: Expression, IsVariadic,
1367 DL: DVR.getDebugLoc(), Order: SDNodeOrder);
1368 }
1369 }
1370}
1371
1372void SelectionDAGBuilder::visit(const Instruction &I) {
1373 visitDbgInfo(I);
1374
1375 // Set up outgoing PHI node register values before emitting the terminator.
1376 if (I.isTerminator()) {
1377 HandlePHINodesInSuccessorBlocks(LLVMBB: I.getParent());
1378 }
1379
1380 ++SDNodeOrder;
1381 CurInst = &I;
1382
1383 // Set inserted listener only if required.
1384 bool NodeInserted = false;
1385 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1386 MDNode *PCSectionsMD = I.getMetadata(KindID: LLVMContext::MD_pcsections);
1387 MDNode *MMRA = I.getMetadata(KindID: LLVMContext::MD_mmra);
1388 if (PCSectionsMD || MMRA) {
1389 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1390 args&: DAG, args: [&](SDNode *) { NodeInserted = true; });
1391 }
1392
1393 visit(Opcode: I.getOpcode(), I);
1394
1395 if (!I.isTerminator() && !HasTailCall &&
1396 !isa<GCStatepointInst>(Val: I)) // statepoints handle their exports internally
1397 CopyToExportRegsIfNeeded(V: &I);
1398
1399 // Handle metadata.
1400 if (PCSectionsMD || MMRA) {
1401 auto It = NodeMap.find(Val: &I);
1402 if (It != NodeMap.end()) {
1403 if (PCSectionsMD)
1404 DAG.addPCSections(Node: It->second.getNode(), MD: PCSectionsMD);
1405 if (MMRA)
1406 DAG.addMMRAMetadata(Node: It->second.getNode(), MMRA);
1407 } else if (NodeInserted) {
1408 // This should not happen; if it does, don't let it go unnoticed so we can
1409 // fix it. Relevant visit*() function is probably missing a setValue().
1410 errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1411 << I.getModule()->getName() << "]\n";
1412 LLVM_DEBUG(I.dump());
1413 assert(false);
1414 }
1415 }
1416
1417 CurInst = nullptr;
1418}
1419
1420void SelectionDAGBuilder::visitPHI(const PHINode &) {
1421 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1422}
1423
1424void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1425 // Note: this doesn't use InstVisitor, because it has to work with
1426 // ConstantExpr's in addition to instructions.
1427 switch (Opcode) {
1428 default: llvm_unreachable("Unknown instruction type encountered!");
1429 // Build the switch statement using the Instruction.def file.
1430#define HANDLE_INST(NUM, OPCODE, CLASS) \
1431 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1432#include "llvm/IR/Instruction.def"
1433 }
1434}
1435
1436static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1437 DILocalVariable *Variable,
1438 DebugLoc DL, unsigned Order,
1439 SmallVectorImpl<Value *> &Values,
1440 DIExpression *Expression) {
1441 // For variadic dbg_values we will now insert poison.
1442 // FIXME: We can potentially recover these!
1443 SmallVector<SDDbgOperand, 2> Locs;
1444 for (const Value *V : Values) {
1445 auto *Poison = PoisonValue::get(T: V->getType());
1446 Locs.push_back(Elt: SDDbgOperand::fromConst(Const: Poison));
1447 }
1448 SDDbgValue *SDV = DAG.getDbgValueList(Var: Variable, Expr: Expression, Locs, Dependencies: {},
1449 /*IsIndirect=*/false, DL, O: Order,
1450 /*IsVariadic=*/true);
1451 DAG.AddDbgValue(DB: SDV, /*isParameter=*/false);
1452 return true;
1453}
1454
1455void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1456 DILocalVariable *Var,
1457 DIExpression *Expr,
1458 bool IsVariadic, DebugLoc DL,
1459 unsigned Order) {
1460 if (IsVariadic) {
1461 handleDanglingVariadicDebugInfo(DAG, Variable: Var, DL, Order, Values, Expression: Expr);
1462 return;
1463 }
1464 // TODO: Dangling debug info will eventually either be resolved or produce
1465 // a poison DBG_VALUE. However in the resolution case, a gap may appear
1466 // between the original dbg.value location and its resolved DBG_VALUE,
1467 // which we should ideally fill with an extra poison DBG_VALUE.
1468 assert(Values.size() == 1);
1469 DanglingDebugInfoMap[Values[0]].emplace_back(args&: Var, args&: Expr, args&: DL, args&: Order);
1470}
1471
1472void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1473 const DIExpression *Expr) {
1474 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1475 DIVariable *DanglingVariable = DDI.getVariable();
1476 DIExpression *DanglingExpr = DDI.getExpression();
1477 if (DanglingVariable == Variable && Expr->fragmentsOverlap(Other: DanglingExpr)) {
1478 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1479 << printDDI(nullptr, DDI) << "\n");
1480 return true;
1481 }
1482 return false;
1483 };
1484
1485 for (auto &DDIMI : DanglingDebugInfoMap) {
1486 DanglingDebugInfoVector &DDIV = DDIMI.second;
1487
1488 // If debug info is to be dropped, run it through final checks to see
1489 // whether it can be salvaged.
1490 for (auto &DDI : DDIV)
1491 if (isMatchingDbgValue(DDI))
1492 salvageUnresolvedDbgValue(V: DDIMI.first, DDI);
1493
1494 erase_if(C&: DDIV, P: isMatchingDbgValue);
1495 }
1496}
1497
1498// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1499// generate the debug data structures now that we've seen its definition.
1500void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1501 SDValue Val) {
1502 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(Key: V);
1503 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1504 return;
1505
1506 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1507 for (auto &DDI : DDIV) {
1508 DebugLoc DL = DDI.getDebugLoc();
1509 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1510 DILocalVariable *Variable = DDI.getVariable();
1511 DIExpression *Expr = DDI.getExpression();
1512 assert(Variable->isValidLocationForIntrinsic(DL) &&
1513 "Expected inlined-at fields to agree");
1514 SDDbgValue *SDV;
1515 if (Val.getNode()) {
1516 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1517 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1518 // we couldn't resolve it directly when examining the DbgValue intrinsic
1519 // in the first place we should not be more successful here). Unless we
1520 // have some test case that prove this to be correct we should avoid
1521 // calling EmitFuncArgumentDbgValue here.
1522 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1523 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1524 Kind: FuncArgumentDbgValueKind::Value, N: Val)) {
1525 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1526 << printDDI(V, DDI) << "\n");
1527 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1528 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1529 // inserted after the definition of Val when emitting the instructions
1530 // after ISel. An alternative could be to teach
1531 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1532 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1533 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1534 << ValSDNodeOrder << "\n");
1535 SDV = getDbgValue(N: Val, Variable, Expr, dl: DL,
1536 DbgSDNodeOrder: std::max(a: DbgSDNodeOrder, b: ValSDNodeOrder));
1537 DAG.AddDbgValue(DB: SDV, isParameter: false);
1538 } else
1539 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1540 << printDDI(V, DDI)
1541 << " in EmitFuncArgumentDbgValue\n");
1542 } else {
1543 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1544 << "\n");
1545 auto Poison = PoisonValue::get(T: V->getType());
1546 auto SDV =
1547 DAG.getConstantDbgValue(Var: Variable, Expr, C: Poison, DL, O: DbgSDNodeOrder);
1548 DAG.AddDbgValue(DB: SDV, isParameter: false);
1549 }
1550 }
1551 DDIV.clear();
1552}
1553
1554void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1555 DanglingDebugInfo &DDI) {
1556 // TODO: For the variadic implementation, instead of only checking the fail
1557 // state of `handleDebugValue`, we need know specifically which values were
1558 // invalid, so that we attempt to salvage only those values when processing
1559 // a DIArgList.
1560 const Value *OrigV = V;
1561 DILocalVariable *Var = DDI.getVariable();
1562 DIExpression *Expr = DDI.getExpression();
1563 DebugLoc DL = DDI.getDebugLoc();
1564 unsigned SDOrder = DDI.getSDNodeOrder();
1565
1566 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1567 // that DW_OP_stack_value is desired.
1568 bool StackValue = true;
1569
1570 // Can this Value can be encoded without any further work?
1571 if (handleDebugValue(Values: V, Var, Expr, DbgLoc: DL, Order: SDOrder, /*IsVariadic=*/false))
1572 return;
1573
1574 // Attempt to salvage back through as many instructions as possible. Bail if
1575 // a non-instruction is seen, such as a constant expression or global
1576 // variable. FIXME: Further work could recover those too.
1577 while (isa<Instruction>(Val: V)) {
1578 const Instruction &VAsInst = *cast<const Instruction>(Val: V);
1579 // Temporary "0", awaiting real implementation.
1580 SmallVector<uint64_t, 16> Ops;
1581 SmallVector<Value *, 4> AdditionalValues;
1582 V = salvageDebugInfoImpl(I&: const_cast<Instruction &>(VAsInst),
1583 CurrentLocOps: Expr->getNumLocationOperands(), Ops,
1584 AdditionalValues);
1585 // If we cannot salvage any further, and haven't yet found a suitable debug
1586 // expression, bail out.
1587 if (!V)
1588 break;
1589
1590 // TODO: If AdditionalValues isn't empty, then the salvage can only be
1591 // represented with a DBG_VALUE_LIST, so we give up. When we have support
1592 // here for variadic dbg_values, remove that condition.
1593 if (!AdditionalValues.empty())
1594 break;
1595
1596 // New value and expr now represent this debuginfo.
1597 Expr = DIExpression::appendOpsToArg(Expr, Ops, ArgNo: 0, StackValue);
1598
1599 // Some kind of simplification occurred: check whether the operand of the
1600 // salvaged debug expression can be encoded in this DAG.
1601 if (handleDebugValue(Values: V, Var, Expr, DbgLoc: DL, Order: SDOrder, /*IsVariadic=*/false)) {
1602 LLVM_DEBUG(
1603 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n"
1604 << *OrigV << "\nBy stripping back to:\n " << *V << "\n");
1605 return;
1606 }
1607 }
1608
1609 // This was the final opportunity to salvage this debug information, and it
1610 // couldn't be done. Place a poison DBG_VALUE at this location to terminate
1611 // any earlier variable location.
1612 assert(OrigV && "V shouldn't be null");
1613 auto *Poison = PoisonValue::get(T: OrigV->getType());
1614 auto *SDV = DAG.getConstantDbgValue(Var, Expr, C: Poison, DL, O: SDNodeOrder);
1615 DAG.AddDbgValue(DB: SDV, isParameter: false);
1616 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n "
1617 << printDDI(OrigV, DDI) << "\n");
1618}
1619
1620void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1621 DIExpression *Expr,
1622 DebugLoc DbgLoc,
1623 unsigned Order) {
1624 Value *Poison = PoisonValue::get(T: Type::getInt1Ty(C&: *Context));
1625 DIExpression *NewExpr =
1626 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1627 handleDebugValue(Values: Poison, Var, Expr: NewExpr, DbgLoc, Order,
1628 /*IsVariadic*/ false);
1629}
1630
1631bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1632 DILocalVariable *Var,
1633 DIExpression *Expr, DebugLoc DbgLoc,
1634 unsigned Order, bool IsVariadic) {
1635 if (Values.empty())
1636 return true;
1637
1638 // Filter EntryValue locations out early.
1639 if (visitEntryValueDbgValue(Values, Variable: Var, Expr, DbgLoc))
1640 return true;
1641
1642 SmallVector<SDDbgOperand> LocationOps;
1643 SmallVector<SDNode *> Dependencies;
1644 for (const Value *V : Values) {
1645 // Constant value.
1646 if (isa<ConstantInt>(Val: V) || isa<ConstantFP>(Val: V) || isa<UndefValue>(Val: V) ||
1647 isa<ConstantPointerNull>(Val: V)) {
1648 LocationOps.emplace_back(Args: SDDbgOperand::fromConst(Const: V));
1649 continue;
1650 }
1651
1652 // Look through IntToPtr constants.
1653 if (auto *CE = dyn_cast<ConstantExpr>(Val: V))
1654 if (CE->getOpcode() == Instruction::IntToPtr) {
1655 LocationOps.emplace_back(Args: SDDbgOperand::fromConst(Const: CE->getOperand(i_nocapture: 0)));
1656 continue;
1657 }
1658
1659 // If the Value is a frame index, we can create a FrameIndex debug value
1660 // without relying on the DAG at all.
1661 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Val: V)) {
1662 auto SI = FuncInfo.StaticAllocaMap.find(Val: AI);
1663 if (SI != FuncInfo.StaticAllocaMap.end()) {
1664 LocationOps.emplace_back(Args: SDDbgOperand::fromFrameIdx(FrameIdx: SI->second));
1665 continue;
1666 }
1667 }
1668
1669 // Do not use getValue() in here; we don't want to generate code at
1670 // this point if it hasn't been done yet.
1671 SDValue N = NodeMap[V];
1672 if (!N.getNode() && isa<Argument>(Val: V)) // Check unused arguments map.
1673 N = UnusedArgNodeMap[V];
1674
1675 if (N.getNode()) {
1676 // Only emit func arg dbg value for non-variadic dbg.values for now.
1677 if (!IsVariadic &&
1678 EmitFuncArgumentDbgValue(V, Variable: Var, Expr, DL: DbgLoc,
1679 Kind: FuncArgumentDbgValueKind::Value, N))
1680 return true;
1681 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Val: N.getNode())) {
1682 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1683 // describe stack slot locations.
1684 //
1685 // Consider "int x = 0; int *px = &x;". There are two kinds of
1686 // interesting debug values here after optimization:
1687 //
1688 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
1689 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1690 //
1691 // Both describe the direct values of their associated variables.
1692 Dependencies.push_back(Elt: N.getNode());
1693 LocationOps.emplace_back(Args: SDDbgOperand::fromFrameIdx(FrameIdx: FISDN->getIndex()));
1694 continue;
1695 }
1696 LocationOps.emplace_back(
1697 Args: SDDbgOperand::fromNode(Node: N.getNode(), ResNo: N.getResNo()));
1698 continue;
1699 }
1700
1701 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1702 // Special rules apply for the first dbg.values of parameter variables in a
1703 // function. Identify them by the fact they reference Argument Values, that
1704 // they're parameters, and they are parameters of the current function. We
1705 // need to let them dangle until they get an SDNode.
1706 bool IsParamOfFunc =
1707 isa<Argument>(Val: V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1708 if (IsParamOfFunc)
1709 return false;
1710
1711 // The value is not used in this block yet (or it would have an SDNode).
1712 // We still want the value to appear for the user if possible -- if it has
1713 // an associated VReg, we can refer to that instead.
1714 auto VMI = FuncInfo.ValueMap.find(Val: V);
1715 if (VMI != FuncInfo.ValueMap.end()) {
1716 Register Reg = VMI->second;
1717 // If this is a PHI node, it may be split up into several MI PHI nodes
1718 // (in FunctionLoweringInfo::set).
1719 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1720 V->getType(), std::nullopt);
1721 if (RFV.occupiesMultipleRegs()) {
1722 // FIXME: We could potentially support variadic dbg_values here.
1723 if (IsVariadic)
1724 return false;
1725 unsigned Offset = 0;
1726 unsigned BitsToDescribe = 0;
1727 if (auto VarSize = Var->getSizeInBits())
1728 BitsToDescribe = *VarSize;
1729 if (auto Fragment = Expr->getFragmentInfo())
1730 BitsToDescribe = Fragment->SizeInBits;
1731 for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1732 // Bail out if all bits are described already.
1733 if (Offset >= BitsToDescribe)
1734 break;
1735 // TODO: handle scalable vectors.
1736 unsigned RegisterSize = RegAndSize.second;
1737 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1738 ? BitsToDescribe - Offset
1739 : RegisterSize;
1740 auto FragmentExpr = DIExpression::createFragmentExpression(
1741 Expr, OffsetInBits: Offset, SizeInBits: FragmentSize);
1742 if (!FragmentExpr)
1743 continue;
1744 SDDbgValue *SDV = DAG.getVRegDbgValue(
1745 Var, Expr: *FragmentExpr, VReg: RegAndSize.first, IsIndirect: false, DL: DbgLoc, O: Order);
1746 DAG.AddDbgValue(DB: SDV, isParameter: false);
1747 Offset += RegisterSize;
1748 }
1749 return true;
1750 }
1751 // We can use simple vreg locations for variadic dbg_values as well.
1752 LocationOps.emplace_back(Args: SDDbgOperand::fromVReg(VReg: Reg));
1753 continue;
1754 }
1755 // We failed to create a SDDbgOperand for V.
1756 return false;
1757 }
1758
1759 // We have created a SDDbgOperand for each Value in Values.
1760 assert(!LocationOps.empty());
1761 SDDbgValue *SDV =
1762 DAG.getDbgValueList(Var, Expr, Locs: LocationOps, Dependencies,
1763 /*IsIndirect=*/false, DL: DbgLoc, O: Order, IsVariadic);
1764 DAG.AddDbgValue(DB: SDV, /*isParameter=*/false);
1765 return true;
1766}
1767
1768void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1769 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1770 for (auto &Pair : DanglingDebugInfoMap)
1771 for (auto &DDI : Pair.second)
1772 salvageUnresolvedDbgValue(V: const_cast<Value *>(Pair.first), DDI);
1773 clearDanglingDebugInfo();
1774}
1775
1776/// getCopyFromRegs - If there was virtual register allocated for the value V
1777/// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1778SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1779 auto It = FuncInfo.ValueMap.find(Val: V);
1780 SDValue Result;
1781
1782 if (It != FuncInfo.ValueMap.end()) {
1783 Register InReg = It->second;
1784
1785 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1786 DAG.getDataLayout(), InReg, Ty,
1787 std::nullopt); // This is not an ABI copy.
1788 SDValue Chain = DAG.getEntryNode();
1789 Result = RFV.getCopyFromRegs(DAG, FuncInfo, dl: getCurSDLoc(), Chain, Glue: nullptr,
1790 V);
1791 resolveDanglingDebugInfo(V, Val: Result);
1792 }
1793
1794 return Result;
1795}
1796
1797/// getValue - Return an SDValue for the given Value.
1798SDValue SelectionDAGBuilder::getValue(const Value *V) {
1799 // If we already have an SDValue for this value, use it. It's important
1800 // to do this first, so that we don't create a CopyFromReg if we already
1801 // have a regular SDValue.
1802 SDValue &N = NodeMap[V];
1803 if (N.getNode()) return N;
1804
1805 // If there's a virtual register allocated and initialized for this
1806 // value, use it.
1807 if (SDValue copyFromReg = getCopyFromRegs(V, Ty: V->getType()))
1808 return copyFromReg;
1809
1810 // Otherwise create a new SDValue and remember it.
1811 SDValue Val = getValueImpl(V);
1812 NodeMap[V] = Val;
1813 resolveDanglingDebugInfo(V, Val);
1814 return Val;
1815}
1816
1817void SelectionDAGBuilder::setValueToPoison(const Value *V, const SDLoc &dl) {
1818 if (V->getType()->isVoidTy())
1819 return;
1820
1821 SmallVector<EVT, 4> ValueVTs;
1822 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(),
1823 Ty: V->getType(), ValueVTs);
1824 setValue(V, NewN: DAG.getErrorMergeValues(ResultTypes: ValueVTs, Chain: SDValue(), dl));
1825}
1826
1827/// getNonRegisterValue - Return an SDValue for the given Value, but
1828/// don't look in FuncInfo.ValueMap for a virtual register.
1829SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1830 // If we already have an SDValue for this value, use it.
1831 SDValue &N = NodeMap[V];
1832 if (N.getNode()) {
1833 if (isIntOrFPConstant(V: N)) {
1834 // Remove the debug location from the node as the node is about to be used
1835 // in a location which may differ from the original debug location. This
1836 // is relevant to Constant and ConstantFP nodes because they can appear
1837 // as constant expressions inside PHI nodes.
1838 N->setDebugLoc(DebugLoc());
1839 }
1840 return N;
1841 }
1842
1843 // Otherwise create a new SDValue and remember it.
1844 SDValue Val = getValueImpl(V);
1845 NodeMap[V] = Val;
1846 resolveDanglingDebugInfo(V, Val);
1847 return Val;
1848}
1849
1850/// getValueImpl - Helper function for getValue and getNonRegisterValue.
1851/// Create an SDValue for the given value.
1852SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1853 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1854
1855 if (const Constant *C = dyn_cast<Constant>(Val: V)) {
1856 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: V->getType(), AllowUnknown: true);
1857
1858 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: C)) {
1859 SDLoc DL = getCurSDLoc();
1860
1861 // DAG.getConstant() may attempt to legalise the vector constant which can
1862 // significantly change the combines applied to the DAG. To reduce the
1863 // divergence when enabling ConstantInt based vectors we try to construct
1864 // the DAG in the same way as shufflevector based splats. TODO: The
1865 // divergence sometimes leads to better optimisations. Ideally we should
1866 // prevent DAG.getConstant() from legalising too early but there are some
1867 // degradations preventing this.
1868 if (VT.isScalableVector())
1869 return DAG.getNode(
1870 Opcode: ISD::SPLAT_VECTOR, DL, VT,
1871 Operand: DAG.getConstant(Val: CI->getValue(), DL, VT: VT.getVectorElementType()));
1872 if (VT.isFixedLengthVector())
1873 return DAG.getSplatBuildVector(
1874 VT, DL,
1875 Op: DAG.getConstant(Val: CI->getValue(), DL, VT: VT.getVectorElementType()));
1876 return DAG.getConstant(Val: *CI, DL, VT);
1877 }
1878
1879 if (const ConstantByte *CB = dyn_cast<ConstantByte>(Val: C))
1880 return DAG.getConstant(Val: CB->getValue(), DL: getCurSDLoc(), VT);
1881
1882 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Val: C))
1883 return DAG.getGlobalAddress(GV, DL: getCurSDLoc(), VT);
1884
1885 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(Val: C)) {
1886 return DAG.getNode(Opcode: ISD::PtrAuthGlobalAddress, DL: getCurSDLoc(), VT,
1887 N1: getValue(V: CPA->getPointer()), N2: getValue(V: CPA->getKey()),
1888 N3: getValue(V: CPA->getAddrDiscriminator()),
1889 N4: getValue(V: CPA->getDiscriminator()));
1890 }
1891
1892 if (isa<ConstantPointerNull>(Val: C))
1893 return DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT);
1894
1895 if (match(V: C, P: m_VScale()))
1896 return DAG.getVScale(DL: getCurSDLoc(), VT, MulImm: APInt(VT.getSizeInBits(), 1));
1897
1898 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Val: C))
1899 return DAG.getConstantFP(V: *CFP, DL: getCurSDLoc(), VT);
1900
1901 if (isa<UndefValue>(Val: C) && !V->getType()->isAggregateType())
1902 return isa<PoisonValue>(Val: C) ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
1903
1904 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: C)) {
1905 visit(Opcode: CE->getOpcode(), I: *CE);
1906 SDValue N1 = NodeMap[V];
1907 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1908 return N1;
1909 }
1910
1911 if (isa<ConstantStruct>(Val: C) || isa<ConstantArray>(Val: C)) {
1912 SmallVector<SDValue, 4> Constants;
1913 for (const Use &U : C->operands()) {
1914 SDNode *Val = getValue(V: U).getNode();
1915 // If the operand is an empty aggregate, there are no values.
1916 if (!Val) continue;
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 Constants.push_back(Elt: SDValue(Val, i));
1921 }
1922
1923 return DAG.getMergeValues(Ops: Constants, dl: getCurSDLoc());
1924 }
1925
1926 if (const ConstantDataSequential *CDS =
1927 dyn_cast<ConstantDataSequential>(Val: C)) {
1928 SmallVector<SDValue, 4> Ops;
1929 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i) {
1930 SDNode *Val = getValue(V: CDS->getElementAsConstant(i)).getNode();
1931 // Add each leaf value from the operand to the Constants list
1932 // to form a flattened list of all the values.
1933 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1934 Ops.push_back(Elt: SDValue(Val, i));
1935 }
1936
1937 if (isa<ArrayType>(Val: CDS->getType()))
1938 return DAG.getMergeValues(Ops, dl: getCurSDLoc());
1939 return DAG.getBuildVector(VT, DL: getCurSDLoc(), Ops);
1940 }
1941
1942 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1943 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1944 "Unknown struct or array constant!");
1945
1946 SmallVector<EVT, 4> ValueVTs;
1947 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: C->getType(), ValueVTs);
1948 unsigned NumElts = ValueVTs.size();
1949 if (NumElts == 0)
1950 return SDValue(); // empty struct
1951 SmallVector<SDValue, 4> Constants(NumElts);
1952 for (unsigned i = 0; i != NumElts; ++i) {
1953 EVT EltVT = ValueVTs[i];
1954 if (isa<UndefValue>(Val: C))
1955 Constants[i] = DAG.getUNDEF(VT: EltVT);
1956 else if (EltVT.isFloatingPoint())
1957 Constants[i] = DAG.getConstantFP(Val: 0, DL: getCurSDLoc(), VT: EltVT);
1958 else
1959 Constants[i] = DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: EltVT);
1960 }
1961
1962 return DAG.getMergeValues(Ops: Constants, dl: getCurSDLoc());
1963 }
1964
1965 if (const BlockAddress *BA = dyn_cast<BlockAddress>(Val: C))
1966 return DAG.getBlockAddress(BA, VT);
1967
1968 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(Val: C))
1969 return getValue(V: Equiv->getGlobalValue());
1970
1971 if (const auto *NC = dyn_cast<NoCFIValue>(Val: C))
1972 return getValue(V: NC->getGlobalValue());
1973
1974 if (VT == MVT::aarch64svcount) {
1975 assert(C->isNullValue() && "Can only zero this target type!");
1976 return DAG.getNode(Opcode: ISD::BITCAST, DL: getCurSDLoc(), VT,
1977 Operand: DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: MVT::nxv16i1));
1978 }
1979
1980 if (VT.isRISCVVectorTuple()) {
1981 assert(C->isNullValue() && "Can only zero this target type!");
1982 return DAG.getNode(
1983 Opcode: ISD::BITCAST, DL: getCurSDLoc(), VT,
1984 Operand: DAG.getNode(
1985 Opcode: ISD::SPLAT_VECTOR, DL: getCurSDLoc(),
1986 VT: EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::i8,
1987 NumElements: VT.getSizeInBits().getKnownMinValue() / 8, IsScalable: true),
1988 Operand: DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: MVT::getIntegerVT(BitWidth: 8))));
1989 }
1990
1991 if (VT == MVT::externref || VT == MVT::funcref) {
1992 assert(C->isNullValue() && "Can only zero this target type!");
1993 // The zero value of a WebAssembly reference type is the null reference,
1994 // materialized with ref.null.
1995 Intrinsic::ID IID = VT == MVT::externref ? Intrinsic::wasm_ref_null_extern
1996 : Intrinsic::wasm_ref_null_func;
1997 return DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: getCurSDLoc(), VT,
1998 Operand: DAG.getTargetConstant(Val: IID, DL: getCurSDLoc(), VT: MVT::i32));
1999 }
2000
2001 VectorType *VecTy = cast<VectorType>(Val: V->getType());
2002
2003 // Now that we know the number and type of the elements, get that number of
2004 // elements into the Ops array based on what kind of constant it is.
2005 if (const ConstantVector *CV = dyn_cast<ConstantVector>(Val: C)) {
2006 SmallVector<SDValue, 16> Ops;
2007 unsigned NumElements = cast<FixedVectorType>(Val: VecTy)->getNumElements();
2008 for (unsigned i = 0; i != NumElements; ++i)
2009 Ops.push_back(Elt: getValue(V: CV->getOperand(i_nocapture: i)));
2010
2011 return DAG.getBuildVector(VT, DL: getCurSDLoc(), Ops);
2012 }
2013
2014 if (isa<ConstantAggregateZero>(Val: C)) {
2015 EVT EltVT =
2016 TLI.getValueType(DL: DAG.getDataLayout(), Ty: VecTy->getElementType());
2017
2018 SDValue Op;
2019 if (EltVT.isFloatingPoint())
2020 Op = DAG.getConstantFP(Val: 0, DL: getCurSDLoc(), VT: EltVT);
2021 else
2022 Op = DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: EltVT);
2023
2024 return DAG.getSplat(VT, DL: getCurSDLoc(), Op);
2025 }
2026
2027 llvm_unreachable("Unknown vector constant");
2028 }
2029
2030 // If this is a static alloca, generate it as the frameindex instead of
2031 // computation.
2032 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Val: V)) {
2033 auto SI = FuncInfo.StaticAllocaMap.find(Val: AI);
2034 if (SI != FuncInfo.StaticAllocaMap.end())
2035 return DAG.getFrameIndex(
2036 FI: SI->second, VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: AI->getType()));
2037 }
2038
2039 // If this is an instruction which fast-isel has deferred, select it now.
2040 if (const Instruction *Inst = dyn_cast<Instruction>(Val: V)) {
2041 Register InReg = FuncInfo.InitializeRegForValue(V: Inst);
2042 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
2043 Inst->getType(), std::nullopt);
2044 SDValue Chain = DAG.getEntryNode();
2045 return RFV.getCopyFromRegs(DAG, FuncInfo, dl: getCurSDLoc(), Chain, Glue: nullptr, V);
2046 }
2047
2048 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(Val: V))
2049 return DAG.getMDNode(MD: cast<MDNode>(Val: MD->getMetadata()));
2050
2051 if (const auto *BB = dyn_cast<BasicBlock>(Val: V))
2052 return DAG.getBasicBlock(MBB: FuncInfo.getMBB(BB));
2053
2054 llvm_unreachable("Can't get register for value!");
2055}
2056
2057void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
2058 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2059 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
2060 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
2061 bool IsSEH = isAsynchronousEHPersonality(Pers);
2062 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
2063 if (IsSEH) {
2064 // For SEH, EHCont Guard needs to know that this catchpad is a target.
2065 CatchPadMBB->setIsEHContTarget(true);
2066 DAG.getMachineFunction().setHasEHContTarget(true);
2067 } else
2068 CatchPadMBB->setIsEHScopeEntry();
2069 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
2070 if (IsMSVCCXX || IsCoreCLR)
2071 CatchPadMBB->setIsEHFuncletEntry();
2072}
2073
2074void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
2075 // Update machine-CFG edge.
2076 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(BB: I.getSuccessor());
2077 FuncInfo.MBB->addSuccessor(Succ: TargetMBB);
2078
2079 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2080 bool IsSEH = isAsynchronousEHPersonality(Pers);
2081 if (IsSEH) {
2082 // If this is not a fall-through branch or optimizations are switched off,
2083 // emit the branch.
2084 if (TargetMBB != NextBlock(MBB: FuncInfo.MBB) ||
2085 TM.getOptLevel() == CodeGenOptLevel::None)
2086 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other,
2087 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: TargetMBB)));
2088 return;
2089 }
2090
2091 // For non-SEH, EHCont Guard needs to know that this catchret is a target.
2092 TargetMBB->setIsEHContTarget(true);
2093 DAG.getMachineFunction().setHasEHContTarget(true);
2094
2095 // Figure out the funclet membership for the catchret's successor.
2096 // This will be used by the FuncletLayout pass to determine how to order the
2097 // BB's.
2098 // A 'catchret' returns to the outer scope's color.
2099 Value *ParentPad = I.getCatchSwitchParentPad();
2100 const BasicBlock *SuccessorColor;
2101 if (isa<ConstantTokenNone>(Val: ParentPad))
2102 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2103 else
2104 SuccessorColor = cast<Instruction>(Val: ParentPad)->getParent();
2105 assert(SuccessorColor && "No parent funclet for catchret!");
2106 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(BB: SuccessorColor);
2107 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2108
2109 // Create the terminator node.
2110 SDValue Ret = DAG.getNode(Opcode: ISD::CATCHRET, DL: getCurSDLoc(), VT: MVT::Other,
2111 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: TargetMBB),
2112 N3: DAG.getBasicBlock(MBB: SuccessorColorMBB));
2113 DAG.setRoot(Ret);
2114}
2115
2116void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2117 // Don't emit any special code for the cleanuppad instruction. It just marks
2118 // the start of an EH scope/funclet.
2119 FuncInfo.MBB->setIsEHScopeEntry();
2120 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2121 if (Pers != EHPersonality::Wasm_CXX) {
2122 FuncInfo.MBB->setIsEHFuncletEntry();
2123 FuncInfo.MBB->setIsCleanupFuncletEntry();
2124 }
2125}
2126
2127/// When an invoke or a cleanupret unwinds to the next EH pad, there are
2128/// many places it could ultimately go. In the IR, we have a single unwind
2129/// destination, but in the machine CFG, we enumerate all the possible blocks.
2130/// This function skips over imaginary basic blocks that hold catchswitch
2131/// instructions, and finds all the "real" machine
2132/// basic block destinations. As those destinations may not be successors of
2133/// EHPadBB, here we also calculate the edge probability to those destinations.
2134/// The passed-in Prob is the edge probability to EHPadBB.
2135static void findUnwindDestinations(
2136 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2137 BranchProbability Prob,
2138 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2139 &UnwindDests) {
2140 EHPersonality Personality =
2141 classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2142 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2143 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2144 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2145 bool IsSEH = isAsynchronousEHPersonality(Pers: Personality);
2146
2147 while (EHPadBB) {
2148 BasicBlock::const_iterator Pad = EHPadBB->getFirstNonPHIIt();
2149 BasicBlock *NewEHPadBB = nullptr;
2150 if (isa<LandingPadInst>(Val: Pad)) {
2151 // Stop on landingpads. They are not funclets.
2152 UnwindDests.emplace_back(Args: FuncInfo.getMBB(BB: EHPadBB), Args&: Prob);
2153 break;
2154 } else if (isa<CleanupPadInst>(Val: Pad)) {
2155 // Stop on cleanup pads. Cleanups are always funclet entries for all known
2156 // personalities except Wasm. And in Wasm this becomes a catch_all(_ref),
2157 // which always catches an exception.
2158 UnwindDests.emplace_back(Args: FuncInfo.getMBB(BB: EHPadBB), Args&: Prob);
2159 UnwindDests.back().first->setIsEHScopeEntry();
2160 // In Wasm, EH scopes are not funclets
2161 if (!IsWasmCXX)
2162 UnwindDests.back().first->setIsEHFuncletEntry();
2163 break;
2164 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Val&: Pad)) {
2165 // Add the catchpad handlers to the possible destinations.
2166 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2167 UnwindDests.emplace_back(Args: FuncInfo.getMBB(BB: CatchPadBB), Args&: Prob);
2168 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2169 if (IsMSVCCXX || IsCoreCLR)
2170 UnwindDests.back().first->setIsEHFuncletEntry();
2171 if (!IsSEH)
2172 UnwindDests.back().first->setIsEHScopeEntry();
2173 }
2174 NewEHPadBB = CatchSwitch->getUnwindDest();
2175 } else {
2176 continue;
2177 }
2178
2179 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2180 if (BPI && NewEHPadBB)
2181 Prob *= BPI->getEdgeProbability(Src: EHPadBB, Dst: NewEHPadBB);
2182 EHPadBB = NewEHPadBB;
2183 }
2184}
2185
2186void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2187 // Update successor info.
2188 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2189 auto UnwindDest = I.getUnwindDest();
2190 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2191 BranchProbability UnwindDestProb =
2192 (BPI && UnwindDest)
2193 ? BPI->getEdgeProbability(Src: FuncInfo.MBB->getBasicBlock(), Dst: UnwindDest)
2194 : BranchProbability::getZero();
2195 findUnwindDestinations(FuncInfo, EHPadBB: UnwindDest, Prob: UnwindDestProb, UnwindDests);
2196 for (auto &UnwindDest : UnwindDests) {
2197 UnwindDest.first->setIsEHPad();
2198 addSuccessorWithProb(Src: FuncInfo.MBB, Dst: UnwindDest.first, Prob: UnwindDest.second);
2199 }
2200 FuncInfo.MBB->normalizeSuccProbs();
2201
2202 // Create the terminator node.
2203 MachineBasicBlock *CleanupPadMBB =
2204 FuncInfo.getMBB(BB: I.getCleanupPad()->getParent());
2205 SDValue Ret = DAG.getNode(Opcode: ISD::CLEANUPRET, DL: getCurSDLoc(), VT: MVT::Other,
2206 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: CleanupPadMBB));
2207 DAG.setRoot(Ret);
2208}
2209
2210void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2211 report_fatal_error(reason: "visitCatchSwitch not yet implemented!");
2212}
2213
2214void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2215 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2216 auto &DL = DAG.getDataLayout();
2217 SDValue Chain = getControlRoot();
2218 SmallVector<ISD::OutputArg, 8> Outs;
2219 SmallVector<SDValue, 8> OutVals;
2220
2221 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2222 // lower
2223 //
2224 // %val = call <ty> @llvm.experimental.deoptimize()
2225 // ret <ty> %val
2226 //
2227 // differently.
2228 if (I.getParent()->getTerminatingDeoptimizeCall()) {
2229 LowerDeoptimizingReturn();
2230 return;
2231 }
2232
2233 if (!FuncInfo.CanLowerReturn) {
2234 Register DemoteReg = FuncInfo.DemoteRegister;
2235
2236 // Emit a store of the return value through the virtual register.
2237 // Leave Outs empty so that LowerReturn won't try to load return
2238 // registers the usual way.
2239 MVT PtrValueVT = TLI.getPointerTy(DL, AS: DL.getAllocaAddrSpace());
2240 SDValue RetPtr =
2241 DAG.getCopyFromReg(Chain, dl: getCurSDLoc(), Reg: DemoteReg, VT: PtrValueVT);
2242 Type *RetTy = I.getOperand(i_nocapture: 0)->getType();
2243 Align BaseAlign = DL.getPrefTypeAlign(Ty: RetTy);
2244 RetPtr =
2245 TLI.annotateStackObjectPointer(Ptr: RetPtr, DAG, DL: getCurSDLoc(), Alignment: BaseAlign);
2246 SDValue RetOp = getValue(V: I.getOperand(i_nocapture: 0));
2247
2248 SmallVector<EVT, 4> ValueVTs, MemVTs;
2249 SmallVector<uint64_t, 4> Offsets;
2250 ComputeValueVTs(TLI, DL, Ty: RetTy, ValueVTs, MemVTs: &MemVTs, FixedOffsets: &Offsets, StartingOffset: 0);
2251 unsigned NumValues = ValueVTs.size();
2252
2253 SmallVector<SDValue, 4> Chains(NumValues);
2254 for (unsigned i = 0; i != NumValues; ++i) {
2255 // An aggregate return value cannot wrap around the address space, so
2256 // offsets to its parts don't wrap either.
2257 SDValue Ptr = DAG.getObjectPtrOffset(SL: getCurSDLoc(), Ptr: RetPtr,
2258 Offset: TypeSize::getFixed(ExactSize: Offsets[i]));
2259
2260 SDValue Val = RetOp.getValue(R: RetOp.getResNo() + i);
2261 if (MemVTs[i] != ValueVTs[i])
2262 Val = DAG.getPtrExtOrTrunc(Op: Val, DL: getCurSDLoc(), VT: MemVTs[i]);
2263 Chains[i] = DAG.getStore(
2264 Chain, dl: getCurSDLoc(), Val,
2265 // FIXME: better loc info would be nice.
2266 Ptr, PtrInfo: MachinePointerInfo::getUnknownStack(MF&: DAG.getMachineFunction()),
2267 Alignment: commonAlignment(A: BaseAlign, Offset: Offsets[i]));
2268 }
2269
2270 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: getCurSDLoc(),
2271 VT: MVT::Other, Ops: Chains);
2272 } else if (I.getNumOperands() != 0) {
2273 SmallVector<Type *, 4> Types;
2274 ComputeValueTypes(DL, Ty: I.getOperand(i_nocapture: 0)->getType(), Types);
2275 unsigned NumValues = Types.size();
2276 if (NumValues) {
2277 SDValue RetOp = getValue(V: I.getOperand(i_nocapture: 0));
2278
2279 const Function *F = I.getParent()->getParent();
2280
2281 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2282 Ty: I.getOperand(i_nocapture: 0)->getType(), CallConv: F->getCallingConv(),
2283 /*IsVarArg*/ isVarArg: false, DL);
2284
2285 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2286 if (F->getAttributes().hasRetAttr(Kind: Attribute::SExt))
2287 ExtendKind = ISD::SIGN_EXTEND;
2288 else if (F->getAttributes().hasRetAttr(Kind: Attribute::ZExt))
2289 ExtendKind = ISD::ZERO_EXTEND;
2290
2291 LLVMContext &Context = F->getContext();
2292 bool RetInReg = F->getAttributes().hasRetAttr(Kind: Attribute::InReg);
2293
2294 for (unsigned j = 0; j != NumValues; ++j) {
2295 EVT VT = TLI.getValueType(DL, Ty: Types[j]);
2296
2297 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2298 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2299
2300 CallingConv::ID CC = F->getCallingConv();
2301
2302 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2303 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2304 SmallVector<SDValue, 4> Parts(NumParts);
2305 getCopyToParts(DAG, DL: getCurSDLoc(),
2306 Val: SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2307 Parts: &Parts[0], NumParts, PartVT, V: &I, CallConv: CC, ExtendKind);
2308
2309 // 'inreg' on function refers to return value
2310 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2311 if (RetInReg)
2312 Flags.setInReg();
2313
2314 if (I.getOperand(i_nocapture: 0)->getType()->isPointerTy()) {
2315 Flags.setPointer();
2316 Flags.setPointerAddrSpace(
2317 cast<PointerType>(Val: I.getOperand(i_nocapture: 0)->getType())->getAddressSpace());
2318 }
2319
2320 if (NeedsRegBlock) {
2321 Flags.setInConsecutiveRegs();
2322 if (j == NumValues - 1)
2323 Flags.setInConsecutiveRegsLast();
2324 }
2325
2326 // Propagate extension type if any
2327 if (ExtendKind == ISD::SIGN_EXTEND)
2328 Flags.setSExt();
2329 else if (ExtendKind == ISD::ZERO_EXTEND)
2330 Flags.setZExt();
2331 else if (F->getAttributes().hasRetAttr(Kind: Attribute::NoExt))
2332 Flags.setNoExt();
2333
2334 for (unsigned i = 0; i < NumParts; ++i) {
2335 Outs.push_back(Elt: ISD::OutputArg(Flags,
2336 Parts[i].getValueType().getSimpleVT(),
2337 VT, Types[j], 0, 0));
2338 OutVals.push_back(Elt: Parts[i]);
2339 }
2340 }
2341 }
2342 }
2343
2344 // Push in swifterror virtual register as the last element of Outs. This makes
2345 // sure swifterror virtual register will be returned in the swifterror
2346 // physical register.
2347 const Function *F = I.getParent()->getParent();
2348 if (TLI.supportSwiftError() &&
2349 F->getAttributes().hasAttrSomewhere(Kind: Attribute::SwiftError)) {
2350 assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2351 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2352 Flags.setSwiftError();
2353 Outs.push_back(Elt: ISD::OutputArg(Flags, /*vt=*/TLI.getPointerTy(DL),
2354 /*argvt=*/EVT(TLI.getPointerTy(DL)),
2355 PointerType::getUnqual(C&: *DAG.getContext()),
2356 /*origidx=*/1, /*partOffs=*/0));
2357 // Create SDNode for the swifterror virtual register.
2358 OutVals.push_back(
2359 Elt: DAG.getRegister(Reg: SwiftError.getOrCreateVRegUseAt(
2360 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2361 VT: EVT(TLI.getPointerTy(DL))));
2362 }
2363
2364 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2365 CallingConv::ID CallConv =
2366 DAG.getMachineFunction().getFunction().getCallingConv();
2367 Chain = DAG.getTargetLoweringInfo().LowerReturn(
2368 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2369
2370 // Verify that the target's LowerReturn behaved as expected.
2371 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2372 "LowerReturn didn't return a valid chain!");
2373
2374 // Update the DAG with the new chain value resulting from return lowering.
2375 DAG.setRoot(Chain);
2376}
2377
2378/// CopyToExportRegsIfNeeded - If the given value has virtual registers
2379/// created for it, emit nodes to copy the value into the virtual
2380/// registers.
2381void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2382 // Skip empty types
2383 if (V->getType()->isEmptyTy())
2384 return;
2385
2386 auto VMI = FuncInfo.ValueMap.find(Val: V);
2387 if (VMI != FuncInfo.ValueMap.end()) {
2388 assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2389 "Unused value assigned virtual registers!");
2390 CopyValueToVirtualRegister(V, Reg: VMI->second);
2391 }
2392}
2393
2394/// ExportFromCurrentBlock - If this condition isn't known to be exported from
2395/// the current basic block, add it to ValueMap now so that we'll get a
2396/// CopyTo/FromReg.
2397void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2398 // No need to export constants.
2399 if (!isa<Instruction>(Val: V) && !isa<Argument>(Val: V)) return;
2400
2401 // Already exported?
2402 if (FuncInfo.isExportedInst(V)) return;
2403
2404 Register Reg = FuncInfo.InitializeRegForValue(V);
2405 CopyValueToVirtualRegister(V, Reg);
2406}
2407
2408bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2409 const BasicBlock *FromBB) {
2410 // The operands of the setcc have to be in this block. We don't know
2411 // how to export them from some other block.
2412 if (const Instruction *VI = dyn_cast<Instruction>(Val: V)) {
2413 // Can export from current BB.
2414 if (VI->getParent() == FromBB)
2415 return true;
2416
2417 // Is already exported, noop.
2418 return FuncInfo.isExportedInst(V);
2419 }
2420
2421 // If this is an argument, we can export it if the BB is the entry block or
2422 // if it is already exported.
2423 if (isa<Argument>(Val: V)) {
2424 if (FromBB->isEntryBlock())
2425 return true;
2426
2427 // Otherwise, can only export this if it is already exported.
2428 return FuncInfo.isExportedInst(V);
2429 }
2430
2431 // Otherwise, constants can always be exported.
2432 return true;
2433}
2434
2435/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2436BranchProbability
2437SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2438 const MachineBasicBlock *Dst) const {
2439 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2440 const BasicBlock *SrcBB = Src->getBasicBlock();
2441 const BasicBlock *DstBB = Dst->getBasicBlock();
2442 if (!BPI) {
2443 // If BPI is not available, set the default probability as 1 / N, where N is
2444 // the number of successors.
2445 auto SuccSize = std::max<uint32_t>(a: succ_size(BB: SrcBB), b: 1);
2446 return BranchProbability(1, SuccSize);
2447 }
2448 return BPI->getEdgeProbability(Src: SrcBB, Dst: DstBB);
2449}
2450
2451void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2452 MachineBasicBlock *Dst,
2453 BranchProbability Prob) {
2454 if (!FuncInfo.BPI)
2455 Src->addSuccessorWithoutProb(Succ: Dst);
2456 else {
2457 if (Prob.isUnknown())
2458 Prob = getEdgeProbability(Src, Dst);
2459 Src->addSuccessor(Succ: Dst, Prob);
2460 }
2461}
2462
2463static bool InBlock(const Value *V, const BasicBlock *BB) {
2464 if (const Instruction *I = dyn_cast<Instruction>(Val: V))
2465 return I->getParent() == BB;
2466 return true;
2467}
2468
2469/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2470/// This function emits a branch and is used at the leaves of an OR or an
2471/// AND operator tree.
2472void
2473SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2474 MachineBasicBlock *TBB,
2475 MachineBasicBlock *FBB,
2476 MachineBasicBlock *CurBB,
2477 MachineBasicBlock *SwitchBB,
2478 BranchProbability TProb,
2479 BranchProbability FProb,
2480 bool InvertCond) {
2481 const BasicBlock *BB = CurBB->getBasicBlock();
2482
2483 // If the leaf of the tree is a comparison, merge the condition into
2484 // the caseblock.
2485 if (const CmpInst *BOp = dyn_cast<CmpInst>(Val: Cond)) {
2486 // The operands of the cmp have to be in this block. We don't know
2487 // how to export them from some other block. If this is the first block
2488 // of the sequence, no exporting is needed.
2489 if (CurBB == SwitchBB ||
2490 (isExportableFromCurrentBlock(V: BOp->getOperand(i_nocapture: 0), FromBB: BB) &&
2491 isExportableFromCurrentBlock(V: BOp->getOperand(i_nocapture: 1), FromBB: BB))) {
2492 ISD::CondCode Condition;
2493 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Val: Cond)) {
2494 ICmpInst::Predicate Pred =
2495 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2496 Condition = getICmpCondCode(Pred);
2497 } else {
2498 const FCmpInst *FC = cast<FCmpInst>(Val: Cond);
2499 FCmpInst::Predicate Pred =
2500 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2501 Condition = getFCmpCondCode(Pred);
2502 if (FC->hasNoNaNs() ||
2503 (isKnownNeverNaN(V: FC->getOperand(i_nocapture: 0),
2504 SQ: SimplifyQuery(DAG.getDataLayout(), FC)) &&
2505 isKnownNeverNaN(V: FC->getOperand(i_nocapture: 1),
2506 SQ: SimplifyQuery(DAG.getDataLayout(), FC))))
2507 Condition = getFCmpCodeWithoutNaN(CC: Condition);
2508 }
2509
2510 CaseBlock CB(Condition, BOp->getOperand(i_nocapture: 0), BOp->getOperand(i_nocapture: 1), nullptr,
2511 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2512 SL->SwitchCases.push_back(x: CB);
2513 return;
2514 }
2515 }
2516
2517 // Create a CaseBlock record representing this branch.
2518 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2519 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(Context&: *DAG.getContext()),
2520 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2521 SL->SwitchCases.push_back(x: CB);
2522}
2523
2524// Collect dependencies on V recursively. This is used for the cost analysis in
2525// `shouldKeepJumpConditionsTogether`.
2526static bool collectInstructionDeps(
2527 SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2528 SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2529 unsigned Depth = 0) {
2530 // Return false if we have an incomplete count.
2531 if (Depth >= SelectionDAG::MaxRecursionDepth)
2532 return false;
2533
2534 auto *I = dyn_cast<Instruction>(Val: V);
2535 if (I == nullptr)
2536 return true;
2537
2538 if (Necessary != nullptr) {
2539 // This instruction is necessary for the other side of the condition so
2540 // don't count it.
2541 if (Necessary->contains(Key: I))
2542 return true;
2543 }
2544
2545 // Already added this dep.
2546 if (!Deps->try_emplace(Key: I, Args: false).second)
2547 return true;
2548
2549 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2550 if (!collectInstructionDeps(Deps, V: I->getOperand(i: OpIdx), Necessary,
2551 Depth: Depth + 1))
2552 return false;
2553 return true;
2554}
2555
2556bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2557 const FunctionLoweringInfo &FuncInfo, const CondBrInst &I,
2558 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2559 TargetLoweringBase::CondMergingParams Params) const {
2560 if (Params.BaseCost < 0)
2561 return false;
2562
2563 // Baseline cost.
2564 InstructionCost CostThresh = Params.BaseCost;
2565
2566 BranchProbabilityInfo *BPI = nullptr;
2567 if (Params.LikelyBias || Params.UnlikelyBias)
2568 BPI = FuncInfo.BPI;
2569 if (BPI != nullptr) {
2570 // See if we are either likely to get an early out or compute both lhs/rhs
2571 // of the condition.
2572 BasicBlock *IfFalse = I.getSuccessor(i: 0);
2573 BasicBlock *IfTrue = I.getSuccessor(i: 1);
2574
2575 std::optional<bool> Likely;
2576 if (BPI->isEdgeHot(Src: I.getParent(), Dst: IfTrue))
2577 Likely = true;
2578 else if (BPI->isEdgeHot(Src: I.getParent(), Dst: IfFalse))
2579 Likely = false;
2580
2581 if (Likely) {
2582 if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2583 // Its likely we will have to compute both lhs and rhs of condition
2584 CostThresh += Params.LikelyBias;
2585 else {
2586 if (Params.UnlikelyBias < 0)
2587 return false;
2588 // Its likely we will get an early out.
2589 CostThresh -= Params.UnlikelyBias;
2590 }
2591 }
2592 }
2593
2594 if (CostThresh <= 0)
2595 return false;
2596
2597 // Collect "all" instructions that lhs condition is dependent on.
2598 // Use map for stable iteration (to avoid non-determanism of iteration of
2599 // SmallPtrSet). The `bool` value is just a dummy.
2600 SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2601 collectInstructionDeps(Deps: &LhsDeps, V: Lhs);
2602 // Collect "all" instructions that rhs condition is dependent on AND are
2603 // dependencies of lhs. This gives us an estimate on which instructions we
2604 // stand to save by splitting the condition.
2605 if (!collectInstructionDeps(Deps: &RhsDeps, V: Rhs, Necessary: &LhsDeps))
2606 return false;
2607 // Add the compare instruction itself unless its a dependency on the LHS.
2608 if (const auto *RhsI = dyn_cast<Instruction>(Val: Rhs))
2609 if (!LhsDeps.contains(Key: RhsI))
2610 RhsDeps.try_emplace(Key: RhsI, Args: false);
2611
2612 InstructionCost CostOfIncluding = 0;
2613 // See if this instruction will need to computed independently of whether RHS
2614 // is.
2615 Value *BrCond = I.getCondition();
2616 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2617 for (const auto *U : Ins->users()) {
2618 // If user is independent of RHS calculation we don't need to count it.
2619 if (auto *UIns = dyn_cast<Instruction>(Val: U))
2620 if (UIns != BrCond && !RhsDeps.contains(Key: UIns))
2621 return false;
2622 }
2623 return true;
2624 };
2625
2626 // Prune instructions from RHS Deps that are dependencies of unrelated
2627 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2628 // arbitrary and just meant to cap the how much time we spend in the pruning
2629 // loop. Its highly unlikely to come into affect.
2630 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2631 // Stop after a certain point. No incorrectness from including too many
2632 // instructions.
2633 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2634 const Instruction *ToDrop = nullptr;
2635 for (const auto &InsPair : RhsDeps) {
2636 if (!ShouldCountInsn(InsPair.first)) {
2637 ToDrop = InsPair.first;
2638 break;
2639 }
2640 }
2641 if (ToDrop == nullptr)
2642 break;
2643 RhsDeps.erase(Key: ToDrop);
2644 }
2645
2646 for (const auto &InsPair : RhsDeps) {
2647 // Finally accumulate latency that we can only attribute to computing the
2648 // RHS condition. Use latency because we are essentially trying to calculate
2649 // the cost of the dependency chain.
2650 // Possible TODO: We could try to estimate ILP and make this more precise.
2651 CostOfIncluding += TTI->getInstructionCost(
2652 U: InsPair.first, CostKind: TargetTransformInfo::TCK_Latency);
2653
2654 if (CostOfIncluding > CostThresh)
2655 return false;
2656 }
2657 return true;
2658}
2659
2660void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2661 MachineBasicBlock *TBB,
2662 MachineBasicBlock *FBB,
2663 MachineBasicBlock *CurBB,
2664 MachineBasicBlock *SwitchBB,
2665 Instruction::BinaryOps Opc,
2666 BranchProbability TProb,
2667 BranchProbability FProb,
2668 bool InvertCond) {
2669 // Skip over not part of the tree and remember to invert op and operands at
2670 // next level.
2671 Value *NotCond;
2672 if (match(V: Cond, P: m_OneUse(SubPattern: m_Not(V: m_Value(V&: NotCond)))) &&
2673 InBlock(V: NotCond, BB: CurBB->getBasicBlock())) {
2674 FindMergedConditions(Cond: NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2675 InvertCond: !InvertCond);
2676 return;
2677 }
2678
2679 const Instruction *BOp = dyn_cast<Instruction>(Val: Cond);
2680 const Value *BOpOp0, *BOpOp1;
2681 // Compute the effective opcode for Cond, taking into account whether it needs
2682 // to be inverted, e.g.
2683 // and (not (or A, B)), C
2684 // gets lowered as
2685 // and (and (not A, not B), C)
2686 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2687 if (BOp) {
2688 BOpc = match(V: BOp, P: m_LogicalAnd(L: m_Value(V&: BOpOp0), R: m_Value(V&: BOpOp1)))
2689 ? Instruction::And
2690 : (match(V: BOp, P: m_LogicalOr(L: m_Value(V&: BOpOp0), R: m_Value(V&: BOpOp1)))
2691 ? Instruction::Or
2692 : (Instruction::BinaryOps)0);
2693 if (InvertCond) {
2694 if (BOpc == Instruction::And)
2695 BOpc = Instruction::Or;
2696 else if (BOpc == Instruction::Or)
2697 BOpc = Instruction::And;
2698 }
2699 }
2700
2701 // If this node is not part of the or/and tree, emit it as a branch.
2702 // Note that all nodes in the tree should have same opcode.
2703 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2704 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2705 !InBlock(V: BOpOp0, BB: CurBB->getBasicBlock()) ||
2706 !InBlock(V: BOpOp1, BB: CurBB->getBasicBlock())) {
2707 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2708 TProb, FProb, InvertCond);
2709 return;
2710 }
2711
2712 // Create TmpBB after CurBB.
2713 MachineFunction::iterator BBI(CurBB);
2714 MachineFunction &MF = DAG.getMachineFunction();
2715 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(BB: CurBB->getBasicBlock());
2716 CurBB->getParent()->insert(MBBI: ++BBI, MBB: TmpBB);
2717
2718 if (Opc == Instruction::Or) {
2719 // Codegen X | Y as:
2720 // BB1:
2721 // jmp_if_X TBB
2722 // jmp TmpBB
2723 // TmpBB:
2724 // jmp_if_Y TBB
2725 // jmp FBB
2726 //
2727
2728 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2729 // The requirement is that
2730 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2731 // = TrueProb for original BB.
2732 // Assuming the original probabilities are A and B, one choice is to set
2733 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2734 // A/(1+B) and 2B/(1+B). This choice assumes that
2735 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2736 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2737 // TmpBB, but the math is more complicated.
2738
2739 auto NewTrueProb = TProb / 2;
2740 auto NewFalseProb = TProb / 2 + FProb;
2741 // Emit the LHS condition.
2742 FindMergedConditions(Cond: BOpOp0, TBB, FBB: TmpBB, CurBB, SwitchBB, Opc, TProb: NewTrueProb,
2743 FProb: NewFalseProb, InvertCond);
2744
2745 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2746 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2747 BranchProbability::normalizeProbabilities(Begin: Probs.begin(), End: Probs.end());
2748 // Emit the RHS condition into TmpBB.
2749 FindMergedConditions(Cond: BOpOp1, TBB, FBB, CurBB: TmpBB, SwitchBB, Opc, TProb: Probs[0],
2750 FProb: Probs[1], InvertCond);
2751 } else {
2752 assert(Opc == Instruction::And && "Unknown merge op!");
2753 // Codegen X & Y as:
2754 // BB1:
2755 // jmp_if_X TmpBB
2756 // jmp FBB
2757 // TmpBB:
2758 // jmp_if_Y TBB
2759 // jmp FBB
2760 //
2761 // This requires creation of TmpBB after CurBB.
2762
2763 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2764 // The requirement is that
2765 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2766 // = FalseProb for original BB.
2767 // Assuming the original probabilities are A and B, one choice is to set
2768 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2769 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2770 // TrueProb for BB1 * FalseProb for TmpBB.
2771
2772 auto NewTrueProb = TProb + FProb / 2;
2773 auto NewFalseProb = FProb / 2;
2774 // Emit the LHS condition.
2775 FindMergedConditions(Cond: BOpOp0, TBB: TmpBB, FBB, CurBB, SwitchBB, Opc, TProb: NewTrueProb,
2776 FProb: NewFalseProb, InvertCond);
2777
2778 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2779 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2780 BranchProbability::normalizeProbabilities(Begin: Probs.begin(), End: Probs.end());
2781 // Emit the RHS condition into TmpBB.
2782 FindMergedConditions(Cond: BOpOp1, TBB, FBB, CurBB: TmpBB, SwitchBB, Opc, TProb: Probs[0],
2783 FProb: Probs[1], InvertCond);
2784 }
2785}
2786
2787/// If the set of cases should be emitted as a series of branches, return true.
2788/// If we should emit this as a bunch of and/or'd together conditions, return
2789/// false.
2790bool
2791SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2792 if (Cases.size() != 2) return true;
2793
2794 // If this is two comparisons of the same values or'd or and'd together, they
2795 // will get folded into a single comparison, so don't emit two blocks.
2796 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2797 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2798 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2799 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2800 return false;
2801 }
2802
2803 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2804 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2805 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2806 Cases[0].CC == Cases[1].CC &&
2807 isa<Constant>(Val: Cases[0].CmpRHS) &&
2808 cast<Constant>(Val: Cases[0].CmpRHS)->isNullValue()) {
2809 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2810 return false;
2811 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2812 return false;
2813 }
2814
2815 return true;
2816}
2817
2818void SelectionDAGBuilder::visitUncondBr(const UncondBrInst &I) {
2819 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2820
2821 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(BB: I.getSuccessor(i: 0));
2822
2823 // Update machine-CFG edges.
2824 BrMBB->addSuccessor(Succ: Succ0MBB);
2825
2826 // If this is not a fall-through branch or optimizations are switched off,
2827 // emit the branch.
2828 if (Succ0MBB != NextBlock(MBB: BrMBB) ||
2829 TM.getOptLevel() == CodeGenOptLevel::None) {
2830 auto Br = DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other, N1: getControlRoot(),
2831 N2: DAG.getBasicBlock(MBB: Succ0MBB));
2832 setValue(V: &I, NewN: Br);
2833 DAG.setRoot(Br);
2834 }
2835}
2836
2837void SelectionDAGBuilder::visitCondBr(const CondBrInst &I) {
2838 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2839
2840 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(BB: I.getSuccessor(i: 0));
2841
2842 // If this condition is one of the special cases we handle, do special stuff
2843 // now.
2844 const Value *CondVal = I.getCondition();
2845 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(BB: I.getSuccessor(i: 1));
2846
2847 // If this is a series of conditions that are or'd or and'd together, emit
2848 // this as a sequence of branches instead of setcc's with and/or operations.
2849 // As long as jumps are not expensive (exceptions for multi-use logic ops,
2850 // unpredictable branches, and vector extracts because those jumps are likely
2851 // expensive for any target), this should improve performance.
2852 // For example, instead of something like:
2853 // cmp A, B
2854 // C = seteq
2855 // cmp D, E
2856 // F = setle
2857 // or C, F
2858 // jnz foo
2859 // Emit:
2860 // cmp A, B
2861 // je foo
2862 // cmp D, E
2863 // jle foo
2864 bool IsUnpredictable = I.hasMetadata(KindID: LLVMContext::MD_unpredictable);
2865 const Instruction *BOp = dyn_cast<Instruction>(Val: CondVal);
2866 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2867 BOp->hasOneUse() && !IsUnpredictable) {
2868 Value *Vec;
2869 const Value *BOp0, *BOp1;
2870 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2871 if (match(V: BOp, P: m_LogicalAnd(L: m_Value(V&: BOp0), R: m_Value(V&: BOp1))))
2872 Opcode = Instruction::And;
2873 else if (match(V: BOp, P: m_LogicalOr(L: m_Value(V&: BOp0), R: m_Value(V&: BOp1))))
2874 Opcode = Instruction::Or;
2875
2876 if (Opcode &&
2877 !(match(V: BOp0, P: m_ExtractElt(Val: m_Value(V&: Vec), Idx: m_Value())) &&
2878 match(V: BOp1, P: m_ExtractElt(Val: m_Specific(V: Vec), Idx: m_Value()))) &&
2879 !shouldKeepJumpConditionsTogether(
2880 FuncInfo, I, Opc: Opcode, Lhs: BOp0, Rhs: BOp1,
2881 Params: DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2882 Opcode, BOp0, BOp1, FuncInfo.Fn))) {
2883 FindMergedConditions(Cond: BOp, TBB: Succ0MBB, FBB: Succ1MBB, CurBB: BrMBB, SwitchBB: BrMBB, Opc: Opcode,
2884 TProb: getEdgeProbability(Src: BrMBB, Dst: Succ0MBB),
2885 FProb: getEdgeProbability(Src: BrMBB, Dst: Succ1MBB),
2886 /*InvertCond=*/false);
2887 // If the compares in later blocks need to use values not currently
2888 // exported from this block, export them now. This block should always
2889 // be the first entry.
2890 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2891
2892 // Allow some cases to be rejected.
2893 if (ShouldEmitAsBranches(Cases: SL->SwitchCases)) {
2894 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2895 ExportFromCurrentBlock(V: SL->SwitchCases[i].CmpLHS);
2896 ExportFromCurrentBlock(V: SL->SwitchCases[i].CmpRHS);
2897 }
2898
2899 // Emit the branch for this block.
2900 visitSwitchCase(CB&: SL->SwitchCases[0], SwitchBB: BrMBB);
2901 SL->SwitchCases.erase(position: SL->SwitchCases.begin());
2902 return;
2903 }
2904
2905 // Okay, we decided not to do this, remove any inserted MBB's and clear
2906 // SwitchCases.
2907 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2908 FuncInfo.MF->erase(MBBI: SL->SwitchCases[i].ThisBB);
2909
2910 SL->SwitchCases.clear();
2911 }
2912 }
2913
2914 // Create a CaseBlock record representing this branch.
2915 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(Context&: *DAG.getContext()),
2916 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2917 BranchProbability::getUnknown(), BranchProbability::getUnknown(),
2918 IsUnpredictable);
2919
2920 // Use visitSwitchCase to actually insert the fast branch sequence for this
2921 // cond branch.
2922 visitSwitchCase(CB, SwitchBB: BrMBB);
2923}
2924
2925/// visitSwitchCase - Emits the necessary code to represent a single node in
2926/// the binary search tree resulting from lowering a switch instruction.
2927void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2928 MachineBasicBlock *SwitchBB) {
2929 SDValue Cond;
2930 SDValue CondLHS = getValue(V: CB.CmpLHS);
2931 SDLoc dl = CB.DL;
2932
2933 if (CB.CC == ISD::SETTRUE) {
2934 // Branch or fall through to TrueBB.
2935 addSuccessorWithProb(Src: SwitchBB, Dst: CB.TrueBB, Prob: CB.TrueProb);
2936 SwitchBB->normalizeSuccProbs();
2937 if (CB.TrueBB != NextBlock(MBB: SwitchBB)) {
2938 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: getControlRoot(),
2939 N2: DAG.getBasicBlock(MBB: CB.TrueBB)));
2940 }
2941 return;
2942 }
2943
2944 auto &TLI = DAG.getTargetLoweringInfo();
2945 EVT MemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: CB.CmpLHS->getType());
2946
2947 // Build the setcc now.
2948 if (!CB.CmpMHS) {
2949 // Fold "(X == true)" to X and "(X == false)" to !X to
2950 // handle common cases produced by branch lowering.
2951 if (CB.CmpRHS == ConstantInt::getTrue(Context&: *DAG.getContext()) &&
2952 CB.CC == ISD::SETEQ)
2953 Cond = CondLHS;
2954 else if (CB.CmpRHS == ConstantInt::getFalse(Context&: *DAG.getContext()) &&
2955 CB.CC == ISD::SETEQ) {
2956 SDValue True = DAG.getConstant(Val: 1, DL: dl, VT: CondLHS.getValueType());
2957 Cond = DAG.getNode(Opcode: ISD::XOR, DL: dl, VT: CondLHS.getValueType(), N1: CondLHS, N2: True);
2958 } else {
2959 SDValue CondRHS = getValue(V: CB.CmpRHS);
2960
2961 // If a pointer's DAG type is larger than its memory type then the DAG
2962 // values are zero-extended. This breaks signed comparisons so truncate
2963 // back to the underlying type before doing the compare.
2964 if (CondLHS.getValueType() != MemVT) {
2965 CondLHS = DAG.getPtrExtOrTrunc(Op: CondLHS, DL: getCurSDLoc(), VT: MemVT);
2966 CondRHS = DAG.getPtrExtOrTrunc(Op: CondRHS, DL: getCurSDLoc(), VT: MemVT);
2967 }
2968 Cond = DAG.getSetCC(DL: dl, VT: MVT::i1, LHS: CondLHS, RHS: CondRHS, Cond: CB.CC);
2969 }
2970 } else {
2971 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2972
2973 const APInt& Low = cast<ConstantInt>(Val: CB.CmpLHS)->getValue();
2974 const APInt& High = cast<ConstantInt>(Val: CB.CmpRHS)->getValue();
2975
2976 SDValue CmpOp = getValue(V: CB.CmpMHS);
2977 EVT VT = CmpOp.getValueType();
2978
2979 if (cast<ConstantInt>(Val: CB.CmpLHS)->isMinValue(IsSigned: true)) {
2980 Cond = DAG.getSetCC(DL: dl, VT: MVT::i1, LHS: CmpOp, RHS: DAG.getConstant(Val: High, DL: dl, VT),
2981 Cond: ISD::SETLE);
2982 } else {
2983 SDValue SUB = DAG.getNode(Opcode: ISD::SUB, DL: dl,
2984 VT, N1: CmpOp, N2: DAG.getConstant(Val: Low, DL: dl, VT));
2985 Cond = DAG.getSetCC(DL: dl, VT: MVT::i1, LHS: SUB,
2986 RHS: DAG.getConstant(Val: High-Low, DL: dl, VT), Cond: ISD::SETULE);
2987 }
2988 }
2989
2990 // Update successor info
2991 addSuccessorWithProb(Src: SwitchBB, Dst: CB.TrueBB, Prob: CB.TrueProb);
2992 // TrueBB and FalseBB are always different unless the incoming IR is
2993 // degenerate. This only happens when running llc on weird IR.
2994 if (CB.TrueBB != CB.FalseBB)
2995 addSuccessorWithProb(Src: SwitchBB, Dst: CB.FalseBB, Prob: CB.FalseProb);
2996 SwitchBB->normalizeSuccProbs();
2997
2998 // If the lhs block is the next block, invert the condition so that we can
2999 // fall through to the lhs instead of the rhs block.
3000 if (CB.TrueBB == NextBlock(MBB: SwitchBB)) {
3001 std::swap(a&: CB.TrueBB, b&: CB.FalseBB);
3002 SDValue True = DAG.getConstant(Val: 1, DL: dl, VT: Cond.getValueType());
3003 Cond = DAG.getNode(Opcode: ISD::XOR, DL: dl, VT: Cond.getValueType(), N1: Cond, N2: True);
3004 }
3005
3006 SDNodeFlags Flags;
3007 Flags.setUnpredictable(CB.IsUnpredictable);
3008 SDValue BrCond = DAG.getNode(Opcode: ISD::BRCOND, DL: dl, VT: MVT::Other, N1: getControlRoot(),
3009 N2: Cond, N3: DAG.getBasicBlock(MBB: CB.TrueBB), Flags);
3010
3011 setValue(V: CurInst, NewN: BrCond);
3012
3013 // Insert the false branch. Do this even if it's a fall through branch,
3014 // this makes it easier to do DAG optimizations which require inverting
3015 // the branch condition.
3016 BrCond = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: BrCond,
3017 N2: DAG.getBasicBlock(MBB: CB.FalseBB));
3018
3019 DAG.setRoot(BrCond);
3020}
3021
3022/// visitJumpTable - Emit JumpTable node in the current MBB
3023void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
3024 // Emit the code for the jump table
3025 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3026 assert(JT.Reg && "Should lower JT Header first!");
3027 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DL: DAG.getDataLayout());
3028 SDValue Index = DAG.getCopyFromReg(Chain: getControlRoot(), dl: *JT.SL, Reg: JT.Reg, VT: PTy);
3029 SDValue Table = DAG.getJumpTable(JTI: JT.JTI, VT: PTy);
3030 SDValue BrJumpTable = DAG.getNode(Opcode: ISD::BR_JT, DL: *JT.SL, VT: MVT::Other,
3031 N1: Index.getValue(R: 1), N2: Table, N3: Index);
3032 DAG.setRoot(BrJumpTable);
3033}
3034
3035/// visitJumpTableHeader - This function emits necessary code to produce index
3036/// in the JumpTable from switch case.
3037void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
3038 JumpTableHeader &JTH,
3039 MachineBasicBlock *SwitchBB) {
3040 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3041 const SDLoc &dl = *JT.SL;
3042
3043 // Subtract the lowest switch case value from the value being switched on.
3044 SDValue SwitchOp = getValue(V: JTH.SValue);
3045 EVT VT = SwitchOp.getValueType();
3046 SDValue Sub = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: SwitchOp,
3047 N2: DAG.getConstant(Val: JTH.First, DL: dl, VT));
3048
3049 // The SDNode we just created, which holds the value being switched on minus
3050 // the smallest case value, needs to be copied to a virtual register so it
3051 // can be used as an index into the jump table in a subsequent basic block.
3052 // This value may be smaller or larger than the target's pointer type, and
3053 // therefore require extension or truncating.
3054 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3055 SwitchOp =
3056 DAG.getZExtOrTrunc(Op: Sub, DL: dl, VT: TLI.getJumpTableRegTy(DL: DAG.getDataLayout()));
3057
3058 Register JumpTableReg =
3059 FuncInfo.CreateReg(VT: TLI.getJumpTableRegTy(DL: DAG.getDataLayout()));
3060 SDValue CopyTo =
3061 DAG.getCopyToReg(Chain: getControlRoot(), dl, Reg: JumpTableReg, N: SwitchOp);
3062 JT.Reg = JumpTableReg;
3063
3064 if (!JTH.FallthroughUnreachable) {
3065 // Emit the range check for the jump table, and branch to the default block
3066 // for the switch statement if the value being switched on exceeds the
3067 // largest case in the switch.
3068 SDValue CMP = DAG.getSetCC(
3069 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(),
3070 VT: Sub.getValueType()),
3071 LHS: Sub, RHS: DAG.getConstant(Val: JTH.Last - JTH.First, DL: dl, VT), Cond: ISD::SETUGT);
3072
3073 SDValue BrCond = DAG.getNode(Opcode: ISD::BRCOND, DL: dl,
3074 VT: MVT::Other, N1: CopyTo, N2: CMP,
3075 N3: DAG.getBasicBlock(MBB: JT.Default));
3076
3077 // Avoid emitting unnecessary branches to the next block.
3078 if (JT.MBB != NextBlock(MBB: SwitchBB))
3079 BrCond = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: BrCond,
3080 N2: DAG.getBasicBlock(MBB: JT.MBB));
3081
3082 DAG.setRoot(BrCond);
3083 } else {
3084 // Avoid emitting unnecessary branches to the next block.
3085 if (JT.MBB != NextBlock(MBB: SwitchBB))
3086 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: CopyTo,
3087 N2: DAG.getBasicBlock(MBB: JT.MBB)));
3088 else
3089 DAG.setRoot(CopyTo);
3090 }
3091}
3092
3093/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3094/// variable if there exists one.
3095static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3096 SDValue &Chain) {
3097 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3098 EVT PtrTy = TLI.getPointerTy(DL: DAG.getDataLayout());
3099 EVT PtrMemTy = TLI.getPointerMemTy(DL: DAG.getDataLayout());
3100 MachineFunction &MF = DAG.getMachineFunction();
3101 Value *Global =
3102 TLI.getSDagStackGuard(M: *MF.getFunction().getParent(), Libcalls: DAG.getLibcalls());
3103 MachineSDNode *Node =
3104 DAG.getMachineNode(Opcode: TargetOpcode::LOAD_STACK_GUARD, dl: DL, VT: PtrTy, Op1: Chain);
3105 if (Global) {
3106 MachinePointerInfo MPInfo(Global);
3107 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3108 MachineMemOperand::MODereferenceable;
3109 MachineMemOperand *MemRef = MF.getMachineMemOperand(
3110 PtrInfo: MPInfo, F: Flags, Size: PtrTy.getSizeInBits() / 8, BaseAlignment: DAG.getEVTAlign(MemoryVT: PtrTy));
3111 DAG.setNodeMemRefs(N: Node, NewMemRefs: {MemRef});
3112 }
3113 if (PtrTy != PtrMemTy)
3114 return DAG.getPtrExtOrTrunc(Op: SDValue(Node, 0), DL, VT: PtrMemTy);
3115 return SDValue(Node, 0);
3116}
3117
3118/// Codegen a new tail for a stack protector check ParentMBB which has had its
3119/// tail spliced into a stack protector check success bb.
3120///
3121/// For a high level explanation of how this fits into the stack protector
3122/// generation see the comment on the declaration of class
3123/// StackProtectorDescriptor.
3124void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3125 MachineBasicBlock *ParentBB) {
3126
3127 // First create the loads to the guard/stack slot for the comparison.
3128 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3129 auto &DL = DAG.getDataLayout();
3130 EVT PtrTy = TLI.getFrameIndexTy(DL);
3131 EVT PtrMemTy = TLI.getPointerMemTy(DL, AS: DL.getAllocaAddrSpace());
3132
3133 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3134 int FI = MFI.getStackProtectorIndex();
3135
3136 SDValue Guard;
3137 SDLoc dl = getCurSDLoc();
3138 SDValue StackSlotPtr = DAG.getFrameIndex(FI, VT: PtrTy);
3139 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3140 Align Align = DL.getPrefTypeAlign(
3141 Ty: PointerType::get(C&: M.getContext(), AddressSpace: DL.getAllocaAddrSpace()));
3142
3143 // Generate code to load the content of the guard slot.
3144 SDValue GuardVal = DAG.getLoad(
3145 VT: PtrMemTy, dl, Chain: DAG.getEntryNode(), Ptr: StackSlotPtr,
3146 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI), Alignment: Align,
3147 MMOFlags: MachineMemOperand::MOVolatile);
3148
3149 // If cookie mixing is enabled, unmix the stored GuardVal to get back the
3150 // original cookie for comparison. The prologue stored (FP - Cookie) or
3151 // (FP XOR Cookie), so we apply the same operation again to unmix:
3152 // FP - (FP - Cookie) = Cookie, or (FP XOR Cookie) XOR FP = Cookie.
3153 if (TLI.useStackGuardMixFP())
3154 GuardVal = TLI.emitStackGuardMixFP(DAG, Val: GuardVal, DL: dl);
3155
3156 // If we're using function-based instrumentation, call the guard check
3157 // function
3158 if (SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3159 // Get the guard check function from the target and verify it exists since
3160 // we're using function-based instrumentation
3161 const Function *GuardCheckFn =
3162 TLI.getSSPStackGuardCheck(M, Libcalls: DAG.getLibcalls());
3163 assert(GuardCheckFn && "Guard check function is null");
3164
3165 // The target provides a guard check function to validate the guard value.
3166 // Generate a call to that function with the content of the guard slot as
3167 // argument.
3168 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3169 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3170
3171 TargetLowering::ArgListTy Args;
3172 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(i: 0));
3173 if (GuardCheckFn->hasParamAttribute(ArgNo: 0, Kind: Attribute::AttrKind::InReg))
3174 Entry.IsInReg = true;
3175 Args.push_back(x: Entry);
3176
3177 TargetLowering::CallLoweringInfo CLI(DAG);
3178 CLI.setDebugLoc(getCurSDLoc())
3179 .setChain(DAG.getEntryNode())
3180 .setCallee(CC: GuardCheckFn->getCallingConv(), ResultType: FnTy->getReturnType(),
3181 Target: getValue(V: GuardCheckFn), ArgsList: std::move(Args));
3182
3183 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3184 DAG.setRoot(Result.second);
3185 return;
3186 }
3187
3188 // Load the fresh guard value for comparison.
3189 // For targets that mix the cookie in LOAD_STACK_GUARD expansion, we need to
3190 // load directly without using LOAD_STACK_GUARD to avoid unwanted mixing.
3191 SDValue Chain = DAG.getEntryNode();
3192 if (TLI.useStackGuardMixFP()) {
3193 // Mixing targets: load cookie directly to avoid mixing in LOAD_STACK_GUARD
3194 if (const Value *IRGuard = TLI.getSDagStackGuard(M, Libcalls: DAG.getLibcalls())) {
3195 SDValue GuardPtr = getValue(V: IRGuard);
3196 Guard = DAG.getLoad(VT: PtrMemTy, dl, Chain, Ptr: GuardPtr,
3197 PtrInfo: MachinePointerInfo(IRGuard, 0), Alignment: Align,
3198 MMOFlags: MachineMemOperand::MOVolatile);
3199 } else {
3200 LLVMContext &Ctx = *DAG.getContext();
3201 Ctx.diagnose(DI: DiagnosticInfoGeneric("unable to lower stackguard"));
3202 Guard = DAG.getPOISON(VT: PtrMemTy);
3203 }
3204 } else {
3205 // Non-mixing targets: use LOAD_STACK_GUARD or direct load as usual
3206 if (TLI.useLoadStackGuardNode(M)) {
3207 Guard = getLoadStackGuard(DAG, DL: dl, Chain);
3208 } else {
3209 if (const Value *IRGuard = TLI.getSDagStackGuard(M, Libcalls: DAG.getLibcalls())) {
3210 SDValue GuardPtr = getValue(V: IRGuard);
3211 Guard = DAG.getLoad(VT: PtrMemTy, dl, Chain, Ptr: GuardPtr,
3212 PtrInfo: MachinePointerInfo(IRGuard, 0), Alignment: Align,
3213 MMOFlags: MachineMemOperand::MOVolatile);
3214 } else {
3215 LLVMContext &Ctx = *DAG.getContext();
3216 Ctx.diagnose(DI: DiagnosticInfoGeneric("unable to lower stackguard"));
3217 Guard = DAG.getPOISON(VT: PtrMemTy);
3218 }
3219 }
3220 }
3221
3222 // Now both Guard (fresh cookie) and GuardVal (unmixed from stored value)
3223 // contain unmixed cookie values that can be compared directly.
3224
3225 // Perform the comparison via a getsetcc.
3226 SDValue Cmp = DAG.getSetCC(
3227 DL: dl, VT: TLI.getSetCCResultType(DL, Context&: *DAG.getContext(), VT: Guard.getValueType()),
3228 LHS: Guard, RHS: GuardVal, Cond: ISD::SETNE);
3229
3230 // If the guard/stackslot do not equal, branch to failure MBB.
3231 SDValue BrCond = DAG.getNode(Opcode: ISD::BRCOND, DL: dl, VT: MVT::Other, N1: getControlRoot(),
3232 N2: Cmp, N3: DAG.getBasicBlock(MBB: SPD.getFailureMBB()));
3233 // Otherwise branch to success MBB.
3234 SDValue Br = DAG.getNode(Opcode: ISD::BR, DL: dl,
3235 VT: MVT::Other, N1: BrCond,
3236 N2: DAG.getBasicBlock(MBB: SPD.getSuccessMBB()));
3237
3238 DAG.setRoot(Br);
3239}
3240
3241/// Codegen the failure basic block for a stack protector check.
3242///
3243/// A failure stack protector machine basic block consists simply of a call to
3244/// __stack_chk_fail().
3245///
3246/// For a high level explanation of how this fits into the stack protector
3247/// generation see the comment on the declaration of class
3248/// StackProtectorDescriptor.
3249void SelectionDAGBuilder::visitSPDescriptorFailure(
3250 StackProtectorDescriptor &SPD) {
3251
3252 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3253 MachineBasicBlock *ParentBB = SPD.getParentMBB();
3254 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3255 SDValue Chain;
3256
3257 // For -Oz builds with a guard check function, we use function-based
3258 // instrumentation. Otherwise, if we have a guard check function, we call it
3259 // in the failure block.
3260 auto *GuardCheckFn = TLI.getSSPStackGuardCheck(M, Libcalls: DAG.getLibcalls());
3261 if (GuardCheckFn && !SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3262 // First create the loads to the guard/stack slot for the comparison.
3263 auto &DL = DAG.getDataLayout();
3264 EVT PtrTy = TLI.getFrameIndexTy(DL);
3265 EVT PtrMemTy = TLI.getPointerMemTy(DL, AS: DL.getAllocaAddrSpace());
3266
3267 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3268 int FI = MFI.getStackProtectorIndex();
3269
3270 SDLoc dl = getCurSDLoc();
3271 SDValue StackSlotPtr = DAG.getFrameIndex(FI, VT: PtrTy);
3272 Align Align = DL.getPrefTypeAlign(
3273 Ty: PointerType::get(C&: M.getContext(), AddressSpace: DL.getAllocaAddrSpace()));
3274
3275 // Generate code to load the content of the guard slot.
3276 SDValue GuardVal = DAG.getLoad(
3277 VT: PtrMemTy, dl, Chain: DAG.getEntryNode(), Ptr: StackSlotPtr,
3278 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI), Alignment: Align,
3279 MMOFlags: MachineMemOperand::MOVolatile);
3280
3281 if (TLI.useStackGuardMixFP())
3282 GuardVal = TLI.emitStackGuardMixFP(DAG, Val: GuardVal, DL: dl);
3283
3284 // The target provides a guard check function to validate the guard value.
3285 // Generate a call to that function with the content of the guard slot as
3286 // argument.
3287 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3288 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3289
3290 TargetLowering::ArgListTy Args;
3291 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(i: 0));
3292 if (GuardCheckFn->hasParamAttribute(ArgNo: 0, Kind: Attribute::AttrKind::InReg))
3293 Entry.IsInReg = true;
3294 Args.push_back(x: Entry);
3295
3296 TargetLowering::CallLoweringInfo CLI(DAG);
3297 CLI.setDebugLoc(getCurSDLoc())
3298 .setChain(DAG.getEntryNode())
3299 .setCallee(CC: GuardCheckFn->getCallingConv(), ResultType: FnTy->getReturnType(),
3300 Target: getValue(V: GuardCheckFn), ArgsList: std::move(Args));
3301
3302 Chain = TLI.LowerCallTo(CLI).second;
3303 } else {
3304 TargetLowering::MakeLibCallOptions CallOptions;
3305 CallOptions.setDiscardResult(true);
3306 Chain = TLI.makeLibCall(DAG, LC: RTLIB::STACKPROTECTOR_CHECK_FAIL, RetVT: MVT::isVoid,
3307 Ops: {}, CallOptions, dl: getCurSDLoc())
3308 .second;
3309 }
3310
3311 // Emit a trap instruction if we are required to do so.
3312 const TargetOptions &TargetOpts = DAG.getTarget().Options;
3313 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3314 Chain = DAG.getNode(Opcode: ISD::TRAP, DL: getCurSDLoc(), VT: MVT::Other, Operand: Chain);
3315
3316 DAG.setRoot(Chain);
3317}
3318
3319/// visitBitTestHeader - This function emits necessary code to produce value
3320/// suitable for "bit tests"
3321void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3322 MachineBasicBlock *SwitchBB) {
3323 SDLoc dl = getCurSDLoc();
3324
3325 // Subtract the minimum value.
3326 SDValue SwitchOp = getValue(V: B.SValue);
3327 EVT VT = SwitchOp.getValueType();
3328 SDValue RangeSub =
3329 DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: SwitchOp, N2: DAG.getConstant(Val: B.First, DL: dl, VT));
3330
3331 // Determine the type of the test operands.
3332 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3333 bool UsePtrType = false;
3334 if (!TLI.isTypeLegal(VT)) {
3335 UsePtrType = true;
3336 } else {
3337 for (const BitTestCase &Case : B.Cases)
3338 if (!isUIntN(N: VT.getSizeInBits(), x: Case.Mask)) {
3339 // Switch table case range are encoded into series of masks.
3340 // Just use pointer type, it's guaranteed to fit.
3341 UsePtrType = true;
3342 break;
3343 }
3344 }
3345 SDValue Sub = RangeSub;
3346 if (UsePtrType) {
3347 VT = TLI.getPointerTy(DL: DAG.getDataLayout());
3348 Sub = DAG.getZExtOrTrunc(Op: Sub, DL: dl, VT);
3349 }
3350
3351 B.RegVT = VT.getSimpleVT();
3352 B.Reg = FuncInfo.CreateReg(VT: B.RegVT);
3353 SDValue CopyTo = DAG.getCopyToReg(Chain: getControlRoot(), dl, Reg: B.Reg, N: Sub);
3354
3355 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3356
3357 if (!B.FallthroughUnreachable)
3358 addSuccessorWithProb(Src: SwitchBB, Dst: B.Default, Prob: B.DefaultProb);
3359 addSuccessorWithProb(Src: SwitchBB, Dst: MBB, Prob: B.Prob);
3360 SwitchBB->normalizeSuccProbs();
3361
3362 SDValue Root = CopyTo;
3363 if (!B.FallthroughUnreachable) {
3364 // Conditional branch to the default block.
3365 SDValue RangeCmp = DAG.getSetCC(DL: dl,
3366 VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(),
3367 VT: RangeSub.getValueType()),
3368 LHS: RangeSub, RHS: DAG.getConstant(Val: B.Range, DL: dl, VT: RangeSub.getValueType()),
3369 Cond: ISD::SETUGT);
3370
3371 Root = DAG.getNode(Opcode: ISD::BRCOND, DL: dl, VT: MVT::Other, N1: Root, N2: RangeCmp,
3372 N3: DAG.getBasicBlock(MBB: B.Default));
3373 }
3374
3375 // Avoid emitting unnecessary branches to the next block.
3376 if (MBB != NextBlock(MBB: SwitchBB))
3377 Root = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: Root, N2: DAG.getBasicBlock(MBB));
3378
3379 DAG.setRoot(Root);
3380}
3381
3382/// visitBitTestCase - this function produces one "bit test"
3383void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3384 MachineBasicBlock *NextMBB,
3385 BranchProbability BranchProbToNext,
3386 Register Reg, BitTestCase &B,
3387 MachineBasicBlock *SwitchBB) {
3388 SDLoc dl = getCurSDLoc();
3389 MVT VT = BB.RegVT;
3390 SDValue ShiftOp = DAG.getCopyFromReg(Chain: getControlRoot(), dl, Reg, VT);
3391 SDValue Cmp;
3392 unsigned PopCount = llvm::popcount(Value: B.Mask);
3393 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3394 if (PopCount == 1) {
3395 // Testing for a single bit; just compare the shift count with what it
3396 // would need to be to shift a 1 bit in that position.
3397 Cmp = DAG.getSetCC(
3398 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(), VT),
3399 LHS: ShiftOp, RHS: DAG.getConstant(Val: llvm::countr_zero(Val: B.Mask), DL: dl, VT),
3400 Cond: ISD::SETEQ);
3401 } else if (PopCount == BB.Range) {
3402 // There is only one zero bit in the range, test for it directly.
3403 Cmp = DAG.getSetCC(
3404 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(), VT),
3405 LHS: ShiftOp, RHS: DAG.getConstant(Val: llvm::countr_one(Value: B.Mask), DL: dl, VT), Cond: ISD::SETNE);
3406 } else {
3407 // Make desired shift
3408 SDValue SwitchVal = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT,
3409 N1: DAG.getConstant(Val: 1, DL: dl, VT), N2: ShiftOp);
3410
3411 // Emit bit tests and jumps
3412 SDValue AndOp = DAG.getNode(Opcode: ISD::AND, DL: dl,
3413 VT, N1: SwitchVal, N2: DAG.getConstant(Val: B.Mask, DL: dl, VT));
3414 Cmp = DAG.getSetCC(
3415 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(), VT),
3416 LHS: AndOp, RHS: DAG.getConstant(Val: 0, DL: dl, VT), Cond: ISD::SETNE);
3417 }
3418
3419 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3420 addSuccessorWithProb(Src: SwitchBB, Dst: B.TargetBB, Prob: B.ExtraProb);
3421 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3422 addSuccessorWithProb(Src: SwitchBB, Dst: NextMBB, Prob: BranchProbToNext);
3423 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3424 // one as they are relative probabilities (and thus work more like weights),
3425 // and hence we need to normalize them to let the sum of them become one.
3426 SwitchBB->normalizeSuccProbs();
3427
3428 SDValue BrAnd = DAG.getNode(Opcode: ISD::BRCOND, DL: dl,
3429 VT: MVT::Other, N1: getControlRoot(),
3430 N2: Cmp, N3: DAG.getBasicBlock(MBB: B.TargetBB));
3431
3432 // Avoid emitting unnecessary branches to the next block.
3433 if (NextMBB != NextBlock(MBB: SwitchBB))
3434 BrAnd = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: BrAnd,
3435 N2: DAG.getBasicBlock(MBB: NextMBB));
3436
3437 DAG.setRoot(BrAnd);
3438}
3439
3440void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3441 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3442
3443 // Retrieve successors. Look through artificial IR level blocks like
3444 // catchswitch for successors.
3445 MachineBasicBlock *Return = FuncInfo.getMBB(BB: I.getSuccessor(i: 0));
3446 const BasicBlock *EHPadBB = I.getSuccessor(i: 1);
3447 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(BB: EHPadBB);
3448
3449 // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3450 // have to do anything here to lower funclet bundles.
3451 failForInvalidBundles(I, Name: "invokes",
3452 AllowedBundles: {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3453 LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3454 LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3455 LLVMContext::OB_clang_arc_attachedcall,
3456 LLVMContext::OB_kcfi});
3457
3458 const Value *Callee(I.getCalledOperand());
3459 const Function *Fn = dyn_cast<Function>(Val: Callee);
3460 if (isa<InlineAsm>(Val: Callee))
3461 visitInlineAsm(Call: I, EHPadBB);
3462 else if (Fn && Fn->isIntrinsic()) {
3463 switch (Fn->getIntrinsicID()) {
3464 default:
3465 llvm_unreachable("Cannot invoke this intrinsic");
3466 case Intrinsic::donothing:
3467 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3468 case Intrinsic::seh_try_begin:
3469 case Intrinsic::seh_scope_begin:
3470 case Intrinsic::seh_try_end:
3471 case Intrinsic::seh_scope_end:
3472 if (EHPadMBB)
3473 // a block referenced by EH table
3474 // so dtor-funclet not removed by opts
3475 EHPadMBB->setMachineBlockAddressTaken();
3476 break;
3477 case Intrinsic::experimental_patchpoint_void:
3478 case Intrinsic::experimental_patchpoint:
3479 visitPatchpoint(CB: I, EHPadBB);
3480 break;
3481 case Intrinsic::experimental_gc_statepoint:
3482 LowerStatepoint(I: cast<GCStatepointInst>(Val: I), EHPadBB);
3483 break;
3484 // wasm_throw, wasm_rethrow: This is usually done in visitTargetIntrinsic,
3485 // but these intrinsics are special because they can be invoked, so we
3486 // manually lower it to a DAG node here.
3487 case Intrinsic::wasm_throw: {
3488 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3489 std::array<SDValue, 4> Ops = {
3490 getControlRoot(), // inchain for the terminator node
3491 DAG.getTargetConstant(Val: Intrinsic::wasm_throw, DL: getCurSDLoc(),
3492 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
3493 getValue(V: I.getArgOperand(i: 0)), // tag
3494 getValue(V: I.getArgOperand(i: 1)) // thrown value
3495 };
3496 SDVTList VTs = DAG.getVTList(VTs: ArrayRef<EVT>({MVT::Other})); // outchain
3497 DAG.setRoot(DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL: getCurSDLoc(), VTList: VTs, Ops));
3498 break;
3499 }
3500 case Intrinsic::wasm_rethrow: {
3501 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3502 std::array<SDValue, 2> Ops = {
3503 getControlRoot(), // inchain for the terminator node
3504 DAG.getTargetConstant(Val: Intrinsic::wasm_rethrow, DL: getCurSDLoc(),
3505 VT: TLI.getPointerTy(DL: DAG.getDataLayout()))};
3506 SDVTList VTs = DAG.getVTList(VTs: ArrayRef<EVT>({MVT::Other})); // outchain
3507 DAG.setRoot(DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL: getCurSDLoc(), VTList: VTs, Ops));
3508 break;
3509 }
3510 }
3511 } else if (I.hasDeoptState()) {
3512 // Currently we do not lower any intrinsic calls with deopt operand bundles.
3513 // Eventually we will support lowering the @llvm.experimental.deoptimize
3514 // intrinsic, and right now there are no plans to support other intrinsics
3515 // with deopt state.
3516 LowerCallSiteWithDeoptBundle(Call: &I, Callee: getValue(V: Callee), EHPadBB);
3517 } else if (I.countOperandBundlesOfType(ID: LLVMContext::OB_ptrauth)) {
3518 LowerCallSiteWithPtrAuthBundle(CB: cast<CallBase>(Val: I), EHPadBB);
3519 } else {
3520 LowerCallTo(CB: I, Callee: getValue(V: Callee), IsTailCall: false, IsMustTailCall: false, EHPadBB);
3521 }
3522
3523 // If the value of the invoke is used outside of its defining block, make it
3524 // available as a virtual register.
3525 // We already took care of the exported value for the statepoint instruction
3526 // during call to the LowerStatepoint.
3527 if (!isa<GCStatepointInst>(Val: I)) {
3528 CopyToExportRegsIfNeeded(V: &I);
3529 }
3530
3531 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3532 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3533 BranchProbability EHPadBBProb =
3534 BPI ? BPI->getEdgeProbability(Src: InvokeMBB->getBasicBlock(), Dst: EHPadBB)
3535 : BranchProbability::getZero();
3536 findUnwindDestinations(FuncInfo, EHPadBB, Prob: EHPadBBProb, UnwindDests);
3537
3538 // Update successor info.
3539 addSuccessorWithProb(Src: InvokeMBB, Dst: Return);
3540 for (auto &UnwindDest : UnwindDests) {
3541 UnwindDest.first->setIsEHPad();
3542 addSuccessorWithProb(Src: InvokeMBB, Dst: UnwindDest.first, Prob: UnwindDest.second);
3543 }
3544 InvokeMBB->normalizeSuccProbs();
3545
3546 // Drop into normal successor.
3547 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other, N1: getControlRoot(),
3548 N2: DAG.getBasicBlock(MBB: Return)));
3549}
3550
3551/// The intrinsics currently supported by callbr are implicit control flow
3552/// intrinsics such as amdgcn.kill.
3553/// - they should be called (no "dontcall-" attributes)
3554/// - they do not touch memory on the target (= !TLI.getTgtMemIntrinsic())
3555/// - they do not need custom argument handling (no
3556/// TLI.CollectTargetIntrinsicOperands())
3557void SelectionDAGBuilder::visitCallBrIntrinsic(const CallBrInst &I) {
3558#ifndef NDEBUG
3559 SmallVector<TargetLowering::IntrinsicInfo, 2> Infos;
3560 DAG.getTargetLoweringInfo().getTgtMemIntrinsic(
3561 Infos, I, DAG.getMachineFunction(), I.getIntrinsicID());
3562 assert(Infos.empty() && "Intrinsic touches memory");
3563#endif
3564
3565 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
3566
3567 SmallVector<SDValue, 8> Ops =
3568 getTargetIntrinsicOperands(I, HasChain, OnlyLoad);
3569 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
3570
3571 // Create the node.
3572 SDValue Result =
3573 getTargetNonMemIntrinsicNode(IntrinsicVT: *I.getType(), HasChain, Ops, VTs);
3574 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
3575
3576 setValue(V: &I, NewN: Result);
3577}
3578
3579void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3580 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3581
3582 if (I.isInlineAsm()) {
3583 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3584 // have to do anything here to lower funclet bundles.
3585 failForInvalidBundles(I, Name: "callbrs",
3586 AllowedBundles: {LLVMContext::OB_deopt, LLVMContext::OB_funclet});
3587 visitInlineAsm(Call: I);
3588 } else {
3589 assert(!I.hasOperandBundles() &&
3590 "Can't have operand bundles for intrinsics");
3591 visitCallBrIntrinsic(I);
3592 }
3593 CopyToExportRegsIfNeeded(V: &I);
3594
3595 // Retrieve successors.
3596 SmallPtrSet<BasicBlock *, 8> Dests;
3597 Dests.insert(Ptr: I.getDefaultDest());
3598 MachineBasicBlock *Return = FuncInfo.getMBB(BB: I.getDefaultDest());
3599
3600 // Update successor info.
3601 addSuccessorWithProb(Src: CallBrMBB, Dst: Return, Prob: BranchProbability::getOne());
3602 // TODO: For most of the cases where there is an intrinsic callbr, we're
3603 // having exactly one indirect target, which will be unreachable. As soon as
3604 // this changes, we might need to enhance
3605 // Target->setIsInlineAsmBrIndirectTarget or add something similar for
3606 // intrinsic indirect branches.
3607 if (I.isInlineAsm()) {
3608 for (BasicBlock *Dest : I.getIndirectDests()) {
3609 MachineBasicBlock *Target = FuncInfo.getMBB(BB: Dest);
3610 Target->setIsInlineAsmBrIndirectTarget();
3611 // If we introduce a type of asm goto statement that is permitted to use
3612 // an indirect call instruction to jump to its labels, then we should add
3613 // a call to Target->setMachineBlockAddressTaken() here, to mark the
3614 // target block as requiring a BTI.
3615
3616 Target->setLabelMustBeEmitted();
3617 // Don't add duplicate machine successors.
3618 if (Dests.insert(Ptr: Dest).second)
3619 addSuccessorWithProb(Src: CallBrMBB, Dst: Target, Prob: BranchProbability::getZero());
3620 }
3621 }
3622 CallBrMBB->normalizeSuccProbs();
3623
3624 // Drop into default successor.
3625 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(),
3626 VT: MVT::Other, N1: getControlRoot(),
3627 N2: DAG.getBasicBlock(MBB: Return)));
3628}
3629
3630void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3631 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3632}
3633
3634void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3635 assert(FuncInfo.MBB->isEHPad() &&
3636 "Call to landingpad not in landing pad!");
3637
3638 // If there aren't registers to copy the values into (e.g., during SjLj
3639 // exceptions), then don't bother to create these DAG nodes.
3640 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3641 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3642 if (TLI.getExceptionPointerRegister(EH: FuncInfo.ExceptionModel, PersonalityFn) ==
3643 0 &&
3644 TLI.getExceptionSelectorRegister(EH: FuncInfo.ExceptionModel,
3645 PersonalityFn) == 0)
3646 return;
3647
3648 // If landingpad's return type is token type, we don't create DAG nodes
3649 // for its exception pointer and selector value. The extraction of exception
3650 // pointer or selector value from token type landingpads is not currently
3651 // supported.
3652 if (LP.getType()->isTokenTy())
3653 return;
3654
3655 SmallVector<EVT, 2> ValueVTs;
3656 SDLoc dl = getCurSDLoc();
3657 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: LP.getType(), ValueVTs);
3658 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3659
3660 // Get the two live-in registers as SDValues. The physregs have already been
3661 // copied into virtual registers.
3662 SDValue Ops[2];
3663 if (FuncInfo.ExceptionPointerVirtReg) {
3664 Ops[0] = DAG.getZExtOrTrunc(
3665 Op: DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl,
3666 Reg: FuncInfo.ExceptionPointerVirtReg,
3667 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
3668 DL: dl, VT: ValueVTs[0]);
3669 } else {
3670 Ops[0] = DAG.getConstant(Val: 0, DL: dl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
3671 }
3672 Ops[1] = DAG.getZExtOrTrunc(
3673 Op: DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl,
3674 Reg: FuncInfo.ExceptionSelectorVirtReg,
3675 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
3676 DL: dl, VT: ValueVTs[1]);
3677
3678 // Merge into one.
3679 SDValue Res = DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl,
3680 VTList: DAG.getVTList(VTs: ValueVTs), Ops);
3681 setValue(V: &LP, NewN: Res);
3682}
3683
3684void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3685 MachineBasicBlock *Last) {
3686 // Update JTCases.
3687 for (JumpTableBlock &JTB : SL->JTCases)
3688 if (JTB.first.HeaderBB == First)
3689 JTB.first.HeaderBB = Last;
3690
3691 // Update BitTestCases.
3692 for (BitTestBlock &BTB : SL->BitTestCases)
3693 if (BTB.Parent == First)
3694 BTB.Parent = Last;
3695}
3696
3697void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3698 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3699
3700 // Update machine-CFG edges with unique successors.
3701 SmallPtrSet<BasicBlock *, 32> Done;
3702 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3703 BasicBlock *BB = I.getSuccessor(i);
3704 bool Inserted = Done.insert(Ptr: BB).second;
3705 if (!Inserted)
3706 continue;
3707
3708 MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3709 addSuccessorWithProb(Src: IndirectBrMBB, Dst: Succ);
3710 }
3711 IndirectBrMBB->normalizeSuccProbs();
3712
3713 DAG.setRoot(DAG.getNode(Opcode: ISD::BRIND, DL: getCurSDLoc(),
3714 VT: MVT::Other, N1: getControlRoot(),
3715 N2: getValue(V: I.getAddress())));
3716}
3717
3718void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3719 if (!I.shouldLowerToTrap(TrapUnreachable: DAG.getTarget().Options.TrapUnreachable,
3720 NoTrapAfterNoreturn: DAG.getTarget().Options.NoTrapAfterNoreturn))
3721 return;
3722
3723 DAG.setRoot(DAG.getNode(Opcode: ISD::TRAP, DL: getCurSDLoc(), VT: MVT::Other, Operand: DAG.getRoot()));
3724}
3725
3726void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3727 SDNodeFlags Flags;
3728 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
3729 Flags.copyFMF(FPMO: *FPOp);
3730
3731 SDValue Op = getValue(V: I.getOperand(i: 0));
3732 SDValue UnNodeValue = DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Op.getValueType(),
3733 Operand: Op, Flags);
3734 setValue(V: &I, NewN: UnNodeValue);
3735}
3736
3737void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3738 SDNodeFlags Flags;
3739 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(Val: &I)) {
3740 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3741 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3742 }
3743 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(Val: &I))
3744 Flags.setExact(ExactOp->isExact());
3745 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(Val: &I))
3746 Flags.setDisjoint(DisjointOp->isDisjoint());
3747 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
3748 Flags.copyFMF(FPMO: *FPOp);
3749
3750 SDValue Op1 = getValue(V: I.getOperand(i: 0));
3751 SDValue Op2 = getValue(V: I.getOperand(i: 1));
3752 SDValue BinNodeValue = DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Op1.getValueType(),
3753 N1: Op1, N2: Op2, Flags);
3754 setValue(V: &I, NewN: BinNodeValue);
3755}
3756
3757void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3758 SDValue Op1 = getValue(V: I.getOperand(i: 0));
3759 SDValue Op2 = getValue(V: I.getOperand(i: 1));
3760
3761 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3762 LHSTy: Op1.getValueType(), DL: DAG.getDataLayout());
3763
3764 // Coerce the shift amount to the right type if we can. This exposes the
3765 // truncate or zext to optimization early.
3766 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3767 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3768 "Unexpected shift type");
3769 Op2 = DAG.getZExtOrTrunc(Op: Op2, DL: getCurSDLoc(), VT: ShiftTy);
3770 }
3771
3772 bool nuw = false;
3773 bool nsw = false;
3774 bool exact = false;
3775
3776 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3777
3778 if (const OverflowingBinaryOperator *OFBinOp =
3779 dyn_cast<const OverflowingBinaryOperator>(Val: &I)) {
3780 nuw = OFBinOp->hasNoUnsignedWrap();
3781 nsw = OFBinOp->hasNoSignedWrap();
3782 }
3783 if (const PossiblyExactOperator *ExactOp =
3784 dyn_cast<const PossiblyExactOperator>(Val: &I))
3785 exact = ExactOp->isExact();
3786 }
3787 SDNodeFlags Flags;
3788 Flags.setExact(exact);
3789 Flags.setNoSignedWrap(nsw);
3790 Flags.setNoUnsignedWrap(nuw);
3791 SDValue Res = DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Op1.getValueType(), N1: Op1, N2: Op2,
3792 Flags);
3793 setValue(V: &I, NewN: Res);
3794}
3795
3796void SelectionDAGBuilder::visitSDiv(const User &I) {
3797 SDValue Op1 = getValue(V: I.getOperand(i: 0));
3798 SDValue Op2 = getValue(V: I.getOperand(i: 1));
3799
3800 SDNodeFlags Flags;
3801 Flags.setExact(isa<PossiblyExactOperator>(Val: &I) &&
3802 cast<PossiblyExactOperator>(Val: &I)->isExact());
3803 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SDIV, DL: getCurSDLoc(), VT: Op1.getValueType(), N1: Op1,
3804 N2: Op2, Flags));
3805}
3806
3807void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3808 ICmpInst::Predicate predicate = I.getPredicate();
3809 SDValue Op1 = getValue(V: I.getOperand(i_nocapture: 0));
3810 SDValue Op2 = getValue(V: I.getOperand(i_nocapture: 1));
3811 ISD::CondCode Opcode = getICmpCondCode(Pred: predicate);
3812
3813 auto &TLI = DAG.getTargetLoweringInfo();
3814 EVT MemVT =
3815 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i_nocapture: 0)->getType());
3816
3817 // If a pointer's DAG type is larger than its memory type then the DAG values
3818 // are zero-extended. This breaks signed comparisons so truncate back to the
3819 // underlying type before doing the compare.
3820 if (Op1.getValueType() != MemVT) {
3821 Op1 = DAG.getPtrExtOrTrunc(Op: Op1, DL: getCurSDLoc(), VT: MemVT);
3822 Op2 = DAG.getPtrExtOrTrunc(Op: Op2, DL: getCurSDLoc(), VT: MemVT);
3823 }
3824
3825 SDNodeFlags Flags;
3826 Flags.setSameSign(I.hasSameSign());
3827
3828 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
3829 Ty: I.getType());
3830 setValue(V: &I, NewN: DAG.getSetCC(DL: getCurSDLoc(), VT: DestVT, LHS: Op1, RHS: Op2, Cond: Opcode,
3831 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3832}
3833
3834void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3835 FCmpInst::Predicate predicate = I.getPredicate();
3836 SDValue Op1 = getValue(V: I.getOperand(i_nocapture: 0));
3837 SDValue Op2 = getValue(V: I.getOperand(i_nocapture: 1));
3838
3839 ISD::CondCode Condition = getFCmpCondCode(Pred: predicate);
3840 auto *FPMO = cast<FPMathOperator>(Val: &I);
3841 if (FPMO->hasNoNaNs() ||
3842 (DAG.isKnownNeverNaN(Op: Op1) && DAG.isKnownNeverNaN(Op: Op2)))
3843 Condition = getFCmpCodeWithoutNaN(CC: Condition);
3844
3845 SDNodeFlags Flags;
3846 Flags.copyFMF(FPMO: *FPMO);
3847
3848 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
3849 Ty: I.getType());
3850 setValue(V: &I, NewN: DAG.getSetCC(DL: getCurSDLoc(), VT: DestVT, LHS: Op1, RHS: Op2, Cond: Condition,
3851 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3852}
3853
3854// Check if the condition of the select has one use or two users that are both
3855// selects with the same condition.
3856static bool hasOnlySelectUsers(const Value *Cond) {
3857 return llvm::all_of(Range: Cond->users(), P: [](const Value *V) {
3858 return isa<SelectInst>(Val: V);
3859 });
3860}
3861
3862void SelectionDAGBuilder::visitSelect(const User &I) {
3863 SmallVector<EVT, 4> ValueVTs;
3864 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty: I.getType(),
3865 ValueVTs);
3866 unsigned NumValues = ValueVTs.size();
3867 if (NumValues == 0) return;
3868
3869 SmallVector<SDValue, 4> Values(NumValues);
3870 SDValue Cond = getValue(V: I.getOperand(i: 0));
3871 SDValue LHSVal = getValue(V: I.getOperand(i: 1));
3872 SDValue RHSVal = getValue(V: I.getOperand(i: 2));
3873 SmallVector<SDValue, 1> BaseOps(1, Cond);
3874 ISD::NodeType OpCode =
3875 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3876
3877 bool IsUnaryAbs = false;
3878 bool Negate = false;
3879
3880 SDNodeFlags Flags;
3881 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
3882 Flags.copyFMF(FPMO: *FPOp);
3883
3884 Flags.setUnpredictable(
3885 cast<SelectInst>(Val: I).getMetadata(KindID: LLVMContext::MD_unpredictable));
3886
3887 // Min/max matching is only viable if all output VTs are the same.
3888 if (all_equal(Range&: ValueVTs)) {
3889 EVT VT = ValueVTs[0];
3890 LLVMContext &Ctx = *DAG.getContext();
3891 auto &TLI = DAG.getTargetLoweringInfo();
3892
3893 // We care about the legality of the operation after it has been type
3894 // legalized.
3895 while (TLI.getTypeAction(Context&: Ctx, VT) != TargetLoweringBase::TypeLegal)
3896 VT = TLI.getTypeToTransformTo(Context&: Ctx, VT);
3897
3898 // If the vselect is legal, assume we want to leave this as a vector setcc +
3899 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3900 // min/max is legal on the scalar type.
3901 bool UseScalarMinMax = VT.isVector() &&
3902 !TLI.isOperationLegalOrCustom(Op: ISD::VSELECT, VT);
3903
3904 // ValueTracking's select pattern matching does not account for -0.0,
3905 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3906 // -0.0 is less than +0.0.
3907 const Value *LHS, *RHS;
3908 auto SPR = matchSelectPattern(V: &I, LHS, RHS);
3909 ISD::NodeType Opc = ISD::DELETED_NODE;
3910 switch (SPR.Flavor) {
3911 case SPF_UMAX: Opc = ISD::UMAX; break;
3912 case SPF_UMIN: Opc = ISD::UMIN; break;
3913 case SPF_SMAX: Opc = ISD::SMAX; break;
3914 case SPF_SMIN: Opc = ISD::SMIN; break;
3915 case SPF_FMINNUM:
3916 if (!TLI.isProfitableToCombineMinNumMaxNum(VT))
3917 break;
3918
3919 switch (SPR.NaNBehavior) {
3920 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3921 case SPNB_RETURNS_ANY:
3922 case SPNB_RETURNS_NAN:
3923 break;
3924 case SPNB_RETURNS_OTHER:
3925 Opc = ISD::FMINIMUMNUM;
3926 Flags.setNoSignedZeros(true);
3927 break;
3928 }
3929 break;
3930 case SPF_FMAXNUM:
3931 if (!TLI.isProfitableToCombineMinNumMaxNum(VT))
3932 break;
3933
3934 switch (SPR.NaNBehavior) {
3935 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3936 case SPNB_RETURNS_NAN:
3937 case SPNB_RETURNS_ANY:
3938 break;
3939 case SPNB_RETURNS_OTHER:
3940 Opc = ISD::FMAXIMUMNUM;
3941 Flags.setNoSignedZeros(true);
3942 break;
3943 }
3944 break;
3945 case SPF_NABS:
3946 Negate = true;
3947 [[fallthrough]];
3948 case SPF_ABS:
3949 IsUnaryAbs = true;
3950 Opc = ISD::ABS;
3951 break;
3952 default: break;
3953 }
3954
3955 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3956 (TLI.isOperationLegalOrCustom(Op: Opc, VT) ||
3957 (UseScalarMinMax &&
3958 TLI.isOperationLegalOrCustom(Op: Opc, VT: VT.getScalarType()))) &&
3959 // If the underlying comparison instruction is used by any other
3960 // instruction, the consumed instructions won't be destroyed, so it is
3961 // not profitable to convert to a min/max.
3962 hasOnlySelectUsers(Cond: cast<SelectInst>(Val: I).getCondition())) {
3963 OpCode = Opc;
3964 LHSVal = getValue(V: LHS);
3965 RHSVal = getValue(V: RHS);
3966 BaseOps.clear();
3967 }
3968
3969 if (IsUnaryAbs) {
3970 OpCode = Opc;
3971 LHSVal = getValue(V: LHS);
3972 BaseOps.clear();
3973 }
3974 }
3975
3976 if (IsUnaryAbs) {
3977 for (unsigned i = 0; i != NumValues; ++i) {
3978 SDLoc dl = getCurSDLoc();
3979 EVT VT = LHSVal.getNode()->getValueType(ResNo: LHSVal.getResNo() + i);
3980 Values[i] =
3981 DAG.getNode(Opcode: OpCode, DL: dl, VT, Operand: LHSVal.getValue(R: LHSVal.getResNo() + i));
3982 if (Negate)
3983 Values[i] = DAG.getNegative(Val: Values[i], DL: dl, VT);
3984 }
3985 } else {
3986 for (unsigned i = 0; i != NumValues; ++i) {
3987 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3988 Ops.push_back(Elt: SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3989 Ops.push_back(Elt: SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3990 Values[i] = DAG.getNode(
3991 Opcode: OpCode, DL: getCurSDLoc(),
3992 VT: LHSVal.getNode()->getValueType(ResNo: LHSVal.getResNo() + i), Ops, Flags);
3993 }
3994 }
3995
3996 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
3997 VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values));
3998}
3999
4000void SelectionDAGBuilder::visitTrunc(const User &I) {
4001 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
4002 SDValue N = getValue(V: I.getOperand(i: 0));
4003 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4004 Ty: I.getType());
4005 SDNodeFlags Flags;
4006 if (auto *Trunc = dyn_cast<TruncInst>(Val: &I)) {
4007 Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
4008 Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
4009 }
4010
4011 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::TRUNCATE, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
4012}
4013
4014void SelectionDAGBuilder::visitZExt(const User &I) {
4015 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4016 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
4017 SDValue N = getValue(V: I.getOperand(i: 0));
4018 auto &TLI = DAG.getTargetLoweringInfo();
4019 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4020
4021 SDNodeFlags Flags;
4022 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(Val: &I))
4023 Flags.setNonNeg(PNI->hasNonNeg());
4024
4025 // Eagerly use nonneg information to canonicalize towards sign_extend if
4026 // that is the target's preference.
4027 // TODO: Let the target do this later.
4028 if (Flags.hasNonNeg() &&
4029 TLI.isSExtCheaperThanZExt(FromTy: N.getValueType(), ToTy: DestVT)) {
4030 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4031 return;
4032 }
4033
4034 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
4035}
4036
4037void SelectionDAGBuilder::visitSExt(const User &I) {
4038 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4039 // SExt also can't be a cast to bool for same reason. So, nothing much to do
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::SIGN_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4044}
4045
4046void SelectionDAGBuilder::visitFPTrunc(const User &I) {
4047 // FPTrunc is never a no-op cast, no need to check
4048 SDValue N = getValue(V: I.getOperand(i: 0));
4049 SDLoc dl = getCurSDLoc();
4050 SDNodeFlags Flags;
4051 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
4052 Flags.copyFMF(FPMO: *FPOp);
4053 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4054 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4055 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_ROUND, DL: dl, VT: DestVT, N1: N,
4056 N2: DAG.getTargetConstant(
4057 Val: 0, DL: dl, VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
4058 Flags));
4059}
4060
4061void SelectionDAGBuilder::visitFPExt(const User &I) {
4062 // FPExt is never a no-op cast, no need to check
4063 SDValue N = getValue(V: I.getOperand(i: 0));
4064 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4065 Ty: I.getType());
4066 SDNodeFlags Flags;
4067 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
4068 Flags.copyFMF(FPMO: *FPOp);
4069 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
4070}
4071
4072void SelectionDAGBuilder::visitFPToUI(const User &I) {
4073 // FPToUI is never a no-op cast, no need to check
4074 SDValue N = getValue(V: I.getOperand(i: 0));
4075 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4076 Ty: I.getType());
4077 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_UINT, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4078}
4079
4080void SelectionDAGBuilder::visitFPToSI(const User &I) {
4081 // FPToSI is never a no-op cast, no need to check
4082 SDValue N = getValue(V: I.getOperand(i: 0));
4083 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4084 Ty: I.getType());
4085 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_SINT, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4086}
4087
4088void SelectionDAGBuilder::visitUIToFP(const User &I) {
4089 // UIToFP is never a no-op cast, no need to check
4090 SDValue N = getValue(V: I.getOperand(i: 0));
4091 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4092 Ty: I.getType());
4093 SDNodeFlags Flags;
4094 Flags.setNonNeg(cast<PossiblyNonNegInst>(Val: &I)->hasNonNeg());
4095 Flags.copyFMF(FPMO: *cast<FPMathOperator>(Val: &I));
4096
4097 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UINT_TO_FP, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
4098}
4099
4100void SelectionDAGBuilder::visitSIToFP(const User &I) {
4101 // SIToFP is never a no-op cast, no need to check
4102 SDValue N = getValue(V: I.getOperand(i: 0));
4103 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4104 Ty: I.getType());
4105 SDNodeFlags Flags;
4106 Flags.copyFMF(FPMO: *cast<FPMathOperator>(Val: &I));
4107
4108 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
4109}
4110
4111void SelectionDAGBuilder::visitPtrToAddr(const User &I) {
4112 SDValue N = getValue(V: I.getOperand(i: 0));
4113 // By definition the type of the ptrtoaddr must be equal to the address type.
4114 const auto &TLI = DAG.getTargetLoweringInfo();
4115 EVT AddrVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4116 // The address width must be smaller or equal to the pointer representation
4117 // width, so we lower ptrtoaddr as a truncate (possibly folded to a no-op).
4118 N = DAG.getNode(Opcode: ISD::TRUNCATE, DL: getCurSDLoc(), VT: AddrVT, Operand: N);
4119 setValue(V: &I, NewN: N);
4120}
4121
4122void SelectionDAGBuilder::visitPtrToInt(const User &I) {
4123 // What to do depends on the size of the integer and the size of the pointer.
4124 // We can either truncate, zero extend, or no-op, accordingly.
4125 SDValue N = getValue(V: I.getOperand(i: 0));
4126 auto &TLI = DAG.getTargetLoweringInfo();
4127 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4128 Ty: I.getType());
4129 EVT PtrMemVT =
4130 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i: 0)->getType());
4131 N = DAG.getPtrExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: PtrMemVT);
4132 N = DAG.getZExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: DestVT);
4133 setValue(V: &I, NewN: N);
4134}
4135
4136void SelectionDAGBuilder::visitIntToPtr(const User &I) {
4137 // What to do depends on the size of the integer and the size of the pointer.
4138 // We can either truncate, zero extend, or no-op, accordingly.
4139 SDValue N = getValue(V: I.getOperand(i: 0));
4140 auto &TLI = DAG.getTargetLoweringInfo();
4141 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4142 EVT PtrMemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4143 N = DAG.getZExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: PtrMemVT);
4144 N = DAG.getPtrExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: DestVT);
4145 setValue(V: &I, NewN: N);
4146}
4147
4148void SelectionDAGBuilder::visitBitCast(const User &I) {
4149 SDValue N = getValue(V: I.getOperand(i: 0));
4150 SDLoc dl = getCurSDLoc();
4151 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4152 Ty: I.getType());
4153
4154 // BitCast assures us that source and destination are the same size so this is
4155 // either a BITCAST or a no-op.
4156 if (DestVT != N.getValueType())
4157 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::BITCAST, DL: dl,
4158 VT: DestVT, Operand: N)); // convert types.
4159 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
4160 // might fold any kind of constant expression to an integer constant and that
4161 // is not what we are looking for. Only recognize a bitcast of a genuine
4162 // constant integer as an opaque constant.
4163 else if(ConstantInt *C = dyn_cast<ConstantInt>(Val: I.getOperand(i: 0)))
4164 setValue(V: &I, NewN: DAG.getConstant(Val: C->getValue(), DL: dl, VT: DestVT, /*isTarget=*/false,
4165 /*isOpaque*/true));
4166 else
4167 setValue(V: &I, NewN: N); // noop cast.
4168}
4169
4170void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
4171 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4172 const Value *SV = I.getOperand(i: 0);
4173 SDValue N = getValue(V: SV);
4174 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4175
4176 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
4177 unsigned DestAS = I.getType()->getPointerAddressSpace();
4178
4179 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) {
4180 SDNodeFlags Flags;
4181 if (const auto *ASC = dyn_cast<AddrSpaceCastInst>(Val: &I))
4182 Flags.setNonNull(ASC->hasNonNull());
4183 N = DAG.getAddrSpaceCast(dl: getCurSDLoc(), VT: DestVT, Ptr: N, SrcAS, DestAS, Flags);
4184 }
4185
4186 setValue(V: &I, NewN: N);
4187}
4188
4189void SelectionDAGBuilder::visitInsertElement(const User &I) {
4190 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4191 SDValue InVec = getValue(V: I.getOperand(i: 0));
4192 SDValue InVal = getValue(V: I.getOperand(i: 1));
4193 SDValue InIdx = DAG.getZExtOrTrunc(Op: getValue(V: I.getOperand(i: 2)), DL: getCurSDLoc(),
4194 VT: TLI.getVectorIdxTy(DL: DAG.getDataLayout()));
4195 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: getCurSDLoc(),
4196 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
4197 N1: InVec, N2: InVal, N3: InIdx));
4198}
4199
4200void SelectionDAGBuilder::visitExtractElement(const User &I) {
4201 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4202 SDValue InVec = getValue(V: I.getOperand(i: 0));
4203 SDValue InIdx = DAG.getZExtOrTrunc(Op: getValue(V: I.getOperand(i: 1)), DL: getCurSDLoc(),
4204 VT: TLI.getVectorIdxTy(DL: DAG.getDataLayout()));
4205 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: getCurSDLoc(),
4206 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
4207 N1: InVec, N2: InIdx));
4208}
4209
4210void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4211 SDValue Src1 = getValue(V: I.getOperand(i: 0));
4212 SDValue Src2 = getValue(V: I.getOperand(i: 1));
4213 ArrayRef<int> Mask;
4214 if (auto *SVI = dyn_cast<ShuffleVectorInst>(Val: &I))
4215 Mask = SVI->getShuffleMask();
4216 else
4217 Mask = cast<ConstantExpr>(Val: I).getShuffleMask();
4218 SDLoc DL = getCurSDLoc();
4219 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4220 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4221 EVT SrcVT = Src1.getValueType();
4222
4223 if (all_of(Range&: Mask, P: equal_to(Arg: 0)) && VT.isScalableVector()) {
4224 // Canonical splat form of first element of first input vector.
4225 SDValue FirstElt =
4226 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: SrcVT.getScalarType(), N1: Src1,
4227 N2: DAG.getVectorIdxConstant(Val: 0, DL));
4228 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SPLAT_VECTOR, DL, VT, Operand: FirstElt));
4229 return;
4230 }
4231
4232 // For now, we only handle splats for scalable vectors.
4233 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4234 // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4235 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4236
4237 unsigned SrcNumElts = SrcVT.getVectorNumElements();
4238 unsigned MaskNumElts = Mask.size();
4239
4240 if (SrcNumElts == MaskNumElts) {
4241 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: Src1, N2: Src2, Mask));
4242 return;
4243 }
4244
4245 // Normalize the shuffle vector since mask and vector length don't match.
4246 if (SrcNumElts < MaskNumElts) {
4247 // Mask is longer than the source vectors. We can use concatenate vector to
4248 // make the mask and vectors lengths match.
4249
4250 if (MaskNumElts % SrcNumElts == 0) {
4251 // Mask length is a multiple of the source vector length.
4252 // Check if the shuffle is some kind of concatenation of the input
4253 // vectors.
4254 unsigned NumConcat = MaskNumElts / SrcNumElts;
4255 bool IsConcat = true;
4256 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4257 for (unsigned i = 0; i != MaskNumElts; ++i) {
4258 int Idx = Mask[i];
4259 if (Idx < 0)
4260 continue;
4261 // Ensure the indices in each SrcVT sized piece are sequential and that
4262 // the same source is used for the whole piece.
4263 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4264 (ConcatSrcs[i / SrcNumElts] >= 0 &&
4265 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4266 IsConcat = false;
4267 break;
4268 }
4269 // Remember which source this index came from.
4270 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4271 }
4272
4273 // The shuffle is concatenating multiple vectors together. Just emit
4274 // a CONCAT_VECTORS operation.
4275 if (IsConcat) {
4276 SmallVector<SDValue, 8> ConcatOps;
4277 for (auto Src : ConcatSrcs) {
4278 if (Src < 0)
4279 ConcatOps.push_back(Elt: DAG.getUNDEF(VT: SrcVT));
4280 else if (Src == 0)
4281 ConcatOps.push_back(Elt: Src1);
4282 else
4283 ConcatOps.push_back(Elt: Src2);
4284 }
4285 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT, Ops: ConcatOps));
4286 return;
4287 }
4288 }
4289
4290 unsigned PaddedMaskNumElts = alignTo(Value: MaskNumElts, Align: SrcNumElts);
4291 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4292 EVT PaddedVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: VT.getScalarType(),
4293 NumElements: PaddedMaskNumElts);
4294
4295 // Pad both vectors with undefs to make them the same length as the mask.
4296 SDValue UndefVal = DAG.getUNDEF(VT: SrcVT);
4297
4298 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4299 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4300 MOps1[0] = Src1;
4301 MOps2[0] = Src2;
4302
4303 Src1 = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: PaddedVT, Ops: MOps1);
4304 Src2 = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: PaddedVT, Ops: MOps2);
4305
4306 // Readjust mask for new input vector length.
4307 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4308 for (unsigned i = 0; i != MaskNumElts; ++i) {
4309 int Idx = Mask[i];
4310 if (Idx >= (int)SrcNumElts)
4311 Idx -= SrcNumElts - PaddedMaskNumElts;
4312 MappedOps[i] = Idx;
4313 }
4314
4315 SDValue Result = DAG.getVectorShuffle(VT: PaddedVT, dl: DL, N1: Src1, N2: Src2, Mask: MappedOps);
4316
4317 // If the concatenated vector was padded, extract a subvector with the
4318 // correct number of elements.
4319 if (MaskNumElts != PaddedMaskNumElts)
4320 Result = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT, N1: Result,
4321 N2: DAG.getVectorIdxConstant(Val: 0, DL));
4322
4323 setValue(V: &I, NewN: Result);
4324 return;
4325 }
4326
4327 assert(SrcNumElts > MaskNumElts);
4328
4329 // Analyze the access pattern of the vector to see if we can extract
4330 // two subvectors and do the shuffle.
4331 int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4332 bool CanExtract = true;
4333 for (int Idx : Mask) {
4334 unsigned Input = 0;
4335 if (Idx < 0)
4336 continue;
4337
4338 if (Idx >= (int)SrcNumElts) {
4339 Input = 1;
4340 Idx -= SrcNumElts;
4341 }
4342
4343 // If all the indices come from the same MaskNumElts sized portion of
4344 // the sources we can use extract. Also make sure the extract wouldn't
4345 // extract past the end of the source.
4346 int NewStartIdx = alignDown(Value: Idx, Align: MaskNumElts);
4347 if (NewStartIdx + MaskNumElts > SrcNumElts ||
4348 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4349 CanExtract = false;
4350 // Make sure we always update StartIdx as we use it to track if all
4351 // elements are undef.
4352 StartIdx[Input] = NewStartIdx;
4353 }
4354
4355 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4356 setValue(V: &I, NewN: DAG.getUNDEF(VT)); // Vectors are not used.
4357 return;
4358 }
4359 if (CanExtract) {
4360 // Extract appropriate subvector and generate a vector shuffle
4361 for (unsigned Input = 0; Input < 2; ++Input) {
4362 SDValue &Src = Input == 0 ? Src1 : Src2;
4363 if (StartIdx[Input] < 0)
4364 Src = DAG.getUNDEF(VT);
4365 else {
4366 Src = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT, N1: Src,
4367 N2: DAG.getVectorIdxConstant(Val: StartIdx[Input], DL));
4368 }
4369 }
4370
4371 // Calculate new mask.
4372 SmallVector<int, 8> MappedOps(Mask);
4373 for (int &Idx : MappedOps) {
4374 if (Idx >= (int)SrcNumElts)
4375 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4376 else if (Idx >= 0)
4377 Idx -= StartIdx[0];
4378 }
4379
4380 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: Src1, N2: Src2, Mask: MappedOps));
4381 return;
4382 }
4383
4384 // We can't use either concat vectors or extract subvectors so fall back to
4385 // replacing the shuffle with extract and build vector.
4386 // to insert and build vector.
4387 EVT EltVT = VT.getVectorElementType();
4388 SmallVector<SDValue,8> Ops;
4389 for (int Idx : Mask) {
4390 SDValue Res;
4391
4392 if (Idx < 0) {
4393 Res = DAG.getUNDEF(VT: EltVT);
4394 } else {
4395 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4396 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4397
4398 Res = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: EltVT, N1: Src,
4399 N2: DAG.getVectorIdxConstant(Val: Idx, DL));
4400 }
4401
4402 Ops.push_back(Elt: Res);
4403 }
4404
4405 setValue(V: &I, NewN: DAG.getBuildVector(VT, DL, Ops));
4406}
4407
4408void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4409 ArrayRef<unsigned> Indices = I.getIndices();
4410 const Value *Op0 = I.getOperand(i_nocapture: 0);
4411 const Value *Op1 = I.getOperand(i_nocapture: 1);
4412 Type *AggTy = I.getType();
4413 Type *ValTy = Op1->getType();
4414 bool IntoUndef = isa<UndefValue>(Val: Op0);
4415 bool FromUndef = isa<UndefValue>(Val: Op1);
4416
4417 unsigned LinearIndex = ComputeLinearIndex(Ty: AggTy, Indices);
4418
4419 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4420 SmallVector<EVT, 4> AggValueVTs;
4421 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: AggTy, ValueVTs&: AggValueVTs);
4422 SmallVector<EVT, 4> ValValueVTs;
4423 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: ValTy, ValueVTs&: ValValueVTs);
4424
4425 unsigned NumAggValues = AggValueVTs.size();
4426 unsigned NumValValues = ValValueVTs.size();
4427 SmallVector<SDValue, 4> Values(NumAggValues);
4428
4429 // Ignore an insertvalue that produces an empty object
4430 if (!NumAggValues) {
4431 setValue(V: &I, NewN: DAG.getUNDEF(VT: MVT(MVT::Other)));
4432 return;
4433 }
4434
4435 SDValue Agg = getValue(V: Op0);
4436 unsigned i = 0;
4437 // Copy the beginning value(s) from the original aggregate.
4438 for (; i != LinearIndex; ++i)
4439 Values[i] = IntoUndef ? DAG.getUNDEF(VT: AggValueVTs[i]) :
4440 SDValue(Agg.getNode(), Agg.getResNo() + i);
4441 // Copy values from the inserted value(s).
4442 if (NumValValues) {
4443 SDValue Val = getValue(V: Op1);
4444 for (; i != LinearIndex + NumValValues; ++i)
4445 Values[i] = FromUndef ? DAG.getUNDEF(VT: AggValueVTs[i]) :
4446 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4447 }
4448 // Copy remaining value(s) from the original aggregate.
4449 for (; i != NumAggValues; ++i)
4450 Values[i] = IntoUndef ? DAG.getUNDEF(VT: AggValueVTs[i]) :
4451 SDValue(Agg.getNode(), Agg.getResNo() + i);
4452
4453 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
4454 VTList: DAG.getVTList(VTs: AggValueVTs), Ops: Values));
4455}
4456
4457void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4458 ArrayRef<unsigned> Indices = I.getIndices();
4459 const Value *Op0 = I.getOperand(i_nocapture: 0);
4460 Type *AggTy = Op0->getType();
4461 Type *ValTy = I.getType();
4462 bool OutOfUndef = isa<UndefValue>(Val: Op0);
4463
4464 unsigned LinearIndex = ComputeLinearIndex(Ty: AggTy, Indices);
4465
4466 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4467 SmallVector<EVT, 4> ValValueVTs;
4468 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: ValTy, ValueVTs&: ValValueVTs);
4469
4470 unsigned NumValValues = ValValueVTs.size();
4471
4472 // Ignore a extractvalue that produces an empty object
4473 if (!NumValValues) {
4474 setValue(V: &I, NewN: DAG.getUNDEF(VT: MVT(MVT::Other)));
4475 return;
4476 }
4477
4478 SmallVector<SDValue, 4> Values(NumValValues);
4479
4480 SDValue Agg = getValue(V: Op0);
4481 // Copy out the selected value(s).
4482 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4483 Values[i - LinearIndex] =
4484 OutOfUndef ?
4485 DAG.getUNDEF(VT: Agg.getNode()->getValueType(ResNo: Agg.getResNo() + i)) :
4486 SDValue(Agg.getNode(), Agg.getResNo() + i);
4487
4488 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
4489 VTList: DAG.getVTList(VTs: ValValueVTs), Ops: Values));
4490}
4491
4492void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4493 Value *Op0 = I.getOperand(i: 0);
4494 // Note that the pointer operand may be a vector of pointers. Take the scalar
4495 // element which holds a pointer.
4496 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4497 SDValue N = getValue(V: Op0);
4498 SDLoc dl = getCurSDLoc();
4499 auto &TLI = DAG.getTargetLoweringInfo();
4500 GEPNoWrapFlags NW = cast<GEPOperator>(Val: I).getNoWrapFlags();
4501
4502 // For a vector GEP, keep the prefix scalar as long as possible, then
4503 // convert any scalars encountered after the first vector operand to vectors.
4504 bool IsVectorGEP = I.getType()->isVectorTy();
4505 ElementCount VectorElementCount =
4506 IsVectorGEP ? cast<VectorType>(Val: I.getType())->getElementCount()
4507 : ElementCount::getFixed(MinVal: 0);
4508
4509 for (gep_type_iterator GTI = gep_type_begin(GEP: &I), E = gep_type_end(GEP: &I);
4510 GTI != E; ++GTI) {
4511 const Value *Idx = GTI.getOperand();
4512 if (StructType *StTy = GTI.getStructTypeOrNull()) {
4513 unsigned Field = cast<Constant>(Val: Idx)->getUniqueInteger().getZExtValue();
4514 if (Field) {
4515 // N = N + Offset
4516 uint64_t Offset =
4517 DAG.getDataLayout().getStructLayout(Ty: StTy)->getElementOffset(Idx: Field);
4518
4519 // In an inbounds GEP with an offset that is nonnegative even when
4520 // interpreted as signed, assume there is no unsigned overflow.
4521 SDNodeFlags Flags;
4522 if (NW.hasNoUnsignedWrap() ||
4523 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4524 Flags |= SDNodeFlags::NoUnsignedWrap;
4525 Flags.setInBounds(NW.isInBounds());
4526
4527 N = DAG.getMemBasePlusOffset(
4528 Base: N, Offset: DAG.getConstant(Val: Offset, DL: dl, VT: N.getValueType()), DL: dl, Flags);
4529 }
4530 } else {
4531 // IdxSize is the width of the arithmetic according to IR semantics.
4532 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4533 // (and fix up the result later).
4534 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4535 MVT IdxTy = MVT::getIntegerVT(BitWidth: IdxSize);
4536 TypeSize ElementSize =
4537 GTI.getSequentialElementStride(DL: DAG.getDataLayout());
4538 // We intentionally mask away the high bits here; ElementSize may not
4539 // fit in IdxTy.
4540 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4541 /*isSigned=*/false, /*implicitTrunc=*/true);
4542 bool ElementScalable = ElementSize.isScalable();
4543
4544 // If this is a scalar constant or a splat vector of constants,
4545 // handle it quickly.
4546 const auto *C = dyn_cast<Constant>(Val: Idx);
4547 if (C && isa<VectorType>(Val: C->getType()))
4548 C = C->getSplatValue();
4549
4550 const auto *CI = dyn_cast_or_null<ConstantInt>(Val: C);
4551 if (CI && CI->isZero())
4552 continue;
4553 if (CI && !ElementScalable) {
4554 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(width: IdxSize);
4555 LLVMContext &Context = *DAG.getContext();
4556 SDValue OffsVal;
4557 if (N.getValueType().isVector())
4558 OffsVal = DAG.getConstant(
4559 Val: Offs, DL: dl, VT: EVT::getVectorVT(Context, VT: IdxTy, EC: VectorElementCount));
4560 else
4561 OffsVal = DAG.getConstant(Val: Offs, DL: dl, VT: IdxTy);
4562
4563 // In an inbounds GEP with an offset that is nonnegative even when
4564 // interpreted as signed, assume there is no unsigned overflow.
4565 SDNodeFlags Flags;
4566 if (NW.hasNoUnsignedWrap() ||
4567 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4568 Flags.setNoUnsignedWrap(true);
4569 Flags.setInBounds(NW.isInBounds());
4570
4571 OffsVal = DAG.getSExtOrTrunc(Op: OffsVal, DL: dl, VT: N.getValueType());
4572
4573 N = DAG.getMemBasePlusOffset(Base: N, Offset: OffsVal, DL: dl, Flags);
4574 continue;
4575 }
4576
4577 // N = N + Idx * ElementMul;
4578 SDValue IdxN = getValue(V: Idx);
4579
4580 if (IdxN.getValueType().isVector() != N.getValueType().isVector()) {
4581 if (N.getValueType().isVector()) {
4582 EVT VT = EVT::getVectorVT(Context&: *Context, VT: IdxN.getValueType(),
4583 EC: VectorElementCount);
4584 IdxN = DAG.getSplat(VT, DL: dl, Op: IdxN);
4585 } else {
4586 EVT VT =
4587 EVT::getVectorVT(Context&: *Context, VT: N.getValueType(), EC: VectorElementCount);
4588 N = DAG.getSplat(VT, DL: dl, Op: N);
4589 }
4590 }
4591
4592 // If the index is smaller or larger than intptr_t, truncate or extend
4593 // it.
4594 IdxN = DAG.getSExtOrTrunc(Op: IdxN, DL: dl, VT: N.getValueType());
4595
4596 SDNodeFlags ScaleFlags;
4597 // The multiplication of an index by the type size does not wrap the
4598 // pointer index type in a signed sense (mul nsw).
4599 ScaleFlags.setNoSignedWrap(NW.hasNoUnsignedSignedWrap());
4600
4601 // The multiplication of an index by the type size does not wrap the
4602 // pointer index type in an unsigned sense (mul nuw).
4603 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4604
4605 if (ElementScalable) {
4606 EVT VScaleTy = N.getValueType().getScalarType();
4607 SDValue VScale = DAG.getNode(
4608 Opcode: ISD::VSCALE, DL: dl, VT: VScaleTy,
4609 Operand: DAG.getConstant(Val: ElementMul.getZExtValue(), DL: dl, VT: VScaleTy));
4610 if (N.getValueType().isVector())
4611 VScale = DAG.getSplatVector(VT: N.getValueType(), DL: dl, Op: VScale);
4612 IdxN = DAG.getNode(Opcode: ISD::MUL, DL: dl, VT: N.getValueType(), N1: IdxN, N2: VScale,
4613 Flags: ScaleFlags);
4614 } else {
4615 // If this is a multiply by a power of two, turn it into a shl
4616 // immediately. This is a very common case.
4617 if (ElementMul != 1) {
4618 if (ElementMul.isPowerOf2()) {
4619 unsigned Amt = ElementMul.logBase2();
4620 IdxN = DAG.getNode(
4621 Opcode: ISD::SHL, DL: dl, VT: N.getValueType(), N1: IdxN,
4622 N2: DAG.getShiftAmountConstant(Val: Amt, VT: N.getValueType(), DL: dl),
4623 Flags: ScaleFlags);
4624 } else {
4625 SDValue Scale = DAG.getConstant(Val: ElementMul.getZExtValue(), DL: dl,
4626 VT: IdxN.getValueType());
4627 IdxN = DAG.getNode(Opcode: ISD::MUL, DL: dl, VT: N.getValueType(), N1: IdxN, N2: Scale,
4628 Flags: ScaleFlags);
4629 }
4630 }
4631 }
4632
4633 // The successive addition of the current address, truncated to the
4634 // pointer index type and interpreted as an unsigned number, and each
4635 // offset, also interpreted as an unsigned number, does not wrap the
4636 // pointer index type (add nuw).
4637 SDNodeFlags AddFlags;
4638 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4639 AddFlags.setInBounds(NW.isInBounds());
4640
4641 N = DAG.getMemBasePlusOffset(Base: N, Offset: IdxN, DL: dl, Flags: AddFlags);
4642 }
4643 }
4644
4645 if (IsVectorGEP && !N.getValueType().isVector()) {
4646 EVT VT = EVT::getVectorVT(Context&: *Context, VT: N.getValueType(), EC: VectorElementCount);
4647 N = DAG.getSplat(VT, DL: dl, Op: N);
4648 }
4649
4650 MVT PtrTy = TLI.getPointerTy(DL: DAG.getDataLayout(), AS);
4651 MVT PtrMemTy = TLI.getPointerMemTy(DL: DAG.getDataLayout(), AS);
4652 if (IsVectorGEP) {
4653 PtrTy = MVT::getVectorVT(VT: PtrTy, EC: VectorElementCount);
4654 PtrMemTy = MVT::getVectorVT(VT: PtrMemTy, EC: VectorElementCount);
4655 }
4656
4657 if (PtrMemTy != PtrTy && !cast<GEPOperator>(Val: I).isInBounds())
4658 N = DAG.getPtrExtendInReg(Op: N, DL: dl, VT: PtrMemTy);
4659
4660 setValue(V: &I, NewN: N);
4661}
4662
4663void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4664 // If this is a fixed sized alloca in the entry block of the function,
4665 // allocate it statically on the stack.
4666 if (FuncInfo.StaticAllocaMap.count(Val: &I))
4667 return; // getValue will auto-populate this.
4668
4669 SDLoc dl = getCurSDLoc();
4670 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4671 auto &DL = DAG.getDataLayout();
4672 TypeSize TySize = I.getAllocationBaseSize(DL);
4673 MaybeAlign Alignment = I.getAlign();
4674
4675 SDValue AllocSize = getValue(V: I.getArraySize());
4676
4677 EVT IntPtr = TLI.getPointerTy(DL, AS: I.getAddressSpace());
4678 if (AllocSize.getValueType() != IntPtr)
4679 AllocSize = DAG.getZExtOrTrunc(Op: AllocSize, DL: dl, VT: IntPtr);
4680
4681 AllocSize = DAG.getNode(
4682 Opcode: ISD::MUL, DL: dl, VT: IntPtr, N1: AllocSize,
4683 N2: DAG.getZExtOrTrunc(Op: DAG.getTypeSize(DL: dl, VT: MVT::i64, TS: TySize), DL: dl, VT: IntPtr));
4684
4685 // Handle alignment. If the requested alignment is less than or equal to
4686 // the stack alignment, ignore it. If the size is greater than or equal to
4687 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4688 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4689 if (*Alignment <= StackAlign)
4690 Alignment = std::nullopt;
4691
4692 const uint64_t StackAlignMask = StackAlign.value() - 1U;
4693 // Round the size of the allocation up to the stack alignment size
4694 // by add SA-1 to the size. This doesn't overflow because we're computing
4695 // an address inside an alloca.
4696 AllocSize = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: AllocSize.getValueType(), N1: AllocSize,
4697 N2: DAG.getConstant(Val: StackAlignMask, DL: dl, VT: IntPtr),
4698 Flags: SDNodeFlags::NoUnsignedWrap);
4699
4700 // Mask out the low bits for alignment purposes.
4701 AllocSize = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: AllocSize.getValueType(), N1: AllocSize,
4702 N2: DAG.getSignedConstant(Val: ~StackAlignMask, DL: dl, VT: IntPtr));
4703
4704 SDValue Ops[] = {
4705 getRoot(), AllocSize,
4706 DAG.getConstant(Val: Alignment ? Alignment->value() : 0, DL: dl, VT: IntPtr)};
4707 SDVTList VTs = DAG.getVTList(VT1: AllocSize.getValueType(), VT2: MVT::Other);
4708 SDValue DSA = DAG.getNode(Opcode: ISD::DYNAMIC_STACKALLOC, DL: dl, VTList: VTs, Ops);
4709 setValue(V: &I, NewN: DSA);
4710 DAG.setRoot(DSA.getValue(R: 1));
4711
4712 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4713}
4714
4715static const MDNode *getRangeMetadata(const Instruction &I) {
4716 return I.getMetadata(KindID: LLVMContext::MD_range);
4717}
4718
4719static std::optional<ConstantRange> getRange(const Instruction &I) {
4720 if (const auto *CB = dyn_cast<CallBase>(Val: &I))
4721 if (std::optional<ConstantRange> CR = CB->getRange())
4722 return CR;
4723 if (const MDNode *Range = getRangeMetadata(I))
4724 return getConstantRangeFromMetadata(RangeMD: *Range);
4725 return std::nullopt;
4726}
4727
4728static FPClassTest getNoFPClass(const Instruction &I) {
4729 if (const auto *CB = dyn_cast<CallBase>(Val: &I))
4730 return CB->getRetNoFPClass();
4731 return fcNone;
4732}
4733
4734void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4735 if (I.isAtomic())
4736 return visitAtomicLoad(I);
4737
4738 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4739 const Value *SV = I.getOperand(i_nocapture: 0);
4740 if (TLI.supportSwiftError()) {
4741 // Swifterror values can come from either a function parameter with
4742 // swifterror attribute or an alloca with swifterror attribute.
4743 if (const Argument *Arg = dyn_cast<Argument>(Val: SV)) {
4744 if (Arg->hasSwiftErrorAttr())
4745 return visitLoadFromSwiftError(I);
4746 }
4747
4748 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(Val: SV)) {
4749 if (Alloca->isSwiftError())
4750 return visitLoadFromSwiftError(I);
4751 }
4752 }
4753
4754 SDValue Ptr = getValue(V: SV);
4755
4756 Type *Ty = I.getType();
4757 SmallVector<EVT, 4> ValueVTs, MemVTs;
4758 SmallVector<TypeSize, 4> Offsets;
4759 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty, ValueVTs, MemVTs: &MemVTs, Offsets: &Offsets);
4760 unsigned NumValues = ValueVTs.size();
4761 if (NumValues == 0)
4762 return;
4763
4764 Align Alignment = I.getAlign();
4765 AAMDNodes AAInfo = I.getAAMetadata();
4766 const MDNode *Ranges = getRangeMetadata(I);
4767 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
4768 bool isVolatile = I.isVolatile();
4769 MachineMemOperand::Flags MMOFlags =
4770 TLI.getLoadMemOperandFlags(LI: I, DL: DAG.getDataLayout(), AC, LibInfo);
4771
4772 SDValue Root;
4773 bool ConstantMemory = false;
4774 if (isVolatile)
4775 // Serialize volatile loads with other side effects.
4776 Root = getRoot();
4777 else if (NumValues > MaxParallelChains)
4778 Root = getMemoryRoot();
4779 else if (BatchAA &&
4780 BatchAA->pointsToConstantMemory(Loc: MemoryLocation(
4781 SV,
4782 LocationSize::precise(Value: DAG.getDataLayout().getTypeStoreSize(Ty)),
4783 AAInfo))) {
4784 // Do not serialize (non-volatile) loads of constant memory with anything.
4785 Root = DAG.getEntryNode();
4786 ConstantMemory = true;
4787 MMOFlags |= MachineMemOperand::MOInvariant;
4788 } else {
4789 // Do not serialize non-volatile loads against each other.
4790 Root = DAG.getRoot();
4791 }
4792
4793 SDLoc dl = getCurSDLoc();
4794
4795 if (isVolatile)
4796 Root = TLI.prepareVolatileOrAtomicLoad(Chain: Root, DL: dl, DAG);
4797
4798 SmallVector<SDValue, 4> Values(NumValues);
4799 SmallVector<SDValue, 4> Chains(std::min(a: MaxParallelChains, b: NumValues));
4800
4801 unsigned ChainI = 0;
4802 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4803 // Serializing loads here may result in excessive register pressure, and
4804 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4805 // could recover a bit by hoisting nodes upward in the chain by recognizing
4806 // they are side-effect free or do not alias. The optimizer should really
4807 // avoid this case by converting large object/array copies to llvm.memcpy
4808 // (MaxParallelChains should always remain as failsafe).
4809 if (ChainI == MaxParallelChains) {
4810 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4811 SDValue Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4812 Ops: ArrayRef(Chains.data(), ChainI));
4813 Root = Chain;
4814 ChainI = 0;
4815 }
4816
4817 // TODO: MachinePointerInfo only supports a fixed length offset.
4818 MachinePointerInfo PtrInfo =
4819 !Offsets[i].isScalable() || Offsets[i].isZero()
4820 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4821 : MachinePointerInfo();
4822
4823 SDValue A = DAG.getObjectPtrOffset(SL: dl, Ptr, Offset: Offsets[i]);
4824 SDValue L =
4825 DAG.getLoad(VT: MemVTs[i], dl, Chain: Root, Ptr: A, PtrInfo, Alignment, MMOFlags,
4826 Metadata: MMOMetadata(AAInfo, Ranges, MemCacheHint));
4827 Chains[ChainI] = L.getValue(R: 1);
4828
4829 if (MemVTs[i] != ValueVTs[i])
4830 L = DAG.getPtrExtOrTrunc(Op: L, DL: dl, VT: ValueVTs[i]);
4831
4832 if (MDNode *NoFPClassMD = I.getMetadata(KindID: LLVMContext::MD_nofpclass)) {
4833 uint64_t FPTestInt =
4834 cast<ConstantInt>(
4835 Val: cast<ConstantAsMetadata>(Val: NoFPClassMD->getOperand(I: 0))->getValue())
4836 ->getZExtValue();
4837 if (FPTestInt != fcNone) {
4838 SDValue FPTestConst =
4839 DAG.getTargetConstant(Val: FPTestInt, DL: SDLoc(), VT: MVT::i32);
4840 L = DAG.getNode(Opcode: ISD::AssertNoFPClass, DL: dl, VT: L.getValueType(), N1: L,
4841 N2: FPTestConst);
4842 }
4843 }
4844 Values[i] = L;
4845 }
4846
4847 if (!ConstantMemory) {
4848 SDValue Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4849 Ops: ArrayRef(Chains.data(), ChainI));
4850 if (isVolatile)
4851 DAG.setRoot(Chain);
4852 else
4853 PendingLoads.push_back(Elt: Chain);
4854 }
4855
4856 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl,
4857 VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values));
4858}
4859
4860void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4861 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4862 "call visitStoreToSwiftError when backend supports swifterror");
4863
4864 SmallVector<EVT, 4> ValueVTs;
4865 SmallVector<uint64_t, 4> Offsets;
4866 const Value *SrcV = I.getOperand(i_nocapture: 0);
4867 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(),
4868 Ty: SrcV->getType(), ValueVTs, /*MemVTs=*/nullptr, FixedOffsets: &Offsets, StartingOffset: 0);
4869 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4870 "expect a single EVT for swifterror");
4871
4872 SDValue Src = getValue(V: SrcV);
4873 // Create a virtual register, then update the virtual register.
4874 Register VReg =
4875 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4876 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4877 // Chain can be getRoot or getControlRoot.
4878 SDValue CopyNode = DAG.getCopyToReg(Chain: getRoot(), dl: getCurSDLoc(), Reg: VReg,
4879 N: SDValue(Src.getNode(), Src.getResNo()));
4880 DAG.setRoot(CopyNode);
4881}
4882
4883void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4884 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4885 "call visitLoadFromSwiftError when backend supports swifterror");
4886
4887 assert(!I.isVolatile() &&
4888 !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4889 !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4890 "Support volatile, non temporal, invariant for load_from_swift_error");
4891
4892 const Value *SV = I.getOperand(i_nocapture: 0);
4893 Type *Ty = I.getType();
4894 assert(
4895 (!BatchAA ||
4896 !BatchAA->pointsToConstantMemory(MemoryLocation(
4897 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4898 I.getAAMetadata()))) &&
4899 "load_from_swift_error should not be constant memory");
4900
4901 SmallVector<EVT, 4> ValueVTs;
4902 SmallVector<uint64_t, 4> Offsets;
4903 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty,
4904 ValueVTs, /*MemVTs=*/nullptr, FixedOffsets: &Offsets, StartingOffset: 0);
4905 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4906 "expect a single EVT for swifterror");
4907
4908 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4909 SDValue L = DAG.getCopyFromReg(
4910 Chain: getRoot(), dl: getCurSDLoc(),
4911 Reg: SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), VT: ValueVTs[0]);
4912
4913 setValue(V: &I, NewN: L);
4914}
4915
4916void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4917 if (I.isAtomic())
4918 return visitAtomicStore(I);
4919
4920 const Value *SrcV = I.getOperand(i_nocapture: 0);
4921 const Value *PtrV = I.getOperand(i_nocapture: 1);
4922
4923 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4924 if (TLI.supportSwiftError()) {
4925 // Swifterror values can come from either a function parameter with
4926 // swifterror attribute or an alloca with swifterror attribute.
4927 if (const Argument *Arg = dyn_cast<Argument>(Val: PtrV)) {
4928 if (Arg->hasSwiftErrorAttr())
4929 return visitStoreToSwiftError(I);
4930 }
4931
4932 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(Val: PtrV)) {
4933 if (Alloca->isSwiftError())
4934 return visitStoreToSwiftError(I);
4935 }
4936 }
4937
4938 SmallVector<EVT, 4> ValueVTs, MemVTs;
4939 SmallVector<TypeSize, 4> Offsets;
4940 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(),
4941 Ty: SrcV->getType(), ValueVTs, MemVTs: &MemVTs, Offsets: &Offsets);
4942 unsigned NumValues = ValueVTs.size();
4943 if (NumValues == 0)
4944 return;
4945
4946 // Get the lowered operands. Note that we do this after
4947 // checking if NumResults is zero, because with zero results
4948 // the operands won't have values in the map.
4949 SDValue Src = getValue(V: SrcV);
4950 SDValue Ptr = getValue(V: PtrV);
4951
4952 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4953 SmallVector<SDValue, 4> Chains(std::min(a: MaxParallelChains, b: NumValues));
4954 SDLoc dl = getCurSDLoc();
4955 Align Alignment = I.getAlign();
4956 AAMDNodes AAInfo = I.getAAMetadata();
4957 const MDNode *MemCacheHint =
4958 getMemCacheHintMetadata(I, OperandNo: I.getPointerOperandIndex());
4959
4960 auto MMOFlags = TLI.getStoreMemOperandFlags(SI: I, DL: DAG.getDataLayout());
4961
4962 unsigned ChainI = 0;
4963 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4964 // See visitLoad comments.
4965 if (ChainI == MaxParallelChains) {
4966 SDValue Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4967 Ops: ArrayRef(Chains.data(), ChainI));
4968 Root = Chain;
4969 ChainI = 0;
4970 }
4971
4972 // TODO: MachinePointerInfo only supports a fixed length offset.
4973 MachinePointerInfo PtrInfo =
4974 !Offsets[i].isScalable() || Offsets[i].isZero()
4975 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4976 : MachinePointerInfo();
4977
4978 SDValue Add = DAG.getObjectPtrOffset(SL: dl, Ptr, Offset: Offsets[i]);
4979 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4980 if (MemVTs[i] != ValueVTs[i])
4981 Val = DAG.getPtrExtOrTrunc(Op: Val, DL: dl, VT: MemVTs[i]);
4982 SDValue St =
4983 DAG.getStore(Chain: Root, dl, Val, Ptr: Add, PtrInfo, Alignment, MMOFlags,
4984 Metadata: MMOMetadata(AAInfo, /*Ranges=*/nullptr, MemCacheHint));
4985 Chains[ChainI] = St;
4986 }
4987
4988 SDValue StoreNode = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4989 Ops: ArrayRef(Chains.data(), ChainI));
4990 setValue(V: &I, NewN: StoreNode);
4991 DAG.setRoot(StoreNode);
4992}
4993
4994void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4995 bool IsCompressing) {
4996 SDLoc sdl = getCurSDLoc();
4997
4998 Value *Src0Operand = I.getArgOperand(i: 0);
4999 Value *PtrOperand = I.getArgOperand(i: 1);
5000 Value *MaskOperand = I.getArgOperand(i: 2);
5001 Align Alignment = I.getParamAlign(ArgNo: 1).valueOrOne();
5002
5003 SDValue Ptr = getValue(V: PtrOperand);
5004 SDValue Src0 = getValue(V: Src0Operand);
5005 SDValue Mask = getValue(V: MaskOperand);
5006 SDValue Offset = DAG.getPOISON(VT: Ptr.getValueType());
5007
5008 EVT VT = Src0.getValueType();
5009
5010 const auto &TLI = DAG.getTargetLoweringInfo();
5011
5012 auto MMOFlags = MachineMemOperand::MOStore;
5013 MMOFlags |= TLI.getTargetMMOFlags(I);
5014 if (I.hasMetadata(KindID: LLVMContext::MD_nontemporal))
5015 MMOFlags |= MachineMemOperand::MONonTemporal;
5016
5017 const MDNode *MemCacheHint = getMemCacheHintMetadata(I, /*OperandNo=*/1);
5018
5019 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5020 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
5021 Size: LocationSize::upperBound(Value: VT.getStoreSize()), BaseAlignment: Alignment,
5022 Metadata: MMOMetadata(I.getAAMetadata(), /*Ranges=*/nullptr, MemCacheHint));
5023
5024 SDValue StoreNode =
5025 !IsCompressing && TTI->hasConditionalLoadStoreForType(
5026 Ty: I.getArgOperand(i: 0)->getType(), /*IsStore=*/true)
5027 ? TLI.visitMaskedStore(DAG, DL: sdl, Chain: getMemoryRoot(), MMO, Ptr, Val: Src0,
5028 Mask)
5029 : DAG.getMaskedStore(Chain: getMemoryRoot(), dl: sdl, Val: Src0, Base: Ptr, Offset, Mask,
5030 MemVT: VT, MMO, AM: ISD::UNINDEXED, /*Truncating=*/IsTruncating: false,
5031 IsCompressing);
5032 DAG.setRoot(StoreNode);
5033 setValue(V: &I, NewN: StoreNode);
5034}
5035
5036// Get a uniform base for the Gather/Scatter intrinsic.
5037// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
5038// We try to represent it as a base pointer + vector of indices.
5039// Usually, the vector of pointers comes from a 'getelementptr' instruction.
5040// The first operand of the GEP may be a single pointer or a vector of pointers
5041// Example:
5042// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
5043// or
5044// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
5045// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
5046//
5047// When the first GEP operand is a single pointer - it is the uniform base we
5048// are looking for. If first operand of the GEP is a splat vector - we
5049// extract the splat value and use it as a uniform base.
5050// In all other cases the function returns 'false'.
5051static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
5052 SDValue &Scale, SelectionDAGBuilder *SDB,
5053 const BasicBlock *CurBB, uint64_t ElemSize) {
5054 SelectionDAG& DAG = SDB->DAG;
5055 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5056 const DataLayout &DL = DAG.getDataLayout();
5057
5058 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
5059
5060 // Handle splat constant pointer.
5061 if (auto *C = dyn_cast<Constant>(Val: Ptr)) {
5062 C = C->getSplatValue();
5063 if (!C)
5064 return false;
5065
5066 Base = SDB->getValue(V: C);
5067
5068 ElementCount NumElts = cast<VectorType>(Val: Ptr->getType())->getElementCount();
5069 EVT VT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: TLI.getPointerTy(DL), EC: NumElts);
5070 Index = DAG.getConstant(Val: 0, DL: SDB->getCurSDLoc(), VT);
5071 Scale = DAG.getTargetConstant(Val: 1, DL: SDB->getCurSDLoc(), VT: TLI.getPointerTy(DL));
5072 return true;
5073 }
5074
5075 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Val: Ptr);
5076 if (!GEP || GEP->getParent() != CurBB)
5077 return false;
5078
5079 if (GEP->getNumOperands() != 2)
5080 return false;
5081
5082 const Value *BasePtr = GEP->getPointerOperand();
5083 const Value *IndexVal = GEP->getOperand(i_nocapture: GEP->getNumOperands() - 1);
5084
5085 // Make sure the base is scalar and the index is a vector.
5086 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
5087 return false;
5088
5089 TypeSize ScaleVal = DL.getTypeAllocSize(Ty: GEP->getResultElementType());
5090 if (ScaleVal.isScalable())
5091 return false;
5092
5093 // Target may not support the required addressing mode.
5094 if (ScaleVal != 1 &&
5095 !TLI.isLegalScaleForGatherScatter(Scale: ScaleVal.getFixedValue(), ElemSize))
5096 return false;
5097
5098 Base = SDB->getValue(V: BasePtr);
5099 Index = SDB->getValue(V: IndexVal);
5100
5101 Scale =
5102 DAG.getTargetConstant(Val: ScaleVal, DL: SDB->getCurSDLoc(), VT: TLI.getPointerTy(DL));
5103 return true;
5104}
5105
5106void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
5107 SDLoc sdl = getCurSDLoc();
5108
5109 // llvm.masked.scatter.*(Src0, Ptrs, Mask)
5110 const Value *Ptr = I.getArgOperand(i: 1);
5111 SDValue Src0 = getValue(V: I.getArgOperand(i: 0));
5112 SDValue Mask = getValue(V: I.getArgOperand(i: 2));
5113 EVT VT = Src0.getValueType();
5114 Align Alignment = I.getParamAlign(ArgNo: 1).valueOrOne();
5115 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5116
5117 SDValue Base;
5118 SDValue Index;
5119 SDValue Scale;
5120 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, SDB: this,
5121 CurBB: I.getParent(), ElemSize: VT.getScalarStoreSize());
5122
5123 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5124 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5125 PtrInfo: MachinePointerInfo(AS), F: MachineMemOperand::MOStore,
5126 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: Alignment, Metadata: I.getAAMetadata());
5127 if (!UniformBase) {
5128 Base = DAG.getConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5129 Index = getValue(V: Ptr);
5130 Scale =
5131 DAG.getTargetConstant(Val: 1, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5132 }
5133
5134 EVT IdxVT = Index.getValueType();
5135 EVT EltTy = IdxVT.getVectorElementType();
5136 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
5137 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
5138 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: sdl, VT: NewIdxVT, Operand: Index);
5139 }
5140
5141 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
5142 SDValue Scatter = DAG.getMaskedScatter(VTs: DAG.getVTList(VT: MVT::Other), MemVT: VT, dl: sdl,
5143 Ops, MMO, IndexType: ISD::SIGNED_SCALED, IsTruncating: false);
5144 DAG.setRoot(Scatter);
5145 setValue(V: &I, NewN: Scatter);
5146}
5147
5148void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
5149 SDLoc sdl = getCurSDLoc();
5150
5151 Value *PtrOperand = I.getArgOperand(i: 0);
5152 Value *MaskOperand = I.getArgOperand(i: 1);
5153 Value *Src0Operand = I.getArgOperand(i: 2);
5154 Align Alignment = I.getParamAlign(ArgNo: 0).valueOrOne();
5155
5156 SDValue Ptr = getValue(V: PtrOperand);
5157 SDValue Src0 = getValue(V: Src0Operand);
5158 SDValue Mask = getValue(V: MaskOperand);
5159 SDValue Offset = DAG.getPOISON(VT: Ptr.getValueType());
5160
5161 EVT VT = Src0.getValueType();
5162 AAMDNodes AAInfo = I.getAAMetadata();
5163 const MDNode *Ranges = getRangeMetadata(I);
5164 const MDNode *MemCacheHint = getMemCacheHintMetadata(I, /*OperandNo=*/0);
5165
5166 // Do not serialize masked loads of constant memory with anything.
5167 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
5168 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
5169
5170 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
5171
5172 const auto &TLI = DAG.getTargetLoweringInfo();
5173
5174 auto MMOFlags = MachineMemOperand::MOLoad;
5175 MMOFlags |= TLI.getTargetMMOFlags(I);
5176 if (I.hasMetadata(KindID: LLVMContext::MD_nontemporal))
5177 MMOFlags |= MachineMemOperand::MONonTemporal;
5178 if (I.hasMetadata(KindID: LLVMContext::MD_invariant_load))
5179 MMOFlags |= MachineMemOperand::MOInvariant;
5180
5181 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5182 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
5183 Size: LocationSize::upperBound(Value: VT.getStoreSize()), BaseAlignment: Alignment,
5184 Metadata: MMOMetadata(AAInfo, Ranges, MemCacheHint));
5185
5186 // The Load/Res may point to different values and both of them are output
5187 // variables.
5188 SDValue Load;
5189 SDValue Res;
5190 if (!IsExpanding &&
5191 TTI->hasConditionalLoadStoreForType(Ty: Src0Operand->getType(),
5192 /*IsStore=*/false))
5193 Res = TLI.visitMaskedLoad(DAG, DL: sdl, Chain: InChain, MMO, NewLoad&: Load, Ptr, PassThru: Src0, Mask);
5194 else
5195 Res = Load =
5196 DAG.getMaskedLoad(VT, dl: sdl, Chain: InChain, Base: Ptr, Offset, Mask, Src0, MemVT: VT, MMO,
5197 AM: ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5198 if (AddToChain)
5199 PendingLoads.push_back(Elt: Load.getValue(R: 1));
5200 setValue(V: &I, NewN: Res);
5201}
5202
5203void SelectionDAGBuilder::visitSpeculativeLoad(const CallInst &I) {
5204 SDLoc sdl = getCurSDLoc();
5205 Value *PtrOperand = I.getArgOperand(i: 0);
5206 // The remaining arguments (num_accessible_bytes or oracle function + args)
5207 // are IR-level semantics only; they are not needed at codegen.
5208 SDValue Ptr = getValue(V: PtrOperand);
5209
5210 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5211 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
5212 Align Alignment = I.getParamAlign(ArgNo: 0).valueOrOne();
5213 AAMDNodes AAInfo = I.getAAMetadata();
5214
5215 SDValue InChain = DAG.getRoot();
5216
5217 // Use MOLoad but NOT MODereferenceable - the memory may not be
5218 // fully dereferenceable.
5219 auto MMOFlags = MachineMemOperand::MOLoad;
5220 MMOFlags |= TLI.getTargetMMOFlags(I);
5221 if (I.hasMetadata(KindID: LLVMContext::MD_nontemporal))
5222 MMOFlags |= MachineMemOperand::MONonTemporal;
5223 if (I.hasMetadata(KindID: LLVMContext::MD_invariant_load))
5224 MMOFlags |= MachineMemOperand::MOInvariant;
5225
5226 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5227 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
5228 Size: LocationSize::precise(Value: VT.getStoreSize()), BaseAlignment: Alignment, Metadata: AAInfo);
5229
5230 SDValue Load = DAG.getLoad(VT, dl: sdl, Chain: InChain, Ptr, MMO);
5231 PendingLoads.push_back(Elt: Load.getValue(R: 1));
5232 setValue(V: &I, NewN: Load);
5233}
5234
5235void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5236 SDLoc sdl = getCurSDLoc();
5237
5238 // @llvm.masked.gather.*(Ptrs, Mask, Src0)
5239 const Value *Ptr = I.getArgOperand(i: 0);
5240 SDValue Src0 = getValue(V: I.getArgOperand(i: 2));
5241 SDValue Mask = getValue(V: I.getArgOperand(i: 1));
5242
5243 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5244 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
5245 Align Alignment = I.getParamAlign(ArgNo: 0).valueOrOne();
5246
5247 const MDNode *Ranges = getRangeMetadata(I);
5248
5249 SDValue Root = DAG.getRoot();
5250 SDValue Base;
5251 SDValue Index;
5252 SDValue Scale;
5253 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, SDB: this,
5254 CurBB: I.getParent(), ElemSize: VT.getScalarStoreSize());
5255 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5256 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5257 PtrInfo: MachinePointerInfo(AS), F: MachineMemOperand::MOLoad,
5258 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: Alignment,
5259 Metadata: MMOMetadata(I.getAAMetadata(), Ranges));
5260
5261 if (!UniformBase) {
5262 Base = DAG.getConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5263 Index = getValue(V: Ptr);
5264 Scale =
5265 DAG.getTargetConstant(Val: 1, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5266 }
5267
5268 EVT IdxVT = Index.getValueType();
5269 EVT EltTy = IdxVT.getVectorElementType();
5270 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
5271 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
5272 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: sdl, VT: NewIdxVT, Operand: Index);
5273 }
5274
5275 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5276 SDValue Gather =
5277 DAG.getMaskedGather(VTs: DAG.getVTList(VT1: VT, VT2: MVT::Other), MemVT: VT, dl: sdl, Ops, MMO,
5278 IndexType: ISD::SIGNED_SCALED, ExtTy: ISD::NON_EXTLOAD);
5279
5280 PendingLoads.push_back(Elt: Gather.getValue(R: 1));
5281 setValue(V: &I, NewN: Gather);
5282}
5283
5284void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5285 SDLoc dl = getCurSDLoc();
5286 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5287 AtomicOrdering FailureOrdering = I.getFailureOrdering();
5288 SyncScope::ID SSID = I.getSyncScopeID();
5289
5290 SDValue InChain = getRoot();
5291
5292 MVT MemVT = getValue(V: I.getCompareOperand()).getSimpleValueType();
5293 SDVTList VTs = DAG.getVTList(VT1: MemVT, VT2: MVT::i1, VT3: MVT::Other);
5294
5295 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5296 auto Flags = TLI.getAtomicMemOperandFlags(AI: I, DL: DAG.getDataLayout());
5297
5298 MachineFunction &MF = DAG.getMachineFunction();
5299 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5300 MachineMemOperand *MMO = MF.getMachineMemOperand(
5301 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5302 BaseAlignment: I.getAlign(), Metadata: MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5303 SSID, Ordering: SuccessOrdering, FailureOrdering);
5304
5305 SDValue L = DAG.getAtomicCmpSwap(Opcode: ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5306 dl, MemVT, VTs, Chain: InChain,
5307 Ptr: getValue(V: I.getPointerOperand()),
5308 Cmp: getValue(V: I.getCompareOperand()),
5309 Swp: getValue(V: I.getNewValOperand()), MMO);
5310
5311 SDValue OutChain = L.getValue(R: 2);
5312
5313 setValue(V: &I, NewN: L);
5314 DAG.setRoot(OutChain);
5315}
5316
5317void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5318 SDLoc dl = getCurSDLoc();
5319 ISD::NodeType NT;
5320 switch (I.getOperation()) {
5321 default: llvm_unreachable("Unknown atomicrmw operation");
5322 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5323 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
5324 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
5325 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
5326 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5327 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
5328 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
5329 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
5330 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
5331 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5332 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5333 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5334 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5335 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5336 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5337 case AtomicRMWInst::FMaximum:
5338 NT = ISD::ATOMIC_LOAD_FMAXIMUM;
5339 break;
5340 case AtomicRMWInst::FMinimum:
5341 NT = ISD::ATOMIC_LOAD_FMINIMUM;
5342 break;
5343 case AtomicRMWInst::FMaximumNum:
5344 NT = ISD::ATOMIC_LOAD_FMAXIMUMNUM;
5345 break;
5346 case AtomicRMWInst::FMinimumNum:
5347 NT = ISD::ATOMIC_LOAD_FMINIMUMNUM;
5348 break;
5349 case AtomicRMWInst::UIncWrap:
5350 NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5351 break;
5352 case AtomicRMWInst::UDecWrap:
5353 NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5354 break;
5355 case AtomicRMWInst::USubCond:
5356 NT = ISD::ATOMIC_LOAD_USUB_COND;
5357 break;
5358 case AtomicRMWInst::USubSat:
5359 NT = ISD::ATOMIC_LOAD_USUB_SAT;
5360 break;
5361 }
5362 AtomicOrdering Ordering = I.getOrdering();
5363 SyncScope::ID SSID = I.getSyncScopeID();
5364
5365 SDValue InChain = getRoot();
5366
5367 auto MemVT = getValue(V: I.getValOperand()).getSimpleValueType();
5368 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5369 auto Flags = TLI.getAtomicMemOperandFlags(AI: I, DL: DAG.getDataLayout());
5370
5371 MachineFunction &MF = DAG.getMachineFunction();
5372 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5373 MachineMemOperand *MMO = MF.getMachineMemOperand(
5374 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5375 BaseAlignment: I.getAlign(), Metadata: MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5376 SSID, Ordering);
5377
5378 SDValue L =
5379 DAG.getAtomic(Opcode: NT, dl, MemVT, Chain: InChain,
5380 Ptr: getValue(V: I.getPointerOperand()), Val: getValue(V: I.getValOperand()),
5381 MMO);
5382
5383 SDValue OutChain = L.getValue(R: 1);
5384
5385 setValue(V: &I, NewN: L);
5386 DAG.setRoot(OutChain);
5387}
5388
5389void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5390 SDLoc dl = getCurSDLoc();
5391 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5392 SDValue Ops[3];
5393 Ops[0] = getRoot();
5394 Ops[1] = DAG.getTargetConstant(Val: (unsigned)I.getOrdering(), DL: dl,
5395 VT: TLI.getFenceOperandTy(DL: DAG.getDataLayout()));
5396 Ops[2] = DAG.getTargetConstant(Val: I.getSyncScopeID(), DL: dl,
5397 VT: TLI.getFenceOperandTy(DL: DAG.getDataLayout()));
5398 SDValue N = DAG.getNode(Opcode: ISD::ATOMIC_FENCE, DL: dl, VT: MVT::Other, Ops);
5399 setValue(V: &I, NewN: N);
5400 DAG.setRoot(N);
5401}
5402
5403void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5404 SDLoc dl = getCurSDLoc();
5405 AtomicOrdering Order = I.getOrdering();
5406 SyncScope::ID SSID = I.getSyncScopeID();
5407
5408 SDValue InChain = getRoot();
5409
5410 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5411 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
5412 EVT MemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getType());
5413
5414 if (!TLI.isAtomicAlignmentSupported(Alignment: I.getAlign(), SizeInBytes: MemVT.getSizeInBits() / 8))
5415 report_fatal_error(reason: "Cannot generate unaligned atomic load");
5416
5417 auto Flags = TLI.getLoadMemOperandFlags(LI: I, DL: DAG.getDataLayout(), AC, LibInfo);
5418
5419 const MDNode *Ranges = getRangeMetadata(I);
5420 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5421 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5422 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5423 BaseAlignment: I.getAlign(), Metadata: MMOMetadata(AAMDNodes(), Ranges, MemCacheHint), SSID,
5424 Ordering: Order);
5425
5426 InChain = TLI.prepareVolatileOrAtomicLoad(Chain: InChain, DL: dl, DAG);
5427
5428 SDValue Ptr = getValue(V: I.getPointerOperand());
5429 SDValue L =
5430 DAG.getAtomicLoad(ExtType: ISD::NON_EXTLOAD, dl, MemVT, VT: MemVT, Chain: InChain, Ptr, MMO);
5431
5432 SDValue OutChain = L.getValue(R: 1);
5433 if (MemVT != VT)
5434 L = DAG.getPtrExtOrTrunc(Op: L, DL: dl, VT);
5435
5436 setValue(V: &I, NewN: L);
5437 DAG.setRoot(OutChain);
5438}
5439
5440void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5441 SDLoc dl = getCurSDLoc();
5442
5443 AtomicOrdering Ordering = I.getOrdering();
5444 SyncScope::ID SSID = I.getSyncScopeID();
5445
5446 SDValue InChain = getRoot();
5447
5448 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5449 EVT MemVT =
5450 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getValueOperand()->getType());
5451
5452 if (!TLI.isAtomicAlignmentSupported(Alignment: I.getAlign(), SizeInBytes: MemVT.getSizeInBits() / 8))
5453 report_fatal_error(reason: "Cannot generate unaligned atomic store");
5454
5455 auto Flags = TLI.getStoreMemOperandFlags(SI: I, DL: DAG.getDataLayout());
5456
5457 MachineFunction &MF = DAG.getMachineFunction();
5458 const MDNode *MemCacheHint =
5459 getMemCacheHintMetadata(I, OperandNo: I.getPointerOperandIndex());
5460 MachineMemOperand *MMO = MF.getMachineMemOperand(
5461 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5462 BaseAlignment: I.getAlign(), Metadata: MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5463 SSID, Ordering);
5464
5465 SDValue Val = getValue(V: I.getValueOperand());
5466 if (Val.getValueType() != MemVT)
5467 Val = DAG.getPtrExtOrTrunc(Op: Val, DL: dl, VT: MemVT);
5468 SDValue Ptr = getValue(V: I.getPointerOperand());
5469
5470 SDValue OutChain =
5471 DAG.getAtomic(Opcode: ISD::ATOMIC_STORE, dl, MemVT, Chain: InChain, Ptr: Val, Val: Ptr, MMO);
5472
5473 setValue(V: &I, NewN: OutChain);
5474 DAG.setRoot(OutChain);
5475}
5476
5477/// Check if this intrinsic call depends on the chain (1st return value)
5478/// and if it only *loads* memory.
5479/// Ignore the callsite's attributes. A specific call site may be marked with
5480/// readnone, but the lowering code will expect the chain based on the
5481/// definition.
5482std::pair<bool, bool>
5483SelectionDAGBuilder::getTargetIntrinsicCallProperties(const CallBase &I) {
5484 const Function *F = I.getCalledFunction();
5485 bool HasChain = !F->doesNotAccessMemory();
5486 bool OnlyLoad =
5487 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5488
5489 return {HasChain, OnlyLoad};
5490}
5491
5492SmallVector<SDValue, 8> SelectionDAGBuilder::getTargetIntrinsicOperands(
5493 const CallBase &I, bool HasChain, bool OnlyLoad,
5494 TargetLowering::IntrinsicInfo *TgtMemIntrinsicInfo) {
5495 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5496
5497 // Build the operand list.
5498 SmallVector<SDValue, 8> Ops;
5499 if (HasChain) { // If this intrinsic has side-effects, chainify it.
5500 if (OnlyLoad) {
5501 // We don't need to serialize loads against other loads.
5502 Ops.push_back(Elt: DAG.getRoot());
5503 } else {
5504 Ops.push_back(Elt: getRoot());
5505 }
5506 }
5507
5508 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5509 if (!TgtMemIntrinsicInfo || TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_VOID ||
5510 TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_W_CHAIN)
5511 Ops.push_back(Elt: DAG.getTargetConstant(Val: I.getIntrinsicID(), DL: getCurSDLoc(),
5512 VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
5513
5514 // Add all operands of the call to the operand list.
5515 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5516 const Value *Arg = I.getArgOperand(i);
5517 if (!I.paramHasAttr(ArgNo: i, Kind: Attribute::ImmArg)) {
5518 Ops.push_back(Elt: getValue(V: Arg));
5519 continue;
5520 }
5521
5522 // Use TargetConstant instead of a regular constant for immarg.
5523 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: Arg->getType(), AllowUnknown: true);
5524 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: Arg)) {
5525 assert(CI->getBitWidth() <= 64 &&
5526 "large intrinsic immediates not handled");
5527 Ops.push_back(Elt: DAG.getTargetConstant(Val: *CI, DL: SDLoc(), VT));
5528 } else {
5529 Ops.push_back(
5530 Elt: DAG.getTargetConstantFP(Val: *cast<ConstantFP>(Val: Arg), DL: SDLoc(), VT));
5531 }
5532 }
5533
5534 if (std::optional<OperandBundleUse> Bundle =
5535 I.getOperandBundle(ID: LLVMContext::OB_deactivation_symbol)) {
5536 auto *Sym = Bundle->Inputs[0].get();
5537 SDValue SDSym = getValue(V: Sym);
5538 SDSym = DAG.getDeactivationSymbol(GV: cast<GlobalValue>(Val: Sym));
5539 Ops.push_back(Elt: SDSym);
5540 }
5541
5542 if (std::optional<OperandBundleUse> Bundle =
5543 I.getOperandBundle(ID: LLVMContext::OB_convergencectrl)) {
5544 Value *Token = Bundle->Inputs[0].get();
5545 SDValue ConvControlToken = getValue(V: Token);
5546 assert(Ops.back().getValueType() != MVT::Glue &&
5547 "Did not expect another glue node here.");
5548 ConvControlToken =
5549 DAG.getNode(Opcode: ISD::CONVERGENCECTRL_GLUE, DL: {}, VT: MVT::Glue, Operand: ConvControlToken);
5550 Ops.push_back(Elt: ConvControlToken);
5551 }
5552
5553 return Ops;
5554}
5555
5556SDVTList SelectionDAGBuilder::getTargetIntrinsicVTList(const CallBase &I,
5557 bool HasChain) {
5558 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5559
5560 SmallVector<EVT, 4> ValueVTs;
5561 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: I.getType(), ValueVTs);
5562
5563 if (HasChain)
5564 ValueVTs.push_back(Elt: MVT::Other);
5565
5566 return DAG.getVTList(VTs: ValueVTs);
5567}
5568
5569/// Get an INTRINSIC node for a target intrinsic which does not touch memory.
5570SDValue SelectionDAGBuilder::getTargetNonMemIntrinsicNode(
5571 const Type &IntrinsicVT, bool HasChain, ArrayRef<SDValue> Ops,
5572 const SDVTList &VTs) {
5573 if (!HasChain)
5574 return DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: getCurSDLoc(), VTList: VTs, Ops);
5575 if (!IntrinsicVT.isVoidTy())
5576 return DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL: getCurSDLoc(), VTList: VTs, Ops);
5577 return DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL: getCurSDLoc(), VTList: VTs, Ops);
5578}
5579
5580/// Set root, convert return type if necessary and check alignment.
5581SDValue SelectionDAGBuilder::handleTargetIntrinsicRet(const CallBase &I,
5582 bool HasChain,
5583 bool OnlyLoad,
5584 SDValue Result) {
5585 if (HasChain) {
5586 SDValue Chain = Result.getValue(R: Result.getNode()->getNumValues() - 1);
5587 if (OnlyLoad)
5588 PendingLoads.push_back(Elt: Chain);
5589 else
5590 DAG.setRoot(Chain);
5591 }
5592
5593 if (I.getType()->isVoidTy())
5594 return Result;
5595
5596 if (MaybeAlign Alignment = I.getRetAlign(); InsertAssertAlign && Alignment) {
5597 // Insert `assertalign` node if there's an alignment.
5598 Result = DAG.getAssertAlign(DL: getCurSDLoc(), V: Result, A: Alignment.valueOrOne());
5599 } else if (!isa<VectorType>(Val: I.getType())) {
5600 Result = lowerRangeToAssertZExt(DAG, I, Op: Result);
5601 }
5602
5603 return Result;
5604}
5605
5606/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5607/// node.
5608void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5609 unsigned Intrinsic) {
5610 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
5611 Intrinsic::ID IntrinsicID = static_cast<Intrinsic::ID>(Intrinsic);
5612
5613 if (!DAG.getMachineFunction().getSubtarget().isIntrinsicSupported(
5614 IntrinsicID: Intrinsic)) {
5615 SDLoc DL = getCurSDLoc();
5616 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupportedTargetIntrinsic(
5617 *I.getFunction(), IntrinsicID, DL.getDebugLoc()));
5618
5619 // The intrinsic is not available on this subtarget. Preserve the chain for
5620 // side-effecting intrinsics and lower any result to poison so that
5621 // compilation can continue and collect further diagnostics.
5622 if (HasChain && !OnlyLoad)
5623 DAG.setRoot(getRoot());
5624
5625 setValueToPoison(V: &I, dl: DL);
5626 return;
5627 }
5628
5629 // Infos is set by getTgtMemIntrinsic.
5630 SmallVector<TargetLowering::IntrinsicInfo> Infos;
5631 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5632 TLI.getTgtMemIntrinsic(Infos, I, MF&: DAG.getMachineFunction(), Intrinsic);
5633 // Use the first (primary) info determines the node opcode.
5634 TargetLowering::IntrinsicInfo *Info = !Infos.empty() ? &Infos[0] : nullptr;
5635
5636 SmallVector<SDValue, 8> Ops =
5637 getTargetIntrinsicOperands(I, HasChain, OnlyLoad, TgtMemIntrinsicInfo: Info);
5638 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
5639
5640 // Propagate fast-math-flags from IR to node(s).
5641 SDNodeFlags Flags;
5642 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &I))
5643 Flags.copyFMF(FPMO: *FPMO);
5644 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5645
5646 // Create the node.
5647 SDValue Result;
5648
5649 // In some cases, custom collection of operands from CallInst I may be needed.
5650 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5651 if (!Infos.empty()) {
5652 // This is target intrinsic that touches memory
5653 // Create MachineMemOperands for each memory access described by the target.
5654 MachineFunction &MF = DAG.getMachineFunction();
5655 SmallVector<MachineMemOperand *> MMOs;
5656 for (const auto &Info : Infos) {
5657 // TODO: We currently just fallback to address space 0 if
5658 // getTgtMemIntrinsic didn't yield anything useful.
5659 MachinePointerInfo MPI;
5660 if (Info.ptrVal)
5661 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5662 else if (Info.fallbackAddressSpace)
5663 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5664 EVT MemVT = Info.memVT;
5665 LocationSize Size = LocationSize::precise(Value: Info.size);
5666 if (Size.hasValue() && !Size.getValue())
5667 Size = LocationSize::precise(Value: MemVT.getStoreSize());
5668 Align Alignment = Info.align.value_or(u: DAG.getEVTAlign(MemoryVT: MemVT));
5669 MachineMemOperand *MMO = MF.getMachineMemOperand(
5670 PtrInfo: MPI, F: Info.flags, Size, BaseAlignment: Alignment, Metadata: I.getAAMetadata(), SSID: Info.ssid,
5671 Ordering: Info.order, FailureOrdering: Info.failureOrder);
5672 MMOs.push_back(Elt: MMO);
5673 }
5674
5675 Result = DAG.getMemIntrinsicNode(Opcode: Info->opc, dl: getCurSDLoc(), VTList: VTs, Ops,
5676 MemVT: Info->memVT, MMOs);
5677 } else {
5678 Result = getTargetNonMemIntrinsicNode(IntrinsicVT: *I.getType(), HasChain, Ops, VTs);
5679 }
5680
5681 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
5682
5683 setValue(V: &I, NewN: Result);
5684}
5685
5686/// GetSignificand - Get the significand and build it into a floating-point
5687/// number with exponent of 1:
5688///
5689/// Op = (Op & 0x007fffff) | 0x3f800000;
5690///
5691/// where Op is the hexadecimal representation of floating point value.
5692static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5693 SDValue t1 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: Op,
5694 N2: DAG.getConstant(Val: 0x007fffff, DL: dl, VT: MVT::i32));
5695 SDValue t2 = DAG.getNode(Opcode: ISD::OR, DL: dl, VT: MVT::i32, N1: t1,
5696 N2: DAG.getConstant(Val: 0x3f800000, DL: dl, VT: MVT::i32));
5697 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f32, Operand: t2);
5698}
5699
5700/// GetExponent - Get the exponent:
5701///
5702/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5703///
5704/// where Op is the hexadecimal representation of floating point value.
5705static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5706 const TargetLowering &TLI, const SDLoc &dl) {
5707 SDValue t0 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: Op,
5708 N2: DAG.getConstant(Val: 0x7f800000, DL: dl, VT: MVT::i32));
5709 SDValue t1 = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32, N1: t0,
5710 N2: DAG.getShiftAmountConstant(Val: 23, VT: MVT::i32, DL: dl));
5711 SDValue t2 = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32, N1: t1,
5712 N2: DAG.getConstant(Val: 127, DL: dl, VT: MVT::i32));
5713 return DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::f32, Operand: t2);
5714}
5715
5716/// getF32Constant - Get 32-bit floating point constant.
5717static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5718 const SDLoc &dl) {
5719 return DAG.getConstantFP(Val: APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), DL: dl,
5720 VT: MVT::f32);
5721}
5722
5723static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5724 SelectionDAG &DAG) {
5725 // TODO: What fast-math-flags should be set on the floating-point nodes?
5726
5727 // IntegerPartOfX = ((int32_t)(t0);
5728 SDValue IntegerPartOfX = DAG.getNode(Opcode: ISD::FP_TO_SINT, DL: dl, VT: MVT::i32, Operand: t0);
5729
5730 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
5731 SDValue t1 = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::f32, Operand: IntegerPartOfX);
5732 SDValue X = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t0, N2: t1);
5733
5734 // IntegerPartOfX <<= 23;
5735 IntegerPartOfX = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT: MVT::i32, N1: IntegerPartOfX,
5736 N2: DAG.getShiftAmountConstant(Val: 23, VT: MVT::i32, DL: dl));
5737
5738 SDValue TwoToFractionalPartOfX;
5739 if (LimitFloatPrecision <= 6) {
5740 // For floating-point precision of 6:
5741 //
5742 // TwoToFractionalPartOfX =
5743 // 0.997535578f +
5744 // (0.735607626f + 0.252464424f * x) * x;
5745 //
5746 // error 0.0144103317, which is 6 bits
5747 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5748 N2: getF32Constant(DAG, Flt: 0x3e814304, dl));
5749 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5750 N2: getF32Constant(DAG, Flt: 0x3f3c50c8, dl));
5751 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5752 TwoToFractionalPartOfX = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5753 N2: getF32Constant(DAG, Flt: 0x3f7f5e7e, dl));
5754 } else if (LimitFloatPrecision <= 12) {
5755 // For floating-point precision of 12:
5756 //
5757 // TwoToFractionalPartOfX =
5758 // 0.999892986f +
5759 // (0.696457318f +
5760 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
5761 //
5762 // error 0.000107046256, which is 13 to 14 bits
5763 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5764 N2: getF32Constant(DAG, Flt: 0x3da235e3, dl));
5765 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5766 N2: getF32Constant(DAG, Flt: 0x3e65b8f3, dl));
5767 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5768 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5769 N2: getF32Constant(DAG, Flt: 0x3f324b07, dl));
5770 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5771 TwoToFractionalPartOfX = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t6,
5772 N2: getF32Constant(DAG, Flt: 0x3f7ff8fd, dl));
5773 } else { // LimitFloatPrecision <= 18
5774 // For floating-point precision of 18:
5775 //
5776 // TwoToFractionalPartOfX =
5777 // 0.999999982f +
5778 // (0.693148872f +
5779 // (0.240227044f +
5780 // (0.554906021e-1f +
5781 // (0.961591928e-2f +
5782 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5783 // error 2.47208000*10^(-7), which is better than 18 bits
5784 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5785 N2: getF32Constant(DAG, Flt: 0x3924b03e, dl));
5786 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5787 N2: getF32Constant(DAG, Flt: 0x3ab24b87, dl));
5788 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5789 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5790 N2: getF32Constant(DAG, Flt: 0x3c1d8c17, dl));
5791 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5792 SDValue t7 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t6,
5793 N2: getF32Constant(DAG, Flt: 0x3d634a1d, dl));
5794 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
5795 SDValue t9 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t8,
5796 N2: getF32Constant(DAG, Flt: 0x3e75fe14, dl));
5797 SDValue t10 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t9, N2: X);
5798 SDValue t11 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t10,
5799 N2: getF32Constant(DAG, Flt: 0x3f317234, dl));
5800 SDValue t12 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t11, N2: X);
5801 TwoToFractionalPartOfX = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t12,
5802 N2: getF32Constant(DAG, Flt: 0x3f800000, dl));
5803 }
5804
5805 // Add the exponent into the result in integer domain.
5806 SDValue t13 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: TwoToFractionalPartOfX);
5807 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f32,
5808 Operand: DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: t13, N2: IntegerPartOfX));
5809}
5810
5811/// expandExp - Lower an exp intrinsic. Handles the special sequences for
5812/// limited-precision mode.
5813static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5814 const TargetLowering &TLI, SDNodeFlags Flags) {
5815 if (Op.getValueType() == MVT::f32 &&
5816 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5817
5818 // Put the exponent in the right bit position for later addition to the
5819 // final result:
5820 //
5821 // t0 = Op * log2(e)
5822
5823 // TODO: What fast-math-flags should be set here?
5824 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: Op,
5825 N2: DAG.getConstantFP(Val: numbers::log2ef, DL: dl, VT: MVT::f32));
5826 return getLimitedPrecisionExp2(t0, dl, DAG);
5827 }
5828
5829 // No special expansion.
5830 return DAG.getNode(Opcode: ISD::FEXP, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5831}
5832
5833/// expandLog - Lower a log intrinsic. Handles the special sequences for
5834/// limited-precision mode.
5835static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5836 const TargetLowering &TLI, SDNodeFlags Flags) {
5837 // TODO: What fast-math-flags should be set on the floating-point nodes?
5838
5839 if (Op.getValueType() == MVT::f32 &&
5840 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5841 SDValue Op1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Op);
5842
5843 // Scale the exponent by log(2).
5844 SDValue Exp = GetExponent(DAG, Op: Op1, TLI, dl);
5845 SDValue LogOfExponent =
5846 DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: Exp,
5847 N2: DAG.getConstantFP(Val: numbers::ln2f, DL: dl, VT: MVT::f32));
5848
5849 // Get the significand and build it into a floating-point number with
5850 // exponent of 1.
5851 SDValue X = GetSignificand(DAG, Op: Op1, dl);
5852
5853 SDValue LogOfMantissa;
5854 if (LimitFloatPrecision <= 6) {
5855 // For floating-point precision of 6:
5856 //
5857 // LogofMantissa =
5858 // -1.1609546f +
5859 // (1.4034025f - 0.23903021f * x) * x;
5860 //
5861 // error 0.0034276066, which is better than 8 bits
5862 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5863 N2: getF32Constant(DAG, Flt: 0xbe74c456, dl));
5864 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5865 N2: getF32Constant(DAG, Flt: 0x3fb3a2b1, dl));
5866 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5867 LogOfMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5868 N2: getF32Constant(DAG, Flt: 0x3f949a29, dl));
5869 } else if (LimitFloatPrecision <= 12) {
5870 // For floating-point precision of 12:
5871 //
5872 // LogOfMantissa =
5873 // -1.7417939f +
5874 // (2.8212026f +
5875 // (-1.4699568f +
5876 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5877 //
5878 // error 0.000061011436, which is 14 bits
5879 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5880 N2: getF32Constant(DAG, Flt: 0xbd67b6d6, dl));
5881 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5882 N2: getF32Constant(DAG, Flt: 0x3ee4f4b8, dl));
5883 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5884 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5885 N2: getF32Constant(DAG, Flt: 0x3fbc278b, dl));
5886 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5887 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5888 N2: getF32Constant(DAG, Flt: 0x40348e95, dl));
5889 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5890 LogOfMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5891 N2: getF32Constant(DAG, Flt: 0x3fdef31a, dl));
5892 } else { // LimitFloatPrecision <= 18
5893 // For floating-point precision of 18:
5894 //
5895 // LogOfMantissa =
5896 // -2.1072184f +
5897 // (4.2372794f +
5898 // (-3.7029485f +
5899 // (2.2781945f +
5900 // (-0.87823314f +
5901 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5902 //
5903 // error 0.0000023660568, which is better than 18 bits
5904 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5905 N2: getF32Constant(DAG, Flt: 0xbc91e5ac, dl));
5906 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5907 N2: getF32Constant(DAG, Flt: 0x3e4350aa, dl));
5908 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5909 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5910 N2: getF32Constant(DAG, Flt: 0x3f60d3e3, dl));
5911 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5912 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5913 N2: getF32Constant(DAG, Flt: 0x4011cdf0, dl));
5914 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5915 SDValue t7 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5916 N2: getF32Constant(DAG, Flt: 0x406cfd1c, dl));
5917 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
5918 SDValue t9 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t8,
5919 N2: getF32Constant(DAG, Flt: 0x408797cb, dl));
5920 SDValue t10 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t9, N2: X);
5921 LogOfMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t10,
5922 N2: getF32Constant(DAG, Flt: 0x4006dcab, dl));
5923 }
5924
5925 return DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: LogOfExponent, N2: LogOfMantissa);
5926 }
5927
5928 // No special expansion.
5929 return DAG.getNode(Opcode: ISD::FLOG, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5930}
5931
5932/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5933/// limited-precision mode.
5934static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5935 const TargetLowering &TLI, SDNodeFlags Flags) {
5936 // TODO: What fast-math-flags should be set on the floating-point nodes?
5937
5938 if (Op.getValueType() == MVT::f32 &&
5939 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5940 SDValue Op1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Op);
5941
5942 // Get the exponent.
5943 SDValue LogOfExponent = GetExponent(DAG, Op: Op1, TLI, dl);
5944
5945 // Get the significand and build it into a floating-point number with
5946 // exponent of 1.
5947 SDValue X = GetSignificand(DAG, Op: Op1, dl);
5948
5949 // Different possible minimax approximations of significand in
5950 // floating-point for various degrees of accuracy over [1,2].
5951 SDValue Log2ofMantissa;
5952 if (LimitFloatPrecision <= 6) {
5953 // For floating-point precision of 6:
5954 //
5955 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5956 //
5957 // error 0.0049451742, which is more than 7 bits
5958 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5959 N2: getF32Constant(DAG, Flt: 0xbeb08fe0, dl));
5960 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5961 N2: getF32Constant(DAG, Flt: 0x40019463, dl));
5962 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5963 Log2ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5964 N2: getF32Constant(DAG, Flt: 0x3fd6633d, dl));
5965 } else if (LimitFloatPrecision <= 12) {
5966 // For floating-point precision of 12:
5967 //
5968 // Log2ofMantissa =
5969 // -2.51285454f +
5970 // (4.07009056f +
5971 // (-2.12067489f +
5972 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5973 //
5974 // error 0.0000876136000, which is better than 13 bits
5975 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5976 N2: getF32Constant(DAG, Flt: 0xbda7262e, dl));
5977 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5978 N2: getF32Constant(DAG, Flt: 0x3f25280b, dl));
5979 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5980 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5981 N2: getF32Constant(DAG, Flt: 0x4007b923, dl));
5982 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5983 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5984 N2: getF32Constant(DAG, Flt: 0x40823e2f, dl));
5985 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5986 Log2ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5987 N2: getF32Constant(DAG, Flt: 0x4020d29c, dl));
5988 } else { // LimitFloatPrecision <= 18
5989 // For floating-point precision of 18:
5990 //
5991 // Log2ofMantissa =
5992 // -3.0400495f +
5993 // (6.1129976f +
5994 // (-5.3420409f +
5995 // (3.2865683f +
5996 // (-1.2669343f +
5997 // (0.27515199f -
5998 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5999 //
6000 // error 0.0000018516, which is better than 18 bits
6001 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
6002 N2: getF32Constant(DAG, Flt: 0xbcd2769e, dl));
6003 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
6004 N2: getF32Constant(DAG, Flt: 0x3e8ce0b9, dl));
6005 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
6006 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
6007 N2: getF32Constant(DAG, Flt: 0x3fa22ae7, dl));
6008 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
6009 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
6010 N2: getF32Constant(DAG, Flt: 0x40525723, dl));
6011 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
6012 SDValue t7 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
6013 N2: getF32Constant(DAG, Flt: 0x40aaf200, dl));
6014 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
6015 SDValue t9 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t8,
6016 N2: getF32Constant(DAG, Flt: 0x40c39dad, dl));
6017 SDValue t10 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t9, N2: X);
6018 Log2ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t10,
6019 N2: getF32Constant(DAG, Flt: 0x4042902c, dl));
6020 }
6021
6022 return DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: LogOfExponent, N2: Log2ofMantissa);
6023 }
6024
6025 // No special expansion.
6026 return DAG.getNode(Opcode: ISD::FLOG2, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
6027}
6028
6029/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
6030/// limited-precision mode.
6031static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
6032 const TargetLowering &TLI, SDNodeFlags Flags) {
6033 // TODO: What fast-math-flags should be set on the floating-point nodes?
6034
6035 if (Op.getValueType() == MVT::f32 &&
6036 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
6037 SDValue Op1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Op);
6038
6039 // Scale the exponent by log10(2) [0.30102999f].
6040 SDValue Exp = GetExponent(DAG, Op: Op1, TLI, dl);
6041 SDValue LogOfExponent = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: Exp,
6042 N2: getF32Constant(DAG, Flt: 0x3e9a209a, dl));
6043
6044 // Get the significand and build it into a floating-point number with
6045 // exponent of 1.
6046 SDValue X = GetSignificand(DAG, Op: Op1, dl);
6047
6048 SDValue Log10ofMantissa;
6049 if (LimitFloatPrecision <= 6) {
6050 // For floating-point precision of 6:
6051 //
6052 // Log10ofMantissa =
6053 // -0.50419619f +
6054 // (0.60948995f - 0.10380950f * x) * x;
6055 //
6056 // error 0.0014886165, which is 6 bits
6057 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
6058 N2: getF32Constant(DAG, Flt: 0xbdd49a13, dl));
6059 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
6060 N2: getF32Constant(DAG, Flt: 0x3f1c0789, dl));
6061 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
6062 Log10ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
6063 N2: getF32Constant(DAG, Flt: 0x3f011300, dl));
6064 } else if (LimitFloatPrecision <= 12) {
6065 // For floating-point precision of 12:
6066 //
6067 // Log10ofMantissa =
6068 // -0.64831180f +
6069 // (0.91751397f +
6070 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
6071 //
6072 // error 0.00019228036, which is better than 12 bits
6073 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
6074 N2: getF32Constant(DAG, Flt: 0x3d431f31, dl));
6075 SDValue t1 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t0,
6076 N2: getF32Constant(DAG, Flt: 0x3ea21fb2, dl));
6077 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
6078 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
6079 N2: getF32Constant(DAG, Flt: 0x3f6ae232, dl));
6080 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
6081 Log10ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t4,
6082 N2: getF32Constant(DAG, Flt: 0x3f25f7c3, dl));
6083 } else { // LimitFloatPrecision <= 18
6084 // For floating-point precision of 18:
6085 //
6086 // Log10ofMantissa =
6087 // -0.84299375f +
6088 // (1.5327582f +
6089 // (-1.0688956f +
6090 // (0.49102474f +
6091 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
6092 //
6093 // error 0.0000037995730, which is better than 18 bits
6094 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
6095 N2: getF32Constant(DAG, Flt: 0x3c5d51ce, dl));
6096 SDValue t1 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t0,
6097 N2: getF32Constant(DAG, Flt: 0x3e00685a, dl));
6098 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
6099 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
6100 N2: getF32Constant(DAG, Flt: 0x3efb6798, dl));
6101 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
6102 SDValue t5 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t4,
6103 N2: getF32Constant(DAG, Flt: 0x3f88d192, dl));
6104 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
6105 SDValue t7 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t6,
6106 N2: getF32Constant(DAG, Flt: 0x3fc4316c, dl));
6107 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
6108 Log10ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t8,
6109 N2: getF32Constant(DAG, Flt: 0x3f57ce70, dl));
6110 }
6111
6112 return DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: LogOfExponent, N2: Log10ofMantissa);
6113 }
6114
6115 // No special expansion.
6116 return DAG.getNode(Opcode: ISD::FLOG10, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
6117}
6118
6119/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
6120/// limited-precision mode.
6121static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
6122 const TargetLowering &TLI, SDNodeFlags Flags) {
6123 if (Op.getValueType() == MVT::f32 &&
6124 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
6125 return getLimitedPrecisionExp2(t0: Op, dl, DAG);
6126
6127 // No special expansion.
6128 return DAG.getNode(Opcode: ISD::FEXP2, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
6129}
6130
6131/// visitPow - Lower a pow intrinsic. Handles the special sequences for
6132/// limited-precision mode with x == 10.0f.
6133static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
6134 SelectionDAG &DAG, const TargetLowering &TLI,
6135 SDNodeFlags Flags) {
6136 bool IsExp10 = false;
6137 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
6138 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
6139 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(Val&: LHS)) {
6140 APFloat Ten(10.0f);
6141 IsExp10 = LHSC->isExactlyValue(V: Ten);
6142 }
6143 }
6144
6145 // TODO: What fast-math-flags should be set on the FMUL node?
6146 if (IsExp10) {
6147 // Put the exponent in the right bit position for later addition to the
6148 // final result:
6149 //
6150 // #define LOG2OF10 3.3219281f
6151 // t0 = Op * LOG2OF10;
6152 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: RHS,
6153 N2: getF32Constant(DAG, Flt: 0x40549a78, dl));
6154 return getLimitedPrecisionExp2(t0, dl, DAG);
6155 }
6156
6157 // No special expansion.
6158 return DAG.getNode(Opcode: ISD::FPOW, DL: dl, VT: LHS.getValueType(), N1: LHS, N2: RHS, Flags);
6159}
6160
6161/// ExpandPowI - Expand a llvm.powi intrinsic.
6162static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
6163 SelectionDAG &DAG) {
6164 // If RHS is a constant, we can expand this out to a multiplication tree if
6165 // it's beneficial on the target, otherwise we end up lowering to a call to
6166 // __powidf2 (for example).
6167 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Val&: RHS)) {
6168 unsigned Val = RHSC->getSExtValue();
6169
6170 // powi(x, 0) -> 1.0
6171 if (Val == 0)
6172 return DAG.getConstantFP(Val: 1.0, DL, VT: LHS.getValueType());
6173
6174 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
6175 Exponent: Val, OptForSize: DAG.shouldOptForSize())) {
6176 // Get the exponent as a positive value.
6177 if ((int)Val < 0)
6178 Val = -Val;
6179 // We use the simple binary decomposition method to generate the multiply
6180 // sequence. There are more optimal ways to do this (for example,
6181 // powi(x,15) generates one more multiply than it should), but this has
6182 // the benefit of being both really simple and much better than a libcall.
6183 SDValue Res; // Logically starts equal to 1.0
6184 SDValue CurSquare = LHS;
6185 // TODO: Intrinsics should have fast-math-flags that propagate to these
6186 // nodes.
6187 while (Val) {
6188 if (Val & 1) {
6189 if (Res.getNode())
6190 Res =
6191 DAG.getNode(Opcode: ISD::FMUL, DL, VT: Res.getValueType(), N1: Res, N2: CurSquare);
6192 else
6193 Res = CurSquare; // 1.0*CurSquare.
6194 }
6195
6196 CurSquare = DAG.getNode(Opcode: ISD::FMUL, DL, VT: CurSquare.getValueType(),
6197 N1: CurSquare, N2: CurSquare);
6198 Val >>= 1;
6199 }
6200
6201 // If the original was negative, invert the result, producing 1/(x*x*x).
6202 if (RHSC->getSExtValue() < 0)
6203 Res = DAG.getNode(Opcode: ISD::FDIV, DL, VT: LHS.getValueType(),
6204 N1: DAG.getConstantFP(Val: 1.0, DL, VT: LHS.getValueType()), N2: Res);
6205 return Res;
6206 }
6207 }
6208
6209 // Otherwise, expand to a libcall.
6210 return DAG.getNode(Opcode: ISD::FPOWI, DL, VT: LHS.getValueType(), N1: LHS, N2: RHS);
6211}
6212
6213static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
6214 SDValue LHS, SDValue RHS, SDValue Scale,
6215 SelectionDAG &DAG, const TargetLowering &TLI) {
6216 EVT VT = LHS.getValueType();
6217 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
6218 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
6219 LLVMContext &Ctx = *DAG.getContext();
6220
6221 // If the type is legal but the operation isn't, this node might survive all
6222 // the way to operation legalization. If we end up there and we do not have
6223 // the ability to widen the type (if VT*2 is not legal), we cannot expand the
6224 // node.
6225
6226 // Coax the legalizer into expanding the node during type legalization instead
6227 // by bumping the size by one bit. This will force it to Promote, enabling the
6228 // early expansion and avoiding the need to expand later.
6229
6230 // We don't have to do this if Scale is 0; that can always be expanded, unless
6231 // it's a saturating signed operation. Those can experience true integer
6232 // division overflow, a case which we must avoid.
6233
6234 // FIXME: We wouldn't have to do this (or any of the early
6235 // expansion/promotion) if it was possible to expand a libcall of an
6236 // illegal type during operation legalization. But it's not, so things
6237 // get a bit hacky.
6238 unsigned ScaleInt = Scale->getAsZExtVal();
6239 if ((ScaleInt > 0 || (Saturating && Signed)) &&
6240 (TLI.isTypeLegal(VT) ||
6241 (VT.isVector() && TLI.isTypeLegal(VT: VT.getVectorElementType())))) {
6242 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
6243 Op: Opcode, VT, Scale: ScaleInt);
6244 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
6245 EVT PromVT;
6246 if (VT.isScalarInteger())
6247 PromVT = EVT::getIntegerVT(Context&: Ctx, BitWidth: VT.getSizeInBits() + 1);
6248 else if (VT.isVector()) {
6249 PromVT = VT.getVectorElementType();
6250 PromVT = EVT::getIntegerVT(Context&: Ctx, BitWidth: PromVT.getSizeInBits() + 1);
6251 PromVT = EVT::getVectorVT(Context&: Ctx, VT: PromVT, EC: VT.getVectorElementCount());
6252 } else
6253 llvm_unreachable("Wrong VT for DIVFIX?");
6254 LHS = DAG.getExtOrTrunc(IsSigned: Signed, Op: LHS, DL, VT: PromVT);
6255 RHS = DAG.getExtOrTrunc(IsSigned: Signed, Op: RHS, DL, VT: PromVT);
6256 EVT ShiftTy = TLI.getShiftAmountTy(LHSTy: PromVT, DL: DAG.getDataLayout());
6257 // For saturating operations, we need to shift up the LHS to get the
6258 // proper saturation width, and then shift down again afterwards.
6259 if (Saturating)
6260 LHS = DAG.getNode(Opcode: ISD::SHL, DL, VT: PromVT, N1: LHS,
6261 N2: DAG.getConstant(Val: 1, DL, VT: ShiftTy));
6262 SDValue Res = DAG.getNode(Opcode, DL, VT: PromVT, N1: LHS, N2: RHS, N3: Scale);
6263 if (Saturating)
6264 Res = DAG.getNode(Opcode: Signed ? ISD::SRA : ISD::SRL, DL, VT: PromVT, N1: Res,
6265 N2: DAG.getConstant(Val: 1, DL, VT: ShiftTy));
6266 return DAG.getZExtOrTrunc(Op: Res, DL, VT);
6267 }
6268 }
6269
6270 return DAG.getNode(Opcode, DL, VT, N1: LHS, N2: RHS, N3: Scale);
6271}
6272
6273// getUnderlyingArgRegs - Find underlying registers used for a truncated,
6274// bitcasted, or split argument. Returns a list of <Register, size in bits>
6275static void
6276getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
6277 const SDValue &N) {
6278 switch (N.getOpcode()) {
6279 case ISD::CopyFromReg: {
6280 SDValue Op = N.getOperand(i: 1);
6281 Regs.emplace_back(Args: cast<RegisterSDNode>(Val&: Op)->getReg(),
6282 Args: Op.getValueType().getSizeInBits());
6283 return;
6284 }
6285 case ISD::BITCAST:
6286 case ISD::AssertZext:
6287 case ISD::AssertSext:
6288 case ISD::TRUNCATE:
6289 getUnderlyingArgRegs(Regs, N: N.getOperand(i: 0));
6290 return;
6291 case ISD::BUILD_PAIR:
6292 case ISD::BUILD_VECTOR:
6293 case ISD::CONCAT_VECTORS:
6294 for (SDValue Op : N->op_values())
6295 getUnderlyingArgRegs(Regs, N: Op);
6296 return;
6297 default:
6298 return;
6299 }
6300}
6301
6302/// If the DbgValueInst is a dbg_value of a function argument, create the
6303/// corresponding DBG_VALUE machine instruction for it now. At the end of
6304/// instruction selection, they will be inserted to the entry BB.
6305/// We don't currently support this for variadic dbg_values, as they shouldn't
6306/// appear for function arguments or in the prologue.
6307bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6308 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6309 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6310 const Argument *Arg = dyn_cast<Argument>(Val: V);
6311 if (!Arg)
6312 return false;
6313
6314 MachineFunction &MF = DAG.getMachineFunction();
6315 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6316
6317 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6318 // we've been asked to pursue.
6319 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6320 bool Indirect) {
6321 if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6322 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6323 // pointing at the VReg, which will be patched up later.
6324 auto &Inst = TII->get(Opcode: TargetOpcode::DBG_INSTR_REF);
6325 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
6326 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6327 /* isKill */ false, /* isDead */ false,
6328 /* isUndef */ false, /* isEarlyClobber */ false,
6329 /* SubReg */ 0, /* isDebug */ true)});
6330
6331 auto *NewDIExpr = FragExpr;
6332 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6333 // the DIExpression.
6334 if (Indirect)
6335 NewDIExpr = DIExpression::prepend(Expr: FragExpr, Flags: DIExpression::DerefBefore);
6336 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6337 NewDIExpr = DIExpression::prependOpcodes(Expr: NewDIExpr, Ops);
6338 return BuildMI(MF, DL, MCID: Inst, IsIndirect: false, MOs, Variable, Expr: NewDIExpr);
6339 } else {
6340 // Create a completely standard DBG_VALUE.
6341 auto &Inst = TII->get(Opcode: TargetOpcode::DBG_VALUE);
6342 return BuildMI(MF, DL, MCID: Inst, IsIndirect: Indirect, Reg, Variable, Expr: FragExpr);
6343 }
6344 };
6345
6346 if (Kind == FuncArgumentDbgValueKind::Value) {
6347 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6348 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6349 // the entry block.
6350 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6351 if (!IsInEntryBlock)
6352 return false;
6353
6354 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6355 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6356 // variable that also is a param.
6357 //
6358 // Although, if we are at the top of the entry block already, we can still
6359 // emit using ArgDbgValue. This might catch some situations when the
6360 // dbg.value refers to an argument that isn't used in the entry block, so
6361 // any CopyToReg node would be optimized out and the only way to express
6362 // this DBG_VALUE is by using the physical reg (or FI) as done in this
6363 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
6364 // we should only emit as ArgDbgValue if the Variable is an argument to the
6365 // current function, and the dbg.value intrinsic is found in the entry
6366 // block.
6367 bool VariableIsFunctionInputArg = Variable->isParameter() &&
6368 !DL->getInlinedAt();
6369 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6370 if (!IsInPrologue && !VariableIsFunctionInputArg)
6371 return false;
6372
6373 // Here we assume that a function argument on IR level only can be used to
6374 // describe one input parameter on source level. If we for example have
6375 // source code like this
6376 //
6377 // struct A { long x, y; };
6378 // void foo(struct A a, long b) {
6379 // ...
6380 // b = a.x;
6381 // ...
6382 // }
6383 //
6384 // and IR like this
6385 //
6386 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
6387 // entry:
6388 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6389 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6390 // call void @llvm.dbg.value(metadata i32 %b, "b",
6391 // ...
6392 // call void @llvm.dbg.value(metadata i32 %a1, "b"
6393 // ...
6394 //
6395 // then the last dbg.value is describing a parameter "b" using a value that
6396 // is an argument. But since we already has used %a1 to describe a parameter
6397 // we should not handle that last dbg.value here (that would result in an
6398 // incorrect hoisting of the DBG_VALUE to the function entry).
6399 // Notice that we allow one dbg.value per IR level argument, to accommodate
6400 // for the situation with fragments above.
6401 // If there is no node for the value being handled, we return true to skip
6402 // the normal generation of debug info, as it would kill existing debug
6403 // info for the parameter in case of duplicates.
6404 if (VariableIsFunctionInputArg) {
6405 unsigned ArgNo = Arg->getArgNo();
6406 if (ArgNo >= FuncInfo.DescribedArgs.size())
6407 FuncInfo.DescribedArgs.resize(N: ArgNo + 1, t: false);
6408 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(Idx: ArgNo))
6409 return !NodeMap[V].getNode();
6410 FuncInfo.DescribedArgs.set(ArgNo);
6411 }
6412 }
6413
6414 bool IsIndirect = false;
6415 std::optional<MachineOperand> Op;
6416 // Some arguments' frame index is recorded during argument lowering.
6417 int FI = FuncInfo.getArgumentFrameIndex(A: Arg);
6418 if (FI != std::numeric_limits<int>::max())
6419 Op = MachineOperand::CreateFI(Idx: FI);
6420
6421 SmallVector<std::pair<Register, TypeSize>, 8> ArgRegsAndSizes;
6422 if (!Op && N.getNode()) {
6423 getUnderlyingArgRegs(Regs&: ArgRegsAndSizes, N);
6424 Register Reg;
6425 if (ArgRegsAndSizes.size() == 1)
6426 Reg = ArgRegsAndSizes.front().first;
6427
6428 if (Reg && Reg.isVirtual()) {
6429 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6430 Register PR = RegInfo.getLiveInPhysReg(VReg: Reg);
6431 if (PR)
6432 Reg = PR;
6433 }
6434 if (Reg) {
6435 Op = MachineOperand::CreateReg(Reg, isDef: false);
6436 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6437 }
6438 }
6439
6440 if (!Op && N.getNode()) {
6441 // Check if frame index is available.
6442 SDValue LCandidate = peekThroughBitcasts(V: N);
6443 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(Val: LCandidate.getNode()))
6444 if (FrameIndexSDNode *FINode =
6445 dyn_cast<FrameIndexSDNode>(Val: LNode->getBasePtr().getNode()))
6446 Op = MachineOperand::CreateFI(Idx: FINode->getIndex());
6447 }
6448
6449 if (!Op) {
6450 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6451 auto splitMultiRegDbgValue =
6452 [&](ArrayRef<std::pair<Register, TypeSize>> SplitRegs) -> bool {
6453 unsigned Offset = 0;
6454 for (const auto &[Reg, RegSizeInBits] : SplitRegs) {
6455 // FIXME: Scalable sizes are not supported in fragment expressions.
6456 if (RegSizeInBits.isScalable())
6457 return false;
6458
6459 // If the expression is already a fragment, the current register
6460 // offset+size might extend beyond the fragment. In this case, only
6461 // the register bits that are inside the fragment are relevant.
6462 int RegFragmentSizeInBits = RegSizeInBits.getFixedValue();
6463 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6464 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6465 // The register is entirely outside the expression fragment,
6466 // so is irrelevant for debug info.
6467 if (Offset >= ExprFragmentSizeInBits)
6468 break;
6469 // The register is partially outside the expression fragment, only
6470 // the low bits within the fragment are relevant for debug info.
6471 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6472 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6473 }
6474 }
6475
6476 auto FragmentExpr = DIExpression::createFragmentExpression(
6477 Expr, OffsetInBits: Offset, SizeInBits: RegFragmentSizeInBits);
6478 Offset += RegSizeInBits.getFixedValue();
6479 // If a valid fragment expression cannot be created, the variable's
6480 // correct value cannot be determined and so it is set as poison.
6481 if (!FragmentExpr) {
6482 SDDbgValue *SDV = DAG.getConstantDbgValue(
6483 Var: Variable, Expr, C: PoisonValue::get(T: V->getType()), DL, O: SDNodeOrder);
6484 DAG.AddDbgValue(DB: SDV, isParameter: false);
6485 continue;
6486 }
6487 MachineInstr *NewMI = MakeVRegDbgValue(
6488 Reg, *FragmentExpr, Kind != FuncArgumentDbgValueKind::Value);
6489 FuncInfo.ArgDbgValues.push_back(Elt: NewMI);
6490 }
6491
6492 return true;
6493 };
6494
6495 // Check if ValueMap has reg number.
6496 DenseMap<const Value *, Register>::const_iterator
6497 VMI = FuncInfo.ValueMap.find(Val: V);
6498 if (VMI != FuncInfo.ValueMap.end()) {
6499 const auto &TLI = DAG.getTargetLoweringInfo();
6500 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6501 V->getType(), std::nullopt);
6502 if (RFV.occupiesMultipleRegs())
6503 return splitMultiRegDbgValue(RFV.getRegsAndSizes());
6504
6505 Op = MachineOperand::CreateReg(Reg: VMI->second, isDef: false);
6506 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6507 } else if (ArgRegsAndSizes.size() > 1) {
6508 // This was split due to the calling convention, and no virtual register
6509 // mapping exists for the value.
6510 return splitMultiRegDbgValue(ArgRegsAndSizes);
6511 }
6512 }
6513
6514 if (!Op)
6515 return false;
6516
6517 assert(Variable->isValidLocationForIntrinsic(DL) &&
6518 "Expected inlined-at fields to agree");
6519 MachineInstr *NewMI = nullptr;
6520
6521 if (Op->isReg())
6522 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6523 else
6524 NewMI = BuildMI(MF, DL, MCID: TII->get(Opcode: TargetOpcode::DBG_VALUE), IsIndirect: true, MOs: *Op,
6525 Variable, Expr);
6526
6527 // Otherwise, use ArgDbgValues.
6528 FuncInfo.ArgDbgValues.push_back(Elt: NewMI);
6529 return true;
6530}
6531
6532/// Return the appropriate SDDbgValue based on N.
6533SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6534 DILocalVariable *Variable,
6535 DIExpression *Expr,
6536 const DebugLoc &dl,
6537 unsigned DbgSDNodeOrder) {
6538 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Val: N.getNode())) {
6539 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6540 // stack slot locations.
6541 //
6542 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6543 // debug values here after optimization:
6544 //
6545 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
6546 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6547 //
6548 // Both describe the direct values of their associated variables.
6549 return DAG.getFrameIndexDbgValue(Var: Variable, Expr, FI: FISDN->getIndex(),
6550 /*IsIndirect*/ false, DL: dl, O: DbgSDNodeOrder);
6551 }
6552 return DAG.getDbgValue(Var: Variable, Expr, N: N.getNode(), R: N.getResNo(),
6553 /*IsIndirect*/ false, DL: dl, O: DbgSDNodeOrder);
6554}
6555
6556static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6557 switch (Intrinsic) {
6558 case Intrinsic::smul_fix:
6559 return ISD::SMULFIX;
6560 case Intrinsic::umul_fix:
6561 return ISD::UMULFIX;
6562 case Intrinsic::smul_fix_sat:
6563 return ISD::SMULFIXSAT;
6564 case Intrinsic::umul_fix_sat:
6565 return ISD::UMULFIXSAT;
6566 case Intrinsic::sdiv_fix:
6567 return ISD::SDIVFIX;
6568 case Intrinsic::udiv_fix:
6569 return ISD::UDIVFIX;
6570 case Intrinsic::sdiv_fix_sat:
6571 return ISD::SDIVFIXSAT;
6572 case Intrinsic::udiv_fix_sat:
6573 return ISD::UDIVFIXSAT;
6574 default:
6575 llvm_unreachable("Unhandled fixed point intrinsic");
6576 }
6577}
6578
6579/// Given a @llvm.call.preallocated.setup, return the corresponding
6580/// preallocated call.
6581static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6582 assert(cast<CallBase>(PreallocatedSetup)
6583 ->getCalledFunction()
6584 ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6585 "expected call_preallocated_setup Value");
6586 for (const auto *U : PreallocatedSetup->users()) {
6587 auto *UseCall = cast<CallBase>(Val: U);
6588 const Function *Fn = UseCall->getCalledFunction();
6589 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6590 return UseCall;
6591 }
6592 }
6593 llvm_unreachable("expected corresponding call to preallocated setup/arg");
6594}
6595
6596/// If DI is a debug value with an EntryValue expression, lower it using the
6597/// corresponding physical register of the associated Argument value
6598/// (guaranteed to exist by the verifier).
6599bool SelectionDAGBuilder::visitEntryValueDbgValue(
6600 ArrayRef<const Value *> Values, DILocalVariable *Variable,
6601 DIExpression *Expr, DebugLoc DbgLoc) {
6602 if (!Expr->isEntryValue() || !hasSingleElement(C&: Values))
6603 return false;
6604
6605 // These properties are guaranteed by the verifier.
6606 const Argument *Arg = cast<Argument>(Val: Values[0]);
6607 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6608
6609 auto ArgIt = FuncInfo.ValueMap.find(Val: Arg);
6610 if (ArgIt == FuncInfo.ValueMap.end()) {
6611 LLVM_DEBUG(
6612 dbgs() << "Dropping dbg.value: expression is entry_value but "
6613 "couldn't find an associated register for the Argument\n");
6614 return true;
6615 }
6616 Register ArgVReg = ArgIt->getSecond();
6617
6618 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6619 if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6620 SDDbgValue *SDV = DAG.getVRegDbgValue(
6621 Var: Variable, Expr, VReg: PhysReg, IsIndirect: false /*IsIndidrect*/, DL: DbgLoc, O: SDNodeOrder);
6622 DAG.AddDbgValue(DB: SDV, isParameter: false /*treat as dbg.declare byval parameter*/);
6623 return true;
6624 }
6625 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6626 "couldn't find a physical register\n");
6627 return true;
6628}
6629
6630/// Lower the call to the specified intrinsic function.
6631void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6632 unsigned Intrinsic) {
6633 SDLoc sdl = getCurSDLoc();
6634 switch (Intrinsic) {
6635 case Intrinsic::experimental_convergence_anchor:
6636 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERGENCECTRL_ANCHOR, DL: sdl, VT: MVT::Untyped));
6637 break;
6638 case Intrinsic::experimental_convergence_entry:
6639 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERGENCECTRL_ENTRY, DL: sdl, VT: MVT::Untyped));
6640 break;
6641 case Intrinsic::experimental_convergence_loop: {
6642 auto Bundle = I.getOperandBundle(ID: LLVMContext::OB_convergencectrl);
6643 auto *Token = Bundle->Inputs[0].get();
6644 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERGENCECTRL_LOOP, DL: sdl, VT: MVT::Untyped,
6645 Operand: getValue(V: Token)));
6646 break;
6647 }
6648 }
6649}
6650
6651void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6652 unsigned IntrinsicID) {
6653 // For now, we're only lowering an 'add' histogram.
6654 // We can add others later, e.g. saturating adds, min/max.
6655 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6656 "Tried to lower unsupported histogram type");
6657 SDLoc sdl = getCurSDLoc();
6658 Value *Ptr = I.getOperand(i_nocapture: 0);
6659 SDValue Inc = getValue(V: I.getOperand(i_nocapture: 1));
6660 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 2));
6661
6662 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6663 DataLayout TargetDL = DAG.getDataLayout();
6664 EVT VT = Inc.getValueType();
6665 Align Alignment = DAG.getEVTAlign(MemoryVT: VT);
6666
6667 const MDNode *Ranges = getRangeMetadata(I);
6668
6669 SDValue Root = DAG.getRoot();
6670 SDValue Base;
6671 SDValue Index;
6672 SDValue Scale;
6673 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, SDB: this,
6674 CurBB: I.getParent(), ElemSize: VT.getScalarStoreSize());
6675
6676 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6677
6678 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6679 PtrInfo: MachinePointerInfo(AS),
6680 F: MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6681 Size: MemoryLocation::UnknownSize, BaseAlignment: Alignment,
6682 Metadata: MMOMetadata(I.getAAMetadata(), Ranges));
6683
6684 if (!UniformBase) {
6685 Base = DAG.getConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
6686 Index = getValue(V: Ptr);
6687 Scale =
6688 DAG.getTargetConstant(Val: 1, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
6689 }
6690
6691 EVT IdxVT = Index.getValueType();
6692
6693 // Avoid using e.g. i32 as index type when the increment must be performed
6694 // on i64's.
6695 bool MustExtendIndex = VT.getScalarSizeInBits() > IdxVT.getScalarSizeInBits();
6696 EVT EltTy = MustExtendIndex ? VT : IdxVT.getVectorElementType();
6697 if (MustExtendIndex || TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
6698 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
6699 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: sdl, VT: NewIdxVT, Operand: Index);
6700 }
6701
6702 SDValue ID = DAG.getTargetConstant(Val: IntrinsicID, DL: sdl, VT: MVT::i32);
6703
6704 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6705 SDValue Histogram = DAG.getMaskedHistogram(VTs: DAG.getVTList(VT: MVT::Other), MemVT: VT, dl: sdl,
6706 Ops, MMO, IndexType: ISD::SIGNED_SCALED);
6707
6708 setValue(V: &I, NewN: Histogram);
6709 DAG.setRoot(Histogram);
6710}
6711
6712void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6713 unsigned Intrinsic) {
6714 assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6715 "Tried lowering invalid vector extract last");
6716 SDLoc sdl = getCurSDLoc();
6717 const DataLayout &Layout = DAG.getDataLayout();
6718 SDValue Data = getValue(V: I.getOperand(i_nocapture: 0));
6719 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 1));
6720
6721 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6722 EVT ResVT = TLI.getValueType(DL: Layout, Ty: I.getType());
6723
6724 EVT ExtVT = TLI.getVectorIdxTy(DL: Layout);
6725 SDValue Idx = DAG.getNode(Opcode: ISD::VECTOR_FIND_LAST_ACTIVE, DL: sdl, VT: ExtVT, Operand: Mask);
6726 SDValue Result = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: sdl, VT: ResVT, N1: Data, N2: Idx);
6727
6728 Value *Default = I.getOperand(i_nocapture: 2);
6729 if (!isa<PoisonValue>(Val: Default) && !isa<UndefValue>(Val: Default)) {
6730 SDValue PassThru = getValue(V: Default);
6731 EVT BoolVT = Mask.getValueType().getScalarType();
6732 SDValue AnyActive = DAG.getNode(Opcode: ISD::VECREDUCE_OR, DL: sdl, VT: BoolVT, Operand: Mask);
6733 Result = DAG.getSelect(DL: sdl, VT: ResVT, Cond: AnyActive, LHS: Result, RHS: PassThru);
6734 }
6735
6736 setValue(V: &I, NewN: Result);
6737}
6738
6739/// Lower the call to the specified intrinsic function.
6740void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6741 unsigned Intrinsic) {
6742 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6743 SDLoc sdl = getCurSDLoc();
6744 DebugLoc dl = getCurDebugLoc();
6745 SDValue Res;
6746
6747 SDNodeFlags Flags;
6748 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
6749 Flags.copyFMF(FPMO: *FPOp);
6750
6751 switch (Intrinsic) {
6752 default:
6753 // By default, turn this into a target intrinsic node.
6754 visitTargetIntrinsic(I, Intrinsic);
6755 return;
6756 case Intrinsic::vscale: {
6757 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
6758 setValue(V: &I, NewN: DAG.getVScale(DL: sdl, VT, MulImm: APInt(VT.getSizeInBits(), 1)));
6759 return;
6760 }
6761 case Intrinsic::vastart: visitVAStart(I); return;
6762 case Intrinsic::vaend: visitVAEnd(I); return;
6763 case Intrinsic::vacopy: visitVACopy(I); return;
6764 case Intrinsic::returnaddress:
6765 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::RETURNADDR, DL: sdl,
6766 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
6767 Operand: getValue(V: I.getArgOperand(i: 0))));
6768 return;
6769 case Intrinsic::addressofreturnaddress:
6770 setValue(V: &I,
6771 NewN: DAG.getNode(Opcode: ISD::ADDROFRETURNADDR, DL: sdl,
6772 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType())));
6773 return;
6774 case Intrinsic::sponentry:
6775 setValue(V: &I,
6776 NewN: DAG.getNode(Opcode: ISD::SPONENTRY, DL: sdl,
6777 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType())));
6778 return;
6779 case Intrinsic::frameaddress:
6780 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FRAMEADDR, DL: sdl,
6781 VT: TLI.getFrameIndexTy(DL: DAG.getDataLayout()),
6782 Operand: getValue(V: I.getArgOperand(i: 0))));
6783 return;
6784 case Intrinsic::read_volatile_register:
6785 case Intrinsic::read_register: {
6786 Value *Reg = I.getArgOperand(i: 0);
6787 SDValue Chain = getRoot();
6788 SDValue RegName =
6789 DAG.getMDNode(MD: cast<MDNode>(Val: cast<MetadataAsValue>(Val: Reg)->getMetadata()));
6790 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
6791 Res = DAG.getNode(Opcode: ISD::READ_REGISTER, DL: sdl,
6792 VTList: DAG.getVTList(VT1: VT, VT2: MVT::Other), N1: Chain, N2: RegName);
6793 setValue(V: &I, NewN: Res);
6794 DAG.setRoot(Res.getValue(R: 1));
6795 return;
6796 }
6797 case Intrinsic::write_register: {
6798 Value *Reg = I.getArgOperand(i: 0);
6799 Value *RegValue = I.getArgOperand(i: 1);
6800 SDValue Chain = getRoot();
6801 SDValue RegName =
6802 DAG.getMDNode(MD: cast<MDNode>(Val: cast<MetadataAsValue>(Val: Reg)->getMetadata()));
6803 DAG.setRoot(DAG.getNode(Opcode: ISD::WRITE_REGISTER, DL: sdl, VT: MVT::Other, N1: Chain,
6804 N2: RegName, N3: getValue(V: RegValue)));
6805 return;
6806 }
6807 case Intrinsic::write_volatile_register: {
6808 Value *Reg = I.getArgOperand(i: 0);
6809 Value *RegValue = I.getArgOperand(i: 1);
6810 SDValue Chain = getRoot();
6811 const MDNode *MD = cast<MDNode>(Val: cast<MetadataAsValue>(Val: Reg)->getMetadata());
6812 SDValue RegName = DAG.getMDNode(MD);
6813 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: RegValue->getType());
6814 SDValue WriteChain = DAG.getNode(Opcode: ISD::WRITE_REGISTER, DL: sdl, VT: MVT::Other,
6815 N1: Chain, N2: RegName, N3: getValue(V: RegValue));
6816 // FAKE_USE of the physical register marks it live after the WRITE_REGISTER,
6817 // preventing the backend from dead-eliminating the write. This is
6818 // preferred over READ_REGISTER, which would emit extra register copies
6819 // (e.g. fmov xN, dN for FP/SIMD registers).
6820 const MDString *RegStr = cast<MDString>(Val: MD->getOperand(I: 0));
6821 LLT Ty = VT.isSimple() ? getLLTForMVT(Ty: VT.getSimpleVT()) : LLT();
6822 const MachineFunction &MF = DAG.getMachineFunction();
6823 Register PhysReg =
6824 TLI.getRegisterByName(RegName: RegStr->getString().data(), Ty, MF);
6825 if (PhysReg.isValid()) {
6826 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6827 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg: PhysReg);
6828 MVT RegVT = *TRI->legalclasstypes_begin(RC: *RC);
6829 DAG.setRoot(DAG.getNode(Opcode: ISD::FAKE_USE, DL: sdl, VT: MVT::Other,
6830 Ops: {WriteChain, DAG.getRegister(Reg: PhysReg, VT: RegVT)}));
6831 } else {
6832 DAG.setRoot(WriteChain);
6833 }
6834 return;
6835 }
6836 case Intrinsic::memcpy:
6837 case Intrinsic::memcpy_inline: {
6838 const auto &MCI = cast<MemCpyInst>(Val: I);
6839 SDValue Dst = getValue(V: I.getArgOperand(i: 0));
6840 SDValue Src = getValue(V: I.getArgOperand(i: 1));
6841 SDValue Size = getValue(V: I.getArgOperand(i: 2));
6842 assert((!MCI.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6843 "memcpy_inline needs constant size");
6844 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6845 Align DstAlign = MCI.getDestAlign().valueOrOne();
6846 Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6847 bool isVol = MCI.isVolatile();
6848 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6849 SDValue MC = DAG.getMemcpy(Chain: Root, dl: sdl, Dst, Src, Size, DstAlign, SrcAlign,
6850 isVol, AlwaysInline: MCI.isForceInlined(), CI: &I, OverrideTailCall: std::nullopt,
6851 DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
6852 SrcPtrInfo: MachinePointerInfo(I.getArgOperand(i: 1)),
6853 AAInfo: I.getAAMetadata(), BatchAA);
6854 updateDAGForMaybeTailCall(MaybeTC: MC);
6855 return;
6856 }
6857 case Intrinsic::memset:
6858 case Intrinsic::memset_inline: {
6859 const auto &MSII = cast<MemSetInst>(Val: I);
6860 SDValue Dst = getValue(V: I.getArgOperand(i: 0));
6861 SDValue Value = getValue(V: I.getArgOperand(i: 1));
6862 SDValue Size = getValue(V: I.getArgOperand(i: 2));
6863 assert((!MSII.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6864 "memset_inline needs constant size");
6865 // @llvm.memset defines 0 and 1 to both mean no alignment.
6866 Align DstAlign = MSII.getDestAlign().valueOrOne();
6867 bool isVol = MSII.isVolatile();
6868 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6869 SDValue MC = DAG.getMemset(
6870 Chain: Root, dl: sdl, Dst, Src: Value, Size, Alignment: DstAlign, isVol, AlwaysInline: MSII.isForceInlined(),
6871 CI: &I, DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)), AAInfo: I.getAAMetadata());
6872 updateDAGForMaybeTailCall(MaybeTC: MC);
6873 return;
6874 }
6875 case Intrinsic::memmove: {
6876 const auto &MMI = cast<MemMoveInst>(Val: I);
6877 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
6878 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
6879 SDValue Op3 = getValue(V: I.getArgOperand(i: 2));
6880 // @llvm.memmove defines 0 and 1 to both mean no alignment.
6881 Align DstAlign = MMI.getDestAlign().valueOrOne();
6882 Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6883 bool isVol = MMI.isVolatile();
6884 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6885 SDValue MM = DAG.getMemmove(
6886 Chain: Root, dl: sdl, Dst: Op1, Src: Op2, Size: Op3, DstAlign, SrcAlign, isVol, CI: &I,
6887 /* OverrideTailCall */ std::nullopt,
6888 DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
6889 SrcPtrInfo: MachinePointerInfo(I.getArgOperand(i: 1)), AAInfo: I.getAAMetadata(), BatchAA);
6890 updateDAGForMaybeTailCall(MaybeTC: MM);
6891 return;
6892 }
6893 case Intrinsic::memcpy_element_unordered_atomic: {
6894 auto &MI = cast<AnyMemCpyInst>(Val: I);
6895 SDValue Dst = getValue(V: MI.getRawDest());
6896 SDValue Src = getValue(V: MI.getRawSource());
6897 SDValue Length = getValue(V: MI.getLength());
6898
6899 Type *LengthTy = MI.getLength()->getType();
6900 unsigned ElemSz = MI.getElementSizeInBytes();
6901 bool isTC = I.isTailCall() && isInTailCallPosition(Call: I, TM: DAG.getTarget());
6902 SDValue MC =
6903 DAG.getAtomicMemcpy(Chain: getRoot(), dl: sdl, Dst, Src, Size: Length, SizeTy: LengthTy, ElemSz,
6904 isTailCall: isTC, DstPtrInfo: MachinePointerInfo(MI.getRawDest()),
6905 SrcPtrInfo: MachinePointerInfo(MI.getRawSource()));
6906 updateDAGForMaybeTailCall(MaybeTC: MC);
6907 return;
6908 }
6909 case Intrinsic::memmove_element_unordered_atomic: {
6910 auto &MI = cast<AnyMemMoveInst>(Val: I);
6911 SDValue Dst = getValue(V: MI.getRawDest());
6912 SDValue Src = getValue(V: MI.getRawSource());
6913 SDValue Length = getValue(V: MI.getLength());
6914
6915 Type *LengthTy = MI.getLength()->getType();
6916 unsigned ElemSz = MI.getElementSizeInBytes();
6917 bool isTC = I.isTailCall() && isInTailCallPosition(Call: I, TM: DAG.getTarget());
6918 SDValue MC =
6919 DAG.getAtomicMemmove(Chain: getRoot(), dl: sdl, Dst, Src, Size: Length, SizeTy: LengthTy, ElemSz,
6920 isTailCall: isTC, DstPtrInfo: MachinePointerInfo(MI.getRawDest()),
6921 SrcPtrInfo: MachinePointerInfo(MI.getRawSource()));
6922 updateDAGForMaybeTailCall(MaybeTC: MC);
6923 return;
6924 }
6925 case Intrinsic::memset_element_unordered_atomic: {
6926 auto &MI = cast<AnyMemSetInst>(Val: I);
6927 SDValue Dst = getValue(V: MI.getRawDest());
6928 SDValue Val = getValue(V: MI.getValue());
6929 SDValue Length = getValue(V: MI.getLength());
6930
6931 Type *LengthTy = MI.getLength()->getType();
6932 unsigned ElemSz = MI.getElementSizeInBytes();
6933 bool isTC = I.isTailCall() && isInTailCallPosition(Call: I, TM: DAG.getTarget());
6934 SDValue MC =
6935 DAG.getAtomicMemset(Chain: getRoot(), dl: sdl, Dst, Value: Val, Size: Length, SizeTy: LengthTy, ElemSz,
6936 isTailCall: isTC, DstPtrInfo: MachinePointerInfo(MI.getRawDest()));
6937 updateDAGForMaybeTailCall(MaybeTC: MC);
6938 return;
6939 }
6940 case Intrinsic::call_preallocated_setup: {
6941 const CallBase *PreallocatedCall = FindPreallocatedCall(PreallocatedSetup: &I);
6942 SDValue SrcValue = DAG.getSrcValue(v: PreallocatedCall);
6943 SDValue Res = DAG.getNode(Opcode: ISD::PREALLOCATED_SETUP, DL: sdl, VT: MVT::Other,
6944 N1: getRoot(), N2: SrcValue);
6945 setValue(V: &I, NewN: Res);
6946 DAG.setRoot(Res);
6947 return;
6948 }
6949 case Intrinsic::call_preallocated_arg: {
6950 const CallBase *PreallocatedCall = FindPreallocatedCall(PreallocatedSetup: I.getOperand(i_nocapture: 0));
6951 SDValue SrcValue = DAG.getSrcValue(v: PreallocatedCall);
6952 SDValue Ops[3];
6953 Ops[0] = getRoot();
6954 Ops[1] = SrcValue;
6955 Ops[2] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 1)), DL: sdl,
6956 VT: MVT::i32); // arg index
6957 SDValue Res = DAG.getNode(
6958 Opcode: ISD::PREALLOCATED_ARG, DL: sdl,
6959 VTList: DAG.getVTList(VT1: TLI.getPointerTy(DL: DAG.getDataLayout()), VT2: MVT::Other), Ops);
6960 setValue(V: &I, NewN: Res);
6961 DAG.setRoot(Res.getValue(R: 1));
6962 return;
6963 }
6964
6965 case Intrinsic::eh_typeid_for: {
6966 // Find the type id for the given typeinfo.
6967 GlobalValue *GV = ExtractTypeInfo(V: I.getArgOperand(i: 0));
6968 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(TI: GV);
6969 Res = DAG.getConstant(Val: TypeID, DL: sdl, VT: MVT::i32);
6970 setValue(V: &I, NewN: Res);
6971 return;
6972 }
6973
6974 case Intrinsic::eh_return_i32:
6975 case Intrinsic::eh_return_i64:
6976 DAG.getMachineFunction().setCallsEHReturn(true);
6977 DAG.setRoot(DAG.getNode(Opcode: ISD::EH_RETURN, DL: sdl,
6978 VT: MVT::Other,
6979 N1: getControlRoot(),
6980 N2: getValue(V: I.getArgOperand(i: 0)),
6981 N3: getValue(V: I.getArgOperand(i: 1))));
6982 return;
6983 case Intrinsic::eh_unwind_init:
6984 DAG.getMachineFunction().setCallsUnwindInit(true);
6985 return;
6986 case Intrinsic::eh_dwarf_cfa:
6987 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::EH_DWARF_CFA, DL: sdl,
6988 VT: TLI.getPointerTy(DL: DAG.getDataLayout()),
6989 Operand: getValue(V: I.getArgOperand(i: 0))));
6990 return;
6991 case Intrinsic::eh_sjlj_callsite: {
6992 ConstantInt *CI = cast<ConstantInt>(Val: I.getArgOperand(i: 0));
6993 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6994
6995 FuncInfo.setCurrentCallSite(CI->getZExtValue());
6996 return;
6997 }
6998 case Intrinsic::eh_sjlj_functioncontext: {
6999 // Get and store the index of the function context.
7000 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7001 AllocaInst *FnCtx =
7002 cast<AllocaInst>(Val: I.getArgOperand(i: 0)->stripPointerCasts());
7003 int FI = FuncInfo.StaticAllocaMap[FnCtx];
7004 MFI.setFunctionContextIndex(FI);
7005 return;
7006 }
7007 case Intrinsic::eh_sjlj_setjmp: {
7008 SDValue Ops[2];
7009 Ops[0] = getRoot();
7010 Ops[1] = getValue(V: I.getArgOperand(i: 0));
7011 SDValue Op = DAG.getNode(Opcode: ISD::EH_SJLJ_SETJMP, DL: sdl,
7012 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::Other), Ops);
7013 setValue(V: &I, NewN: Op.getValue(R: 0));
7014 DAG.setRoot(Op.getValue(R: 1));
7015 return;
7016 }
7017 case Intrinsic::eh_sjlj_longjmp:
7018 DAG.setRoot(DAG.getNode(Opcode: ISD::EH_SJLJ_LONGJMP, DL: sdl, VT: MVT::Other,
7019 N1: getRoot(), N2: getValue(V: I.getArgOperand(i: 0))));
7020 return;
7021 case Intrinsic::eh_sjlj_setup_dispatch:
7022 DAG.setRoot(DAG.getNode(Opcode: ISD::EH_SJLJ_SETUP_DISPATCH, DL: sdl, VT: MVT::Other,
7023 Operand: getRoot()));
7024 return;
7025 case Intrinsic::masked_gather:
7026 visitMaskedGather(I);
7027 return;
7028 case Intrinsic::masked_load:
7029 visitMaskedLoad(I);
7030 return;
7031 case Intrinsic::masked_scatter:
7032 visitMaskedScatter(I);
7033 return;
7034 case Intrinsic::masked_store:
7035 visitMaskedStore(I);
7036 return;
7037 case Intrinsic::masked_expandload:
7038 visitMaskedLoad(I, IsExpanding: true /* IsExpanding */);
7039 return;
7040 case Intrinsic::masked_compressstore:
7041 visitMaskedStore(I, IsCompressing: true /* IsCompressing */);
7042 return;
7043 case Intrinsic::speculative_load:
7044 visitSpeculativeLoad(I);
7045 return;
7046 case Intrinsic::powi:
7047 setValue(V: &I, NewN: ExpandPowI(DL: sdl, LHS: getValue(V: I.getArgOperand(i: 0)),
7048 RHS: getValue(V: I.getArgOperand(i: 1)), DAG));
7049 return;
7050 case Intrinsic::log:
7051 setValue(V: &I, NewN: expandLog(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
7052 return;
7053 case Intrinsic::log2:
7054 setValue(V: &I,
7055 NewN: expandLog2(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
7056 return;
7057 case Intrinsic::log10:
7058 setValue(V: &I,
7059 NewN: expandLog10(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
7060 return;
7061 case Intrinsic::exp:
7062 setValue(V: &I, NewN: expandExp(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
7063 return;
7064 case Intrinsic::exp2:
7065 setValue(V: &I,
7066 NewN: expandExp2(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
7067 return;
7068 case Intrinsic::pow:
7069 setValue(V: &I, NewN: expandPow(dl: sdl, LHS: getValue(V: I.getArgOperand(i: 0)),
7070 RHS: getValue(V: I.getArgOperand(i: 1)), DAG, TLI, Flags));
7071 return;
7072 case Intrinsic::sqrt:
7073 case Intrinsic::fabs:
7074 case Intrinsic::sin:
7075 case Intrinsic::cos:
7076 case Intrinsic::tan:
7077 case Intrinsic::asin:
7078 case Intrinsic::acos:
7079 case Intrinsic::atan:
7080 case Intrinsic::sinh:
7081 case Intrinsic::cosh:
7082 case Intrinsic::tanh:
7083 case Intrinsic::exp10:
7084 case Intrinsic::floor:
7085 case Intrinsic::ceil:
7086 case Intrinsic::trunc:
7087 case Intrinsic::rint:
7088 case Intrinsic::nearbyint:
7089 case Intrinsic::round:
7090 case Intrinsic::roundeven:
7091 case Intrinsic::canonicalize: {
7092 unsigned Opcode;
7093 // clang-format off
7094 switch (Intrinsic) {
7095 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7096 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
7097 case Intrinsic::fabs: Opcode = ISD::FABS; break;
7098 case Intrinsic::sin: Opcode = ISD::FSIN; break;
7099 case Intrinsic::cos: Opcode = ISD::FCOS; break;
7100 case Intrinsic::tan: Opcode = ISD::FTAN; break;
7101 case Intrinsic::asin: Opcode = ISD::FASIN; break;
7102 case Intrinsic::acos: Opcode = ISD::FACOS; break;
7103 case Intrinsic::atan: Opcode = ISD::FATAN; break;
7104 case Intrinsic::sinh: Opcode = ISD::FSINH; break;
7105 case Intrinsic::cosh: Opcode = ISD::FCOSH; break;
7106 case Intrinsic::tanh: Opcode = ISD::FTANH; break;
7107 case Intrinsic::exp10: Opcode = ISD::FEXP10; break;
7108 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
7109 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
7110 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
7111 case Intrinsic::rint: Opcode = ISD::FRINT; break;
7112 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
7113 case Intrinsic::round: Opcode = ISD::FROUND; break;
7114 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
7115 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
7116 }
7117 // clang-format on
7118
7119 setValue(V: &I, NewN: DAG.getNode(Opcode, DL: sdl,
7120 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7121 Operand: getValue(V: I.getArgOperand(i: 0)), Flags));
7122 return;
7123 }
7124 case Intrinsic::atan2:
7125 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FATAN2, DL: sdl,
7126 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7127 N1: getValue(V: I.getArgOperand(i: 0)),
7128 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7129 return;
7130 case Intrinsic::lround:
7131 case Intrinsic::llround:
7132 case Intrinsic::lrint:
7133 case Intrinsic::llrint: {
7134 unsigned Opcode;
7135 // clang-format off
7136 switch (Intrinsic) {
7137 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7138 case Intrinsic::lround: Opcode = ISD::LROUND; break;
7139 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
7140 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
7141 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
7142 }
7143 // clang-format on
7144
7145 EVT RetVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7146 setValue(V: &I, NewN: DAG.getNode(Opcode, DL: sdl, VT: RetVT,
7147 Operand: getValue(V: I.getArgOperand(i: 0))));
7148 return;
7149 }
7150 case Intrinsic::minnum:
7151 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMINNUM, DL: sdl,
7152 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7153 N1: getValue(V: I.getArgOperand(i: 0)),
7154 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7155 return;
7156 case Intrinsic::maxnum:
7157 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMAXNUM, DL: sdl,
7158 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7159 N1: getValue(V: I.getArgOperand(i: 0)),
7160 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7161 return;
7162 case Intrinsic::minimum:
7163 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMINIMUM, DL: sdl,
7164 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7165 N1: getValue(V: I.getArgOperand(i: 0)),
7166 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7167 return;
7168 case Intrinsic::maximum:
7169 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMAXIMUM, DL: sdl,
7170 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7171 N1: getValue(V: I.getArgOperand(i: 0)),
7172 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7173 return;
7174 case Intrinsic::minimumnum:
7175 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMINIMUMNUM, DL: sdl,
7176 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7177 N1: getValue(V: I.getArgOperand(i: 0)),
7178 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7179 return;
7180 case Intrinsic::maximumnum:
7181 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMAXIMUMNUM, DL: sdl,
7182 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7183 N1: getValue(V: I.getArgOperand(i: 0)),
7184 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7185 return;
7186 case Intrinsic::copysign:
7187 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FCOPYSIGN, DL: sdl,
7188 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7189 N1: getValue(V: I.getArgOperand(i: 0)),
7190 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7191 return;
7192 case Intrinsic::ldexp:
7193 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FLDEXP, DL: sdl,
7194 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7195 N1: getValue(V: I.getArgOperand(i: 0)),
7196 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7197 return;
7198 case Intrinsic::modf:
7199 case Intrinsic::sincos:
7200 case Intrinsic::sincospi:
7201 case Intrinsic::frexp: {
7202 unsigned Opcode;
7203 switch (Intrinsic) {
7204 default:
7205 llvm_unreachable("unexpected intrinsic");
7206 case Intrinsic::sincos:
7207 Opcode = ISD::FSINCOS;
7208 break;
7209 case Intrinsic::sincospi:
7210 Opcode = ISD::FSINCOSPI;
7211 break;
7212 case Intrinsic::modf:
7213 Opcode = ISD::FMODF;
7214 break;
7215 case Intrinsic::frexp:
7216 Opcode = ISD::FFREXP;
7217 break;
7218 }
7219 SmallVector<EVT, 2> ValueVTs;
7220 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: I.getType(), ValueVTs);
7221 SDVTList VTs = DAG.getVTList(VTs: ValueVTs);
7222 setValue(
7223 V: &I, NewN: DAG.getNode(Opcode, DL: sdl, VTList: VTs, Ops: getValue(V: I.getArgOperand(i: 0)), Flags));
7224 return;
7225 }
7226 case Intrinsic::arithmetic_fence: {
7227 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::ARITH_FENCE, DL: sdl,
7228 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7229 Operand: getValue(V: I.getArgOperand(i: 0)), Flags));
7230 return;
7231 }
7232 case Intrinsic::fma:
7233 setValue(V: &I, NewN: DAG.getNode(
7234 Opcode: ISD::FMA, DL: sdl, VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7235 N1: getValue(V: I.getArgOperand(i: 0)), N2: getValue(V: I.getArgOperand(i: 1)),
7236 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
7237 return;
7238#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
7239 case Intrinsic::INTRINSIC:
7240#include "llvm/IR/ConstrainedOps.def"
7241 visitConstrainedFPIntrinsic(FPI: cast<ConstrainedFPIntrinsic>(Val: I));
7242 return;
7243#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7244#include "llvm/IR/VPIntrinsics.def"
7245 visitVectorPredicationIntrinsic(VPIntrin: cast<VPIntrinsic>(Val: I));
7246 return;
7247 case Intrinsic::fptrunc_round: {
7248 // Get the last argument, the metadata and convert it to an integer in the
7249 // call
7250 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 1))->getMetadata();
7251 std::optional<RoundingMode> RoundMode =
7252 convertStrToRoundingMode(cast<MDString>(Val: MD)->getString());
7253
7254 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7255
7256 // Propagate fast-math-flags from IR to node(s).
7257 SDNodeFlags Flags;
7258 Flags.copyFMF(FPMO: *cast<FPMathOperator>(Val: &I));
7259 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7260
7261 SDValue Result;
7262 Result = DAG.getNode(
7263 Opcode: ISD::FPTRUNC_ROUND, DL: sdl, VT, N1: getValue(V: I.getArgOperand(i: 0)),
7264 N2: DAG.getTargetConstant(Val: (int)*RoundMode, DL: sdl, VT: MVT::i32));
7265 setValue(V: &I, NewN: Result);
7266
7267 return;
7268 }
7269 case Intrinsic::fmuladd: {
7270 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7271 if (TLI.isFMAFasterThanFMulAndFAdd(MF: DAG.getMachineFunction(), VT)) {
7272 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMA, DL: sdl,
7273 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7274 N1: getValue(V: I.getArgOperand(i: 0)),
7275 N2: getValue(V: I.getArgOperand(i: 1)),
7276 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
7277 } else if (TLI.isOperationLegalOrCustom(Op: ISD::FMULADD, VT)) {
7278 // TODO: Support splitting the vector.
7279 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMULADD, DL: sdl,
7280 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7281 N1: getValue(V: I.getArgOperand(i: 0)),
7282 N2: getValue(V: I.getArgOperand(i: 1)),
7283 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
7284 } else {
7285 // TODO: Intrinsic calls should have fast-math-flags.
7286 SDValue Mul = DAG.getNode(
7287 Opcode: ISD::FMUL, DL: sdl, VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7288 N1: getValue(V: I.getArgOperand(i: 0)), N2: getValue(V: I.getArgOperand(i: 1)), Flags);
7289 SDValue Add = DAG.getNode(Opcode: ISD::FADD, DL: sdl,
7290 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7291 N1: Mul, N2: getValue(V: I.getArgOperand(i: 2)), Flags);
7292 setValue(V: &I, NewN: Add);
7293 }
7294 return;
7295 }
7296 case Intrinsic::fptosi_sat: {
7297 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7298 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_SINT_SAT, DL: sdl, VT,
7299 N1: getValue(V: I.getArgOperand(i: 0)),
7300 N2: DAG.getValueType(VT.getScalarType())));
7301 return;
7302 }
7303 case Intrinsic::fptoui_sat: {
7304 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7305 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_UINT_SAT, DL: sdl, VT,
7306 N1: getValue(V: I.getArgOperand(i: 0)),
7307 N2: DAG.getValueType(VT.getScalarType())));
7308 return;
7309 }
7310 case Intrinsic::convert_from_arbitrary_fp: {
7311 // Extract format metadata and convert to semantics enum.
7312 EVT DstVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7313 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 1))->getMetadata();
7314 StringRef FormatStr = cast<MDString>(Val: MD)->getString();
7315 const fltSemantics *SrcSem =
7316 APFloatBase::getArbitraryFPSemantics(Format: FormatStr);
7317 if (!SrcSem) {
7318 DAG.getContext()->emitError(
7319 ErrorStr: "convert_from_arbitrary_fp: not implemented format '" + FormatStr +
7320 "'");
7321 setValue(V: &I, NewN: DAG.getPOISON(VT: DstVT));
7322 return;
7323 }
7324 APFloatBase::Semantics SemEnum = APFloatBase::SemanticsToEnum(Sem: *SrcSem);
7325
7326 SDValue IntVal = getValue(V: I.getArgOperand(i: 0));
7327
7328 // Emit ISD::CONVERT_FROM_ARBITRARY_FP node.
7329 SDValue SemConst =
7330 DAG.getTargetConstant(Val: static_cast<int>(SemEnum), DL: sdl, VT: MVT::i32);
7331 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERT_FROM_ARBITRARY_FP, DL: sdl, VT: DstVT, N1: IntVal,
7332 N2: SemConst));
7333 return;
7334 }
7335 case Intrinsic::convert_to_arbitrary_fp: {
7336 // Extract format metadata and convert to semantics enum.
7337 EVT DstVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7338 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 1))->getMetadata();
7339 StringRef FormatStr = cast<MDString>(Val: MD)->getString();
7340 const fltSemantics *DstSem =
7341 APFloatBase::getArbitraryFPSemantics(Format: FormatStr);
7342 if (!DstSem) {
7343 DAG.getContext()->emitError(
7344 ErrorStr: "convert_to_arbitrary_fp: not implemented format '" + FormatStr +
7345 "'");
7346 setValue(V: &I, NewN: DAG.getPOISON(VT: DstVT));
7347 return;
7348 }
7349 APFloatBase::Semantics SemEnum = APFloatBase::SemanticsToEnum(Sem: *DstSem);
7350
7351 Metadata *RoundMD =
7352 cast<MetadataAsValue>(Val: I.getArgOperand(i: 2))->getMetadata();
7353 StringRef RoundStr = cast<MDString>(Val: RoundMD)->getString();
7354 std::optional<RoundingMode> RoundMode = convertStrToRoundingMode(RoundStr);
7355 assert(RoundMode && *RoundMode != RoundingMode::Dynamic &&
7356 "Dynamic rounding mode should have been rejected by the verifier");
7357
7358 uint64_t Saturate =
7359 cast<ConstantInt>(Val: I.getArgOperand(i: 3))->getZExtValue() ? 1 : 0;
7360
7361 SDValue FloatVal = getValue(V: I.getArgOperand(i: 0));
7362
7363 SDValue SemConst =
7364 DAG.getTargetConstant(Val: static_cast<int>(SemEnum), DL: sdl, VT: MVT::i32);
7365 SDValue RoundConst =
7366 DAG.getTargetConstant(Val: static_cast<int>(*RoundMode), DL: sdl, VT: MVT::i32);
7367 SDValue SatConst = DAG.getTargetConstant(Val: Saturate, DL: sdl, VT: MVT::i32);
7368 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERT_TO_ARBITRARY_FP, DL: sdl, VT: DstVT, N1: FloatVal,
7369 N2: SemConst, N3: RoundConst, N4: SatConst));
7370 return;
7371 }
7372 case Intrinsic::set_rounding:
7373 Res = DAG.getNode(Opcode: ISD::SET_ROUNDING, DL: sdl, VT: MVT::Other,
7374 Ops: {getRoot(), getValue(V: I.getArgOperand(i: 0))});
7375 setValue(V: &I, NewN: Res);
7376 DAG.setRoot(Res.getValue(R: 0));
7377 return;
7378 case Intrinsic::is_fpclass: {
7379 const DataLayout DLayout = DAG.getDataLayout();
7380 EVT DestVT = TLI.getValueType(DL: DLayout, Ty: I.getType());
7381 EVT ArgVT = TLI.getValueType(DL: DLayout, Ty: I.getArgOperand(i: 0)->getType());
7382 FPClassTest Test = static_cast<FPClassTest>(
7383 cast<ConstantInt>(Val: I.getArgOperand(i: 1))->getZExtValue());
7384 MachineFunction &MF = DAG.getMachineFunction();
7385 const Function &F = MF.getFunction();
7386 SDValue Op = getValue(V: I.getArgOperand(i: 0));
7387 SDNodeFlags Flags;
7388 Flags.setNoFPExcept(
7389 !F.getAttributes().hasFnAttr(Kind: llvm::Attribute::StrictFP));
7390 // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7391 // expansion can use illegal types. Making expansion early allows
7392 // legalizing these types prior to selection.
7393 if (!TLI.isOperationLegal(Op: ISD::IS_FPCLASS, VT: ArgVT) &&
7394 !TLI.isOperationCustom(Op: ISD::IS_FPCLASS, VT: ArgVT)) {
7395 SDValue Result = TLI.expandIS_FPCLASS(ResultVT: DestVT, Op, Test, Flags, DL: sdl, DAG);
7396 setValue(V: &I, NewN: Result);
7397 return;
7398 }
7399
7400 SDValue Check = DAG.getTargetConstant(Val: Test, DL: sdl, VT: MVT::i32);
7401 SDValue V = DAG.getNode(Opcode: ISD::IS_FPCLASS, DL: sdl, VT: DestVT, Ops: {Op, Check}, Flags);
7402 setValue(V: &I, NewN: V);
7403 return;
7404 }
7405 case Intrinsic::get_fpenv: {
7406 const DataLayout DLayout = DAG.getDataLayout();
7407 EVT EnvVT = TLI.getValueType(DL: DLayout, Ty: I.getType());
7408 Align TempAlign = DAG.getEVTAlign(MemoryVT: EnvVT);
7409 SDValue Chain = getRoot();
7410 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7411 // and temporary storage in stack.
7412 if (TLI.isOperationLegalOrCustom(Op: ISD::GET_FPENV, VT: EnvVT)) {
7413 Res = DAG.getNode(
7414 Opcode: ISD::GET_FPENV, DL: sdl,
7415 VTList: DAG.getVTList(VT1: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
7416 VT2: MVT::Other),
7417 N: Chain);
7418 } else {
7419 SDValue Temp = DAG.CreateStackTemporary(VT: EnvVT, minAlign: TempAlign.value());
7420 int SPFI = cast<FrameIndexSDNode>(Val: Temp.getNode())->getIndex();
7421 auto MPI =
7422 MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI: SPFI);
7423 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7424 PtrInfo: MPI, F: MachineMemOperand::MOStore, Size: LocationSize::beforeOrAfterPointer(),
7425 BaseAlignment: TempAlign);
7426 Chain = DAG.getGetFPEnv(Chain, dl: sdl, Ptr: Temp, MemVT: EnvVT, MMO);
7427 Res = DAG.getLoad(VT: EnvVT, dl: sdl, Chain, Ptr: Temp, PtrInfo: MPI);
7428 }
7429 setValue(V: &I, NewN: Res);
7430 DAG.setRoot(Res.getValue(R: 1));
7431 return;
7432 }
7433 case Intrinsic::set_fpenv: {
7434 const DataLayout DLayout = DAG.getDataLayout();
7435 SDValue Env = getValue(V: I.getArgOperand(i: 0));
7436 EVT EnvVT = Env.getValueType();
7437 Align TempAlign = DAG.getEVTAlign(MemoryVT: EnvVT);
7438 SDValue Chain = getRoot();
7439 // If SET_FPENV is custom or legal, use it. Otherwise use loading
7440 // environment from memory.
7441 if (TLI.isOperationLegalOrCustom(Op: ISD::SET_FPENV, VT: EnvVT)) {
7442 Chain = DAG.getNode(Opcode: ISD::SET_FPENV, DL: sdl, VT: MVT::Other, N1: Chain, N2: Env);
7443 } else {
7444 // Allocate space in stack, copy environment bits into it and use this
7445 // memory in SET_FPENV_MEM.
7446 SDValue Temp = DAG.CreateStackTemporary(VT: EnvVT, minAlign: TempAlign.value());
7447 int SPFI = cast<FrameIndexSDNode>(Val: Temp.getNode())->getIndex();
7448 auto MPI =
7449 MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI: SPFI);
7450 Chain = DAG.getStore(Chain, dl: sdl, Val: Env, Ptr: Temp, PtrInfo: MPI, Alignment: TempAlign,
7451 MMOFlags: MachineMemOperand::MOStore);
7452 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7453 PtrInfo: MPI, F: MachineMemOperand::MOLoad, Size: LocationSize::beforeOrAfterPointer(),
7454 BaseAlignment: TempAlign);
7455 Chain = DAG.getSetFPEnv(Chain, dl: sdl, Ptr: Temp, MemVT: EnvVT, MMO);
7456 }
7457 DAG.setRoot(Chain);
7458 return;
7459 }
7460 case Intrinsic::reset_fpenv:
7461 DAG.setRoot(DAG.getNode(Opcode: ISD::RESET_FPENV, DL: sdl, VT: MVT::Other, Operand: getRoot()));
7462 return;
7463 case Intrinsic::get_fpmode:
7464 Res = DAG.getNode(
7465 Opcode: ISD::GET_FPMODE, DL: sdl,
7466 VTList: DAG.getVTList(VT1: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
7467 VT2: MVT::Other),
7468 N: DAG.getRoot());
7469 setValue(V: &I, NewN: Res);
7470 DAG.setRoot(Res.getValue(R: 1));
7471 return;
7472 case Intrinsic::set_fpmode:
7473 Res = DAG.getNode(Opcode: ISD::SET_FPMODE, DL: sdl, VT: MVT::Other, N1: {DAG.getRoot()},
7474 N2: getValue(V: I.getArgOperand(i: 0)));
7475 DAG.setRoot(Res);
7476 return;
7477 case Intrinsic::reset_fpmode: {
7478 Res = DAG.getNode(Opcode: ISD::RESET_FPMODE, DL: sdl, VT: MVT::Other, Operand: getRoot());
7479 DAG.setRoot(Res);
7480 return;
7481 }
7482 case Intrinsic::pcmarker: {
7483 SDValue Tmp = getValue(V: I.getArgOperand(i: 0));
7484 DAG.setRoot(DAG.getNode(Opcode: ISD::PCMARKER, DL: sdl, VT: MVT::Other, N1: getRoot(), N2: Tmp));
7485 return;
7486 }
7487 case Intrinsic::readcyclecounter: {
7488 SDValue Op = getRoot();
7489 Res = DAG.getNode(Opcode: ISD::READCYCLECOUNTER, DL: sdl,
7490 VTList: DAG.getVTList(VT1: MVT::i64, VT2: MVT::Other), N: Op);
7491 setValue(V: &I, NewN: Res);
7492 DAG.setRoot(Res.getValue(R: 1));
7493 return;
7494 }
7495 case Intrinsic::readsteadycounter: {
7496 SDValue Op = getRoot();
7497 Res = DAG.getNode(Opcode: ISD::READSTEADYCOUNTER, DL: sdl,
7498 VTList: DAG.getVTList(VT1: MVT::i64, VT2: MVT::Other), N: Op);
7499 setValue(V: &I, NewN: Res);
7500 DAG.setRoot(Res.getValue(R: 1));
7501 return;
7502 }
7503 case Intrinsic::bitreverse:
7504 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::BITREVERSE, DL: sdl,
7505 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7506 Operand: getValue(V: I.getArgOperand(i: 0))));
7507 return;
7508 case Intrinsic::bswap:
7509 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::BSWAP, DL: sdl,
7510 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7511 Operand: getValue(V: I.getArgOperand(i: 0))));
7512 return;
7513 case Intrinsic::cttz: {
7514 SDValue Arg = getValue(V: I.getArgOperand(i: 0));
7515 ConstantInt *CI = cast<ConstantInt>(Val: I.getArgOperand(i: 1));
7516 EVT Ty = Arg.getValueType();
7517 setValue(V: &I, NewN: DAG.getNode(Opcode: CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_POISON,
7518 DL: sdl, VT: Ty, Operand: Arg));
7519 return;
7520 }
7521 case Intrinsic::ctlz: {
7522 SDValue Arg = getValue(V: I.getArgOperand(i: 0));
7523 ConstantInt *CI = cast<ConstantInt>(Val: I.getArgOperand(i: 1));
7524 EVT Ty = Arg.getValueType();
7525 setValue(V: &I, NewN: DAG.getNode(Opcode: CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_POISON,
7526 DL: sdl, VT: Ty, Operand: Arg));
7527 return;
7528 }
7529 case Intrinsic::ctpop: {
7530 SDValue Arg = getValue(V: I.getArgOperand(i: 0));
7531 EVT Ty = Arg.getValueType();
7532 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CTPOP, DL: sdl, VT: Ty, Operand: Arg));
7533 return;
7534 }
7535 case Intrinsic::fshl:
7536 case Intrinsic::fshr: {
7537 bool IsFSHL = Intrinsic == Intrinsic::fshl;
7538 SDValue X = getValue(V: I.getArgOperand(i: 0));
7539 SDValue Y = getValue(V: I.getArgOperand(i: 1));
7540 SDValue Z = getValue(V: I.getArgOperand(i: 2));
7541 EVT VT = X.getValueType();
7542
7543 if (X == Y) {
7544 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7545 setValue(V: &I, NewN: DAG.getNode(Opcode: RotateOpcode, DL: sdl, VT, N1: X, N2: Z));
7546 } else {
7547 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7548 setValue(V: &I, NewN: DAG.getNode(Opcode: FunnelOpcode, DL: sdl, VT, N1: X, N2: Y, N3: Z));
7549 }
7550 return;
7551 }
7552 case Intrinsic::clmul: {
7553 SDValue X = getValue(V: I.getArgOperand(i: 0));
7554 SDValue Y = getValue(V: I.getArgOperand(i: 1));
7555 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CLMUL, DL: sdl, VT: X.getValueType(), N1: X, N2: Y));
7556 return;
7557 }
7558 case Intrinsic::pext: {
7559 SDValue X = getValue(V: I.getArgOperand(i: 0));
7560 SDValue Y = getValue(V: I.getArgOperand(i: 1));
7561 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::PEXT, DL: sdl, VT: X.getValueType(), N1: X, N2: Y));
7562 return;
7563 }
7564 case Intrinsic::pdep: {
7565 SDValue X = getValue(V: I.getArgOperand(i: 0));
7566 SDValue Y = getValue(V: I.getArgOperand(i: 1));
7567 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::PDEP, DL: sdl, VT: X.getValueType(), N1: X, N2: Y));
7568 return;
7569 }
7570 case Intrinsic::smulh:
7571 case Intrinsic::umulh: {
7572 auto Opc = Intrinsic == Intrinsic::smulh ? ISD::MULHS : ISD::MULHU;
7573 SDValue X = getValue(V: I.getArgOperand(i: 0));
7574 SDValue Y = getValue(V: I.getArgOperand(i: 1));
7575 setValue(V: &I, NewN: DAG.getNode(Opcode: Opc, DL: sdl, VT: X.getValueType(), N1: X, N2: Y));
7576 return;
7577 }
7578 case Intrinsic::sadd_sat: {
7579 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7580 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7581 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SADDSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7582 return;
7583 }
7584 case Intrinsic::uadd_sat: {
7585 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7586 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7587 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UADDSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7588 return;
7589 }
7590 case Intrinsic::ssub_sat: {
7591 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7592 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7593 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SSUBSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7594 return;
7595 }
7596 case Intrinsic::usub_sat: {
7597 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7598 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7599 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::USUBSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7600 return;
7601 }
7602 case Intrinsic::sshl_sat:
7603 case Intrinsic::ushl_sat: {
7604 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7605 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7606
7607 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
7608 LHSTy: Op1.getValueType(), DL: DAG.getDataLayout());
7609
7610 // Coerce the shift amount to the right type if we can. This exposes the
7611 // truncate or zext to optimization early.
7612 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
7613 assert(ShiftTy.getSizeInBits() >=
7614 Log2_32_Ceil(Op1.getValueSizeInBits()) &&
7615 "Unexpected shift type");
7616 Op2 = DAG.getZExtOrTrunc(Op: Op2, DL: getCurSDLoc(), VT: ShiftTy);
7617 }
7618
7619 unsigned Opc =
7620 Intrinsic == Intrinsic::sshl_sat ? ISD::SSHLSAT : ISD::USHLSAT;
7621 setValue(V: &I, NewN: DAG.getNode(Opcode: Opc, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7622 return;
7623 }
7624 case Intrinsic::smul_fix:
7625 case Intrinsic::umul_fix:
7626 case Intrinsic::smul_fix_sat:
7627 case Intrinsic::umul_fix_sat: {
7628 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7629 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7630 SDValue Op3 = getValue(V: I.getArgOperand(i: 2));
7631 setValue(V: &I, NewN: DAG.getNode(Opcode: FixedPointIntrinsicToOpcode(Intrinsic), DL: sdl,
7632 VT: Op1.getValueType(), N1: Op1, N2: Op2, N3: Op3));
7633 return;
7634 }
7635 case Intrinsic::sdiv_fix:
7636 case Intrinsic::udiv_fix:
7637 case Intrinsic::sdiv_fix_sat:
7638 case Intrinsic::udiv_fix_sat: {
7639 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7640 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7641 SDValue Op3 = getValue(V: I.getArgOperand(i: 2));
7642 setValue(V: &I, NewN: expandDivFix(Opcode: FixedPointIntrinsicToOpcode(Intrinsic), DL: sdl,
7643 LHS: Op1, RHS: Op2, Scale: Op3, DAG, TLI));
7644 return;
7645 }
7646 case Intrinsic::smax: {
7647 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7648 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7649 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SMAX, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7650 return;
7651 }
7652 case Intrinsic::smin: {
7653 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7654 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7655 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SMIN, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7656 return;
7657 }
7658 case Intrinsic::umax: {
7659 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7660 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7661 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UMAX, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7662 return;
7663 }
7664 case Intrinsic::umin: {
7665 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7666 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7667 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UMIN, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7668 return;
7669 }
7670 case Intrinsic::abs: {
7671 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7672 bool IntMinIsPoison = cast<ConstantInt>(Val: I.getArgOperand(i: 1))->isOne();
7673 unsigned Opc = IntMinIsPoison ? ISD::ABS_MIN_POISON : ISD::ABS;
7674 setValue(V: &I, NewN: DAG.getNode(Opcode: Opc, DL: sdl, VT: Op1.getValueType(), Operand: Op1));
7675 return;
7676 }
7677 case Intrinsic::scmp: {
7678 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7679 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7680 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7681 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SCMP, DL: sdl, VT: DestVT, N1: Op1, N2: Op2));
7682 break;
7683 }
7684 case Intrinsic::ucmp: {
7685 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7686 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7687 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7688 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UCMP, DL: sdl, VT: DestVT, N1: Op1, N2: Op2));
7689 break;
7690 }
7691 case Intrinsic::stackaddress:
7692 case Intrinsic::stacksave: {
7693 unsigned SDOpcode = Intrinsic == Intrinsic::stackaddress ? ISD::STACKADDRESS
7694 : ISD::STACKSAVE;
7695 SDValue Op = getRoot();
7696 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7697 Res = DAG.getNode(Opcode: SDOpcode, DL: sdl, VTList: DAG.getVTList(VT1: VT, VT2: MVT::Other), N: Op);
7698 setValue(V: &I, NewN: Res);
7699 DAG.setRoot(Res.getValue(R: 1));
7700 return;
7701 }
7702 case Intrinsic::stackrestore:
7703 Res = getValue(V: I.getArgOperand(i: 0));
7704 DAG.setRoot(DAG.getNode(Opcode: ISD::STACKRESTORE, DL: sdl, VT: MVT::Other, N1: getRoot(), N2: Res));
7705 return;
7706 case Intrinsic::get_dynamic_area_offset: {
7707 SDValue Op = getRoot();
7708 EVT ResTy = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7709 Res = DAG.getNode(Opcode: ISD::GET_DYNAMIC_AREA_OFFSET, DL: sdl, VTList: DAG.getVTList(VT: ResTy),
7710 N: Op);
7711 DAG.setRoot(Op);
7712 setValue(V: &I, NewN: Res);
7713 return;
7714 }
7715 case Intrinsic::stackguard: {
7716 MachineFunction &MF = DAG.getMachineFunction();
7717 const Module &M = *MF.getFunction().getParent();
7718 EVT PtrTy = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7719 SDValue Chain = getRoot();
7720 if (TLI.useLoadStackGuardNode(M)) {
7721 Res = getLoadStackGuard(DAG, DL: sdl, Chain);
7722 Res = DAG.getPtrExtOrTrunc(Op: Res, DL: sdl, VT: PtrTy);
7723 } else {
7724 const Value *Global = TLI.getSDagStackGuard(M, Libcalls: DAG.getLibcalls());
7725 if (!Global) {
7726 LLVMContext &Ctx = *DAG.getContext();
7727 Ctx.diagnose(DI: DiagnosticInfoGeneric("unable to lower stackguard"));
7728 setValue(V: &I, NewN: DAG.getPOISON(VT: PtrTy));
7729 return;
7730 }
7731
7732 Align Align = DAG.getDataLayout().getPrefTypeAlign(Ty: Global->getType());
7733 Res = DAG.getLoad(VT: PtrTy, dl: sdl, Chain, Ptr: getValue(V: Global),
7734 PtrInfo: MachinePointerInfo(Global, 0), Alignment: Align,
7735 MMOFlags: MachineMemOperand::MOVolatile);
7736 }
7737 // Mix the cookie with FP if enabled. Skip if using LOAD_STACK_GUARD
7738 // with post-RA mixing (AArch64 MSVCRT), as the mixing will be done during
7739 // post-RA expansion of LOAD_STACK_GUARD.
7740 if (TLI.useStackGuardMixFP() && !TLI.useLoadStackGuardNode(M))
7741 Res = TLI.emitStackGuardMixFP(DAG, Val: Res, DL: sdl);
7742 DAG.setRoot(Chain);
7743 setValue(V: &I, NewN: Res);
7744 return;
7745 }
7746 case Intrinsic::stackprotector: {
7747 // Emit code into the DAG to store the stack guard onto the stack.
7748 MachineFunction &MF = DAG.getMachineFunction();
7749 MachineFrameInfo &MFI = MF.getFrameInfo();
7750 const Module &M = *MF.getFunction().getParent();
7751 SDValue Src, Chain = getRoot();
7752
7753 if (TLI.useLoadStackGuardNode(M))
7754 Src = getLoadStackGuard(DAG, DL: sdl, Chain);
7755 else
7756 Src = getValue(V: I.getArgOperand(i: 0)); // The guard's value.
7757
7758 AllocaInst *Slot = cast<AllocaInst>(Val: I.getArgOperand(i: 1));
7759
7760 int FI = FuncInfo.StaticAllocaMap[Slot];
7761 MFI.setStackProtectorIndex(FI);
7762 EVT PtrTy = TLI.getFrameIndexTy(DL: DAG.getDataLayout());
7763
7764 SDValue FIN = DAG.getFrameIndex(FI, VT: PtrTy);
7765
7766 // Store the stack protector onto the stack.
7767 Res = DAG.getStore(
7768 Chain, dl: sdl, Val: Src, Ptr: FIN,
7769 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI),
7770 Alignment: MaybeAlign(), MMOFlags: MachineMemOperand::MOVolatile);
7771 setValue(V: &I, NewN: Res);
7772 DAG.setRoot(Res);
7773 return;
7774 }
7775 case Intrinsic::objectsize:
7776 llvm_unreachable("llvm.objectsize.* should have been lowered already");
7777
7778 case Intrinsic::is_constant:
7779 llvm_unreachable("llvm.is.constant.* should have been lowered already");
7780
7781 case Intrinsic::annotation:
7782 case Intrinsic::ptr_annotation:
7783 case Intrinsic::launder_invariant_group:
7784 case Intrinsic::strip_invariant_group:
7785 // Drop the intrinsic, but forward the value
7786 setValue(V: &I, NewN: getValue(V: I.getOperand(i_nocapture: 0)));
7787 return;
7788
7789 case Intrinsic::type_test:
7790 case Intrinsic::public_type_test:
7791 case Intrinsic::type_checked_load:
7792 case Intrinsic::type_checked_load_relative: {
7793 // These intrinsics are expected to be lowered by the LowerTypeTests pass
7794 // before code generation. Surviving until here usually indicates a
7795 // misconfiguration, for instance when devirtualization is enabled but LTO
7796 // does not actually run.
7797 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
7798 *I.getFunction(),
7799 Intrinsic::getBaseName(id: Intrinsic) +
7800 " intrinsic must be lowered by the LowerTypeTests pass "
7801 "before code generation",
7802 sdl.getDebugLoc()));
7803
7804 // Lower the result to poison so that compilation can continue and collect
7805 // any further diagnostics.
7806 setValueToPoison(V: &I, dl: sdl);
7807 return;
7808 }
7809
7810 case Intrinsic::assume:
7811 case Intrinsic::experimental_noalias_scope_decl:
7812 case Intrinsic::var_annotation:
7813 case Intrinsic::sideeffect:
7814 // Discard annotate attributes, noalias scope declarations, assumptions, and
7815 // artificial side-effects.
7816 return;
7817
7818 case Intrinsic::codeview_annotation: {
7819 // Emit a label associated with this metadata.
7820 MachineFunction &MF = DAG.getMachineFunction();
7821 MCSymbol *Label = MF.getContext().createTempSymbol(Name: "annotation", AlwaysAddSuffix: true);
7822 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 0))->getMetadata();
7823 MF.addCodeViewAnnotation(Label, MD: cast<MDNode>(Val: MD));
7824 Res = DAG.getLabelNode(Opcode: ISD::ANNOTATION_LABEL, dl: sdl, Root: getRoot(), Label);
7825 DAG.setRoot(Res);
7826 return;
7827 }
7828
7829 case Intrinsic::init_trampoline: {
7830 const Function *F = cast<Function>(Val: I.getArgOperand(i: 1)->stripPointerCasts());
7831
7832 SDValue Ops[6];
7833 Ops[0] = getRoot();
7834 Ops[1] = getValue(V: I.getArgOperand(i: 0));
7835 Ops[2] = getValue(V: I.getArgOperand(i: 1));
7836 Ops[3] = getValue(V: I.getArgOperand(i: 2));
7837 Ops[4] = DAG.getSrcValue(v: I.getArgOperand(i: 0));
7838 Ops[5] = DAG.getSrcValue(v: F);
7839
7840 Res = DAG.getNode(Opcode: ISD::INIT_TRAMPOLINE, DL: sdl, VT: MVT::Other, Ops);
7841
7842 DAG.setRoot(Res);
7843 return;
7844 }
7845 case Intrinsic::adjust_trampoline:
7846 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::ADJUST_TRAMPOLINE, DL: sdl,
7847 VT: TLI.getPointerTy(DL: DAG.getDataLayout()),
7848 Operand: getValue(V: I.getArgOperand(i: 0))));
7849 return;
7850 case Intrinsic::gcroot: {
7851 assert(DAG.getMachineFunction().getFunction().hasGC() &&
7852 "only valid in functions with gc specified, enforced by Verifier");
7853 assert(GFI && "implied by previous");
7854 const Value *Alloca = I.getArgOperand(i: 0)->stripPointerCasts();
7855 const Constant *TypeMap = cast<Constant>(Val: I.getArgOperand(i: 1));
7856
7857 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(Val: getValue(V: Alloca).getNode());
7858 GFI->addStackRoot(Num: FI->getIndex(), Metadata: TypeMap);
7859 return;
7860 }
7861 case Intrinsic::gcread:
7862 case Intrinsic::gcwrite:
7863 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7864 case Intrinsic::get_rounding:
7865 Res = DAG.getNode(Opcode: ISD::GET_ROUNDING, DL: sdl, ResultTys: {MVT::i32, MVT::Other}, Ops: getRoot());
7866 setValue(V: &I, NewN: Res);
7867 DAG.setRoot(Res.getValue(R: 1));
7868 return;
7869
7870 case Intrinsic::expect:
7871 case Intrinsic::expect_with_probability:
7872 // Just replace __builtin_expect(exp, c) and
7873 // __builtin_expect_with_probability(exp, c, p) with EXP.
7874 setValue(V: &I, NewN: getValue(V: I.getArgOperand(i: 0)));
7875 return;
7876
7877 case Intrinsic::ubsantrap:
7878 case Intrinsic::debugtrap:
7879 case Intrinsic::trap: {
7880 StringRef TrapFuncName =
7881 I.getAttributes().getFnAttr(Kind: "trap-func-name").getValueAsString();
7882 if (TrapFuncName.empty()) {
7883 switch (Intrinsic) {
7884 case Intrinsic::trap:
7885 DAG.setRoot(DAG.getNode(Opcode: ISD::TRAP, DL: sdl, VT: MVT::Other, Operand: getRoot()));
7886 break;
7887 case Intrinsic::debugtrap:
7888 DAG.setRoot(DAG.getNode(Opcode: ISD::DEBUGTRAP, DL: sdl, VT: MVT::Other, Operand: getRoot()));
7889 break;
7890 case Intrinsic::ubsantrap:
7891 DAG.setRoot(DAG.getNode(
7892 Opcode: ISD::UBSANTRAP, DL: sdl, VT: MVT::Other, N1: getRoot(),
7893 N2: DAG.getTargetConstant(
7894 Val: cast<ConstantInt>(Val: I.getArgOperand(i: 0))->getZExtValue(), DL: sdl,
7895 VT: MVT::i32)));
7896 break;
7897 default: llvm_unreachable("unknown trap intrinsic");
7898 }
7899 DAG.addNoMergeSiteInfo(Node: DAG.getRoot().getNode(),
7900 NoMerge: I.hasFnAttr(Kind: Attribute::NoMerge));
7901 return;
7902 }
7903 TargetLowering::ArgListTy Args;
7904 if (Intrinsic == Intrinsic::ubsantrap) {
7905 Value *Arg = I.getArgOperand(i: 0);
7906 Args.emplace_back(args&: Arg, args: getValue(V: Arg));
7907 }
7908
7909 TargetLowering::CallLoweringInfo CLI(DAG);
7910 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7911 CC: CallingConv::C, ResultType: I.getType(),
7912 Target: DAG.getExternalSymbol(Sym: TrapFuncName.data(),
7913 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
7914 ArgsList: std::move(Args));
7915 CLI.NoMerge = I.hasFnAttr(Kind: Attribute::NoMerge);
7916 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7917 DAG.setRoot(Result.second);
7918 return;
7919 }
7920
7921 case Intrinsic::allow_runtime_check:
7922 case Intrinsic::allow_ubsan_check:
7923 setValue(V: &I, NewN: getValue(V: ConstantInt::getTrue(Ty: I.getType())));
7924 return;
7925
7926 case Intrinsic::uadd_with_overflow:
7927 case Intrinsic::sadd_with_overflow:
7928 case Intrinsic::usub_with_overflow:
7929 case Intrinsic::ssub_with_overflow:
7930 case Intrinsic::umul_with_overflow:
7931 case Intrinsic::smul_with_overflow: {
7932 ISD::NodeType Op;
7933 switch (Intrinsic) {
7934 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7935 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7936 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7937 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7938 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7939 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7940 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7941 }
7942 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7943 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7944
7945 EVT ResultVT = Op1.getValueType();
7946 EVT OverflowVT = ResultVT.changeElementType(Context&: *Context, EltVT: MVT::i1);
7947
7948 SDVTList VTs = DAG.getVTList(VT1: ResultVT, VT2: OverflowVT);
7949 setValue(V: &I, NewN: DAG.getNode(Opcode: Op, DL: sdl, VTList: VTs, N1: Op1, N2: Op2));
7950 return;
7951 }
7952 case Intrinsic::prefetch: {
7953 SDValue Ops[5];
7954 unsigned rw = cast<ConstantInt>(Val: I.getArgOperand(i: 1))->getZExtValue();
7955 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7956 Ops[0] = DAG.getRoot();
7957 Ops[1] = getValue(V: I.getArgOperand(i: 0));
7958 Ops[2] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 1)), DL: sdl,
7959 VT: MVT::i32);
7960 Ops[3] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 2)), DL: sdl,
7961 VT: MVT::i32);
7962 Ops[4] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 3)), DL: sdl,
7963 VT: MVT::i32);
7964 SDValue Result = DAG.getMemIntrinsicNode(
7965 Opcode: ISD::PREFETCH, dl: sdl, VTList: DAG.getVTList(VT: MVT::Other), Ops,
7966 MemVT: EVT::getIntegerVT(Context&: *Context, BitWidth: 8), PtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
7967 /* align */ Alignment: std::nullopt, Flags);
7968
7969 // Chain the prefetch in parallel with any pending loads, to stay out of
7970 // the way of later optimizations.
7971 PendingLoads.push_back(Elt: Result);
7972 Result = getRoot();
7973 DAG.setRoot(Result);
7974 return;
7975 }
7976 case Intrinsic::lifetime_start:
7977 case Intrinsic::lifetime_end: {
7978 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7979 // Stack coloring is not enabled in O0, discard region information.
7980 if (TM.getOptLevel() == CodeGenOptLevel::None)
7981 return;
7982
7983 const AllocaInst *LifetimeObject = dyn_cast<AllocaInst>(Val: I.getArgOperand(i: 0));
7984 if (!LifetimeObject)
7985 return;
7986
7987 // First check that the Alloca is static, otherwise it won't have a
7988 // valid frame index.
7989 auto SI = FuncInfo.StaticAllocaMap.find(Val: LifetimeObject);
7990 if (SI == FuncInfo.StaticAllocaMap.end())
7991 return;
7992
7993 const int FrameIndex = SI->second;
7994 Res = DAG.getLifetimeNode(IsStart, dl: sdl, Chain: getRoot(), FrameIndex);
7995 DAG.setRoot(Res);
7996 return;
7997 }
7998 case Intrinsic::pseudoprobe: {
7999 auto Guid = cast<ConstantInt>(Val: I.getArgOperand(i: 0))->getZExtValue();
8000 auto Index = cast<ConstantInt>(Val: I.getArgOperand(i: 1))->getZExtValue();
8001 auto Attr = cast<ConstantInt>(Val: I.getArgOperand(i: 2))->getZExtValue();
8002 Res = DAG.getPseudoProbeNode(Dl: sdl, Chain: getRoot(), Guid, Index, Attr);
8003 DAG.setRoot(Res);
8004 return;
8005 }
8006 case Intrinsic::invariant_start:
8007 // Discard region information.
8008 setValue(V: &I,
8009 NewN: DAG.getUNDEF(VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType())));
8010 return;
8011 case Intrinsic::invariant_end:
8012 // Discard region information.
8013 return;
8014 case Intrinsic::clear_cache: {
8015 SDValue InputChain = DAG.getRoot();
8016 SDValue StartVal = getValue(V: I.getArgOperand(i: 0));
8017 SDValue EndVal = getValue(V: I.getArgOperand(i: 1));
8018 Res = DAG.getNode(Opcode: ISD::CLEAR_CACHE, DL: sdl, VTList: DAG.getVTList(VT: MVT::Other),
8019 Ops: {InputChain, StartVal, EndVal});
8020 setValue(V: &I, NewN: Res);
8021 DAG.setRoot(Res);
8022 return;
8023 }
8024 case Intrinsic::donothing:
8025 case Intrinsic::seh_try_begin:
8026 case Intrinsic::seh_scope_begin:
8027 case Intrinsic::seh_try_end:
8028 case Intrinsic::seh_scope_end:
8029 // ignore
8030 return;
8031 case Intrinsic::experimental_stackmap:
8032 visitStackmap(I);
8033 return;
8034 case Intrinsic::experimental_patchpoint_void:
8035 case Intrinsic::experimental_patchpoint:
8036 visitPatchpoint(CB: I);
8037 return;
8038 case Intrinsic::experimental_gc_statepoint:
8039 LowerStatepoint(I: cast<GCStatepointInst>(Val: I));
8040 return;
8041 case Intrinsic::experimental_gc_result:
8042 visitGCResult(I: cast<GCResultInst>(Val: I));
8043 return;
8044 case Intrinsic::experimental_gc_relocate:
8045 visitGCRelocate(Relocate: cast<GCRelocateInst>(Val: I));
8046 return;
8047 case Intrinsic::instrprof_cover:
8048 llvm_unreachable("instrprof failed to lower a cover");
8049 case Intrinsic::instrprof_increment:
8050 llvm_unreachable("instrprof failed to lower an increment");
8051 case Intrinsic::instrprof_timestamp:
8052 llvm_unreachable("instrprof failed to lower a timestamp");
8053 case Intrinsic::instrprof_value_profile:
8054 llvm_unreachable("instrprof failed to lower a value profiling call");
8055 case Intrinsic::instrprof_mcdc_parameters:
8056 llvm_unreachable("instrprof failed to lower mcdc parameters");
8057 case Intrinsic::instrprof_mcdc_tvbitmap_update:
8058 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
8059 case Intrinsic::localescape: {
8060 MachineFunction &MF = DAG.getMachineFunction();
8061 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
8062
8063 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
8064 // is the same on all targets.
8065 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
8066 Value *Arg = I.getArgOperand(i: Idx)->stripPointerCasts();
8067 if (isa<ConstantPointerNull>(Val: Arg))
8068 continue; // Skip null pointers. They represent a hole in index space.
8069 AllocaInst *Slot = cast<AllocaInst>(Val: Arg);
8070 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
8071 "can only escape static allocas");
8072 int FI = FuncInfo.StaticAllocaMap[Slot];
8073 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8074 FuncName: GlobalValue::dropLLVMManglingEscape(Name: MF.getName()), Idx);
8075 BuildMI(BB&: *FuncInfo.MBB, I: FuncInfo.InsertPt, MIMD: dl,
8076 MCID: TII->get(Opcode: TargetOpcode::LOCAL_ESCAPE))
8077 .addSym(Sym: FrameAllocSym)
8078 .addFrameIndex(Idx: FI);
8079 }
8080
8081 return;
8082 }
8083
8084 case Intrinsic::localrecover: {
8085 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
8086 MachineFunction &MF = DAG.getMachineFunction();
8087
8088 // Get the symbol that defines the frame offset.
8089 auto *Fn = cast<Function>(Val: I.getArgOperand(i: 0)->stripPointerCasts());
8090 auto *Idx = cast<ConstantInt>(Val: I.getArgOperand(i: 2));
8091 unsigned IdxVal =
8092 unsigned(Idx->getLimitedValue(Limit: std::numeric_limits<int>::max()));
8093 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8094 FuncName: GlobalValue::dropLLVMManglingEscape(Name: Fn->getName()), Idx: IdxVal);
8095
8096 Value *FP = I.getArgOperand(i: 1);
8097 SDValue FPVal = getValue(V: FP);
8098 EVT PtrVT = FPVal.getValueType();
8099
8100 // Create a MCSymbol for the label to avoid any target lowering
8101 // that would make this PC relative.
8102 SDValue OffsetSym = DAG.getMCSymbol(Sym: FrameAllocSym, VT: PtrVT);
8103 SDValue OffsetVal =
8104 DAG.getNode(Opcode: ISD::LOCAL_RECOVER, DL: sdl, VT: PtrVT, Operand: OffsetSym);
8105
8106 // Add the offset to the FP.
8107 SDValue Add = DAG.getMemBasePlusOffset(Base: FPVal, Offset: OffsetVal, DL: sdl);
8108 setValue(V: &I, NewN: Add);
8109
8110 return;
8111 }
8112
8113 case Intrinsic::fake_use: {
8114 Value *V = I.getArgOperand(i: 0);
8115 SDValue Ops[2];
8116 // For Values not declared or previously used in this basic block, the
8117 // NodeMap will not have an entry, and `getValue` will assert if V has no
8118 // valid register value.
8119 auto FakeUseValue = [&]() -> SDValue {
8120 SDValue &N = NodeMap[V];
8121 if (N.getNode())
8122 return N;
8123
8124 // If there's a virtual register allocated and initialized for this
8125 // value, use it.
8126 if (SDValue copyFromReg = getCopyFromRegs(V, Ty: V->getType()))
8127 return copyFromReg;
8128 // FIXME: Do we want to preserve constants? It seems pointless.
8129 if (isa<Constant>(Val: V))
8130 return getValue(V);
8131 return SDValue();
8132 }();
8133 if (!FakeUseValue || FakeUseValue.isUndef())
8134 return;
8135 Ops[0] = getRoot();
8136 Ops[1] = FakeUseValue;
8137 // Also, do not translate a fake use with an undef operand, or any other
8138 // empty SDValues.
8139 if (!Ops[1] || Ops[1].isUndef())
8140 return;
8141 DAG.setRoot(DAG.getNode(Opcode: ISD::FAKE_USE, DL: sdl, VT: MVT::Other, Ops));
8142 return;
8143 }
8144
8145 case Intrinsic::reloc_none: {
8146 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 0))->getMetadata();
8147 StringRef SymbolName = cast<MDString>(Val: MD)->getString();
8148 SDValue Ops[2] = {
8149 getRoot(),
8150 DAG.getTargetExternalSymbol(
8151 Sym: SymbolName.data(), VT: TLI.getProgramPointerTy(DL: DAG.getDataLayout()))};
8152 DAG.setRoot(DAG.getNode(Opcode: ISD::RELOC_NONE, DL: sdl, VT: MVT::Other, Ops));
8153 return;
8154 }
8155
8156 case Intrinsic::cond_loop: {
8157 SDValue InputChain = DAG.getRoot();
8158 SDValue P = getValue(V: I.getArgOperand(i: 0));
8159 Res = DAG.getNode(Opcode: ISD::COND_LOOP, DL: sdl, VTList: DAG.getVTList(VT: MVT::Other),
8160 Ops: {InputChain, P});
8161 setValue(V: &I, NewN: Res);
8162 DAG.setRoot(Res);
8163 return;
8164 }
8165
8166 case Intrinsic::eh_exceptionpointer:
8167 case Intrinsic::eh_exceptioncode: {
8168 // Get the exception pointer vreg, copy from it, and resize it to fit.
8169 const auto *CPI = cast<CatchPadInst>(Val: I.getArgOperand(i: 0));
8170 MVT PtrVT = TLI.getPointerTy(DL: DAG.getDataLayout());
8171 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(VT: PtrVT);
8172 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, RC: PtrRC);
8173 SDValue N = DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl: sdl, Reg: VReg, VT: PtrVT);
8174 if (Intrinsic == Intrinsic::eh_exceptioncode)
8175 N = DAG.getZExtOrTrunc(Op: N, DL: sdl, VT: MVT::i32);
8176 setValue(V: &I, NewN: N);
8177 return;
8178 }
8179 case Intrinsic::xray_customevent: {
8180 // Here we want to make sure that the intrinsic behaves as if it has a
8181 // specific calling convention.
8182 const auto &Triple = DAG.getTarget().getTargetTriple();
8183 if (!Triple.isAArch64(PointerWidth: 64) && Triple.getArch() != Triple::x86_64 &&
8184 Triple.getArch() != Triple::hexagon)
8185 return;
8186
8187 SmallVector<SDValue, 8> Ops;
8188
8189 // We want to say that we always want the arguments in registers.
8190 SDValue LogEntryVal = getValue(V: I.getArgOperand(i: 0));
8191 SDValue StrSizeVal = getValue(V: I.getArgOperand(i: 1));
8192 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
8193 SDValue Chain = getRoot();
8194 Ops.push_back(Elt: LogEntryVal);
8195 Ops.push_back(Elt: StrSizeVal);
8196 Ops.push_back(Elt: Chain);
8197
8198 // We need to enforce the calling convention for the callsite, so that
8199 // argument ordering is enforced correctly, and that register allocation can
8200 // see that some registers may be assumed clobbered and have to preserve
8201 // them across calls to the intrinsic.
8202 MachineSDNode *MN = DAG.getMachineNode(Opcode: TargetOpcode::PATCHABLE_EVENT_CALL,
8203 dl: sdl, VTs: NodeTys, Ops);
8204 SDValue patchableNode = SDValue(MN, 0);
8205 DAG.setRoot(patchableNode);
8206 setValue(V: &I, NewN: patchableNode);
8207 return;
8208 }
8209 case Intrinsic::xray_typedevent: {
8210 // Here we want to make sure that the intrinsic behaves as if it has a
8211 // specific calling convention.
8212 const auto &Triple = DAG.getTarget().getTargetTriple();
8213 if (!Triple.isAArch64(PointerWidth: 64) && Triple.getArch() != Triple::x86_64 &&
8214 Triple.getArch() != Triple::hexagon)
8215 return;
8216
8217 SmallVector<SDValue, 8> Ops;
8218
8219 // We want to say that we always want the arguments in registers.
8220 // It's unclear to me how manipulating the selection DAG here forces callers
8221 // to provide arguments in registers instead of on the stack.
8222 SDValue LogTypeId = getValue(V: I.getArgOperand(i: 0));
8223 SDValue LogEntryVal = getValue(V: I.getArgOperand(i: 1));
8224 SDValue StrSizeVal = getValue(V: I.getArgOperand(i: 2));
8225 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
8226 SDValue Chain = getRoot();
8227 Ops.push_back(Elt: LogTypeId);
8228 Ops.push_back(Elt: LogEntryVal);
8229 Ops.push_back(Elt: StrSizeVal);
8230 Ops.push_back(Elt: Chain);
8231
8232 // We need to enforce the calling convention for the callsite, so that
8233 // argument ordering is enforced correctly, and that register allocation can
8234 // see that some registers may be assumed clobbered and have to preserve
8235 // them across calls to the intrinsic.
8236 MachineSDNode *MN = DAG.getMachineNode(
8237 Opcode: TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, dl: sdl, VTs: NodeTys, Ops);
8238 SDValue patchableNode = SDValue(MN, 0);
8239 DAG.setRoot(patchableNode);
8240 setValue(V: &I, NewN: patchableNode);
8241 return;
8242 }
8243 case Intrinsic::experimental_deoptimize:
8244 LowerDeoptimizeCall(CI: &I);
8245 return;
8246 case Intrinsic::stepvector:
8247 visitStepVector(I);
8248 return;
8249 case Intrinsic::vector_reduce_fadd:
8250 case Intrinsic::vector_reduce_fmul:
8251 case Intrinsic::vector_reduce_add:
8252 case Intrinsic::vector_reduce_mul:
8253 case Intrinsic::vector_reduce_and:
8254 case Intrinsic::vector_reduce_or:
8255 case Intrinsic::vector_reduce_xor:
8256 case Intrinsic::vector_reduce_smax:
8257 case Intrinsic::vector_reduce_smin:
8258 case Intrinsic::vector_reduce_umax:
8259 case Intrinsic::vector_reduce_umin:
8260 case Intrinsic::vector_reduce_fmax:
8261 case Intrinsic::vector_reduce_fmin:
8262 case Intrinsic::vector_reduce_fmaximum:
8263 case Intrinsic::vector_reduce_fminimum:
8264 case Intrinsic::vector_reduce_fmaximumnum:
8265 case Intrinsic::vector_reduce_fminimumnum:
8266 visitVectorReduce(I, Intrinsic);
8267 return;
8268
8269 case Intrinsic::icall_branch_funnel: {
8270 SmallVector<SDValue, 16> Ops;
8271 Ops.push_back(Elt: getValue(V: I.getArgOperand(i: 0)));
8272
8273 int64_t Offset;
8274 auto *Base = dyn_cast<GlobalObject>(Val: GetPointerBaseWithConstantOffset(
8275 Ptr: I.getArgOperand(i: 1), Offset, DL: DAG.getDataLayout()));
8276 if (!Base)
8277 report_fatal_error(
8278 reason: "llvm.icall.branch.funnel operand must be a GlobalValue");
8279 Ops.push_back(Elt: DAG.getTargetGlobalAddress(GV: Base, DL: sdl, VT: MVT::i64, offset: 0));
8280
8281 struct BranchFunnelTarget {
8282 int64_t Offset;
8283 SDValue Target;
8284 };
8285 SmallVector<BranchFunnelTarget, 8> Targets;
8286
8287 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
8288 auto *ElemBase = dyn_cast<GlobalObject>(Val: GetPointerBaseWithConstantOffset(
8289 Ptr: I.getArgOperand(i: Op), Offset, DL: DAG.getDataLayout()));
8290 if (ElemBase != Base)
8291 report_fatal_error(reason: "all llvm.icall.branch.funnel operands must refer "
8292 "to the same GlobalValue");
8293
8294 SDValue Val = getValue(V: I.getArgOperand(i: Op + 1));
8295 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
8296 if (!GA)
8297 report_fatal_error(
8298 reason: "llvm.icall.branch.funnel operand must be a GlobalValue");
8299 Targets.push_back(Elt: {.Offset: Offset, .Target: DAG.getTargetGlobalAddress(
8300 GV: GA->getGlobal(), DL: sdl, VT: Val.getValueType(),
8301 offset: GA->getOffset())});
8302 }
8303 llvm::sort(C&: Targets,
8304 Comp: [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
8305 return T1.Offset < T2.Offset;
8306 });
8307
8308 for (auto &T : Targets) {
8309 Ops.push_back(Elt: DAG.getTargetConstant(Val: T.Offset, DL: sdl, VT: MVT::i32));
8310 Ops.push_back(Elt: T.Target);
8311 }
8312
8313 Ops.push_back(Elt: DAG.getRoot()); // Chain
8314 SDValue N(DAG.getMachineNode(Opcode: TargetOpcode::ICALL_BRANCH_FUNNEL, dl: sdl,
8315 VT: MVT::Other, Ops),
8316 0);
8317 DAG.setRoot(N);
8318 setValue(V: &I, NewN: N);
8319 HasTailCall = true;
8320 return;
8321 }
8322
8323 case Intrinsic::wasm_landingpad_index:
8324 // Information this intrinsic contained has been transferred to
8325 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
8326 // delete it now.
8327 return;
8328
8329 case Intrinsic::aarch64_settag:
8330 case Intrinsic::aarch64_settag_zero: {
8331 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8332 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
8333 SDValue Val = TSI.EmitTargetCodeForSetTag(
8334 DAG, dl: sdl, Chain: getRoot(), Addr: getValue(V: I.getArgOperand(i: 0)),
8335 Size: getValue(V: I.getArgOperand(i: 1)), DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
8336 ZeroData: ZeroMemory);
8337 DAG.setRoot(Val);
8338 setValue(V: &I, NewN: Val);
8339 return;
8340 }
8341 case Intrinsic::amdgcn_cs_chain: {
8342 // At this point we don't care if it's amdgpu_cs_chain or
8343 // amdgpu_cs_chain_preserve.
8344 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
8345
8346 Type *RetTy = I.getType();
8347 assert(RetTy->isVoidTy() && "Should not return");
8348
8349 SDValue Callee = getValue(V: I.getOperand(i_nocapture: 0));
8350
8351 // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8352 // We'll also tack the value of the EXEC mask at the end.
8353 TargetLowering::ArgListTy Args;
8354 Args.reserve(n: 3);
8355
8356 for (unsigned Idx : {2, 3, 1}) {
8357 TargetLowering::ArgListEntry Arg(getValue(V: I.getOperand(i_nocapture: Idx)),
8358 I.getOperand(i_nocapture: Idx)->getType());
8359 Arg.setAttributes(Call: &I, ArgIdx: Idx);
8360 Args.push_back(x: Arg);
8361 }
8362
8363 assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8364 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8365 Args[2].IsInReg = true; // EXEC should be inreg
8366
8367 // Forward the flags and any additional arguments.
8368 for (unsigned Idx = 4; Idx < I.arg_size(); ++Idx) {
8369 TargetLowering::ArgListEntry Arg(getValue(V: I.getOperand(i_nocapture: Idx)),
8370 I.getOperand(i_nocapture: Idx)->getType());
8371 Arg.setAttributes(Call: &I, ArgIdx: Idx);
8372 Args.push_back(x: Arg);
8373 }
8374
8375 TargetLowering::CallLoweringInfo CLI(DAG);
8376 CLI.setDebugLoc(getCurSDLoc())
8377 .setChain(getRoot())
8378 .setCallee(CC, ResultType: RetTy, Target: Callee, ArgsList: std::move(Args))
8379 .setNoReturn(true)
8380 .setTailCall(true)
8381 .setConvergent(I.isConvergent());
8382 CLI.CB = &I;
8383 std::pair<SDValue, SDValue> Result =
8384 lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8385 (void)Result;
8386 assert(!Result.first.getNode() && !Result.second.getNode() &&
8387 "Should've lowered as tail call");
8388
8389 HasTailCall = true;
8390 return;
8391 }
8392 case Intrinsic::amdgcn_call_whole_wave: {
8393 TargetLowering::ArgListTy Args;
8394 bool isTailCall = I.isTailCall();
8395
8396 // The first argument is the callee. Skip it when assembling the call args.
8397 for (unsigned Idx = 1; Idx < I.arg_size(); ++Idx) {
8398 TargetLowering::ArgListEntry Arg(getValue(V: I.getArgOperand(i: Idx)),
8399 I.getArgOperand(i: Idx)->getType());
8400 Arg.setAttributes(Call: &I, ArgIdx: Idx);
8401
8402 // If we have an explicit sret argument that is an Instruction, (i.e., it
8403 // might point to function-local memory), we can't meaningfully tail-call.
8404 if (Arg.IsSRet && isa<Instruction>(Val: I.getArgOperand(i: Idx)))
8405 isTailCall = false;
8406
8407 Args.push_back(x: Arg);
8408 }
8409
8410 SDValue ConvControlToken;
8411 if (auto Bundle = I.getOperandBundle(ID: LLVMContext::OB_convergencectrl)) {
8412 auto *Token = Bundle->Inputs[0].get();
8413 ConvControlToken = getValue(V: Token);
8414 }
8415
8416 TargetLowering::CallLoweringInfo CLI(DAG);
8417 CLI.setDebugLoc(getCurSDLoc())
8418 .setChain(getRoot())
8419 .setCallee(CC: CallingConv::AMDGPU_Gfx_WholeWave, ResultType: I.getType(),
8420 Target: getValue(V: I.getArgOperand(i: 0)), ArgsList: std::move(Args))
8421 .setTailCall(isTailCall && canTailCall(CB: I))
8422 .setIsPreallocated(
8423 I.countOperandBundlesOfType(ID: LLVMContext::OB_preallocated) != 0)
8424 .setConvergent(I.isConvergent())
8425 .setConvergenceControlToken(ConvControlToken);
8426 CLI.CB = &I;
8427
8428 std::pair<SDValue, SDValue> Result =
8429 lowerInvokable(CLI, /*EHPadBB=*/nullptr);
8430
8431 if (Result.first.getNode())
8432 setValue(V: &I, NewN: Result.first);
8433 return;
8434 }
8435 case Intrinsic::ptrmask: {
8436 SDValue Ptr = getValue(V: I.getOperand(i_nocapture: 0));
8437 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 1));
8438
8439 // On arm64_32, pointers are 32 bits when stored in memory, but
8440 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to
8441 // match the index type, but the pointer is 64 bits, so the mask must be
8442 // zero-extended up to 64 bits to match the pointer.
8443 EVT PtrVT =
8444 TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i_nocapture: 0)->getType());
8445 EVT MemVT =
8446 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i_nocapture: 0)->getType());
8447 assert(PtrVT == Ptr.getValueType());
8448 if (Mask.getValueType().getFixedSizeInBits() < MemVT.getFixedSizeInBits()) {
8449 // For AMDGPU buffer descriptors the mask is 48 bits, but the pointer is
8450 // 128-bit, so we have to pad the mask with ones for unused bits.
8451 auto HighOnes = DAG.getNode(
8452 Opcode: ISD::SHL, DL: sdl, VT: PtrVT, N1: DAG.getAllOnesConstant(DL: sdl, VT: PtrVT),
8453 N2: DAG.getShiftAmountConstant(Val: Mask.getValueType().getFixedSizeInBits(),
8454 VT: PtrVT, DL: sdl));
8455 Mask = DAG.getNode(Opcode: ISD::OR, DL: sdl, VT: PtrVT,
8456 N1: DAG.getZExtOrTrunc(Op: Mask, DL: sdl, VT: PtrVT), N2: HighOnes);
8457 } else if (Mask.getValueType() != PtrVT)
8458 Mask = DAG.getPtrExtOrTrunc(Op: Mask, DL: sdl, VT: PtrVT);
8459
8460 assert(Mask.getValueType() == PtrVT);
8461 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::AND, DL: sdl, VT: PtrVT, N1: Ptr, N2: Mask));
8462 return;
8463 }
8464 case Intrinsic::threadlocal_address: {
8465 setValue(V: &I, NewN: getValue(V: I.getOperand(i_nocapture: 0)));
8466 return;
8467 }
8468 case Intrinsic::get_active_lane_mask: {
8469 EVT CCVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8470 SDValue Index = getValue(V: I.getOperand(i_nocapture: 0));
8471 SDValue TripCount = getValue(V: I.getOperand(i_nocapture: 1));
8472 EVT ElementVT = Index.getValueType();
8473
8474 if (!TLI.shouldExpandGetActiveLaneMask(VT: CCVT, OpVT: ElementVT)) {
8475 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::GET_ACTIVE_LANE_MASK, DL: sdl, VT: CCVT, N1: Index,
8476 N2: TripCount));
8477 return;
8478 }
8479
8480 EVT VecTy = EVT::getVectorVT(Context&: *DAG.getContext(), VT: ElementVT,
8481 EC: CCVT.getVectorElementCount());
8482
8483 SDValue VectorIndex = DAG.getSplat(VT: VecTy, DL: sdl, Op: Index);
8484 SDValue VectorTripCount = DAG.getSplat(VT: VecTy, DL: sdl, Op: TripCount);
8485 SDValue VectorStep = DAG.getStepVector(DL: sdl, ResVT: VecTy);
8486 SDValue VectorInduction = DAG.getNode(
8487 Opcode: ISD::UADDSAT, DL: sdl, VT: VecTy, N1: VectorIndex, N2: VectorStep);
8488 SDValue SetCC = DAG.getSetCC(DL: sdl, VT: CCVT, LHS: VectorInduction,
8489 RHS: VectorTripCount, Cond: ISD::CondCode::SETULT);
8490 setValue(V: &I, NewN: SetCC);
8491 return;
8492 }
8493 case Intrinsic::experimental_get_vector_length: {
8494 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8495 "Expected positive VF");
8496 unsigned VF = cast<ConstantInt>(Val: I.getOperand(i_nocapture: 1))->getZExtValue();
8497 bool IsScalable = cast<ConstantInt>(Val: I.getOperand(i_nocapture: 2))->isOne();
8498
8499 SDValue Count = getValue(V: I.getOperand(i_nocapture: 0));
8500 EVT CountVT = Count.getValueType();
8501
8502 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8503 visitTargetIntrinsic(I, Intrinsic);
8504 return;
8505 }
8506
8507 // Expand to a umin between the trip count and the maximum elements the type
8508 // can hold.
8509 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8510
8511 // Extend the trip count to at least the result VT.
8512 if (CountVT.bitsLT(VT)) {
8513 Count = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: sdl, VT, Operand: Count);
8514 CountVT = VT;
8515 }
8516
8517 SDValue MaxEVL = DAG.getElementCount(DL: sdl, VT: CountVT,
8518 EC: ElementCount::get(MinVal: VF, Scalable: IsScalable));
8519
8520 SDValue UMin = DAG.getNode(Opcode: ISD::UMIN, DL: sdl, VT: CountVT, N1: Count, N2: MaxEVL);
8521 // Clip to the result type if needed.
8522 SDValue Trunc = DAG.getNode(Opcode: ISD::TRUNCATE, DL: sdl, VT, Operand: UMin);
8523
8524 setValue(V: &I, NewN: Trunc);
8525 return;
8526 }
8527 case Intrinsic::vector_partial_reduce_add: {
8528 SDValue Acc = getValue(V: I.getOperand(i_nocapture: 0));
8529 SDValue Input = getValue(V: I.getOperand(i_nocapture: 1));
8530 setValue(V: &I,
8531 NewN: DAG.getNode(Opcode: ISD::PARTIAL_REDUCE_UMLA, DL: sdl, VT: Acc.getValueType(), N1: Acc,
8532 N2: Input, N3: DAG.getConstant(Val: 1, DL: sdl, VT: Input.getValueType())));
8533 return;
8534 }
8535 case Intrinsic::vector_partial_reduce_fadd: {
8536 SDValue Acc = getValue(V: I.getOperand(i_nocapture: 0));
8537 SDValue Input = getValue(V: I.getOperand(i_nocapture: 1));
8538 setValue(V: &I, NewN: DAG.getNode(
8539 Opcode: ISD::PARTIAL_REDUCE_FMLA, DL: sdl, VT: Acc.getValueType(), N1: Acc,
8540 N2: Input, N3: DAG.getConstantFP(Val: 1.0, DL: sdl, VT: Input.getValueType())));
8541 return;
8542 }
8543 case Intrinsic::experimental_cttz_elts: {
8544 SDValue Op = getValue(V: I.getOperand(i_nocapture: 0));
8545 EVT OpVT = Op.getValueType();
8546 EVT RetTy = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8547 bool ZeroIsPoison =
8548 !cast<ConstantSDNode>(Val: getValue(V: I.getOperand(i_nocapture: 1)))->isZero();
8549 if (OpVT.getVectorElementType() != MVT::i1) {
8550 // Compare the input vector elements to zero & use to count trailing
8551 // zeros.
8552 SDValue AllZero = DAG.getConstant(Val: 0, DL: sdl, VT: OpVT);
8553 EVT I1OpVT = OpVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: MVT::i1);
8554 Op = DAG.getSetCC(DL: sdl, VT: I1OpVT, LHS: Op, RHS: AllZero, Cond: ISD::SETNE);
8555 }
8556 setValue(V: &I, NewN: DAG.getNode(Opcode: ZeroIsPoison ? ISD::CTTZ_ELTS_ZERO_POISON
8557 : ISD::CTTZ_ELTS,
8558 DL: sdl, VT: RetTy, Operand: Op));
8559 return;
8560 }
8561 case Intrinsic::vector_insert: {
8562 SDValue Vec = getValue(V: I.getOperand(i_nocapture: 0));
8563 SDValue SubVec = getValue(V: I.getOperand(i_nocapture: 1));
8564 SDValue Index = getValue(V: I.getOperand(i_nocapture: 2));
8565
8566 // The intrinsic's index type is i64, but the SDNode requires an index type
8567 // suitable for the target. Convert the index as required.
8568 MVT VectorIdxTy = TLI.getVectorIdxTy(DL: DAG.getDataLayout());
8569 if (Index.getValueType() != VectorIdxTy)
8570 Index = DAG.getVectorIdxConstant(Val: Index->getAsZExtVal(), DL: sdl);
8571
8572 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8573 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::INSERT_SUBVECTOR, DL: sdl, VT: ResultVT, N1: Vec, N2: SubVec,
8574 N3: Index));
8575 return;
8576 }
8577 case Intrinsic::vector_extract: {
8578 SDValue Vec = getValue(V: I.getOperand(i_nocapture: 0));
8579 SDValue Index = getValue(V: I.getOperand(i_nocapture: 1));
8580 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8581
8582 // The intrinsic's index type is i64, but the SDNode requires an index type
8583 // suitable for the target. Convert the index as required.
8584 MVT VectorIdxTy = TLI.getVectorIdxTy(DL: DAG.getDataLayout());
8585 if (Index.getValueType() != VectorIdxTy)
8586 Index = DAG.getVectorIdxConstant(Val: Index->getAsZExtVal(), DL: sdl);
8587
8588 setValue(V: &I,
8589 NewN: DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: sdl, VT: ResultVT, N1: Vec, N2: Index));
8590 return;
8591 }
8592 case Intrinsic::experimental_vector_match: {
8593 SDValue Op1 = getValue(V: I.getOperand(i_nocapture: 0));
8594 SDValue Op2 = getValue(V: I.getOperand(i_nocapture: 1));
8595 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 2));
8596 EVT ResVT = Mask.getValueType();
8597 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::VECTOR_MATCH, DL: sdl, VT: ResVT, N1: Op1, N2: Op2, N3: Mask));
8598 return;
8599 }
8600 case Intrinsic::vector_reverse:
8601 visitVectorReverse(I);
8602 return;
8603 case Intrinsic::vector_splice_left:
8604 case Intrinsic::vector_splice_right:
8605 visitVectorSplice(I);
8606 return;
8607 case Intrinsic::callbr_landingpad:
8608 visitCallBrLandingPad(I);
8609 return;
8610 case Intrinsic::vector_interleave2:
8611 visitVectorInterleave(I, Factor: 2);
8612 return;
8613 case Intrinsic::vector_interleave3:
8614 visitVectorInterleave(I, Factor: 3);
8615 return;
8616 case Intrinsic::vector_interleave4:
8617 visitVectorInterleave(I, Factor: 4);
8618 return;
8619 case Intrinsic::vector_interleave5:
8620 visitVectorInterleave(I, Factor: 5);
8621 return;
8622 case Intrinsic::vector_interleave6:
8623 visitVectorInterleave(I, Factor: 6);
8624 return;
8625 case Intrinsic::vector_interleave7:
8626 visitVectorInterleave(I, Factor: 7);
8627 return;
8628 case Intrinsic::vector_interleave8:
8629 visitVectorInterleave(I, Factor: 8);
8630 return;
8631 case Intrinsic::vector_deinterleave2:
8632 visitVectorDeinterleave(I, Factor: 2);
8633 return;
8634 case Intrinsic::vector_deinterleave3:
8635 visitVectorDeinterleave(I, Factor: 3);
8636 return;
8637 case Intrinsic::vector_deinterleave4:
8638 visitVectorDeinterleave(I, Factor: 4);
8639 return;
8640 case Intrinsic::vector_deinterleave5:
8641 visitVectorDeinterleave(I, Factor: 5);
8642 return;
8643 case Intrinsic::vector_deinterleave6:
8644 visitVectorDeinterleave(I, Factor: 6);
8645 return;
8646 case Intrinsic::vector_deinterleave7:
8647 visitVectorDeinterleave(I, Factor: 7);
8648 return;
8649 case Intrinsic::vector_deinterleave8:
8650 visitVectorDeinterleave(I, Factor: 8);
8651 return;
8652 case Intrinsic::experimental_vector_compress:
8653 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::VECTOR_COMPRESS, DL: sdl,
8654 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
8655 N1: getValue(V: I.getArgOperand(i: 0)),
8656 N2: getValue(V: I.getArgOperand(i: 1)),
8657 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
8658 return;
8659 case Intrinsic::experimental_convergence_anchor:
8660 case Intrinsic::experimental_convergence_entry:
8661 case Intrinsic::experimental_convergence_loop:
8662 visitConvergenceControl(I, Intrinsic);
8663 return;
8664 case Intrinsic::experimental_vector_histogram_add: {
8665 visitVectorHistogram(I, IntrinsicID: Intrinsic);
8666 return;
8667 }
8668 case Intrinsic::experimental_vector_extract_last_active: {
8669 visitVectorExtractLastActive(I, Intrinsic);
8670 return;
8671 }
8672 case Intrinsic::loop_dependence_war_mask:
8673 setValue(V: &I,
8674 NewN: DAG.getNode(Opcode: ISD::LOOP_DEPENDENCE_WAR_MASK, DL: sdl,
8675 VT: EVT::getEVT(Ty: I.getType()), N1: getValue(V: I.getOperand(i_nocapture: 0)),
8676 N2: getValue(V: I.getOperand(i_nocapture: 1)), N3: getValue(V: I.getOperand(i_nocapture: 2)),
8677 N4: DAG.getConstant(Val: 0, DL: sdl, VT: MVT::i64)));
8678 return;
8679 case Intrinsic::loop_dependence_raw_mask:
8680 setValue(V: &I,
8681 NewN: DAG.getNode(Opcode: ISD::LOOP_DEPENDENCE_RAW_MASK, DL: sdl,
8682 VT: EVT::getEVT(Ty: I.getType()), N1: getValue(V: I.getOperand(i_nocapture: 0)),
8683 N2: getValue(V: I.getOperand(i_nocapture: 1)), N3: getValue(V: I.getOperand(i_nocapture: 2)),
8684 N4: DAG.getConstant(Val: 0, DL: sdl, VT: MVT::i64)));
8685 return;
8686 case Intrinsic::masked_udiv:
8687 setValue(V: &I,
8688 NewN: DAG.getNode(Opcode: ISD::MASKED_UDIV, DL: sdl, VT: EVT::getEVT(Ty: I.getType()),
8689 N1: getValue(V: I.getOperand(i_nocapture: 0)), N2: getValue(V: I.getOperand(i_nocapture: 1)),
8690 N3: getValue(V: I.getOperand(i_nocapture: 2))));
8691 return;
8692 case Intrinsic::masked_sdiv:
8693 setValue(V: &I,
8694 NewN: DAG.getNode(Opcode: ISD::MASKED_SDIV, DL: sdl, VT: EVT::getEVT(Ty: I.getType()),
8695 N1: getValue(V: I.getOperand(i_nocapture: 0)), N2: getValue(V: I.getOperand(i_nocapture: 1)),
8696 N3: getValue(V: I.getOperand(i_nocapture: 2))));
8697 return;
8698 case Intrinsic::masked_urem:
8699 setValue(V: &I,
8700 NewN: DAG.getNode(Opcode: ISD::MASKED_UREM, DL: sdl, VT: EVT::getEVT(Ty: I.getType()),
8701 N1: getValue(V: I.getOperand(i_nocapture: 0)), N2: getValue(V: I.getOperand(i_nocapture: 1)),
8702 N3: getValue(V: I.getOperand(i_nocapture: 2))));
8703 return;
8704 case Intrinsic::masked_srem:
8705 setValue(V: &I,
8706 NewN: DAG.getNode(Opcode: ISD::MASKED_SREM, DL: sdl, VT: EVT::getEVT(Ty: I.getType()),
8707 N1: getValue(V: I.getOperand(i_nocapture: 0)), N2: getValue(V: I.getOperand(i_nocapture: 1)),
8708 N3: getValue(V: I.getOperand(i_nocapture: 2))));
8709 return;
8710 }
8711}
8712
8713void SelectionDAGBuilder::pushFPOpOutChain(SDValue Result,
8714 fp::ExceptionBehavior EB) {
8715 assert(Result.getNode()->getNumValues() == 2);
8716 SDValue OutChain = Result.getValue(R: 1);
8717 assert(OutChain.getValueType() == MVT::Other);
8718
8719 // Instead of updating the root immediately, push the produced chain to the
8720 // appropriate list, deferring the update until the root is requested. In this
8721 // case, the nodes from the lists are chained using TokenFactor, indicating
8722 // that the operations are independent.
8723 //
8724 // In particular, the root is updated before any call that might access the
8725 // floating-point environment, except for constrained intrinsics.
8726 switch (EB) {
8727 case fp::ExceptionBehavior::ebMayTrap:
8728 case fp::ExceptionBehavior::ebIgnore:
8729 PendingConstrainedFP.push_back(Elt: OutChain);
8730 break;
8731 case fp::ExceptionBehavior::ebStrict:
8732 PendingConstrainedFPStrict.push_back(Elt: OutChain);
8733 break;
8734 }
8735}
8736
8737void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8738 const ConstrainedFPIntrinsic &FPI) {
8739 SDLoc sdl = getCurSDLoc();
8740
8741 // We do not need to serialize constrained FP intrinsics against
8742 // each other or against (nonvolatile) loads, so they can be
8743 // chained like loads.
8744 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8745 SDValue Chain = getFPOperationRoot(EB);
8746 SmallVector<SDValue, 4> Opers;
8747 Opers.push_back(Elt: Chain);
8748 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8749 Opers.push_back(Elt: getValue(V: FPI.getArgOperand(i: I)));
8750
8751 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8752 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: FPI.getType());
8753 SDVTList VTs = DAG.getVTList(VT1: VT, VT2: MVT::Other);
8754
8755 SDNodeFlags Flags;
8756 if (EB == fp::ExceptionBehavior::ebIgnore)
8757 Flags.setNoFPExcept(true);
8758
8759 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &FPI))
8760 Flags.copyFMF(FPMO: *FPOp);
8761
8762 unsigned Opcode;
8763 switch (FPI.getIntrinsicID()) {
8764 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8765#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8766 case Intrinsic::INTRINSIC: \
8767 Opcode = ISD::STRICT_##DAGN; \
8768 break;
8769#include "llvm/IR/ConstrainedOps.def"
8770 case Intrinsic::experimental_constrained_fmuladd: {
8771 Opcode = ISD::STRICT_FMA;
8772 // Break fmuladd into fmul and fadd.
8773 if (!TLI.isFMAFasterThanFMulAndFAdd(MF: DAG.getMachineFunction(), VT)) {
8774 Opers.pop_back();
8775 SDValue Mul = DAG.getNode(Opcode: ISD::STRICT_FMUL, DL: sdl, VTList: VTs, Ops: Opers, Flags);
8776 pushFPOpOutChain(Result: Mul, EB);
8777 Opcode = ISD::STRICT_FADD;
8778 Opers.clear();
8779 Opers.push_back(Elt: Mul.getValue(R: 1));
8780 Opers.push_back(Elt: Mul.getValue(R: 0));
8781 Opers.push_back(Elt: getValue(V: FPI.getArgOperand(i: 2)));
8782 }
8783 break;
8784 }
8785 }
8786
8787 // A few strict DAG nodes carry additional operands that are not
8788 // set up by the default code above.
8789 switch (Opcode) {
8790 default: break;
8791 case ISD::STRICT_FP_ROUND:
8792 Opers.push_back(
8793 Elt: DAG.getTargetConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
8794 break;
8795 case ISD::STRICT_FSETCC:
8796 case ISD::STRICT_FSETCCS: {
8797 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(Val: &FPI);
8798 ISD::CondCode Condition = getFCmpCondCode(Pred: FPCmp->getPredicate());
8799 if (DAG.isKnownNeverNaN(Op: Opers[1]) && DAG.isKnownNeverNaN(Op: Opers[2]))
8800 Condition = getFCmpCodeWithoutNaN(CC: Condition);
8801 Opers.push_back(Elt: DAG.getCondCode(Cond: Condition));
8802 break;
8803 }
8804 }
8805
8806 SDValue Result = DAG.getNode(Opcode, DL: sdl, VTList: VTs, Ops: Opers, Flags);
8807 pushFPOpOutChain(Result, EB);
8808
8809 SDValue FPResult = Result.getValue(R: 0);
8810 setValue(V: &FPI, NewN: FPResult);
8811}
8812
8813static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8814 std::optional<unsigned> ResOPC;
8815 switch (VPIntrin.getIntrinsicID()) {
8816 case Intrinsic::vp_cttz_elts: {
8817 bool IsZeroPoison = cast<ConstantInt>(Val: VPIntrin.getArgOperand(i: 1))->isOne();
8818 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_POISON : ISD::VP_CTTZ_ELTS;
8819 break;
8820 }
8821#define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \
8822 case Intrinsic::VPID: \
8823 ResOPC = ISD::VPSD; \
8824 break;
8825#include "llvm/IR/VPIntrinsics.def"
8826 }
8827
8828 if (!ResOPC)
8829 llvm_unreachable(
8830 "Inconsistency: no SDNode available for this VPIntrinsic!");
8831
8832 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8833 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8834 if (VPIntrin.getFastMathFlags().allowReassoc())
8835 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8836 : ISD::VP_REDUCE_FMUL;
8837 }
8838
8839 return *ResOPC;
8840}
8841
8842void SelectionDAGBuilder::visitVPLoad(
8843 const VPIntrinsic &VPIntrin, EVT VT,
8844 const SmallVectorImpl<SDValue> &OpValues) {
8845 SDLoc DL = getCurSDLoc();
8846 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8847 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8848 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8849 const MDNode *Ranges = getRangeMetadata(I: VPIntrin);
8850 SDValue LD;
8851 // Do not serialize variable-length loads of constant memory with
8852 // anything.
8853 if (!Alignment)
8854 Alignment = DAG.getEVTAlign(MemoryVT: VT);
8855 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
8856 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
8857 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8858 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8859 MachineMemOperand::Flags MMOFlags =
8860 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8861 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8862 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
8863 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: *Alignment,
8864 Metadata: MMOMetadata(AAInfo, Ranges));
8865 LD = DAG.getLoadVP(VT, dl: DL, Chain: InChain, Ptr: OpValues[0], Mask: OpValues[1], EVL: OpValues[2],
8866 MMO, IsExpanding: false /*IsExpanding */);
8867 if (AddToChain)
8868 PendingLoads.push_back(Elt: LD.getValue(R: 1));
8869 setValue(V: &VPIntrin, NewN: LD);
8870}
8871
8872void SelectionDAGBuilder::visitVPLoadFF(
8873 const VPIntrinsic &VPIntrin, EVT VT, EVT EVLVT,
8874 const SmallVectorImpl<SDValue> &OpValues) {
8875 assert(OpValues.size() == 3 && "Unexpected number of operands");
8876 SDLoc DL = getCurSDLoc();
8877 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8878 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8879 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8880 const MDNode *Ranges = VPIntrin.getMetadata(KindID: LLVMContext::MD_range);
8881 SDValue LD;
8882 // Do not serialize variable-length loads of constant memory with
8883 // anything.
8884 if (!Alignment)
8885 Alignment = DAG.getEVTAlign(MemoryVT: VT);
8886 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
8887 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
8888 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8889 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8890 PtrInfo: MachinePointerInfo(PtrOperand), F: MachineMemOperand::MOLoad,
8891 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: *Alignment,
8892 Metadata: MMOMetadata(AAInfo, Ranges));
8893 LD = DAG.getLoadFFVP(VT, DL, Chain: InChain, Ptr: OpValues[0], Mask: OpValues[1], EVL: OpValues[2],
8894 MMO);
8895 SDValue Trunc = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: EVLVT, Operand: LD.getValue(R: 1));
8896 if (AddToChain)
8897 PendingLoads.push_back(Elt: LD.getValue(R: 2));
8898 setValue(V: &VPIntrin, NewN: DAG.getMergeValues(Ops: {LD.getValue(R: 0), Trunc}, dl: DL));
8899}
8900
8901void SelectionDAGBuilder::visitVPGather(
8902 const VPIntrinsic &VPIntrin, EVT VT,
8903 const SmallVectorImpl<SDValue> &OpValues) {
8904 SDLoc DL = getCurSDLoc();
8905 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8906 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8907 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8908 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8909 const MDNode *Ranges = getRangeMetadata(I: VPIntrin);
8910 SDValue LD;
8911 if (!Alignment)
8912 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
8913 unsigned AS =
8914 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8915 MachineMemOperand::Flags MMOFlags =
8916 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8917 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8918 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
8919 BaseAlignment: *Alignment, Metadata: MMOMetadata(AAInfo, Ranges));
8920 SDValue Base, Index, Scale;
8921 bool UniformBase =
8922 getUniformBase(Ptr: PtrOperand, Base, Index, Scale, SDB: this, CurBB: VPIntrin.getParent(),
8923 ElemSize: VT.getScalarStoreSize());
8924 if (!UniformBase) {
8925 Base = DAG.getConstant(Val: 0, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8926 Index = getValue(V: PtrOperand);
8927 Scale = DAG.getTargetConstant(Val: 1, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8928 }
8929 EVT IdxVT = Index.getValueType();
8930 EVT EltTy = IdxVT.getVectorElementType();
8931 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
8932 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
8933 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT: NewIdxVT, Operand: Index);
8934 }
8935 LD = DAG.getGatherVP(
8936 VTs: DAG.getVTList(VT1: VT, VT2: MVT::Other), VT, dl: DL,
8937 Ops: {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8938 IndexType: ISD::SIGNED_SCALED);
8939 PendingLoads.push_back(Elt: LD.getValue(R: 1));
8940 setValue(V: &VPIntrin, NewN: LD);
8941}
8942
8943void SelectionDAGBuilder::visitVPStore(
8944 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8945 SDLoc DL = getCurSDLoc();
8946 Value *PtrOperand = VPIntrin.getArgOperand(i: 1);
8947 EVT VT = OpValues[0].getValueType();
8948 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8949 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8950 SDValue ST;
8951 if (!Alignment)
8952 Alignment = DAG.getEVTAlign(MemoryVT: VT);
8953 SDValue Ptr = OpValues[1];
8954 SDValue Offset = DAG.getPOISON(VT: Ptr.getValueType());
8955 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8956 MachineMemOperand::Flags MMOFlags =
8957 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8958 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8959 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
8960 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: *Alignment, Metadata: AAInfo);
8961 ST = DAG.getStoreVP(Chain: getMemoryRoot(), dl: DL, Val: OpValues[0], Ptr, Offset,
8962 Mask: OpValues[2], EVL: OpValues[3], MemVT: VT, MMO, AM: ISD::UNINDEXED,
8963 /* IsTruncating */ false, /*IsCompressing*/ false);
8964 DAG.setRoot(ST);
8965 setValue(V: &VPIntrin, NewN: ST);
8966}
8967
8968void SelectionDAGBuilder::visitVPScatter(
8969 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8970 SDLoc DL = getCurSDLoc();
8971 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8972 Value *PtrOperand = VPIntrin.getArgOperand(i: 1);
8973 EVT VT = OpValues[0].getValueType();
8974 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8975 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8976 SDValue ST;
8977 if (!Alignment)
8978 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
8979 unsigned AS =
8980 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8981 MachineMemOperand::Flags MMOFlags =
8982 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8983 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8984 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
8985 BaseAlignment: *Alignment, Metadata: AAInfo);
8986 SDValue Base, Index, Scale;
8987 bool UniformBase =
8988 getUniformBase(Ptr: PtrOperand, Base, Index, Scale, SDB: this, CurBB: VPIntrin.getParent(),
8989 ElemSize: VT.getScalarStoreSize());
8990 if (!UniformBase) {
8991 Base = DAG.getConstant(Val: 0, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8992 Index = getValue(V: PtrOperand);
8993 Scale = DAG.getTargetConstant(Val: 1, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8994 }
8995 EVT IdxVT = Index.getValueType();
8996 EVT EltTy = IdxVT.getVectorElementType();
8997 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
8998 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
8999 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT: NewIdxVT, Operand: Index);
9000 }
9001 ST = DAG.getScatterVP(VTs: DAG.getVTList(VT: MVT::Other), VT, dl: DL,
9002 Ops: {getMemoryRoot(), OpValues[0], Base, Index, Scale,
9003 OpValues[2], OpValues[3]},
9004 MMO, IndexType: ISD::SIGNED_SCALED);
9005 DAG.setRoot(ST);
9006 setValue(V: &VPIntrin, NewN: ST);
9007}
9008
9009void SelectionDAGBuilder::visitVPStridedLoad(
9010 const VPIntrinsic &VPIntrin, EVT VT,
9011 const SmallVectorImpl<SDValue> &OpValues) {
9012 SDLoc DL = getCurSDLoc();
9013 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
9014 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9015 if (!Alignment)
9016 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
9017 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9018 const MDNode *Ranges = getRangeMetadata(I: VPIntrin);
9019 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
9020 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
9021 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9022 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9023 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9024 MachineMemOperand::Flags MMOFlags =
9025 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9026 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9027 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
9028 BaseAlignment: *Alignment, Metadata: MMOMetadata(AAInfo, Ranges));
9029
9030 SDValue LD = DAG.getStridedLoadVP(VT, DL, Chain: InChain, Ptr: OpValues[0], Stride: OpValues[1],
9031 Mask: OpValues[2], EVL: OpValues[3], MMO,
9032 IsExpanding: false /*IsExpanding*/);
9033
9034 if (AddToChain)
9035 PendingLoads.push_back(Elt: LD.getValue(R: 1));
9036 setValue(V: &VPIntrin, NewN: LD);
9037}
9038
9039void SelectionDAGBuilder::visitVPStridedStore(
9040 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9041 SDLoc DL = getCurSDLoc();
9042 Value *PtrOperand = VPIntrin.getArgOperand(i: 1);
9043 EVT VT = OpValues[0].getValueType();
9044 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9045 if (!Alignment)
9046 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
9047 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9048 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9049 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9050 MachineMemOperand::Flags MMOFlags =
9051 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9052 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9053 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
9054 BaseAlignment: *Alignment, Metadata: AAInfo);
9055
9056 SDValue ST = DAG.getStridedStoreVP(
9057 Chain: getMemoryRoot(), DL, Val: OpValues[0], Ptr: OpValues[1],
9058 Offset: DAG.getPOISON(VT: OpValues[1].getValueType()), Stride: OpValues[2], Mask: OpValues[3],
9059 EVL: OpValues[4], MemVT: VT, MMO, AM: ISD::UNINDEXED, /*IsTruncating*/ false,
9060 /*IsCompressing*/ false);
9061
9062 DAG.setRoot(ST);
9063 setValue(V: &VPIntrin, NewN: ST);
9064}
9065
9066void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
9067 const VPIntrinsic &VPIntrin) {
9068 SDLoc DL = getCurSDLoc();
9069 unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
9070
9071 auto IID = VPIntrin.getIntrinsicID();
9072
9073 SmallVector<EVT, 4> ValueVTs;
9074 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9075 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: VPIntrin.getType(), ValueVTs);
9076 SDVTList VTs = DAG.getVTList(VTs: ValueVTs);
9077
9078 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IntrinsicID: IID);
9079
9080 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
9081 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
9082 "Unexpected target EVL type");
9083
9084 // Request operands.
9085 SmallVector<SDValue, 7> OpValues;
9086 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
9087 auto Op = getValue(V: VPIntrin.getArgOperand(i: I));
9088 if (I == EVLParamPos)
9089 Op = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL, VT: EVLParamVT, Operand: Op);
9090 OpValues.push_back(Elt: Op);
9091 }
9092
9093 switch (Opcode) {
9094 default: {
9095 SDNodeFlags SDFlags;
9096 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &VPIntrin))
9097 SDFlags.copyFMF(FPMO: *FPMO);
9098 SDValue Result = DAG.getNode(Opcode, DL, VTList: VTs, Ops: OpValues, Flags: SDFlags);
9099 setValue(V: &VPIntrin, NewN: Result);
9100 break;
9101 }
9102 case ISD::VP_LOAD:
9103 visitVPLoad(VPIntrin, VT: ValueVTs[0], OpValues);
9104 break;
9105 case ISD::VP_LOAD_FF:
9106 visitVPLoadFF(VPIntrin, VT: ValueVTs[0], EVLVT: ValueVTs[1], OpValues);
9107 break;
9108 case ISD::VP_GATHER:
9109 visitVPGather(VPIntrin, VT: ValueVTs[0], OpValues);
9110 break;
9111 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
9112 visitVPStridedLoad(VPIntrin, VT: ValueVTs[0], OpValues);
9113 break;
9114 case ISD::VP_STORE:
9115 visitVPStore(VPIntrin, OpValues);
9116 break;
9117 case ISD::VP_SCATTER:
9118 visitVPScatter(VPIntrin, OpValues);
9119 break;
9120 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
9121 visitVPStridedStore(VPIntrin, OpValues);
9122 break;
9123 case ISD::VP_CTTZ_ELTS_ZERO_POISON:
9124 case ISD::VP_CTTZ_ELTS: {
9125 SDValue Result =
9126 DAG.getNode(Opcode, DL, VTList: VTs, Ops: {OpValues[0], OpValues[2], OpValues[3]});
9127 setValue(V: &VPIntrin, NewN: Result);
9128 break;
9129 }
9130 }
9131}
9132
9133SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
9134 const BasicBlock *EHPadBB,
9135 MCSymbol *&BeginLabel) {
9136 MachineFunction &MF = DAG.getMachineFunction();
9137
9138 // Insert a label before the invoke call to mark the try range. This can be
9139 // used to detect deletion of the invoke via the MachineModuleInfo.
9140 BeginLabel = MF.getContext().createTempSymbol();
9141
9142 // For SjLj, keep track of which landing pads go with which invokes
9143 // so as to maintain the ordering of pads in the LSDA.
9144 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
9145 if (CallSiteIndex) {
9146 MF.setCallSiteBeginLabel(BeginLabel, Site: CallSiteIndex);
9147 LPadToCallSiteMap[FuncInfo.getMBB(BB: EHPadBB)].push_back(Elt: CallSiteIndex);
9148
9149 // Now that the call site is handled, stop tracking it.
9150 FuncInfo.setCurrentCallSite(0);
9151 }
9152
9153 return DAG.getEHLabel(dl: getCurSDLoc(), Root: Chain, Label: BeginLabel);
9154}
9155
9156SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
9157 const BasicBlock *EHPadBB,
9158 MCSymbol *BeginLabel) {
9159 assert(BeginLabel && "BeginLabel should've been set");
9160
9161 MachineFunction &MF = DAG.getMachineFunction();
9162
9163 // Insert a label at the end of the invoke call to mark the try range. This
9164 // can be used to detect deletion of the invoke via the MachineModuleInfo.
9165 MCSymbol *EndLabel = MF.getContext().createTempSymbol();
9166 Chain = DAG.getEHLabel(dl: getCurSDLoc(), Root: Chain, Label: EndLabel);
9167
9168 // Inform MachineModuleInfo of range.
9169 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
9170 // There is a platform (e.g. wasm) that uses funclet style IR but does not
9171 // actually use outlined funclets and their LSDA info style.
9172 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
9173 assert(II && "II should've been set");
9174 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
9175 EHInfo->addIPToStateRange(II, InvokeBegin: BeginLabel, InvokeEnd: EndLabel);
9176 } else if (!isScopedEHPersonality(Pers)) {
9177 assert(EHPadBB);
9178 MF.addInvoke(LandingPad: FuncInfo.getMBB(BB: EHPadBB), BeginLabel, EndLabel);
9179 }
9180
9181 return Chain;
9182}
9183
9184std::pair<SDValue, SDValue>
9185SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
9186 const BasicBlock *EHPadBB) {
9187 MCSymbol *BeginLabel = nullptr;
9188
9189 if (EHPadBB) {
9190 // Both PendingLoads and PendingExports must be flushed here;
9191 // this call might not return.
9192 (void)getRoot();
9193 DAG.setRoot(lowerStartEH(Chain: getControlRoot(), EHPadBB, BeginLabel));
9194 CLI.setChain(getRoot());
9195 }
9196
9197 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9198 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
9199
9200 assert((CLI.IsTailCall || Result.second.getNode()) &&
9201 "Non-null chain expected with non-tail call!");
9202 assert((Result.second.getNode() || !Result.first.getNode()) &&
9203 "Null value expected with tail call!");
9204
9205 if (!Result.second.getNode()) {
9206 // As a special case, a null chain means that a tail call has been emitted
9207 // and the DAG root is already updated.
9208 HasTailCall = true;
9209
9210 // Since there's no actual continuation from this block, nothing can be
9211 // relying on us setting vregs for them.
9212 PendingExports.clear();
9213 } else {
9214 DAG.setRoot(Result.second);
9215 }
9216
9217 if (EHPadBB) {
9218 DAG.setRoot(lowerEndEH(Chain: getRoot(), II: cast_or_null<InvokeInst>(Val: CLI.CB), EHPadBB,
9219 BeginLabel));
9220 Result.second = getRoot();
9221 }
9222
9223 return Result;
9224}
9225
9226bool SelectionDAGBuilder::canTailCall(const CallBase &CB) const {
9227 bool isMustTailCall = CB.isMustTailCall();
9228
9229 // Avoid emitting tail calls in functions with the disable-tail-calls
9230 // attribute.
9231 const Function *Caller = CB.getParent()->getParent();
9232 if (!isMustTailCall &&
9233 Caller->getFnAttribute(Kind: "disable-tail-calls").getValueAsBool())
9234 return false;
9235
9236 // We can't tail call inside a function with a swifterror argument. Lowering
9237 // does not support this yet. It would have to move into the swifterror
9238 // register before the call.
9239 if (DAG.hasSwiftErrorArg())
9240 return false;
9241
9242 // Check if target-independent constraints permit a tail call here.
9243 // Target-dependent constraints are checked within TLI->LowerCallTo.
9244 return isInTailCallPosition(Call: CB, TM: DAG.getTarget());
9245}
9246
9247void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
9248 bool isTailCall, bool isMustTailCall,
9249 const BasicBlock *EHPadBB,
9250 const TargetLowering::PtrAuthInfo *PAI) {
9251 auto &DL = DAG.getDataLayout();
9252 FunctionType *FTy = CB.getFunctionType();
9253 Type *RetTy = CB.getType();
9254
9255 TargetLowering::ArgListTy Args;
9256 Args.reserve(n: CB.arg_size());
9257
9258 const Value *SwiftErrorVal = nullptr;
9259 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9260
9261 if (isTailCall)
9262 isTailCall = canTailCall(CB);
9263
9264 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
9265 const Value *V = *I;
9266
9267 // Skip empty types
9268 if (V->getType()->isEmptyTy())
9269 continue;
9270
9271 SDValue ArgNode = getValue(V);
9272 TargetLowering::ArgListEntry Entry(ArgNode, V->getType());
9273 Entry.setAttributes(Call: &CB, ArgIdx: I - CB.arg_begin());
9274
9275 // Use swifterror virtual register as input to the call.
9276 if (Entry.IsSwiftError && TLI.supportSwiftError()) {
9277 SwiftErrorVal = V;
9278 // We find the virtual register for the actual swifterror argument.
9279 // Instead of using the Value, we use the virtual register instead.
9280 Entry.Node =
9281 DAG.getRegister(Reg: SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
9282 VT: EVT(TLI.getPointerTy(DL)));
9283 }
9284
9285 Args.push_back(x: Entry);
9286
9287 // If we have an explicit sret argument that is an Instruction, (i.e., it
9288 // might point to function-local memory), we can't meaningfully tail-call.
9289 if (Entry.IsSRet && isa<Instruction>(Val: V))
9290 isTailCall = false;
9291 }
9292
9293 // If call site has a cfguardtarget operand bundle, create and add an
9294 // additional ArgListEntry.
9295 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_cfguardtarget)) {
9296 Value *V = Bundle->Inputs[0];
9297 TargetLowering::ArgListEntry Entry(V, getValue(V));
9298 Entry.IsCFGuardTarget = true;
9299 Args.push_back(x: Entry);
9300 }
9301
9302 // Disable tail calls if there is an swifterror argument. Targets have not
9303 // been updated to support tail calls.
9304 if (TLI.supportSwiftError() && SwiftErrorVal)
9305 isTailCall = false;
9306
9307 ConstantInt *CFIType = nullptr;
9308 if (CB.isIndirectCall()) {
9309 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_kcfi)) {
9310 if (!TLI.supportKCFIBundles())
9311 report_fatal_error(
9312 reason: "Target doesn't support calls with kcfi operand bundles.");
9313 CFIType = cast<ConstantInt>(Val: Bundle->Inputs[0]);
9314 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
9315 }
9316 }
9317
9318 SDValue ConvControlToken;
9319 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_convergencectrl)) {
9320 auto *Token = Bundle->Inputs[0].get();
9321 ConvControlToken = getValue(V: Token);
9322 }
9323
9324 GlobalValue *DeactivationSymbol = nullptr;
9325 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_deactivation_symbol)) {
9326 DeactivationSymbol = cast<GlobalValue>(Val: Bundle->Inputs[0].get());
9327 }
9328
9329 TargetLowering::CallLoweringInfo CLI(DAG);
9330 CLI.setDebugLoc(getCurSDLoc())
9331 .setChain(getRoot())
9332 .setCallee(ResultType: RetTy, FTy, Target: Callee, ArgsList: std::move(Args), Call: CB)
9333 .setTailCall(isTailCall)
9334 .setConvergent(CB.isConvergent())
9335 .setIsPreallocated(
9336 CB.countOperandBundlesOfType(ID: LLVMContext::OB_preallocated) != 0)
9337 .setCFIType(CFIType)
9338 .setConvergenceControlToken(ConvControlToken)
9339 .setDeactivationSymbol(DeactivationSymbol);
9340
9341 // Set the pointer authentication info if we have it.
9342 if (PAI) {
9343 if (!TLI.supportPtrAuthBundles())
9344 report_fatal_error(
9345 reason: "This target doesn't support calls with ptrauth operand bundles.");
9346 CLI.setPtrAuth(*PAI);
9347 }
9348
9349 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9350
9351 if (Result.first.getNode()) {
9352 Result.first = lowerRangeToAssertZExt(DAG, I: CB, Op: Result.first);
9353 Result.first = lowerNoFPClassToAssertNoFPClass(DAG, I: CB, Op: Result.first);
9354 setValue(V: &CB, NewN: Result.first);
9355 }
9356
9357 // The last element of CLI.InVals has the SDValue for swifterror return.
9358 // Here we copy it to a virtual register and update SwiftErrorMap for
9359 // book-keeping.
9360 if (SwiftErrorVal && TLI.supportSwiftError()) {
9361 // Get the last element of InVals.
9362 SDValue Src = CLI.InVals.back();
9363 Register VReg =
9364 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
9365 SDValue CopyNode = CLI.DAG.getCopyToReg(Chain: Result.second, dl: CLI.DL, Reg: VReg, N: Src);
9366 DAG.setRoot(CopyNode);
9367 }
9368}
9369
9370static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
9371 SelectionDAGBuilder &Builder) {
9372 // Check to see if this load can be trivially constant folded, e.g. if the
9373 // input is from a string literal.
9374 if (const Constant *LoadInput = dyn_cast<Constant>(Val: PtrVal)) {
9375 // Cast pointer to the type we really want to load.
9376 Type *LoadTy =
9377 Type::getIntNTy(C&: PtrVal->getContext(), N: LoadVT.getScalarSizeInBits());
9378 if (LoadVT.isVector())
9379 LoadTy = FixedVectorType::get(ElementType: LoadTy, NumElts: LoadVT.getVectorNumElements());
9380 if (const Constant *LoadCst =
9381 ConstantFoldLoadFromConstPtr(C: const_cast<Constant *>(LoadInput),
9382 Ty: LoadTy, DL: Builder.DAG.getDataLayout()))
9383 return Builder.getValue(V: LoadCst);
9384 }
9385
9386 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
9387 // still constant memory, the input chain can be the entry node.
9388 SDValue Root;
9389 bool ConstantMemory = false;
9390
9391 // Do not serialize (non-volatile) loads of constant memory with anything.
9392 if (Builder.BatchAA && Builder.BatchAA->pointsToConstantMemory(P: PtrVal)) {
9393 Root = Builder.DAG.getEntryNode();
9394 ConstantMemory = true;
9395 } else {
9396 // Do not serialize non-volatile loads against each other.
9397 Root = Builder.DAG.getRoot();
9398 }
9399
9400 SDValue Ptr = Builder.getValue(V: PtrVal);
9401 SDValue LoadVal =
9402 Builder.DAG.getLoad(VT: LoadVT, dl: Builder.getCurSDLoc(), Chain: Root, Ptr,
9403 PtrInfo: MachinePointerInfo(PtrVal), Alignment: Align(1));
9404
9405 if (!ConstantMemory)
9406 Builder.PendingLoads.push_back(Elt: LoadVal.getValue(R: 1));
9407 return LoadVal;
9408}
9409
9410/// Record the value for an instruction that produces an integer result,
9411/// converting the type where necessary.
9412void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
9413 SDValue Value,
9414 bool IsSigned) {
9415 EVT VT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
9416 Ty: I.getType(), AllowUnknown: true);
9417 Value = DAG.getExtOrTrunc(IsSigned, Op: Value, DL: getCurSDLoc(), VT);
9418 setValue(V: &I, NewN: Value);
9419}
9420
9421/// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
9422/// true and lower it. Otherwise return false, and it will be lowered like a
9423/// normal call.
9424/// The caller already checked that \p I calls the appropriate LibFunc with a
9425/// correct prototype.
9426bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
9427 const Value *LHS = I.getArgOperand(i: 0), *RHS = I.getArgOperand(i: 1);
9428 const Value *Size = I.getArgOperand(i: 2);
9429 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(Val: getValue(V: Size));
9430 if (CSize && CSize->getZExtValue() == 0) {
9431 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
9432 Ty: I.getType(), AllowUnknown: true);
9433 setValue(V: &I, NewN: DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: CallVT));
9434 return true;
9435 }
9436
9437 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9438 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9439 DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(), Op1: getValue(V: LHS), Op2: getValue(V: RHS),
9440 Op3: getValue(V: Size), CI: &I);
9441 if (Res.first.getNode()) {
9442 processIntegerCallValue(I, Value: Res.first, IsSigned: true);
9443 PendingLoads.push_back(Elt: Res.second);
9444 return true;
9445 }
9446
9447 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
9448 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
9449 if (!CSize || !isOnlyUsedInZeroEqualityComparison(CxtI: &I))
9450 return false;
9451
9452 // If the target has a fast compare for the given size, it will return a
9453 // preferred load type for that size. Require that the load VT is legal and
9454 // that the target supports unaligned loads of that type. Otherwise, return
9455 // INVALID.
9456 auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9457 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9458 MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9459 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9460 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9461 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9462 // TODO: Check alignment of src and dest ptrs.
9463 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9464 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9465 if (!TLI.isTypeLegal(VT: LVT) ||
9466 !TLI.allowsMisalignedMemoryAccesses(LVT, AddrSpace: SrcAS) ||
9467 !TLI.allowsMisalignedMemoryAccesses(LVT, AddrSpace: DstAS))
9468 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
9469 }
9470
9471 return LVT;
9472 };
9473
9474 // This turns into unaligned loads. We only do this if the target natively
9475 // supports the MVT we'll be loading or if it is small enough (<= 4) that
9476 // we'll only produce a small number of byte loads.
9477 MVT LoadVT;
9478 unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9479 switch (NumBitsToCompare) {
9480 default:
9481 return false;
9482 case 16:
9483 LoadVT = MVT::i16;
9484 break;
9485 case 32:
9486 LoadVT = MVT::i32;
9487 break;
9488 case 64:
9489 case 128:
9490 case 256:
9491 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9492 break;
9493 }
9494
9495 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9496 return false;
9497
9498 SDValue LoadL = getMemCmpLoad(PtrVal: LHS, LoadVT, Builder&: *this);
9499 SDValue LoadR = getMemCmpLoad(PtrVal: RHS, LoadVT, Builder&: *this);
9500
9501 // Bitcast to a wide integer type if the loads are vectors.
9502 if (LoadVT.isVector()) {
9503 EVT CmpVT = EVT::getIntegerVT(Context&: LHS->getContext(), BitWidth: LoadVT.getSizeInBits());
9504 LoadL = DAG.getBitcast(VT: CmpVT, V: LoadL);
9505 LoadR = DAG.getBitcast(VT: CmpVT, V: LoadR);
9506 }
9507
9508 SDValue Cmp = DAG.getSetCC(DL: getCurSDLoc(), VT: MVT::i1, LHS: LoadL, RHS: LoadR, Cond: ISD::SETNE);
9509 processIntegerCallValue(I, Value: Cmp, IsSigned: false);
9510 return true;
9511}
9512
9513/// See if we can lower a memchr call into an optimized form. If so, return
9514/// true and lower it. Otherwise return false, and it will be lowered like a
9515/// normal call.
9516/// The caller already checked that \p I calls the appropriate LibFunc with a
9517/// correct prototype.
9518bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9519 const Value *Src = I.getArgOperand(i: 0);
9520 const Value *Char = I.getArgOperand(i: 1);
9521 const Value *Length = I.getArgOperand(i: 2);
9522
9523 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9524 std::pair<SDValue, SDValue> Res =
9525 TSI.EmitTargetCodeForMemchr(DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(),
9526 Src: getValue(V: Src), Char: getValue(V: Char), Length: getValue(V: Length),
9527 SrcPtrInfo: MachinePointerInfo(Src));
9528 if (Res.first.getNode()) {
9529 setValue(V: &I, NewN: Res.first);
9530 PendingLoads.push_back(Elt: Res.second);
9531 return true;
9532 }
9533
9534 return false;
9535}
9536
9537/// See if we can lower a memccpy call into an optimized form. If so, return
9538/// true and lower it, otherwise return false and it will be lowered like a
9539/// normal call.
9540/// The caller already checked that \p I calls the appropriate LibFunc with a
9541/// correct prototype.
9542bool SelectionDAGBuilder::visitMemCCpyCall(const CallInst &I) {
9543 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9544 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemccpy(
9545 DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(), Dst: getValue(V: I.getArgOperand(i: 0)),
9546 Src: getValue(V: I.getArgOperand(i: 1)), C: getValue(V: I.getArgOperand(i: 2)),
9547 Size: getValue(V: I.getArgOperand(i: 3)), CI: &I);
9548
9549 if (Res.first) {
9550 processIntegerCallValue(I, Value: Res.first, IsSigned: true);
9551 PendingLoads.push_back(Elt: Res.second);
9552 return true;
9553 }
9554 return false;
9555}
9556
9557/// See if we can lower a mempcpy call into an optimized form. If so, return
9558/// true and lower it. Otherwise return false, and it will be lowered like a
9559/// normal call.
9560/// The caller already checked that \p I calls the appropriate LibFunc with a
9561/// correct prototype.
9562bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9563 SDValue Dst = getValue(V: I.getArgOperand(i: 0));
9564 SDValue Src = getValue(V: I.getArgOperand(i: 1));
9565 SDValue Size = getValue(V: I.getArgOperand(i: 2));
9566
9567 Align DstAlign = DAG.InferPtrAlign(Ptr: Dst).valueOrOne();
9568 Align SrcAlign = DAG.InferPtrAlign(Ptr: Src).valueOrOne();
9569
9570 SDLoc sdl = getCurSDLoc();
9571
9572 // In the mempcpy context we need to pass in a false value for isTailCall
9573 // because the return pointer needs to be adjusted by the size of
9574 // the copied memory.
9575 SDValue Root = getMemoryRoot();
9576 SDValue MC = DAG.getMemcpy(
9577 Chain: Root, dl: sdl, Dst, Src, Size, DstAlign, SrcAlign, isVol: false, AlwaysInline: false,
9578 /*CI=*/nullptr, OverrideTailCall: std::nullopt, DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
9579 SrcPtrInfo: MachinePointerInfo(I.getArgOperand(i: 1)), AAInfo: I.getAAMetadata());
9580 assert(MC.getNode() != nullptr &&
9581 "** memcpy should not be lowered as TailCall in mempcpy context **");
9582 DAG.setRoot(MC);
9583
9584 // Check if Size needs to be truncated or extended.
9585 Size = DAG.getSExtOrTrunc(Op: Size, DL: sdl, VT: Dst.getValueType());
9586
9587 // Adjust return pointer to point just past the last dst byte.
9588 SDValue DstPlusSize = DAG.getMemBasePlusOffset(Base: Dst, Offset: Size, DL: sdl);
9589 setValue(V: &I, NewN: DstPlusSize);
9590 return true;
9591}
9592
9593/// See if we can lower a strcpy call into an optimized form. If so, return
9594/// true and lower it, otherwise return false and it will be lowered like a
9595/// normal call.
9596/// The caller already checked that \p I calls the appropriate LibFunc with a
9597/// correct prototype.
9598bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9599 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9600
9601 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9602 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcpy(
9603 DAG, DL: getCurSDLoc(), Chain: getRoot(), Dest: getValue(V: Arg0), Src: getValue(V: Arg1),
9604 DestPtrInfo: MachinePointerInfo(Arg0), SrcPtrInfo: MachinePointerInfo(Arg1), isStpcpy, CI: &I);
9605 if (Res.first.getNode()) {
9606 setValue(V: &I, NewN: Res.first);
9607 DAG.setRoot(Res.second);
9608 return true;
9609 }
9610
9611 return false;
9612}
9613
9614/// See if we can lower a strcmp call into an optimized form. If so, return
9615/// true and lower it, otherwise return false and it will be lowered like a
9616/// normal call.
9617/// The caller already checked that \p I calls the appropriate LibFunc with a
9618/// correct prototype.
9619bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9620 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9621
9622 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9623 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcmp(
9624 DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(), Op1: getValue(V: Arg0), Op2: getValue(V: Arg1),
9625 Op1PtrInfo: MachinePointerInfo(Arg0), Op2PtrInfo: MachinePointerInfo(Arg1), CI: &I);
9626 if (Res.first.getNode()) {
9627 processIntegerCallValue(I, Value: Res.first, IsSigned: true);
9628 PendingLoads.push_back(Elt: Res.second);
9629 return true;
9630 }
9631
9632 return false;
9633}
9634
9635/// See if we can lower a strlen call into an optimized form. If so, return
9636/// true and lower it, otherwise return false and it will be lowered like a
9637/// normal call.
9638/// The caller already checked that \p I calls the appropriate LibFunc with a
9639/// correct prototype.
9640bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9641 const Value *Arg0 = I.getArgOperand(i: 0);
9642
9643 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9644 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrlen(
9645 DAG, DL: getCurSDLoc(), Chain: DAG.getRoot(), Src: getValue(V: Arg0), CI: &I);
9646 if (Res.first.getNode()) {
9647 processIntegerCallValue(I, Value: Res.first, IsSigned: false);
9648 PendingLoads.push_back(Elt: Res.second);
9649 return true;
9650 }
9651
9652 return false;
9653}
9654
9655/// See if we can lower a strnlen call into an optimized form. If so, return
9656/// true and lower it, otherwise return false and it will be lowered like a
9657/// normal call.
9658/// The caller already checked that \p I calls the appropriate LibFunc with a
9659/// correct prototype.
9660bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9661 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9662
9663 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9664 std::pair<SDValue, SDValue> Res =
9665 TSI.EmitTargetCodeForStrnlen(DAG, DL: getCurSDLoc(), Chain: DAG.getRoot(),
9666 Src: getValue(V: Arg0), MaxLength: getValue(V: Arg1),
9667 SrcPtrInfo: MachinePointerInfo(Arg0));
9668 if (Res.first.getNode()) {
9669 processIntegerCallValue(I, Value: Res.first, IsSigned: false);
9670 PendingLoads.push_back(Elt: Res.second);
9671 return true;
9672 }
9673
9674 return false;
9675}
9676
9677/// See if we can lower a Strstr call into an optimized form. If so, return
9678/// true and lower it, otherwise return false and it will be lowered like a
9679/// normal call.
9680/// The caller already checked that \p I calls the appropriate LibFunc with a
9681/// correct prototype.
9682bool SelectionDAGBuilder::visitStrstrCall(const CallInst &I) {
9683 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9684 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9685 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrstr(
9686 DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(), Op1: getValue(V: Arg0), Op2: getValue(V: Arg1), CI: &I);
9687 if (Res.first) {
9688 processIntegerCallValue(I, Value: Res.first, IsSigned: false);
9689 PendingLoads.push_back(Elt: Res.second);
9690 return true;
9691 }
9692 return false;
9693}
9694
9695/// See if we can lower a unary floating-point operation into an SDNode with
9696/// the specified Opcode. If so, return true and lower it, otherwise return
9697/// false and it will be lowered like a normal call.
9698/// The caller already checked that \p I calls the appropriate LibFunc with a
9699/// correct prototype.
9700bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9701 unsigned Opcode) {
9702 // We already checked this call's prototype; verify it doesn't modify errno.
9703 // Do not perform optimizations for call sites that require strict
9704 // floating-point semantics.
9705 if (!I.onlyReadsMemory() || I.isStrictFP())
9706 return false;
9707
9708 SDNodeFlags Flags;
9709 Flags.copyFMF(FPMO: cast<FPMathOperator>(Val: I));
9710
9711 SDValue Tmp = getValue(V: I.getArgOperand(i: 0));
9712 setValue(V: &I,
9713 NewN: DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Tmp.getValueType(), Operand: Tmp, Flags));
9714 return true;
9715}
9716
9717/// See if we can lower a binary floating-point operation into an SDNode with
9718/// the specified Opcode. If so, return true and lower it. Otherwise return
9719/// false, and it will be lowered like a normal call.
9720/// The caller already checked that \p I calls the appropriate LibFunc with a
9721/// correct prototype.
9722bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9723 unsigned Opcode) {
9724 // We already checked this call's prototype; verify it doesn't modify errno.
9725 // Do not perform optimizations for call sites that require strict
9726 // floating-point semantics.
9727 if (!I.onlyReadsMemory() || I.isStrictFP())
9728 return false;
9729
9730 SDNodeFlags Flags;
9731 Flags.copyFMF(FPMO: cast<FPMathOperator>(Val: I));
9732
9733 SDValue Tmp0 = getValue(V: I.getArgOperand(i: 0));
9734 SDValue Tmp1 = getValue(V: I.getArgOperand(i: 1));
9735 EVT VT = Tmp0.getValueType();
9736 setValue(V: &I, NewN: DAG.getNode(Opcode, DL: getCurSDLoc(), VT, N1: Tmp0, N2: Tmp1, Flags));
9737 return true;
9738}
9739
9740void SelectionDAGBuilder::visitCall(const CallInst &I) {
9741 // Handle inline assembly differently.
9742 if (I.isInlineAsm()) {
9743 visitInlineAsm(Call: I);
9744 return;
9745 }
9746
9747 diagnoseDontCall(CI: I);
9748
9749 if (Function *F = I.getCalledFunction()) {
9750 if (F->isDeclaration()) {
9751 // Is this an LLVM intrinsic?
9752 if (unsigned IID = F->getIntrinsicID()) {
9753 visitIntrinsicCall(I, Intrinsic: IID);
9754 return;
9755 }
9756 }
9757
9758 // Check for well-known libc/libm calls. If the function is internal, it
9759 // can't be a library call. Don't do the check if marked as nobuiltin for
9760 // some reason.
9761 // This code should not handle libcalls that are already canonicalized to
9762 // intrinsics by the middle-end.
9763 LibFunc Func = !I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName()
9764 ? LibInfo->getLibFunc(FDecl: *F)
9765 : NotLibFunc;
9766 if (LibInfo->hasOptimizedCodeGen(F: Func)) {
9767 switch (Func) {
9768 default: break;
9769 case LibFunc_bcmp:
9770 if (visitMemCmpBCmpCall(I))
9771 return;
9772 break;
9773 case LibFunc_copysign:
9774 case LibFunc_copysignf:
9775 case LibFunc_copysignl:
9776 // We already checked this call's prototype; verify it doesn't modify
9777 // errno.
9778 if (I.onlyReadsMemory()) {
9779 SDValue LHS = getValue(V: I.getArgOperand(i: 0));
9780 SDValue RHS = getValue(V: I.getArgOperand(i: 1));
9781 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FCOPYSIGN, DL: getCurSDLoc(),
9782 VT: LHS.getValueType(), N1: LHS, N2: RHS));
9783 return;
9784 }
9785 break;
9786 case LibFunc_sin:
9787 case LibFunc_sinf:
9788 case LibFunc_sinl:
9789 if (visitUnaryFloatCall(I, Opcode: ISD::FSIN))
9790 return;
9791 break;
9792 case LibFunc_cos:
9793 case LibFunc_cosf:
9794 case LibFunc_cosl:
9795 if (visitUnaryFloatCall(I, Opcode: ISD::FCOS))
9796 return;
9797 break;
9798 case LibFunc_tan:
9799 case LibFunc_tanf:
9800 case LibFunc_tanl:
9801 if (visitUnaryFloatCall(I, Opcode: ISD::FTAN))
9802 return;
9803 break;
9804 case LibFunc_asin:
9805 case LibFunc_asinf:
9806 case LibFunc_asinl:
9807 if (visitUnaryFloatCall(I, Opcode: ISD::FASIN))
9808 return;
9809 break;
9810 case LibFunc_acos:
9811 case LibFunc_acosf:
9812 case LibFunc_acosl:
9813 if (visitUnaryFloatCall(I, Opcode: ISD::FACOS))
9814 return;
9815 break;
9816 case LibFunc_atan:
9817 case LibFunc_atanf:
9818 case LibFunc_atanl:
9819 if (visitUnaryFloatCall(I, Opcode: ISD::FATAN))
9820 return;
9821 break;
9822 case LibFunc_atan2:
9823 case LibFunc_atan2f:
9824 case LibFunc_atan2l:
9825 if (visitBinaryFloatCall(I, Opcode: ISD::FATAN2))
9826 return;
9827 break;
9828 case LibFunc_sinh:
9829 case LibFunc_sinhf:
9830 case LibFunc_sinhl:
9831 if (visitUnaryFloatCall(I, Opcode: ISD::FSINH))
9832 return;
9833 break;
9834 case LibFunc_cosh:
9835 case LibFunc_coshf:
9836 case LibFunc_coshl:
9837 if (visitUnaryFloatCall(I, Opcode: ISD::FCOSH))
9838 return;
9839 break;
9840 case LibFunc_tanh:
9841 case LibFunc_tanhf:
9842 case LibFunc_tanhl:
9843 if (visitUnaryFloatCall(I, Opcode: ISD::FTANH))
9844 return;
9845 break;
9846 case LibFunc_sqrt:
9847 case LibFunc_sqrtf:
9848 case LibFunc_sqrtl:
9849 case LibFunc_sqrt_finite:
9850 case LibFunc_sqrtf_finite:
9851 case LibFunc_sqrtl_finite:
9852 if (visitUnaryFloatCall(I, Opcode: ISD::FSQRT))
9853 return;
9854 break;
9855 case LibFunc_log2:
9856 case LibFunc_log2f:
9857 case LibFunc_log2l:
9858 if (visitUnaryFloatCall(I, Opcode: ISD::FLOG2))
9859 return;
9860 break;
9861 case LibFunc_exp2:
9862 case LibFunc_exp2f:
9863 case LibFunc_exp2l:
9864 if (visitUnaryFloatCall(I, Opcode: ISD::FEXP2))
9865 return;
9866 break;
9867 case LibFunc_exp10:
9868 case LibFunc_exp10f:
9869 case LibFunc_exp10l:
9870 if (visitUnaryFloatCall(I, Opcode: ISD::FEXP10))
9871 return;
9872 break;
9873 case LibFunc_ldexp:
9874 case LibFunc_ldexpf:
9875 case LibFunc_ldexpl:
9876 if (visitBinaryFloatCall(I, Opcode: ISD::FLDEXP))
9877 return;
9878 break;
9879 case LibFunc_strstr:
9880 if (visitStrstrCall(I))
9881 return;
9882 break;
9883 case LibFunc_memcmp:
9884 if (visitMemCmpBCmpCall(I))
9885 return;
9886 break;
9887 case LibFunc_memccpy:
9888 if (visitMemCCpyCall(I))
9889 return;
9890 break;
9891 case LibFunc_mempcpy:
9892 if (visitMemPCpyCall(I))
9893 return;
9894 break;
9895 case LibFunc_memchr:
9896 if (visitMemChrCall(I))
9897 return;
9898 break;
9899 case LibFunc_strcpy:
9900 if (visitStrCpyCall(I, isStpcpy: false))
9901 return;
9902 break;
9903 case LibFunc_stpcpy:
9904 if (visitStrCpyCall(I, isStpcpy: true))
9905 return;
9906 break;
9907 case LibFunc_strcmp:
9908 if (visitStrCmpCall(I))
9909 return;
9910 break;
9911 case LibFunc_strlen:
9912 if (visitStrLenCall(I))
9913 return;
9914 break;
9915 case LibFunc_strnlen:
9916 if (visitStrNLenCall(I))
9917 return;
9918 break;
9919 }
9920 }
9921 }
9922
9923 if (I.countOperandBundlesOfType(ID: LLVMContext::OB_ptrauth)) {
9924 LowerCallSiteWithPtrAuthBundle(CB: cast<CallBase>(Val: I), /*EHPadBB=*/nullptr);
9925 return;
9926 }
9927
9928 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9929 // have to do anything here to lower funclet bundles.
9930 // CFGuardTarget bundles are lowered in LowerCallTo.
9931 failForInvalidBundles(
9932 I, Name: "calls",
9933 AllowedBundles: {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9934 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9935 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9936 LLVMContext::OB_convergencectrl, LLVMContext::OB_deactivation_symbol});
9937
9938 SDValue Callee = getValue(V: I.getCalledOperand());
9939
9940 if (I.hasDeoptState())
9941 LowerCallSiteWithDeoptBundle(Call: &I, Callee, EHPadBB: nullptr);
9942 else
9943 // Check if we can potentially perform a tail call. More detailed checking
9944 // is be done within LowerCallTo, after more information about the call is
9945 // known.
9946 LowerCallTo(CB: I, Callee, isTailCall: I.isTailCall(), isMustTailCall: I.isMustTailCall());
9947}
9948
9949void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9950 const CallBase &CB, const BasicBlock *EHPadBB) {
9951 auto PAB = CB.getOperandBundle(Name: "ptrauth");
9952 const Value *CalleeV = CB.getCalledOperand();
9953
9954 // Gather the call ptrauth data from the operand bundle:
9955 // [ i32 <key>, i64 <discriminator> ]
9956 const auto *Key = cast<ConstantInt>(Val: PAB->Inputs[0]);
9957 const Value *Discriminator = PAB->Inputs[1];
9958
9959 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9960 assert(Discriminator->getType()->isIntegerTy(64) &&
9961 "Invalid ptrauth discriminator");
9962
9963 // Look through ptrauth constants to find the raw callee.
9964 // Do a direct unauthenticated call if we found it and everything matches.
9965 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(Val: CalleeV))
9966 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9967 DL: DAG.getDataLayout()))
9968 return LowerCallTo(CB, Callee: getValue(V: CalleeCPA->getPointer()), isTailCall: CB.isTailCall(),
9969 isMustTailCall: CB.isMustTailCall(), EHPadBB);
9970
9971 // Functions should never be ptrauth-called directly.
9972 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9973
9974 // Otherwise, do an authenticated indirect call.
9975 TargetLowering::PtrAuthInfo PAI = {.Key: Key->getZExtValue(),
9976 .Discriminator: getValue(V: Discriminator)};
9977
9978 LowerCallTo(CB, Callee: getValue(V: CalleeV), isTailCall: CB.isTailCall(), isMustTailCall: CB.isMustTailCall(),
9979 EHPadBB, PAI: &PAI);
9980}
9981
9982namespace {
9983
9984/// AsmOperandInfo - This contains information for each constraint that we are
9985/// lowering.
9986class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9987public:
9988 /// CallOperand - If this is the result output operand or a clobber
9989 /// this is null, otherwise it is the incoming operand to the CallInst.
9990 /// This gets modified as the asm is processed.
9991 SDValue CallOperand;
9992
9993 /// AssignedRegs - If this is a register or register class operand, this
9994 /// contains the set of register corresponding to the operand.
9995 RegsForValue AssignedRegs;
9996
9997 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9998 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9999 }
10000
10001 /// Whether or not this operand accesses memory
10002 bool hasMemory(const TargetLowering &TLI) const {
10003 // Indirect operand accesses access memory.
10004 if (isIndirect)
10005 return true;
10006
10007 for (const auto &Code : Codes)
10008 if (TLI.getConstraintType(Constraint: Code) == TargetLowering::C_Memory)
10009 return true;
10010
10011 return false;
10012 }
10013};
10014
10015
10016} // end anonymous namespace
10017
10018/// Make sure that the output operand \p OpInfo and its corresponding input
10019/// operand \p MatchingOpInfo have compatible constraint types (otherwise error
10020/// out).
10021static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
10022 SDISelAsmOperandInfo &MatchingOpInfo,
10023 SelectionDAG &DAG) {
10024 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
10025 return;
10026
10027 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
10028 const auto &TLI = DAG.getTargetLoweringInfo();
10029
10030 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
10031 TLI.getRegForInlineAsmConstraint(TRI, Constraint: OpInfo.ConstraintCode,
10032 VT: OpInfo.ConstraintVT);
10033 std::pair<unsigned, const TargetRegisterClass *> InputRC =
10034 TLI.getRegForInlineAsmConstraint(TRI, Constraint: MatchingOpInfo.ConstraintCode,
10035 VT: MatchingOpInfo.ConstraintVT);
10036 const bool OutOpIsIntOrFP =
10037 OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
10038 const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
10039 MatchingOpInfo.ConstraintVT.isFloatingPoint();
10040 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
10041 // FIXME: error out in a more elegant fashion
10042 report_fatal_error(reason: "Unsupported asm: input constraint"
10043 " with a matching output constraint of"
10044 " incompatible type!");
10045 }
10046 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
10047}
10048
10049/// Get a direct memory input to behave well as an indirect operand.
10050/// This may introduce stores, hence the need for a \p Chain.
10051/// \return The (possibly updated) chain.
10052static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
10053 SDISelAsmOperandInfo &OpInfo,
10054 SelectionDAG &DAG) {
10055 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10056
10057 // If we don't have an indirect input, put it in the constpool if we can,
10058 // otherwise spill it to a stack slot.
10059 // TODO: This isn't quite right. We need to handle these according to
10060 // the addressing mode that the constraint wants. Also, this may take
10061 // an additional register for the computation and we don't want that
10062 // either.
10063
10064 // If the operand is a float, integer, or vector constant, spill to a
10065 // constant pool entry to get its address.
10066 const Value *OpVal = OpInfo.CallOperandVal;
10067 if (isa<ConstantFP>(Val: OpVal) || isa<ConstantInt>(Val: OpVal) ||
10068 isa<ConstantVector>(Val: OpVal) || isa<ConstantDataVector>(Val: OpVal)) {
10069 OpInfo.CallOperand = DAG.getConstantPool(
10070 C: cast<Constant>(Val: OpVal), VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
10071 return Chain;
10072 }
10073
10074 // Otherwise, create a stack slot and emit a store to it before the asm.
10075 Type *Ty = OpVal->getType();
10076 auto &DL = DAG.getDataLayout();
10077 TypeSize TySize = DL.getTypeAllocSize(Ty);
10078 MachineFunction &MF = DAG.getMachineFunction();
10079 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
10080 int StackID = 0;
10081 if (TySize.isScalable())
10082 StackID = TFI->getStackIDForScalableVectors();
10083 int SSFI = MF.getFrameInfo().CreateStackObject(Size: TySize.getKnownMinValue(),
10084 Alignment: DL.getPrefTypeAlign(Ty), isSpillSlot: false,
10085 Alloca: nullptr, ID: StackID);
10086 SDValue StackSlot = DAG.getFrameIndex(FI: SSFI, VT: TLI.getFrameIndexTy(DL));
10087 Chain = DAG.getTruncStore(Chain, dl: Location, Val: OpInfo.CallOperand, Ptr: StackSlot,
10088 PtrInfo: MachinePointerInfo::getFixedStack(MF, FI: SSFI),
10089 SVT: TLI.getMemValueType(DL, Ty));
10090 OpInfo.CallOperand = StackSlot;
10091
10092 return Chain;
10093}
10094
10095/// GetRegistersForValue - Assign registers (virtual or physical) for the
10096/// specified operand. We prefer to assign virtual registers, to allow the
10097/// register allocator to handle the assignment process. However, if the asm
10098/// uses features that we can't model on machineinstrs, we have SDISel do the
10099/// allocation. This produces generally horrible, but correct, code.
10100///
10101/// OpInfo describes the operand
10102/// RefOpInfo describes the matching operand if any, the operand otherwise
10103static std::optional<unsigned>
10104getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
10105 SDISelAsmOperandInfo &OpInfo,
10106 SDISelAsmOperandInfo &RefOpInfo) {
10107 LLVMContext &Context = *DAG.getContext();
10108 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10109
10110 MachineFunction &MF = DAG.getMachineFunction();
10111 SmallVector<Register, 4> Regs;
10112 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10113
10114 // No work to do for memory/address operands.
10115 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
10116 OpInfo.ConstraintType == TargetLowering::C_Address)
10117 return std::nullopt;
10118
10119 // If this is a constraint for a single physreg, or a constraint for a
10120 // register class, find it.
10121 unsigned AssignedReg;
10122 const TargetRegisterClass *RC;
10123 std::tie(args&: AssignedReg, args&: RC) = TLI.getRegForInlineAsmConstraint(
10124 TRI: &TRI, Constraint: RefOpInfo.ConstraintCode, VT: RefOpInfo.ConstraintVT);
10125 // RC is unset only on failure. Return immediately.
10126 if (!RC)
10127 return std::nullopt;
10128
10129 // Get the actual register value type. This is important, because the user
10130 // may have asked for (e.g.) the AX register in i32 type. We need to
10131 // remember that AX is actually i16 to get the right extension.
10132 const MVT RegVT = *TRI.legalclasstypes_begin(RC: *RC);
10133
10134 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
10135 // If this is an FP operand in an integer register (or visa versa), or more
10136 // generally if the operand value disagrees with the register class we plan
10137 // to stick it in, fix the operand type.
10138 //
10139 // If this is an input value, the bitcast to the new type is done now.
10140 // Bitcast for output value is done at the end of visitInlineAsm().
10141 if ((OpInfo.Type == InlineAsm::isOutput ||
10142 OpInfo.Type == InlineAsm::isInput) &&
10143 !TRI.isTypeLegalForClass(RC: *RC, T: OpInfo.ConstraintVT)) {
10144 // Try to convert to the first EVT that the reg class contains. If the
10145 // types are identical size, use a bitcast to convert (e.g. two differing
10146 // vector types). Note: output bitcast is done at the end of
10147 // visitInlineAsm().
10148 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
10149 // Exclude indirect inputs while they are unsupported because the code
10150 // to perform the load is missing and thus OpInfo.CallOperand still
10151 // refers to the input address rather than the pointed-to value.
10152 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
10153 OpInfo.CallOperand =
10154 DAG.getNode(Opcode: ISD::BITCAST, DL, VT: RegVT, Operand: OpInfo.CallOperand);
10155 OpInfo.ConstraintVT = RegVT;
10156 // If the operand is an FP value and we want it in integer registers,
10157 // use the corresponding integer type. This turns an f64 value into
10158 // i64, which can be passed with two i32 values on a 32-bit machine.
10159 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
10160 MVT VT = MVT::getIntegerVT(BitWidth: OpInfo.ConstraintVT.getSizeInBits());
10161 if (OpInfo.Type == InlineAsm::isInput)
10162 OpInfo.CallOperand =
10163 DAG.getNode(Opcode: ISD::BITCAST, DL, VT, Operand: OpInfo.CallOperand);
10164 OpInfo.ConstraintVT = VT;
10165 }
10166 }
10167 }
10168
10169 // No need to allocate a matching input constraint since the constraint it's
10170 // matching to has already been allocated.
10171 if (OpInfo.isMatchingInputConstraint())
10172 return std::nullopt;
10173
10174 EVT ValueVT = OpInfo.ConstraintVT;
10175 if (OpInfo.ConstraintVT == MVT::Other)
10176 ValueVT = RegVT;
10177
10178 // Initialize NumRegs.
10179 unsigned NumRegs = 1;
10180 if (OpInfo.ConstraintVT != MVT::Other)
10181 NumRegs = TLI.getNumRegisters(Context, VT: OpInfo.ConstraintVT, RegisterVT: RegVT);
10182
10183 // If this is a constraint for a specific physical register, like {r17},
10184 // assign it now.
10185
10186 // If this associated to a specific register, initialize iterator to correct
10187 // place. If virtual, make sure we have enough registers
10188
10189 // Initialize iterator if necessary
10190 TargetRegisterClass::iterator I = RC->begin();
10191 MachineRegisterInfo &RegInfo = MF.getRegInfo();
10192
10193 // Do not check for single registers.
10194 if (AssignedReg) {
10195 I = std::find(first: I, last: RC->end(), val: AssignedReg);
10196 if (I == RC->end()) {
10197 // RC does not contain the selected register, which indicates a
10198 // mismatch between the register and the required type/bitwidth.
10199 return {AssignedReg};
10200 }
10201 }
10202
10203 for (; NumRegs; --NumRegs, ++I) {
10204 assert(I != RC->end() && "Ran out of registers to allocate!");
10205 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RegClass: RC);
10206 Regs.push_back(Elt: R);
10207 }
10208
10209 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
10210 return std::nullopt;
10211}
10212
10213static unsigned
10214findMatchingInlineAsmOperand(unsigned OperandNo,
10215 const std::vector<SDValue> &AsmNodeOperands) {
10216 // Scan until we find the definition we already emitted of this operand.
10217 unsigned CurOp = InlineAsm::Op_FirstOperand;
10218 for (; OperandNo; --OperandNo) {
10219 // Advance to the next operand.
10220 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
10221 const InlineAsm::Flag F(OpFlag);
10222 assert(
10223 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
10224 "Skipped past definitions?");
10225 CurOp += F.getNumOperandRegisters() + 1;
10226 }
10227 return CurOp;
10228}
10229
10230namespace {
10231
10232class ExtraFlags {
10233 unsigned Flags = 0;
10234
10235public:
10236 explicit ExtraFlags(const CallBase &Call) {
10237 const InlineAsm *IA = cast<InlineAsm>(Val: Call.getCalledOperand());
10238 if (IA->hasSideEffects())
10239 Flags |= InlineAsm::Extra_HasSideEffects;
10240 if (IA->isAlignStack())
10241 Flags |= InlineAsm::Extra_IsAlignStack;
10242 if (IA->canThrow())
10243 Flags |= InlineAsm::Extra_MayUnwind;
10244 if (Call.isConvergent())
10245 Flags |= InlineAsm::Extra_IsConvergent;
10246 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
10247 }
10248
10249 void update(const TargetLowering::AsmOperandInfo &OpInfo) {
10250 // Ideally, we would only check against memory constraints. However, the
10251 // meaning of an Other constraint can be target-specific and we can't easily
10252 // reason about it. Therefore, be conservative and set MayLoad/MayStore
10253 // for Other constraints as well.
10254 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
10255 OpInfo.ConstraintType == TargetLowering::C_Other) {
10256 if (OpInfo.Type == InlineAsm::isInput)
10257 Flags |= InlineAsm::Extra_MayLoad;
10258 else if (OpInfo.Type == InlineAsm::isOutput)
10259 Flags |= InlineAsm::Extra_MayStore;
10260 else if (OpInfo.Type == InlineAsm::isClobber)
10261 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
10262 }
10263 }
10264
10265 unsigned get() const { return Flags; }
10266};
10267
10268} // end anonymous namespace
10269
10270static bool isFunction(SDValue Op) {
10271 if (Op && Op.getOpcode() == ISD::GlobalAddress) {
10272 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Val&: Op)) {
10273 auto Fn = dyn_cast_or_null<Function>(Val: GA->getGlobal());
10274
10275 // In normal "call dllimport func" instruction (non-inlineasm) it force
10276 // indirect access by specifing call opcode. And usually specially print
10277 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
10278 // not do in this way now. (In fact, this is similar with "Data Access"
10279 // action). So here we ignore dllimport function.
10280 if (Fn && !Fn->hasDLLImportStorageClass())
10281 return true;
10282 }
10283 }
10284 return false;
10285}
10286
10287namespace {
10288
10289struct ConstraintDecisionInfo {
10290 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
10291 std::vector<SDValue> AsmNodeOperands;
10292 SDValue Glue, Chain;
10293 bool HasSideEffect = false;
10294 MCSymbol *BeginLabel = nullptr;
10295
10296 SmallVector<char> Buffer;
10297 raw_svector_ostream ErrorMsg;
10298
10299 ConstraintDecisionInfo() : ErrorMsg(Buffer) {}
10300};
10301
10302} // end anonymous namespace
10303
10304/// Construct operand info objects.
10305static bool
10306constructOperandInfo(ConstraintDecisionInfo &Info,
10307 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10308 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10309 ExtraFlags &ExtraInfo) {
10310 for (auto &T : TargetConstraints) {
10311 Info.ConstraintOperands.push_back(Elt: SDISelAsmOperandInfo(T));
10312 SDISelAsmOperandInfo &OpInfo = Info.ConstraintOperands.back();
10313
10314 if (OpInfo.CallOperandVal)
10315 OpInfo.CallOperand = Builder.getValue(V: OpInfo.CallOperandVal);
10316
10317 if (!Info.HasSideEffect)
10318 Info.HasSideEffect = OpInfo.hasMemory(TLI);
10319
10320 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
10321 // FIXME: Could we compute this on OpInfo rather than T?
10322
10323 // Compute the constraint code and ConstraintType to use.
10324 TLI.ComputeConstraintToUse(OpInfo&: T, Op: SDValue());
10325
10326 if (T.ConstraintType == TargetLowering::C_Immediate && OpInfo.CallOperand &&
10327 !isa<ConstantSDNode>(Val: OpInfo.CallOperand)) {
10328 // We've delayed emitting a diagnostic like the "n" constraint because
10329 // inlining could cause an integer showing up.
10330 Info.ErrorMsg << "constraint '" << T.ConstraintCode
10331 << "' expects an integer constant expression";
10332 return true;
10333 }
10334
10335 ExtraInfo.update(OpInfo: T);
10336 }
10337
10338 return false;
10339}
10340
10341/// Compute which constraint option to use for each operand.
10342static void
10343computeConstraintToUse(ConstraintDecisionInfo &Info, const CallBase &Call,
10344 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10345 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10346 const TargetMachine &TM, SelectionDAG &DAG) {
10347 const auto *IA = cast<InlineAsm>(Val: Call.getCalledOperand());
10348 SmallVector<StringRef, 4> AsmStrs;
10349 IA->collectAsmStrs(AsmStrs);
10350
10351 int OpNo = -1;
10352 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10353 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
10354 OpNo++;
10355
10356 // If this is an output operand with a matching input operand, look up the
10357 // matching input. If their types mismatch, e.g. one is an integer, the
10358 // other is floating point, or their sizes are different, flag it as an
10359 // error.
10360 if (OpInfo.hasMatchingInput()) {
10361 SDISelAsmOperandInfo &Input =
10362 Info.ConstraintOperands[OpInfo.MatchingInput];
10363 patchMatchingInput(OpInfo, MatchingOpInfo&: Input, DAG);
10364 }
10365
10366 // Compute the constraint code and ConstraintType to use.
10367 TLI.ComputeConstraintToUse(OpInfo, Op: OpInfo.CallOperand, DAG: &DAG);
10368
10369 if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
10370 OpInfo.Type == InlineAsm::isClobber) ||
10371 OpInfo.ConstraintType == TargetLowering::C_Address)
10372 continue;
10373
10374 // In Linux PIC model, there are 4 cases about value/label addressing:
10375 //
10376 // 1: Function call or Label jmp inside the module.
10377 // 2: Data access (such as global variable, static variable) inside module.
10378 // 3: Function call or Label jmp outside the module.
10379 // 4: Data access (such as global variable) outside the module.
10380 //
10381 // Due to current llvm inline asm architecture designed to not "recognize"
10382 // the asm code, there are quite troubles for us to treat mem addressing
10383 // differently for same value/adress used in different instuctions.
10384 // For example, in pic model, call a func may in plt way or direclty
10385 // pc-related, but lea/mov a function adress may use got.
10386 //
10387 // Here we try to "recognize" function call for the case 1 and case 3 in
10388 // inline asm. And try to adjust the constraint for them.
10389 //
10390 // TODO: Due to current inline asm didn't encourage to jmp to the outsider
10391 // label, so here we don't handle jmp function label now, but we need to
10392 // enhance it (especilly in PIC model) if we meet meaningful requirements.
10393 if (OpInfo.isIndirect && isFunction(Op: OpInfo.CallOperand) &&
10394 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
10395 TM.getCodeModel() != CodeModel::Large) {
10396 OpInfo.isIndirect = false;
10397 OpInfo.ConstraintType = TargetLowering::C_Address;
10398 }
10399
10400 // If this is a memory input, and if the operand is not indirect, do what we
10401 // need to provide an address for the memory input.
10402 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
10403 !OpInfo.isIndirect) {
10404 assert((OpInfo.isMultipleAlternative ||
10405 (OpInfo.Type == InlineAsm::isInput)) &&
10406 "Can only indirectify direct input operands!");
10407
10408 // Memory operands really want the address of the value.
10409 Info.Chain = getAddressForMemoryInput(Chain: Info.Chain, Location: Builder.getCurSDLoc(),
10410 OpInfo, DAG);
10411
10412 // There is no longer a Value* corresponding to this operand.
10413 OpInfo.CallOperandVal = nullptr;
10414
10415 // It is now an indirect operand.
10416 OpInfo.isIndirect = true;
10417 }
10418 }
10419}
10420
10421/// Prepare DAG-level operands. As part of this, assign virtual and physical
10422/// registers for inputs and output.
10423static bool prepareDAGLevelOperands(ConstraintDecisionInfo &Info,
10424 const CallBase &Call,
10425 SelectionDAGBuilder &Builder,
10426 const TargetLowering &TLI,
10427 SelectionDAG &DAG) {
10428 SDLoc DL = Builder.getCurSDLoc();
10429 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10430 // Assign Registers.
10431 SDISelAsmOperandInfo &RefOpInfo =
10432 OpInfo.isMatchingInputConstraint()
10433 ? Info.ConstraintOperands[OpInfo.getMatchedOperand()]
10434 : OpInfo;
10435 const auto RegError = getRegistersForValue(DAG, DL, OpInfo, RefOpInfo);
10436 if (RegError) {
10437 const MachineFunction &MF = DAG.getMachineFunction();
10438 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10439 const char *RegName = TRI.getName(RegNo: *RegError);
10440 Info.ErrorMsg << "register '" << RegName << "' allocated for constraint '"
10441 << OpInfo.ConstraintCode
10442 << "' does not match required type";
10443 return true;
10444 }
10445
10446 auto DetectWriteToReservedRegister = [&]() {
10447 const MachineFunction &MF = DAG.getMachineFunction();
10448 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10449
10450 for (Register Reg : OpInfo.AssignedRegs.Regs) {
10451 if (Reg.isPhysical() && TRI.isInlineAsmReadOnlyReg(MF, PhysReg: Reg)) {
10452 Info.ErrorMsg << "write to reserved register '"
10453 << TRI.getRegAsmName(Reg) << "'";
10454 return true;
10455 }
10456 }
10457
10458 return false;
10459 };
10460 assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10461 (OpInfo.Type == InlineAsm::isInput &&
10462 !OpInfo.isMatchingInputConstraint())) &&
10463 "Only address as input operand is allowed.");
10464
10465 switch (OpInfo.Type) {
10466 case InlineAsm::isOutput:
10467 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10468 const InlineAsm::ConstraintCode ConstraintID =
10469 TLI.getInlineAsmMemConstraint(ConstraintCode: OpInfo.ConstraintCode);
10470 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10471 "Failed to convert memory constraint code to constraint id.");
10472
10473 // Add information to the INLINEASM node to know about this output.
10474 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
10475 OpFlags.setMemConstraint(ConstraintID);
10476 Info.AsmNodeOperands.push_back(
10477 x: DAG.getTargetConstant(Val: OpFlags, DL, VT: MVT::i32));
10478 Info.AsmNodeOperands.push_back(x: OpInfo.CallOperand);
10479 } else {
10480 // Otherwise, this outputs to a register (directly for C_Register /
10481 // C_RegisterClass, and a target-defined fashion for
10482 // C_Immediate/C_Other). Find a register that we can use.
10483 if (OpInfo.AssignedRegs.Regs.empty()) {
10484 Info.ErrorMsg << "could not allocate output register for "
10485 << "constraint '" << OpInfo.ConstraintCode << "'";
10486 return true;
10487 }
10488
10489 if (DetectWriteToReservedRegister())
10490 return true;
10491
10492 // Add information to the INLINEASM node to know that this register is
10493 // set.
10494 OpInfo.AssignedRegs.AddInlineAsmOperands(
10495 Code: OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10496 : InlineAsm::Kind::RegDef,
10497 HasMatching: false, MatchingIdx: 0, dl: DL, DAG, Ops&: Info.AsmNodeOperands);
10498 }
10499 break;
10500
10501 case InlineAsm::isInput:
10502 case InlineAsm::isLabel: {
10503 SDValue InOperandVal = OpInfo.CallOperand;
10504
10505 if (OpInfo.isMatchingInputConstraint()) {
10506 // If this is required to match an output register we have already set,
10507 // just use its register.
10508 auto CurOp = findMatchingInlineAsmOperand(OperandNo: OpInfo.getMatchedOperand(),
10509 AsmNodeOperands: Info.AsmNodeOperands);
10510 InlineAsm::Flag Flag(Info.AsmNodeOperands[CurOp]->getAsZExtVal());
10511 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10512 if (OpInfo.isIndirect) {
10513 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10514 Info.ErrorMsg << "inline asm not supported yet: cannot handle "
10515 << "tied indirect register inputs";
10516 return true;
10517 }
10518
10519 SmallVector<Register, 4> Regs;
10520 MachineFunction &MF = DAG.getMachineFunction();
10521 MachineRegisterInfo &MRI = MF.getRegInfo();
10522 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10523 auto *R = cast<RegisterSDNode>(Val&: Info.AsmNodeOperands[CurOp + 1]);
10524 Register TiedReg = R->getReg();
10525 MVT RegVT = R->getSimpleValueType(ResNo: 0);
10526 const TargetRegisterClass *RC =
10527 TiedReg.isVirtual() ? MRI.getRegClass(Reg: TiedReg)
10528 : RegVT != MVT::Untyped ? TLI.getRegClassFor(VT: RegVT)
10529 : TRI.getMinimalPhysRegClass(Reg: TiedReg);
10530 for (unsigned I = 0, E = Flag.getNumOperandRegisters(); I != E; ++I)
10531 Regs.push_back(Elt: MRI.createVirtualRegister(RegClass: RC));
10532
10533 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10534
10535 // Use the produced MatchedRegs object to
10536 MatchedRegs.getCopyToRegs(Val: InOperandVal, DAG, dl: DL, Chain&: Info.Chain,
10537 Glue: &Info.Glue, V: &Call);
10538 MatchedRegs.AddInlineAsmOperands(Code: InlineAsm::Kind::RegUse, HasMatching: true,
10539 MatchingIdx: OpInfo.getMatchedOperand(), dl: DL, DAG,
10540 Ops&: Info.AsmNodeOperands);
10541 break;
10542 }
10543
10544 assert(Flag.isMemKind() && "Unknown matching constraint!");
10545 assert(Flag.getNumOperandRegisters() == 1 &&
10546 "Unexpected number of operands");
10547
10548 // Add information to the INLINEASM node to know about this input.
10549 // See InlineAsm.h isUseOperandTiedToDef.
10550 Flag.clearMemConstraint();
10551 Flag.setMatchingOp(OpInfo.getMatchedOperand());
10552 Info.AsmNodeOperands.push_back(x: DAG.getTargetConstant(
10553 Val: Flag, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
10554 Info.AsmNodeOperands.push_back(x: Info.AsmNodeOperands[CurOp + 1]);
10555 break;
10556 }
10557
10558 // Treat indirect 'X' constraint as memory.
10559 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10560 OpInfo.isIndirect)
10561 OpInfo.ConstraintType = TargetLowering::C_Memory;
10562
10563 if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10564 OpInfo.ConstraintType == TargetLowering::C_Other) {
10565 std::vector<SDValue> Ops;
10566 TLI.LowerAsmOperandForConstraint(Op: InOperandVal, Constraint: OpInfo.ConstraintCode,
10567 Ops, DAG);
10568 if (Ops.empty()) {
10569 if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10570 if (isa<ConstantSDNode>(Val: InOperandVal)) {
10571 Info.ErrorMsg << "value out of range for constraint '"
10572 << OpInfo.ConstraintCode << "'";
10573 return true;
10574 }
10575
10576 Info.ErrorMsg << "invalid operand for inline asm constraint '"
10577 << OpInfo.ConstraintCode << "'";
10578 return true;
10579 }
10580
10581 // Add information to the INLINEASM node to know about this input.
10582 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10583 Info.AsmNodeOperands.push_back(x: DAG.getTargetConstant(
10584 Val: ResOpType, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
10585 llvm::append_range(C&: Info.AsmNodeOperands, R&: Ops);
10586 break;
10587 }
10588
10589 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10590 assert((OpInfo.isIndirect ||
10591 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10592 "Operand must be indirect to be a mem!");
10593 assert(InOperandVal.getValueType() ==
10594 TLI.getPointerTy(DAG.getDataLayout()) &&
10595 "Memory operands expect pointer values");
10596
10597 const InlineAsm::ConstraintCode ConstraintID =
10598 TLI.getInlineAsmMemConstraint(ConstraintCode: OpInfo.ConstraintCode);
10599 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10600 "Failed to convert memory constraint code to constraint id.");
10601
10602 // Add information to the INLINEASM node to know about this input.
10603 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10604 ResOpType.setMemConstraint(ConstraintID);
10605 Info.AsmNodeOperands.push_back(
10606 x: DAG.getTargetConstant(Val: ResOpType, DL, VT: MVT::i32));
10607 Info.AsmNodeOperands.push_back(x: InOperandVal);
10608 break;
10609 }
10610
10611 if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10612 const InlineAsm::ConstraintCode ConstraintID =
10613 TLI.getInlineAsmMemConstraint(ConstraintCode: OpInfo.ConstraintCode);
10614 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10615 "Failed to convert memory constraint code to constraint id.");
10616
10617 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10618
10619 SDValue AsmOp = InOperandVal;
10620 if (isFunction(Op: InOperandVal)) {
10621 auto *GA = cast<GlobalAddressSDNode>(Val&: InOperandVal);
10622 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10623 AsmOp = DAG.getTargetGlobalAddress(GV: GA->getGlobal(), DL,
10624 VT: InOperandVal.getValueType(),
10625 offset: GA->getOffset());
10626 }
10627
10628 // Add information to the INLINEASM node to know about this input.
10629 ResOpType.setMemConstraint(ConstraintID);
10630
10631 Info.AsmNodeOperands.push_back(
10632 x: DAG.getTargetConstant(Val: ResOpType, DL, VT: MVT::i32));
10633 Info.AsmNodeOperands.push_back(x: AsmOp);
10634 break;
10635 }
10636
10637 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10638 OpInfo.ConstraintType != TargetLowering::C_Register) {
10639 Info.ErrorMsg << "unknown asm constraint '" << OpInfo.ConstraintCode
10640 << "'";
10641 return true;
10642 }
10643
10644 // TODO: Support this.
10645 if (OpInfo.isIndirect) {
10646 Info.ErrorMsg << "cannot handle indirect register inputs yet for "
10647 << "constraint '" << OpInfo.ConstraintCode << "'";
10648 return true;
10649 }
10650
10651 // Copy the input into the appropriate registers.
10652 if (OpInfo.AssignedRegs.Regs.empty()) {
10653 Info.ErrorMsg << "could not allocate input reg for constraint '"
10654 << OpInfo.ConstraintCode << "'";
10655 return true;
10656 }
10657
10658 if (DetectWriteToReservedRegister())
10659 return true;
10660
10661 OpInfo.AssignedRegs.getCopyToRegs(Val: InOperandVal, DAG, dl: DL, Chain&: Info.Chain,
10662 Glue: &Info.Glue, V: &Call);
10663 OpInfo.AssignedRegs.AddInlineAsmOperands(
10664 Code: InlineAsm::Kind::RegUse, HasMatching: false, MatchingIdx: 0, dl: DL, DAG, Ops&: Info.AsmNodeOperands);
10665 break;
10666 }
10667
10668 case InlineAsm::isClobber:
10669 // Add the clobbered value to the operand list, so that the register
10670 // allocator is aware that the physreg got clobbered.
10671 if (!OpInfo.AssignedRegs.Regs.empty())
10672 OpInfo.AssignedRegs.AddInlineAsmOperands(
10673 Code: InlineAsm::Kind::Clobber, HasMatching: false, MatchingIdx: 0, dl: DL, DAG, Ops&: Info.AsmNodeOperands);
10674 break;
10675 }
10676 }
10677
10678 return false;
10679}
10680
10681/// DetermineConstraints - Find the constraints to use for inline asm operands.
10682static bool
10683determineConstraints(ConstraintDecisionInfo &Info,
10684 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10685 const CallBase &Call, SelectionDAGBuilder &Builder,
10686 const TargetLowering &TLI, const TargetMachine &TM,
10687 SelectionDAG &DAG, const BasicBlock *EHPadBB) {
10688 const auto *IA = cast<InlineAsm>(Val: Call.getCalledOperand());
10689 ExtraFlags ExtraInfo(Call);
10690
10691 // First pass: Construct operand info objects.
10692 Info.HasSideEffect = IA->hasSideEffects();
10693 if (constructOperandInfo(Info, TargetConstraints, Builder, TLI, ExtraInfo))
10694 return true;
10695
10696 // We won't need to flush pending loads if this asm doesn't touch
10697 // memory and is nonvolatile.
10698 Info.Chain = Info.HasSideEffect ? Builder.getRoot() : DAG.getRoot();
10699
10700 bool IsCallBr = isa<CallBrInst>(Val: Call);
10701 bool EmitEHLabels = isa<InvokeInst>(Val: Call);
10702 if (IsCallBr || EmitEHLabels)
10703 // If this is a callbr or invoke we need to flush pending exports since
10704 // inlineasm_br and invoke are terminators.
10705 // We need to do this before nodes are glued to the inlineasm_br node.
10706 Info.Chain = Builder.getControlRoot();
10707
10708 if (EmitEHLabels)
10709 Info.Chain = Builder.lowerStartEH(Chain: Info.Chain, EHPadBB, BeginLabel&: Info.BeginLabel);
10710
10711 // Second pass: Compute which constraint option to use.
10712 computeConstraintToUse(Info, Call, TargetConstraints, Builder, TLI, TM, DAG);
10713
10714 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10715 Info.AsmNodeOperands.push_back(x: SDValue()); // reserve space for input chain
10716 Info.AsmNodeOperands.push_back(x: DAG.getTargetExternalSymbol(
10717 Sym: IA->getAsmString().data(), VT: TLI.getProgramPointerTy(DL: DAG.getDataLayout())));
10718
10719 // If we have a !srcloc metadata node associated with it, we want to attach
10720 // this to the ultimately generated inline asm machineinstr. To do this, we
10721 // pass in the third operand as this (potentially null) inline asm MDNode.
10722 const MDNode *SrcLoc = Call.getMetadata(Kind: "srcloc");
10723 Info.AsmNodeOperands.push_back(x: DAG.getMDNode(MD: SrcLoc));
10724
10725 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10726 // bits as operand 3.
10727 Info.AsmNodeOperands.push_back(
10728 x: DAG.getTargetConstant(Val: ExtraInfo.get(), DL: Builder.getCurSDLoc(),
10729 VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
10730
10731 // Third pass: Prepare DAG-level operands
10732 return prepareDAGLevelOperands(Info, Call, Builder, TLI, DAG);
10733}
10734
10735/// visitInlineAsm - Handle a call to an InlineAsm object.
10736void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
10737 const BasicBlock *EHPadBB) {
10738 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10739 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
10740 DL: DAG.getDataLayout(), TRI: DAG.getSubtarget().getRegisterInfo(), Call);
10741
10742 assert((!isa<InvokeInst>(Call) || EHPadBB) &&
10743 "InvokeInst must have an EHPadBB");
10744
10745 ConstraintDecisionInfo Info;
10746 if (determineConstraints(Info, TargetConstraints, Call, Builder&: *this, TLI, TM, DAG,
10747 EHPadBB))
10748 return emitInlineAsmError(Call, Message: Info.ErrorMsg.str());
10749
10750 SDValue Glue = Info.Glue;
10751 SDValue Chain = Info.Chain;
10752
10753 // Finish up input operands. Set the input chain and add the flag last.
10754 Info.AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10755 if (Glue.getNode())
10756 Info.AsmNodeOperands.push_back(x: Glue);
10757
10758 bool IsCallBr = isa<CallBrInst>(Val: Call);
10759 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10760 Chain =
10761 DAG.getNode(Opcode: ISDOpc, DL: getCurSDLoc(), VTList: DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue),
10762 Ops: Info.AsmNodeOperands);
10763 Glue = Chain.getValue(R: 1);
10764
10765 // Do additional work to generate outputs.
10766
10767 SmallVector<EVT, 1> ResultVTs;
10768 SmallVector<SDValue, 1> ResultValues;
10769 SmallVector<SDValue, 8> OutChains;
10770
10771 llvm::Type *CallResultType = Call.getType();
10772 ArrayRef<Type *> ResultTypes;
10773 if (StructType *StructResult = dyn_cast<StructType>(Val: CallResultType))
10774 ResultTypes = StructResult->elements();
10775 else if (!CallResultType->isVoidTy())
10776 ResultTypes = ArrayRef(CallResultType);
10777
10778 auto CurResultType = ResultTypes.begin();
10779 auto handleRegAssign = [&](SDValue V) {
10780 assert(CurResultType != ResultTypes.end() && "Unexpected value");
10781 assert((*CurResultType)->isSized() && "Unexpected unsized type");
10782 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: *CurResultType);
10783 ++CurResultType;
10784 // If the type of the inline asm call site return value is different but has
10785 // same size as the type of the asm output bitcast it. One example of this
10786 // is for vectors with different width / number of elements. This can
10787 // happen for register classes that can contain multiple different value
10788 // types. The preg or vreg allocated may not have the same VT as was
10789 // expected.
10790 //
10791 // This can also happen for a return value that disagrees with the register
10792 // class it is put in, eg. a double in a general-purpose register on a
10793 // 32-bit machine.
10794 if (ResultVT != V.getValueType() &&
10795 ResultVT.getSizeInBits() == V.getValueSizeInBits())
10796 V = DAG.getNode(Opcode: ISD::BITCAST, DL: getCurSDLoc(), VT: ResultVT, Operand: V);
10797 else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10798 V.getValueType().isInteger()) {
10799 // If a result value was tied to an input value, the computed result
10800 // may have a wider width than the expected result. Extract the
10801 // relevant portion.
10802 V = DAG.getNode(Opcode: ISD::TRUNCATE, DL: getCurSDLoc(), VT: ResultVT, Operand: V);
10803 }
10804 assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10805 ResultVTs.push_back(Elt: ResultVT);
10806 ResultValues.push_back(Elt: V);
10807 };
10808
10809 // Deal with output operands.
10810 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10811 if (OpInfo.Type == InlineAsm::isOutput) {
10812 SDValue Val;
10813 // Skip trivial output operands.
10814 if (OpInfo.AssignedRegs.Regs.empty())
10815 continue;
10816
10817 switch (OpInfo.ConstraintType) {
10818 case TargetLowering::C_Register:
10819 case TargetLowering::C_RegisterClass:
10820 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, dl: getCurSDLoc(),
10821 Chain, Glue: &Glue, V: &Call);
10822 break;
10823 case TargetLowering::C_Immediate:
10824 case TargetLowering::C_Other:
10825 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, DL: getCurSDLoc(),
10826 OpInfo, DAG);
10827 break;
10828 case TargetLowering::C_Memory:
10829 break; // Already handled.
10830 case TargetLowering::C_Address:
10831 break; // Silence warning.
10832 case TargetLowering::C_Unknown:
10833 assert(false && "Unexpected unknown constraint");
10834 }
10835
10836 // Indirect output manifest as stores. Record output chains.
10837 if (OpInfo.isIndirect) {
10838 const Value *Ptr = OpInfo.CallOperandVal;
10839 assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10840 SDValue Store = DAG.getStore(Chain, dl: getCurSDLoc(), Val, Ptr: getValue(V: Ptr),
10841 PtrInfo: MachinePointerInfo(Ptr));
10842 OutChains.push_back(Elt: Store);
10843 } else {
10844 // generate CopyFromRegs to associated registers.
10845 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10846 if (Val.getOpcode() == ISD::MERGE_VALUES) {
10847 for (const SDValue &V : Val->op_values())
10848 handleRegAssign(V);
10849 } else
10850 handleRegAssign(Val);
10851 }
10852 }
10853 }
10854
10855 // Set results.
10856 if (!ResultValues.empty()) {
10857 assert(CurResultType == ResultTypes.end() &&
10858 "Mismatch in number of ResultTypes");
10859 assert(ResultValues.size() == ResultTypes.size() &&
10860 "Mismatch in number of output operands in asm result");
10861
10862 SDValue V = DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
10863 VTList: DAG.getVTList(VTs: ResultVTs), Ops: ResultValues);
10864 setValue(V: &Call, NewN: V);
10865 }
10866
10867 // Collect store chains.
10868 if (!OutChains.empty())
10869 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: getCurSDLoc(), VT: MVT::Other, Ops: OutChains);
10870
10871 if (const auto *II = dyn_cast<InvokeInst>(Val: &Call))
10872 Chain = lowerEndEH(Chain, II, EHPadBB, BeginLabel: Info.BeginLabel);
10873
10874 // Only Update Root if inline assembly has a memory effect.
10875 if (ResultValues.empty() || Info.HasSideEffect || !OutChains.empty() ||
10876 IsCallBr || isa<InvokeInst>(Val: Call))
10877 DAG.setRoot(Chain);
10878}
10879
10880void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10881 const Twine &Message) {
10882 LLVMContext &Ctx = *DAG.getContext();
10883 Ctx.diagnose(DI: DiagnosticInfoInlineAsm(Call, Message));
10884
10885 // Make sure we leave the DAG in a valid state
10886 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10887 SmallVector<EVT, 1> ValueVTs;
10888 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: Call.getType(), ValueVTs);
10889
10890 if (ValueVTs.empty())
10891 return;
10892
10893 SmallVector<SDValue, 1> Ops;
10894 for (const EVT &VT : ValueVTs)
10895 Ops.push_back(Elt: DAG.getUNDEF(VT));
10896
10897 setValue(V: &Call, NewN: DAG.getMergeValues(Ops, dl: getCurSDLoc()));
10898}
10899
10900void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10901 DAG.setRoot(DAG.getNode(Opcode: ISD::VASTART, DL: getCurSDLoc(),
10902 VT: MVT::Other, N1: getRoot(),
10903 N2: getValue(V: I.getArgOperand(i: 0)),
10904 N3: DAG.getSrcValue(v: I.getArgOperand(i: 0))));
10905}
10906
10907void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10908 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10909 const DataLayout &DL = DAG.getDataLayout();
10910 SDValue V = DAG.getVAArg(
10911 VT: TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getType()), dl: getCurSDLoc(),
10912 Chain: getRoot(), Ptr: getValue(V: I.getOperand(i_nocapture: 0)), SV: DAG.getSrcValue(v: I.getOperand(i_nocapture: 0)),
10913 Align: DL.getABITypeAlign(Ty: I.getType()).value());
10914 DAG.setRoot(V.getValue(R: 1));
10915
10916 if (I.getType()->isPointerTy())
10917 V = DAG.getPtrExtOrTrunc(
10918 Op: V, DL: getCurSDLoc(), VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()));
10919 setValue(V: &I, NewN: V);
10920}
10921
10922void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10923 DAG.setRoot(DAG.getNode(Opcode: ISD::VAEND, DL: getCurSDLoc(),
10924 VT: MVT::Other, N1: getRoot(),
10925 N2: getValue(V: I.getArgOperand(i: 0)),
10926 N3: DAG.getSrcValue(v: I.getArgOperand(i: 0))));
10927}
10928
10929void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10930 DAG.setRoot(DAG.getNode(Opcode: ISD::VACOPY, DL: getCurSDLoc(),
10931 VT: MVT::Other, N1: getRoot(),
10932 N2: getValue(V: I.getArgOperand(i: 0)),
10933 N3: getValue(V: I.getArgOperand(i: 1)),
10934 N4: DAG.getSrcValue(v: I.getArgOperand(i: 0)),
10935 N5: DAG.getSrcValue(v: I.getArgOperand(i: 1))));
10936}
10937
10938SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10939 const Instruction &I,
10940 SDValue Op) {
10941 std::optional<ConstantRange> CR = getRange(I);
10942
10943 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10944 return Op;
10945
10946 APInt Hi = CR->getUnsignedMax();
10947 unsigned Bits = std::max(a: Hi.getActiveBits(),
10948 b: static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10949
10950 EVT SmallVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: Bits);
10951
10952 SDLoc SL = getCurSDLoc();
10953
10954 SDValue ZExt = DAG.getNode(Opcode: ISD::AssertZext, DL: SL, VT: Op.getValueType(), N1: Op,
10955 N2: DAG.getValueType(SmallVT));
10956 unsigned NumVals = Op.getNode()->getNumValues();
10957 if (NumVals == 1)
10958 return ZExt;
10959
10960 SmallVector<SDValue, 4> Ops;
10961
10962 Ops.push_back(Elt: ZExt);
10963 for (unsigned I = 1; I != NumVals; ++I)
10964 Ops.push_back(Elt: Op.getValue(R: I));
10965
10966 return DAG.getMergeValues(Ops, dl: SL);
10967}
10968
10969SDValue SelectionDAGBuilder::lowerNoFPClassToAssertNoFPClass(
10970 SelectionDAG &DAG, const Instruction &I, SDValue Op) {
10971 FPClassTest Classes = getNoFPClass(I);
10972 if (Classes == fcNone)
10973 return Op;
10974
10975 SDLoc SL = getCurSDLoc();
10976 SDValue TestConst = DAG.getTargetConstant(Val: Classes, DL: SDLoc(), VT: MVT::i32);
10977
10978 if (Op.getOpcode() != ISD::MERGE_VALUES) {
10979 return DAG.getNode(Opcode: ISD::AssertNoFPClass, DL: SL, VT: Op.getValueType(), N1: Op,
10980 N2: TestConst);
10981 }
10982
10983 SmallVector<SDValue, 8> Ops(Op.getNumOperands());
10984 for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
10985 SDValue MergeOp = Op.getOperand(i: I);
10986 Ops[I] = DAG.getNode(Opcode: ISD::AssertNoFPClass, DL: SL, VT: MergeOp.getValueType(),
10987 N1: MergeOp, N2: TestConst);
10988 }
10989
10990 return DAG.getMergeValues(Ops, dl: SL);
10991}
10992
10993/// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10994/// the call being lowered.
10995///
10996/// This is a helper for lowering intrinsics that follow a target calling
10997/// convention or require stack pointer adjustment. Only a subset of the
10998/// intrinsic's operands need to participate in the calling convention.
10999void SelectionDAGBuilder::populateCallLoweringInfo(
11000 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
11001 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
11002 AttributeSet RetAttrs, bool IsPatchPoint) {
11003 TargetLowering::ArgListTy Args;
11004 Args.reserve(n: NumArgs);
11005
11006 // Populate the argument list.
11007 // Attributes for args start at offset 1, after the return attribute.
11008 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
11009 ArgI != ArgE; ++ArgI) {
11010 const Value *V = Call->getOperand(i_nocapture: ArgI);
11011
11012 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
11013
11014 TargetLowering::ArgListEntry Entry(getValue(V), V->getType());
11015 Entry.setAttributes(Call, ArgIdx: ArgI);
11016 Args.push_back(x: Entry);
11017 }
11018
11019 CLI.setDebugLoc(getCurSDLoc())
11020 .setChain(getRoot())
11021 .setCallee(CC: Call->getCallingConv(), ResultType: ReturnTy, Target: Callee, ArgsList: std::move(Args),
11022 ResultAttrs: RetAttrs)
11023 .setDiscardResult(Call->use_empty())
11024 .setIsPatchPoint(IsPatchPoint)
11025 .setIsPreallocated(
11026 Call->countOperandBundlesOfType(ID: LLVMContext::OB_preallocated) != 0);
11027}
11028
11029/// Add a stack map intrinsic call's live variable operands to a stackmap
11030/// or patchpoint target node's operand list.
11031///
11032/// Constants are converted to TargetConstants purely as an optimization to
11033/// avoid constant materialization and register allocation.
11034///
11035/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
11036/// generate addess computation nodes, and so FinalizeISel can convert the
11037/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
11038/// address materialization and register allocation, but may also be required
11039/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
11040/// alloca in the entry block, then the runtime may assume that the alloca's
11041/// StackMap location can be read immediately after compilation and that the
11042/// location is valid at any point during execution (this is similar to the
11043/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
11044/// only available in a register, then the runtime would need to trap when
11045/// execution reaches the StackMap in order to read the alloca's location.
11046static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
11047 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
11048 SelectionDAGBuilder &Builder) {
11049 SelectionDAG &DAG = Builder.DAG;
11050 for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
11051 SDValue Op = Builder.getValue(V: Call.getArgOperand(i: I));
11052
11053 // Things on the stack are pointer-typed, meaning that they are already
11054 // legal and can be emitted directly to target nodes.
11055 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Val&: Op)) {
11056 Ops.push_back(Elt: DAG.getTargetFrameIndex(FI: FI->getIndex(), VT: Op.getValueType()));
11057 } else {
11058 // Otherwise emit a target independent node to be legalised.
11059 Ops.push_back(Elt: Builder.getValue(V: Call.getArgOperand(i: I)));
11060 }
11061 }
11062}
11063
11064/// Lower llvm.experimental.stackmap.
11065void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
11066 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
11067 // [live variables...])
11068
11069 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
11070
11071 SDValue Chain, InGlue, Callee;
11072 SmallVector<SDValue, 32> Ops;
11073
11074 SDLoc DL = getCurSDLoc();
11075 Callee = getValue(V: CI.getCalledOperand());
11076
11077 // The stackmap intrinsic only records the live variables (the arguments
11078 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
11079 // intrinsic, this won't be lowered to a function call. This means we don't
11080 // have to worry about calling conventions and target specific lowering code.
11081 // Instead we perform the call lowering right here.
11082 //
11083 // chain, flag = CALLSEQ_START(chain, 0, 0)
11084 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
11085 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
11086 //
11087 Chain = DAG.getCALLSEQ_START(Chain: getRoot(), InSize: 0, OutSize: 0, DL);
11088 InGlue = Chain.getValue(R: 1);
11089
11090 // Add the STACKMAP operands, starting with DAG house-keeping.
11091 Ops.push_back(Elt: Chain);
11092 Ops.push_back(Elt: InGlue);
11093
11094 // Add the <id>, <numShadowBytes> operands.
11095 //
11096 // These do not require legalisation, and can be emitted directly to target
11097 // constant nodes.
11098 SDValue ID = getValue(V: CI.getArgOperand(i: 0));
11099 assert(ID.getValueType() == MVT::i64);
11100 SDValue IDConst =
11101 DAG.getTargetConstant(Val: ID->getAsZExtVal(), DL, VT: ID.getValueType());
11102 Ops.push_back(Elt: IDConst);
11103
11104 SDValue Shad = getValue(V: CI.getArgOperand(i: 1));
11105 assert(Shad.getValueType() == MVT::i32);
11106 SDValue ShadConst =
11107 DAG.getTargetConstant(Val: Shad->getAsZExtVal(), DL, VT: Shad.getValueType());
11108 Ops.push_back(Elt: ShadConst);
11109
11110 // Add the live variables.
11111 addStackMapLiveVars(Call: CI, StartIdx: 2, DL, Ops, Builder&: *this);
11112
11113 // Create the STACKMAP node.
11114 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
11115 Chain = DAG.getNode(Opcode: ISD::STACKMAP, DL, VTList: NodeTys, Ops);
11116 InGlue = Chain.getValue(R: 1);
11117
11118 Chain = DAG.getCALLSEQ_END(Chain, Size1: 0, Size2: 0, Glue: InGlue, DL);
11119
11120 // Stackmaps don't generate values, so nothing goes into the NodeMap.
11121
11122 // Set the root to the target-lowered call chain.
11123 DAG.setRoot(Chain);
11124
11125 // Inform the Frame Information that we have a stackmap in this function.
11126 FuncInfo.MF->getFrameInfo().setHasStackMap();
11127}
11128
11129/// Lower llvm.experimental.patchpoint directly to its target opcode.
11130void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
11131 const BasicBlock *EHPadBB) {
11132 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
11133 // i32 <numBytes>,
11134 // i8* <target>,
11135 // i32 <numArgs>,
11136 // [Args...],
11137 // [live variables...])
11138
11139 CallingConv::ID CC = CB.getCallingConv();
11140 bool IsAnyRegCC = CC == CallingConv::AnyReg;
11141 bool HasDef = !CB.getType()->isVoidTy();
11142 SDLoc dl = getCurSDLoc();
11143 SDValue Callee = getValue(V: CB.getArgOperand(i: PatchPointOpers::TargetPos));
11144
11145 // Handle immediate and symbolic callees.
11146 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Val&: Callee))
11147 Callee = DAG.getIntPtrConstant(Val: ConstCallee->getZExtValue(), DL: dl,
11148 /*isTarget=*/true);
11149 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Val&: Callee))
11150 Callee = DAG.getTargetGlobalAddress(GV: SymbolicCallee->getGlobal(),
11151 DL: SDLoc(SymbolicCallee),
11152 VT: SymbolicCallee->getValueType(ResNo: 0));
11153
11154 // Get the real number of arguments participating in the call <numArgs>
11155 SDValue NArgVal = getValue(V: CB.getArgOperand(i: PatchPointOpers::NArgPos));
11156 unsigned NumArgs = NArgVal->getAsZExtVal();
11157
11158 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
11159 // Intrinsics include all meta-operands up to but not including CC.
11160 unsigned NumMetaOpers = PatchPointOpers::CCPos;
11161 assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
11162 "Not enough arguments provided to the patchpoint intrinsic");
11163
11164 // For AnyRegCC the arguments are lowered later on manually.
11165 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
11166 Type *ReturnTy =
11167 IsAnyRegCC ? Type::getVoidTy(C&: *DAG.getContext()) : CB.getType();
11168
11169 TargetLowering::CallLoweringInfo CLI(DAG);
11170 populateCallLoweringInfo(CLI, Call: &CB, ArgIdx: NumMetaOpers, NumArgs: NumCallArgs, Callee,
11171 ReturnTy, RetAttrs: CB.getAttributes().getRetAttrs(), IsPatchPoint: true);
11172 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
11173
11174 SDNode *CallEnd = Result.second.getNode();
11175 if (CallEnd->getOpcode() == ISD::EH_LABEL)
11176 CallEnd = CallEnd->getOperand(Num: 0).getNode();
11177 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
11178 CallEnd = CallEnd->getOperand(Num: 0).getNode();
11179
11180 /// Get a call instruction from the call sequence chain.
11181 /// Tail calls are not allowed.
11182 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
11183 "Expected a callseq node.");
11184 SDNode *Call = CallEnd->getOperand(Num: 0).getNode();
11185 bool HasGlue = Call->getGluedNode();
11186
11187 // Replace the target specific call node with the patchable intrinsic.
11188 SmallVector<SDValue, 8> Ops;
11189
11190 // Push the chain.
11191 Ops.push_back(Elt: *(Call->op_begin()));
11192
11193 // Optionally, push the glue (if any).
11194 if (HasGlue)
11195 Ops.push_back(Elt: *(Call->op_end() - 1));
11196
11197 // Push the register mask info.
11198 if (HasGlue)
11199 Ops.push_back(Elt: *(Call->op_end() - 2));
11200 else
11201 Ops.push_back(Elt: *(Call->op_end() - 1));
11202
11203 // Add the <id> and <numBytes> constants.
11204 SDValue IDVal = getValue(V: CB.getArgOperand(i: PatchPointOpers::IDPos));
11205 Ops.push_back(Elt: DAG.getTargetConstant(Val: IDVal->getAsZExtVal(), DL: dl, VT: MVT::i64));
11206 SDValue NBytesVal = getValue(V: CB.getArgOperand(i: PatchPointOpers::NBytesPos));
11207 Ops.push_back(Elt: DAG.getTargetConstant(Val: NBytesVal->getAsZExtVal(), DL: dl, VT: MVT::i32));
11208
11209 // Add the callee.
11210 Ops.push_back(Elt: Callee);
11211
11212 // Adjust <numArgs> to account for any arguments that have been passed on the
11213 // stack instead.
11214 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
11215 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
11216 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
11217 Ops.push_back(Elt: DAG.getTargetConstant(Val: NumCallRegArgs, DL: dl, VT: MVT::i32));
11218
11219 // Add the calling convention
11220 Ops.push_back(Elt: DAG.getTargetConstant(Val: (unsigned)CC, DL: dl, VT: MVT::i32));
11221
11222 // Add the arguments we omitted previously. The register allocator should
11223 // place these in any free register.
11224 if (IsAnyRegCC)
11225 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
11226 Ops.push_back(Elt: getValue(V: CB.getArgOperand(i)));
11227
11228 // Push the arguments from the call instruction.
11229 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
11230 Ops.append(in_start: Call->op_begin() + 2, in_end: e);
11231
11232 // Push live variables for the stack map.
11233 addStackMapLiveVars(Call: CB, StartIdx: NumMetaOpers + NumArgs, DL: dl, Ops, Builder&: *this);
11234
11235 SDVTList NodeTys;
11236 if (IsAnyRegCC && HasDef) {
11237 // Create the return types based on the intrinsic definition
11238 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11239 SmallVector<EVT, 3> ValueVTs;
11240 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: CB.getType(), ValueVTs);
11241 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
11242
11243 // There is always a chain and a glue type at the end
11244 ValueVTs.push_back(Elt: MVT::Other);
11245 ValueVTs.push_back(Elt: MVT::Glue);
11246 NodeTys = DAG.getVTList(VTs: ValueVTs);
11247 } else
11248 NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
11249
11250 // Replace the target specific call node with a PATCHPOINT node.
11251 SDValue PPV = DAG.getNode(Opcode: ISD::PATCHPOINT, DL: dl, VTList: NodeTys, Ops);
11252
11253 // Update the NodeMap.
11254 if (HasDef) {
11255 if (IsAnyRegCC)
11256 setValue(V: &CB, NewN: SDValue(PPV.getNode(), 0));
11257 else
11258 setValue(V: &CB, NewN: Result.first);
11259 }
11260
11261 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
11262 // call sequence. Furthermore the location of the chain and glue can change
11263 // when the AnyReg calling convention is used and the intrinsic returns a
11264 // value.
11265 if (IsAnyRegCC && HasDef) {
11266 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
11267 SDValue To[] = {PPV.getValue(R: 1), PPV.getValue(R: 2)};
11268 DAG.ReplaceAllUsesOfValuesWith(From, To, Num: 2);
11269 } else
11270 DAG.ReplaceAllUsesWith(From: Call, To: PPV.getNode());
11271 DAG.DeleteNode(N: Call);
11272
11273 // Inform the Frame Information that we have a patchpoint in this function.
11274 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
11275}
11276
11277void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
11278 unsigned Intrinsic) {
11279 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11280 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
11281 SDValue Op2;
11282 if (I.arg_size() > 1)
11283 Op2 = getValue(V: I.getArgOperand(i: 1));
11284 SDLoc dl = getCurSDLoc();
11285 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
11286 SDValue Res;
11287 SDNodeFlags SDFlags;
11288 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &I))
11289 SDFlags.copyFMF(FPMO: *FPMO);
11290
11291 switch (Intrinsic) {
11292 case Intrinsic::vector_reduce_fadd:
11293 if (SDFlags.hasAllowReassociation())
11294 Res = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT, N1: Op1,
11295 N2: DAG.getNode(Opcode: ISD::VECREDUCE_FADD, DL: dl, VT, Operand: Op2, Flags: SDFlags),
11296 Flags: SDFlags);
11297 else
11298 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SEQ_FADD, DL: dl, VT, N1: Op1, N2: Op2, Flags: SDFlags);
11299 break;
11300 case Intrinsic::vector_reduce_fmul:
11301 if (SDFlags.hasAllowReassociation())
11302 Res = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT, N1: Op1,
11303 N2: DAG.getNode(Opcode: ISD::VECREDUCE_FMUL, DL: dl, VT, Operand: Op2, Flags: SDFlags),
11304 Flags: SDFlags);
11305 else
11306 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SEQ_FMUL, DL: dl, VT, N1: Op1, N2: Op2, Flags: SDFlags);
11307 break;
11308 case Intrinsic::vector_reduce_add:
11309 Res = DAG.getNode(Opcode: ISD::VECREDUCE_ADD, DL: dl, VT, Operand: Op1);
11310 break;
11311 case Intrinsic::vector_reduce_mul:
11312 Res = DAG.getNode(Opcode: ISD::VECREDUCE_MUL, DL: dl, VT, Operand: Op1);
11313 break;
11314 case Intrinsic::vector_reduce_and:
11315 Res = DAG.getNode(Opcode: ISD::VECREDUCE_AND, DL: dl, VT, Operand: Op1);
11316 break;
11317 case Intrinsic::vector_reduce_or:
11318 Res = DAG.getNode(Opcode: ISD::VECREDUCE_OR, DL: dl, VT, Operand: Op1);
11319 break;
11320 case Intrinsic::vector_reduce_xor:
11321 Res = DAG.getNode(Opcode: ISD::VECREDUCE_XOR, DL: dl, VT, Operand: Op1);
11322 break;
11323 case Intrinsic::vector_reduce_smax:
11324 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SMAX, DL: dl, VT, Operand: Op1);
11325 break;
11326 case Intrinsic::vector_reduce_smin:
11327 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SMIN, DL: dl, VT, Operand: Op1);
11328 break;
11329 case Intrinsic::vector_reduce_umax:
11330 Res = DAG.getNode(Opcode: ISD::VECREDUCE_UMAX, DL: dl, VT, Operand: Op1);
11331 break;
11332 case Intrinsic::vector_reduce_umin:
11333 Res = DAG.getNode(Opcode: ISD::VECREDUCE_UMIN, DL: dl, VT, Operand: Op1);
11334 break;
11335 case Intrinsic::vector_reduce_fmax:
11336 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMAX, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11337 break;
11338 case Intrinsic::vector_reduce_fmin:
11339 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMIN, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11340 break;
11341 case Intrinsic::vector_reduce_fmaximum:
11342 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMAXIMUM, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11343 break;
11344 case Intrinsic::vector_reduce_fminimum:
11345 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMINIMUM, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11346 break;
11347 case Intrinsic::vector_reduce_fmaximumnum:
11348 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMAXIMUMNUM, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11349 break;
11350 case Intrinsic::vector_reduce_fminimumnum:
11351 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMINIMUMNUM, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11352 break;
11353 default:
11354 llvm_unreachable("Unhandled vector reduce intrinsic");
11355 }
11356 setValue(V: &I, NewN: Res);
11357}
11358
11359/// Returns an AttributeList representing the attributes applied to the return
11360/// value of the given call.
11361static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
11362 SmallVector<Attribute::AttrKind, 2> Attrs;
11363 if (CLI.RetSExt)
11364 Attrs.push_back(Elt: Attribute::SExt);
11365 if (CLI.RetZExt)
11366 Attrs.push_back(Elt: Attribute::ZExt);
11367 if (CLI.IsInReg)
11368 Attrs.push_back(Elt: Attribute::InReg);
11369
11370 return AttributeList::get(C&: CLI.RetTy->getContext(), Index: AttributeList::ReturnIndex,
11371 Kinds: Attrs);
11372}
11373
11374/// TargetLowering::LowerCallTo - This is the default LowerCallTo
11375/// implementation, which just calls LowerCall.
11376/// FIXME: When all targets are
11377/// migrated to using LowerCall, this hook should be integrated into SDISel.
11378std::pair<SDValue, SDValue>
11379TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
11380 LLVMContext &Context = CLI.RetTy->getContext();
11381
11382 // Handle the incoming return values from the call.
11383 CLI.Ins.clear();
11384 SmallVector<Type *, 4> RetOrigTys;
11385 SmallVector<TypeSize, 4> Offsets;
11386 auto &DL = CLI.DAG.getDataLayout();
11387 ComputeValueTypes(DL, Ty: CLI.OrigRetTy, Types&: RetOrigTys, Offsets: &Offsets);
11388
11389 SmallVector<EVT, 4> RetVTs;
11390 if (CLI.RetTy != CLI.OrigRetTy) {
11391 assert(RetOrigTys.size() == 1 &&
11392 "Only supported for non-aggregate returns");
11393 RetVTs.push_back(Elt: getValueType(DL, Ty: CLI.RetTy));
11394 } else {
11395 for (Type *Ty : RetOrigTys)
11396 RetVTs.push_back(Elt: getValueType(DL, Ty));
11397 }
11398
11399 if (CLI.IsPostTypeLegalization) {
11400 // If we are lowering a libcall after legalization, split the return type.
11401 SmallVector<Type *, 4> OldRetOrigTys;
11402 SmallVector<EVT, 4> OldRetVTs;
11403 SmallVector<TypeSize, 4> OldOffsets;
11404 RetOrigTys.swap(RHS&: OldRetOrigTys);
11405 RetVTs.swap(RHS&: OldRetVTs);
11406 Offsets.swap(RHS&: OldOffsets);
11407
11408 for (size_t i = 0, e = OldRetVTs.size(); i != e; ++i) {
11409 EVT RetVT = OldRetVTs[i];
11410 uint64_t Offset = OldOffsets[i];
11411 MVT RegisterVT = getRegisterType(Context, VT: RetVT);
11412 unsigned NumRegs = getNumRegisters(Context, VT: RetVT);
11413 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
11414 RetOrigTys.append(NumInputs: NumRegs, Elt: OldRetOrigTys[i]);
11415 RetVTs.append(NumInputs: NumRegs, Elt: RegisterVT);
11416 for (unsigned j = 0; j != NumRegs; ++j)
11417 Offsets.push_back(Elt: TypeSize::getFixed(ExactSize: Offset + j * RegisterVTByteSZ));
11418 }
11419 }
11420
11421 SmallVector<ISD::OutputArg, 4> Outs;
11422 GetReturnInfo(CC: CLI.CallConv, ReturnType: CLI.RetTy, attr: getReturnAttrs(CLI), Outs, TLI: *this, DL);
11423
11424 bool CanLowerReturn =
11425 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
11426 CLI.IsVarArg, Outs, Context, RetTy: CLI.RetTy);
11427
11428 SDValue DemoteStackSlot;
11429 int DemoteStackIdx = -100;
11430 if (!CanLowerReturn) {
11431 // FIXME: equivalent assert?
11432 // assert(!CS.hasInAllocaArgument() &&
11433 // "sret demotion is incompatible with inalloca");
11434 uint64_t TySize = DL.getTypeAllocSize(Ty: CLI.RetTy);
11435 Align Alignment = DL.getPrefTypeAlign(Ty: CLI.RetTy);
11436 MachineFunction &MF = CLI.DAG.getMachineFunction();
11437 DemoteStackIdx =
11438 MF.getFrameInfo().CreateStackObject(Size: TySize, Alignment, isSpillSlot: false);
11439 Type *StackSlotPtrType = PointerType::get(C&: Context, AddressSpace: DL.getAllocaAddrSpace());
11440
11441 DemoteStackSlot = CLI.DAG.getFrameIndex(FI: DemoteStackIdx, VT: getFrameIndexTy(DL));
11442 ArgListEntry Entry(DemoteStackSlot, StackSlotPtrType);
11443 Entry.IsSRet = true;
11444 Entry.Alignment = Alignment;
11445 CLI.getArgs().insert(position: CLI.getArgs().begin(), x: Entry);
11446 CLI.NumFixedArgs += 1;
11447 CLI.getArgs()[0].IndirectType = CLI.RetTy;
11448 CLI.RetTy = CLI.OrigRetTy = Type::getVoidTy(C&: Context);
11449
11450 // sret demotion isn't compatible with tail-calls, since the sret argument
11451 // points into the callers stack frame.
11452 CLI.IsTailCall = false;
11453 } else {
11454 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11455 Ty: CLI.RetTy, CallConv: CLI.CallConv, isVarArg: CLI.IsVarArg, DL);
11456 for (unsigned I = 0, E = RetVTs.size(); I != E; ++I) {
11457 ISD::ArgFlagsTy Flags;
11458 if (NeedsRegBlock) {
11459 Flags.setInConsecutiveRegs();
11460 if (I == RetVTs.size() - 1)
11461 Flags.setInConsecutiveRegsLast();
11462 }
11463 EVT VT = RetVTs[I];
11464 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CC: CLI.CallConv, VT);
11465 unsigned NumRegs =
11466 getNumRegistersForCallingConv(Context, CC: CLI.CallConv, VT);
11467 for (unsigned i = 0; i != NumRegs; ++i) {
11468 ISD::InputArg Ret(Flags, RegisterVT, VT, RetOrigTys[I],
11469 CLI.IsReturnValueUsed, ISD::InputArg::NoArgIndex, 0);
11470 if (CLI.RetTy->isPointerTy()) {
11471 Ret.Flags.setPointer();
11472 Ret.Flags.setPointerAddrSpace(
11473 cast<PointerType>(Val: CLI.RetTy)->getAddressSpace());
11474 }
11475 if (CLI.RetSExt)
11476 Ret.Flags.setSExt();
11477 if (CLI.RetZExt)
11478 Ret.Flags.setZExt();
11479 if (CLI.IsInReg)
11480 Ret.Flags.setInReg();
11481 CLI.Ins.push_back(Elt: Ret);
11482 }
11483 }
11484 }
11485
11486 // We push in swifterror return as the last element of CLI.Ins.
11487 ArgListTy &Args = CLI.getArgs();
11488 if (supportSwiftError()) {
11489 for (const ArgListEntry &Arg : Args) {
11490 if (Arg.IsSwiftError) {
11491 ISD::ArgFlagsTy Flags;
11492 Flags.setSwiftError();
11493 ISD::InputArg Ret(Flags, getPointerTy(DL), EVT(getPointerTy(DL)),
11494 PointerType::getUnqual(C&: Context),
11495 /*Used=*/true, ISD::InputArg::NoArgIndex, 0);
11496 CLI.Ins.push_back(Elt: Ret);
11497 }
11498 }
11499 }
11500
11501 // Handle all of the outgoing arguments.
11502 CLI.Outs.clear();
11503 CLI.OutVals.clear();
11504 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11505 SmallVector<Type *, 4> OrigArgTys;
11506 ComputeValueTypes(DL, Ty: Args[i].OrigTy, Types&: OrigArgTys);
11507 // FIXME: Split arguments if CLI.IsPostTypeLegalization
11508 Type *FinalType = Args[i].Ty;
11509 if (Args[i].IsByVal)
11510 FinalType = Args[i].IndirectType;
11511 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11512 Ty: FinalType, CallConv: CLI.CallConv, isVarArg: CLI.IsVarArg, DL);
11513 for (unsigned Value = 0, NumValues = OrigArgTys.size(); Value != NumValues;
11514 ++Value) {
11515 Type *OrigArgTy = OrigArgTys[Value];
11516 Type *ArgTy = OrigArgTy;
11517 if (Args[i].Ty != Args[i].OrigTy) {
11518 assert(Value == 0 && "Only supported for non-aggregate arguments");
11519 ArgTy = Args[i].Ty;
11520 }
11521
11522 EVT VT = getValueType(DL, Ty: ArgTy);
11523 SDValue Op = SDValue(Args[i].Node.getNode(),
11524 Args[i].Node.getResNo() + Value);
11525 ISD::ArgFlagsTy Flags;
11526
11527 // Certain targets (such as MIPS), may have a different ABI alignment
11528 // for a type depending on the context. Give the target a chance to
11529 // specify the alignment it wants.
11530 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11531 Flags.setOrigAlign(OriginalAlignment);
11532
11533 if (i >= CLI.NumFixedArgs)
11534 Flags.setVarArg();
11535 if (ArgTy->isPointerTy()) {
11536 Flags.setPointer();
11537 Flags.setPointerAddrSpace(cast<PointerType>(Val: ArgTy)->getAddressSpace());
11538 }
11539 if (Args[i].IsZExt)
11540 Flags.setZExt();
11541 if (Args[i].IsSExt)
11542 Flags.setSExt();
11543 if (Args[i].IsNoExt)
11544 Flags.setNoExt();
11545 if (Args[i].IsInReg) {
11546 // If we are using vectorcall calling convention, a structure that is
11547 // passed InReg - is surely an HVA
11548 if (CLI.CallConv == CallingConv::X86_VectorCall &&
11549 isa<StructType>(Val: FinalType)) {
11550 // The first value of a structure is marked
11551 if (0 == Value)
11552 Flags.setHvaStart();
11553 Flags.setHva();
11554 }
11555 // Set InReg Flag
11556 Flags.setInReg();
11557 }
11558 if (Args[i].IsSRet)
11559 Flags.setSRet();
11560 if (Args[i].IsSwiftSelf)
11561 Flags.setSwiftSelf();
11562 if (Args[i].IsSwiftAsync)
11563 Flags.setSwiftAsync();
11564 if (Args[i].IsSwiftError)
11565 Flags.setSwiftError();
11566 if (Args[i].IsCFGuardTarget)
11567 Flags.setCFGuardTarget();
11568 if (Args[i].IsByVal)
11569 Flags.setByVal();
11570 if (Args[i].IsByRef)
11571 Flags.setByRef();
11572 if (Args[i].IsPreallocated) {
11573 Flags.setPreallocated();
11574 // Set the byval flag for CCAssignFn callbacks that don't know about
11575 // preallocated. This way we can know how many bytes we should've
11576 // allocated and how many bytes a callee cleanup function will pop. If
11577 // we port preallocated to more targets, we'll have to add custom
11578 // preallocated handling in the various CC lowering callbacks.
11579 Flags.setByVal();
11580 }
11581 if (Args[i].IsInAlloca) {
11582 Flags.setInAlloca();
11583 // Set the byval flag for CCAssignFn callbacks that don't know about
11584 // inalloca. This way we can know how many bytes we should've allocated
11585 // and how many bytes a callee cleanup function will pop. If we port
11586 // inalloca to more targets, we'll have to add custom inalloca handling
11587 // in the various CC lowering callbacks.
11588 Flags.setByVal();
11589 }
11590 Align MemAlign;
11591 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11592 unsigned FrameSize = DL.getTypeAllocSize(Ty: Args[i].IndirectType);
11593 Flags.setByValSize(FrameSize);
11594
11595 // info is not there but there are cases it cannot get right.
11596 if (auto MA = Args[i].Alignment)
11597 MemAlign = *MA;
11598 else
11599 MemAlign = getByValTypeAlignment(Ty: Args[i].IndirectType, DL);
11600 } else if (auto MA = Args[i].Alignment) {
11601 MemAlign = *MA;
11602 } else {
11603 MemAlign = OriginalAlignment;
11604 }
11605 Flags.setMemAlign(MemAlign);
11606 if (Args[i].IsNest)
11607 Flags.setNest();
11608 if (NeedsRegBlock)
11609 Flags.setInConsecutiveRegs();
11610
11611 MVT PartVT = getRegisterTypeForCallingConv(Context, CC: CLI.CallConv, VT);
11612 unsigned NumParts =
11613 getNumRegistersForCallingConv(Context, CC: CLI.CallConv, VT);
11614 SmallVector<SDValue, 4> Parts(NumParts);
11615 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11616
11617 if (Args[i].IsSExt)
11618 ExtendKind = ISD::SIGN_EXTEND;
11619 else if (Args[i].IsZExt)
11620 ExtendKind = ISD::ZERO_EXTEND;
11621
11622 // Conservatively only handle 'returned' on non-vectors that can be lowered,
11623 // for now.
11624 if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11625 CanLowerReturn) {
11626 assert((CLI.RetTy == Args[i].Ty ||
11627 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11628 CLI.RetTy->getPointerAddressSpace() ==
11629 Args[i].Ty->getPointerAddressSpace())) &&
11630 RetVTs.size() == NumValues && "unexpected use of 'returned'");
11631 // Before passing 'returned' to the target lowering code, ensure that
11632 // either the register MVT and the actual EVT are the same size or that
11633 // the return value and argument are extended in the same way; in these
11634 // cases it's safe to pass the argument register value unchanged as the
11635 // return register value (although it's at the target's option whether
11636 // to do so)
11637 // TODO: allow code generation to take advantage of partially preserved
11638 // registers rather than clobbering the entire register when the
11639 // parameter extension method is not compatible with the return
11640 // extension method
11641 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11642 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11643 CLI.RetZExt == Args[i].IsZExt))
11644 Flags.setReturned();
11645 }
11646
11647 getCopyToParts(DAG&: CLI.DAG, DL: CLI.DL, Val: Op, Parts: &Parts[0], NumParts, PartVT, V: CLI.CB,
11648 CallConv: CLI.CallConv, ExtendKind);
11649
11650 for (unsigned j = 0; j != NumParts; ++j) {
11651 // if it isn't first piece, alignment must be 1
11652 // For scalable vectors the scalable part is currently handled
11653 // by individual targets, so we just use the known minimum size here.
11654 ISD::OutputArg MyFlags(
11655 Flags, Parts[j].getValueType().getSimpleVT(), VT, OrigArgTy, i,
11656 j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11657 if (NumParts > 1 && j == 0)
11658 MyFlags.Flags.setSplit();
11659 else if (j != 0) {
11660 MyFlags.Flags.setOrigAlign(Align(1));
11661 if (j == NumParts - 1)
11662 MyFlags.Flags.setSplitEnd();
11663 }
11664
11665 CLI.Outs.push_back(Elt: MyFlags);
11666 CLI.OutVals.push_back(Elt: Parts[j]);
11667 }
11668
11669 if (NeedsRegBlock && Value == NumValues - 1)
11670 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11671 }
11672 }
11673
11674 SmallVector<SDValue, 4> InVals;
11675 CLI.Chain = LowerCall(CLI, InVals);
11676
11677 // Update CLI.InVals to use outside of this function.
11678 CLI.InVals = InVals;
11679
11680 // Verify that the target's LowerCall behaved as expected.
11681 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11682 "LowerCall didn't return a valid chain!");
11683 assert((!CLI.IsTailCall || InVals.empty()) &&
11684 "LowerCall emitted a return value for a tail call!");
11685 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11686 "LowerCall didn't emit the correct number of values!");
11687
11688 // For a tail call, the return value is merely live-out and there aren't
11689 // any nodes in the DAG representing it. Return a special value to
11690 // indicate that a tail call has been emitted and no more Instructions
11691 // should be processed in the current block.
11692 if (CLI.IsTailCall) {
11693 CLI.DAG.setRoot(CLI.Chain);
11694 return std::make_pair(x: SDValue(), y: SDValue());
11695 }
11696
11697#ifndef NDEBUG
11698 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11699 assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11700 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11701 "LowerCall emitted a value with the wrong type!");
11702 }
11703#endif
11704
11705 SmallVector<SDValue, 4> ReturnValues;
11706 if (!CanLowerReturn) {
11707 // The instruction result is the result of loading from the
11708 // hidden sret parameter.
11709 MVT PtrVT = getPointerTy(DL, AS: DL.getAllocaAddrSpace());
11710
11711 unsigned NumValues = RetVTs.size();
11712 ReturnValues.resize(N: NumValues);
11713 SmallVector<SDValue, 4> Chains(NumValues);
11714
11715 // An aggregate return value cannot wrap around the address space, so
11716 // offsets to its parts don't wrap either.
11717 MachineFunction &MF = CLI.DAG.getMachineFunction();
11718 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(ObjectIdx: DemoteStackIdx);
11719 for (unsigned i = 0; i < NumValues; ++i) {
11720 SDValue Add = CLI.DAG.getMemBasePlusOffset(
11721 Base: DemoteStackSlot, Offset: CLI.DAG.getConstant(Val: Offsets[i], DL: CLI.DL, VT: PtrVT),
11722 DL: CLI.DL, Flags: SDNodeFlags::NoUnsignedWrap);
11723 SDValue L = CLI.DAG.getLoad(
11724 VT: RetVTs[i], dl: CLI.DL, Chain: CLI.Chain, Ptr: Add,
11725 PtrInfo: MachinePointerInfo::getFixedStack(MF&: CLI.DAG.getMachineFunction(),
11726 FI: DemoteStackIdx, Offset: Offsets[i]),
11727 Alignment: HiddenSRetAlign);
11728 ReturnValues[i] = L;
11729 Chains[i] = L.getValue(R: 1);
11730 }
11731
11732 CLI.Chain = CLI.DAG.getNode(Opcode: ISD::TokenFactor, DL: CLI.DL, VT: MVT::Other, Ops: Chains);
11733 } else {
11734 // Collect the legal value parts into potentially illegal values
11735 // that correspond to the original function's return values.
11736 std::optional<ISD::NodeType> AssertOp;
11737 if (CLI.RetSExt)
11738 AssertOp = ISD::AssertSext;
11739 else if (CLI.RetZExt)
11740 AssertOp = ISD::AssertZext;
11741 unsigned CurReg = 0;
11742 for (EVT VT : RetVTs) {
11743 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CC: CLI.CallConv, VT);
11744 unsigned NumRegs =
11745 getNumRegistersForCallingConv(Context, CC: CLI.CallConv, VT);
11746
11747 ReturnValues.push_back(Elt: getCopyFromParts(
11748 DAG&: CLI.DAG, DL: CLI.DL, Parts: &InVals[CurReg], NumParts: NumRegs, PartVT: RegisterVT, ValueVT: VT, V: nullptr,
11749 InChain: CLI.Chain, CC: CLI.CallConv, AssertOp));
11750 CurReg += NumRegs;
11751 }
11752
11753 // For a function returning void, there is no return value. We can't create
11754 // such a node, so we just return a null return value in that case. In
11755 // that case, nothing will actually look at the value.
11756 if (ReturnValues.empty())
11757 return std::make_pair(x: SDValue(), y&: CLI.Chain);
11758 }
11759
11760 SDValue Res = CLI.DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: CLI.DL,
11761 VTList: CLI.DAG.getVTList(VTs: RetVTs), Ops: ReturnValues);
11762 return std::make_pair(x&: Res, y&: CLI.Chain);
11763}
11764
11765/// Places new result values for the node in Results (their number
11766/// and types must exactly match those of the original return values of
11767/// the node), or leaves Results empty, which indicates that the node is not
11768/// to be custom lowered after all.
11769void TargetLowering::LowerOperationWrapper(SDNode *N,
11770 SmallVectorImpl<SDValue> &Results,
11771 SelectionDAG &DAG) const {
11772 SDValue Res = LowerOperation(Op: SDValue(N, 0), DAG);
11773
11774 if (!Res.getNode())
11775 return;
11776
11777 // If the original node has one result, take the return value from
11778 // LowerOperation as is. It might not be result number 0.
11779 if (N->getNumValues() == 1) {
11780 Results.push_back(Elt: Res);
11781 return;
11782 }
11783
11784 // If the original node has multiple results, then the return node should
11785 // have the same number of results.
11786 assert((N->getNumValues() == Res->getNumValues()) &&
11787 "Lowering returned the wrong number of results!");
11788
11789 // Places new result values base on N result number.
11790 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11791 Results.push_back(Elt: Res.getValue(R: I));
11792}
11793
11794SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11795 llvm_unreachable("LowerOperation not implemented for this target!");
11796}
11797
11798void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11799 Register Reg,
11800 ISD::NodeType ExtendType) {
11801 SDValue Op = getNonRegisterValue(V);
11802 assert((Op.getOpcode() != ISD::CopyFromReg ||
11803 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11804 "Copy from a reg to the same reg!");
11805 assert(!Reg.isPhysical() && "Is a physreg");
11806
11807 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11808 // If this is an InlineAsm we have to match the registers required, not the
11809 // notional registers required by the type.
11810
11811 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11812 std::nullopt); // This is not an ABI copy.
11813 SDValue Chain = DAG.getEntryNode();
11814
11815 if (ExtendType == ISD::ANY_EXTEND) {
11816 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(Val: V);
11817 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11818 ExtendType = PreferredExtendIt->second;
11819 }
11820 RFV.getCopyToRegs(Val: Op, DAG, dl: getCurSDLoc(), Chain, Glue: nullptr, V, PreferredExtendType: ExtendType);
11821 PendingExports.push_back(Elt: Chain);
11822}
11823
11824#include "llvm/CodeGen/SelectionDAGISel.h"
11825
11826/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11827/// entry block, return true. This includes arguments used by switches, since
11828/// the switch may expand into multiple basic blocks.
11829static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11830 // With FastISel active, we may be splitting blocks, so force creation
11831 // of virtual registers for all non-dead arguments.
11832 if (FastISel)
11833 return A->use_empty();
11834
11835 const BasicBlock &Entry = A->getParent()->front();
11836 for (const User *U : A->users())
11837 if (cast<Instruction>(Val: U)->getParent() != &Entry || isa<SwitchInst>(Val: U))
11838 return false; // Use not in entry block.
11839
11840 return true;
11841}
11842
11843using ArgCopyElisionMapTy =
11844 DenseMap<const Argument *,
11845 std::pair<const AllocaInst *, const StoreInst *>>;
11846
11847/// Scan the entry block of the function in FuncInfo for arguments that look
11848/// like copies into a local alloca. Record any copied arguments in
11849/// ArgCopyElisionCandidates.
11850static void
11851findArgumentCopyElisionCandidates(const DataLayout &DL,
11852 FunctionLoweringInfo *FuncInfo,
11853 ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11854 // Record the state of every static alloca used in the entry block. Argument
11855 // allocas are all used in the entry block, so we need approximately as many
11856 // entries as we have arguments.
11857 enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11858 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11859 unsigned NumArgs = FuncInfo->Fn->arg_size();
11860 StaticAllocas.reserve(NumEntries: NumArgs * 2);
11861
11862 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11863 if (!V)
11864 return nullptr;
11865 V = V->stripPointerCasts();
11866 const auto *AI = dyn_cast<AllocaInst>(Val: V);
11867 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(Val: AI))
11868 return nullptr;
11869 auto Iter = StaticAllocas.insert(KV: {AI, Unknown});
11870 return &Iter.first->second;
11871 };
11872
11873 // Look for stores of arguments to static allocas. Look through bitcasts and
11874 // GEPs to handle type coercions, as long as the alloca is fully initialized
11875 // by the store. Any non-store use of an alloca escapes it and any subsequent
11876 // unanalyzed store might write it.
11877 // FIXME: Handle structs initialized with multiple stores.
11878 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11879 // Look for stores, and handle non-store uses conservatively.
11880 const auto *SI = dyn_cast<StoreInst>(Val: &I);
11881 if (!SI) {
11882 // We will look through cast uses, so ignore them completely.
11883 if (I.isCast())
11884 continue;
11885 // Ignore debug info and pseudo op intrinsics, they don't escape or store
11886 // to allocas.
11887 if (I.isDebugOrPseudoInst())
11888 continue;
11889 // This is an unknown instruction. Assume it escapes or writes to all
11890 // static alloca operands.
11891 for (const Use &U : I.operands()) {
11892 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11893 *Info = StaticAllocaInfo::Clobbered;
11894 }
11895 continue;
11896 }
11897
11898 // If the stored value is a static alloca, mark it as escaped.
11899 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11900 *Info = StaticAllocaInfo::Clobbered;
11901
11902 // Check if the destination is a static alloca.
11903 const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11904 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11905 if (!Info)
11906 continue;
11907 const AllocaInst *AI = cast<AllocaInst>(Val: Dst);
11908
11909 // Skip allocas that have been initialized or clobbered.
11910 if (*Info != StaticAllocaInfo::Unknown)
11911 continue;
11912
11913 // Check if the stored value is an argument, and that this store fully
11914 // initializes the alloca.
11915 // If the argument type has padding bits we can't directly forward a pointer
11916 // as the upper bits may contain garbage.
11917 // Don't elide copies from the same argument twice.
11918 const Value *Val = SI->getValueOperand()->stripPointerCasts();
11919 const auto *Arg = dyn_cast<Argument>(Val);
11920 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL);
11921 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11922 Arg->getType()->isEmptyTy() || !AllocaSize ||
11923 DL.getTypeStoreSize(Ty: Arg->getType()) != *AllocaSize ||
11924 !DL.typeSizeEqualsStoreSize(Ty: Arg->getType()) ||
11925 ArgCopyElisionCandidates.count(Val: Arg)) {
11926 *Info = StaticAllocaInfo::Clobbered;
11927 continue;
11928 }
11929
11930 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11931 << '\n');
11932
11933 // Mark this alloca and store for argument copy elision.
11934 *Info = StaticAllocaInfo::Elidable;
11935 ArgCopyElisionCandidates.insert(KV: {Arg, {AI, SI}});
11936
11937 // Stop scanning if we've seen all arguments. This will happen early in -O0
11938 // builds, which is useful, because -O0 builds have large entry blocks and
11939 // many allocas.
11940 if (ArgCopyElisionCandidates.size() == NumArgs)
11941 break;
11942 }
11943}
11944
11945/// Try to elide argument copies from memory into a local alloca. Succeeds if
11946/// ArgVal is a load from a suitable fixed stack object.
11947static void tryToElideArgumentCopy(
11948 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11949 DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11950 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11951 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11952 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11953 // Check if this is a load from a fixed stack object.
11954 auto *LNode = dyn_cast<LoadSDNode>(Val: ArgVals[0]);
11955 if (!LNode)
11956 return;
11957 auto *FINode = dyn_cast<FrameIndexSDNode>(Val: LNode->getBasePtr().getNode());
11958 if (!FINode)
11959 return;
11960
11961 // Check that the fixed stack object is the right size and alignment.
11962 // Look at the alignment that the user wrote on the alloca instead of looking
11963 // at the stack object.
11964 auto ArgCopyIter = ArgCopyElisionCandidates.find(Val: &Arg);
11965 assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11966 const AllocaInst *AI = ArgCopyIter->second.first;
11967 int FixedIndex = FINode->getIndex();
11968 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11969 int OldIndex = AllocaIndex;
11970 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11971 if (MFI.getObjectSize(ObjectIdx: FixedIndex) != MFI.getObjectSize(ObjectIdx: OldIndex)) {
11972 LLVM_DEBUG(
11973 dbgs() << " argument copy elision failed due to bad fixed stack "
11974 "object size\n");
11975 return;
11976 }
11977 Align RequiredAlignment = AI->getAlign();
11978 if (MFI.getObjectAlign(ObjectIdx: FixedIndex) < RequiredAlignment) {
11979 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
11980 "greater than stack argument alignment ("
11981 << DebugStr(RequiredAlignment) << " vs "
11982 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11983 return;
11984 }
11985
11986 // Perform the elision. Delete the old stack object and replace its only use
11987 // in the variable info map. Mark the stack object as mutable and aliased.
11988 LLVM_DEBUG({
11989 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11990 << " Replacing frame index " << OldIndex << " with " << FixedIndex
11991 << '\n';
11992 });
11993 MFI.RemoveStackObject(ObjectIdx: OldIndex);
11994 MFI.setIsImmutableObjectIndex(ObjectIdx: FixedIndex, IsImmutable: false);
11995 MFI.setIsAliasedObjectIndex(ObjectIdx: FixedIndex, IsAliased: true);
11996 AllocaIndex = FixedIndex;
11997 ArgCopyElisionFrameIndexMap.insert(KV: {OldIndex, FixedIndex});
11998 for (SDValue ArgVal : ArgVals)
11999 Chains.push_back(Elt: ArgVal.getValue(R: 1));
12000
12001 // Avoid emitting code for the store implementing the copy.
12002 const StoreInst *SI = ArgCopyIter->second.second;
12003 ElidedArgCopyInstrs.insert(Ptr: SI);
12004
12005 // Check for uses of the argument again so that we can avoid exporting ArgVal
12006 // if it is't used by anything other than the store.
12007 for (const Value *U : Arg.users()) {
12008 if (U != SI) {
12009 ArgHasUses = true;
12010 break;
12011 }
12012 }
12013}
12014
12015void SelectionDAGISel::LowerArguments(const Function &F) {
12016 SelectionDAG &DAG = SDB->DAG;
12017 SDLoc dl = SDB->getCurSDLoc();
12018 const DataLayout &DL = DAG.getDataLayout();
12019 SmallVector<ISD::InputArg, 16> Ins;
12020
12021 // In Naked functions we aren't going to save any registers.
12022 if (F.hasFnAttribute(Kind: Attribute::Naked))
12023 return;
12024
12025 if (!FuncInfo->CanLowerReturn) {
12026 // Put in an sret pointer parameter before all the other parameters.
12027 MVT ValueVT = TLI->getPointerTy(DL, AS: DL.getAllocaAddrSpace());
12028
12029 ISD::ArgFlagsTy Flags;
12030 Flags.setSRet();
12031 MVT RegisterVT = TLI->getRegisterType(Context&: *DAG.getContext(), VT: ValueVT);
12032 ISD::InputArg RetArg(Flags, RegisterVT, ValueVT, F.getReturnType(), true,
12033 ISD::InputArg::NoArgIndex, 0);
12034 Ins.push_back(Elt: RetArg);
12035 }
12036
12037 // Look for stores of arguments to static allocas. Mark such arguments with a
12038 // flag to ask the target to give us the memory location of that argument if
12039 // available.
12040 ArgCopyElisionMapTy ArgCopyElisionCandidates;
12041 findArgumentCopyElisionCandidates(DL, FuncInfo: FuncInfo.get(),
12042 ArgCopyElisionCandidates);
12043
12044 // Set up the incoming argument description vector.
12045 for (const Argument &Arg : F.args()) {
12046 unsigned ArgNo = Arg.getArgNo();
12047 SmallVector<Type *, 4> Types;
12048 ComputeValueTypes(DL: DAG.getDataLayout(), Ty: Arg.getType(), Types);
12049 bool isArgValueUsed = !Arg.use_empty();
12050 Type *FinalType = Arg.getType();
12051 if (Arg.hasAttribute(Kind: Attribute::ByVal))
12052 FinalType = Arg.getParamByValType();
12053 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
12054 Ty: FinalType, CallConv: F.getCallingConv(), isVarArg: F.isVarArg(), DL);
12055 for (unsigned Value = 0, NumValues = Types.size(); Value != NumValues;
12056 ++Value) {
12057 Type *ArgTy = Types[Value];
12058 EVT VT = TLI->getValueType(DL, Ty: ArgTy);
12059 ISD::ArgFlagsTy Flags;
12060
12061 if (ArgTy->isPointerTy()) {
12062 Flags.setPointer();
12063 Flags.setPointerAddrSpace(cast<PointerType>(Val: ArgTy)->getAddressSpace());
12064 }
12065 if (Arg.hasAttribute(Kind: Attribute::ZExt))
12066 Flags.setZExt();
12067 if (Arg.hasAttribute(Kind: Attribute::SExt))
12068 Flags.setSExt();
12069 if (Arg.hasAttribute(Kind: Attribute::InReg)) {
12070 // If we are using vectorcall calling convention, a structure that is
12071 // passed InReg - is surely an HVA
12072 if (F.getCallingConv() == CallingConv::X86_VectorCall &&
12073 isa<StructType>(Val: Arg.getType())) {
12074 // The first value of a structure is marked
12075 if (0 == Value)
12076 Flags.setHvaStart();
12077 Flags.setHva();
12078 }
12079 // Set InReg Flag
12080 Flags.setInReg();
12081 }
12082 if (Arg.hasAttribute(Kind: Attribute::StructRet))
12083 Flags.setSRet();
12084 if (Arg.hasAttribute(Kind: Attribute::SwiftSelf))
12085 Flags.setSwiftSelf();
12086 if (Arg.hasAttribute(Kind: Attribute::SwiftAsync))
12087 Flags.setSwiftAsync();
12088 if (Arg.hasAttribute(Kind: Attribute::SwiftError))
12089 Flags.setSwiftError();
12090 if (Arg.hasAttribute(Kind: Attribute::ByVal))
12091 Flags.setByVal();
12092 if (Arg.hasAttribute(Kind: Attribute::ByRef))
12093 Flags.setByRef();
12094 if (Arg.hasAttribute(Kind: Attribute::InAlloca)) {
12095 Flags.setInAlloca();
12096 // Set the byval flag for CCAssignFn callbacks that don't know about
12097 // inalloca. This way we can know how many bytes we should've allocated
12098 // and how many bytes a callee cleanup function will pop. If we port
12099 // inalloca to more targets, we'll have to add custom inalloca handling
12100 // in the various CC lowering callbacks.
12101 Flags.setByVal();
12102 }
12103 if (Arg.hasAttribute(Kind: Attribute::Preallocated)) {
12104 Flags.setPreallocated();
12105 // Set the byval flag for CCAssignFn callbacks that don't know about
12106 // preallocated. This way we can know how many bytes we should've
12107 // allocated and how many bytes a callee cleanup function will pop. If
12108 // we port preallocated to more targets, we'll have to add custom
12109 // preallocated handling in the various CC lowering callbacks.
12110 Flags.setByVal();
12111 }
12112
12113 // Certain targets (such as MIPS), may have a different ABI alignment
12114 // for a type depending on the context. Give the target a chance to
12115 // specify the alignment it wants.
12116 const Align OriginalAlignment(
12117 TLI->getABIAlignmentForCallingConv(ArgTy, DL));
12118 Flags.setOrigAlign(OriginalAlignment);
12119
12120 Align MemAlign;
12121 Type *ArgMemTy = nullptr;
12122 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
12123 Flags.isByRef()) {
12124 if (!ArgMemTy)
12125 ArgMemTy = Arg.getPointeeInMemoryValueType();
12126
12127 uint64_t MemSize = DL.getTypeAllocSize(Ty: ArgMemTy);
12128
12129 // For in-memory arguments, size and alignment should be passed from FE.
12130 // BE will guess if this info is not there but there are cases it cannot
12131 // get right.
12132 if (auto ParamAlign = Arg.getParamStackAlign())
12133 MemAlign = *ParamAlign;
12134 else if ((ParamAlign = Arg.getParamAlign()))
12135 MemAlign = *ParamAlign;
12136 else
12137 MemAlign = TLI->getByValTypeAlignment(Ty: ArgMemTy, DL);
12138 if (Flags.isByRef())
12139 Flags.setByRefSize(MemSize);
12140 else
12141 Flags.setByValSize(MemSize);
12142 } else if (auto ParamAlign = Arg.getParamStackAlign()) {
12143 MemAlign = *ParamAlign;
12144 } else {
12145 MemAlign = OriginalAlignment;
12146 }
12147 Flags.setMemAlign(MemAlign);
12148
12149 if (Arg.hasAttribute(Kind: Attribute::Nest))
12150 Flags.setNest();
12151 if (NeedsRegBlock)
12152 Flags.setInConsecutiveRegs();
12153 if (ArgCopyElisionCandidates.count(Val: &Arg))
12154 Flags.setCopyElisionCandidate();
12155 if (Arg.hasAttribute(Kind: Attribute::Returned))
12156 Flags.setReturned();
12157
12158 MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
12159 Context&: *CurDAG->getContext(), CC: F.getCallingConv(), VT);
12160 unsigned NumRegs = TLI->getNumRegistersForCallingConv(
12161 Context&: *CurDAG->getContext(), CC: F.getCallingConv(), VT);
12162 for (unsigned i = 0; i != NumRegs; ++i) {
12163 // For scalable vectors, use the minimum size; individual targets
12164 // are responsible for handling scalable vector arguments and
12165 // return values.
12166 ISD::InputArg MyFlags(
12167 Flags, RegisterVT, VT, ArgTy, isArgValueUsed, ArgNo,
12168 i * RegisterVT.getStoreSize().getKnownMinValue());
12169 if (NumRegs > 1 && i == 0)
12170 MyFlags.Flags.setSplit();
12171 // if it isn't first piece, alignment must be 1
12172 else if (i > 0) {
12173 MyFlags.Flags.setOrigAlign(Align(1));
12174 if (i == NumRegs - 1)
12175 MyFlags.Flags.setSplitEnd();
12176 }
12177 Ins.push_back(Elt: MyFlags);
12178 }
12179 if (NeedsRegBlock && Value == NumValues - 1)
12180 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
12181 }
12182 }
12183
12184 // Call the target to set up the argument values.
12185 SmallVector<SDValue, 8> InVals;
12186 SDValue NewRoot = TLI->LowerFormalArguments(
12187 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
12188
12189 // Verify that the target's LowerFormalArguments behaved as expected.
12190 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
12191 "LowerFormalArguments didn't return a valid chain!");
12192 assert(InVals.size() == Ins.size() &&
12193 "LowerFormalArguments didn't emit the correct number of values!");
12194 assert(all_of(InVals, [](SDValue InVal) { return InVal.getNode(); }) &&
12195 "LowerFormalArguments emitted a null value!");
12196
12197 // Update the DAG with the new chain value resulting from argument lowering.
12198 DAG.setRoot(NewRoot);
12199
12200 // Set up the argument values.
12201 unsigned i = 0;
12202 if (!FuncInfo->CanLowerReturn) {
12203 // Create a virtual register for the sret pointer, and put in a copy
12204 // from the sret argument into it.
12205 MVT VT = TLI->getPointerTy(DL, AS: DL.getAllocaAddrSpace());
12206 MVT RegVT = TLI->getRegisterType(Context&: *CurDAG->getContext(), VT);
12207 std::optional<ISD::NodeType> AssertOp;
12208 SDValue ArgValue =
12209 getCopyFromParts(DAG, DL: dl, Parts: &InVals[0], NumParts: 1, PartVT: RegVT, ValueVT: VT, V: nullptr, InChain: NewRoot,
12210 CC: F.getCallingConv(), AssertOp);
12211
12212 MachineFunction& MF = SDB->DAG.getMachineFunction();
12213 MachineRegisterInfo& RegInfo = MF.getRegInfo();
12214 Register SRetReg =
12215 RegInfo.createVirtualRegister(RegClass: TLI->getRegClassFor(VT: RegVT));
12216 FuncInfo->DemoteRegister = SRetReg;
12217 NewRoot =
12218 SDB->DAG.getCopyToReg(Chain: NewRoot, dl: SDB->getCurSDLoc(), Reg: SRetReg, N: ArgValue);
12219 DAG.setRoot(NewRoot);
12220
12221 // i indexes lowered arguments. Bump it past the hidden sret argument.
12222 ++i;
12223 }
12224
12225 SmallVector<SDValue, 4> Chains;
12226 DenseMap<int, int> ArgCopyElisionFrameIndexMap;
12227 for (const Argument &Arg : F.args()) {
12228 SmallVector<SDValue, 4> ArgValues;
12229 SmallVector<EVT, 4> ValueVTs;
12230 ComputeValueVTs(TLI: *TLI, DL: DAG.getDataLayout(), Ty: Arg.getType(), ValueVTs);
12231 unsigned NumValues = ValueVTs.size();
12232 if (NumValues == 0)
12233 continue;
12234
12235 bool ArgHasUses = !Arg.use_empty();
12236
12237 // Elide the copying store if the target loaded this argument from a
12238 // suitable fixed stack object.
12239 if (Ins[i].Flags.isCopyElisionCandidate()) {
12240 unsigned NumParts = 0;
12241 for (EVT VT : ValueVTs)
12242 NumParts += TLI->getNumRegistersForCallingConv(Context&: *CurDAG->getContext(),
12243 CC: F.getCallingConv(), VT);
12244
12245 tryToElideArgumentCopy(FuncInfo&: *FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
12246 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
12247 ArgVals: ArrayRef(&InVals[i], NumParts), ArgHasUses);
12248 }
12249
12250 // If this argument is unused then remember its value. It is used to generate
12251 // debugging information.
12252 bool isSwiftErrorArg =
12253 TLI->supportSwiftError() &&
12254 Arg.hasAttribute(Kind: Attribute::SwiftError);
12255 if (!ArgHasUses && !isSwiftErrorArg) {
12256 SDB->setUnusedArgValue(V: &Arg, NewN: InVals[i]);
12257
12258 // Also remember any frame index for use in FastISel.
12259 if (FrameIndexSDNode *FI =
12260 dyn_cast<FrameIndexSDNode>(Val: InVals[i].getNode()))
12261 FuncInfo->setArgumentFrameIndex(A: &Arg, FI: FI->getIndex());
12262 }
12263
12264 for (unsigned Val = 0; Val != NumValues; ++Val) {
12265 EVT VT = ValueVTs[Val];
12266 MVT PartVT = TLI->getRegisterTypeForCallingConv(Context&: *CurDAG->getContext(),
12267 CC: F.getCallingConv(), VT);
12268 unsigned NumParts = TLI->getNumRegistersForCallingConv(
12269 Context&: *CurDAG->getContext(), CC: F.getCallingConv(), VT);
12270
12271 // Even an apparent 'unused' swifterror argument needs to be returned. So
12272 // we do generate a copy for it that can be used on return from the
12273 // function.
12274 if (ArgHasUses || isSwiftErrorArg) {
12275 std::optional<ISD::NodeType> AssertOp;
12276 if (Arg.hasAttribute(Kind: Attribute::SExt))
12277 AssertOp = ISD::AssertSext;
12278 else if (Arg.hasAttribute(Kind: Attribute::ZExt))
12279 AssertOp = ISD::AssertZext;
12280
12281 SDValue OutVal =
12282 getCopyFromParts(DAG, DL: dl, Parts: &InVals[i], NumParts, PartVT, ValueVT: VT, V: nullptr,
12283 InChain: NewRoot, CC: F.getCallingConv(), AssertOp);
12284
12285 FPClassTest NoFPClass = Arg.getNoFPClass();
12286 if (NoFPClass != fcNone) {
12287 SDValue SDNoFPClass = DAG.getTargetConstant(
12288 Val: static_cast<uint64_t>(NoFPClass), DL: dl, VT: MVT::i32);
12289 OutVal = DAG.getNode(Opcode: ISD::AssertNoFPClass, DL: dl, VT: OutVal.getValueType(),
12290 N1: OutVal, N2: SDNoFPClass);
12291 }
12292 ArgValues.push_back(Elt: OutVal);
12293 }
12294
12295 i += NumParts;
12296 }
12297
12298 // We don't need to do anything else for unused arguments.
12299 if (ArgValues.empty())
12300 continue;
12301
12302 // Note down frame index.
12303 if (FrameIndexSDNode *FI =
12304 dyn_cast<FrameIndexSDNode>(Val: ArgValues[0].getNode()))
12305 FuncInfo->setArgumentFrameIndex(A: &Arg, FI: FI->getIndex());
12306
12307 SDValue Res = DAG.getMergeValues(Ops: ArrayRef(ArgValues.data(), NumValues),
12308 dl: SDB->getCurSDLoc());
12309
12310 SDB->setValue(V: &Arg, NewN: Res);
12311 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
12312 // We want to associate the argument with the frame index, among
12313 // involved operands, that correspond to the lowest address. The
12314 // getCopyFromParts function, called earlier, is swapping the order of
12315 // the operands to BUILD_PAIR depending on endianness. The result of
12316 // that swapping is that the least significant bits of the argument will
12317 // be in the first operand of the BUILD_PAIR node, and the most
12318 // significant bits will be in the second operand.
12319 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
12320 if (LoadSDNode *LNode =
12321 dyn_cast<LoadSDNode>(Val: Res.getOperand(i: LowAddressOp).getNode()))
12322 if (FrameIndexSDNode *FI =
12323 dyn_cast<FrameIndexSDNode>(Val: LNode->getBasePtr().getNode()))
12324 FuncInfo->setArgumentFrameIndex(A: &Arg, FI: FI->getIndex());
12325 }
12326
12327 // Analyses past this point are naive and don't expect an assertion.
12328 if (Res.getOpcode() == ISD::AssertZext)
12329 Res = Res.getOperand(i: 0);
12330
12331 // Update the SwiftErrorVRegDefMap.
12332 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
12333 Register Reg = cast<RegisterSDNode>(Val: Res.getOperand(i: 1))->getReg();
12334 if (Reg.isVirtual())
12335 SwiftError->setCurrentVReg(MBB: FuncInfo->MBB, SwiftError->getFunctionArg(),
12336 Reg);
12337 }
12338
12339 // If this argument is live outside of the entry block, insert a copy from
12340 // wherever we got it to the vreg that other BB's will reference it as.
12341 if (Res.getOpcode() == ISD::CopyFromReg) {
12342 // If we can, though, try to skip creating an unnecessary vreg.
12343 // FIXME: This isn't very clean... it would be nice to make this more
12344 // general.
12345 Register Reg = cast<RegisterSDNode>(Val: Res.getOperand(i: 1))->getReg();
12346 if (Reg.isVirtual()) {
12347 FuncInfo->ValueMap[&Arg] = Reg;
12348 continue;
12349 }
12350 }
12351 if (!isOnlyUsedInEntryBlock(A: &Arg, FastISel: TM.Options.EnableFastISel)) {
12352 FuncInfo->InitializeRegForValue(V: &Arg);
12353 SDB->CopyToExportRegsIfNeeded(V: &Arg);
12354 }
12355 }
12356
12357 if (!Chains.empty()) {
12358 Chains.push_back(Elt: NewRoot);
12359 NewRoot = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: Chains);
12360 }
12361
12362 DAG.setRoot(NewRoot);
12363
12364 assert(i == InVals.size() && "Argument register count mismatch!");
12365
12366 // If any argument copy elisions occurred and we have debug info, update the
12367 // stale frame indices used in the dbg.declare variable info table.
12368 if (!ArgCopyElisionFrameIndexMap.empty()) {
12369 for (MachineFunction::VariableDbgInfo &VI :
12370 MF->getInStackSlotVariableDbgInfo()) {
12371 auto I = ArgCopyElisionFrameIndexMap.find(Val: VI.getStackSlot());
12372 if (I != ArgCopyElisionFrameIndexMap.end())
12373 VI.updateStackSlot(NewSlot: I->second);
12374 }
12375 }
12376
12377 // Finally, if the target has anything special to do, allow it to do so.
12378 emitFunctionEntryCode();
12379}
12380
12381/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
12382/// ensure constants are generated when needed. Remember the virtual registers
12383/// that need to be added to the Machine PHI nodes as input. We cannot just
12384/// directly add them, because expansion might result in multiple MBB's for one
12385/// BB. As such, the start of the BB might correspond to a different MBB than
12386/// the end.
12387void
12388SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
12389 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12390
12391 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
12392
12393 // Check PHI nodes in successors that expect a value to be available from this
12394 // block.
12395 for (const BasicBlock *SuccBB : successors(I: LLVMBB->getTerminator())) {
12396 if (!isa<PHINode>(Val: SuccBB->begin())) continue;
12397 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(BB: SuccBB);
12398
12399 // If this terminator has multiple identical successors (common for
12400 // switches), only handle each succ once.
12401 if (!SuccsHandled.insert(Ptr: SuccMBB).second)
12402 continue;
12403
12404 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
12405
12406 // At this point we know that there is a 1-1 correspondence between LLVM PHI
12407 // nodes and Machine PHI nodes, but the incoming operands have not been
12408 // emitted yet.
12409 for (const PHINode &PN : SuccBB->phis()) {
12410 // Ignore dead phi's.
12411 if (PN.use_empty())
12412 continue;
12413
12414 // Skip empty types
12415 if (PN.getType()->isEmptyTy())
12416 continue;
12417
12418 Register Reg;
12419 const Value *PHIOp = PN.getIncomingValueForBlock(BB: LLVMBB);
12420
12421 if (const auto *C = dyn_cast<Constant>(Val: PHIOp)) {
12422 Register &RegOut = ConstantsOut[C];
12423 if (!RegOut) {
12424 RegOut = FuncInfo.CreateRegs(V: &PN);
12425 // We need to zero/sign extend ConstantInt phi operands to match
12426 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
12427 ISD::NodeType ExtendType = ISD::ANY_EXTEND;
12428 if (auto *CI = dyn_cast<ConstantInt>(Val: C))
12429 ExtendType = TLI.signExtendConstant(C: CI) ? ISD::SIGN_EXTEND
12430 : ISD::ZERO_EXTEND;
12431 CopyValueToVirtualRegister(V: C, Reg: RegOut, ExtendType);
12432 }
12433 Reg = RegOut;
12434 } else {
12435 auto I = FuncInfo.ValueMap.find(Val: PHIOp);
12436 if (I != FuncInfo.ValueMap.end())
12437 Reg = I->second;
12438 else {
12439 assert(isa<AllocaInst>(PHIOp) &&
12440 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
12441 "Didn't codegen value into a register!??");
12442 Reg = FuncInfo.CreateRegs(V: &PN);
12443 CopyValueToVirtualRegister(V: PHIOp, Reg);
12444 }
12445 }
12446
12447 // Remember that this register needs to added to the machine PHI node as
12448 // the input for this MBB.
12449 SmallVector<EVT, 4> ValueVTs;
12450 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: PN.getType(), ValueVTs);
12451 for (EVT VT : ValueVTs) {
12452 const unsigned NumRegisters = TLI.getNumRegisters(Context&: *DAG.getContext(), VT);
12453 for (unsigned i = 0; i != NumRegisters; ++i)
12454 FuncInfo.PHINodesToUpdate.emplace_back(args: &*MBBI++, args: Reg + i);
12455 Reg += NumRegisters;
12456 }
12457 }
12458 }
12459
12460 ConstantsOut.clear();
12461}
12462
12463MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
12464 MachineFunction::iterator I(MBB);
12465 if (++I == FuncInfo.MF->end())
12466 return nullptr;
12467 return &*I;
12468}
12469
12470/// During lowering new call nodes can be created (such as memset, etc.).
12471/// Those will become new roots of the current DAG, but complications arise
12472/// when they are tail calls. In such cases, the call lowering will update
12473/// the root, but the builder still needs to know that a tail call has been
12474/// lowered in order to avoid generating an additional return.
12475void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12476 // If the node is null, we do have a tail call.
12477 if (MaybeTC.getNode() != nullptr)
12478 DAG.setRoot(MaybeTC);
12479 else
12480 HasTailCall = true;
12481}
12482
12483void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12484 MachineBasicBlock *SwitchMBB,
12485 MachineBasicBlock *DefaultMBB) {
12486 MachineFunction *CurMF = FuncInfo.MF;
12487 MachineBasicBlock *NextMBB = nullptr;
12488 MachineFunction::iterator BBI(W.MBB);
12489 if (++BBI != FuncInfo.MF->end())
12490 NextMBB = &*BBI;
12491
12492 unsigned Size = W.LastCluster - W.FirstCluster + 1;
12493
12494 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12495
12496 if (Size == 2 && W.MBB == SwitchMBB) {
12497 // If any two of the cases has the same destination, and if one value
12498 // is the same as the other, but has one bit unset that the other has set,
12499 // use bit manipulation to do two compares at once. For example:
12500 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12501 // TODO: This could be extended to merge any 2 cases in switches with 3
12502 // cases.
12503 // TODO: Handle cases where W.CaseBB != SwitchBB.
12504 CaseCluster &Small = *W.FirstCluster;
12505 CaseCluster &Big = *W.LastCluster;
12506
12507 if (Small.Low == Small.High && Big.Low == Big.High &&
12508 Small.MBB == Big.MBB) {
12509 const APInt &SmallValue = Small.Low->getValue();
12510 const APInt &BigValue = Big.Low->getValue();
12511
12512 // Check that there is only one bit different.
12513 APInt CommonBit = BigValue ^ SmallValue;
12514 if (CommonBit.isPowerOf2()) {
12515 SDValue CondLHS = getValue(V: Cond);
12516 EVT VT = CondLHS.getValueType();
12517 SDLoc DL = getCurSDLoc();
12518
12519 SDValue Or = DAG.getNode(Opcode: ISD::OR, DL, VT, N1: CondLHS,
12520 N2: DAG.getConstant(Val: CommonBit, DL, VT));
12521 SDValue Cond = DAG.getSetCC(
12522 DL, VT: MVT::i1, LHS: Or, RHS: DAG.getConstant(Val: BigValue | SmallValue, DL, VT),
12523 Cond: ISD::SETEQ);
12524
12525 // Update successor info.
12526 // Both Small and Big will jump to Small.BB, so we sum up the
12527 // probabilities.
12528 addSuccessorWithProb(Src: SwitchMBB, Dst: Small.MBB, Prob: Small.Prob + Big.Prob);
12529 if (BPI)
12530 addSuccessorWithProb(
12531 Src: SwitchMBB, Dst: DefaultMBB,
12532 // The default destination is the first successor in IR.
12533 Prob: BPI->getEdgeProbability(Src: SwitchMBB->getBasicBlock(), IndexInSuccessors: (unsigned)0));
12534 else
12535 addSuccessorWithProb(Src: SwitchMBB, Dst: DefaultMBB);
12536
12537 // Insert the true branch.
12538 SDValue BrCond =
12539 DAG.getNode(Opcode: ISD::BRCOND, DL, VT: MVT::Other, N1: getControlRoot(), N2: Cond,
12540 N3: DAG.getBasicBlock(MBB: Small.MBB));
12541 // Insert the false branch.
12542 BrCond = DAG.getNode(Opcode: ISD::BR, DL, VT: MVT::Other, N1: BrCond,
12543 N2: DAG.getBasicBlock(MBB: DefaultMBB));
12544
12545 DAG.setRoot(BrCond);
12546 return;
12547 }
12548 }
12549 }
12550
12551 if (TM.getOptLevel() != CodeGenOptLevel::None) {
12552 // Here, we order cases by probability so the most likely case will be
12553 // checked first. However, two clusters can have the same probability in
12554 // which case their relative ordering is non-deterministic. So we use Low
12555 // as a tie-breaker as clusters are guaranteed to never overlap.
12556 llvm::sort(Start: W.FirstCluster, End: W.LastCluster + 1,
12557 Comp: [](const CaseCluster &a, const CaseCluster &b) {
12558 return a.Prob != b.Prob ?
12559 a.Prob > b.Prob :
12560 a.Low->getValue().slt(RHS: b.Low->getValue());
12561 });
12562
12563 // Rearrange the case blocks so that the last one falls through if possible
12564 // without changing the order of probabilities.
12565 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12566 --I;
12567 if (I->Prob > W.LastCluster->Prob)
12568 break;
12569 if (I->Kind == CC_Range && I->MBB == NextMBB) {
12570 std::swap(a&: *I, b&: *W.LastCluster);
12571 break;
12572 }
12573 }
12574 }
12575
12576 // Compute total probability.
12577 BranchProbability DefaultProb = W.DefaultProb;
12578 BranchProbability UnhandledProbs = DefaultProb;
12579 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12580 UnhandledProbs += I->Prob;
12581
12582 MachineBasicBlock *CurMBB = W.MBB;
12583 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12584 bool FallthroughUnreachable = false;
12585 MachineBasicBlock *Fallthrough;
12586 if (I == W.LastCluster) {
12587 // For the last cluster, fall through to the default destination.
12588 Fallthrough = DefaultMBB;
12589 FallthroughUnreachable = isa<UnreachableInst>(
12590 Val: DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12591 } else {
12592 Fallthrough = CurMF->CreateMachineBasicBlock(BB: CurMBB->getBasicBlock());
12593 CurMF->insert(MBBI: BBI, MBB: Fallthrough);
12594 // Put Cond in a virtual register to make it available from the new blocks.
12595 ExportFromCurrentBlock(V: Cond);
12596 }
12597 UnhandledProbs -= I->Prob;
12598
12599 switch (I->Kind) {
12600 case CC_JumpTable: {
12601 // FIXME: Optimize away range check based on pivot comparisons.
12602 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12603 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12604
12605 // The jump block hasn't been inserted yet; insert it here.
12606 MachineBasicBlock *JumpMBB = JT->MBB;
12607 CurMF->insert(MBBI: BBI, MBB: JumpMBB);
12608
12609 auto JumpProb = I->Prob;
12610 auto FallthroughProb = UnhandledProbs;
12611
12612 // If the default statement is a target of the jump table, we evenly
12613 // distribute the default probability to successors of CurMBB. Also
12614 // update the probability on the edge from JumpMBB to Fallthrough.
12615 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12616 SE = JumpMBB->succ_end();
12617 SI != SE; ++SI) {
12618 if (*SI == DefaultMBB) {
12619 JumpProb += DefaultProb / 2;
12620 FallthroughProb -= DefaultProb / 2;
12621 JumpMBB->setSuccProbability(I: SI, Prob: DefaultProb / 2);
12622 JumpMBB->normalizeSuccProbs();
12623 break;
12624 }
12625 }
12626
12627 // If the default clause is unreachable, propagate that knowledge into
12628 // JTH->FallthroughUnreachable which will use it to suppress the range
12629 // check.
12630 //
12631 // However, don't do this if we're doing branch target enforcement,
12632 // because a table branch _without_ a range check can be a tempting JOP
12633 // gadget - out-of-bounds inputs that are impossible in correct
12634 // execution become possible again if an attacker can influence the
12635 // control flow. So if an attacker doesn't already have a BTI bypass
12636 // available, we don't want them to be able to get one out of this
12637 // table branch.
12638 if (FallthroughUnreachable) {
12639 Function &CurFunc = CurMF->getFunction();
12640 if (!CurFunc.hasFnAttribute(Kind: "branch-target-enforcement"))
12641 JTH->FallthroughUnreachable = true;
12642 }
12643
12644 if (!JTH->FallthroughUnreachable)
12645 addSuccessorWithProb(Src: CurMBB, Dst: Fallthrough, Prob: FallthroughProb);
12646 addSuccessorWithProb(Src: CurMBB, Dst: JumpMBB, Prob: JumpProb);
12647 CurMBB->normalizeSuccProbs();
12648
12649 // The jump table header will be inserted in our current block, do the
12650 // range check, and fall through to our fallthrough block.
12651 JTH->HeaderBB = CurMBB;
12652 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12653
12654 // If we're in the right place, emit the jump table header right now.
12655 if (CurMBB == SwitchMBB) {
12656 visitJumpTableHeader(JT&: *JT, JTH&: *JTH, SwitchBB: SwitchMBB);
12657 JTH->Emitted = true;
12658 }
12659 break;
12660 }
12661 case CC_BitTests: {
12662 // FIXME: Optimize away range check based on pivot comparisons.
12663 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12664
12665 // The bit test blocks haven't been inserted yet; insert them here.
12666 for (BitTestCase &BTC : BTB->Cases)
12667 CurMF->insert(MBBI: BBI, MBB: BTC.ThisBB);
12668
12669 // Fill in fields of the BitTestBlock.
12670 BTB->Parent = CurMBB;
12671 BTB->Default = Fallthrough;
12672
12673 BTB->DefaultProb = UnhandledProbs;
12674 // If the cases in bit test don't form a contiguous range, we evenly
12675 // distribute the probability on the edge to Fallthrough to two
12676 // successors of CurMBB.
12677 if (!BTB->ContiguousRange) {
12678 BTB->Prob += DefaultProb / 2;
12679 BTB->DefaultProb -= DefaultProb / 2;
12680 }
12681
12682 if (FallthroughUnreachable)
12683 BTB->FallthroughUnreachable = true;
12684
12685 // If we're in the right place, emit the bit test header right now.
12686 if (CurMBB == SwitchMBB) {
12687 visitBitTestHeader(B&: *BTB, SwitchBB: SwitchMBB);
12688 BTB->Emitted = true;
12689 }
12690 break;
12691 }
12692 case CC_Range: {
12693 const Value *RHS, *LHS, *MHS;
12694 ISD::CondCode CC;
12695 if (I->Low == I->High) {
12696 // Check Cond == I->Low.
12697 CC = ISD::SETEQ;
12698 LHS = Cond;
12699 RHS=I->Low;
12700 MHS = nullptr;
12701 } else {
12702 // Check I->Low <= Cond <= I->High.
12703 CC = ISD::SETLE;
12704 LHS = I->Low;
12705 MHS = Cond;
12706 RHS = I->High;
12707 }
12708
12709 // If Fallthrough is unreachable, fold away the comparison.
12710 if (FallthroughUnreachable)
12711 CC = ISD::SETTRUE;
12712
12713 // The false probability is the sum of all unhandled cases.
12714 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12715 getCurSDLoc(), I->Prob, UnhandledProbs);
12716
12717 if (CurMBB == SwitchMBB)
12718 visitSwitchCase(CB, SwitchBB: SwitchMBB);
12719 else
12720 SL->SwitchCases.push_back(x: CB);
12721
12722 break;
12723 }
12724 }
12725 CurMBB = Fallthrough;
12726 }
12727}
12728
12729void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12730 const SwitchWorkListItem &W,
12731 Value *Cond,
12732 MachineBasicBlock *SwitchMBB) {
12733 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12734 "Clusters not sorted?");
12735 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12736
12737 auto [LastLeft, FirstRight, LeftProb, RightProb] =
12738 SL->computeSplitWorkItemInfo(W);
12739
12740 // Use the first element on the right as pivot since we will make less-than
12741 // comparisons against it.
12742 CaseClusterIt PivotCluster = FirstRight;
12743 assert(PivotCluster > W.FirstCluster);
12744 assert(PivotCluster <= W.LastCluster);
12745
12746 CaseClusterIt FirstLeft = W.FirstCluster;
12747 CaseClusterIt LastRight = W.LastCluster;
12748
12749 const ConstantInt *Pivot = PivotCluster->Low;
12750
12751 // New blocks will be inserted immediately after the current one.
12752 MachineFunction::iterator BBI(W.MBB);
12753 ++BBI;
12754
12755 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12756 // we can branch to its destination directly if it's squeezed exactly in
12757 // between the known lower bound and Pivot - 1.
12758 MachineBasicBlock *LeftMBB;
12759 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12760 FirstLeft->Low == W.GE &&
12761 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12762 LeftMBB = FirstLeft->MBB;
12763 } else {
12764 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(BB: W.MBB->getBasicBlock());
12765 FuncInfo.MF->insert(MBBI: BBI, MBB: LeftMBB);
12766 WorkList.push_back(
12767 Elt: {.MBB: LeftMBB, .FirstCluster: FirstLeft, .LastCluster: LastLeft, .GE: W.GE, .LT: Pivot, .DefaultProb: W.DefaultProb / 2});
12768 // Put Cond in a virtual register to make it available from the new blocks.
12769 ExportFromCurrentBlock(V: Cond);
12770 }
12771
12772 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12773 // single cluster, RHS.Low == Pivot, and we can branch to its destination
12774 // directly if RHS.High equals the current upper bound.
12775 MachineBasicBlock *RightMBB;
12776 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12777 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12778 RightMBB = FirstRight->MBB;
12779 } else {
12780 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(BB: W.MBB->getBasicBlock());
12781 FuncInfo.MF->insert(MBBI: BBI, MBB: RightMBB);
12782 WorkList.push_back(
12783 Elt: {.MBB: RightMBB, .FirstCluster: FirstRight, .LastCluster: LastRight, .GE: Pivot, .LT: W.LT, .DefaultProb: W.DefaultProb / 2});
12784 // Put Cond in a virtual register to make it available from the new blocks.
12785 ExportFromCurrentBlock(V: Cond);
12786 }
12787
12788 // Create the CaseBlock record that will be used to lower the branch.
12789 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12790 getCurSDLoc(), LeftProb, RightProb);
12791
12792 if (W.MBB == SwitchMBB)
12793 visitSwitchCase(CB, SwitchBB: SwitchMBB);
12794 else
12795 SL->SwitchCases.push_back(x: CB);
12796}
12797
12798// Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12799// from the swith statement.
12800static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12801 BranchProbability PeeledCaseProb) {
12802 if (PeeledCaseProb == BranchProbability::getOne())
12803 return BranchProbability::getZero();
12804 BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12805
12806 uint32_t Numerator = CaseProb.getNumerator();
12807 uint32_t Denominator = SwitchProb.scale(Num: CaseProb.getDenominator());
12808 return BranchProbability(Numerator, std::max(a: Numerator, b: Denominator));
12809}
12810
12811// Try to peel the top probability case if it exceeds the threshold.
12812// Return current MachineBasicBlock for the switch statement if the peeling
12813// does not occur.
12814// If the peeling is performed, return the newly created MachineBasicBlock
12815// for the peeled switch statement. Also update Clusters to remove the peeled
12816// case. PeeledCaseProb is the BranchProbability for the peeled case.
12817MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12818 const SwitchInst &SI, CaseClusterVector &Clusters,
12819 BranchProbability &PeeledCaseProb) {
12820 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12821 // Don't perform if there is only one cluster or optimizing for size.
12822 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12823 TM.getOptLevel() == CodeGenOptLevel::None ||
12824 SwitchMBB->getParent()->getFunction().hasMinSize())
12825 return SwitchMBB;
12826
12827 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12828 unsigned PeeledCaseIndex = 0;
12829 bool SwitchPeeled = false;
12830 for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12831 CaseCluster &CC = Clusters[Index];
12832 if (CC.Prob < TopCaseProb)
12833 continue;
12834 TopCaseProb = CC.Prob;
12835 PeeledCaseIndex = Index;
12836 SwitchPeeled = true;
12837 }
12838 if (!SwitchPeeled)
12839 return SwitchMBB;
12840
12841 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12842 << TopCaseProb << "\n");
12843
12844 // Record the MBB for the peeled switch statement.
12845 MachineFunction::iterator BBI(SwitchMBB);
12846 ++BBI;
12847 MachineBasicBlock *PeeledSwitchMBB =
12848 FuncInfo.MF->CreateMachineBasicBlock(BB: SwitchMBB->getBasicBlock());
12849 FuncInfo.MF->insert(MBBI: BBI, MBB: PeeledSwitchMBB);
12850
12851 ExportFromCurrentBlock(V: SI.getCondition());
12852 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12853 SwitchWorkListItem W = {.MBB: SwitchMBB, .FirstCluster: PeeledCaseIt, .LastCluster: PeeledCaseIt,
12854 .GE: nullptr, .LT: nullptr, .DefaultProb: TopCaseProb.getCompl()};
12855 lowerWorkItem(W, Cond: SI.getCondition(), SwitchMBB, DefaultMBB: PeeledSwitchMBB);
12856
12857 Clusters.erase(position: PeeledCaseIt);
12858 for (CaseCluster &CC : Clusters) {
12859 LLVM_DEBUG(
12860 dbgs() << "Scale the probablity for one cluster, before scaling: "
12861 << CC.Prob << "\n");
12862 CC.Prob = scaleCaseProbality(CaseProb: CC.Prob, PeeledCaseProb: TopCaseProb);
12863 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12864 }
12865 PeeledCaseProb = TopCaseProb;
12866 return PeeledSwitchMBB;
12867}
12868
12869void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12870 // Extract cases from the switch.
12871 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12872 CaseClusterVector Clusters;
12873 Clusters.reserve(n: SI.getNumCases());
12874 for (auto I : SI.cases()) {
12875 MachineBasicBlock *Succ = FuncInfo.getMBB(BB: I.getCaseSuccessor());
12876 const ConstantInt *CaseVal = I.getCaseValue();
12877 BranchProbability Prob =
12878 BPI ? BPI->getEdgeProbability(Src: SI.getParent(), IndexInSuccessors: I.getSuccessorIndex())
12879 : BranchProbability(1, SI.getNumCases() + 1);
12880 Clusters.push_back(x: CaseCluster::range(Low: CaseVal, High: CaseVal, MBB: Succ, Prob));
12881 }
12882
12883 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(BB: SI.getDefaultDest());
12884
12885 // Cluster adjacent cases with the same destination. We do this at all
12886 // optimization levels because it's cheap to do and will make codegen faster
12887 // if there are many clusters.
12888 sortAndRangeify(Clusters);
12889
12890 // The branch probablity of the peeled case.
12891 BranchProbability PeeledCaseProb = BranchProbability::getZero();
12892 MachineBasicBlock *PeeledSwitchMBB =
12893 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12894
12895 // If there is only the default destination, jump there directly.
12896 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12897 if (Clusters.empty()) {
12898 assert(PeeledSwitchMBB == SwitchMBB);
12899 SwitchMBB->addSuccessor(Succ: DefaultMBB);
12900 if (DefaultMBB != NextBlock(MBB: SwitchMBB)) {
12901 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other,
12902 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: DefaultMBB)));
12903 }
12904 return;
12905 }
12906
12907 SL->findJumpTables(Clusters, SI: &SI, SL: getCurSDLoc(), DefaultMBB, PSI: DAG.getPSI(),
12908 BFI: DAG.getBFI());
12909 SL->findBitTestClusters(Clusters, SI: &SI);
12910
12911 LLVM_DEBUG({
12912 dbgs() << "Case clusters: ";
12913 for (const CaseCluster &C : Clusters) {
12914 if (C.Kind == CC_JumpTable)
12915 dbgs() << "JT:";
12916 if (C.Kind == CC_BitTests)
12917 dbgs() << "BT:";
12918
12919 C.Low->getValue().print(dbgs(), true);
12920 if (C.Low != C.High) {
12921 dbgs() << '-';
12922 C.High->getValue().print(dbgs(), true);
12923 }
12924 dbgs() << ' ';
12925 }
12926 dbgs() << '\n';
12927 });
12928
12929 assert(!Clusters.empty());
12930 SwitchWorkList WorkList;
12931 CaseClusterIt First = Clusters.begin();
12932 CaseClusterIt Last = Clusters.end() - 1;
12933 auto DefaultProb = getEdgeProbability(Src: PeeledSwitchMBB, Dst: DefaultMBB);
12934 // Scale the branchprobability for DefaultMBB if the peel occurs and
12935 // DefaultMBB is not replaced.
12936 if (PeeledCaseProb != BranchProbability::getZero() &&
12937 DefaultMBB == FuncInfo.getMBB(BB: SI.getDefaultDest()))
12938 DefaultProb = scaleCaseProbality(CaseProb: DefaultProb, PeeledCaseProb);
12939 WorkList.push_back(
12940 Elt: {.MBB: PeeledSwitchMBB, .FirstCluster: First, .LastCluster: Last, .GE: nullptr, .LT: nullptr, .DefaultProb: DefaultProb});
12941
12942 while (!WorkList.empty()) {
12943 SwitchWorkListItem W = WorkList.pop_back_val();
12944 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12945
12946 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12947 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12948 // For optimized builds, lower large range as a balanced binary tree.
12949 splitWorkItem(WorkList, W, Cond: SI.getCondition(), SwitchMBB);
12950 continue;
12951 }
12952
12953 lowerWorkItem(W, Cond: SI.getCondition(), SwitchMBB, DefaultMBB);
12954 }
12955}
12956
12957void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12958 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12959 auto DL = getCurSDLoc();
12960 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
12961 setValue(V: &I, NewN: DAG.getStepVector(DL, ResVT: ResultVT));
12962}
12963
12964void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12965 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12966 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
12967
12968 SDLoc DL = getCurSDLoc();
12969 SDValue V = getValue(V: I.getOperand(i_nocapture: 0));
12970 assert(VT == V.getValueType() && "Malformed vector.reverse!");
12971
12972 if (VT.isScalableVector()) {
12973 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::VECTOR_REVERSE, DL, VT, Operand: V));
12974 return;
12975 }
12976
12977 // Use VECTOR_SHUFFLE for the fixed-length vector
12978 // to maintain existing behavior.
12979 SmallVector<int, 8> Mask;
12980 unsigned NumElts = VT.getVectorMinNumElements();
12981 for (unsigned i = 0; i != NumElts; ++i)
12982 Mask.push_back(Elt: NumElts - 1 - i);
12983
12984 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: V, N2: DAG.getUNDEF(VT), Mask));
12985}
12986
12987void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I,
12988 unsigned Factor) {
12989 auto DL = getCurSDLoc();
12990 SDValue InVec = getValue(V: I.getOperand(i_nocapture: 0));
12991
12992 SmallVector<EVT, 4> ValueVTs;
12993 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty: I.getType(),
12994 ValueVTs);
12995
12996 EVT OutVT = ValueVTs[0];
12997 unsigned OutNumElts = OutVT.getVectorMinNumElements();
12998
12999 SmallVector<SDValue, 4> SubVecs(Factor);
13000 for (unsigned i = 0; i != Factor; ++i) {
13001 assert(ValueVTs[i] == OutVT && "Expected VTs to be the same");
13002 SubVecs[i] = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: OutVT, N1: InVec,
13003 N2: DAG.getVectorIdxConstant(Val: OutNumElts * i, DL));
13004 }
13005
13006 // Use VECTOR_SHUFFLE for fixed-length vectors with factor of 2 to benefit
13007 // from existing legalisation and combines.
13008 if (OutVT.isFixedLengthVector() && Factor == 2) {
13009 SDValue Even = DAG.getVectorShuffle(VT: OutVT, dl: DL, N1: SubVecs[0], N2: SubVecs[1],
13010 Mask: createStrideMask(Start: 0, Stride: 2, VF: OutNumElts));
13011 SDValue Odd = DAG.getVectorShuffle(VT: OutVT, dl: DL, N1: SubVecs[0], N2: SubVecs[1],
13012 Mask: createStrideMask(Start: 1, Stride: 2, VF: OutNumElts));
13013 SDValue Res = DAG.getMergeValues(Ops: {Even, Odd}, dl: getCurSDLoc());
13014 setValue(V: &I, NewN: Res);
13015 return;
13016 }
13017
13018 SDValue Res = DAG.getNode(Opcode: ISD::VECTOR_DEINTERLEAVE, DL,
13019 VTList: DAG.getVTList(VTs: ValueVTs), Ops: SubVecs);
13020 setValue(V: &I, NewN: Res);
13021}
13022
13023void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I,
13024 unsigned Factor) {
13025 auto DL = getCurSDLoc();
13026 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13027 EVT InVT = getValue(V: I.getOperand(i_nocapture: 0)).getValueType();
13028 EVT OutVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
13029
13030 SmallVector<SDValue, 8> InVecs(Factor);
13031 for (unsigned i = 0; i < Factor; ++i) {
13032 InVecs[i] = getValue(V: I.getOperand(i_nocapture: i));
13033 assert(InVecs[i].getValueType() == InVecs[0].getValueType() &&
13034 "Expected VTs to be the same");
13035 }
13036
13037 // Use VECTOR_SHUFFLE for fixed-length vectors with factor of 2 to benefit
13038 // from existing legalisation and combines.
13039 if (OutVT.isFixedLengthVector() && Factor == 2) {
13040 unsigned NumElts = InVT.getVectorMinNumElements();
13041 SDValue V = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: OutVT, Ops: InVecs);
13042 setValue(V: &I, NewN: DAG.getVectorShuffle(VT: OutVT, dl: DL, N1: V, N2: DAG.getUNDEF(VT: OutVT),
13043 Mask: createInterleaveMask(VF: NumElts, NumVecs: 2)));
13044 return;
13045 }
13046
13047 SmallVector<EVT, 8> ValueVTs(Factor, InVT);
13048 SDValue Res =
13049 DAG.getNode(Opcode: ISD::VECTOR_INTERLEAVE, DL, VTList: DAG.getVTList(VTs: ValueVTs), Ops: InVecs);
13050
13051 SmallVector<SDValue, 8> Results(Factor);
13052 for (unsigned i = 0; i < Factor; ++i)
13053 Results[i] = Res.getValue(R: i);
13054
13055 Res = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: OutVT, Ops: Results);
13056 setValue(V: &I, NewN: Res);
13057}
13058
13059void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
13060 SmallVector<EVT, 4> ValueVTs;
13061 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty: I.getType(),
13062 ValueVTs);
13063 unsigned NumValues = ValueVTs.size();
13064 if (NumValues == 0) return;
13065
13066 SmallVector<SDValue, 4> Values(NumValues);
13067 SDValue Op = getValue(V: I.getOperand(i_nocapture: 0));
13068
13069 for (unsigned i = 0; i != NumValues; ++i)
13070 Values[i] = DAG.getNode(Opcode: ISD::FREEZE, DL: getCurSDLoc(), VT: ValueVTs[i],
13071 Operand: SDValue(Op.getNode(), Op.getResNo() + i));
13072
13073 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
13074 VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values));
13075}
13076
13077void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
13078 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13079 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
13080
13081 SDLoc DL = getCurSDLoc();
13082 SDValue V1 = getValue(V: I.getOperand(i_nocapture: 0));
13083 SDValue V2 = getValue(V: I.getOperand(i_nocapture: 1));
13084 const bool IsLeft = I.getIntrinsicID() == Intrinsic::vector_splice_left;
13085
13086 // VECTOR_SHUFFLE doesn't support a scalable or non-constant mask.
13087 if (VT.isScalableVector() || !isa<ConstantInt>(Val: I.getOperand(i_nocapture: 2))) {
13088 SDValue Offset = DAG.getZExtOrTrunc(
13089 Op: getValue(V: I.getOperand(i_nocapture: 2)), DL, VT: TLI.getVectorIdxTy(DL: DAG.getDataLayout()));
13090 setValue(V: &I, NewN: DAG.getNode(Opcode: IsLeft ? ISD::VECTOR_SPLICE_LEFT
13091 : ISD::VECTOR_SPLICE_RIGHT,
13092 DL, VT, N1: V1, N2: V2, N3: Offset));
13093 return;
13094 }
13095 uint64_t Imm = cast<ConstantInt>(Val: I.getOperand(i_nocapture: 2))->getZExtValue();
13096
13097 unsigned NumElts = VT.getVectorNumElements();
13098
13099 uint64_t Idx = IsLeft ? Imm : NumElts - Imm;
13100
13101 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
13102 SmallVector<int, 8> Mask;
13103 for (unsigned i = 0; i < NumElts; ++i)
13104 Mask.push_back(Elt: Idx + i);
13105 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: V1, N2: V2, Mask));
13106}
13107
13108// Consider the following MIR after SelectionDAG, which produces output in
13109// phyregs in the first case or virtregs in the second case.
13110//
13111// INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
13112// %5:gr32 = COPY $ebx
13113// %6:gr32 = COPY $edx
13114// %1:gr32 = COPY %6:gr32
13115// %0:gr32 = COPY %5:gr32
13116//
13117// INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
13118// %1:gr32 = COPY %6:gr32
13119// %0:gr32 = COPY %5:gr32
13120//
13121// Given %0, we'd like to return $ebx in the first case and %5 in the second.
13122// Given %1, we'd like to return $edx in the first case and %6 in the second.
13123//
13124// If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
13125// to a single virtreg (such as %0). The remaining outputs monotonically
13126// increase in virtreg number from there. If a callbr has no outputs, then it
13127// should not have a corresponding callbr landingpad; in fact, the callbr
13128// landingpad would not even be able to refer to such a callbr.
13129static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
13130 MachineInstr *MI = MRI.def_begin(RegNo: Reg)->getParent();
13131 // There is definitely at least one copy.
13132 assert(MI->getOpcode() == TargetOpcode::COPY &&
13133 "start of copy chain MUST be COPY");
13134 Reg = MI->getOperand(i: 1).getReg();
13135
13136 // If the copied register in the first copy must be virtual.
13137 assert(Reg.isVirtual() && "expected COPY of virtual register");
13138 MI = MRI.def_begin(RegNo: Reg)->getParent();
13139
13140 // There may be an optional second copy.
13141 if (MI->getOpcode() == TargetOpcode::COPY) {
13142 assert(Reg.isVirtual() && "expected COPY of virtual register");
13143 Reg = MI->getOperand(i: 1).getReg();
13144 assert(Reg.isPhysical() && "expected COPY of physical register");
13145 } else {
13146 // The start of the chain must be an INLINEASM_BR.
13147 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
13148 "end of copy chain MUST be INLINEASM_BR");
13149 }
13150
13151 return Reg;
13152}
13153
13154// We must do this walk rather than the simpler
13155// setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
13156// otherwise we will end up with copies of virtregs only valid along direct
13157// edges.
13158void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
13159 SmallVector<EVT, 8> ResultVTs;
13160 SmallVector<SDValue, 8> ResultValues;
13161 const auto *CBR =
13162 cast<CallBrInst>(Val: I.getParent()->getUniquePredecessor()->getTerminator());
13163
13164 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13165 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
13166 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
13167
13168 Register InitialDef = FuncInfo.ValueMap[CBR];
13169 SDValue Chain = DAG.getRoot();
13170
13171 // Re-parse the asm constraints string.
13172 TargetLowering::AsmOperandInfoVector TargetConstraints =
13173 TLI.ParseConstraints(DL: DAG.getDataLayout(), TRI, Call: *CBR);
13174 for (auto &T : TargetConstraints) {
13175 SDISelAsmOperandInfo OpInfo(T);
13176 if (OpInfo.Type != InlineAsm::isOutput)
13177 continue;
13178
13179 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
13180 // individual constraint.
13181 TLI.ComputeConstraintToUse(OpInfo, Op: OpInfo.CallOperand, DAG: &DAG);
13182
13183 switch (OpInfo.ConstraintType) {
13184 case TargetLowering::C_Register:
13185 case TargetLowering::C_RegisterClass: {
13186 // Fill in OpInfo.AssignedRegs.Regs.
13187 getRegistersForValue(DAG, DL: getCurSDLoc(), OpInfo, RefOpInfo&: OpInfo);
13188
13189 // getRegistersForValue may produce 1 to many registers based on whether
13190 // the OpInfo.ConstraintVT is legal on the target or not.
13191 for (Register &Reg : OpInfo.AssignedRegs.Regs) {
13192 Register OriginalDef = FollowCopyChain(MRI, Reg: InitialDef++);
13193 if (OriginalDef.isPhysical())
13194 FuncInfo.MBB->addLiveIn(PhysReg: OriginalDef);
13195 // Update the assigned registers to use the original defs.
13196 Reg = OriginalDef;
13197 }
13198
13199 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
13200 DAG, FuncInfo, dl: getCurSDLoc(), Chain, Glue: nullptr, V: CBR);
13201 ResultValues.push_back(Elt: V);
13202 ResultVTs.push_back(Elt: OpInfo.ConstraintVT);
13203 break;
13204 }
13205 case TargetLowering::C_Other: {
13206 SDValue Flag;
13207 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Glue&: Flag, DL: getCurSDLoc(),
13208 OpInfo, DAG);
13209 ++InitialDef;
13210 ResultValues.push_back(Elt: V);
13211 ResultVTs.push_back(Elt: OpInfo.ConstraintVT);
13212 break;
13213 }
13214 default:
13215 break;
13216 }
13217 }
13218 SDValue V = DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
13219 VTList: DAG.getVTList(VTs: ResultVTs), Ops: ResultValues);
13220 setValue(V: &I, NewN: V);
13221}
13222