1//===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements routines for translating from LLVM IR into SelectionDAG IR.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SelectionDAGBuilder.h"
14#include "SDNodeDbgValue.h"
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/Analysis/BranchProbabilityInfo.h"
25#include "llvm/Analysis/ConstantFolding.h"
26#include "llvm/Analysis/Loads.h"
27#include "llvm/Analysis/MemoryLocation.h"
28#include "llvm/Analysis/TargetLibraryInfo.h"
29#include "llvm/Analysis/TargetTransformInfo.h"
30#include "llvm/Analysis/ValueTracking.h"
31#include "llvm/Analysis/VectorUtils.h"
32#include "llvm/CodeGen/Analysis.h"
33#include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
34#include "llvm/CodeGen/CodeGenCommonISel.h"
35#include "llvm/CodeGen/FunctionLoweringInfo.h"
36#include "llvm/CodeGen/GCMetadata.h"
37#include "llvm/CodeGen/ISDOpcodes.h"
38#include "llvm/CodeGen/MachineBasicBlock.h"
39#include "llvm/CodeGen/MachineFrameInfo.h"
40#include "llvm/CodeGen/MachineFunction.h"
41#include "llvm/CodeGen/MachineInstrBuilder.h"
42#include "llvm/CodeGen/MachineInstrBundleIterator.h"
43#include "llvm/CodeGen/MachineMemOperand.h"
44#include "llvm/CodeGen/MachineModuleInfo.h"
45#include "llvm/CodeGen/MachineOperand.h"
46#include "llvm/CodeGen/MachineRegisterInfo.h"
47#include "llvm/CodeGen/SelectionDAG.h"
48#include "llvm/CodeGen/SelectionDAGNodes.h"
49#include "llvm/CodeGen/SelectionDAGTargetInfo.h"
50#include "llvm/CodeGen/StackMaps.h"
51#include "llvm/CodeGen/SwiftErrorValueTracking.h"
52#include "llvm/CodeGen/TargetFrameLowering.h"
53#include "llvm/CodeGen/TargetInstrInfo.h"
54#include "llvm/CodeGen/TargetOpcodes.h"
55#include "llvm/CodeGen/TargetRegisterInfo.h"
56#include "llvm/CodeGen/TargetSubtargetInfo.h"
57#include "llvm/CodeGen/WinEHFuncInfo.h"
58#include "llvm/IR/Argument.h"
59#include "llvm/IR/Attributes.h"
60#include "llvm/IR/BasicBlock.h"
61#include "llvm/IR/CFG.h"
62#include "llvm/IR/CallingConv.h"
63#include "llvm/IR/Constant.h"
64#include "llvm/IR/ConstantRange.h"
65#include "llvm/IR/Constants.h"
66#include "llvm/IR/DataLayout.h"
67#include "llvm/IR/DebugInfo.h"
68#include "llvm/IR/DebugInfoMetadata.h"
69#include "llvm/IR/DerivedTypes.h"
70#include "llvm/IR/DiagnosticInfo.h"
71#include "llvm/IR/EHPersonalities.h"
72#include "llvm/IR/Function.h"
73#include "llvm/IR/GetElementPtrTypeIterator.h"
74#include "llvm/IR/InlineAsm.h"
75#include "llvm/IR/InstrTypes.h"
76#include "llvm/IR/Instructions.h"
77#include "llvm/IR/IntrinsicInst.h"
78#include "llvm/IR/Intrinsics.h"
79#include "llvm/IR/IntrinsicsAArch64.h"
80#include "llvm/IR/IntrinsicsAMDGPU.h"
81#include "llvm/IR/IntrinsicsWebAssembly.h"
82#include "llvm/IR/LLVMContext.h"
83#include "llvm/IR/MemoryModelRelaxationAnnotations.h"
84#include "llvm/IR/Metadata.h"
85#include "llvm/IR/Module.h"
86#include "llvm/IR/Operator.h"
87#include "llvm/IR/PatternMatch.h"
88#include "llvm/IR/Statepoint.h"
89#include "llvm/IR/Type.h"
90#include "llvm/IR/User.h"
91#include "llvm/IR/Value.h"
92#include "llvm/MC/MCContext.h"
93#include "llvm/Support/AtomicOrdering.h"
94#include "llvm/Support/Casting.h"
95#include "llvm/Support/CommandLine.h"
96#include "llvm/Support/Compiler.h"
97#include "llvm/Support/Debug.h"
98#include "llvm/Support/InstructionCost.h"
99#include "llvm/Support/MathExtras.h"
100#include "llvm/Support/raw_ostream.h"
101#include "llvm/Target/TargetMachine.h"
102#include "llvm/Target/TargetOptions.h"
103#include "llvm/TargetParser/Triple.h"
104#include "llvm/Transforms/Utils/Local.h"
105#include <cstddef>
106#include <limits>
107#include <optional>
108#include <tuple>
109
110using namespace llvm;
111using namespace PatternMatch;
112using namespace SwitchCG;
113
114#define DEBUG_TYPE "isel"
115
116/// LimitFloatPrecision - Generate low-precision inline sequences for
117/// some float libcalls (6, 8 or 12 bits).
118static unsigned LimitFloatPrecision;
119
120static cl::opt<bool>
121 InsertAssertAlign("insert-assert-align", cl::init(Val: true),
122 cl::desc("Insert the experimental `assertalign` node."),
123 cl::ReallyHidden);
124
125static cl::opt<unsigned, true>
126 LimitFPPrecision("limit-float-precision",
127 cl::desc("Generate low-precision inline sequences "
128 "for some float libcalls"),
129 cl::location(L&: LimitFloatPrecision), cl::Hidden,
130 cl::init(Val: 0));
131
132static cl::opt<unsigned> SwitchPeelThreshold(
133 "switch-peel-threshold", cl::Hidden, cl::init(Val: 66),
134 cl::desc("Set the case probability threshold for peeling the case from a "
135 "switch statement. A value greater than 100 will void this "
136 "optimization"));
137
138// Limit the width of DAG chains. This is important in general to prevent
139// DAG-based analysis from blowing up. For example, alias analysis and
140// load clustering may not complete in reasonable time. It is difficult to
141// recognize and avoid this situation within each individual analysis, and
142// future analyses are likely to have the same behavior. Limiting DAG width is
143// the safe approach and will be especially important with global DAGs.
144//
145// MaxParallelChains default is arbitrarily high to avoid affecting
146// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
147// sequence over this should have been converted to llvm.memcpy by the
148// frontend. It is easy to induce this behavior with .ll code such as:
149// %buffer = alloca [4096 x i8]
150// %data = load [4096 x i8]* %argPtr
151// store [4096 x i8] %data, [4096 x i8]* %buffer
152static const unsigned MaxParallelChains = 64;
153
154static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
155 const SDValue *Parts, unsigned NumParts,
156 MVT PartVT, EVT ValueVT, const Value *V,
157 SDValue InChain,
158 std::optional<CallingConv::ID> CC);
159
160/// getCopyFromParts - Create a value that contains the specified legal parts
161/// combined into the value they represent. If the parts combine to a type
162/// larger than ValueVT then AssertOp can be used to specify whether the extra
163/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
164/// (ISD::AssertSext).
165static SDValue
166getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
167 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
168 SDValue InChain,
169 std::optional<CallingConv::ID> CC = std::nullopt,
170 std::optional<ISD::NodeType> AssertOp = std::nullopt) {
171 // Let the target assemble the parts if it wants to
172 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
173 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
174 PartVT, ValueVT, CC))
175 return Val;
176
177 if (ValueVT.isVector())
178 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
179 InChain, CC);
180
181 assert(NumParts > 0 && "No parts to assemble!");
182 SDValue Val = Parts[0];
183
184 if (NumParts > 1) {
185 // Assemble the value from multiple parts.
186 if (ValueVT.isInteger()) {
187 unsigned PartBits = PartVT.getSizeInBits();
188 unsigned ValueBits = ValueVT.getSizeInBits();
189
190 // Assemble the power of 2 part.
191 unsigned RoundParts = llvm::bit_floor(Value: NumParts);
192 unsigned RoundBits = PartBits * RoundParts;
193 EVT RoundVT = RoundBits == ValueBits ?
194 ValueVT : EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: RoundBits);
195 SDValue Lo, Hi;
196
197 EVT HalfVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: RoundBits/2);
198
199 if (RoundParts > 2) {
200 Lo = getCopyFromParts(DAG, DL, Parts, NumParts: RoundParts / 2, PartVT, ValueVT: HalfVT, V,
201 InChain);
202 Hi = getCopyFromParts(DAG, DL, Parts: Parts + RoundParts / 2, NumParts: RoundParts / 2,
203 PartVT, ValueVT: HalfVT, V, InChain);
204 } else {
205 Lo = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: HalfVT, Operand: Parts[0]);
206 Hi = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: HalfVT, Operand: Parts[1]);
207 }
208
209 if (DAG.getDataLayout().isBigEndian())
210 std::swap(a&: Lo, b&: Hi);
211
212 Val = DAG.getNode(Opcode: ISD::BUILD_PAIR, DL, VT: RoundVT, N1: Lo, N2: Hi);
213
214 if (RoundParts < NumParts) {
215 // Assemble the trailing non-power-of-2 part.
216 unsigned OddParts = NumParts - RoundParts;
217 EVT OddVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: OddParts * PartBits);
218 Hi = getCopyFromParts(DAG, DL, Parts: Parts + RoundParts, NumParts: OddParts, PartVT,
219 ValueVT: OddVT, V, InChain, CC);
220
221 // Combine the round and odd parts.
222 Lo = Val;
223 if (DAG.getDataLayout().isBigEndian())
224 std::swap(a&: Lo, b&: Hi);
225 EVT TotalVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: NumParts * PartBits);
226 Hi = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: TotalVT, Operand: Hi);
227 Hi = DAG.getNode(
228 Opcode: ISD::SHL, DL, VT: TotalVT, N1: Hi,
229 N2: DAG.getShiftAmountConstant(Val: Lo.getValueSizeInBits(), VT: TotalVT, DL));
230 Lo = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL, VT: TotalVT, Operand: Lo);
231 Val = DAG.getNode(Opcode: ISD::OR, DL, VT: TotalVT, N1: Lo, N2: Hi);
232 }
233 } else if (PartVT.isFloatingPoint()) {
234 // FP split into multiple FP parts (for ppcf128)
235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
236 "Unexpected split");
237 SDValue Lo, Hi;
238 Lo = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: EVT(MVT::f64), Operand: Parts[0]);
239 Hi = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: EVT(MVT::f64), Operand: Parts[1]);
240 if (TLI.hasBigEndianPartOrdering(VT: ValueVT, DL: DAG.getDataLayout()))
241 std::swap(a&: Lo, b&: Hi);
242 Val = DAG.getNode(Opcode: ISD::BUILD_PAIR, DL, VT: ValueVT, N1: Lo, N2: Hi);
243 } else {
244 // FP split into integer parts (soft fp)
245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
246 !PartVT.isVector() && "Unexpected split");
247 EVT IntVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueVT.getSizeInBits());
248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, ValueVT: IntVT, V,
249 InChain, CC);
250 }
251 }
252
253 // There is now one part, held in Val. Correct it to match ValueVT.
254 // PartEVT is the type of the register class that holds the value.
255 // ValueVT is the type of the inline asm operation.
256 EVT PartEVT = Val.getValueType();
257
258 if (PartEVT == ValueVT)
259 return Val;
260
261 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
262 ValueVT.bitsLT(VT: PartEVT)) {
263 // For an FP value in an integer part, we need to truncate to the right
264 // width first.
265 PartEVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueVT.getSizeInBits());
266 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: PartEVT, Operand: Val);
267 }
268
269 // Handle types that have the same size.
270 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
271 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
272
273 // Handle types with different sizes.
274 if (PartEVT.isInteger() && ValueVT.isInteger()) {
275 if (ValueVT.bitsLT(VT: PartEVT)) {
276 // For a truncate, see if we have any information to
277 // indicate whether the truncated bits will always be
278 // zero or sign-extension.
279 if (AssertOp)
280 Val = DAG.getNode(Opcode: *AssertOp, DL, VT: PartEVT, N1: Val,
281 N2: DAG.getValueType(ValueVT));
282 return DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: ValueVT, Operand: Val);
283 }
284 return DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: ValueVT, Operand: Val);
285 }
286
287 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
288 // FP_ROUND's are always exact here.
289 if (ValueVT.bitsLT(VT: Val.getValueType())) {
290
291 SDValue NoChange =
292 DAG.getTargetConstant(Val: 1, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
293
294 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
295 Kind: llvm::Attribute::StrictFP)) {
296 return DAG.getNode(Opcode: ISD::STRICT_FP_ROUND, DL,
297 VTList: DAG.getVTList(VT1: ValueVT, VT2: MVT::Other), N1: InChain, N2: Val,
298 N3: NoChange);
299 }
300
301 return DAG.getNode(Opcode: ISD::FP_ROUND, DL, VT: ValueVT, N1: Val, N2: NoChange);
302 }
303
304 return DAG.getNode(Opcode: ISD::FP_EXTEND, DL, VT: ValueVT, Operand: Val);
305 }
306
307 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
308 // then truncating.
309 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
310 ValueVT.bitsLT(VT: PartEVT)) {
311 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::i64, Operand: Val);
312 return DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: ValueVT, Operand: Val);
313 }
314
315 report_fatal_error(reason: "Unknown mismatch in getCopyFromParts!");
316}
317
318static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
319 const Twine &ErrMsg) {
320 const Instruction *I = dyn_cast_or_null<Instruction>(Val: V);
321 if (!I)
322 return Ctx.emitError(ErrorStr: ErrMsg);
323
324 if (const CallInst *CI = dyn_cast<CallInst>(Val: I))
325 if (CI->isInlineAsm()) {
326 return Ctx.diagnose(DI: DiagnosticInfoInlineAsm(
327 *CI, ErrMsg + ", possible invalid constraint for vector type"));
328 }
329
330 return Ctx.emitError(I, ErrorStr: ErrMsg);
331}
332
333/// getCopyFromPartsVector - Create a value that contains the specified legal
334/// parts combined into the value they represent. If the parts combine to a
335/// type larger than ValueVT then AssertOp can be used to specify whether the
336/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
337/// ValueVT (ISD::AssertSext).
338static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
339 const SDValue *Parts, unsigned NumParts,
340 MVT PartVT, EVT ValueVT, const Value *V,
341 SDValue InChain,
342 std::optional<CallingConv::ID> CallConv) {
343 assert(ValueVT.isVector() && "Not a vector value");
344 assert(NumParts > 0 && "No parts to assemble!");
345 const bool IsABIRegCopy = CallConv.has_value();
346
347 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
348 SDValue Val = Parts[0];
349
350 // Handle a multi-element vector.
351 if (NumParts > 1) {
352 EVT IntermediateVT;
353 MVT RegisterVT;
354 unsigned NumIntermediates;
355 unsigned NumRegs;
356
357 if (IsABIRegCopy) {
358 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
359 Context&: *DAG.getContext(), CC: *CallConv, VT: ValueVT, IntermediateVT,
360 NumIntermediates, RegisterVT);
361 } else {
362 NumRegs =
363 TLI.getVectorTypeBreakdown(Context&: *DAG.getContext(), VT: ValueVT, IntermediateVT,
364 NumIntermediates, RegisterVT);
365 }
366
367 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
368 NumParts = NumRegs; // Silence a compiler warning.
369 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
370 assert(RegisterVT.getSizeInBits() ==
371 Parts[0].getSimpleValueType().getSizeInBits() &&
372 "Part type sizes don't match!");
373
374 // Assemble the parts into intermediate operands.
375 SmallVector<SDValue, 8> Ops(NumIntermediates);
376 if (NumIntermediates == NumParts) {
377 // If the register was not expanded, truncate or copy the value,
378 // as appropriate.
379 for (unsigned i = 0; i != NumParts; ++i)
380 Ops[i] = getCopyFromParts(DAG, DL, Parts: &Parts[i], NumParts: 1, PartVT, ValueVT: IntermediateVT,
381 V, InChain, CC: CallConv);
382 } else if (NumParts > 0) {
383 // If the intermediate type was expanded, build the intermediate
384 // operands from the parts.
385 assert(NumParts % NumIntermediates == 0 &&
386 "Must expand into a divisible number of parts!");
387 unsigned Factor = NumParts / NumIntermediates;
388 for (unsigned i = 0; i != NumIntermediates; ++i)
389 Ops[i] = getCopyFromParts(DAG, DL, Parts: &Parts[i * Factor], NumParts: Factor, PartVT,
390 ValueVT: IntermediateVT, V, InChain, CC: CallConv);
391 }
392
393 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
394 // intermediate operands.
395 EVT BuiltVectorTy =
396 IntermediateVT.isVector()
397 ? EVT::getVectorVT(
398 Context&: *DAG.getContext(), VT: IntermediateVT.getScalarType(),
399 EC: IntermediateVT.getVectorElementCount() * NumParts)
400 : EVT::getVectorVT(Context&: *DAG.getContext(),
401 VT: IntermediateVT.getScalarType(),
402 NumElements: NumIntermediates);
403 Val = DAG.getNode(Opcode: IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
404 : ISD::BUILD_VECTOR,
405 DL, VT: BuiltVectorTy, Ops);
406 }
407
408 // There is now one part, held in Val. Correct it to match ValueVT.
409 EVT PartEVT = Val.getValueType();
410
411 if (PartEVT == ValueVT)
412 return Val;
413
414 if (PartEVT.isVector()) {
415 // Vector/Vector bitcast.
416 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
417 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
418
419 // If the parts vector has more elements than the value vector, then we
420 // have a vector widening case (e.g. <2 x float> -> <4 x float>).
421 // Extract the elements we want.
422 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
423 assert((PartEVT.getVectorElementCount().getKnownMinValue() >
424 ValueVT.getVectorElementCount().getKnownMinValue()) &&
425 (PartEVT.getVectorElementCount().isScalable() ==
426 ValueVT.getVectorElementCount().isScalable()) &&
427 "Cannot narrow, it would be a lossy transformation");
428 PartEVT =
429 EVT::getVectorVT(Context&: *DAG.getContext(), VT: PartEVT.getVectorElementType(),
430 EC: ValueVT.getVectorElementCount());
431 Val = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: PartEVT, N1: Val,
432 N2: DAG.getVectorIdxConstant(Val: 0, DL));
433 if (PartEVT == ValueVT)
434 return Val;
435 if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
436 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
437
438 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
439 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
440 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
441 }
442
443 // Promoted vector extract
444 return DAG.getAnyExtOrTrunc(Op: Val, DL, VT: ValueVT);
445 }
446
447 // Trivial bitcast if the types are the same size and the destination
448 // vector type is legal.
449 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
450 TLI.isTypeLegal(VT: ValueVT))
451 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
452
453 if (ValueVT.getVectorNumElements() != 1) {
454 // Certain ABIs require that vectors are passed as integers. For vectors
455 // are the same size, this is an obvious bitcast.
456 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
457 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
458 } else if (ValueVT.bitsLT(VT: PartEVT)) {
459 const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
460 EVT IntermediateType = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueSize);
461 // Drop the extra bits.
462 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: IntermediateType, Operand: Val);
463 return DAG.getBitcast(VT: ValueVT, V: Val);
464 }
465
466 diagnosePossiblyInvalidConstraint(
467 Ctx&: *DAG.getContext(), V, ErrMsg: "non-trivial scalar-to-vector conversion");
468 return DAG.getUNDEF(VT: ValueVT);
469 }
470
471 // Handle cases such as i8 -> <1 x i1>
472 EVT ValueSVT = ValueVT.getVectorElementType();
473 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
474 unsigned ValueSize = ValueSVT.getSizeInBits();
475 if (ValueSize == PartEVT.getSizeInBits()) {
476 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueSVT, Operand: Val);
477 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
478 // It's possible a scalar floating point type gets softened to integer and
479 // then promoted to a larger integer. If PartEVT is the larger integer
480 // we need to truncate it and then bitcast to the FP type.
481 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
482 EVT IntermediateType = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueSize);
483 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: IntermediateType, Operand: Val);
484 Val = DAG.getBitcast(VT: ValueSVT, V: Val);
485 } else {
486 Val = ValueVT.isFloatingPoint()
487 ? DAG.getFPExtendOrRound(Op: Val, DL, VT: ValueSVT)
488 : DAG.getAnyExtOrTrunc(Op: Val, DL, VT: ValueSVT);
489 }
490 }
491
492 return DAG.getBuildVector(VT: ValueVT, DL, Ops: Val);
493}
494
495static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
496 SDValue Val, SDValue *Parts, unsigned NumParts,
497 MVT PartVT, const Value *V,
498 std::optional<CallingConv::ID> CallConv);
499
500/// getCopyToParts - Create a series of nodes that contain the specified value
501/// split into legal parts. If the parts contain more bits than Val, then, for
502/// integers, ExtendKind can be used to specify how to generate the extra bits.
503static void
504getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
505 unsigned NumParts, MVT PartVT, const Value *V,
506 std::optional<CallingConv::ID> CallConv = std::nullopt,
507 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
508 // Let the target split the parts if it wants to
509 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
510 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
511 CC: CallConv))
512 return;
513 EVT ValueVT = Val.getValueType();
514
515 // Handle the vector case separately.
516 if (ValueVT.isVector())
517 return getCopyToPartsVector(DAG, dl: DL, Val, Parts, NumParts, PartVT, V,
518 CallConv);
519
520 unsigned OrigNumParts = NumParts;
521 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
522 "Copying to an illegal type!");
523
524 if (NumParts == 0)
525 return;
526
527 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
528 EVT PartEVT = PartVT;
529 if (PartEVT == ValueVT) {
530 assert(NumParts == 1 && "No-op copy with multiple parts!");
531 Parts[0] = Val;
532 return;
533 }
534
535 unsigned PartBits = PartVT.getSizeInBits();
536 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
537 // If the parts cover more bits than the value has, promote the value.
538 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
539 assert(NumParts == 1 && "Do not know what to promote to!");
540 Val = DAG.getNode(Opcode: ISD::FP_EXTEND, DL, VT: PartVT, Operand: Val);
541 } else {
542 if (ValueVT.isFloatingPoint()) {
543 // FP values need to be bitcast, then extended if they are being put
544 // into a larger container.
545 ValueVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueVT.getSizeInBits());
546 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
547 }
548 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
549 ValueVT.isInteger() &&
550 "Unknown mismatch!");
551 ValueVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: NumParts * PartBits);
552 Val = DAG.getNode(Opcode: ExtendKind, DL, VT: ValueVT, Operand: Val);
553 if (PartVT == MVT::x86mmx)
554 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
555 }
556 } else if (PartBits == ValueVT.getSizeInBits()) {
557 // Different types of the same size.
558 assert(NumParts == 1 && PartEVT != ValueVT);
559 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
560 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
561 // If the parts cover less bits than value has, truncate the value.
562 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
563 ValueVT.isInteger() &&
564 "Unknown mismatch!");
565 ValueVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: NumParts * PartBits);
566 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: ValueVT, Operand: Val);
567 if (PartVT == MVT::x86mmx)
568 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
569 }
570
571 // The value may have changed - recompute ValueVT.
572 ValueVT = Val.getValueType();
573 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
574 "Failed to tile the value with PartVT!");
575
576 if (NumParts == 1) {
577 if (PartEVT != ValueVT) {
578 diagnosePossiblyInvalidConstraint(Ctx&: *DAG.getContext(), V,
579 ErrMsg: "scalar-to-vector conversion failed");
580 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
581 }
582
583 Parts[0] = Val;
584 return;
585 }
586
587 // Expand the value into multiple parts.
588 if (NumParts & (NumParts - 1)) {
589 // The number of parts is not a power of 2. Split off and copy the tail.
590 assert(PartVT.isInteger() && ValueVT.isInteger() &&
591 "Do not know what to expand to!");
592 unsigned RoundParts = llvm::bit_floor(Value: NumParts);
593 unsigned RoundBits = RoundParts * PartBits;
594 unsigned OddParts = NumParts - RoundParts;
595 SDValue OddVal = DAG.getNode(Opcode: ISD::SRL, DL, VT: ValueVT, N1: Val,
596 N2: DAG.getShiftAmountConstant(Val: RoundBits, VT: ValueVT, DL));
597
598 getCopyToParts(DAG, DL, Val: OddVal, Parts: Parts + RoundParts, NumParts: OddParts, PartVT, V,
599 CallConv);
600
601 if (DAG.getDataLayout().isBigEndian())
602 // The odd parts were reversed by getCopyToParts - unreverse them.
603 std::reverse(first: Parts + RoundParts, last: Parts + NumParts);
604
605 NumParts = RoundParts;
606 ValueVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: NumParts * PartBits);
607 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: ValueVT, Operand: Val);
608 }
609
610 // The number of parts is a power of 2. Repeatedly bisect the value using
611 // EXTRACT_ELEMENT.
612 Parts[0] = DAG.getNode(Opcode: ISD::BITCAST, DL,
613 VT: EVT::getIntegerVT(Context&: *DAG.getContext(),
614 BitWidth: ValueVT.getSizeInBits()),
615 Operand: Val);
616
617 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
618 for (unsigned i = 0; i < NumParts; i += StepSize) {
619 unsigned ThisBits = StepSize * PartBits / 2;
620 EVT ThisVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ThisBits);
621 SDValue &Part0 = Parts[i];
622 SDValue &Part1 = Parts[i+StepSize/2];
623
624 Part1 = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL,
625 VT: ThisVT, N1: Part0, N2: DAG.getIntPtrConstant(Val: 1, DL));
626 Part0 = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL,
627 VT: ThisVT, N1: Part0, N2: DAG.getIntPtrConstant(Val: 0, DL));
628
629 if (ThisBits == PartBits && ThisVT != PartVT) {
630 Part0 = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Part0);
631 Part1 = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Part1);
632 }
633 }
634 }
635
636 if (DAG.getDataLayout().isBigEndian())
637 std::reverse(first: Parts, last: Parts + OrigNumParts);
638}
639
640static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
641 const SDLoc &DL, EVT PartVT) {
642 if (!PartVT.isVector())
643 return SDValue();
644
645 EVT ValueVT = Val.getValueType();
646 EVT PartEVT = PartVT.getVectorElementType();
647 EVT ValueEVT = ValueVT.getVectorElementType();
648 ElementCount PartNumElts = PartVT.getVectorElementCount();
649 ElementCount ValueNumElts = ValueVT.getVectorElementCount();
650
651 // We only support widening vectors with equivalent element types and
652 // fixed/scalable properties. If a target needs to widen a fixed-length type
653 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
654 if (ElementCount::isKnownLE(LHS: PartNumElts, RHS: ValueNumElts) ||
655 PartNumElts.isScalable() != ValueNumElts.isScalable())
656 return SDValue();
657
658 // Have a try for bf16 because some targets share its ABI with fp16.
659 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
660 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
661 "Cannot widen to illegal type");
662 Val = DAG.getNode(
663 Opcode: ISD::BITCAST, DL,
664 VT: ValueVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: MVT::f16), Operand: Val);
665 } else if (PartEVT != ValueEVT) {
666 return SDValue();
667 }
668
669 // Widening a scalable vector to another scalable vector is done by inserting
670 // the vector into a larger undef one.
671 if (PartNumElts.isScalable())
672 return DAG.getNode(Opcode: ISD::INSERT_SUBVECTOR, DL, VT: PartVT, N1: DAG.getUNDEF(VT: PartVT),
673 N2: Val, N3: DAG.getVectorIdxConstant(Val: 0, DL));
674
675 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
676 // undef elements.
677 SmallVector<SDValue, 16> Ops;
678 DAG.ExtractVectorElements(Op: Val, Args&: Ops);
679 SDValue EltUndef = DAG.getUNDEF(VT: PartEVT);
680 Ops.append(NumInputs: (PartNumElts - ValueNumElts).getFixedValue(), Elt: EltUndef);
681
682 // FIXME: Use CONCAT for 2x -> 4x.
683 return DAG.getBuildVector(VT: PartVT, DL, Ops);
684}
685
686/// getCopyToPartsVector - Create a series of nodes that contain the specified
687/// value split into legal parts.
688static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
689 SDValue Val, SDValue *Parts, unsigned NumParts,
690 MVT PartVT, const Value *V,
691 std::optional<CallingConv::ID> CallConv) {
692 EVT ValueVT = Val.getValueType();
693 assert(ValueVT.isVector() && "Not a vector");
694 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
695 const bool IsABIRegCopy = CallConv.has_value();
696
697 if (NumParts == 1) {
698 EVT PartEVT = PartVT;
699 if (PartEVT == ValueVT) {
700 // Nothing to do.
701 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
702 // Bitconvert vector->vector case.
703 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
704 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
705 Val = Widened;
706 } else if (PartVT.isVector() &&
707 PartEVT.getVectorElementType().bitsGE(
708 VT: ValueVT.getVectorElementType()) &&
709 PartEVT.getVectorElementCount() ==
710 ValueVT.getVectorElementCount()) {
711
712 // Promoted vector extract
713 Val = DAG.getAnyExtOrTrunc(Op: Val, DL, VT: PartVT);
714 } else if (PartEVT.isVector() &&
715 PartEVT.getVectorElementType() !=
716 ValueVT.getVectorElementType() &&
717 TLI.getTypeAction(Context&: *DAG.getContext(), VT: ValueVT) ==
718 TargetLowering::TypeWidenVector) {
719 // Combination of widening and promotion.
720 EVT WidenVT =
721 EVT::getVectorVT(Context&: *DAG.getContext(), VT: ValueVT.getVectorElementType(),
722 EC: PartVT.getVectorElementCount());
723 SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT: WidenVT);
724 Val = DAG.getAnyExtOrTrunc(Op: Widened, DL, VT: PartVT);
725 } else {
726 // Don't extract an integer from a float vector. This can happen if the
727 // FP type gets softened to integer and then promoted. The promotion
728 // prevents it from being picked up by the earlier bitcast case.
729 if (ValueVT.getVectorElementCount().isScalar() &&
730 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
731 // If we reach this condition and PartVT is FP, this means that
732 // ValueVT is also FP and both have a different size, otherwise we
733 // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
734 // would be invalid since that would mean the smaller FP type has to
735 // be extended to the larger one.
736 if (PartVT.isFloatingPoint()) {
737 Val = DAG.getBitcast(VT: ValueVT.getScalarType(), V: Val);
738 Val = DAG.getNode(Opcode: ISD::FP_EXTEND, DL, VT: PartVT, Operand: Val);
739 } else
740 Val = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: PartVT, N1: Val,
741 N2: DAG.getVectorIdxConstant(Val: 0, DL));
742 } else {
743 uint64_t ValueSize = ValueVT.getFixedSizeInBits();
744 assert(PartVT.getFixedSizeInBits() > ValueSize &&
745 "lossy conversion of vector to scalar type");
746 EVT IntermediateType = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: ValueSize);
747 Val = DAG.getBitcast(VT: IntermediateType, V: Val);
748 Val = DAG.getAnyExtOrTrunc(Op: Val, DL, VT: PartVT);
749 }
750 }
751
752 assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
753 Parts[0] = Val;
754 return;
755 }
756
757 // Handle a multi-element vector.
758 EVT IntermediateVT;
759 MVT RegisterVT;
760 unsigned NumIntermediates;
761 unsigned NumRegs;
762 if (IsABIRegCopy) {
763 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
764 Context&: *DAG.getContext(), CC: *CallConv, VT: ValueVT, IntermediateVT, NumIntermediates,
765 RegisterVT);
766 } else {
767 NumRegs =
768 TLI.getVectorTypeBreakdown(Context&: *DAG.getContext(), VT: ValueVT, IntermediateVT,
769 NumIntermediates, RegisterVT);
770 }
771
772 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
773 NumParts = NumRegs; // Silence a compiler warning.
774 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
775
776 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
777 "Mixing scalable and fixed vectors when copying in parts");
778
779 std::optional<ElementCount> DestEltCnt;
780
781 if (IntermediateVT.isVector())
782 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
783 else
784 DestEltCnt = ElementCount::getFixed(MinVal: NumIntermediates);
785
786 EVT BuiltVectorTy = EVT::getVectorVT(
787 Context&: *DAG.getContext(), VT: IntermediateVT.getScalarType(), EC: *DestEltCnt);
788
789 if (ValueVT == BuiltVectorTy) {
790 // Nothing to do.
791 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
792 // Bitconvert vector->vector case.
793 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: BuiltVectorTy, Operand: Val);
794 } else {
795 if (BuiltVectorTy.getVectorElementType().bitsGT(
796 VT: ValueVT.getVectorElementType())) {
797 // Integer promotion.
798 ValueVT = EVT::getVectorVT(Context&: *DAG.getContext(),
799 VT: BuiltVectorTy.getVectorElementType(),
800 EC: ValueVT.getVectorElementCount());
801 Val = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: ValueVT, Operand: Val);
802 }
803
804 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT: BuiltVectorTy)) {
805 Val = Widened;
806 }
807 }
808
809 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
810
811 // Split the vector into intermediate operands.
812 SmallVector<SDValue, 8> Ops(NumIntermediates);
813 for (unsigned i = 0; i != NumIntermediates; ++i) {
814 if (IntermediateVT.isVector()) {
815 // This does something sensible for scalable vectors - see the
816 // definition of EXTRACT_SUBVECTOR for further details.
817 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
818 Ops[i] =
819 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: IntermediateVT, N1: Val,
820 N2: DAG.getVectorIdxConstant(Val: i * IntermediateNumElts, DL));
821 } else {
822 Ops[i] = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: IntermediateVT, N1: Val,
823 N2: DAG.getVectorIdxConstant(Val: i, DL));
824 }
825 }
826
827 // Split the intermediate operands into legal parts.
828 if (NumParts == NumIntermediates) {
829 // If the register was not expanded, promote or copy the value,
830 // as appropriate.
831 for (unsigned i = 0; i != NumParts; ++i)
832 getCopyToParts(DAG, DL, Val: Ops[i], Parts: &Parts[i], NumParts: 1, PartVT, V, CallConv);
833 } else if (NumParts > 0) {
834 // If the intermediate type was expanded, split each the value into
835 // legal parts.
836 assert(NumIntermediates != 0 && "division by zero");
837 assert(NumParts % NumIntermediates == 0 &&
838 "Must expand into a divisible number of parts!");
839 unsigned Factor = NumParts / NumIntermediates;
840 for (unsigned i = 0; i != NumIntermediates; ++i)
841 getCopyToParts(DAG, DL, Val: Ops[i], Parts: &Parts[i * Factor], NumParts: Factor, PartVT, V,
842 CallConv);
843 }
844}
845
846static void failForInvalidBundles(const CallBase &I, StringRef Name,
847 ArrayRef<uint32_t> AllowedBundles) {
848 if (I.hasOperandBundlesOtherThan(IDs: AllowedBundles)) {
849 ListSeparator LS;
850 std::string Error;
851 raw_string_ostream OS(Error);
852 for (unsigned i = 0, e = I.getNumOperandBundles(); i != e; ++i) {
853 OperandBundleUse U = I.getOperandBundleAt(Index: i);
854 if (!is_contained(Range&: AllowedBundles, Element: U.getTagID()))
855 OS << LS << U.getTagName();
856 }
857 reportFatalUsageError(
858 reason: Twine("cannot lower ", Name)
859 .concat(Suffix: Twine(" with arbitrary operand bundles: ", Error)));
860 }
861}
862
863RegsForValue::RegsForValue(const SmallVector<Register, 4> &regs, MVT regvt,
864 EVT valuevt, std::optional<CallingConv::ID> CC)
865 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
866 RegCount(1, regs.size()), CallConv(CC) {}
867
868RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
869 const DataLayout &DL, Register Reg, Type *Ty,
870 std::optional<CallingConv::ID> CC) {
871 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
872
873 CallConv = CC;
874
875 for (EVT ValueVT : ValueVTs) {
876 unsigned NumRegs =
877 isABIMangled()
878 ? TLI.getNumRegistersForCallingConv(Context, CC: *CC, VT: ValueVT)
879 : TLI.getNumRegisters(Context, VT: ValueVT);
880 MVT RegisterVT =
881 isABIMangled()
882 ? TLI.getRegisterTypeForCallingConv(Context, CC: *CC, VT: ValueVT)
883 : TLI.getRegisterType(Context, VT: ValueVT);
884 for (unsigned i = 0; i != NumRegs; ++i)
885 Regs.push_back(Elt: Reg + i);
886 RegVTs.push_back(Elt: RegisterVT);
887 RegCount.push_back(Elt: NumRegs);
888 Reg = Reg.id() + NumRegs;
889 }
890}
891
892SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
893 FunctionLoweringInfo &FuncInfo,
894 const SDLoc &dl, SDValue &Chain,
895 SDValue *Glue, const Value *V) const {
896 // A Value with type {} or [0 x %t] needs no registers.
897 if (ValueVTs.empty())
898 return SDValue();
899
900 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
901
902 // Assemble the legal parts into the final values.
903 SmallVector<SDValue, 4> Values(ValueVTs.size());
904 SmallVector<SDValue, 8> Parts;
905 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
906 // Copy the legal parts from the registers.
907 EVT ValueVT = ValueVTs[Value];
908 unsigned NumRegs = RegCount[Value];
909 MVT RegisterVT = isABIMangled()
910 ? TLI.getRegisterTypeForCallingConv(
911 Context&: *DAG.getContext(), CC: *CallConv, VT: RegVTs[Value])
912 : RegVTs[Value];
913
914 Parts.resize(N: NumRegs);
915 for (unsigned i = 0; i != NumRegs; ++i) {
916 SDValue P;
917 if (!Glue) {
918 P = DAG.getCopyFromReg(Chain, dl, Reg: Regs[Part+i], VT: RegisterVT);
919 } else {
920 P = DAG.getCopyFromReg(Chain, dl, Reg: Regs[Part+i], VT: RegisterVT, Glue: *Glue);
921 *Glue = P.getValue(R: 2);
922 }
923
924 Chain = P.getValue(R: 1);
925 Parts[i] = P;
926
927 // If the source register was virtual and if we know something about it,
928 // add an assert node.
929 if (!Regs[Part + i].isVirtual() || !RegisterVT.isInteger())
930 continue;
931
932 const FunctionLoweringInfo::LiveOutInfo *LOI =
933 FuncInfo.GetLiveOutRegInfo(Reg: Regs[Part+i]);
934 if (!LOI)
935 continue;
936
937 unsigned RegSize = RegisterVT.getScalarSizeInBits();
938 unsigned NumSignBits = LOI->NumSignBits;
939 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
940
941 if (NumZeroBits == RegSize) {
942 // The current value is a zero.
943 // Explicitly express that as it would be easier for
944 // optimizations to kick in.
945 Parts[i] = DAG.getConstant(Val: 0, DL: dl, VT: RegisterVT);
946 continue;
947 }
948
949 // FIXME: We capture more information than the dag can represent. For
950 // now, just use the tightest assertzext/assertsext possible.
951 bool isSExt;
952 EVT FromVT(MVT::Other);
953 if (NumZeroBits) {
954 FromVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: RegSize - NumZeroBits);
955 isSExt = false;
956 } else if (NumSignBits > 1) {
957 FromVT =
958 EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: RegSize - NumSignBits + 1);
959 isSExt = true;
960 } else {
961 continue;
962 }
963 // Add an assertion node.
964 assert(FromVT != MVT::Other);
965 Parts[i] = DAG.getNode(Opcode: isSExt ? ISD::AssertSext : ISD::AssertZext, DL: dl,
966 VT: RegisterVT, N1: P, N2: DAG.getValueType(FromVT));
967 }
968
969 Values[Value] = getCopyFromParts(DAG, DL: dl, Parts: Parts.begin(), NumParts: NumRegs,
970 PartVT: RegisterVT, ValueVT, V, InChain: Chain, CC: CallConv);
971 Part += NumRegs;
972 Parts.clear();
973 }
974
975 return DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl, VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values);
976}
977
978void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
979 const SDLoc &dl, SDValue &Chain, SDValue *Glue,
980 const Value *V,
981 ISD::NodeType PreferredExtendType) const {
982 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
983 ISD::NodeType ExtendKind = PreferredExtendType;
984
985 // Get the list of the values's legal parts.
986 unsigned NumRegs = Regs.size();
987 SmallVector<SDValue, 8> Parts(NumRegs);
988 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
989 unsigned NumParts = RegCount[Value];
990
991 MVT RegisterVT = isABIMangled()
992 ? TLI.getRegisterTypeForCallingConv(
993 Context&: *DAG.getContext(), CC: *CallConv, VT: RegVTs[Value])
994 : RegVTs[Value];
995
996 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, VT2: RegisterVT))
997 ExtendKind = ISD::ZERO_EXTEND;
998
999 getCopyToParts(DAG, DL: dl, Val: Val.getValue(R: Val.getResNo() + Value), Parts: &Parts[Part],
1000 NumParts, PartVT: RegisterVT, V, CallConv, ExtendKind);
1001 Part += NumParts;
1002 }
1003
1004 // Copy the parts into the registers.
1005 SmallVector<SDValue, 8> Chains(NumRegs);
1006 for (unsigned i = 0; i != NumRegs; ++i) {
1007 SDValue Part;
1008 if (!Glue) {
1009 Part = DAG.getCopyToReg(Chain, dl, Reg: Regs[i], N: Parts[i]);
1010 } else {
1011 Part = DAG.getCopyToReg(Chain, dl, Reg: Regs[i], N: Parts[i], Glue: *Glue);
1012 *Glue = Part.getValue(R: 1);
1013 }
1014
1015 Chains[i] = Part.getValue(R: 0);
1016 }
1017
1018 if (NumRegs == 1 || Glue)
1019 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1020 // flagged to it. That is the CopyToReg nodes and the user are considered
1021 // a single scheduling unit. If we create a TokenFactor and return it as
1022 // chain, then the TokenFactor is both a predecessor (operand) of the
1023 // user as well as a successor (the TF operands are flagged to the user).
1024 // c1, f1 = CopyToReg
1025 // c2, f2 = CopyToReg
1026 // c3 = TokenFactor c1, c2
1027 // ...
1028 // = op c3, ..., f2
1029 Chain = Chains[NumRegs-1];
1030 else
1031 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: Chains);
1032}
1033
1034void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1035 unsigned MatchingIdx, const SDLoc &dl,
1036 SelectionDAG &DAG,
1037 std::vector<SDValue> &Ops) const {
1038 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1039
1040 InlineAsm::Flag Flag(Code, Regs.size());
1041 if (HasMatching)
1042 Flag.setMatchingOp(MatchingIdx);
1043 else if (!Regs.empty() && Regs.front().isVirtual()) {
1044 // Put the register class of the virtual registers in the flag word. That
1045 // way, later passes can recompute register class constraints for inline
1046 // assembly as well as normal instructions.
1047 // Don't do this for tied operands that can use the regclass information
1048 // from the def.
1049 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1050 const TargetRegisterClass *RC = MRI.getRegClass(Reg: Regs.front());
1051 Flag.setRegClass(RC->getID());
1052 }
1053
1054 SDValue Res = DAG.getTargetConstant(Val: Flag, DL: dl, VT: MVT::i32);
1055 Ops.push_back(x: Res);
1056
1057 if (Code == InlineAsm::Kind::Clobber) {
1058 // Clobbers should always have a 1:1 mapping with registers, and may
1059 // reference registers that have illegal (e.g. vector) types. Hence, we
1060 // shouldn't try to apply any sort of splitting logic to them.
1061 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1062 "No 1:1 mapping from clobbers to regs?");
1063 Register SP = TLI.getStackPointerRegisterToSaveRestore();
1064 (void)SP;
1065 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1066 Ops.push_back(x: DAG.getRegister(Reg: Regs[I], VT: RegVTs[I]));
1067 assert(
1068 (Regs[I] != SP ||
1069 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1070 "If we clobbered the stack pointer, MFI should know about it.");
1071 }
1072 return;
1073 }
1074
1075 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1076 MVT RegisterVT = RegVTs[Value];
1077 unsigned NumRegs = TLI.getNumRegisters(Context&: *DAG.getContext(), VT: ValueVTs[Value],
1078 RegisterVT);
1079 for (unsigned i = 0; i != NumRegs; ++i) {
1080 assert(Reg < Regs.size() && "Mismatch in # registers expected");
1081 Register TheReg = Regs[Reg++];
1082 Ops.push_back(x: DAG.getRegister(Reg: TheReg, VT: RegisterVT));
1083 }
1084 }
1085}
1086
1087SmallVector<std::pair<Register, TypeSize>, 4>
1088RegsForValue::getRegsAndSizes() const {
1089 SmallVector<std::pair<Register, TypeSize>, 4> OutVec;
1090 unsigned I = 0;
1091 for (auto CountAndVT : zip_first(t: RegCount, u: RegVTs)) {
1092 unsigned RegCount = std::get<0>(t&: CountAndVT);
1093 MVT RegisterVT = std::get<1>(t&: CountAndVT);
1094 TypeSize RegisterSize = RegisterVT.getSizeInBits();
1095 for (unsigned E = I + RegCount; I != E; ++I)
1096 OutVec.push_back(Elt: std::make_pair(x: Regs[I], y&: RegisterSize));
1097 }
1098 return OutVec;
1099}
1100
1101void SelectionDAGBuilder::init(GCFunctionInfo *gfi, BatchAAResults *aa,
1102 AssumptionCache *ac, const TargetLibraryInfo *li,
1103 const TargetTransformInfo &TTI) {
1104 BatchAA = aa;
1105 AC = ac;
1106 GFI = gfi;
1107 LibInfo = li;
1108 Context = DAG.getContext();
1109 LPadToCallSiteMap.clear();
1110 this->TTI = &TTI;
1111 SL->init(tli: DAG.getTargetLoweringInfo(), tm: TM, dl: DAG.getDataLayout());
1112 AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1113 M: *DAG.getMachineFunction().getFunction().getParent());
1114}
1115
1116void SelectionDAGBuilder::clear() {
1117 NodeMap.clear();
1118 UnusedArgNodeMap.clear();
1119 PendingLoads.clear();
1120 PendingExports.clear();
1121 PendingConstrainedFP.clear();
1122 PendingConstrainedFPStrict.clear();
1123 CurInst = nullptr;
1124 HasTailCall = false;
1125 SDNodeOrder = LowestSDNodeOrder;
1126 StatepointLowering.clear();
1127}
1128
1129void SelectionDAGBuilder::clearDanglingDebugInfo() {
1130 DanglingDebugInfoMap.clear();
1131}
1132
1133// Update DAG root to include dependencies on Pending chains.
1134SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1135 SDValue Root = DAG.getRoot();
1136
1137 if (Pending.empty())
1138 return Root;
1139
1140 // Add current root to PendingChains, unless we already indirectly
1141 // depend on it.
1142 if (Root.getOpcode() != ISD::EntryToken) {
1143 unsigned i = 0, e = Pending.size();
1144 for (; i != e; ++i) {
1145 assert(Pending[i].getNode()->getNumOperands() > 1);
1146 if (Pending[i].getNode()->getOperand(Num: 0) == Root)
1147 break; // Don't add the root if we already indirectly depend on it.
1148 }
1149
1150 if (i == e)
1151 Pending.push_back(Elt: Root);
1152 }
1153
1154 if (Pending.size() == 1)
1155 Root = Pending[0];
1156 else
1157 Root = DAG.getTokenFactor(DL: getCurSDLoc(), Vals&: Pending);
1158
1159 DAG.setRoot(Root);
1160 Pending.clear();
1161 return Root;
1162}
1163
1164SDValue SelectionDAGBuilder::getMemoryRoot() {
1165 return updateRoot(Pending&: PendingLoads);
1166}
1167
1168SDValue SelectionDAGBuilder::getFPOperationRoot(fp::ExceptionBehavior EB) {
1169 // If the new exception behavior differs from that of the pending
1170 // ones, chain up them and update the root.
1171 switch (EB) {
1172 case fp::ExceptionBehavior::ebMayTrap:
1173 case fp::ExceptionBehavior::ebIgnore:
1174 // Floating-point exceptions produced by such operations are not intended
1175 // to be observed, so the sequence of these operations does not need to be
1176 // preserved.
1177 //
1178 // They however must not be mixed with the instructions that have strict
1179 // exception behavior. Placing an operation with 'ebIgnore' behavior between
1180 // 'ebStrict' operations could distort the observed exception behavior.
1181 if (!PendingConstrainedFPStrict.empty()) {
1182 assert(PendingConstrainedFP.empty());
1183 updateRoot(Pending&: PendingConstrainedFPStrict);
1184 }
1185 break;
1186 case fp::ExceptionBehavior::ebStrict:
1187 // Floating-point exception produced by these operations may be observed, so
1188 // they must be correctly chained. If trapping on FP exceptions is
1189 // disabled, the exceptions can be observed only by functions that read
1190 // exception flags, like 'llvm.get_fpenv' or 'fetestexcept'. It means that
1191 // the order of operations is not significant between barriers.
1192 //
1193 // If trapping is enabled, each operation becomes an implicit observation
1194 // point, so the operations must be sequenced according their original
1195 // source order.
1196 if (!PendingConstrainedFP.empty()) {
1197 assert(PendingConstrainedFPStrict.empty());
1198 updateRoot(Pending&: PendingConstrainedFP);
1199 }
1200 // TODO: Add support for trapping-enabled scenarios.
1201 }
1202 return DAG.getRoot();
1203}
1204
1205SDValue SelectionDAGBuilder::getRoot() {
1206 // Chain up all pending constrained intrinsics together with all
1207 // pending loads, by simply appending them to PendingLoads and
1208 // then calling getMemoryRoot().
1209 PendingLoads.reserve(N: PendingLoads.size() +
1210 PendingConstrainedFP.size() +
1211 PendingConstrainedFPStrict.size());
1212 PendingLoads.append(in_start: PendingConstrainedFP.begin(),
1213 in_end: PendingConstrainedFP.end());
1214 PendingLoads.append(in_start: PendingConstrainedFPStrict.begin(),
1215 in_end: PendingConstrainedFPStrict.end());
1216 PendingConstrainedFP.clear();
1217 PendingConstrainedFPStrict.clear();
1218 return getMemoryRoot();
1219}
1220
1221SDValue SelectionDAGBuilder::getControlRoot() {
1222 // We need to emit pending fpexcept.strict constrained intrinsics,
1223 // so append them to the PendingExports list.
1224 PendingExports.append(in_start: PendingConstrainedFPStrict.begin(),
1225 in_end: PendingConstrainedFPStrict.end());
1226 PendingConstrainedFPStrict.clear();
1227 return updateRoot(Pending&: PendingExports);
1228}
1229
1230void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1231 DILocalVariable *Variable,
1232 DIExpression *Expression,
1233 DebugLoc DL) {
1234 assert(Variable && "Missing variable");
1235
1236 // Check if address has undef value.
1237 if (!Address || isa<UndefValue>(Val: Address) ||
1238 (Address->use_empty() && !isa<Argument>(Val: Address))) {
1239 LLVM_DEBUG(
1240 dbgs()
1241 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1242 return;
1243 }
1244
1245 bool IsParameter = Variable->isParameter() || isa<Argument>(Val: Address);
1246
1247 SDValue &N = NodeMap[Address];
1248 if (!N.getNode() && isa<Argument>(Val: Address))
1249 // Check unused arguments map.
1250 N = UnusedArgNodeMap[Address];
1251 SDDbgValue *SDV;
1252 if (N.getNode()) {
1253 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Val: Address))
1254 Address = BCI->getOperand(i_nocapture: 0);
1255 // Parameters are handled specially.
1256 auto *FINode = dyn_cast<FrameIndexSDNode>(Val: N.getNode());
1257 if (IsParameter && FINode) {
1258 // Byval parameter. We have a frame index at this point.
1259 SDV = DAG.getFrameIndexDbgValue(Var: Variable, Expr: Expression, FI: FINode->getIndex(),
1260 /*IsIndirect*/ true, DL, O: SDNodeOrder);
1261 } else if (isa<Argument>(Val: Address)) {
1262 // Address is an argument, so try to emit its dbg value using
1263 // virtual register info from the FuncInfo.ValueMap.
1264 EmitFuncArgumentDbgValue(V: Address, Variable, Expr: Expression, DL,
1265 Kind: FuncArgumentDbgValueKind::Declare, N);
1266 return;
1267 } else {
1268 SDV = DAG.getDbgValue(Var: Variable, Expr: Expression, N: N.getNode(), R: N.getResNo(),
1269 IsIndirect: true, DL, O: SDNodeOrder);
1270 }
1271 DAG.AddDbgValue(DB: SDV, isParameter: IsParameter);
1272 } else {
1273 // If Address is an argument then try to emit its dbg value using
1274 // virtual register info from the FuncInfo.ValueMap.
1275 if (!EmitFuncArgumentDbgValue(V: Address, Variable, Expr: Expression, DL,
1276 Kind: FuncArgumentDbgValueKind::Declare, N)) {
1277 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1278 << " (could not emit func-arg dbg_value)\n");
1279 }
1280 }
1281}
1282
1283void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1284 // Add SDDbgValue nodes for any var locs here. Do so before updating
1285 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1286 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1287 // Add SDDbgValue nodes for any var locs here. Do so before updating
1288 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1289 for (auto It = FnVarLocs->locs_begin(Before: &I), End = FnVarLocs->locs_end(Before: &I);
1290 It != End; ++It) {
1291 auto *Var = FnVarLocs->getDILocalVariable(ID: It->VariableID);
1292 dropDanglingDebugInfo(Variable: Var, Expr: It->Expr);
1293 if (It->Values.isKillLocation(Expression: It->Expr)) {
1294 handleKillDebugValue(Var, Expr: It->Expr, DbgLoc: It->DL, Order: SDNodeOrder);
1295 continue;
1296 }
1297 SmallVector<Value *> Values(It->Values.location_ops());
1298 if (!handleDebugValue(Values, Var, Expr: It->Expr, DbgLoc: It->DL, Order: SDNodeOrder,
1299 IsVariadic: It->Values.hasArgList())) {
1300 SmallVector<Value *, 4> Vals(It->Values.location_ops());
1301 addDanglingDebugInfo(Values&: Vals,
1302 Var: FnVarLocs->getDILocalVariable(ID: It->VariableID),
1303 Expr: It->Expr, IsVariadic: Vals.size() > 1, DL: It->DL, Order: SDNodeOrder);
1304 }
1305 }
1306 }
1307
1308 // We must skip DbgVariableRecords if they've already been processed above as
1309 // we have just emitted the debug values resulting from assignment tracking
1310 // analysis, making any existing DbgVariableRecords redundant (and probably
1311 // less correct). We still need to process DbgLabelRecords. This does sink
1312 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1313 // be important as it does so deterministcally and ordering between
1314 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1315 // printing).
1316 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1317 // Is there is any debug-info attached to this instruction, in the form of
1318 // DbgRecord non-instruction debug-info records.
1319 for (DbgRecord &DR : I.getDbgRecordRange()) {
1320 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(Val: &DR)) {
1321 assert(DLR->getLabel() && "Missing label");
1322 SDDbgLabel *SDV =
1323 DAG.getDbgLabel(Label: DLR->getLabel(), DL: DLR->getDebugLoc(), O: SDNodeOrder);
1324 DAG.AddDbgLabel(DB: SDV);
1325 continue;
1326 }
1327
1328 if (SkipDbgVariableRecords)
1329 continue;
1330 DbgVariableRecord &DVR = cast<DbgVariableRecord>(Val&: DR);
1331 DILocalVariable *Variable = DVR.getVariable();
1332 DIExpression *Expression = DVR.getExpression();
1333 dropDanglingDebugInfo(Variable, Expr: Expression);
1334
1335 if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1336 if (FuncInfo.PreprocessedDVRDeclares.contains(Ptr: &DVR))
1337 continue;
1338 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1339 << "\n");
1340 handleDebugDeclare(Address: DVR.getVariableLocationOp(OpIdx: 0), Variable, Expression,
1341 DL: DVR.getDebugLoc());
1342 continue;
1343 }
1344
1345 // A DbgVariableRecord with no locations is a kill location.
1346 SmallVector<Value *, 4> Values(DVR.location_ops());
1347 if (Values.empty()) {
1348 handleKillDebugValue(Var: Variable, Expr: Expression, DbgLoc: DVR.getDebugLoc(),
1349 Order: SDNodeOrder);
1350 continue;
1351 }
1352
1353 // A DbgVariableRecord with an undef or absent location is also a kill
1354 // location.
1355 if (llvm::any_of(Range&: Values,
1356 P: [](Value *V) { return !V || isa<UndefValue>(Val: V); })) {
1357 handleKillDebugValue(Var: Variable, Expr: Expression, DbgLoc: DVR.getDebugLoc(),
1358 Order: SDNodeOrder);
1359 continue;
1360 }
1361
1362 bool IsVariadic = DVR.hasArgList();
1363 if (!handleDebugValue(Values, Var: Variable, Expr: Expression, DbgLoc: DVR.getDebugLoc(),
1364 Order: SDNodeOrder, IsVariadic)) {
1365 addDanglingDebugInfo(Values, Var: Variable, Expr: Expression, IsVariadic,
1366 DL: DVR.getDebugLoc(), Order: SDNodeOrder);
1367 }
1368 }
1369}
1370
1371void SelectionDAGBuilder::visit(const Instruction &I) {
1372 visitDbgInfo(I);
1373
1374 // Set up outgoing PHI node register values before emitting the terminator.
1375 if (I.isTerminator()) {
1376 HandlePHINodesInSuccessorBlocks(LLVMBB: I.getParent());
1377 }
1378
1379 ++SDNodeOrder;
1380 CurInst = &I;
1381
1382 // Set inserted listener only if required.
1383 bool NodeInserted = false;
1384 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1385 MDNode *PCSectionsMD = I.getMetadata(KindID: LLVMContext::MD_pcsections);
1386 MDNode *MMRA = I.getMetadata(KindID: LLVMContext::MD_mmra);
1387 if (PCSectionsMD || MMRA) {
1388 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1389 args&: DAG, args: [&](SDNode *) { NodeInserted = true; });
1390 }
1391
1392 visit(Opcode: I.getOpcode(), I);
1393
1394 if (!I.isTerminator() && !HasTailCall &&
1395 !isa<GCStatepointInst>(Val: I)) // statepoints handle their exports internally
1396 CopyToExportRegsIfNeeded(V: &I);
1397
1398 // Handle metadata.
1399 if (PCSectionsMD || MMRA) {
1400 auto It = NodeMap.find(Val: &I);
1401 if (It != NodeMap.end()) {
1402 if (PCSectionsMD)
1403 DAG.addPCSections(Node: It->second.getNode(), MD: PCSectionsMD);
1404 if (MMRA)
1405 DAG.addMMRAMetadata(Node: It->second.getNode(), MMRA);
1406 } else if (NodeInserted) {
1407 // This should not happen; if it does, don't let it go unnoticed so we can
1408 // fix it. Relevant visit*() function is probably missing a setValue().
1409 errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1410 << I.getModule()->getName() << "]\n";
1411 LLVM_DEBUG(I.dump());
1412 assert(false);
1413 }
1414 }
1415
1416 CurInst = nullptr;
1417}
1418
1419void SelectionDAGBuilder::visitPHI(const PHINode &) {
1420 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1421}
1422
1423void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1424 // Note: this doesn't use InstVisitor, because it has to work with
1425 // ConstantExpr's in addition to instructions.
1426 switch (Opcode) {
1427 default: llvm_unreachable("Unknown instruction type encountered!");
1428 // Build the switch statement using the Instruction.def file.
1429#define HANDLE_INST(NUM, OPCODE, CLASS) \
1430 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1431#include "llvm/IR/Instruction.def"
1432 }
1433}
1434
1435static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1436 DILocalVariable *Variable,
1437 DebugLoc DL, unsigned Order,
1438 SmallVectorImpl<Value *> &Values,
1439 DIExpression *Expression) {
1440 // For variadic dbg_values we will now insert poison.
1441 // FIXME: We can potentially recover these!
1442 SmallVector<SDDbgOperand, 2> Locs;
1443 for (const Value *V : Values) {
1444 auto *Poison = PoisonValue::get(T: V->getType());
1445 Locs.push_back(Elt: SDDbgOperand::fromConst(Const: Poison));
1446 }
1447 SDDbgValue *SDV = DAG.getDbgValueList(Var: Variable, Expr: Expression, Locs, Dependencies: {},
1448 /*IsIndirect=*/false, DL, O: Order,
1449 /*IsVariadic=*/true);
1450 DAG.AddDbgValue(DB: SDV, /*isParameter=*/false);
1451 return true;
1452}
1453
1454void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1455 DILocalVariable *Var,
1456 DIExpression *Expr,
1457 bool IsVariadic, DebugLoc DL,
1458 unsigned Order) {
1459 if (IsVariadic) {
1460 handleDanglingVariadicDebugInfo(DAG, Variable: Var, DL, Order, Values, Expression: Expr);
1461 return;
1462 }
1463 // TODO: Dangling debug info will eventually either be resolved or produce
1464 // a poison DBG_VALUE. However in the resolution case, a gap may appear
1465 // between the original dbg.value location and its resolved DBG_VALUE,
1466 // which we should ideally fill with an extra poison DBG_VALUE.
1467 assert(Values.size() == 1);
1468 DanglingDebugInfoMap[Values[0]].emplace_back(args&: Var, args&: Expr, args&: DL, args&: Order);
1469}
1470
1471void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1472 const DIExpression *Expr) {
1473 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1474 DIVariable *DanglingVariable = DDI.getVariable();
1475 DIExpression *DanglingExpr = DDI.getExpression();
1476 if (DanglingVariable == Variable && Expr->fragmentsOverlap(Other: DanglingExpr)) {
1477 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1478 << printDDI(nullptr, DDI) << "\n");
1479 return true;
1480 }
1481 return false;
1482 };
1483
1484 for (auto &DDIMI : DanglingDebugInfoMap) {
1485 DanglingDebugInfoVector &DDIV = DDIMI.second;
1486
1487 // If debug info is to be dropped, run it through final checks to see
1488 // whether it can be salvaged.
1489 for (auto &DDI : DDIV)
1490 if (isMatchingDbgValue(DDI))
1491 salvageUnresolvedDbgValue(V: DDIMI.first, DDI);
1492
1493 erase_if(C&: DDIV, P: isMatchingDbgValue);
1494 }
1495}
1496
1497// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1498// generate the debug data structures now that we've seen its definition.
1499void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1500 SDValue Val) {
1501 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(Key: V);
1502 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1503 return;
1504
1505 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1506 for (auto &DDI : DDIV) {
1507 DebugLoc DL = DDI.getDebugLoc();
1508 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
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 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1523 Kind: FuncArgumentDbgValueKind::Value, N: Val)) {
1524 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1525 << printDDI(V, DDI) << "\n");
1526 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1527 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1528 // inserted after the definition of Val when emitting the instructions
1529 // after ISel. An alternative could be to teach
1530 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1531 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1532 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1533 << ValSDNodeOrder << "\n");
1534 SDV = getDbgValue(N: Val, Variable, Expr, dl: DL,
1535 DbgSDNodeOrder: std::max(a: DbgSDNodeOrder, b: ValSDNodeOrder));
1536 DAG.AddDbgValue(DB: SDV, isParameter: false);
1537 } else
1538 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1539 << printDDI(V, DDI)
1540 << " in EmitFuncArgumentDbgValue\n");
1541 } else {
1542 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1543 << "\n");
1544 auto Poison = PoisonValue::get(T: V->getType());
1545 auto SDV =
1546 DAG.getConstantDbgValue(Var: Variable, Expr, C: Poison, DL, O: DbgSDNodeOrder);
1547 DAG.AddDbgValue(DB: SDV, isParameter: false);
1548 }
1549 }
1550 DDIV.clear();
1551}
1552
1553void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1554 DanglingDebugInfo &DDI) {
1555 // TODO: For the variadic implementation, instead of only checking the fail
1556 // state of `handleDebugValue`, we need know specifically which values were
1557 // invalid, so that we attempt to salvage only those values when processing
1558 // a DIArgList.
1559 const Value *OrigV = V;
1560 DILocalVariable *Var = DDI.getVariable();
1561 DIExpression *Expr = DDI.getExpression();
1562 DebugLoc DL = DDI.getDebugLoc();
1563 unsigned SDOrder = DDI.getSDNodeOrder();
1564
1565 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1566 // that DW_OP_stack_value is desired.
1567 bool StackValue = true;
1568
1569 // Can this Value can be encoded without any further work?
1570 if (handleDebugValue(Values: V, Var, Expr, DbgLoc: DL, Order: SDOrder, /*IsVariadic=*/false))
1571 return;
1572
1573 // Attempt to salvage back through as many instructions as possible. Bail if
1574 // a non-instruction is seen, such as a constant expression or global
1575 // variable. FIXME: Further work could recover those too.
1576 while (isa<Instruction>(Val: V)) {
1577 const Instruction &VAsInst = *cast<const Instruction>(Val: V);
1578 // Temporary "0", awaiting real implementation.
1579 SmallVector<uint64_t, 16> Ops;
1580 SmallVector<Value *, 4> AdditionalValues;
1581 V = salvageDebugInfoImpl(I&: const_cast<Instruction &>(VAsInst),
1582 CurrentLocOps: Expr->getNumLocationOperands(), Ops,
1583 AdditionalValues);
1584 // If we cannot salvage any further, and haven't yet found a suitable debug
1585 // expression, bail out.
1586 if (!V)
1587 break;
1588
1589 // TODO: If AdditionalValues isn't empty, then the salvage can only be
1590 // represented with a DBG_VALUE_LIST, so we give up. When we have support
1591 // here for variadic dbg_values, remove that condition.
1592 if (!AdditionalValues.empty())
1593 break;
1594
1595 // New value and expr now represent this debuginfo.
1596 Expr = DIExpression::appendOpsToArg(Expr, Ops, ArgNo: 0, StackValue);
1597
1598 // Some kind of simplification occurred: check whether the operand of the
1599 // salvaged debug expression can be encoded in this DAG.
1600 if (handleDebugValue(Values: V, Var, Expr, DbgLoc: DL, Order: SDOrder, /*IsVariadic=*/false)) {
1601 LLVM_DEBUG(
1602 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n"
1603 << *OrigV << "\nBy stripping back to:\n " << *V << "\n");
1604 return;
1605 }
1606 }
1607
1608 // This was the final opportunity to salvage this debug information, and it
1609 // couldn't be done. Place a poison DBG_VALUE at this location to terminate
1610 // any earlier variable location.
1611 assert(OrigV && "V shouldn't be null");
1612 auto *Poison = PoisonValue::get(T: OrigV->getType());
1613 auto *SDV = DAG.getConstantDbgValue(Var, Expr, C: Poison, DL, O: SDNodeOrder);
1614 DAG.AddDbgValue(DB: SDV, isParameter: false);
1615 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n "
1616 << printDDI(OrigV, DDI) << "\n");
1617}
1618
1619void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1620 DIExpression *Expr,
1621 DebugLoc DbgLoc,
1622 unsigned Order) {
1623 Value *Poison = PoisonValue::get(T: Type::getInt1Ty(C&: *Context));
1624 DIExpression *NewExpr =
1625 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1626 handleDebugValue(Values: Poison, Var, Expr: NewExpr, DbgLoc, Order,
1627 /*IsVariadic*/ false);
1628}
1629
1630bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1631 DILocalVariable *Var,
1632 DIExpression *Expr, DebugLoc DbgLoc,
1633 unsigned Order, bool IsVariadic) {
1634 if (Values.empty())
1635 return true;
1636
1637 // Filter EntryValue locations out early.
1638 if (visitEntryValueDbgValue(Values, Variable: Var, Expr, DbgLoc))
1639 return true;
1640
1641 SmallVector<SDDbgOperand> LocationOps;
1642 SmallVector<SDNode *> Dependencies;
1643 for (const Value *V : Values) {
1644 // Constant value.
1645 if (isa<ConstantInt>(Val: V) || isa<ConstantFP>(Val: V) || isa<UndefValue>(Val: V) ||
1646 isa<ConstantPointerNull>(Val: V)) {
1647 LocationOps.emplace_back(Args: SDDbgOperand::fromConst(Const: V));
1648 continue;
1649 }
1650
1651 // Look through IntToPtr constants.
1652 if (auto *CE = dyn_cast<ConstantExpr>(Val: V))
1653 if (CE->getOpcode() == Instruction::IntToPtr) {
1654 LocationOps.emplace_back(Args: SDDbgOperand::fromConst(Const: CE->getOperand(i_nocapture: 0)));
1655 continue;
1656 }
1657
1658 // If the Value is a frame index, we can create a FrameIndex debug value
1659 // without relying on the DAG at all.
1660 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Val: V)) {
1661 auto SI = FuncInfo.StaticAllocaMap.find(Val: AI);
1662 if (SI != FuncInfo.StaticAllocaMap.end()) {
1663 LocationOps.emplace_back(Args: SDDbgOperand::fromFrameIdx(FrameIdx: SI->second));
1664 continue;
1665 }
1666 }
1667
1668 // Do not use getValue() in here; we don't want to generate code at
1669 // this point if it hasn't been done yet.
1670 SDValue N = NodeMap[V];
1671 if (!N.getNode() && isa<Argument>(Val: V)) // Check unused arguments map.
1672 N = UnusedArgNodeMap[V];
1673
1674 if (N.getNode()) {
1675 // Only emit func arg dbg value for non-variadic dbg.values for now.
1676 if (!IsVariadic &&
1677 EmitFuncArgumentDbgValue(V, Variable: Var, Expr, DL: DbgLoc,
1678 Kind: FuncArgumentDbgValueKind::Value, N))
1679 return true;
1680 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Val: N.getNode())) {
1681 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1682 // describe stack slot locations.
1683 //
1684 // Consider "int x = 0; int *px = &x;". There are two kinds of
1685 // interesting debug values here after optimization:
1686 //
1687 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
1688 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1689 //
1690 // Both describe the direct values of their associated variables.
1691 Dependencies.push_back(Elt: N.getNode());
1692 LocationOps.emplace_back(Args: SDDbgOperand::fromFrameIdx(FrameIdx: FISDN->getIndex()));
1693 continue;
1694 }
1695 LocationOps.emplace_back(
1696 Args: SDDbgOperand::fromNode(Node: N.getNode(), ResNo: N.getResNo()));
1697 continue;
1698 }
1699
1700 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1701 // Special rules apply for the first dbg.values of parameter variables in a
1702 // function. Identify them by the fact they reference Argument Values, that
1703 // they're parameters, and they are parameters of the current function. We
1704 // need to let them dangle until they get an SDNode.
1705 bool IsParamOfFunc =
1706 isa<Argument>(Val: V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1707 if (IsParamOfFunc)
1708 return false;
1709
1710 // The value is not used in this block yet (or it would have an SDNode).
1711 // We still want the value to appear for the user if possible -- if it has
1712 // an associated VReg, we can refer to that instead.
1713 auto VMI = FuncInfo.ValueMap.find(Val: V);
1714 if (VMI != FuncInfo.ValueMap.end()) {
1715 Register Reg = VMI->second;
1716 // If this is a PHI node, it may be split up into several MI PHI nodes
1717 // (in FunctionLoweringInfo::set).
1718 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1719 V->getType(), std::nullopt);
1720 if (RFV.occupiesMultipleRegs()) {
1721 // FIXME: We could potentially support variadic dbg_values here.
1722 if (IsVariadic)
1723 return false;
1724 unsigned Offset = 0;
1725 unsigned BitsToDescribe = 0;
1726 if (auto VarSize = Var->getSizeInBits())
1727 BitsToDescribe = *VarSize;
1728 if (auto Fragment = Expr->getFragmentInfo())
1729 BitsToDescribe = Fragment->SizeInBits;
1730 for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1731 // Bail out if all bits are described already.
1732 if (Offset >= BitsToDescribe)
1733 break;
1734 // TODO: handle scalable vectors.
1735 unsigned RegisterSize = RegAndSize.second;
1736 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1737 ? BitsToDescribe - Offset
1738 : RegisterSize;
1739 auto FragmentExpr = DIExpression::createFragmentExpression(
1740 Expr, OffsetInBits: Offset, SizeInBits: FragmentSize);
1741 if (!FragmentExpr)
1742 continue;
1743 SDDbgValue *SDV = DAG.getVRegDbgValue(
1744 Var, Expr: *FragmentExpr, VReg: RegAndSize.first, IsIndirect: false, DL: DbgLoc, O: Order);
1745 DAG.AddDbgValue(DB: SDV, isParameter: false);
1746 Offset += RegisterSize;
1747 }
1748 return true;
1749 }
1750 // We can use simple vreg locations for variadic dbg_values as well.
1751 LocationOps.emplace_back(Args: SDDbgOperand::fromVReg(VReg: Reg));
1752 continue;
1753 }
1754 // We failed to create a SDDbgOperand for V.
1755 return false;
1756 }
1757
1758 // We have created a SDDbgOperand for each Value in Values.
1759 assert(!LocationOps.empty());
1760 SDDbgValue *SDV =
1761 DAG.getDbgValueList(Var, Expr, Locs: LocationOps, Dependencies,
1762 /*IsIndirect=*/false, DL: DbgLoc, O: Order, IsVariadic);
1763 DAG.AddDbgValue(DB: SDV, /*isParameter=*/false);
1764 return true;
1765}
1766
1767void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1768 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1769 for (auto &Pair : DanglingDebugInfoMap)
1770 for (auto &DDI : Pair.second)
1771 salvageUnresolvedDbgValue(V: const_cast<Value *>(Pair.first), DDI);
1772 clearDanglingDebugInfo();
1773}
1774
1775/// getCopyFromRegs - If there was virtual register allocated for the value V
1776/// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1777SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1778 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(Val: V);
1779 SDValue Result;
1780
1781 if (It != FuncInfo.ValueMap.end()) {
1782 Register InReg = It->second;
1783
1784 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1785 DAG.getDataLayout(), InReg, Ty,
1786 std::nullopt); // This is not an ABI copy.
1787 SDValue Chain = DAG.getEntryNode();
1788 Result = RFV.getCopyFromRegs(DAG, FuncInfo, dl: getCurSDLoc(), Chain, Glue: nullptr,
1789 V);
1790 resolveDanglingDebugInfo(V, Val: Result);
1791 }
1792
1793 return Result;
1794}
1795
1796/// getValue - Return an SDValue for the given Value.
1797SDValue SelectionDAGBuilder::getValue(const Value *V) {
1798 // If we already have an SDValue for this value, use it. It's important
1799 // to do this first, so that we don't create a CopyFromReg if we already
1800 // have a regular SDValue.
1801 SDValue &N = NodeMap[V];
1802 if (N.getNode()) return N;
1803
1804 // If there's a virtual register allocated and initialized for this
1805 // value, use it.
1806 if (SDValue copyFromReg = getCopyFromRegs(V, Ty: V->getType()))
1807 return copyFromReg;
1808
1809 // Otherwise create a new SDValue and remember it.
1810 SDValue Val = getValueImpl(V);
1811 NodeMap[V] = Val;
1812 resolveDanglingDebugInfo(V, Val);
1813 return Val;
1814}
1815
1816/// getNonRegisterValue - Return an SDValue for the given Value, but
1817/// don't look in FuncInfo.ValueMap for a virtual register.
1818SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1819 // If we already have an SDValue for this value, use it.
1820 SDValue &N = NodeMap[V];
1821 if (N.getNode()) {
1822 if (isIntOrFPConstant(V: N)) {
1823 // Remove the debug location from the node as the node is about to be used
1824 // in a location which may differ from the original debug location. This
1825 // is relevant to Constant and ConstantFP nodes because they can appear
1826 // as constant expressions inside PHI nodes.
1827 N->setDebugLoc(DebugLoc());
1828 }
1829 return N;
1830 }
1831
1832 // Otherwise create a new SDValue and remember it.
1833 SDValue Val = getValueImpl(V);
1834 NodeMap[V] = Val;
1835 resolveDanglingDebugInfo(V, Val);
1836 return Val;
1837}
1838
1839/// getValueImpl - Helper function for getValue and getNonRegisterValue.
1840/// Create an SDValue for the given value.
1841SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1842 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1843
1844 if (const Constant *C = dyn_cast<Constant>(Val: V)) {
1845 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: V->getType(), AllowUnknown: true);
1846
1847 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: C)) {
1848 SDLoc DL = getCurSDLoc();
1849
1850 // DAG.getConstant() may attempt to legalise the vector constant which can
1851 // significantly change the combines applied to the DAG. To reduce the
1852 // divergence when enabling ConstantInt based vectors we try to construct
1853 // the DAG in the same way as shufflevector based splats. TODO: The
1854 // divergence sometimes leads to better optimisations. Ideally we should
1855 // prevent DAG.getConstant() from legalising too early but there are some
1856 // degradations preventing this.
1857 if (VT.isScalableVector())
1858 return DAG.getNode(
1859 Opcode: ISD::SPLAT_VECTOR, DL, VT,
1860 Operand: DAG.getConstant(Val: CI->getValue(), DL, VT: VT.getVectorElementType()));
1861 if (VT.isFixedLengthVector())
1862 return DAG.getSplatBuildVector(
1863 VT, DL,
1864 Op: DAG.getConstant(Val: CI->getValue(), DL, VT: VT.getVectorElementType()));
1865 return DAG.getConstant(Val: *CI, DL, VT);
1866 }
1867
1868 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Val: C))
1869 return DAG.getGlobalAddress(GV, DL: getCurSDLoc(), VT);
1870
1871 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(Val: C)) {
1872 return DAG.getNode(Opcode: ISD::PtrAuthGlobalAddress, DL: getCurSDLoc(), VT,
1873 N1: getValue(V: CPA->getPointer()), N2: getValue(V: CPA->getKey()),
1874 N3: getValue(V: CPA->getAddrDiscriminator()),
1875 N4: getValue(V: CPA->getDiscriminator()));
1876 }
1877
1878 if (isa<ConstantPointerNull>(Val: C))
1879 return DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT);
1880
1881 if (match(V: C, P: m_VScale()))
1882 return DAG.getVScale(DL: getCurSDLoc(), VT, MulImm: APInt(VT.getSizeInBits(), 1));
1883
1884 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Val: C))
1885 return DAG.getConstantFP(V: *CFP, DL: getCurSDLoc(), VT);
1886
1887 if (isa<UndefValue>(Val: C) && !V->getType()->isAggregateType())
1888 return isa<PoisonValue>(Val: C) ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
1889
1890 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: C)) {
1891 visit(Opcode: CE->getOpcode(), I: *CE);
1892 SDValue N1 = NodeMap[V];
1893 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1894 return N1;
1895 }
1896
1897 if (isa<ConstantStruct>(Val: C) || isa<ConstantArray>(Val: C)) {
1898 SmallVector<SDValue, 4> Constants;
1899 for (const Use &U : C->operands()) {
1900 SDNode *Val = getValue(V: U).getNode();
1901 // If the operand is an empty aggregate, there are no values.
1902 if (!Val) continue;
1903 // Add each leaf value from the operand to the Constants list
1904 // to form a flattened list of all the values.
1905 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1906 Constants.push_back(Elt: SDValue(Val, i));
1907 }
1908
1909 return DAG.getMergeValues(Ops: Constants, dl: getCurSDLoc());
1910 }
1911
1912 if (const ConstantDataSequential *CDS =
1913 dyn_cast<ConstantDataSequential>(Val: C)) {
1914 SmallVector<SDValue, 4> Ops;
1915 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i) {
1916 SDNode *Val = getValue(V: CDS->getElementAsConstant(i)).getNode();
1917 // Add each leaf value from the operand to the Constants list
1918 // to form a flattened list of all the values.
1919 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1920 Ops.push_back(Elt: SDValue(Val, i));
1921 }
1922
1923 if (isa<ArrayType>(Val: CDS->getType()))
1924 return DAG.getMergeValues(Ops, dl: getCurSDLoc());
1925 return DAG.getBuildVector(VT, DL: getCurSDLoc(), Ops);
1926 }
1927
1928 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1929 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1930 "Unknown struct or array constant!");
1931
1932 SmallVector<EVT, 4> ValueVTs;
1933 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: C->getType(), ValueVTs);
1934 unsigned NumElts = ValueVTs.size();
1935 if (NumElts == 0)
1936 return SDValue(); // empty struct
1937 SmallVector<SDValue, 4> Constants(NumElts);
1938 for (unsigned i = 0; i != NumElts; ++i) {
1939 EVT EltVT = ValueVTs[i];
1940 if (isa<UndefValue>(Val: C))
1941 Constants[i] = DAG.getUNDEF(VT: EltVT);
1942 else if (EltVT.isFloatingPoint())
1943 Constants[i] = DAG.getConstantFP(Val: 0, DL: getCurSDLoc(), VT: EltVT);
1944 else
1945 Constants[i] = DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: EltVT);
1946 }
1947
1948 return DAG.getMergeValues(Ops: Constants, dl: getCurSDLoc());
1949 }
1950
1951 if (const BlockAddress *BA = dyn_cast<BlockAddress>(Val: C))
1952 return DAG.getBlockAddress(BA, VT);
1953
1954 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(Val: C))
1955 return getValue(V: Equiv->getGlobalValue());
1956
1957 if (const auto *NC = dyn_cast<NoCFIValue>(Val: C))
1958 return getValue(V: NC->getGlobalValue());
1959
1960 if (VT == MVT::aarch64svcount) {
1961 assert(C->isNullValue() && "Can only zero this target type!");
1962 return DAG.getNode(Opcode: ISD::BITCAST, DL: getCurSDLoc(), VT,
1963 Operand: DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: MVT::nxv16i1));
1964 }
1965
1966 if (VT.isRISCVVectorTuple()) {
1967 assert(C->isNullValue() && "Can only zero this target type!");
1968 return DAG.getNode(
1969 Opcode: ISD::BITCAST, DL: getCurSDLoc(), VT,
1970 Operand: DAG.getNode(
1971 Opcode: ISD::SPLAT_VECTOR, DL: getCurSDLoc(),
1972 VT: EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::i8,
1973 NumElements: VT.getSizeInBits().getKnownMinValue() / 8, IsScalable: true),
1974 Operand: DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: MVT::getIntegerVT(BitWidth: 8))));
1975 }
1976
1977 VectorType *VecTy = cast<VectorType>(Val: V->getType());
1978
1979 // Now that we know the number and type of the elements, get that number of
1980 // elements into the Ops array based on what kind of constant it is.
1981 if (const ConstantVector *CV = dyn_cast<ConstantVector>(Val: C)) {
1982 SmallVector<SDValue, 16> Ops;
1983 unsigned NumElements = cast<FixedVectorType>(Val: VecTy)->getNumElements();
1984 for (unsigned i = 0; i != NumElements; ++i)
1985 Ops.push_back(Elt: getValue(V: CV->getOperand(i_nocapture: i)));
1986
1987 return DAG.getBuildVector(VT, DL: getCurSDLoc(), Ops);
1988 }
1989
1990 if (isa<ConstantAggregateZero>(Val: C)) {
1991 EVT EltVT =
1992 TLI.getValueType(DL: DAG.getDataLayout(), Ty: VecTy->getElementType());
1993
1994 SDValue Op;
1995 if (EltVT.isFloatingPoint())
1996 Op = DAG.getConstantFP(Val: 0, DL: getCurSDLoc(), VT: EltVT);
1997 else
1998 Op = DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: EltVT);
1999
2000 return DAG.getSplat(VT, DL: getCurSDLoc(), Op);
2001 }
2002
2003 llvm_unreachable("Unknown vector constant");
2004 }
2005
2006 // If this is a static alloca, generate it as the frameindex instead of
2007 // computation.
2008 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Val: V)) {
2009 DenseMap<const AllocaInst*, int>::iterator SI =
2010 FuncInfo.StaticAllocaMap.find(Val: AI);
2011 if (SI != FuncInfo.StaticAllocaMap.end())
2012 return DAG.getFrameIndex(
2013 FI: SI->second, VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: AI->getType()));
2014 }
2015
2016 // If this is an instruction which fast-isel has deferred, select it now.
2017 if (const Instruction *Inst = dyn_cast<Instruction>(Val: V)) {
2018 Register InReg = FuncInfo.InitializeRegForValue(V: Inst);
2019
2020 std::optional<CallingConv::ID> CallConv;
2021 auto *CB = dyn_cast<CallBase>(Val: Inst);
2022 if (CB && !CB->isInlineAsm())
2023 CallConv = CB->getCallingConv();
2024
2025 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
2026 Inst->getType(), CallConv);
2027 SDValue Chain = DAG.getEntryNode();
2028 return RFV.getCopyFromRegs(DAG, FuncInfo, dl: getCurSDLoc(), Chain, Glue: nullptr, V);
2029 }
2030
2031 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(Val: V))
2032 return DAG.getMDNode(MD: cast<MDNode>(Val: MD->getMetadata()));
2033
2034 if (const auto *BB = dyn_cast<BasicBlock>(Val: V))
2035 return DAG.getBasicBlock(MBB: FuncInfo.getMBB(BB));
2036
2037 llvm_unreachable("Can't get register for value!");
2038}
2039
2040void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
2041 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2042 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
2043 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
2044 bool IsSEH = isAsynchronousEHPersonality(Pers);
2045 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
2046 if (IsSEH) {
2047 // For SEH, EHCont Guard needs to know that this catchpad is a target.
2048 CatchPadMBB->setIsEHContTarget(true);
2049 DAG.getMachineFunction().setHasEHContTarget(true);
2050 } else
2051 CatchPadMBB->setIsEHScopeEntry();
2052 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
2053 if (IsMSVCCXX || IsCoreCLR)
2054 CatchPadMBB->setIsEHFuncletEntry();
2055}
2056
2057void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
2058 // Update machine-CFG edge.
2059 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(BB: I.getSuccessor());
2060 FuncInfo.MBB->addSuccessor(Succ: TargetMBB);
2061
2062 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2063 bool IsSEH = isAsynchronousEHPersonality(Pers);
2064 if (IsSEH) {
2065 // If this is not a fall-through branch or optimizations are switched off,
2066 // emit the branch.
2067 if (TargetMBB != NextBlock(MBB: FuncInfo.MBB) ||
2068 TM.getOptLevel() == CodeGenOptLevel::None)
2069 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other,
2070 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: TargetMBB)));
2071 return;
2072 }
2073
2074 // For non-SEH, EHCont Guard needs to know that this catchret is a target.
2075 TargetMBB->setIsEHContTarget(true);
2076 DAG.getMachineFunction().setHasEHContTarget(true);
2077
2078 // Figure out the funclet membership for the catchret's successor.
2079 // This will be used by the FuncletLayout pass to determine how to order the
2080 // BB's.
2081 // A 'catchret' returns to the outer scope's color.
2082 Value *ParentPad = I.getCatchSwitchParentPad();
2083 const BasicBlock *SuccessorColor;
2084 if (isa<ConstantTokenNone>(Val: ParentPad))
2085 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2086 else
2087 SuccessorColor = cast<Instruction>(Val: ParentPad)->getParent();
2088 assert(SuccessorColor && "No parent funclet for catchret!");
2089 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(BB: SuccessorColor);
2090 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2091
2092 // Create the terminator node.
2093 SDValue Ret = DAG.getNode(Opcode: ISD::CATCHRET, DL: getCurSDLoc(), VT: MVT::Other,
2094 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: TargetMBB),
2095 N3: DAG.getBasicBlock(MBB: SuccessorColorMBB));
2096 DAG.setRoot(Ret);
2097}
2098
2099void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2100 // Don't emit any special code for the cleanuppad instruction. It just marks
2101 // the start of an EH scope/funclet.
2102 FuncInfo.MBB->setIsEHScopeEntry();
2103 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2104 if (Pers != EHPersonality::Wasm_CXX) {
2105 FuncInfo.MBB->setIsEHFuncletEntry();
2106 FuncInfo.MBB->setIsCleanupFuncletEntry();
2107 }
2108}
2109
2110/// When an invoke or a cleanupret unwinds to the next EH pad, there are
2111/// many places it could ultimately go. In the IR, we have a single unwind
2112/// destination, but in the machine CFG, we enumerate all the possible blocks.
2113/// This function skips over imaginary basic blocks that hold catchswitch
2114/// instructions, and finds all the "real" machine
2115/// basic block destinations. As those destinations may not be successors of
2116/// EHPadBB, here we also calculate the edge probability to those destinations.
2117/// The passed-in Prob is the edge probability to EHPadBB.
2118static void findUnwindDestinations(
2119 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2120 BranchProbability Prob,
2121 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2122 &UnwindDests) {
2123 EHPersonality Personality =
2124 classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
2125 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2126 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2127 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2128 bool IsSEH = isAsynchronousEHPersonality(Pers: Personality);
2129
2130 while (EHPadBB) {
2131 BasicBlock::const_iterator Pad = EHPadBB->getFirstNonPHIIt();
2132 BasicBlock *NewEHPadBB = nullptr;
2133 if (isa<LandingPadInst>(Val: Pad)) {
2134 // Stop on landingpads. They are not funclets.
2135 UnwindDests.emplace_back(Args: FuncInfo.getMBB(BB: EHPadBB), Args&: Prob);
2136 break;
2137 } else if (isa<CleanupPadInst>(Val: Pad)) {
2138 // Stop on cleanup pads. Cleanups are always funclet entries for all known
2139 // personalities except Wasm. And in Wasm this becomes a catch_all(_ref),
2140 // which always catches an exception.
2141 UnwindDests.emplace_back(Args: FuncInfo.getMBB(BB: EHPadBB), Args&: Prob);
2142 UnwindDests.back().first->setIsEHScopeEntry();
2143 // In Wasm, EH scopes are not funclets
2144 if (!IsWasmCXX)
2145 UnwindDests.back().first->setIsEHFuncletEntry();
2146 break;
2147 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Val&: Pad)) {
2148 // Add the catchpad handlers to the possible destinations.
2149 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2150 UnwindDests.emplace_back(Args: FuncInfo.getMBB(BB: CatchPadBB), Args&: Prob);
2151 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2152 if (IsMSVCCXX || IsCoreCLR)
2153 UnwindDests.back().first->setIsEHFuncletEntry();
2154 if (!IsSEH)
2155 UnwindDests.back().first->setIsEHScopeEntry();
2156 }
2157 NewEHPadBB = CatchSwitch->getUnwindDest();
2158 } else {
2159 continue;
2160 }
2161
2162 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2163 if (BPI && NewEHPadBB)
2164 Prob *= BPI->getEdgeProbability(Src: EHPadBB, Dst: NewEHPadBB);
2165 EHPadBB = NewEHPadBB;
2166 }
2167}
2168
2169void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2170 // Update successor info.
2171 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2172 auto UnwindDest = I.getUnwindDest();
2173 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2174 BranchProbability UnwindDestProb =
2175 (BPI && UnwindDest)
2176 ? BPI->getEdgeProbability(Src: FuncInfo.MBB->getBasicBlock(), Dst: UnwindDest)
2177 : BranchProbability::getZero();
2178 findUnwindDestinations(FuncInfo, EHPadBB: UnwindDest, Prob: UnwindDestProb, UnwindDests);
2179 for (auto &UnwindDest : UnwindDests) {
2180 UnwindDest.first->setIsEHPad();
2181 addSuccessorWithProb(Src: FuncInfo.MBB, Dst: UnwindDest.first, Prob: UnwindDest.second);
2182 }
2183 FuncInfo.MBB->normalizeSuccProbs();
2184
2185 // Create the terminator node.
2186 MachineBasicBlock *CleanupPadMBB =
2187 FuncInfo.getMBB(BB: I.getCleanupPad()->getParent());
2188 SDValue Ret = DAG.getNode(Opcode: ISD::CLEANUPRET, DL: getCurSDLoc(), VT: MVT::Other,
2189 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: CleanupPadMBB));
2190 DAG.setRoot(Ret);
2191}
2192
2193void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2194 report_fatal_error(reason: "visitCatchSwitch not yet implemented!");
2195}
2196
2197void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2198 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2199 auto &DL = DAG.getDataLayout();
2200 SDValue Chain = getControlRoot();
2201 SmallVector<ISD::OutputArg, 8> Outs;
2202 SmallVector<SDValue, 8> OutVals;
2203
2204 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2205 // lower
2206 //
2207 // %val = call <ty> @llvm.experimental.deoptimize()
2208 // ret <ty> %val
2209 //
2210 // differently.
2211 if (I.getParent()->getTerminatingDeoptimizeCall()) {
2212 LowerDeoptimizingReturn();
2213 return;
2214 }
2215
2216 if (!FuncInfo.CanLowerReturn) {
2217 Register DemoteReg = FuncInfo.DemoteRegister;
2218
2219 // Emit a store of the return value through the virtual register.
2220 // Leave Outs empty so that LowerReturn won't try to load return
2221 // registers the usual way.
2222 MVT PtrValueVT = TLI.getPointerTy(DL, AS: DL.getAllocaAddrSpace());
2223 SDValue RetPtr =
2224 DAG.getCopyFromReg(Chain, dl: getCurSDLoc(), Reg: DemoteReg, VT: PtrValueVT);
2225 SDValue RetOp = getValue(V: I.getOperand(i_nocapture: 0));
2226
2227 SmallVector<EVT, 4> ValueVTs, MemVTs;
2228 SmallVector<uint64_t, 4> Offsets;
2229 ComputeValueVTs(TLI, DL, Ty: I.getOperand(i_nocapture: 0)->getType(), ValueVTs, MemVTs: &MemVTs,
2230 FixedOffsets: &Offsets, StartingOffset: 0);
2231 unsigned NumValues = ValueVTs.size();
2232
2233 SmallVector<SDValue, 4> Chains(NumValues);
2234 Align BaseAlign = DL.getPrefTypeAlign(Ty: I.getOperand(i_nocapture: 0)->getType());
2235 for (unsigned i = 0; i != NumValues; ++i) {
2236 // An aggregate return value cannot wrap around the address space, so
2237 // offsets to its parts don't wrap either.
2238 SDValue Ptr = DAG.getObjectPtrOffset(SL: getCurSDLoc(), Ptr: RetPtr,
2239 Offset: TypeSize::getFixed(ExactSize: Offsets[i]));
2240
2241 SDValue Val = RetOp.getValue(R: RetOp.getResNo() + i);
2242 if (MemVTs[i] != ValueVTs[i])
2243 Val = DAG.getPtrExtOrTrunc(Op: Val, DL: getCurSDLoc(), VT: MemVTs[i]);
2244 Chains[i] = DAG.getStore(
2245 Chain, dl: getCurSDLoc(), Val,
2246 // FIXME: better loc info would be nice.
2247 Ptr, PtrInfo: MachinePointerInfo::getUnknownStack(MF&: DAG.getMachineFunction()),
2248 Alignment: commonAlignment(A: BaseAlign, Offset: Offsets[i]));
2249 }
2250
2251 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: getCurSDLoc(),
2252 VT: MVT::Other, Ops: Chains);
2253 } else if (I.getNumOperands() != 0) {
2254 SmallVector<Type *, 4> Types;
2255 ComputeValueTypes(DL, Ty: I.getOperand(i_nocapture: 0)->getType(), Types);
2256 unsigned NumValues = Types.size();
2257 if (NumValues) {
2258 SDValue RetOp = getValue(V: I.getOperand(i_nocapture: 0));
2259
2260 const Function *F = I.getParent()->getParent();
2261
2262 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2263 Ty: I.getOperand(i_nocapture: 0)->getType(), CallConv: F->getCallingConv(),
2264 /*IsVarArg*/ isVarArg: false, DL);
2265
2266 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2267 if (F->getAttributes().hasRetAttr(Kind: Attribute::SExt))
2268 ExtendKind = ISD::SIGN_EXTEND;
2269 else if (F->getAttributes().hasRetAttr(Kind: Attribute::ZExt))
2270 ExtendKind = ISD::ZERO_EXTEND;
2271
2272 LLVMContext &Context = F->getContext();
2273 bool RetInReg = F->getAttributes().hasRetAttr(Kind: Attribute::InReg);
2274
2275 for (unsigned j = 0; j != NumValues; ++j) {
2276 EVT VT = TLI.getValueType(DL, Ty: Types[j]);
2277
2278 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2279 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2280
2281 CallingConv::ID CC = F->getCallingConv();
2282
2283 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2284 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2285 SmallVector<SDValue, 4> Parts(NumParts);
2286 getCopyToParts(DAG, DL: getCurSDLoc(),
2287 Val: SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2288 Parts: &Parts[0], NumParts, PartVT, V: &I, CallConv: CC, ExtendKind);
2289
2290 // 'inreg' on function refers to return value
2291 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2292 if (RetInReg)
2293 Flags.setInReg();
2294
2295 if (I.getOperand(i_nocapture: 0)->getType()->isPointerTy()) {
2296 Flags.setPointer();
2297 Flags.setPointerAddrSpace(
2298 cast<PointerType>(Val: I.getOperand(i_nocapture: 0)->getType())->getAddressSpace());
2299 }
2300
2301 if (NeedsRegBlock) {
2302 Flags.setInConsecutiveRegs();
2303 if (j == NumValues - 1)
2304 Flags.setInConsecutiveRegsLast();
2305 }
2306
2307 // Propagate extension type if any
2308 if (ExtendKind == ISD::SIGN_EXTEND)
2309 Flags.setSExt();
2310 else if (ExtendKind == ISD::ZERO_EXTEND)
2311 Flags.setZExt();
2312 else if (F->getAttributes().hasRetAttr(Kind: Attribute::NoExt))
2313 Flags.setNoExt();
2314
2315 for (unsigned i = 0; i < NumParts; ++i) {
2316 Outs.push_back(Elt: ISD::OutputArg(Flags,
2317 Parts[i].getValueType().getSimpleVT(),
2318 VT, Types[j], 0, 0));
2319 OutVals.push_back(Elt: Parts[i]);
2320 }
2321 }
2322 }
2323 }
2324
2325 // Push in swifterror virtual register as the last element of Outs. This makes
2326 // sure swifterror virtual register will be returned in the swifterror
2327 // physical register.
2328 const Function *F = I.getParent()->getParent();
2329 if (TLI.supportSwiftError() &&
2330 F->getAttributes().hasAttrSomewhere(Kind: Attribute::SwiftError)) {
2331 assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2332 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2333 Flags.setSwiftError();
2334 Outs.push_back(Elt: ISD::OutputArg(Flags, /*vt=*/TLI.getPointerTy(DL),
2335 /*argvt=*/EVT(TLI.getPointerTy(DL)),
2336 PointerType::getUnqual(C&: *DAG.getContext()),
2337 /*origidx=*/1, /*partOffs=*/0));
2338 // Create SDNode for the swifterror virtual register.
2339 OutVals.push_back(
2340 Elt: DAG.getRegister(Reg: SwiftError.getOrCreateVRegUseAt(
2341 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2342 VT: EVT(TLI.getPointerTy(DL))));
2343 }
2344
2345 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2346 CallingConv::ID CallConv =
2347 DAG.getMachineFunction().getFunction().getCallingConv();
2348 Chain = DAG.getTargetLoweringInfo().LowerReturn(
2349 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2350
2351 // Verify that the target's LowerReturn behaved as expected.
2352 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2353 "LowerReturn didn't return a valid chain!");
2354
2355 // Update the DAG with the new chain value resulting from return lowering.
2356 DAG.setRoot(Chain);
2357}
2358
2359/// CopyToExportRegsIfNeeded - If the given value has virtual registers
2360/// created for it, emit nodes to copy the value into the virtual
2361/// registers.
2362void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2363 // Skip empty types
2364 if (V->getType()->isEmptyTy())
2365 return;
2366
2367 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(Val: V);
2368 if (VMI != FuncInfo.ValueMap.end()) {
2369 assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2370 "Unused value assigned virtual registers!");
2371 CopyValueToVirtualRegister(V, Reg: VMI->second);
2372 }
2373}
2374
2375/// ExportFromCurrentBlock - If this condition isn't known to be exported from
2376/// the current basic block, add it to ValueMap now so that we'll get a
2377/// CopyTo/FromReg.
2378void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2379 // No need to export constants.
2380 if (!isa<Instruction>(Val: V) && !isa<Argument>(Val: V)) return;
2381
2382 // Already exported?
2383 if (FuncInfo.isExportedInst(V)) return;
2384
2385 Register Reg = FuncInfo.InitializeRegForValue(V);
2386 CopyValueToVirtualRegister(V, Reg);
2387}
2388
2389bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2390 const BasicBlock *FromBB) {
2391 // The operands of the setcc have to be in this block. We don't know
2392 // how to export them from some other block.
2393 if (const Instruction *VI = dyn_cast<Instruction>(Val: V)) {
2394 // Can export from current BB.
2395 if (VI->getParent() == FromBB)
2396 return true;
2397
2398 // Is already exported, noop.
2399 return FuncInfo.isExportedInst(V);
2400 }
2401
2402 // If this is an argument, we can export it if the BB is the entry block or
2403 // if it is already exported.
2404 if (isa<Argument>(Val: V)) {
2405 if (FromBB->isEntryBlock())
2406 return true;
2407
2408 // Otherwise, can only export this if it is already exported.
2409 return FuncInfo.isExportedInst(V);
2410 }
2411
2412 // Otherwise, constants can always be exported.
2413 return true;
2414}
2415
2416/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2417BranchProbability
2418SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2419 const MachineBasicBlock *Dst) const {
2420 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2421 const BasicBlock *SrcBB = Src->getBasicBlock();
2422 const BasicBlock *DstBB = Dst->getBasicBlock();
2423 if (!BPI) {
2424 // If BPI is not available, set the default probability as 1 / N, where N is
2425 // the number of successors.
2426 auto SuccSize = std::max<uint32_t>(a: succ_size(BB: SrcBB), b: 1);
2427 return BranchProbability(1, SuccSize);
2428 }
2429 return BPI->getEdgeProbability(Src: SrcBB, Dst: DstBB);
2430}
2431
2432void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2433 MachineBasicBlock *Dst,
2434 BranchProbability Prob) {
2435 if (!FuncInfo.BPI)
2436 Src->addSuccessorWithoutProb(Succ: Dst);
2437 else {
2438 if (Prob.isUnknown())
2439 Prob = getEdgeProbability(Src, Dst);
2440 Src->addSuccessor(Succ: Dst, Prob);
2441 }
2442}
2443
2444static bool InBlock(const Value *V, const BasicBlock *BB) {
2445 if (const Instruction *I = dyn_cast<Instruction>(Val: V))
2446 return I->getParent() == BB;
2447 return true;
2448}
2449
2450/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2451/// This function emits a branch and is used at the leaves of an OR or an
2452/// AND operator tree.
2453void
2454SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2455 MachineBasicBlock *TBB,
2456 MachineBasicBlock *FBB,
2457 MachineBasicBlock *CurBB,
2458 MachineBasicBlock *SwitchBB,
2459 BranchProbability TProb,
2460 BranchProbability FProb,
2461 bool InvertCond) {
2462 const BasicBlock *BB = CurBB->getBasicBlock();
2463
2464 // If the leaf of the tree is a comparison, merge the condition into
2465 // the caseblock.
2466 if (const CmpInst *BOp = dyn_cast<CmpInst>(Val: Cond)) {
2467 // The operands of the cmp have to be in this block. We don't know
2468 // how to export them from some other block. If this is the first block
2469 // of the sequence, no exporting is needed.
2470 if (CurBB == SwitchBB ||
2471 (isExportableFromCurrentBlock(V: BOp->getOperand(i_nocapture: 0), FromBB: BB) &&
2472 isExportableFromCurrentBlock(V: BOp->getOperand(i_nocapture: 1), FromBB: BB))) {
2473 ISD::CondCode Condition;
2474 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Val: Cond)) {
2475 ICmpInst::Predicate Pred =
2476 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2477 Condition = getICmpCondCode(Pred);
2478 } else {
2479 const FCmpInst *FC = cast<FCmpInst>(Val: Cond);
2480 FCmpInst::Predicate Pred =
2481 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2482 Condition = getFCmpCondCode(Pred);
2483 if (TM.Options.NoNaNsFPMath)
2484 Condition = getFCmpCodeWithoutNaN(CC: Condition);
2485 }
2486
2487 CaseBlock CB(Condition, BOp->getOperand(i_nocapture: 0), BOp->getOperand(i_nocapture: 1), nullptr,
2488 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2489 SL->SwitchCases.push_back(x: CB);
2490 return;
2491 }
2492 }
2493
2494 // Create a CaseBlock record representing this branch.
2495 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2496 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(Context&: *DAG.getContext()),
2497 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2498 SL->SwitchCases.push_back(x: CB);
2499}
2500
2501// Collect dependencies on V recursively. This is used for the cost analysis in
2502// `shouldKeepJumpConditionsTogether`.
2503static bool collectInstructionDeps(
2504 SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2505 SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2506 unsigned Depth = 0) {
2507 // Return false if we have an incomplete count.
2508 if (Depth >= SelectionDAG::MaxRecursionDepth)
2509 return false;
2510
2511 auto *I = dyn_cast<Instruction>(Val: V);
2512 if (I == nullptr)
2513 return true;
2514
2515 if (Necessary != nullptr) {
2516 // This instruction is necessary for the other side of the condition so
2517 // don't count it.
2518 if (Necessary->contains(Key: I))
2519 return true;
2520 }
2521
2522 // Already added this dep.
2523 if (!Deps->try_emplace(Key: I, Args: false).second)
2524 return true;
2525
2526 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2527 if (!collectInstructionDeps(Deps, V: I->getOperand(i: OpIdx), Necessary,
2528 Depth: Depth + 1))
2529 return false;
2530 return true;
2531}
2532
2533bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2534 const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2535 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2536 TargetLoweringBase::CondMergingParams Params) const {
2537 if (I.getNumSuccessors() != 2)
2538 return false;
2539
2540 if (!I.isConditional())
2541 return false;
2542
2543 if (Params.BaseCost < 0)
2544 return false;
2545
2546 // Baseline cost.
2547 InstructionCost CostThresh = Params.BaseCost;
2548
2549 BranchProbabilityInfo *BPI = nullptr;
2550 if (Params.LikelyBias || Params.UnlikelyBias)
2551 BPI = FuncInfo.BPI;
2552 if (BPI != nullptr) {
2553 // See if we are either likely to get an early out or compute both lhs/rhs
2554 // of the condition.
2555 BasicBlock *IfFalse = I.getSuccessor(i: 0);
2556 BasicBlock *IfTrue = I.getSuccessor(i: 1);
2557
2558 std::optional<bool> Likely;
2559 if (BPI->isEdgeHot(Src: I.getParent(), Dst: IfTrue))
2560 Likely = true;
2561 else if (BPI->isEdgeHot(Src: I.getParent(), Dst: IfFalse))
2562 Likely = false;
2563
2564 if (Likely) {
2565 if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2566 // Its likely we will have to compute both lhs and rhs of condition
2567 CostThresh += Params.LikelyBias;
2568 else {
2569 if (Params.UnlikelyBias < 0)
2570 return false;
2571 // Its likely we will get an early out.
2572 CostThresh -= Params.UnlikelyBias;
2573 }
2574 }
2575 }
2576
2577 if (CostThresh <= 0)
2578 return false;
2579
2580 // Collect "all" instructions that lhs condition is dependent on.
2581 // Use map for stable iteration (to avoid non-determanism of iteration of
2582 // SmallPtrSet). The `bool` value is just a dummy.
2583 SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2584 collectInstructionDeps(Deps: &LhsDeps, V: Lhs);
2585 // Collect "all" instructions that rhs condition is dependent on AND are
2586 // dependencies of lhs. This gives us an estimate on which instructions we
2587 // stand to save by splitting the condition.
2588 if (!collectInstructionDeps(Deps: &RhsDeps, V: Rhs, Necessary: &LhsDeps))
2589 return false;
2590 // Add the compare instruction itself unless its a dependency on the LHS.
2591 if (const auto *RhsI = dyn_cast<Instruction>(Val: Rhs))
2592 if (!LhsDeps.contains(Key: RhsI))
2593 RhsDeps.try_emplace(Key: RhsI, Args: false);
2594
2595 InstructionCost CostOfIncluding = 0;
2596 // See if this instruction will need to computed independently of whether RHS
2597 // is.
2598 Value *BrCond = I.getCondition();
2599 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2600 for (const auto *U : Ins->users()) {
2601 // If user is independent of RHS calculation we don't need to count it.
2602 if (auto *UIns = dyn_cast<Instruction>(Val: U))
2603 if (UIns != BrCond && !RhsDeps.contains(Key: UIns))
2604 return false;
2605 }
2606 return true;
2607 };
2608
2609 // Prune instructions from RHS Deps that are dependencies of unrelated
2610 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2611 // arbitrary and just meant to cap the how much time we spend in the pruning
2612 // loop. Its highly unlikely to come into affect.
2613 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2614 // Stop after a certain point. No incorrectness from including too many
2615 // instructions.
2616 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2617 const Instruction *ToDrop = nullptr;
2618 for (const auto &InsPair : RhsDeps) {
2619 if (!ShouldCountInsn(InsPair.first)) {
2620 ToDrop = InsPair.first;
2621 break;
2622 }
2623 }
2624 if (ToDrop == nullptr)
2625 break;
2626 RhsDeps.erase(Key: ToDrop);
2627 }
2628
2629 for (const auto &InsPair : RhsDeps) {
2630 // Finally accumulate latency that we can only attribute to computing the
2631 // RHS condition. Use latency because we are essentially trying to calculate
2632 // the cost of the dependency chain.
2633 // Possible TODO: We could try to estimate ILP and make this more precise.
2634 CostOfIncluding += TTI->getInstructionCost(
2635 U: InsPair.first, CostKind: TargetTransformInfo::TCK_Latency);
2636
2637 if (CostOfIncluding > CostThresh)
2638 return false;
2639 }
2640 return true;
2641}
2642
2643void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2644 MachineBasicBlock *TBB,
2645 MachineBasicBlock *FBB,
2646 MachineBasicBlock *CurBB,
2647 MachineBasicBlock *SwitchBB,
2648 Instruction::BinaryOps Opc,
2649 BranchProbability TProb,
2650 BranchProbability FProb,
2651 bool InvertCond) {
2652 // Skip over not part of the tree and remember to invert op and operands at
2653 // next level.
2654 Value *NotCond;
2655 if (match(V: Cond, P: m_OneUse(SubPattern: m_Not(V: m_Value(V&: NotCond)))) &&
2656 InBlock(V: NotCond, BB: CurBB->getBasicBlock())) {
2657 FindMergedConditions(Cond: NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2658 InvertCond: !InvertCond);
2659 return;
2660 }
2661
2662 const Instruction *BOp = dyn_cast<Instruction>(Val: Cond);
2663 const Value *BOpOp0, *BOpOp1;
2664 // Compute the effective opcode for Cond, taking into account whether it needs
2665 // to be inverted, e.g.
2666 // and (not (or A, B)), C
2667 // gets lowered as
2668 // and (and (not A, not B), C)
2669 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2670 if (BOp) {
2671 BOpc = match(V: BOp, P: m_LogicalAnd(L: m_Value(V&: BOpOp0), R: m_Value(V&: BOpOp1)))
2672 ? Instruction::And
2673 : (match(V: BOp, P: m_LogicalOr(L: m_Value(V&: BOpOp0), R: m_Value(V&: BOpOp1)))
2674 ? Instruction::Or
2675 : (Instruction::BinaryOps)0);
2676 if (InvertCond) {
2677 if (BOpc == Instruction::And)
2678 BOpc = Instruction::Or;
2679 else if (BOpc == Instruction::Or)
2680 BOpc = Instruction::And;
2681 }
2682 }
2683
2684 // If this node is not part of the or/and tree, emit it as a branch.
2685 // Note that all nodes in the tree should have same opcode.
2686 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2687 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2688 !InBlock(V: BOpOp0, BB: CurBB->getBasicBlock()) ||
2689 !InBlock(V: BOpOp1, BB: CurBB->getBasicBlock())) {
2690 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2691 TProb, FProb, InvertCond);
2692 return;
2693 }
2694
2695 // Create TmpBB after CurBB.
2696 MachineFunction::iterator BBI(CurBB);
2697 MachineFunction &MF = DAG.getMachineFunction();
2698 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(BB: CurBB->getBasicBlock());
2699 CurBB->getParent()->insert(MBBI: ++BBI, MBB: TmpBB);
2700
2701 if (Opc == Instruction::Or) {
2702 // Codegen X | Y as:
2703 // BB1:
2704 // jmp_if_X TBB
2705 // jmp TmpBB
2706 // TmpBB:
2707 // jmp_if_Y TBB
2708 // jmp FBB
2709 //
2710
2711 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2712 // The requirement is that
2713 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2714 // = TrueProb for original BB.
2715 // Assuming the original probabilities are A and B, one choice is to set
2716 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2717 // A/(1+B) and 2B/(1+B). This choice assumes that
2718 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2719 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2720 // TmpBB, but the math is more complicated.
2721
2722 auto NewTrueProb = TProb / 2;
2723 auto NewFalseProb = TProb / 2 + FProb;
2724 // Emit the LHS condition.
2725 FindMergedConditions(Cond: BOpOp0, TBB, FBB: TmpBB, CurBB, SwitchBB, Opc, TProb: NewTrueProb,
2726 FProb: NewFalseProb, InvertCond);
2727
2728 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2729 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2730 BranchProbability::normalizeProbabilities(Begin: Probs.begin(), End: Probs.end());
2731 // Emit the RHS condition into TmpBB.
2732 FindMergedConditions(Cond: BOpOp1, TBB, FBB, CurBB: TmpBB, SwitchBB, Opc, TProb: Probs[0],
2733 FProb: Probs[1], InvertCond);
2734 } else {
2735 assert(Opc == Instruction::And && "Unknown merge op!");
2736 // Codegen X & Y as:
2737 // BB1:
2738 // jmp_if_X TmpBB
2739 // jmp FBB
2740 // TmpBB:
2741 // jmp_if_Y TBB
2742 // jmp FBB
2743 //
2744 // This requires creation of TmpBB after CurBB.
2745
2746 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2747 // The requirement is that
2748 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2749 // = FalseProb for original BB.
2750 // Assuming the original probabilities are A and B, one choice is to set
2751 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2752 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2753 // TrueProb for BB1 * FalseProb for TmpBB.
2754
2755 auto NewTrueProb = TProb + FProb / 2;
2756 auto NewFalseProb = FProb / 2;
2757 // Emit the LHS condition.
2758 FindMergedConditions(Cond: BOpOp0, TBB: TmpBB, FBB, CurBB, SwitchBB, Opc, TProb: NewTrueProb,
2759 FProb: NewFalseProb, InvertCond);
2760
2761 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2762 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2763 BranchProbability::normalizeProbabilities(Begin: Probs.begin(), End: Probs.end());
2764 // Emit the RHS condition into TmpBB.
2765 FindMergedConditions(Cond: BOpOp1, TBB, FBB, CurBB: TmpBB, SwitchBB, Opc, TProb: Probs[0],
2766 FProb: Probs[1], InvertCond);
2767 }
2768}
2769
2770/// If the set of cases should be emitted as a series of branches, return true.
2771/// If we should emit this as a bunch of and/or'd together conditions, return
2772/// false.
2773bool
2774SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2775 if (Cases.size() != 2) return true;
2776
2777 // If this is two comparisons of the same values or'd or and'd together, they
2778 // will get folded into a single comparison, so don't emit two blocks.
2779 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2780 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2781 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2782 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2783 return false;
2784 }
2785
2786 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2787 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2788 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2789 Cases[0].CC == Cases[1].CC &&
2790 isa<Constant>(Val: Cases[0].CmpRHS) &&
2791 cast<Constant>(Val: Cases[0].CmpRHS)->isNullValue()) {
2792 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2793 return false;
2794 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2795 return false;
2796 }
2797
2798 return true;
2799}
2800
2801void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2802 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2803
2804 // Update machine-CFG edges.
2805 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(BB: I.getSuccessor(i: 0));
2806
2807 if (I.isUnconditional()) {
2808 // Update machine-CFG edges.
2809 BrMBB->addSuccessor(Succ: Succ0MBB);
2810
2811 // If this is not a fall-through branch or optimizations are switched off,
2812 // emit the branch.
2813 if (Succ0MBB != NextBlock(MBB: BrMBB) ||
2814 TM.getOptLevel() == CodeGenOptLevel::None) {
2815 auto Br = DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other,
2816 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: Succ0MBB));
2817 setValue(V: &I, NewN: Br);
2818 DAG.setRoot(Br);
2819 }
2820
2821 return;
2822 }
2823
2824 // If this condition is one of the special cases we handle, do special stuff
2825 // now.
2826 const Value *CondVal = I.getCondition();
2827 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(BB: I.getSuccessor(i: 1));
2828
2829 // If this is a series of conditions that are or'd or and'd together, emit
2830 // this as a sequence of branches instead of setcc's with and/or operations.
2831 // As long as jumps are not expensive (exceptions for multi-use logic ops,
2832 // unpredictable branches, and vector extracts because those jumps are likely
2833 // expensive for any target), this should improve performance.
2834 // For example, instead of something like:
2835 // cmp A, B
2836 // C = seteq
2837 // cmp D, E
2838 // F = setle
2839 // or C, F
2840 // jnz foo
2841 // Emit:
2842 // cmp A, B
2843 // je foo
2844 // cmp D, E
2845 // jle foo
2846 bool IsUnpredictable = I.hasMetadata(KindID: LLVMContext::MD_unpredictable);
2847 const Instruction *BOp = dyn_cast<Instruction>(Val: CondVal);
2848 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2849 BOp->hasOneUse() && !IsUnpredictable) {
2850 Value *Vec;
2851 const Value *BOp0, *BOp1;
2852 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2853 if (match(V: BOp, P: m_LogicalAnd(L: m_Value(V&: BOp0), R: m_Value(V&: BOp1))))
2854 Opcode = Instruction::And;
2855 else if (match(V: BOp, P: m_LogicalOr(L: m_Value(V&: BOp0), R: m_Value(V&: BOp1))))
2856 Opcode = Instruction::Or;
2857
2858 if (Opcode &&
2859 !(match(V: BOp0, P: m_ExtractElt(Val: m_Value(V&: Vec), Idx: m_Value())) &&
2860 match(V: BOp1, P: m_ExtractElt(Val: m_Specific(V: Vec), Idx: m_Value()))) &&
2861 !shouldKeepJumpConditionsTogether(
2862 FuncInfo, I, Opc: Opcode, Lhs: BOp0, Rhs: BOp1,
2863 Params: DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2864 Opcode, BOp0, BOp1))) {
2865 FindMergedConditions(Cond: BOp, TBB: Succ0MBB, FBB: Succ1MBB, CurBB: BrMBB, SwitchBB: BrMBB, Opc: Opcode,
2866 TProb: getEdgeProbability(Src: BrMBB, Dst: Succ0MBB),
2867 FProb: getEdgeProbability(Src: BrMBB, Dst: Succ1MBB),
2868 /*InvertCond=*/false);
2869 // If the compares in later blocks need to use values not currently
2870 // exported from this block, export them now. This block should always
2871 // be the first entry.
2872 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2873
2874 // Allow some cases to be rejected.
2875 if (ShouldEmitAsBranches(Cases: SL->SwitchCases)) {
2876 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2877 ExportFromCurrentBlock(V: SL->SwitchCases[i].CmpLHS);
2878 ExportFromCurrentBlock(V: SL->SwitchCases[i].CmpRHS);
2879 }
2880
2881 // Emit the branch for this block.
2882 visitSwitchCase(CB&: SL->SwitchCases[0], SwitchBB: BrMBB);
2883 SL->SwitchCases.erase(position: SL->SwitchCases.begin());
2884 return;
2885 }
2886
2887 // Okay, we decided not to do this, remove any inserted MBB's and clear
2888 // SwitchCases.
2889 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2890 FuncInfo.MF->erase(MBBI: SL->SwitchCases[i].ThisBB);
2891
2892 SL->SwitchCases.clear();
2893 }
2894 }
2895
2896 // Create a CaseBlock record representing this branch.
2897 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(Context&: *DAG.getContext()),
2898 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2899 BranchProbability::getUnknown(), BranchProbability::getUnknown(),
2900 IsUnpredictable);
2901
2902 // Use visitSwitchCase to actually insert the fast branch sequence for this
2903 // cond branch.
2904 visitSwitchCase(CB, SwitchBB: BrMBB);
2905}
2906
2907/// visitSwitchCase - Emits the necessary code to represent a single node in
2908/// the binary search tree resulting from lowering a switch instruction.
2909void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2910 MachineBasicBlock *SwitchBB) {
2911 SDValue Cond;
2912 SDValue CondLHS = getValue(V: CB.CmpLHS);
2913 SDLoc dl = CB.DL;
2914
2915 if (CB.CC == ISD::SETTRUE) {
2916 // Branch or fall through to TrueBB.
2917 addSuccessorWithProb(Src: SwitchBB, Dst: CB.TrueBB, Prob: CB.TrueProb);
2918 SwitchBB->normalizeSuccProbs();
2919 if (CB.TrueBB != NextBlock(MBB: SwitchBB)) {
2920 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: getControlRoot(),
2921 N2: DAG.getBasicBlock(MBB: CB.TrueBB)));
2922 }
2923 return;
2924 }
2925
2926 auto &TLI = DAG.getTargetLoweringInfo();
2927 EVT MemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: CB.CmpLHS->getType());
2928
2929 // Build the setcc now.
2930 if (!CB.CmpMHS) {
2931 // Fold "(X == true)" to X and "(X == false)" to !X to
2932 // handle common cases produced by branch lowering.
2933 if (CB.CmpRHS == ConstantInt::getTrue(Context&: *DAG.getContext()) &&
2934 CB.CC == ISD::SETEQ)
2935 Cond = CondLHS;
2936 else if (CB.CmpRHS == ConstantInt::getFalse(Context&: *DAG.getContext()) &&
2937 CB.CC == ISD::SETEQ) {
2938 SDValue True = DAG.getConstant(Val: 1, DL: dl, VT: CondLHS.getValueType());
2939 Cond = DAG.getNode(Opcode: ISD::XOR, DL: dl, VT: CondLHS.getValueType(), N1: CondLHS, N2: True);
2940 } else {
2941 SDValue CondRHS = getValue(V: CB.CmpRHS);
2942
2943 // If a pointer's DAG type is larger than its memory type then the DAG
2944 // values are zero-extended. This breaks signed comparisons so truncate
2945 // back to the underlying type before doing the compare.
2946 if (CondLHS.getValueType() != MemVT) {
2947 CondLHS = DAG.getPtrExtOrTrunc(Op: CondLHS, DL: getCurSDLoc(), VT: MemVT);
2948 CondRHS = DAG.getPtrExtOrTrunc(Op: CondRHS, DL: getCurSDLoc(), VT: MemVT);
2949 }
2950 Cond = DAG.getSetCC(DL: dl, VT: MVT::i1, LHS: CondLHS, RHS: CondRHS, Cond: CB.CC);
2951 }
2952 } else {
2953 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2954
2955 const APInt& Low = cast<ConstantInt>(Val: CB.CmpLHS)->getValue();
2956 const APInt& High = cast<ConstantInt>(Val: CB.CmpRHS)->getValue();
2957
2958 SDValue CmpOp = getValue(V: CB.CmpMHS);
2959 EVT VT = CmpOp.getValueType();
2960
2961 if (cast<ConstantInt>(Val: CB.CmpLHS)->isMinValue(IsSigned: true)) {
2962 Cond = DAG.getSetCC(DL: dl, VT: MVT::i1, LHS: CmpOp, RHS: DAG.getConstant(Val: High, DL: dl, VT),
2963 Cond: ISD::SETLE);
2964 } else {
2965 SDValue SUB = DAG.getNode(Opcode: ISD::SUB, DL: dl,
2966 VT, N1: CmpOp, N2: DAG.getConstant(Val: Low, DL: dl, VT));
2967 Cond = DAG.getSetCC(DL: dl, VT: MVT::i1, LHS: SUB,
2968 RHS: DAG.getConstant(Val: High-Low, DL: dl, VT), Cond: ISD::SETULE);
2969 }
2970 }
2971
2972 // Update successor info
2973 addSuccessorWithProb(Src: SwitchBB, Dst: CB.TrueBB, Prob: CB.TrueProb);
2974 // TrueBB and FalseBB are always different unless the incoming IR is
2975 // degenerate. This only happens when running llc on weird IR.
2976 if (CB.TrueBB != CB.FalseBB)
2977 addSuccessorWithProb(Src: SwitchBB, Dst: CB.FalseBB, Prob: CB.FalseProb);
2978 SwitchBB->normalizeSuccProbs();
2979
2980 // If the lhs block is the next block, invert the condition so that we can
2981 // fall through to the lhs instead of the rhs block.
2982 if (CB.TrueBB == NextBlock(MBB: SwitchBB)) {
2983 std::swap(a&: CB.TrueBB, b&: CB.FalseBB);
2984 SDValue True = DAG.getConstant(Val: 1, DL: dl, VT: Cond.getValueType());
2985 Cond = DAG.getNode(Opcode: ISD::XOR, DL: dl, VT: Cond.getValueType(), N1: Cond, N2: True);
2986 }
2987
2988 SDNodeFlags Flags;
2989 Flags.setUnpredictable(CB.IsUnpredictable);
2990 SDValue BrCond = DAG.getNode(Opcode: ISD::BRCOND, DL: dl, VT: MVT::Other, N1: getControlRoot(),
2991 N2: Cond, N3: DAG.getBasicBlock(MBB: CB.TrueBB), Flags);
2992
2993 setValue(V: CurInst, NewN: BrCond);
2994
2995 // Insert the false branch. Do this even if it's a fall through branch,
2996 // this makes it easier to do DAG optimizations which require inverting
2997 // the branch condition.
2998 BrCond = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: BrCond,
2999 N2: DAG.getBasicBlock(MBB: CB.FalseBB));
3000
3001 DAG.setRoot(BrCond);
3002}
3003
3004/// visitJumpTable - Emit JumpTable node in the current MBB
3005void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
3006 // Emit the code for the jump table
3007 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3008 assert(JT.Reg && "Should lower JT Header first!");
3009 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DL: DAG.getDataLayout());
3010 SDValue Index = DAG.getCopyFromReg(Chain: getControlRoot(), dl: *JT.SL, Reg: JT.Reg, VT: PTy);
3011 SDValue Table = DAG.getJumpTable(JTI: JT.JTI, VT: PTy);
3012 SDValue BrJumpTable = DAG.getNode(Opcode: ISD::BR_JT, DL: *JT.SL, VT: MVT::Other,
3013 N1: Index.getValue(R: 1), N2: Table, N3: Index);
3014 DAG.setRoot(BrJumpTable);
3015}
3016
3017/// visitJumpTableHeader - This function emits necessary code to produce index
3018/// in the JumpTable from switch case.
3019void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
3020 JumpTableHeader &JTH,
3021 MachineBasicBlock *SwitchBB) {
3022 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3023 const SDLoc &dl = *JT.SL;
3024
3025 // Subtract the lowest switch case value from the value being switched on.
3026 SDValue SwitchOp = getValue(V: JTH.SValue);
3027 EVT VT = SwitchOp.getValueType();
3028 SDValue Sub = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: SwitchOp,
3029 N2: DAG.getConstant(Val: JTH.First, DL: dl, VT));
3030
3031 // The SDNode we just created, which holds the value being switched on minus
3032 // the smallest case value, needs to be copied to a virtual register so it
3033 // can be used as an index into the jump table in a subsequent basic block.
3034 // This value may be smaller or larger than the target's pointer type, and
3035 // therefore require extension or truncating.
3036 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3037 SwitchOp =
3038 DAG.getZExtOrTrunc(Op: Sub, DL: dl, VT: TLI.getJumpTableRegTy(DL: DAG.getDataLayout()));
3039
3040 Register JumpTableReg =
3041 FuncInfo.CreateReg(VT: TLI.getJumpTableRegTy(DL: DAG.getDataLayout()));
3042 SDValue CopyTo =
3043 DAG.getCopyToReg(Chain: getControlRoot(), dl, Reg: JumpTableReg, N: SwitchOp);
3044 JT.Reg = JumpTableReg;
3045
3046 if (!JTH.FallthroughUnreachable) {
3047 // Emit the range check for the jump table, and branch to the default block
3048 // for the switch statement if the value being switched on exceeds the
3049 // largest case in the switch.
3050 SDValue CMP = DAG.getSetCC(
3051 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(),
3052 VT: Sub.getValueType()),
3053 LHS: Sub, RHS: DAG.getConstant(Val: JTH.Last - JTH.First, DL: dl, VT), Cond: ISD::SETUGT);
3054
3055 SDValue BrCond = DAG.getNode(Opcode: ISD::BRCOND, DL: dl,
3056 VT: MVT::Other, N1: CopyTo, N2: CMP,
3057 N3: DAG.getBasicBlock(MBB: JT.Default));
3058
3059 // Avoid emitting unnecessary branches to the next block.
3060 if (JT.MBB != NextBlock(MBB: SwitchBB))
3061 BrCond = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: BrCond,
3062 N2: DAG.getBasicBlock(MBB: JT.MBB));
3063
3064 DAG.setRoot(BrCond);
3065 } else {
3066 // Avoid emitting unnecessary branches to the next block.
3067 if (JT.MBB != NextBlock(MBB: SwitchBB))
3068 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: CopyTo,
3069 N2: DAG.getBasicBlock(MBB: JT.MBB)));
3070 else
3071 DAG.setRoot(CopyTo);
3072 }
3073}
3074
3075/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3076/// variable if there exists one.
3077static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3078 SDValue &Chain) {
3079 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3080 EVT PtrTy = TLI.getPointerTy(DL: DAG.getDataLayout());
3081 EVT PtrMemTy = TLI.getPointerMemTy(DL: DAG.getDataLayout());
3082 MachineFunction &MF = DAG.getMachineFunction();
3083 Value *Global =
3084 TLI.getSDagStackGuard(M: *MF.getFunction().getParent(), Libcalls: DAG.getLibcalls());
3085 MachineSDNode *Node =
3086 DAG.getMachineNode(Opcode: TargetOpcode::LOAD_STACK_GUARD, dl: DL, VT: PtrTy, Op1: Chain);
3087 if (Global) {
3088 MachinePointerInfo MPInfo(Global);
3089 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3090 MachineMemOperand::MODereferenceable;
3091 MachineMemOperand *MemRef = MF.getMachineMemOperand(
3092 PtrInfo: MPInfo, F: Flags, Size: PtrTy.getSizeInBits() / 8, BaseAlignment: DAG.getEVTAlign(MemoryVT: PtrTy));
3093 DAG.setNodeMemRefs(N: Node, NewMemRefs: {MemRef});
3094 }
3095 if (PtrTy != PtrMemTy)
3096 return DAG.getPtrExtOrTrunc(Op: SDValue(Node, 0), DL, VT: PtrMemTy);
3097 return SDValue(Node, 0);
3098}
3099
3100/// Codegen a new tail for a stack protector check ParentMBB which has had its
3101/// tail spliced into a stack protector check success bb.
3102///
3103/// For a high level explanation of how this fits into the stack protector
3104/// generation see the comment on the declaration of class
3105/// StackProtectorDescriptor.
3106void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3107 MachineBasicBlock *ParentBB) {
3108
3109 // First create the loads to the guard/stack slot for the comparison.
3110 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3111 auto &DL = DAG.getDataLayout();
3112 EVT PtrTy = TLI.getFrameIndexTy(DL);
3113 EVT PtrMemTy = TLI.getPointerMemTy(DL, AS: DL.getAllocaAddrSpace());
3114
3115 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3116 int FI = MFI.getStackProtectorIndex();
3117
3118 SDValue Guard;
3119 SDLoc dl = getCurSDLoc();
3120 SDValue StackSlotPtr = DAG.getFrameIndex(FI, VT: PtrTy);
3121 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3122 Align Align = DL.getPrefTypeAlign(
3123 Ty: PointerType::get(C&: M.getContext(), AddressSpace: DL.getAllocaAddrSpace()));
3124
3125 // Generate code to load the content of the guard slot.
3126 SDValue GuardVal = DAG.getLoad(
3127 VT: PtrMemTy, dl, Chain: DAG.getEntryNode(), Ptr: StackSlotPtr,
3128 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI), Alignment: Align,
3129 MMOFlags: MachineMemOperand::MOVolatile);
3130
3131 if (TLI.useStackGuardXorFP())
3132 GuardVal = TLI.emitStackGuardXorFP(DAG, Val: GuardVal, DL: dl);
3133
3134 // If we're using function-based instrumentation, call the guard check
3135 // function
3136 if (SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3137 // Get the guard check function from the target and verify it exists since
3138 // we're using function-based instrumentation
3139 const Function *GuardCheckFn =
3140 TLI.getSSPStackGuardCheck(M, Libcalls: DAG.getLibcalls());
3141 assert(GuardCheckFn && "Guard check function is null");
3142
3143 // The target provides a guard check function to validate the guard value.
3144 // Generate a call to that function with the content of the guard slot as
3145 // argument.
3146 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3147 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3148
3149 TargetLowering::ArgListTy Args;
3150 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(i: 0));
3151 if (GuardCheckFn->hasParamAttribute(ArgNo: 0, Kind: Attribute::AttrKind::InReg))
3152 Entry.IsInReg = true;
3153 Args.push_back(x: Entry);
3154
3155 TargetLowering::CallLoweringInfo CLI(DAG);
3156 CLI.setDebugLoc(getCurSDLoc())
3157 .setChain(DAG.getEntryNode())
3158 .setCallee(CC: GuardCheckFn->getCallingConv(), ResultType: FnTy->getReturnType(),
3159 Target: getValue(V: GuardCheckFn), ArgsList: std::move(Args));
3160
3161 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3162 DAG.setRoot(Result.second);
3163 return;
3164 }
3165
3166 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3167 // Otherwise, emit a volatile load to retrieve the stack guard value.
3168 SDValue Chain = DAG.getEntryNode();
3169 if (TLI.useLoadStackGuardNode(M)) {
3170 Guard = getLoadStackGuard(DAG, DL: dl, Chain);
3171 } else {
3172 if (const Value *IRGuard = TLI.getSDagStackGuard(M, Libcalls: DAG.getLibcalls())) {
3173 SDValue GuardPtr = getValue(V: IRGuard);
3174 Guard = DAG.getLoad(VT: PtrMemTy, dl, Chain, Ptr: GuardPtr,
3175 PtrInfo: MachinePointerInfo(IRGuard, 0), Alignment: Align,
3176 MMOFlags: MachineMemOperand::MOVolatile);
3177 } else {
3178 LLVMContext &Ctx = *DAG.getContext();
3179 Ctx.diagnose(DI: DiagnosticInfoGeneric("unable to lower stackguard"));
3180 Guard = DAG.getPOISON(VT: PtrMemTy);
3181 }
3182 }
3183
3184 // Perform the comparison via a getsetcc.
3185 SDValue Cmp = DAG.getSetCC(
3186 DL: dl, VT: TLI.getSetCCResultType(DL, Context&: *DAG.getContext(), VT: Guard.getValueType()),
3187 LHS: Guard, RHS: GuardVal, Cond: ISD::SETNE);
3188
3189 // If the guard/stackslot do not equal, branch to failure MBB.
3190 SDValue BrCond = DAG.getNode(Opcode: ISD::BRCOND, DL: dl, VT: MVT::Other, N1: getControlRoot(),
3191 N2: Cmp, N3: DAG.getBasicBlock(MBB: SPD.getFailureMBB()));
3192 // Otherwise branch to success MBB.
3193 SDValue Br = DAG.getNode(Opcode: ISD::BR, DL: dl,
3194 VT: MVT::Other, N1: BrCond,
3195 N2: DAG.getBasicBlock(MBB: SPD.getSuccessMBB()));
3196
3197 DAG.setRoot(Br);
3198}
3199
3200/// Codegen the failure basic block for a stack protector check.
3201///
3202/// A failure stack protector machine basic block consists simply of a call to
3203/// __stack_chk_fail().
3204///
3205/// For a high level explanation of how this fits into the stack protector
3206/// generation see the comment on the declaration of class
3207/// StackProtectorDescriptor.
3208void SelectionDAGBuilder::visitSPDescriptorFailure(
3209 StackProtectorDescriptor &SPD) {
3210
3211 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3212 MachineBasicBlock *ParentBB = SPD.getParentMBB();
3213 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3214 SDValue Chain;
3215
3216 // For -Oz builds with a guard check function, we use function-based
3217 // instrumentation. Otherwise, if we have a guard check function, we call it
3218 // in the failure block.
3219 auto *GuardCheckFn = TLI.getSSPStackGuardCheck(M, Libcalls: DAG.getLibcalls());
3220 if (GuardCheckFn && !SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3221 // First create the loads to the guard/stack slot for the comparison.
3222 auto &DL = DAG.getDataLayout();
3223 EVT PtrTy = TLI.getFrameIndexTy(DL);
3224 EVT PtrMemTy = TLI.getPointerMemTy(DL, AS: DL.getAllocaAddrSpace());
3225
3226 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3227 int FI = MFI.getStackProtectorIndex();
3228
3229 SDLoc dl = getCurSDLoc();
3230 SDValue StackSlotPtr = DAG.getFrameIndex(FI, VT: PtrTy);
3231 Align Align = DL.getPrefTypeAlign(
3232 Ty: PointerType::get(C&: M.getContext(), AddressSpace: DL.getAllocaAddrSpace()));
3233
3234 // Generate code to load the content of the guard slot.
3235 SDValue GuardVal = DAG.getLoad(
3236 VT: PtrMemTy, dl, Chain: DAG.getEntryNode(), Ptr: StackSlotPtr,
3237 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI), Alignment: Align,
3238 MMOFlags: MachineMemOperand::MOVolatile);
3239
3240 if (TLI.useStackGuardXorFP())
3241 GuardVal = TLI.emitStackGuardXorFP(DAG, Val: GuardVal, DL: dl);
3242
3243 // The target provides a guard check function to validate the guard value.
3244 // Generate a call to that function with the content of the guard slot as
3245 // argument.
3246 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3247 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3248
3249 TargetLowering::ArgListTy Args;
3250 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(i: 0));
3251 if (GuardCheckFn->hasParamAttribute(ArgNo: 0, Kind: Attribute::AttrKind::InReg))
3252 Entry.IsInReg = true;
3253 Args.push_back(x: Entry);
3254
3255 TargetLowering::CallLoweringInfo CLI(DAG);
3256 CLI.setDebugLoc(getCurSDLoc())
3257 .setChain(DAG.getEntryNode())
3258 .setCallee(CC: GuardCheckFn->getCallingConv(), ResultType: FnTy->getReturnType(),
3259 Target: getValue(V: GuardCheckFn), ArgsList: std::move(Args));
3260
3261 Chain = TLI.LowerCallTo(CLI).second;
3262 } else {
3263 TargetLowering::MakeLibCallOptions CallOptions;
3264 CallOptions.setDiscardResult(true);
3265 Chain = TLI.makeLibCall(DAG, LC: RTLIB::STACKPROTECTOR_CHECK_FAIL, RetVT: MVT::isVoid,
3266 Ops: {}, CallOptions, dl: getCurSDLoc())
3267 .second;
3268 }
3269
3270 // Emit a trap instruction if we are required to do so.
3271 const TargetOptions &TargetOpts = DAG.getTarget().Options;
3272 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3273 Chain = DAG.getNode(Opcode: ISD::TRAP, DL: getCurSDLoc(), VT: MVT::Other, Operand: Chain);
3274
3275 DAG.setRoot(Chain);
3276}
3277
3278/// visitBitTestHeader - This function emits necessary code to produce value
3279/// suitable for "bit tests"
3280void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3281 MachineBasicBlock *SwitchBB) {
3282 SDLoc dl = getCurSDLoc();
3283
3284 // Subtract the minimum value.
3285 SDValue SwitchOp = getValue(V: B.SValue);
3286 EVT VT = SwitchOp.getValueType();
3287 SDValue RangeSub =
3288 DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: SwitchOp, N2: DAG.getConstant(Val: B.First, DL: dl, VT));
3289
3290 // Determine the type of the test operands.
3291 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3292 bool UsePtrType = false;
3293 if (!TLI.isTypeLegal(VT)) {
3294 UsePtrType = true;
3295 } else {
3296 for (const BitTestCase &Case : B.Cases)
3297 if (!isUIntN(N: VT.getSizeInBits(), x: Case.Mask)) {
3298 // Switch table case range are encoded into series of masks.
3299 // Just use pointer type, it's guaranteed to fit.
3300 UsePtrType = true;
3301 break;
3302 }
3303 }
3304 SDValue Sub = RangeSub;
3305 if (UsePtrType) {
3306 VT = TLI.getPointerTy(DL: DAG.getDataLayout());
3307 Sub = DAG.getZExtOrTrunc(Op: Sub, DL: dl, VT);
3308 }
3309
3310 B.RegVT = VT.getSimpleVT();
3311 B.Reg = FuncInfo.CreateReg(VT: B.RegVT);
3312 SDValue CopyTo = DAG.getCopyToReg(Chain: getControlRoot(), dl, Reg: B.Reg, N: Sub);
3313
3314 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3315
3316 if (!B.FallthroughUnreachable)
3317 addSuccessorWithProb(Src: SwitchBB, Dst: B.Default, Prob: B.DefaultProb);
3318 addSuccessorWithProb(Src: SwitchBB, Dst: MBB, Prob: B.Prob);
3319 SwitchBB->normalizeSuccProbs();
3320
3321 SDValue Root = CopyTo;
3322 if (!B.FallthroughUnreachable) {
3323 // Conditional branch to the default block.
3324 SDValue RangeCmp = DAG.getSetCC(DL: dl,
3325 VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(),
3326 VT: RangeSub.getValueType()),
3327 LHS: RangeSub, RHS: DAG.getConstant(Val: B.Range, DL: dl, VT: RangeSub.getValueType()),
3328 Cond: ISD::SETUGT);
3329
3330 Root = DAG.getNode(Opcode: ISD::BRCOND, DL: dl, VT: MVT::Other, N1: Root, N2: RangeCmp,
3331 N3: DAG.getBasicBlock(MBB: B.Default));
3332 }
3333
3334 // Avoid emitting unnecessary branches to the next block.
3335 if (MBB != NextBlock(MBB: SwitchBB))
3336 Root = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: Root, N2: DAG.getBasicBlock(MBB));
3337
3338 DAG.setRoot(Root);
3339}
3340
3341/// visitBitTestCase - this function produces one "bit test"
3342void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3343 MachineBasicBlock *NextMBB,
3344 BranchProbability BranchProbToNext,
3345 Register Reg, BitTestCase &B,
3346 MachineBasicBlock *SwitchBB) {
3347 SDLoc dl = getCurSDLoc();
3348 MVT VT = BB.RegVT;
3349 SDValue ShiftOp = DAG.getCopyFromReg(Chain: getControlRoot(), dl, Reg, VT);
3350 SDValue Cmp;
3351 unsigned PopCount = llvm::popcount(Value: B.Mask);
3352 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3353 if (PopCount == 1) {
3354 // Testing for a single bit; just compare the shift count with what it
3355 // would need to be to shift a 1 bit in that position.
3356 Cmp = DAG.getSetCC(
3357 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(), VT),
3358 LHS: ShiftOp, RHS: DAG.getConstant(Val: llvm::countr_zero(Val: B.Mask), DL: dl, VT),
3359 Cond: ISD::SETEQ);
3360 } else if (PopCount == BB.Range) {
3361 // There is only one zero bit in the range, test for it directly.
3362 Cmp = DAG.getSetCC(
3363 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(), VT),
3364 LHS: ShiftOp, RHS: DAG.getConstant(Val: llvm::countr_one(Value: B.Mask), DL: dl, VT), Cond: ISD::SETNE);
3365 } else {
3366 // Make desired shift
3367 SDValue SwitchVal = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT,
3368 N1: DAG.getConstant(Val: 1, DL: dl, VT), N2: ShiftOp);
3369
3370 // Emit bit tests and jumps
3371 SDValue AndOp = DAG.getNode(Opcode: ISD::AND, DL: dl,
3372 VT, N1: SwitchVal, N2: DAG.getConstant(Val: B.Mask, DL: dl, VT));
3373 Cmp = DAG.getSetCC(
3374 DL: dl, VT: TLI.getSetCCResultType(DL: DAG.getDataLayout(), Context&: *DAG.getContext(), VT),
3375 LHS: AndOp, RHS: DAG.getConstant(Val: 0, DL: dl, VT), Cond: ISD::SETNE);
3376 }
3377
3378 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3379 addSuccessorWithProb(Src: SwitchBB, Dst: B.TargetBB, Prob: B.ExtraProb);
3380 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3381 addSuccessorWithProb(Src: SwitchBB, Dst: NextMBB, Prob: BranchProbToNext);
3382 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3383 // one as they are relative probabilities (and thus work more like weights),
3384 // and hence we need to normalize them to let the sum of them become one.
3385 SwitchBB->normalizeSuccProbs();
3386
3387 SDValue BrAnd = DAG.getNode(Opcode: ISD::BRCOND, DL: dl,
3388 VT: MVT::Other, N1: getControlRoot(),
3389 N2: Cmp, N3: DAG.getBasicBlock(MBB: B.TargetBB));
3390
3391 // Avoid emitting unnecessary branches to the next block.
3392 if (NextMBB != NextBlock(MBB: SwitchBB))
3393 BrAnd = DAG.getNode(Opcode: ISD::BR, DL: dl, VT: MVT::Other, N1: BrAnd,
3394 N2: DAG.getBasicBlock(MBB: NextMBB));
3395
3396 DAG.setRoot(BrAnd);
3397}
3398
3399void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3400 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3401
3402 // Retrieve successors. Look through artificial IR level blocks like
3403 // catchswitch for successors.
3404 MachineBasicBlock *Return = FuncInfo.getMBB(BB: I.getSuccessor(i: 0));
3405 const BasicBlock *EHPadBB = I.getSuccessor(i: 1);
3406 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(BB: EHPadBB);
3407
3408 // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3409 // have to do anything here to lower funclet bundles.
3410 failForInvalidBundles(I, Name: "invokes",
3411 AllowedBundles: {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3412 LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3413 LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3414 LLVMContext::OB_clang_arc_attachedcall,
3415 LLVMContext::OB_kcfi});
3416
3417 const Value *Callee(I.getCalledOperand());
3418 const Function *Fn = dyn_cast<Function>(Val: Callee);
3419 if (isa<InlineAsm>(Val: Callee))
3420 visitInlineAsm(Call: I, EHPadBB);
3421 else if (Fn && Fn->isIntrinsic()) {
3422 switch (Fn->getIntrinsicID()) {
3423 default:
3424 llvm_unreachable("Cannot invoke this intrinsic");
3425 case Intrinsic::donothing:
3426 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3427 case Intrinsic::seh_try_begin:
3428 case Intrinsic::seh_scope_begin:
3429 case Intrinsic::seh_try_end:
3430 case Intrinsic::seh_scope_end:
3431 if (EHPadMBB)
3432 // a block referenced by EH table
3433 // so dtor-funclet not removed by opts
3434 EHPadMBB->setMachineBlockAddressTaken();
3435 break;
3436 case Intrinsic::experimental_patchpoint_void:
3437 case Intrinsic::experimental_patchpoint:
3438 visitPatchpoint(CB: I, EHPadBB);
3439 break;
3440 case Intrinsic::experimental_gc_statepoint:
3441 LowerStatepoint(I: cast<GCStatepointInst>(Val: I), EHPadBB);
3442 break;
3443 // wasm_throw, wasm_rethrow: This is usually done in visitTargetIntrinsic,
3444 // but these intrinsics are special because they can be invoked, so we
3445 // manually lower it to a DAG node here.
3446 case Intrinsic::wasm_throw: {
3447 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3448 std::array<SDValue, 4> Ops = {
3449 getControlRoot(), // inchain for the terminator node
3450 DAG.getTargetConstant(Val: Intrinsic::wasm_throw, DL: getCurSDLoc(),
3451 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
3452 getValue(V: I.getArgOperand(i: 0)), // tag
3453 getValue(V: I.getArgOperand(i: 1)) // thrown value
3454 };
3455 SDVTList VTs = DAG.getVTList(VTs: ArrayRef<EVT>({MVT::Other})); // outchain
3456 DAG.setRoot(DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL: getCurSDLoc(), VTList: VTs, Ops));
3457 break;
3458 }
3459 case Intrinsic::wasm_rethrow: {
3460 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3461 std::array<SDValue, 2> Ops = {
3462 getControlRoot(), // inchain for the terminator node
3463 DAG.getTargetConstant(Val: Intrinsic::wasm_rethrow, DL: getCurSDLoc(),
3464 VT: TLI.getPointerTy(DL: DAG.getDataLayout()))};
3465 SDVTList VTs = DAG.getVTList(VTs: ArrayRef<EVT>({MVT::Other})); // outchain
3466 DAG.setRoot(DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL: getCurSDLoc(), VTList: VTs, Ops));
3467 break;
3468 }
3469 }
3470 } else if (I.hasDeoptState()) {
3471 // Currently we do not lower any intrinsic calls with deopt operand bundles.
3472 // Eventually we will support lowering the @llvm.experimental.deoptimize
3473 // intrinsic, and right now there are no plans to support other intrinsics
3474 // with deopt state.
3475 LowerCallSiteWithDeoptBundle(Call: &I, Callee: getValue(V: Callee), EHPadBB);
3476 } else if (I.countOperandBundlesOfType(ID: LLVMContext::OB_ptrauth)) {
3477 LowerCallSiteWithPtrAuthBundle(CB: cast<CallBase>(Val: I), EHPadBB);
3478 } else {
3479 LowerCallTo(CB: I, Callee: getValue(V: Callee), IsTailCall: false, IsMustTailCall: false, EHPadBB);
3480 }
3481
3482 // If the value of the invoke is used outside of its defining block, make it
3483 // available as a virtual register.
3484 // We already took care of the exported value for the statepoint instruction
3485 // during call to the LowerStatepoint.
3486 if (!isa<GCStatepointInst>(Val: I)) {
3487 CopyToExportRegsIfNeeded(V: &I);
3488 }
3489
3490 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3491 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3492 BranchProbability EHPadBBProb =
3493 BPI ? BPI->getEdgeProbability(Src: InvokeMBB->getBasicBlock(), Dst: EHPadBB)
3494 : BranchProbability::getZero();
3495 findUnwindDestinations(FuncInfo, EHPadBB, Prob: EHPadBBProb, UnwindDests);
3496
3497 // Update successor info.
3498 addSuccessorWithProb(Src: InvokeMBB, Dst: Return);
3499 for (auto &UnwindDest : UnwindDests) {
3500 UnwindDest.first->setIsEHPad();
3501 addSuccessorWithProb(Src: InvokeMBB, Dst: UnwindDest.first, Prob: UnwindDest.second);
3502 }
3503 InvokeMBB->normalizeSuccProbs();
3504
3505 // Drop into normal successor.
3506 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other, N1: getControlRoot(),
3507 N2: DAG.getBasicBlock(MBB: Return)));
3508}
3509
3510/// The intrinsics currently supported by callbr are implicit control flow
3511/// intrinsics such as amdgcn.kill.
3512/// - they should be called (no "dontcall-" attributes)
3513/// - they do not touch memory on the target (= !TLI.getTgtMemIntrinsic())
3514/// - they do not need custom argument handling (no
3515/// TLI.CollectTargetIntrinsicOperands())
3516void SelectionDAGBuilder::visitCallBrIntrinsic(const CallBrInst &I) {
3517#ifndef NDEBUG
3518 SmallVector<TargetLowering::IntrinsicInfo, 2> Infos;
3519 DAG.getTargetLoweringInfo().getTgtMemIntrinsic(
3520 Infos, I, DAG.getMachineFunction(), I.getIntrinsicID());
3521 assert(Infos.empty() && "Intrinsic touches memory");
3522#endif
3523
3524 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
3525
3526 SmallVector<SDValue, 8> Ops =
3527 getTargetIntrinsicOperands(I, HasChain, OnlyLoad);
3528 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
3529
3530 // Create the node.
3531 SDValue Result =
3532 getTargetNonMemIntrinsicNode(IntrinsicVT: *I.getType(), HasChain, Ops, VTs);
3533 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
3534
3535 setValue(V: &I, NewN: Result);
3536}
3537
3538void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3539 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3540
3541 if (I.isInlineAsm()) {
3542 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3543 // have to do anything here to lower funclet bundles.
3544 failForInvalidBundles(I, Name: "callbrs",
3545 AllowedBundles: {LLVMContext::OB_deopt, LLVMContext::OB_funclet});
3546 visitInlineAsm(Call: I);
3547 } else {
3548 assert(!I.hasOperandBundles() &&
3549 "Can't have operand bundles for intrinsics");
3550 visitCallBrIntrinsic(I);
3551 }
3552 CopyToExportRegsIfNeeded(V: &I);
3553
3554 // Retrieve successors.
3555 SmallPtrSet<BasicBlock *, 8> Dests;
3556 Dests.insert(Ptr: I.getDefaultDest());
3557 MachineBasicBlock *Return = FuncInfo.getMBB(BB: I.getDefaultDest());
3558
3559 // Update successor info.
3560 addSuccessorWithProb(Src: CallBrMBB, Dst: Return, Prob: BranchProbability::getOne());
3561 // TODO: For most of the cases where there is an intrinsic callbr, we're
3562 // having exactly one indirect target, which will be unreachable. As soon as
3563 // this changes, we might need to enhance
3564 // Target->setIsInlineAsmBrIndirectTarget or add something similar for
3565 // intrinsic indirect branches.
3566 if (I.isInlineAsm()) {
3567 for (BasicBlock *Dest : I.getIndirectDests()) {
3568 MachineBasicBlock *Target = FuncInfo.getMBB(BB: Dest);
3569 Target->setIsInlineAsmBrIndirectTarget();
3570 // If we introduce a type of asm goto statement that is permitted to use
3571 // an indirect call instruction to jump to its labels, then we should add
3572 // a call to Target->setMachineBlockAddressTaken() here, to mark the
3573 // target block as requiring a BTI.
3574
3575 Target->setLabelMustBeEmitted();
3576 // Don't add duplicate machine successors.
3577 if (Dests.insert(Ptr: Dest).second)
3578 addSuccessorWithProb(Src: CallBrMBB, Dst: Target, Prob: BranchProbability::getZero());
3579 }
3580 }
3581 CallBrMBB->normalizeSuccProbs();
3582
3583 // Drop into default successor.
3584 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(),
3585 VT: MVT::Other, N1: getControlRoot(),
3586 N2: DAG.getBasicBlock(MBB: Return)));
3587}
3588
3589void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3590 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3591}
3592
3593void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3594 assert(FuncInfo.MBB->isEHPad() &&
3595 "Call to landingpad not in landing pad!");
3596
3597 // If there aren't registers to copy the values into (e.g., during SjLj
3598 // exceptions), then don't bother to create these DAG nodes.
3599 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3600 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3601 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3602 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3603 return;
3604
3605 // If landingpad's return type is token type, we don't create DAG nodes
3606 // for its exception pointer and selector value. The extraction of exception
3607 // pointer or selector value from token type landingpads is not currently
3608 // supported.
3609 if (LP.getType()->isTokenTy())
3610 return;
3611
3612 SmallVector<EVT, 2> ValueVTs;
3613 SDLoc dl = getCurSDLoc();
3614 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: LP.getType(), ValueVTs);
3615 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3616
3617 // Get the two live-in registers as SDValues. The physregs have already been
3618 // copied into virtual registers.
3619 SDValue Ops[2];
3620 if (FuncInfo.ExceptionPointerVirtReg) {
3621 Ops[0] = DAG.getZExtOrTrunc(
3622 Op: DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl,
3623 Reg: FuncInfo.ExceptionPointerVirtReg,
3624 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
3625 DL: dl, VT: ValueVTs[0]);
3626 } else {
3627 Ops[0] = DAG.getConstant(Val: 0, DL: dl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
3628 }
3629 Ops[1] = DAG.getZExtOrTrunc(
3630 Op: DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl,
3631 Reg: FuncInfo.ExceptionSelectorVirtReg,
3632 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
3633 DL: dl, VT: ValueVTs[1]);
3634
3635 // Merge into one.
3636 SDValue Res = DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl,
3637 VTList: DAG.getVTList(VTs: ValueVTs), Ops);
3638 setValue(V: &LP, NewN: Res);
3639}
3640
3641void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3642 MachineBasicBlock *Last) {
3643 // Update JTCases.
3644 for (JumpTableBlock &JTB : SL->JTCases)
3645 if (JTB.first.HeaderBB == First)
3646 JTB.first.HeaderBB = Last;
3647
3648 // Update BitTestCases.
3649 for (BitTestBlock &BTB : SL->BitTestCases)
3650 if (BTB.Parent == First)
3651 BTB.Parent = Last;
3652}
3653
3654void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3655 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3656
3657 // Update machine-CFG edges with unique successors.
3658 SmallPtrSet<BasicBlock *, 32> Done;
3659 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3660 BasicBlock *BB = I.getSuccessor(i);
3661 bool Inserted = Done.insert(Ptr: BB).second;
3662 if (!Inserted)
3663 continue;
3664
3665 MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3666 addSuccessorWithProb(Src: IndirectBrMBB, Dst: Succ);
3667 }
3668 IndirectBrMBB->normalizeSuccProbs();
3669
3670 DAG.setRoot(DAG.getNode(Opcode: ISD::BRIND, DL: getCurSDLoc(),
3671 VT: MVT::Other, N1: getControlRoot(),
3672 N2: getValue(V: I.getAddress())));
3673}
3674
3675void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3676 if (!I.shouldLowerToTrap(TrapUnreachable: DAG.getTarget().Options.TrapUnreachable,
3677 NoTrapAfterNoreturn: DAG.getTarget().Options.NoTrapAfterNoreturn))
3678 return;
3679
3680 DAG.setRoot(DAG.getNode(Opcode: ISD::TRAP, DL: getCurSDLoc(), VT: MVT::Other, Operand: DAG.getRoot()));
3681}
3682
3683void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3684 SDNodeFlags Flags;
3685 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
3686 Flags.copyFMF(FPMO: *FPOp);
3687
3688 SDValue Op = getValue(V: I.getOperand(i: 0));
3689 SDValue UnNodeValue = DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Op.getValueType(),
3690 Operand: Op, Flags);
3691 setValue(V: &I, NewN: UnNodeValue);
3692}
3693
3694void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3695 SDNodeFlags Flags;
3696 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(Val: &I)) {
3697 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3698 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3699 }
3700 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(Val: &I))
3701 Flags.setExact(ExactOp->isExact());
3702 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(Val: &I))
3703 Flags.setDisjoint(DisjointOp->isDisjoint());
3704 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
3705 Flags.copyFMF(FPMO: *FPOp);
3706
3707 SDValue Op1 = getValue(V: I.getOperand(i: 0));
3708 SDValue Op2 = getValue(V: I.getOperand(i: 1));
3709 SDValue BinNodeValue = DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Op1.getValueType(),
3710 N1: Op1, N2: Op2, Flags);
3711 setValue(V: &I, NewN: BinNodeValue);
3712}
3713
3714void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3715 SDValue Op1 = getValue(V: I.getOperand(i: 0));
3716 SDValue Op2 = getValue(V: I.getOperand(i: 1));
3717
3718 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3719 LHSTy: Op1.getValueType(), DL: DAG.getDataLayout());
3720
3721 // Coerce the shift amount to the right type if we can. This exposes the
3722 // truncate or zext to optimization early.
3723 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3724 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3725 "Unexpected shift type");
3726 Op2 = DAG.getZExtOrTrunc(Op: Op2, DL: getCurSDLoc(), VT: ShiftTy);
3727 }
3728
3729 bool nuw = false;
3730 bool nsw = false;
3731 bool exact = false;
3732
3733 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3734
3735 if (const OverflowingBinaryOperator *OFBinOp =
3736 dyn_cast<const OverflowingBinaryOperator>(Val: &I)) {
3737 nuw = OFBinOp->hasNoUnsignedWrap();
3738 nsw = OFBinOp->hasNoSignedWrap();
3739 }
3740 if (const PossiblyExactOperator *ExactOp =
3741 dyn_cast<const PossiblyExactOperator>(Val: &I))
3742 exact = ExactOp->isExact();
3743 }
3744 SDNodeFlags Flags;
3745 Flags.setExact(exact);
3746 Flags.setNoSignedWrap(nsw);
3747 Flags.setNoUnsignedWrap(nuw);
3748 SDValue Res = DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Op1.getValueType(), N1: Op1, N2: Op2,
3749 Flags);
3750 setValue(V: &I, NewN: Res);
3751}
3752
3753void SelectionDAGBuilder::visitSDiv(const User &I) {
3754 SDValue Op1 = getValue(V: I.getOperand(i: 0));
3755 SDValue Op2 = getValue(V: I.getOperand(i: 1));
3756
3757 SDNodeFlags Flags;
3758 Flags.setExact(isa<PossiblyExactOperator>(Val: &I) &&
3759 cast<PossiblyExactOperator>(Val: &I)->isExact());
3760 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SDIV, DL: getCurSDLoc(), VT: Op1.getValueType(), N1: Op1,
3761 N2: Op2, Flags));
3762}
3763
3764void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3765 ICmpInst::Predicate predicate = I.getPredicate();
3766 SDValue Op1 = getValue(V: I.getOperand(i_nocapture: 0));
3767 SDValue Op2 = getValue(V: I.getOperand(i_nocapture: 1));
3768 ISD::CondCode Opcode = getICmpCondCode(Pred: predicate);
3769
3770 auto &TLI = DAG.getTargetLoweringInfo();
3771 EVT MemVT =
3772 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i_nocapture: 0)->getType());
3773
3774 // If a pointer's DAG type is larger than its memory type then the DAG values
3775 // are zero-extended. This breaks signed comparisons so truncate back to the
3776 // underlying type before doing the compare.
3777 if (Op1.getValueType() != MemVT) {
3778 Op1 = DAG.getPtrExtOrTrunc(Op: Op1, DL: getCurSDLoc(), VT: MemVT);
3779 Op2 = DAG.getPtrExtOrTrunc(Op: Op2, DL: getCurSDLoc(), VT: MemVT);
3780 }
3781
3782 SDNodeFlags Flags;
3783 Flags.setSameSign(I.hasSameSign());
3784 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3785
3786 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
3787 Ty: I.getType());
3788 setValue(V: &I, NewN: DAG.getSetCC(DL: getCurSDLoc(), VT: DestVT, LHS: Op1, RHS: Op2, Cond: Opcode));
3789}
3790
3791void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3792 FCmpInst::Predicate predicate = I.getPredicate();
3793 SDValue Op1 = getValue(V: I.getOperand(i_nocapture: 0));
3794 SDValue Op2 = getValue(V: I.getOperand(i_nocapture: 1));
3795
3796 ISD::CondCode Condition = getFCmpCondCode(Pred: predicate);
3797 auto *FPMO = cast<FPMathOperator>(Val: &I);
3798 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3799 Condition = getFCmpCodeWithoutNaN(CC: Condition);
3800
3801 SDNodeFlags Flags;
3802 Flags.copyFMF(FPMO: *FPMO);
3803 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3804
3805 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
3806 Ty: I.getType());
3807 setValue(V: &I, NewN: DAG.getSetCC(DL: getCurSDLoc(), VT: DestVT, LHS: Op1, RHS: Op2, Cond: Condition));
3808}
3809
3810// Check if the condition of the select has one use or two users that are both
3811// selects with the same condition.
3812static bool hasOnlySelectUsers(const Value *Cond) {
3813 return llvm::all_of(Range: Cond->users(), P: [](const Value *V) {
3814 return isa<SelectInst>(Val: V);
3815 });
3816}
3817
3818void SelectionDAGBuilder::visitSelect(const User &I) {
3819 SmallVector<EVT, 4> ValueVTs;
3820 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty: I.getType(),
3821 ValueVTs);
3822 unsigned NumValues = ValueVTs.size();
3823 if (NumValues == 0) return;
3824
3825 SmallVector<SDValue, 4> Values(NumValues);
3826 SDValue Cond = getValue(V: I.getOperand(i: 0));
3827 SDValue LHSVal = getValue(V: I.getOperand(i: 1));
3828 SDValue RHSVal = getValue(V: I.getOperand(i: 2));
3829 SmallVector<SDValue, 1> BaseOps(1, Cond);
3830 ISD::NodeType OpCode =
3831 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3832
3833 bool IsUnaryAbs = false;
3834 bool Negate = false;
3835
3836 SDNodeFlags Flags;
3837 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
3838 Flags.copyFMF(FPMO: *FPOp);
3839
3840 Flags.setUnpredictable(
3841 cast<SelectInst>(Val: I).getMetadata(KindID: LLVMContext::MD_unpredictable));
3842
3843 // Min/max matching is only viable if all output VTs are the same.
3844 if (all_equal(Range&: ValueVTs)) {
3845 EVT VT = ValueVTs[0];
3846 LLVMContext &Ctx = *DAG.getContext();
3847 auto &TLI = DAG.getTargetLoweringInfo();
3848
3849 // We care about the legality of the operation after it has been type
3850 // legalized.
3851 while (TLI.getTypeAction(Context&: Ctx, VT) != TargetLoweringBase::TypeLegal)
3852 VT = TLI.getTypeToTransformTo(Context&: Ctx, VT);
3853
3854 // If the vselect is legal, assume we want to leave this as a vector setcc +
3855 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3856 // min/max is legal on the scalar type.
3857 bool UseScalarMinMax = VT.isVector() &&
3858 !TLI.isOperationLegalOrCustom(Op: ISD::VSELECT, VT);
3859
3860 // ValueTracking's select pattern matching does not account for -0.0,
3861 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3862 // -0.0 is less than +0.0.
3863 const Value *LHS, *RHS;
3864 auto SPR = matchSelectPattern(V: &I, LHS, RHS);
3865 ISD::NodeType Opc = ISD::DELETED_NODE;
3866 switch (SPR.Flavor) {
3867 case SPF_UMAX: Opc = ISD::UMAX; break;
3868 case SPF_UMIN: Opc = ISD::UMIN; break;
3869 case SPF_SMAX: Opc = ISD::SMAX; break;
3870 case SPF_SMIN: Opc = ISD::SMIN; break;
3871 case SPF_FMINNUM:
3872 switch (SPR.NaNBehavior) {
3873 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3874 case SPNB_RETURNS_NAN: break;
3875 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3876 case SPNB_RETURNS_ANY:
3877 if (TLI.isOperationLegalOrCustom(Op: ISD::FMINNUM, VT) ||
3878 (UseScalarMinMax &&
3879 TLI.isOperationLegalOrCustom(Op: ISD::FMINNUM, VT: VT.getScalarType())))
3880 Opc = ISD::FMINNUM;
3881 break;
3882 }
3883 break;
3884 case SPF_FMAXNUM:
3885 switch (SPR.NaNBehavior) {
3886 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3887 case SPNB_RETURNS_NAN: break;
3888 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3889 case SPNB_RETURNS_ANY:
3890 if (TLI.isOperationLegalOrCustom(Op: ISD::FMAXNUM, VT) ||
3891 (UseScalarMinMax &&
3892 TLI.isOperationLegalOrCustom(Op: ISD::FMAXNUM, VT: VT.getScalarType())))
3893 Opc = ISD::FMAXNUM;
3894 break;
3895 }
3896 break;
3897 case SPF_NABS:
3898 Negate = true;
3899 [[fallthrough]];
3900 case SPF_ABS:
3901 IsUnaryAbs = true;
3902 Opc = ISD::ABS;
3903 break;
3904 default: break;
3905 }
3906
3907 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3908 (TLI.isOperationLegalOrCustom(Op: Opc, VT) ||
3909 (UseScalarMinMax &&
3910 TLI.isOperationLegalOrCustom(Op: Opc, VT: VT.getScalarType()))) &&
3911 // If the underlying comparison instruction is used by any other
3912 // instruction, the consumed instructions won't be destroyed, so it is
3913 // not profitable to convert to a min/max.
3914 hasOnlySelectUsers(Cond: cast<SelectInst>(Val: I).getCondition())) {
3915 OpCode = Opc;
3916 LHSVal = getValue(V: LHS);
3917 RHSVal = getValue(V: RHS);
3918 BaseOps.clear();
3919 }
3920
3921 if (IsUnaryAbs) {
3922 OpCode = Opc;
3923 LHSVal = getValue(V: LHS);
3924 BaseOps.clear();
3925 }
3926 }
3927
3928 if (IsUnaryAbs) {
3929 for (unsigned i = 0; i != NumValues; ++i) {
3930 SDLoc dl = getCurSDLoc();
3931 EVT VT = LHSVal.getNode()->getValueType(ResNo: LHSVal.getResNo() + i);
3932 Values[i] =
3933 DAG.getNode(Opcode: OpCode, DL: dl, VT, Operand: LHSVal.getValue(R: LHSVal.getResNo() + i));
3934 if (Negate)
3935 Values[i] = DAG.getNegative(Val: Values[i], DL: dl, VT);
3936 }
3937 } else {
3938 for (unsigned i = 0; i != NumValues; ++i) {
3939 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3940 Ops.push_back(Elt: SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3941 Ops.push_back(Elt: SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3942 Values[i] = DAG.getNode(
3943 Opcode: OpCode, DL: getCurSDLoc(),
3944 VT: LHSVal.getNode()->getValueType(ResNo: LHSVal.getResNo() + i), Ops, Flags);
3945 }
3946 }
3947
3948 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
3949 VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values));
3950}
3951
3952void SelectionDAGBuilder::visitTrunc(const User &I) {
3953 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3954 SDValue N = getValue(V: I.getOperand(i: 0));
3955 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
3956 Ty: I.getType());
3957 SDNodeFlags Flags;
3958 if (auto *Trunc = dyn_cast<TruncInst>(Val: &I)) {
3959 Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
3960 Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
3961 }
3962
3963 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::TRUNCATE, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
3964}
3965
3966void SelectionDAGBuilder::visitZExt(const User &I) {
3967 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3968 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3969 SDValue N = getValue(V: I.getOperand(i: 0));
3970 auto &TLI = DAG.getTargetLoweringInfo();
3971 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
3972
3973 SDNodeFlags Flags;
3974 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(Val: &I))
3975 Flags.setNonNeg(PNI->hasNonNeg());
3976
3977 // Eagerly use nonneg information to canonicalize towards sign_extend if
3978 // that is the target's preference.
3979 // TODO: Let the target do this later.
3980 if (Flags.hasNonNeg() &&
3981 TLI.isSExtCheaperThanZExt(FromTy: N.getValueType(), ToTy: DestVT)) {
3982 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N));
3983 return;
3984 }
3985
3986 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
3987}
3988
3989void SelectionDAGBuilder::visitSExt(const User &I) {
3990 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3991 // SExt also can't be a cast to bool for same reason. So, nothing much to do
3992 SDValue N = getValue(V: I.getOperand(i: 0));
3993 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
3994 Ty: I.getType());
3995 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N));
3996}
3997
3998void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3999 // FPTrunc is never a no-op cast, no need to check
4000 SDValue N = getValue(V: I.getOperand(i: 0));
4001 SDLoc dl = getCurSDLoc();
4002 SDNodeFlags Flags;
4003 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
4004 Flags.copyFMF(FPMO: *FPOp);
4005 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4006 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4007 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_ROUND, DL: dl, VT: DestVT, N1: N,
4008 N2: DAG.getTargetConstant(
4009 Val: 0, DL: dl, VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
4010 Flags));
4011}
4012
4013void SelectionDAGBuilder::visitFPExt(const User &I) {
4014 // FPExt is never a no-op cast, no need to check
4015 SDValue N = getValue(V: I.getOperand(i: 0));
4016 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4017 Ty: I.getType());
4018 SDNodeFlags Flags;
4019 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
4020 Flags.copyFMF(FPMO: *FPOp);
4021 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_EXTEND, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
4022}
4023
4024void SelectionDAGBuilder::visitFPToUI(const User &I) {
4025 // FPToUI is never a no-op cast, no need to check
4026 SDValue N = getValue(V: I.getOperand(i: 0));
4027 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4028 Ty: I.getType());
4029 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_UINT, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4030}
4031
4032void SelectionDAGBuilder::visitFPToSI(const User &I) {
4033 // FPToSI is never a no-op cast, no need to check
4034 SDValue N = getValue(V: I.getOperand(i: 0));
4035 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4036 Ty: I.getType());
4037 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_SINT, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4038}
4039
4040void SelectionDAGBuilder::visitUIToFP(const User &I) {
4041 // UIToFP is never a no-op cast, no need to check
4042 SDValue N = getValue(V: I.getOperand(i: 0));
4043 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4044 Ty: I.getType());
4045 SDNodeFlags Flags;
4046 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(Val: &I))
4047 Flags.setNonNeg(PNI->hasNonNeg());
4048
4049 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UINT_TO_FP, DL: getCurSDLoc(), VT: DestVT, Operand: N, Flags));
4050}
4051
4052void SelectionDAGBuilder::visitSIToFP(const User &I) {
4053 // SIToFP is never a no-op cast, no need to check
4054 SDValue N = getValue(V: I.getOperand(i: 0));
4055 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4056 Ty: I.getType());
4057 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: getCurSDLoc(), VT: DestVT, Operand: N));
4058}
4059
4060void SelectionDAGBuilder::visitPtrToAddr(const User &I) {
4061 SDValue N = getValue(V: I.getOperand(i: 0));
4062 // By definition the type of the ptrtoaddr must be equal to the address type.
4063 const auto &TLI = DAG.getTargetLoweringInfo();
4064 EVT AddrVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4065 // The address width must be smaller or equal to the pointer representation
4066 // width, so we lower ptrtoaddr as a truncate (possibly folded to a no-op).
4067 N = DAG.getNode(Opcode: ISD::TRUNCATE, DL: getCurSDLoc(), VT: AddrVT, Operand: N);
4068 setValue(V: &I, NewN: N);
4069}
4070
4071void SelectionDAGBuilder::visitPtrToInt(const User &I) {
4072 // What to do depends on the size of the integer and the size of the pointer.
4073 // We can either truncate, zero extend, or no-op, accordingly.
4074 SDValue N = getValue(V: I.getOperand(i: 0));
4075 auto &TLI = DAG.getTargetLoweringInfo();
4076 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4077 Ty: I.getType());
4078 EVT PtrMemVT =
4079 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i: 0)->getType());
4080 N = DAG.getPtrExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: PtrMemVT);
4081 N = DAG.getZExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: DestVT);
4082 setValue(V: &I, NewN: N);
4083}
4084
4085void SelectionDAGBuilder::visitIntToPtr(const User &I) {
4086 // What to do depends on the size of the integer and the size of the pointer.
4087 // We can either truncate, zero extend, or no-op, accordingly.
4088 SDValue N = getValue(V: I.getOperand(i: 0));
4089 auto &TLI = DAG.getTargetLoweringInfo();
4090 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4091 EVT PtrMemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4092 N = DAG.getZExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: PtrMemVT);
4093 N = DAG.getPtrExtOrTrunc(Op: N, DL: getCurSDLoc(), VT: DestVT);
4094 setValue(V: &I, NewN: N);
4095}
4096
4097void SelectionDAGBuilder::visitBitCast(const User &I) {
4098 SDValue N = getValue(V: I.getOperand(i: 0));
4099 SDLoc dl = getCurSDLoc();
4100 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
4101 Ty: I.getType());
4102
4103 // BitCast assures us that source and destination are the same size so this is
4104 // either a BITCAST or a no-op.
4105 if (DestVT != N.getValueType())
4106 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::BITCAST, DL: dl,
4107 VT: DestVT, Operand: N)); // convert types.
4108 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
4109 // might fold any kind of constant expression to an integer constant and that
4110 // is not what we are looking for. Only recognize a bitcast of a genuine
4111 // constant integer as an opaque constant.
4112 else if(ConstantInt *C = dyn_cast<ConstantInt>(Val: I.getOperand(i: 0)))
4113 setValue(V: &I, NewN: DAG.getConstant(Val: C->getValue(), DL: dl, VT: DestVT, /*isTarget=*/false,
4114 /*isOpaque*/true));
4115 else
4116 setValue(V: &I, NewN: N); // noop cast.
4117}
4118
4119void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
4120 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4121 const Value *SV = I.getOperand(i: 0);
4122 SDValue N = getValue(V: SV);
4123 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4124
4125 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
4126 unsigned DestAS = I.getType()->getPointerAddressSpace();
4127
4128 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
4129 N = DAG.getAddrSpaceCast(dl: getCurSDLoc(), VT: DestVT, Ptr: N, SrcAS, DestAS);
4130
4131 setValue(V: &I, NewN: N);
4132}
4133
4134void SelectionDAGBuilder::visitInsertElement(const User &I) {
4135 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4136 SDValue InVec = getValue(V: I.getOperand(i: 0));
4137 SDValue InVal = getValue(V: I.getOperand(i: 1));
4138 SDValue InIdx = DAG.getZExtOrTrunc(Op: getValue(V: I.getOperand(i: 2)), DL: getCurSDLoc(),
4139 VT: TLI.getVectorIdxTy(DL: DAG.getDataLayout()));
4140 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: getCurSDLoc(),
4141 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
4142 N1: InVec, N2: InVal, N3: InIdx));
4143}
4144
4145void SelectionDAGBuilder::visitExtractElement(const User &I) {
4146 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4147 SDValue InVec = getValue(V: I.getOperand(i: 0));
4148 SDValue InIdx = DAG.getZExtOrTrunc(Op: getValue(V: I.getOperand(i: 1)), DL: getCurSDLoc(),
4149 VT: TLI.getVectorIdxTy(DL: DAG.getDataLayout()));
4150 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: getCurSDLoc(),
4151 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
4152 N1: InVec, N2: InIdx));
4153}
4154
4155void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4156 SDValue Src1 = getValue(V: I.getOperand(i: 0));
4157 SDValue Src2 = getValue(V: I.getOperand(i: 1));
4158 ArrayRef<int> Mask;
4159 if (auto *SVI = dyn_cast<ShuffleVectorInst>(Val: &I))
4160 Mask = SVI->getShuffleMask();
4161 else
4162 Mask = cast<ConstantExpr>(Val: I).getShuffleMask();
4163 SDLoc DL = getCurSDLoc();
4164 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4165 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
4166 EVT SrcVT = Src1.getValueType();
4167
4168 if (all_of(Range&: Mask, P: equal_to(Arg: 0)) && VT.isScalableVector()) {
4169 // Canonical splat form of first element of first input vector.
4170 SDValue FirstElt =
4171 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: SrcVT.getScalarType(), N1: Src1,
4172 N2: DAG.getVectorIdxConstant(Val: 0, DL));
4173 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SPLAT_VECTOR, DL, VT, Operand: FirstElt));
4174 return;
4175 }
4176
4177 // For now, we only handle splats for scalable vectors.
4178 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4179 // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4180 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4181
4182 unsigned SrcNumElts = SrcVT.getVectorNumElements();
4183 unsigned MaskNumElts = Mask.size();
4184
4185 if (SrcNumElts == MaskNumElts) {
4186 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: Src1, N2: Src2, Mask));
4187 return;
4188 }
4189
4190 // Normalize the shuffle vector since mask and vector length don't match.
4191 if (SrcNumElts < MaskNumElts) {
4192 // Mask is longer than the source vectors. We can use concatenate vector to
4193 // make the mask and vectors lengths match.
4194
4195 if (MaskNumElts % SrcNumElts == 0) {
4196 // Mask length is a multiple of the source vector length.
4197 // Check if the shuffle is some kind of concatenation of the input
4198 // vectors.
4199 unsigned NumConcat = MaskNumElts / SrcNumElts;
4200 bool IsConcat = true;
4201 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4202 for (unsigned i = 0; i != MaskNumElts; ++i) {
4203 int Idx = Mask[i];
4204 if (Idx < 0)
4205 continue;
4206 // Ensure the indices in each SrcVT sized piece are sequential and that
4207 // the same source is used for the whole piece.
4208 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4209 (ConcatSrcs[i / SrcNumElts] >= 0 &&
4210 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4211 IsConcat = false;
4212 break;
4213 }
4214 // Remember which source this index came from.
4215 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4216 }
4217
4218 // The shuffle is concatenating multiple vectors together. Just emit
4219 // a CONCAT_VECTORS operation.
4220 if (IsConcat) {
4221 SmallVector<SDValue, 8> ConcatOps;
4222 for (auto Src : ConcatSrcs) {
4223 if (Src < 0)
4224 ConcatOps.push_back(Elt: DAG.getUNDEF(VT: SrcVT));
4225 else if (Src == 0)
4226 ConcatOps.push_back(Elt: Src1);
4227 else
4228 ConcatOps.push_back(Elt: Src2);
4229 }
4230 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT, Ops: ConcatOps));
4231 return;
4232 }
4233 }
4234
4235 unsigned PaddedMaskNumElts = alignTo(Value: MaskNumElts, Align: SrcNumElts);
4236 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4237 EVT PaddedVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: VT.getScalarType(),
4238 NumElements: PaddedMaskNumElts);
4239
4240 // Pad both vectors with undefs to make them the same length as the mask.
4241 SDValue UndefVal = DAG.getUNDEF(VT: SrcVT);
4242
4243 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4244 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4245 MOps1[0] = Src1;
4246 MOps2[0] = Src2;
4247
4248 Src1 = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: PaddedVT, Ops: MOps1);
4249 Src2 = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: PaddedVT, Ops: MOps2);
4250
4251 // Readjust mask for new input vector length.
4252 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4253 for (unsigned i = 0; i != MaskNumElts; ++i) {
4254 int Idx = Mask[i];
4255 if (Idx >= (int)SrcNumElts)
4256 Idx -= SrcNumElts - PaddedMaskNumElts;
4257 MappedOps[i] = Idx;
4258 }
4259
4260 SDValue Result = DAG.getVectorShuffle(VT: PaddedVT, dl: DL, N1: Src1, N2: Src2, Mask: MappedOps);
4261
4262 // If the concatenated vector was padded, extract a subvector with the
4263 // correct number of elements.
4264 if (MaskNumElts != PaddedMaskNumElts)
4265 Result = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT, N1: Result,
4266 N2: DAG.getVectorIdxConstant(Val: 0, DL));
4267
4268 setValue(V: &I, NewN: Result);
4269 return;
4270 }
4271
4272 assert(SrcNumElts > MaskNumElts);
4273
4274 // Analyze the access pattern of the vector to see if we can extract
4275 // two subvectors and do the shuffle.
4276 int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4277 bool CanExtract = true;
4278 for (int Idx : Mask) {
4279 unsigned Input = 0;
4280 if (Idx < 0)
4281 continue;
4282
4283 if (Idx >= (int)SrcNumElts) {
4284 Input = 1;
4285 Idx -= SrcNumElts;
4286 }
4287
4288 // If all the indices come from the same MaskNumElts sized portion of
4289 // the sources we can use extract. Also make sure the extract wouldn't
4290 // extract past the end of the source.
4291 int NewStartIdx = alignDown(Value: Idx, Align: MaskNumElts);
4292 if (NewStartIdx + MaskNumElts > SrcNumElts ||
4293 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4294 CanExtract = false;
4295 // Make sure we always update StartIdx as we use it to track if all
4296 // elements are undef.
4297 StartIdx[Input] = NewStartIdx;
4298 }
4299
4300 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4301 setValue(V: &I, NewN: DAG.getUNDEF(VT)); // Vectors are not used.
4302 return;
4303 }
4304 if (CanExtract) {
4305 // Extract appropriate subvector and generate a vector shuffle
4306 for (unsigned Input = 0; Input < 2; ++Input) {
4307 SDValue &Src = Input == 0 ? Src1 : Src2;
4308 if (StartIdx[Input] < 0)
4309 Src = DAG.getUNDEF(VT);
4310 else {
4311 Src = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT, N1: Src,
4312 N2: DAG.getVectorIdxConstant(Val: StartIdx[Input], DL));
4313 }
4314 }
4315
4316 // Calculate new mask.
4317 SmallVector<int, 8> MappedOps(Mask);
4318 for (int &Idx : MappedOps) {
4319 if (Idx >= (int)SrcNumElts)
4320 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4321 else if (Idx >= 0)
4322 Idx -= StartIdx[0];
4323 }
4324
4325 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: Src1, N2: Src2, Mask: MappedOps));
4326 return;
4327 }
4328
4329 // We can't use either concat vectors or extract subvectors so fall back to
4330 // replacing the shuffle with extract and build vector.
4331 // to insert and build vector.
4332 EVT EltVT = VT.getVectorElementType();
4333 SmallVector<SDValue,8> Ops;
4334 for (int Idx : Mask) {
4335 SDValue Res;
4336
4337 if (Idx < 0) {
4338 Res = DAG.getUNDEF(VT: EltVT);
4339 } else {
4340 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4341 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4342
4343 Res = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: EltVT, N1: Src,
4344 N2: DAG.getVectorIdxConstant(Val: Idx, DL));
4345 }
4346
4347 Ops.push_back(Elt: Res);
4348 }
4349
4350 setValue(V: &I, NewN: DAG.getBuildVector(VT, DL, Ops));
4351}
4352
4353void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4354 ArrayRef<unsigned> Indices = I.getIndices();
4355 const Value *Op0 = I.getOperand(i_nocapture: 0);
4356 const Value *Op1 = I.getOperand(i_nocapture: 1);
4357 Type *AggTy = I.getType();
4358 Type *ValTy = Op1->getType();
4359 bool IntoUndef = isa<UndefValue>(Val: Op0);
4360 bool FromUndef = isa<UndefValue>(Val: Op1);
4361
4362 unsigned LinearIndex = ComputeLinearIndex(Ty: AggTy, Indices);
4363
4364 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4365 SmallVector<EVT, 4> AggValueVTs;
4366 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: AggTy, ValueVTs&: AggValueVTs);
4367 SmallVector<EVT, 4> ValValueVTs;
4368 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: ValTy, ValueVTs&: ValValueVTs);
4369
4370 unsigned NumAggValues = AggValueVTs.size();
4371 unsigned NumValValues = ValValueVTs.size();
4372 SmallVector<SDValue, 4> Values(NumAggValues);
4373
4374 // Ignore an insertvalue that produces an empty object
4375 if (!NumAggValues) {
4376 setValue(V: &I, NewN: DAG.getUNDEF(VT: MVT(MVT::Other)));
4377 return;
4378 }
4379
4380 SDValue Agg = getValue(V: Op0);
4381 unsigned i = 0;
4382 // Copy the beginning value(s) from the original aggregate.
4383 for (; i != LinearIndex; ++i)
4384 Values[i] = IntoUndef ? DAG.getUNDEF(VT: AggValueVTs[i]) :
4385 SDValue(Agg.getNode(), Agg.getResNo() + i);
4386 // Copy values from the inserted value(s).
4387 if (NumValValues) {
4388 SDValue Val = getValue(V: Op1);
4389 for (; i != LinearIndex + NumValValues; ++i)
4390 Values[i] = FromUndef ? DAG.getUNDEF(VT: AggValueVTs[i]) :
4391 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4392 }
4393 // Copy remaining value(s) from the original aggregate.
4394 for (; i != NumAggValues; ++i)
4395 Values[i] = IntoUndef ? DAG.getUNDEF(VT: AggValueVTs[i]) :
4396 SDValue(Agg.getNode(), Agg.getResNo() + i);
4397
4398 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
4399 VTList: DAG.getVTList(VTs: AggValueVTs), Ops: Values));
4400}
4401
4402void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4403 ArrayRef<unsigned> Indices = I.getIndices();
4404 const Value *Op0 = I.getOperand(i_nocapture: 0);
4405 Type *AggTy = Op0->getType();
4406 Type *ValTy = I.getType();
4407 bool OutOfUndef = isa<UndefValue>(Val: Op0);
4408
4409 unsigned LinearIndex = ComputeLinearIndex(Ty: AggTy, Indices);
4410
4411 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4412 SmallVector<EVT, 4> ValValueVTs;
4413 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: ValTy, ValueVTs&: ValValueVTs);
4414
4415 unsigned NumValValues = ValValueVTs.size();
4416
4417 // Ignore a extractvalue that produces an empty object
4418 if (!NumValValues) {
4419 setValue(V: &I, NewN: DAG.getUNDEF(VT: MVT(MVT::Other)));
4420 return;
4421 }
4422
4423 SmallVector<SDValue, 4> Values(NumValValues);
4424
4425 SDValue Agg = getValue(V: Op0);
4426 // Copy out the selected value(s).
4427 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4428 Values[i - LinearIndex] =
4429 OutOfUndef ?
4430 DAG.getUNDEF(VT: Agg.getNode()->getValueType(ResNo: Agg.getResNo() + i)) :
4431 SDValue(Agg.getNode(), Agg.getResNo() + i);
4432
4433 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
4434 VTList: DAG.getVTList(VTs: ValValueVTs), Ops: Values));
4435}
4436
4437void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4438 Value *Op0 = I.getOperand(i: 0);
4439 // Note that the pointer operand may be a vector of pointers. Take the scalar
4440 // element which holds a pointer.
4441 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4442 SDValue N = getValue(V: Op0);
4443 SDLoc dl = getCurSDLoc();
4444 auto &TLI = DAG.getTargetLoweringInfo();
4445 GEPNoWrapFlags NW = cast<GEPOperator>(Val: I).getNoWrapFlags();
4446
4447 // For a vector GEP, keep the prefix scalar as long as possible, then
4448 // convert any scalars encountered after the first vector operand to vectors.
4449 bool IsVectorGEP = I.getType()->isVectorTy();
4450 ElementCount VectorElementCount =
4451 IsVectorGEP ? cast<VectorType>(Val: I.getType())->getElementCount()
4452 : ElementCount::getFixed(MinVal: 0);
4453
4454 for (gep_type_iterator GTI = gep_type_begin(GEP: &I), E = gep_type_end(GEP: &I);
4455 GTI != E; ++GTI) {
4456 const Value *Idx = GTI.getOperand();
4457 if (StructType *StTy = GTI.getStructTypeOrNull()) {
4458 unsigned Field = cast<Constant>(Val: Idx)->getUniqueInteger().getZExtValue();
4459 if (Field) {
4460 // N = N + Offset
4461 uint64_t Offset =
4462 DAG.getDataLayout().getStructLayout(Ty: StTy)->getElementOffset(Idx: Field);
4463
4464 // In an inbounds GEP with an offset that is nonnegative even when
4465 // interpreted as signed, assume there is no unsigned overflow.
4466 SDNodeFlags Flags;
4467 if (NW.hasNoUnsignedWrap() ||
4468 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4469 Flags |= SDNodeFlags::NoUnsignedWrap;
4470 Flags.setInBounds(NW.isInBounds());
4471
4472 N = DAG.getMemBasePlusOffset(
4473 Base: N, Offset: DAG.getConstant(Val: Offset, DL: dl, VT: N.getValueType()), DL: dl, Flags);
4474 }
4475 } else {
4476 // IdxSize is the width of the arithmetic according to IR semantics.
4477 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4478 // (and fix up the result later).
4479 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4480 MVT IdxTy = MVT::getIntegerVT(BitWidth: IdxSize);
4481 TypeSize ElementSize =
4482 GTI.getSequentialElementStride(DL: DAG.getDataLayout());
4483 // We intentionally mask away the high bits here; ElementSize may not
4484 // fit in IdxTy.
4485 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4486 /*isSigned=*/false, /*implicitTrunc=*/true);
4487 bool ElementScalable = ElementSize.isScalable();
4488
4489 // If this is a scalar constant or a splat vector of constants,
4490 // handle it quickly.
4491 const auto *C = dyn_cast<Constant>(Val: Idx);
4492 if (C && isa<VectorType>(Val: C->getType()))
4493 C = C->getSplatValue();
4494
4495 const auto *CI = dyn_cast_or_null<ConstantInt>(Val: C);
4496 if (CI && CI->isZero())
4497 continue;
4498 if (CI && !ElementScalable) {
4499 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(width: IdxSize);
4500 LLVMContext &Context = *DAG.getContext();
4501 SDValue OffsVal;
4502 if (N.getValueType().isVector())
4503 OffsVal = DAG.getConstant(
4504 Val: Offs, DL: dl, VT: EVT::getVectorVT(Context, VT: IdxTy, EC: VectorElementCount));
4505 else
4506 OffsVal = DAG.getConstant(Val: Offs, DL: dl, VT: IdxTy);
4507
4508 // In an inbounds GEP with an offset that is nonnegative even when
4509 // interpreted as signed, assume there is no unsigned overflow.
4510 SDNodeFlags Flags;
4511 if (NW.hasNoUnsignedWrap() ||
4512 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4513 Flags.setNoUnsignedWrap(true);
4514 Flags.setInBounds(NW.isInBounds());
4515
4516 OffsVal = DAG.getSExtOrTrunc(Op: OffsVal, DL: dl, VT: N.getValueType());
4517
4518 N = DAG.getMemBasePlusOffset(Base: N, Offset: OffsVal, DL: dl, Flags);
4519 continue;
4520 }
4521
4522 // N = N + Idx * ElementMul;
4523 SDValue IdxN = getValue(V: Idx);
4524
4525 if (IdxN.getValueType().isVector() != N.getValueType().isVector()) {
4526 if (N.getValueType().isVector()) {
4527 EVT VT = EVT::getVectorVT(Context&: *Context, VT: IdxN.getValueType(),
4528 EC: VectorElementCount);
4529 IdxN = DAG.getSplat(VT, DL: dl, Op: IdxN);
4530 } else {
4531 EVT VT =
4532 EVT::getVectorVT(Context&: *Context, VT: N.getValueType(), EC: VectorElementCount);
4533 N = DAG.getSplat(VT, DL: dl, Op: N);
4534 }
4535 }
4536
4537 // If the index is smaller or larger than intptr_t, truncate or extend
4538 // it.
4539 IdxN = DAG.getSExtOrTrunc(Op: IdxN, DL: dl, VT: N.getValueType());
4540
4541 SDNodeFlags ScaleFlags;
4542 // The multiplication of an index by the type size does not wrap the
4543 // pointer index type in a signed sense (mul nsw).
4544 ScaleFlags.setNoSignedWrap(NW.hasNoUnsignedSignedWrap());
4545
4546 // The multiplication of an index by the type size does not wrap the
4547 // pointer index type in an unsigned sense (mul nuw).
4548 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4549
4550 if (ElementScalable) {
4551 EVT VScaleTy = N.getValueType().getScalarType();
4552 SDValue VScale = DAG.getNode(
4553 Opcode: ISD::VSCALE, DL: dl, VT: VScaleTy,
4554 Operand: DAG.getConstant(Val: ElementMul.getZExtValue(), DL: dl, VT: VScaleTy));
4555 if (N.getValueType().isVector())
4556 VScale = DAG.getSplatVector(VT: N.getValueType(), DL: dl, Op: VScale);
4557 IdxN = DAG.getNode(Opcode: ISD::MUL, DL: dl, VT: N.getValueType(), N1: IdxN, N2: VScale,
4558 Flags: ScaleFlags);
4559 } else {
4560 // If this is a multiply by a power of two, turn it into a shl
4561 // immediately. This is a very common case.
4562 if (ElementMul != 1) {
4563 if (ElementMul.isPowerOf2()) {
4564 unsigned Amt = ElementMul.logBase2();
4565 IdxN = DAG.getNode(
4566 Opcode: ISD::SHL, DL: dl, VT: N.getValueType(), N1: IdxN,
4567 N2: DAG.getShiftAmountConstant(Val: Amt, VT: N.getValueType(), DL: dl),
4568 Flags: ScaleFlags);
4569 } else {
4570 SDValue Scale = DAG.getConstant(Val: ElementMul.getZExtValue(), DL: dl,
4571 VT: IdxN.getValueType());
4572 IdxN = DAG.getNode(Opcode: ISD::MUL, DL: dl, VT: N.getValueType(), N1: IdxN, N2: Scale,
4573 Flags: ScaleFlags);
4574 }
4575 }
4576 }
4577
4578 // The successive addition of the current address, truncated to the
4579 // pointer index type and interpreted as an unsigned number, and each
4580 // offset, also interpreted as an unsigned number, does not wrap the
4581 // pointer index type (add nuw).
4582 SDNodeFlags AddFlags;
4583 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4584 AddFlags.setInBounds(NW.isInBounds());
4585
4586 N = DAG.getMemBasePlusOffset(Base: N, Offset: IdxN, DL: dl, Flags: AddFlags);
4587 }
4588 }
4589
4590 if (IsVectorGEP && !N.getValueType().isVector()) {
4591 EVT VT = EVT::getVectorVT(Context&: *Context, VT: N.getValueType(), EC: VectorElementCount);
4592 N = DAG.getSplat(VT, DL: dl, Op: N);
4593 }
4594
4595 MVT PtrTy = TLI.getPointerTy(DL: DAG.getDataLayout(), AS);
4596 MVT PtrMemTy = TLI.getPointerMemTy(DL: DAG.getDataLayout(), AS);
4597 if (IsVectorGEP) {
4598 PtrTy = MVT::getVectorVT(VT: PtrTy, EC: VectorElementCount);
4599 PtrMemTy = MVT::getVectorVT(VT: PtrMemTy, EC: VectorElementCount);
4600 }
4601
4602 if (PtrMemTy != PtrTy && !cast<GEPOperator>(Val: I).isInBounds())
4603 N = DAG.getPtrExtendInReg(Op: N, DL: dl, VT: PtrMemTy);
4604
4605 setValue(V: &I, NewN: N);
4606}
4607
4608void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4609 // If this is a fixed sized alloca in the entry block of the function,
4610 // allocate it statically on the stack.
4611 if (FuncInfo.StaticAllocaMap.count(Val: &I))
4612 return; // getValue will auto-populate this.
4613
4614 SDLoc dl = getCurSDLoc();
4615 Type *Ty = I.getAllocatedType();
4616 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4617 auto &DL = DAG.getDataLayout();
4618 TypeSize TySize = DL.getTypeAllocSize(Ty);
4619 MaybeAlign Alignment = I.getAlign();
4620
4621 SDValue AllocSize = getValue(V: I.getArraySize());
4622
4623 EVT IntPtr = TLI.getPointerTy(DL, AS: I.getAddressSpace());
4624 if (AllocSize.getValueType() != IntPtr)
4625 AllocSize = DAG.getZExtOrTrunc(Op: AllocSize, DL: dl, VT: IntPtr);
4626
4627 AllocSize = DAG.getNode(
4628 Opcode: ISD::MUL, DL: dl, VT: IntPtr, N1: AllocSize,
4629 N2: DAG.getZExtOrTrunc(Op: DAG.getTypeSize(DL: dl, VT: MVT::i64, TS: TySize), DL: dl, VT: IntPtr));
4630
4631 // Handle alignment. If the requested alignment is less than or equal to
4632 // the stack alignment, ignore it. If the size is greater than or equal to
4633 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4634 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4635 if (*Alignment <= StackAlign)
4636 Alignment = std::nullopt;
4637
4638 const uint64_t StackAlignMask = StackAlign.value() - 1U;
4639 // Round the size of the allocation up to the stack alignment size
4640 // by add SA-1 to the size. This doesn't overflow because we're computing
4641 // an address inside an alloca.
4642 AllocSize = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: AllocSize.getValueType(), N1: AllocSize,
4643 N2: DAG.getConstant(Val: StackAlignMask, DL: dl, VT: IntPtr),
4644 Flags: SDNodeFlags::NoUnsignedWrap);
4645
4646 // Mask out the low bits for alignment purposes.
4647 AllocSize = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: AllocSize.getValueType(), N1: AllocSize,
4648 N2: DAG.getSignedConstant(Val: ~StackAlignMask, DL: dl, VT: IntPtr));
4649
4650 SDValue Ops[] = {
4651 getRoot(), AllocSize,
4652 DAG.getConstant(Val: Alignment ? Alignment->value() : 0, DL: dl, VT: IntPtr)};
4653 SDVTList VTs = DAG.getVTList(VT1: AllocSize.getValueType(), VT2: MVT::Other);
4654 SDValue DSA = DAG.getNode(Opcode: ISD::DYNAMIC_STACKALLOC, DL: dl, VTList: VTs, Ops);
4655 setValue(V: &I, NewN: DSA);
4656 DAG.setRoot(DSA.getValue(R: 1));
4657
4658 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4659}
4660
4661static const MDNode *getRangeMetadata(const Instruction &I) {
4662 return I.getMetadata(KindID: LLVMContext::MD_range);
4663}
4664
4665static std::optional<ConstantRange> getRange(const Instruction &I) {
4666 if (const auto *CB = dyn_cast<CallBase>(Val: &I))
4667 if (std::optional<ConstantRange> CR = CB->getRange())
4668 return CR;
4669 if (const MDNode *Range = getRangeMetadata(I))
4670 return getConstantRangeFromMetadata(RangeMD: *Range);
4671 return std::nullopt;
4672}
4673
4674static FPClassTest getNoFPClass(const Instruction &I) {
4675 if (const auto *CB = dyn_cast<CallBase>(Val: &I))
4676 return CB->getRetNoFPClass();
4677 return fcNone;
4678}
4679
4680void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4681 if (I.isAtomic())
4682 return visitAtomicLoad(I);
4683
4684 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4685 const Value *SV = I.getOperand(i_nocapture: 0);
4686 if (TLI.supportSwiftError()) {
4687 // Swifterror values can come from either a function parameter with
4688 // swifterror attribute or an alloca with swifterror attribute.
4689 if (const Argument *Arg = dyn_cast<Argument>(Val: SV)) {
4690 if (Arg->hasSwiftErrorAttr())
4691 return visitLoadFromSwiftError(I);
4692 }
4693
4694 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(Val: SV)) {
4695 if (Alloca->isSwiftError())
4696 return visitLoadFromSwiftError(I);
4697 }
4698 }
4699
4700 SDValue Ptr = getValue(V: SV);
4701
4702 Type *Ty = I.getType();
4703 SmallVector<EVT, 4> ValueVTs, MemVTs;
4704 SmallVector<TypeSize, 4> Offsets;
4705 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty, ValueVTs, MemVTs: &MemVTs, Offsets: &Offsets);
4706 unsigned NumValues = ValueVTs.size();
4707 if (NumValues == 0)
4708 return;
4709
4710 Align Alignment = I.getAlign();
4711 AAMDNodes AAInfo = I.getAAMetadata();
4712 const MDNode *Ranges = getRangeMetadata(I);
4713 bool isVolatile = I.isVolatile();
4714 MachineMemOperand::Flags MMOFlags =
4715 TLI.getLoadMemOperandFlags(LI: I, DL: DAG.getDataLayout(), AC, LibInfo);
4716
4717 SDValue Root;
4718 bool ConstantMemory = false;
4719 if (isVolatile)
4720 // Serialize volatile loads with other side effects.
4721 Root = getRoot();
4722 else if (NumValues > MaxParallelChains)
4723 Root = getMemoryRoot();
4724 else if (BatchAA &&
4725 BatchAA->pointsToConstantMemory(Loc: MemoryLocation(
4726 SV,
4727 LocationSize::precise(Value: DAG.getDataLayout().getTypeStoreSize(Ty)),
4728 AAInfo))) {
4729 // Do not serialize (non-volatile) loads of constant memory with anything.
4730 Root = DAG.getEntryNode();
4731 ConstantMemory = true;
4732 MMOFlags |= MachineMemOperand::MOInvariant;
4733 } else {
4734 // Do not serialize non-volatile loads against each other.
4735 Root = DAG.getRoot();
4736 }
4737
4738 SDLoc dl = getCurSDLoc();
4739
4740 if (isVolatile)
4741 Root = TLI.prepareVolatileOrAtomicLoad(Chain: Root, DL: dl, DAG);
4742
4743 SmallVector<SDValue, 4> Values(NumValues);
4744 SmallVector<SDValue, 4> Chains(std::min(a: MaxParallelChains, b: NumValues));
4745
4746 unsigned ChainI = 0;
4747 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4748 // Serializing loads here may result in excessive register pressure, and
4749 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4750 // could recover a bit by hoisting nodes upward in the chain by recognizing
4751 // they are side-effect free or do not alias. The optimizer should really
4752 // avoid this case by converting large object/array copies to llvm.memcpy
4753 // (MaxParallelChains should always remain as failsafe).
4754 if (ChainI == MaxParallelChains) {
4755 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4756 SDValue Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4757 Ops: ArrayRef(Chains.data(), ChainI));
4758 Root = Chain;
4759 ChainI = 0;
4760 }
4761
4762 // TODO: MachinePointerInfo only supports a fixed length offset.
4763 MachinePointerInfo PtrInfo =
4764 !Offsets[i].isScalable() || Offsets[i].isZero()
4765 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4766 : MachinePointerInfo();
4767
4768 SDValue A = DAG.getObjectPtrOffset(SL: dl, Ptr, Offset: Offsets[i]);
4769 SDValue L = DAG.getLoad(VT: MemVTs[i], dl, Chain: Root, Ptr: A, PtrInfo, Alignment,
4770 MMOFlags, AAInfo, Ranges);
4771 Chains[ChainI] = L.getValue(R: 1);
4772
4773 if (MemVTs[i] != ValueVTs[i])
4774 L = DAG.getPtrExtOrTrunc(Op: L, DL: dl, VT: ValueVTs[i]);
4775
4776 Values[i] = L;
4777 }
4778
4779 if (!ConstantMemory) {
4780 SDValue Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4781 Ops: ArrayRef(Chains.data(), ChainI));
4782 if (isVolatile)
4783 DAG.setRoot(Chain);
4784 else
4785 PendingLoads.push_back(Elt: Chain);
4786 }
4787
4788 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl,
4789 VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values));
4790}
4791
4792void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4793 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4794 "call visitStoreToSwiftError when backend supports swifterror");
4795
4796 SmallVector<EVT, 4> ValueVTs;
4797 SmallVector<uint64_t, 4> Offsets;
4798 const Value *SrcV = I.getOperand(i_nocapture: 0);
4799 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(),
4800 Ty: SrcV->getType(), ValueVTs, /*MemVTs=*/nullptr, FixedOffsets: &Offsets, StartingOffset: 0);
4801 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4802 "expect a single EVT for swifterror");
4803
4804 SDValue Src = getValue(V: SrcV);
4805 // Create a virtual register, then update the virtual register.
4806 Register VReg =
4807 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4808 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4809 // Chain can be getRoot or getControlRoot.
4810 SDValue CopyNode = DAG.getCopyToReg(Chain: getRoot(), dl: getCurSDLoc(), Reg: VReg,
4811 N: SDValue(Src.getNode(), Src.getResNo()));
4812 DAG.setRoot(CopyNode);
4813}
4814
4815void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4816 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4817 "call visitLoadFromSwiftError when backend supports swifterror");
4818
4819 assert(!I.isVolatile() &&
4820 !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4821 !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4822 "Support volatile, non temporal, invariant for load_from_swift_error");
4823
4824 const Value *SV = I.getOperand(i_nocapture: 0);
4825 Type *Ty = I.getType();
4826 assert(
4827 (!BatchAA ||
4828 !BatchAA->pointsToConstantMemory(MemoryLocation(
4829 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4830 I.getAAMetadata()))) &&
4831 "load_from_swift_error should not be constant memory");
4832
4833 SmallVector<EVT, 4> ValueVTs;
4834 SmallVector<uint64_t, 4> Offsets;
4835 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty,
4836 ValueVTs, /*MemVTs=*/nullptr, FixedOffsets: &Offsets, StartingOffset: 0);
4837 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4838 "expect a single EVT for swifterror");
4839
4840 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4841 SDValue L = DAG.getCopyFromReg(
4842 Chain: getRoot(), dl: getCurSDLoc(),
4843 Reg: SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), VT: ValueVTs[0]);
4844
4845 setValue(V: &I, NewN: L);
4846}
4847
4848void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4849 if (I.isAtomic())
4850 return visitAtomicStore(I);
4851
4852 const Value *SrcV = I.getOperand(i_nocapture: 0);
4853 const Value *PtrV = I.getOperand(i_nocapture: 1);
4854
4855 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4856 if (TLI.supportSwiftError()) {
4857 // Swifterror values can come from either a function parameter with
4858 // swifterror attribute or an alloca with swifterror attribute.
4859 if (const Argument *Arg = dyn_cast<Argument>(Val: PtrV)) {
4860 if (Arg->hasSwiftErrorAttr())
4861 return visitStoreToSwiftError(I);
4862 }
4863
4864 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(Val: PtrV)) {
4865 if (Alloca->isSwiftError())
4866 return visitStoreToSwiftError(I);
4867 }
4868 }
4869
4870 SmallVector<EVT, 4> ValueVTs, MemVTs;
4871 SmallVector<TypeSize, 4> Offsets;
4872 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(),
4873 Ty: SrcV->getType(), ValueVTs, MemVTs: &MemVTs, Offsets: &Offsets);
4874 unsigned NumValues = ValueVTs.size();
4875 if (NumValues == 0)
4876 return;
4877
4878 // Get the lowered operands. Note that we do this after
4879 // checking if NumResults is zero, because with zero results
4880 // the operands won't have values in the map.
4881 SDValue Src = getValue(V: SrcV);
4882 SDValue Ptr = getValue(V: PtrV);
4883
4884 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4885 SmallVector<SDValue, 4> Chains(std::min(a: MaxParallelChains, b: NumValues));
4886 SDLoc dl = getCurSDLoc();
4887 Align Alignment = I.getAlign();
4888 AAMDNodes AAInfo = I.getAAMetadata();
4889
4890 auto MMOFlags = TLI.getStoreMemOperandFlags(SI: I, DL: DAG.getDataLayout());
4891
4892 unsigned ChainI = 0;
4893 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4894 // See visitLoad comments.
4895 if (ChainI == MaxParallelChains) {
4896 SDValue Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4897 Ops: ArrayRef(Chains.data(), ChainI));
4898 Root = Chain;
4899 ChainI = 0;
4900 }
4901
4902 // TODO: MachinePointerInfo only supports a fixed length offset.
4903 MachinePointerInfo PtrInfo =
4904 !Offsets[i].isScalable() || Offsets[i].isZero()
4905 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4906 : MachinePointerInfo();
4907
4908 SDValue Add = DAG.getObjectPtrOffset(SL: dl, Ptr, Offset: Offsets[i]);
4909 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4910 if (MemVTs[i] != ValueVTs[i])
4911 Val = DAG.getPtrExtOrTrunc(Op: Val, DL: dl, VT: MemVTs[i]);
4912 SDValue St =
4913 DAG.getStore(Chain: Root, dl, Val, Ptr: Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4914 Chains[ChainI] = St;
4915 }
4916
4917 SDValue StoreNode = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
4918 Ops: ArrayRef(Chains.data(), ChainI));
4919 setValue(V: &I, NewN: StoreNode);
4920 DAG.setRoot(StoreNode);
4921}
4922
4923void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4924 bool IsCompressing) {
4925 SDLoc sdl = getCurSDLoc();
4926
4927 Value *Src0Operand = I.getArgOperand(i: 0);
4928 Value *PtrOperand = I.getArgOperand(i: 1);
4929 Value *MaskOperand = I.getArgOperand(i: 2);
4930 Align Alignment = I.getParamAlign(ArgNo: 1).valueOrOne();
4931
4932 SDValue Ptr = getValue(V: PtrOperand);
4933 SDValue Src0 = getValue(V: Src0Operand);
4934 SDValue Mask = getValue(V: MaskOperand);
4935 SDValue Offset = DAG.getUNDEF(VT: Ptr.getValueType());
4936
4937 EVT VT = Src0.getValueType();
4938
4939 auto MMOFlags = MachineMemOperand::MOStore;
4940 if (I.hasMetadata(KindID: LLVMContext::MD_nontemporal))
4941 MMOFlags |= MachineMemOperand::MONonTemporal;
4942
4943 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4944 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
4945 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: Alignment, AAInfo: I.getAAMetadata());
4946
4947 const auto &TLI = DAG.getTargetLoweringInfo();
4948
4949 SDValue StoreNode =
4950 !IsCompressing && TTI->hasConditionalLoadStoreForType(
4951 Ty: I.getArgOperand(i: 0)->getType(), /*IsStore=*/true)
4952 ? TLI.visitMaskedStore(DAG, DL: sdl, Chain: getMemoryRoot(), MMO, Ptr, Val: Src0,
4953 Mask)
4954 : DAG.getMaskedStore(Chain: getMemoryRoot(), dl: sdl, Val: Src0, Base: Ptr, Offset, Mask,
4955 MemVT: VT, MMO, AM: ISD::UNINDEXED, /*Truncating=*/IsTruncating: false,
4956 IsCompressing);
4957 DAG.setRoot(StoreNode);
4958 setValue(V: &I, NewN: StoreNode);
4959}
4960
4961// Get a uniform base for the Gather/Scatter intrinsic.
4962// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4963// We try to represent it as a base pointer + vector of indices.
4964// Usually, the vector of pointers comes from a 'getelementptr' instruction.
4965// The first operand of the GEP may be a single pointer or a vector of pointers
4966// Example:
4967// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4968// or
4969// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
4970// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4971//
4972// When the first GEP operand is a single pointer - it is the uniform base we
4973// are looking for. If first operand of the GEP is a splat vector - we
4974// extract the splat value and use it as a uniform base.
4975// In all other cases the function returns 'false'.
4976static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4977 SDValue &Scale, SelectionDAGBuilder *SDB,
4978 const BasicBlock *CurBB, uint64_t ElemSize) {
4979 SelectionDAG& DAG = SDB->DAG;
4980 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4981 const DataLayout &DL = DAG.getDataLayout();
4982
4983 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4984
4985 // Handle splat constant pointer.
4986 if (auto *C = dyn_cast<Constant>(Val: Ptr)) {
4987 C = C->getSplatValue();
4988 if (!C)
4989 return false;
4990
4991 Base = SDB->getValue(V: C);
4992
4993 ElementCount NumElts = cast<VectorType>(Val: Ptr->getType())->getElementCount();
4994 EVT VT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: TLI.getPointerTy(DL), EC: NumElts);
4995 Index = DAG.getConstant(Val: 0, DL: SDB->getCurSDLoc(), VT);
4996 Scale = DAG.getTargetConstant(Val: 1, DL: SDB->getCurSDLoc(), VT: TLI.getPointerTy(DL));
4997 return true;
4998 }
4999
5000 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Val: Ptr);
5001 if (!GEP || GEP->getParent() != CurBB)
5002 return false;
5003
5004 if (GEP->getNumOperands() != 2)
5005 return false;
5006
5007 const Value *BasePtr = GEP->getPointerOperand();
5008 const Value *IndexVal = GEP->getOperand(i_nocapture: GEP->getNumOperands() - 1);
5009
5010 // Make sure the base is scalar and the index is a vector.
5011 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
5012 return false;
5013
5014 TypeSize ScaleVal = DL.getTypeAllocSize(Ty: GEP->getResultElementType());
5015 if (ScaleVal.isScalable())
5016 return false;
5017
5018 // Target may not support the required addressing mode.
5019 if (ScaleVal != 1 &&
5020 !TLI.isLegalScaleForGatherScatter(Scale: ScaleVal.getFixedValue(), ElemSize))
5021 return false;
5022
5023 Base = SDB->getValue(V: BasePtr);
5024 Index = SDB->getValue(V: IndexVal);
5025
5026 Scale =
5027 DAG.getTargetConstant(Val: ScaleVal, DL: SDB->getCurSDLoc(), VT: TLI.getPointerTy(DL));
5028 return true;
5029}
5030
5031void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
5032 SDLoc sdl = getCurSDLoc();
5033
5034 // llvm.masked.scatter.*(Src0, Ptrs, Mask)
5035 const Value *Ptr = I.getArgOperand(i: 1);
5036 SDValue Src0 = getValue(V: I.getArgOperand(i: 0));
5037 SDValue Mask = getValue(V: I.getArgOperand(i: 2));
5038 EVT VT = Src0.getValueType();
5039 Align Alignment = I.getParamAlign(ArgNo: 1).valueOrOne();
5040 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5041
5042 SDValue Base;
5043 SDValue Index;
5044 SDValue Scale;
5045 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, SDB: this,
5046 CurBB: I.getParent(), ElemSize: VT.getScalarStoreSize());
5047
5048 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5049 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5050 PtrInfo: MachinePointerInfo(AS), F: MachineMemOperand::MOStore,
5051 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: Alignment, AAInfo: I.getAAMetadata());
5052 if (!UniformBase) {
5053 Base = DAG.getConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5054 Index = getValue(V: Ptr);
5055 Scale =
5056 DAG.getTargetConstant(Val: 1, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5057 }
5058
5059 EVT IdxVT = Index.getValueType();
5060 EVT EltTy = IdxVT.getVectorElementType();
5061 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
5062 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
5063 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: sdl, VT: NewIdxVT, Operand: Index);
5064 }
5065
5066 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
5067 SDValue Scatter = DAG.getMaskedScatter(VTs: DAG.getVTList(VT: MVT::Other), MemVT: VT, dl: sdl,
5068 Ops, MMO, IndexType: ISD::SIGNED_SCALED, IsTruncating: false);
5069 DAG.setRoot(Scatter);
5070 setValue(V: &I, NewN: Scatter);
5071}
5072
5073void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
5074 SDLoc sdl = getCurSDLoc();
5075
5076 Value *PtrOperand = I.getArgOperand(i: 0);
5077 Value *MaskOperand = I.getArgOperand(i: 1);
5078 Value *Src0Operand = I.getArgOperand(i: 2);
5079 Align Alignment = I.getParamAlign(ArgNo: 0).valueOrOne();
5080
5081 SDValue Ptr = getValue(V: PtrOperand);
5082 SDValue Src0 = getValue(V: Src0Operand);
5083 SDValue Mask = getValue(V: MaskOperand);
5084 SDValue Offset = DAG.getUNDEF(VT: Ptr.getValueType());
5085
5086 EVT VT = Src0.getValueType();
5087 AAMDNodes AAInfo = I.getAAMetadata();
5088 const MDNode *Ranges = getRangeMetadata(I);
5089
5090 // Do not serialize masked loads of constant memory with anything.
5091 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
5092 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
5093
5094 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
5095
5096 auto MMOFlags = MachineMemOperand::MOLoad;
5097 if (I.hasMetadata(KindID: LLVMContext::MD_nontemporal))
5098 MMOFlags |= MachineMemOperand::MONonTemporal;
5099 if (I.hasMetadata(KindID: LLVMContext::MD_invariant_load))
5100 MMOFlags |= MachineMemOperand::MOInvariant;
5101
5102 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5103 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
5104 Size: VT.getStoreSize(), BaseAlignment: Alignment, AAInfo, Ranges);
5105
5106 const auto &TLI = DAG.getTargetLoweringInfo();
5107
5108 // The Load/Res may point to different values and both of them are output
5109 // variables.
5110 SDValue Load;
5111 SDValue Res;
5112 if (!IsExpanding &&
5113 TTI->hasConditionalLoadStoreForType(Ty: Src0Operand->getType(),
5114 /*IsStore=*/false))
5115 Res = TLI.visitMaskedLoad(DAG, DL: sdl, Chain: InChain, MMO, NewLoad&: Load, Ptr, PassThru: Src0, Mask);
5116 else
5117 Res = Load =
5118 DAG.getMaskedLoad(VT, dl: sdl, Chain: InChain, Base: Ptr, Offset, Mask, Src0, MemVT: VT, MMO,
5119 AM: ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5120 if (AddToChain)
5121 PendingLoads.push_back(Elt: Load.getValue(R: 1));
5122 setValue(V: &I, NewN: Res);
5123}
5124
5125void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5126 SDLoc sdl = getCurSDLoc();
5127
5128 // @llvm.masked.gather.*(Ptrs, Mask, Src0)
5129 const Value *Ptr = I.getArgOperand(i: 0);
5130 SDValue Src0 = getValue(V: I.getArgOperand(i: 2));
5131 SDValue Mask = getValue(V: I.getArgOperand(i: 1));
5132
5133 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5134 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
5135 Align Alignment = I.getParamAlign(ArgNo: 0).valueOrOne();
5136
5137 const MDNode *Ranges = getRangeMetadata(I);
5138
5139 SDValue Root = DAG.getRoot();
5140 SDValue Base;
5141 SDValue Index;
5142 SDValue Scale;
5143 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, SDB: this,
5144 CurBB: I.getParent(), ElemSize: VT.getScalarStoreSize());
5145 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5146 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5147 PtrInfo: MachinePointerInfo(AS), F: MachineMemOperand::MOLoad,
5148 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: Alignment, AAInfo: I.getAAMetadata(),
5149 Ranges);
5150
5151 if (!UniformBase) {
5152 Base = DAG.getConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5153 Index = getValue(V: Ptr);
5154 Scale =
5155 DAG.getTargetConstant(Val: 1, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
5156 }
5157
5158 EVT IdxVT = Index.getValueType();
5159 EVT EltTy = IdxVT.getVectorElementType();
5160 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
5161 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
5162 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: sdl, VT: NewIdxVT, Operand: Index);
5163 }
5164
5165 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5166 SDValue Gather =
5167 DAG.getMaskedGather(VTs: DAG.getVTList(VT1: VT, VT2: MVT::Other), MemVT: VT, dl: sdl, Ops, MMO,
5168 IndexType: ISD::SIGNED_SCALED, ExtTy: ISD::NON_EXTLOAD);
5169
5170 PendingLoads.push_back(Elt: Gather.getValue(R: 1));
5171 setValue(V: &I, NewN: Gather);
5172}
5173
5174void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5175 SDLoc dl = getCurSDLoc();
5176 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5177 AtomicOrdering FailureOrdering = I.getFailureOrdering();
5178 SyncScope::ID SSID = I.getSyncScopeID();
5179
5180 SDValue InChain = getRoot();
5181
5182 MVT MemVT = getValue(V: I.getCompareOperand()).getSimpleValueType();
5183 SDVTList VTs = DAG.getVTList(VT1: MemVT, VT2: MVT::i1, VT3: MVT::Other);
5184
5185 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5186 auto Flags = TLI.getAtomicMemOperandFlags(AI: I, DL: DAG.getDataLayout());
5187
5188 MachineFunction &MF = DAG.getMachineFunction();
5189 MachineMemOperand *MMO = MF.getMachineMemOperand(
5190 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5191 BaseAlignment: DAG.getEVTAlign(MemoryVT: MemVT), AAInfo: AAMDNodes(), Ranges: nullptr, SSID, Ordering: SuccessOrdering,
5192 FailureOrdering);
5193
5194 SDValue L = DAG.getAtomicCmpSwap(Opcode: ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5195 dl, MemVT, VTs, Chain: InChain,
5196 Ptr: getValue(V: I.getPointerOperand()),
5197 Cmp: getValue(V: I.getCompareOperand()),
5198 Swp: getValue(V: I.getNewValOperand()), MMO);
5199
5200 SDValue OutChain = L.getValue(R: 2);
5201
5202 setValue(V: &I, NewN: L);
5203 DAG.setRoot(OutChain);
5204}
5205
5206void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5207 SDLoc dl = getCurSDLoc();
5208 ISD::NodeType NT;
5209 switch (I.getOperation()) {
5210 default: llvm_unreachable("Unknown atomicrmw operation");
5211 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5212 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
5213 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
5214 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
5215 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5216 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
5217 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
5218 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
5219 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
5220 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5221 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5222 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5223 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5224 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5225 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5226 case AtomicRMWInst::FMaximum:
5227 NT = ISD::ATOMIC_LOAD_FMAXIMUM;
5228 break;
5229 case AtomicRMWInst::FMinimum:
5230 NT = ISD::ATOMIC_LOAD_FMINIMUM;
5231 break;
5232 case AtomicRMWInst::UIncWrap:
5233 NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5234 break;
5235 case AtomicRMWInst::UDecWrap:
5236 NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5237 break;
5238 case AtomicRMWInst::USubCond:
5239 NT = ISD::ATOMIC_LOAD_USUB_COND;
5240 break;
5241 case AtomicRMWInst::USubSat:
5242 NT = ISD::ATOMIC_LOAD_USUB_SAT;
5243 break;
5244 }
5245 AtomicOrdering Ordering = I.getOrdering();
5246 SyncScope::ID SSID = I.getSyncScopeID();
5247
5248 SDValue InChain = getRoot();
5249
5250 auto MemVT = getValue(V: I.getValOperand()).getSimpleValueType();
5251 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5252 auto Flags = TLI.getAtomicMemOperandFlags(AI: I, DL: DAG.getDataLayout());
5253
5254 MachineFunction &MF = DAG.getMachineFunction();
5255 MachineMemOperand *MMO = MF.getMachineMemOperand(
5256 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5257 BaseAlignment: DAG.getEVTAlign(MemoryVT: MemVT), AAInfo: AAMDNodes(), Ranges: nullptr, SSID, Ordering);
5258
5259 SDValue L =
5260 DAG.getAtomic(Opcode: NT, dl, MemVT, Chain: InChain,
5261 Ptr: getValue(V: I.getPointerOperand()), Val: getValue(V: I.getValOperand()),
5262 MMO);
5263
5264 SDValue OutChain = L.getValue(R: 1);
5265
5266 setValue(V: &I, NewN: L);
5267 DAG.setRoot(OutChain);
5268}
5269
5270void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5271 SDLoc dl = getCurSDLoc();
5272 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5273 SDValue Ops[3];
5274 Ops[0] = getRoot();
5275 Ops[1] = DAG.getTargetConstant(Val: (unsigned)I.getOrdering(), DL: dl,
5276 VT: TLI.getFenceOperandTy(DL: DAG.getDataLayout()));
5277 Ops[2] = DAG.getTargetConstant(Val: I.getSyncScopeID(), DL: dl,
5278 VT: TLI.getFenceOperandTy(DL: DAG.getDataLayout()));
5279 SDValue N = DAG.getNode(Opcode: ISD::ATOMIC_FENCE, DL: dl, VT: MVT::Other, Ops);
5280 setValue(V: &I, NewN: N);
5281 DAG.setRoot(N);
5282}
5283
5284void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5285 SDLoc dl = getCurSDLoc();
5286 AtomicOrdering Order = I.getOrdering();
5287 SyncScope::ID SSID = I.getSyncScopeID();
5288
5289 SDValue InChain = getRoot();
5290
5291 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5292 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
5293 EVT MemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getType());
5294
5295 if (!TLI.supportsUnalignedAtomics() &&
5296 I.getAlign().value() < MemVT.getSizeInBits() / 8)
5297 report_fatal_error(reason: "Cannot generate unaligned atomic load");
5298
5299 auto Flags = TLI.getLoadMemOperandFlags(LI: I, DL: DAG.getDataLayout(), AC, LibInfo);
5300
5301 const MDNode *Ranges = getRangeMetadata(I);
5302 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5303 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5304 BaseAlignment: I.getAlign(), AAInfo: AAMDNodes(), Ranges, SSID, Ordering: Order);
5305
5306 InChain = TLI.prepareVolatileOrAtomicLoad(Chain: InChain, DL: dl, DAG);
5307
5308 SDValue Ptr = getValue(V: I.getPointerOperand());
5309 SDValue L =
5310 DAG.getAtomicLoad(ExtType: ISD::NON_EXTLOAD, dl, MemVT, VT: MemVT, Chain: InChain, Ptr, MMO);
5311
5312 SDValue OutChain = L.getValue(R: 1);
5313 if (MemVT != VT)
5314 L = DAG.getPtrExtOrTrunc(Op: L, DL: dl, VT);
5315
5316 setValue(V: &I, NewN: L);
5317 DAG.setRoot(OutChain);
5318}
5319
5320void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5321 SDLoc dl = getCurSDLoc();
5322
5323 AtomicOrdering Ordering = I.getOrdering();
5324 SyncScope::ID SSID = I.getSyncScopeID();
5325
5326 SDValue InChain = getRoot();
5327
5328 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5329 EVT MemVT =
5330 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getValueOperand()->getType());
5331
5332 if (!TLI.supportsUnalignedAtomics() &&
5333 I.getAlign().value() < MemVT.getSizeInBits() / 8)
5334 report_fatal_error(reason: "Cannot generate unaligned atomic store");
5335
5336 auto Flags = TLI.getStoreMemOperandFlags(SI: I, DL: DAG.getDataLayout());
5337
5338 MachineFunction &MF = DAG.getMachineFunction();
5339 MachineMemOperand *MMO = MF.getMachineMemOperand(
5340 PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, Size: MemVT.getStoreSize(),
5341 BaseAlignment: I.getAlign(), AAInfo: AAMDNodes(), Ranges: nullptr, SSID, Ordering);
5342
5343 SDValue Val = getValue(V: I.getValueOperand());
5344 if (Val.getValueType() != MemVT)
5345 Val = DAG.getPtrExtOrTrunc(Op: Val, DL: dl, VT: MemVT);
5346 SDValue Ptr = getValue(V: I.getPointerOperand());
5347
5348 SDValue OutChain =
5349 DAG.getAtomic(Opcode: ISD::ATOMIC_STORE, dl, MemVT, Chain: InChain, Ptr: Val, Val: Ptr, MMO);
5350
5351 setValue(V: &I, NewN: OutChain);
5352 DAG.setRoot(OutChain);
5353}
5354
5355/// Check if this intrinsic call depends on the chain (1st return value)
5356/// and if it only *loads* memory.
5357/// Ignore the callsite's attributes. A specific call site may be marked with
5358/// readnone, but the lowering code will expect the chain based on the
5359/// definition.
5360std::pair<bool, bool>
5361SelectionDAGBuilder::getTargetIntrinsicCallProperties(const CallBase &I) {
5362 const Function *F = I.getCalledFunction();
5363 bool HasChain = !F->doesNotAccessMemory();
5364 bool OnlyLoad =
5365 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5366
5367 return {HasChain, OnlyLoad};
5368}
5369
5370SmallVector<SDValue, 8> SelectionDAGBuilder::getTargetIntrinsicOperands(
5371 const CallBase &I, bool HasChain, bool OnlyLoad,
5372 TargetLowering::IntrinsicInfo *TgtMemIntrinsicInfo) {
5373 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5374
5375 // Build the operand list.
5376 SmallVector<SDValue, 8> Ops;
5377 if (HasChain) { // If this intrinsic has side-effects, chainify it.
5378 if (OnlyLoad) {
5379 // We don't need to serialize loads against other loads.
5380 Ops.push_back(Elt: DAG.getRoot());
5381 } else {
5382 Ops.push_back(Elt: getRoot());
5383 }
5384 }
5385
5386 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5387 if (!TgtMemIntrinsicInfo || TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_VOID ||
5388 TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_W_CHAIN)
5389 Ops.push_back(Elt: DAG.getTargetConstant(Val: I.getIntrinsicID(), DL: getCurSDLoc(),
5390 VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
5391
5392 // Add all operands of the call to the operand list.
5393 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5394 const Value *Arg = I.getArgOperand(i);
5395 if (!I.paramHasAttr(ArgNo: i, Kind: Attribute::ImmArg)) {
5396 Ops.push_back(Elt: getValue(V: Arg));
5397 continue;
5398 }
5399
5400 // Use TargetConstant instead of a regular constant for immarg.
5401 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: Arg->getType(), AllowUnknown: true);
5402 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: Arg)) {
5403 assert(CI->getBitWidth() <= 64 &&
5404 "large intrinsic immediates not handled");
5405 Ops.push_back(Elt: DAG.getTargetConstant(Val: *CI, DL: SDLoc(), VT));
5406 } else {
5407 Ops.push_back(
5408 Elt: DAG.getTargetConstantFP(Val: *cast<ConstantFP>(Val: Arg), DL: SDLoc(), VT));
5409 }
5410 }
5411
5412 if (std::optional<OperandBundleUse> Bundle =
5413 I.getOperandBundle(ID: LLVMContext::OB_deactivation_symbol)) {
5414 auto *Sym = Bundle->Inputs[0].get();
5415 SDValue SDSym = getValue(V: Sym);
5416 SDSym = DAG.getDeactivationSymbol(GV: cast<GlobalValue>(Val: Sym));
5417 Ops.push_back(Elt: SDSym);
5418 }
5419
5420 if (std::optional<OperandBundleUse> Bundle =
5421 I.getOperandBundle(ID: LLVMContext::OB_convergencectrl)) {
5422 Value *Token = Bundle->Inputs[0].get();
5423 SDValue ConvControlToken = getValue(V: Token);
5424 assert(Ops.back().getValueType() != MVT::Glue &&
5425 "Did not expect another glue node here.");
5426 ConvControlToken =
5427 DAG.getNode(Opcode: ISD::CONVERGENCECTRL_GLUE, DL: {}, VT: MVT::Glue, Operand: ConvControlToken);
5428 Ops.push_back(Elt: ConvControlToken);
5429 }
5430
5431 return Ops;
5432}
5433
5434SDVTList SelectionDAGBuilder::getTargetIntrinsicVTList(const CallBase &I,
5435 bool HasChain) {
5436 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5437
5438 SmallVector<EVT, 4> ValueVTs;
5439 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: I.getType(), ValueVTs);
5440
5441 if (HasChain)
5442 ValueVTs.push_back(Elt: MVT::Other);
5443
5444 return DAG.getVTList(VTs: ValueVTs);
5445}
5446
5447/// Get an INTRINSIC node for a target intrinsic which does not touch memory.
5448SDValue SelectionDAGBuilder::getTargetNonMemIntrinsicNode(
5449 const Type &IntrinsicVT, bool HasChain, ArrayRef<SDValue> Ops,
5450 const SDVTList &VTs) {
5451 if (!HasChain)
5452 return DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: getCurSDLoc(), VTList: VTs, Ops);
5453 if (!IntrinsicVT.isVoidTy())
5454 return DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL: getCurSDLoc(), VTList: VTs, Ops);
5455 return DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL: getCurSDLoc(), VTList: VTs, Ops);
5456}
5457
5458/// Set root, convert return type if necessary and check alignment.
5459SDValue SelectionDAGBuilder::handleTargetIntrinsicRet(const CallBase &I,
5460 bool HasChain,
5461 bool OnlyLoad,
5462 SDValue Result) {
5463 if (HasChain) {
5464 SDValue Chain = Result.getValue(R: Result.getNode()->getNumValues() - 1);
5465 if (OnlyLoad)
5466 PendingLoads.push_back(Elt: Chain);
5467 else
5468 DAG.setRoot(Chain);
5469 }
5470
5471 if (I.getType()->isVoidTy())
5472 return Result;
5473
5474 if (MaybeAlign Alignment = I.getRetAlign(); InsertAssertAlign && Alignment) {
5475 // Insert `assertalign` node if there's an alignment.
5476 Result = DAG.getAssertAlign(DL: getCurSDLoc(), V: Result, A: Alignment.valueOrOne());
5477 } else if (!isa<VectorType>(Val: I.getType())) {
5478 Result = lowerRangeToAssertZExt(DAG, I, Op: Result);
5479 }
5480
5481 return Result;
5482}
5483
5484/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5485/// node.
5486void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5487 unsigned Intrinsic) {
5488 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
5489
5490 // Infos is set by getTgtMemIntrinsic.
5491 SmallVector<TargetLowering::IntrinsicInfo> Infos;
5492 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5493 TLI.getTgtMemIntrinsic(Infos, I, MF&: DAG.getMachineFunction(), Intrinsic);
5494 // Use the first (primary) info determines the node opcode.
5495 TargetLowering::IntrinsicInfo *Info = !Infos.empty() ? &Infos[0] : nullptr;
5496
5497 SmallVector<SDValue, 8> Ops =
5498 getTargetIntrinsicOperands(I, HasChain, OnlyLoad, TgtMemIntrinsicInfo: Info);
5499 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
5500
5501 // Propagate fast-math-flags from IR to node(s).
5502 SDNodeFlags Flags;
5503 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &I))
5504 Flags.copyFMF(FPMO: *FPMO);
5505 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5506
5507 // Create the node.
5508 SDValue Result;
5509
5510 // In some cases, custom collection of operands from CallInst I may be needed.
5511 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5512 if (!Infos.empty()) {
5513 // This is target intrinsic that touches memory
5514 // Create MachineMemOperands for each memory access described by the target.
5515 MachineFunction &MF = DAG.getMachineFunction();
5516 SmallVector<MachineMemOperand *> MMOs;
5517 for (const auto &Info : Infos) {
5518 // TODO: We currently just fallback to address space 0 if
5519 // getTgtMemIntrinsic didn't yield anything useful.
5520 MachinePointerInfo MPI;
5521 if (Info.ptrVal)
5522 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5523 else if (Info.fallbackAddressSpace)
5524 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5525 EVT MemVT = Info.memVT;
5526 LocationSize Size = LocationSize::precise(Value: Info.size);
5527 if (Size.hasValue() && !Size.getValue())
5528 Size = LocationSize::precise(Value: MemVT.getStoreSize());
5529 Align Alignment = Info.align.value_or(u: DAG.getEVTAlign(MemoryVT: MemVT));
5530 MachineMemOperand *MMO = MF.getMachineMemOperand(
5531 PtrInfo: MPI, F: Info.flags, Size, BaseAlignment: Alignment, AAInfo: I.getAAMetadata(),
5532 /*Ranges=*/nullptr, SSID: Info.ssid, Ordering: Info.order, FailureOrdering: Info.failureOrder);
5533 MMOs.push_back(Elt: MMO);
5534 }
5535
5536 Result = DAG.getMemIntrinsicNode(Opcode: Info->opc, dl: getCurSDLoc(), VTList: VTs, Ops,
5537 MemVT: Info->memVT, MMOs);
5538 } else {
5539 Result = getTargetNonMemIntrinsicNode(IntrinsicVT: *I.getType(), HasChain, Ops, VTs);
5540 }
5541
5542 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
5543
5544 setValue(V: &I, NewN: Result);
5545}
5546
5547/// GetSignificand - Get the significand and build it into a floating-point
5548/// number with exponent of 1:
5549///
5550/// Op = (Op & 0x007fffff) | 0x3f800000;
5551///
5552/// where Op is the hexadecimal representation of floating point value.
5553static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5554 SDValue t1 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: Op,
5555 N2: DAG.getConstant(Val: 0x007fffff, DL: dl, VT: MVT::i32));
5556 SDValue t2 = DAG.getNode(Opcode: ISD::OR, DL: dl, VT: MVT::i32, N1: t1,
5557 N2: DAG.getConstant(Val: 0x3f800000, DL: dl, VT: MVT::i32));
5558 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f32, Operand: t2);
5559}
5560
5561/// GetExponent - Get the exponent:
5562///
5563/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5564///
5565/// where Op is the hexadecimal representation of floating point value.
5566static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5567 const TargetLowering &TLI, const SDLoc &dl) {
5568 SDValue t0 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: Op,
5569 N2: DAG.getConstant(Val: 0x7f800000, DL: dl, VT: MVT::i32));
5570 SDValue t1 = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32, N1: t0,
5571 N2: DAG.getShiftAmountConstant(Val: 23, VT: MVT::i32, DL: dl));
5572 SDValue t2 = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32, N1: t1,
5573 N2: DAG.getConstant(Val: 127, DL: dl, VT: MVT::i32));
5574 return DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::f32, Operand: t2);
5575}
5576
5577/// getF32Constant - Get 32-bit floating point constant.
5578static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5579 const SDLoc &dl) {
5580 return DAG.getConstantFP(Val: APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), DL: dl,
5581 VT: MVT::f32);
5582}
5583
5584static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5585 SelectionDAG &DAG) {
5586 // TODO: What fast-math-flags should be set on the floating-point nodes?
5587
5588 // IntegerPartOfX = ((int32_t)(t0);
5589 SDValue IntegerPartOfX = DAG.getNode(Opcode: ISD::FP_TO_SINT, DL: dl, VT: MVT::i32, Operand: t0);
5590
5591 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
5592 SDValue t1 = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::f32, Operand: IntegerPartOfX);
5593 SDValue X = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t0, N2: t1);
5594
5595 // IntegerPartOfX <<= 23;
5596 IntegerPartOfX = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT: MVT::i32, N1: IntegerPartOfX,
5597 N2: DAG.getShiftAmountConstant(Val: 23, VT: MVT::i32, DL: dl));
5598
5599 SDValue TwoToFractionalPartOfX;
5600 if (LimitFloatPrecision <= 6) {
5601 // For floating-point precision of 6:
5602 //
5603 // TwoToFractionalPartOfX =
5604 // 0.997535578f +
5605 // (0.735607626f + 0.252464424f * x) * x;
5606 //
5607 // error 0.0144103317, which is 6 bits
5608 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5609 N2: getF32Constant(DAG, Flt: 0x3e814304, dl));
5610 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5611 N2: getF32Constant(DAG, Flt: 0x3f3c50c8, dl));
5612 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5613 TwoToFractionalPartOfX = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5614 N2: getF32Constant(DAG, Flt: 0x3f7f5e7e, dl));
5615 } else if (LimitFloatPrecision <= 12) {
5616 // For floating-point precision of 12:
5617 //
5618 // TwoToFractionalPartOfX =
5619 // 0.999892986f +
5620 // (0.696457318f +
5621 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
5622 //
5623 // error 0.000107046256, which is 13 to 14 bits
5624 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5625 N2: getF32Constant(DAG, Flt: 0x3da235e3, dl));
5626 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5627 N2: getF32Constant(DAG, Flt: 0x3e65b8f3, dl));
5628 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5629 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5630 N2: getF32Constant(DAG, Flt: 0x3f324b07, dl));
5631 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5632 TwoToFractionalPartOfX = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t6,
5633 N2: getF32Constant(DAG, Flt: 0x3f7ff8fd, dl));
5634 } else { // LimitFloatPrecision <= 18
5635 // For floating-point precision of 18:
5636 //
5637 // TwoToFractionalPartOfX =
5638 // 0.999999982f +
5639 // (0.693148872f +
5640 // (0.240227044f +
5641 // (0.554906021e-1f +
5642 // (0.961591928e-2f +
5643 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5644 // error 2.47208000*10^(-7), which is better than 18 bits
5645 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5646 N2: getF32Constant(DAG, Flt: 0x3924b03e, dl));
5647 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5648 N2: getF32Constant(DAG, Flt: 0x3ab24b87, dl));
5649 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5650 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5651 N2: getF32Constant(DAG, Flt: 0x3c1d8c17, dl));
5652 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5653 SDValue t7 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t6,
5654 N2: getF32Constant(DAG, Flt: 0x3d634a1d, dl));
5655 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
5656 SDValue t9 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t8,
5657 N2: getF32Constant(DAG, Flt: 0x3e75fe14, dl));
5658 SDValue t10 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t9, N2: X);
5659 SDValue t11 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t10,
5660 N2: getF32Constant(DAG, Flt: 0x3f317234, dl));
5661 SDValue t12 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t11, N2: X);
5662 TwoToFractionalPartOfX = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t12,
5663 N2: getF32Constant(DAG, Flt: 0x3f800000, dl));
5664 }
5665
5666 // Add the exponent into the result in integer domain.
5667 SDValue t13 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: TwoToFractionalPartOfX);
5668 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f32,
5669 Operand: DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: t13, N2: IntegerPartOfX));
5670}
5671
5672/// expandExp - Lower an exp intrinsic. Handles the special sequences for
5673/// limited-precision mode.
5674static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5675 const TargetLowering &TLI, SDNodeFlags Flags) {
5676 if (Op.getValueType() == MVT::f32 &&
5677 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5678
5679 // Put the exponent in the right bit position for later addition to the
5680 // final result:
5681 //
5682 // t0 = Op * log2(e)
5683
5684 // TODO: What fast-math-flags should be set here?
5685 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: Op,
5686 N2: DAG.getConstantFP(Val: numbers::log2ef, DL: dl, VT: MVT::f32));
5687 return getLimitedPrecisionExp2(t0, dl, DAG);
5688 }
5689
5690 // No special expansion.
5691 return DAG.getNode(Opcode: ISD::FEXP, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5692}
5693
5694/// expandLog - Lower a log intrinsic. Handles the special sequences for
5695/// limited-precision mode.
5696static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5697 const TargetLowering &TLI, SDNodeFlags Flags) {
5698 // TODO: What fast-math-flags should be set on the floating-point nodes?
5699
5700 if (Op.getValueType() == MVT::f32 &&
5701 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5702 SDValue Op1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Op);
5703
5704 // Scale the exponent by log(2).
5705 SDValue Exp = GetExponent(DAG, Op: Op1, TLI, dl);
5706 SDValue LogOfExponent =
5707 DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: Exp,
5708 N2: DAG.getConstantFP(Val: numbers::ln2f, DL: dl, VT: MVT::f32));
5709
5710 // Get the significand and build it into a floating-point number with
5711 // exponent of 1.
5712 SDValue X = GetSignificand(DAG, Op: Op1, dl);
5713
5714 SDValue LogOfMantissa;
5715 if (LimitFloatPrecision <= 6) {
5716 // For floating-point precision of 6:
5717 //
5718 // LogofMantissa =
5719 // -1.1609546f +
5720 // (1.4034025f - 0.23903021f * x) * x;
5721 //
5722 // error 0.0034276066, which is better than 8 bits
5723 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5724 N2: getF32Constant(DAG, Flt: 0xbe74c456, dl));
5725 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5726 N2: getF32Constant(DAG, Flt: 0x3fb3a2b1, dl));
5727 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5728 LogOfMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5729 N2: getF32Constant(DAG, Flt: 0x3f949a29, dl));
5730 } else if (LimitFloatPrecision <= 12) {
5731 // For floating-point precision of 12:
5732 //
5733 // LogOfMantissa =
5734 // -1.7417939f +
5735 // (2.8212026f +
5736 // (-1.4699568f +
5737 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5738 //
5739 // error 0.000061011436, which is 14 bits
5740 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5741 N2: getF32Constant(DAG, Flt: 0xbd67b6d6, dl));
5742 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5743 N2: getF32Constant(DAG, Flt: 0x3ee4f4b8, dl));
5744 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5745 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5746 N2: getF32Constant(DAG, Flt: 0x3fbc278b, dl));
5747 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5748 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5749 N2: getF32Constant(DAG, Flt: 0x40348e95, dl));
5750 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5751 LogOfMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5752 N2: getF32Constant(DAG, Flt: 0x3fdef31a, dl));
5753 } else { // LimitFloatPrecision <= 18
5754 // For floating-point precision of 18:
5755 //
5756 // LogOfMantissa =
5757 // -2.1072184f +
5758 // (4.2372794f +
5759 // (-3.7029485f +
5760 // (2.2781945f +
5761 // (-0.87823314f +
5762 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5763 //
5764 // error 0.0000023660568, which is better than 18 bits
5765 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5766 N2: getF32Constant(DAG, Flt: 0xbc91e5ac, dl));
5767 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5768 N2: getF32Constant(DAG, Flt: 0x3e4350aa, dl));
5769 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5770 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5771 N2: getF32Constant(DAG, Flt: 0x3f60d3e3, dl));
5772 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5773 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5774 N2: getF32Constant(DAG, Flt: 0x4011cdf0, dl));
5775 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5776 SDValue t7 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5777 N2: getF32Constant(DAG, Flt: 0x406cfd1c, dl));
5778 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
5779 SDValue t9 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t8,
5780 N2: getF32Constant(DAG, Flt: 0x408797cb, dl));
5781 SDValue t10 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t9, N2: X);
5782 LogOfMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t10,
5783 N2: getF32Constant(DAG, Flt: 0x4006dcab, dl));
5784 }
5785
5786 return DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: LogOfExponent, N2: LogOfMantissa);
5787 }
5788
5789 // No special expansion.
5790 return DAG.getNode(Opcode: ISD::FLOG, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5791}
5792
5793/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5794/// limited-precision mode.
5795static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5796 const TargetLowering &TLI, SDNodeFlags Flags) {
5797 // TODO: What fast-math-flags should be set on the floating-point nodes?
5798
5799 if (Op.getValueType() == MVT::f32 &&
5800 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5801 SDValue Op1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Op);
5802
5803 // Get the exponent.
5804 SDValue LogOfExponent = GetExponent(DAG, Op: Op1, TLI, dl);
5805
5806 // Get the significand and build it into a floating-point number with
5807 // exponent of 1.
5808 SDValue X = GetSignificand(DAG, Op: Op1, dl);
5809
5810 // Different possible minimax approximations of significand in
5811 // floating-point for various degrees of accuracy over [1,2].
5812 SDValue Log2ofMantissa;
5813 if (LimitFloatPrecision <= 6) {
5814 // For floating-point precision of 6:
5815 //
5816 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5817 //
5818 // error 0.0049451742, which is more than 7 bits
5819 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5820 N2: getF32Constant(DAG, Flt: 0xbeb08fe0, dl));
5821 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5822 N2: getF32Constant(DAG, Flt: 0x40019463, dl));
5823 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5824 Log2ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5825 N2: getF32Constant(DAG, Flt: 0x3fd6633d, dl));
5826 } else if (LimitFloatPrecision <= 12) {
5827 // For floating-point precision of 12:
5828 //
5829 // Log2ofMantissa =
5830 // -2.51285454f +
5831 // (4.07009056f +
5832 // (-2.12067489f +
5833 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5834 //
5835 // error 0.0000876136000, which is better than 13 bits
5836 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5837 N2: getF32Constant(DAG, Flt: 0xbda7262e, dl));
5838 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5839 N2: getF32Constant(DAG, Flt: 0x3f25280b, dl));
5840 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5841 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5842 N2: getF32Constant(DAG, Flt: 0x4007b923, dl));
5843 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5844 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5845 N2: getF32Constant(DAG, Flt: 0x40823e2f, dl));
5846 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5847 Log2ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5848 N2: getF32Constant(DAG, Flt: 0x4020d29c, dl));
5849 } else { // LimitFloatPrecision <= 18
5850 // For floating-point precision of 18:
5851 //
5852 // Log2ofMantissa =
5853 // -3.0400495f +
5854 // (6.1129976f +
5855 // (-5.3420409f +
5856 // (3.2865683f +
5857 // (-1.2669343f +
5858 // (0.27515199f -
5859 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5860 //
5861 // error 0.0000018516, which is better than 18 bits
5862 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5863 N2: getF32Constant(DAG, Flt: 0xbcd2769e, dl));
5864 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5865 N2: getF32Constant(DAG, Flt: 0x3e8ce0b9, dl));
5866 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5867 SDValue t3 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5868 N2: getF32Constant(DAG, Flt: 0x3fa22ae7, dl));
5869 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5870 SDValue t5 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t4,
5871 N2: getF32Constant(DAG, Flt: 0x40525723, dl));
5872 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5873 SDValue t7 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t6,
5874 N2: getF32Constant(DAG, Flt: 0x40aaf200, dl));
5875 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
5876 SDValue t9 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t8,
5877 N2: getF32Constant(DAG, Flt: 0x40c39dad, dl));
5878 SDValue t10 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t9, N2: X);
5879 Log2ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t10,
5880 N2: getF32Constant(DAG, Flt: 0x4042902c, dl));
5881 }
5882
5883 return DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: LogOfExponent, N2: Log2ofMantissa);
5884 }
5885
5886 // No special expansion.
5887 return DAG.getNode(Opcode: ISD::FLOG2, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5888}
5889
5890/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5891/// limited-precision mode.
5892static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5893 const TargetLowering &TLI, SDNodeFlags Flags) {
5894 // TODO: What fast-math-flags should be set on the floating-point nodes?
5895
5896 if (Op.getValueType() == MVT::f32 &&
5897 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5898 SDValue Op1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Op);
5899
5900 // Scale the exponent by log10(2) [0.30102999f].
5901 SDValue Exp = GetExponent(DAG, Op: Op1, TLI, dl);
5902 SDValue LogOfExponent = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: Exp,
5903 N2: getF32Constant(DAG, Flt: 0x3e9a209a, dl));
5904
5905 // Get the significand and build it into a floating-point number with
5906 // exponent of 1.
5907 SDValue X = GetSignificand(DAG, Op: Op1, dl);
5908
5909 SDValue Log10ofMantissa;
5910 if (LimitFloatPrecision <= 6) {
5911 // For floating-point precision of 6:
5912 //
5913 // Log10ofMantissa =
5914 // -0.50419619f +
5915 // (0.60948995f - 0.10380950f * x) * x;
5916 //
5917 // error 0.0014886165, which is 6 bits
5918 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5919 N2: getF32Constant(DAG, Flt: 0xbdd49a13, dl));
5920 SDValue t1 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t0,
5921 N2: getF32Constant(DAG, Flt: 0x3f1c0789, dl));
5922 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5923 Log10ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t2,
5924 N2: getF32Constant(DAG, Flt: 0x3f011300, dl));
5925 } else if (LimitFloatPrecision <= 12) {
5926 // For floating-point precision of 12:
5927 //
5928 // Log10ofMantissa =
5929 // -0.64831180f +
5930 // (0.91751397f +
5931 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5932 //
5933 // error 0.00019228036, which is better than 12 bits
5934 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5935 N2: getF32Constant(DAG, Flt: 0x3d431f31, dl));
5936 SDValue t1 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t0,
5937 N2: getF32Constant(DAG, Flt: 0x3ea21fb2, dl));
5938 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5939 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5940 N2: getF32Constant(DAG, Flt: 0x3f6ae232, dl));
5941 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5942 Log10ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t4,
5943 N2: getF32Constant(DAG, Flt: 0x3f25f7c3, dl));
5944 } else { // LimitFloatPrecision <= 18
5945 // For floating-point precision of 18:
5946 //
5947 // Log10ofMantissa =
5948 // -0.84299375f +
5949 // (1.5327582f +
5950 // (-1.0688956f +
5951 // (0.49102474f +
5952 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5953 //
5954 // error 0.0000037995730, which is better than 18 bits
5955 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: X,
5956 N2: getF32Constant(DAG, Flt: 0x3c5d51ce, dl));
5957 SDValue t1 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t0,
5958 N2: getF32Constant(DAG, Flt: 0x3e00685a, dl));
5959 SDValue t2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t1, N2: X);
5960 SDValue t3 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t2,
5961 N2: getF32Constant(DAG, Flt: 0x3efb6798, dl));
5962 SDValue t4 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t3, N2: X);
5963 SDValue t5 = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t4,
5964 N2: getF32Constant(DAG, Flt: 0x3f88d192, dl));
5965 SDValue t6 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t5, N2: X);
5966 SDValue t7 = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: t6,
5967 N2: getF32Constant(DAG, Flt: 0x3fc4316c, dl));
5968 SDValue t8 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: t7, N2: X);
5969 Log10ofMantissa = DAG.getNode(Opcode: ISD::FSUB, DL: dl, VT: MVT::f32, N1: t8,
5970 N2: getF32Constant(DAG, Flt: 0x3f57ce70, dl));
5971 }
5972
5973 return DAG.getNode(Opcode: ISD::FADD, DL: dl, VT: MVT::f32, N1: LogOfExponent, N2: Log10ofMantissa);
5974 }
5975
5976 // No special expansion.
5977 return DAG.getNode(Opcode: ISD::FLOG10, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5978}
5979
5980/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5981/// limited-precision mode.
5982static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5983 const TargetLowering &TLI, SDNodeFlags Flags) {
5984 if (Op.getValueType() == MVT::f32 &&
5985 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5986 return getLimitedPrecisionExp2(t0: Op, dl, DAG);
5987
5988 // No special expansion.
5989 return DAG.getNode(Opcode: ISD::FEXP2, DL: dl, VT: Op.getValueType(), Operand: Op, Flags);
5990}
5991
5992/// visitPow - Lower a pow intrinsic. Handles the special sequences for
5993/// limited-precision mode with x == 10.0f.
5994static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5995 SelectionDAG &DAG, const TargetLowering &TLI,
5996 SDNodeFlags Flags) {
5997 bool IsExp10 = false;
5998 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5999 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
6000 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(Val&: LHS)) {
6001 APFloat Ten(10.0f);
6002 IsExp10 = LHSC->isExactlyValue(V: Ten);
6003 }
6004 }
6005
6006 // TODO: What fast-math-flags should be set on the FMUL node?
6007 if (IsExp10) {
6008 // Put the exponent in the right bit position for later addition to the
6009 // final result:
6010 //
6011 // #define LOG2OF10 3.3219281f
6012 // t0 = Op * LOG2OF10;
6013 SDValue t0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::f32, N1: RHS,
6014 N2: getF32Constant(DAG, Flt: 0x40549a78, dl));
6015 return getLimitedPrecisionExp2(t0, dl, DAG);
6016 }
6017
6018 // No special expansion.
6019 return DAG.getNode(Opcode: ISD::FPOW, DL: dl, VT: LHS.getValueType(), N1: LHS, N2: RHS, Flags);
6020}
6021
6022/// ExpandPowI - Expand a llvm.powi intrinsic.
6023static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
6024 SelectionDAG &DAG) {
6025 // If RHS is a constant, we can expand this out to a multiplication tree if
6026 // it's beneficial on the target, otherwise we end up lowering to a call to
6027 // __powidf2 (for example).
6028 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Val&: RHS)) {
6029 unsigned Val = RHSC->getSExtValue();
6030
6031 // powi(x, 0) -> 1.0
6032 if (Val == 0)
6033 return DAG.getConstantFP(Val: 1.0, DL, VT: LHS.getValueType());
6034
6035 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
6036 Exponent: Val, OptForSize: DAG.shouldOptForSize())) {
6037 // Get the exponent as a positive value.
6038 if ((int)Val < 0)
6039 Val = -Val;
6040 // We use the simple binary decomposition method to generate the multiply
6041 // sequence. There are more optimal ways to do this (for example,
6042 // powi(x,15) generates one more multiply than it should), but this has
6043 // the benefit of being both really simple and much better than a libcall.
6044 SDValue Res; // Logically starts equal to 1.0
6045 SDValue CurSquare = LHS;
6046 // TODO: Intrinsics should have fast-math-flags that propagate to these
6047 // nodes.
6048 while (Val) {
6049 if (Val & 1) {
6050 if (Res.getNode())
6051 Res =
6052 DAG.getNode(Opcode: ISD::FMUL, DL, VT: Res.getValueType(), N1: Res, N2: CurSquare);
6053 else
6054 Res = CurSquare; // 1.0*CurSquare.
6055 }
6056
6057 CurSquare = DAG.getNode(Opcode: ISD::FMUL, DL, VT: CurSquare.getValueType(),
6058 N1: CurSquare, N2: CurSquare);
6059 Val >>= 1;
6060 }
6061
6062 // If the original was negative, invert the result, producing 1/(x*x*x).
6063 if (RHSC->getSExtValue() < 0)
6064 Res = DAG.getNode(Opcode: ISD::FDIV, DL, VT: LHS.getValueType(),
6065 N1: DAG.getConstantFP(Val: 1.0, DL, VT: LHS.getValueType()), N2: Res);
6066 return Res;
6067 }
6068 }
6069
6070 // Otherwise, expand to a libcall.
6071 return DAG.getNode(Opcode: ISD::FPOWI, DL, VT: LHS.getValueType(), N1: LHS, N2: RHS);
6072}
6073
6074static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
6075 SDValue LHS, SDValue RHS, SDValue Scale,
6076 SelectionDAG &DAG, const TargetLowering &TLI) {
6077 EVT VT = LHS.getValueType();
6078 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
6079 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
6080 LLVMContext &Ctx = *DAG.getContext();
6081
6082 // If the type is legal but the operation isn't, this node might survive all
6083 // the way to operation legalization. If we end up there and we do not have
6084 // the ability to widen the type (if VT*2 is not legal), we cannot expand the
6085 // node.
6086
6087 // Coax the legalizer into expanding the node during type legalization instead
6088 // by bumping the size by one bit. This will force it to Promote, enabling the
6089 // early expansion and avoiding the need to expand later.
6090
6091 // We don't have to do this if Scale is 0; that can always be expanded, unless
6092 // it's a saturating signed operation. Those can experience true integer
6093 // division overflow, a case which we must avoid.
6094
6095 // FIXME: We wouldn't have to do this (or any of the early
6096 // expansion/promotion) if it was possible to expand a libcall of an
6097 // illegal type during operation legalization. But it's not, so things
6098 // get a bit hacky.
6099 unsigned ScaleInt = Scale->getAsZExtVal();
6100 if ((ScaleInt > 0 || (Saturating && Signed)) &&
6101 (TLI.isTypeLegal(VT) ||
6102 (VT.isVector() && TLI.isTypeLegal(VT: VT.getVectorElementType())))) {
6103 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
6104 Op: Opcode, VT, Scale: ScaleInt);
6105 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
6106 EVT PromVT;
6107 if (VT.isScalarInteger())
6108 PromVT = EVT::getIntegerVT(Context&: Ctx, BitWidth: VT.getSizeInBits() + 1);
6109 else if (VT.isVector()) {
6110 PromVT = VT.getVectorElementType();
6111 PromVT = EVT::getIntegerVT(Context&: Ctx, BitWidth: PromVT.getSizeInBits() + 1);
6112 PromVT = EVT::getVectorVT(Context&: Ctx, VT: PromVT, EC: VT.getVectorElementCount());
6113 } else
6114 llvm_unreachable("Wrong VT for DIVFIX?");
6115 LHS = DAG.getExtOrTrunc(IsSigned: Signed, Op: LHS, DL, VT: PromVT);
6116 RHS = DAG.getExtOrTrunc(IsSigned: Signed, Op: RHS, DL, VT: PromVT);
6117 EVT ShiftTy = TLI.getShiftAmountTy(LHSTy: PromVT, DL: DAG.getDataLayout());
6118 // For saturating operations, we need to shift up the LHS to get the
6119 // proper saturation width, and then shift down again afterwards.
6120 if (Saturating)
6121 LHS = DAG.getNode(Opcode: ISD::SHL, DL, VT: PromVT, N1: LHS,
6122 N2: DAG.getConstant(Val: 1, DL, VT: ShiftTy));
6123 SDValue Res = DAG.getNode(Opcode, DL, VT: PromVT, N1: LHS, N2: RHS, N3: Scale);
6124 if (Saturating)
6125 Res = DAG.getNode(Opcode: Signed ? ISD::SRA : ISD::SRL, DL, VT: PromVT, N1: Res,
6126 N2: DAG.getConstant(Val: 1, DL, VT: ShiftTy));
6127 return DAG.getZExtOrTrunc(Op: Res, DL, VT);
6128 }
6129 }
6130
6131 return DAG.getNode(Opcode, DL, VT, N1: LHS, N2: RHS, N3: Scale);
6132}
6133
6134// getUnderlyingArgRegs - Find underlying registers used for a truncated,
6135// bitcasted, or split argument. Returns a list of <Register, size in bits>
6136static void
6137getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
6138 const SDValue &N) {
6139 switch (N.getOpcode()) {
6140 case ISD::CopyFromReg: {
6141 SDValue Op = N.getOperand(i: 1);
6142 Regs.emplace_back(Args: cast<RegisterSDNode>(Val&: Op)->getReg(),
6143 Args: Op.getValueType().getSizeInBits());
6144 return;
6145 }
6146 case ISD::BITCAST:
6147 case ISD::AssertZext:
6148 case ISD::AssertSext:
6149 case ISD::TRUNCATE:
6150 getUnderlyingArgRegs(Regs, N: N.getOperand(i: 0));
6151 return;
6152 case ISD::BUILD_PAIR:
6153 case ISD::BUILD_VECTOR:
6154 case ISD::CONCAT_VECTORS:
6155 for (SDValue Op : N->op_values())
6156 getUnderlyingArgRegs(Regs, N: Op);
6157 return;
6158 default:
6159 return;
6160 }
6161}
6162
6163/// If the DbgValueInst is a dbg_value of a function argument, create the
6164/// corresponding DBG_VALUE machine instruction for it now. At the end of
6165/// instruction selection, they will be inserted to the entry BB.
6166/// We don't currently support this for variadic dbg_values, as they shouldn't
6167/// appear for function arguments or in the prologue.
6168bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6169 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6170 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6171 const Argument *Arg = dyn_cast<Argument>(Val: V);
6172 if (!Arg)
6173 return false;
6174
6175 MachineFunction &MF = DAG.getMachineFunction();
6176 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6177
6178 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6179 // we've been asked to pursue.
6180 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6181 bool Indirect) {
6182 if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6183 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6184 // pointing at the VReg, which will be patched up later.
6185 auto &Inst = TII->get(Opcode: TargetOpcode::DBG_INSTR_REF);
6186 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
6187 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6188 /* isKill */ false, /* isDead */ false,
6189 /* isUndef */ false, /* isEarlyClobber */ false,
6190 /* SubReg */ 0, /* isDebug */ true)});
6191
6192 auto *NewDIExpr = FragExpr;
6193 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6194 // the DIExpression.
6195 if (Indirect)
6196 NewDIExpr = DIExpression::prepend(Expr: FragExpr, Flags: DIExpression::DerefBefore);
6197 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6198 NewDIExpr = DIExpression::prependOpcodes(Expr: NewDIExpr, Ops);
6199 return BuildMI(MF, DL, MCID: Inst, IsIndirect: false, MOs, Variable, Expr: NewDIExpr);
6200 } else {
6201 // Create a completely standard DBG_VALUE.
6202 auto &Inst = TII->get(Opcode: TargetOpcode::DBG_VALUE);
6203 return BuildMI(MF, DL, MCID: Inst, IsIndirect: Indirect, Reg, Variable, Expr: FragExpr);
6204 }
6205 };
6206
6207 if (Kind == FuncArgumentDbgValueKind::Value) {
6208 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6209 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6210 // the entry block.
6211 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6212 if (!IsInEntryBlock)
6213 return false;
6214
6215 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6216 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6217 // variable that also is a param.
6218 //
6219 // Although, if we are at the top of the entry block already, we can still
6220 // emit using ArgDbgValue. This might catch some situations when the
6221 // dbg.value refers to an argument that isn't used in the entry block, so
6222 // any CopyToReg node would be optimized out and the only way to express
6223 // this DBG_VALUE is by using the physical reg (or FI) as done in this
6224 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
6225 // we should only emit as ArgDbgValue if the Variable is an argument to the
6226 // current function, and the dbg.value intrinsic is found in the entry
6227 // block.
6228 bool VariableIsFunctionInputArg = Variable->isParameter() &&
6229 !DL->getInlinedAt();
6230 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6231 if (!IsInPrologue && !VariableIsFunctionInputArg)
6232 return false;
6233
6234 // Here we assume that a function argument on IR level only can be used to
6235 // describe one input parameter on source level. If we for example have
6236 // source code like this
6237 //
6238 // struct A { long x, y; };
6239 // void foo(struct A a, long b) {
6240 // ...
6241 // b = a.x;
6242 // ...
6243 // }
6244 //
6245 // and IR like this
6246 //
6247 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
6248 // entry:
6249 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6250 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6251 // call void @llvm.dbg.value(metadata i32 %b, "b",
6252 // ...
6253 // call void @llvm.dbg.value(metadata i32 %a1, "b"
6254 // ...
6255 //
6256 // then the last dbg.value is describing a parameter "b" using a value that
6257 // is an argument. But since we already has used %a1 to describe a parameter
6258 // we should not handle that last dbg.value here (that would result in an
6259 // incorrect hoisting of the DBG_VALUE to the function entry).
6260 // Notice that we allow one dbg.value per IR level argument, to accommodate
6261 // for the situation with fragments above.
6262 // If there is no node for the value being handled, we return true to skip
6263 // the normal generation of debug info, as it would kill existing debug
6264 // info for the parameter in case of duplicates.
6265 if (VariableIsFunctionInputArg) {
6266 unsigned ArgNo = Arg->getArgNo();
6267 if (ArgNo >= FuncInfo.DescribedArgs.size())
6268 FuncInfo.DescribedArgs.resize(N: ArgNo + 1, t: false);
6269 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(Idx: ArgNo))
6270 return !NodeMap[V].getNode();
6271 FuncInfo.DescribedArgs.set(ArgNo);
6272 }
6273 }
6274
6275 bool IsIndirect = false;
6276 std::optional<MachineOperand> Op;
6277 // Some arguments' frame index is recorded during argument lowering.
6278 int FI = FuncInfo.getArgumentFrameIndex(A: Arg);
6279 if (FI != std::numeric_limits<int>::max())
6280 Op = MachineOperand::CreateFI(Idx: FI);
6281
6282 SmallVector<std::pair<Register, TypeSize>, 8> ArgRegsAndSizes;
6283 if (!Op && N.getNode()) {
6284 getUnderlyingArgRegs(Regs&: ArgRegsAndSizes, N);
6285 Register Reg;
6286 if (ArgRegsAndSizes.size() == 1)
6287 Reg = ArgRegsAndSizes.front().first;
6288
6289 if (Reg && Reg.isVirtual()) {
6290 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6291 Register PR = RegInfo.getLiveInPhysReg(VReg: Reg);
6292 if (PR)
6293 Reg = PR;
6294 }
6295 if (Reg) {
6296 Op = MachineOperand::CreateReg(Reg, isDef: false);
6297 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6298 }
6299 }
6300
6301 if (!Op && N.getNode()) {
6302 // Check if frame index is available.
6303 SDValue LCandidate = peekThroughBitcasts(V: N);
6304 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(Val: LCandidate.getNode()))
6305 if (FrameIndexSDNode *FINode =
6306 dyn_cast<FrameIndexSDNode>(Val: LNode->getBasePtr().getNode()))
6307 Op = MachineOperand::CreateFI(Idx: FINode->getIndex());
6308 }
6309
6310 if (!Op) {
6311 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6312 auto splitMultiRegDbgValue =
6313 [&](ArrayRef<std::pair<Register, TypeSize>> SplitRegs) -> bool {
6314 unsigned Offset = 0;
6315 for (const auto &[Reg, RegSizeInBits] : SplitRegs) {
6316 // FIXME: Scalable sizes are not supported in fragment expressions.
6317 if (RegSizeInBits.isScalable())
6318 return false;
6319
6320 // If the expression is already a fragment, the current register
6321 // offset+size might extend beyond the fragment. In this case, only
6322 // the register bits that are inside the fragment are relevant.
6323 int RegFragmentSizeInBits = RegSizeInBits.getFixedValue();
6324 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6325 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6326 // The register is entirely outside the expression fragment,
6327 // so is irrelevant for debug info.
6328 if (Offset >= ExprFragmentSizeInBits)
6329 break;
6330 // The register is partially outside the expression fragment, only
6331 // the low bits within the fragment are relevant for debug info.
6332 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6333 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6334 }
6335 }
6336
6337 auto FragmentExpr = DIExpression::createFragmentExpression(
6338 Expr, OffsetInBits: Offset, SizeInBits: RegFragmentSizeInBits);
6339 Offset += RegSizeInBits.getFixedValue();
6340 // If a valid fragment expression cannot be created, the variable's
6341 // correct value cannot be determined and so it is set as poison.
6342 if (!FragmentExpr) {
6343 SDDbgValue *SDV = DAG.getConstantDbgValue(
6344 Var: Variable, Expr, C: PoisonValue::get(T: V->getType()), DL, O: SDNodeOrder);
6345 DAG.AddDbgValue(DB: SDV, isParameter: false);
6346 continue;
6347 }
6348 MachineInstr *NewMI = MakeVRegDbgValue(
6349 Reg, *FragmentExpr, Kind != FuncArgumentDbgValueKind::Value);
6350 FuncInfo.ArgDbgValues.push_back(Elt: NewMI);
6351 }
6352
6353 return true;
6354 };
6355
6356 // Check if ValueMap has reg number.
6357 DenseMap<const Value *, Register>::const_iterator
6358 VMI = FuncInfo.ValueMap.find(Val: V);
6359 if (VMI != FuncInfo.ValueMap.end()) {
6360 const auto &TLI = DAG.getTargetLoweringInfo();
6361 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6362 V->getType(), std::nullopt);
6363 if (RFV.occupiesMultipleRegs())
6364 return splitMultiRegDbgValue(RFV.getRegsAndSizes());
6365
6366 Op = MachineOperand::CreateReg(Reg: VMI->second, isDef: false);
6367 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6368 } else if (ArgRegsAndSizes.size() > 1) {
6369 // This was split due to the calling convention, and no virtual register
6370 // mapping exists for the value.
6371 return splitMultiRegDbgValue(ArgRegsAndSizes);
6372 }
6373 }
6374
6375 if (!Op)
6376 return false;
6377
6378 assert(Variable->isValidLocationForIntrinsic(DL) &&
6379 "Expected inlined-at fields to agree");
6380 MachineInstr *NewMI = nullptr;
6381
6382 if (Op->isReg())
6383 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6384 else
6385 NewMI = BuildMI(MF, DL, MCID: TII->get(Opcode: TargetOpcode::DBG_VALUE), IsIndirect: true, MOs: *Op,
6386 Variable, Expr);
6387
6388 // Otherwise, use ArgDbgValues.
6389 FuncInfo.ArgDbgValues.push_back(Elt: NewMI);
6390 return true;
6391}
6392
6393/// Return the appropriate SDDbgValue based on N.
6394SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6395 DILocalVariable *Variable,
6396 DIExpression *Expr,
6397 const DebugLoc &dl,
6398 unsigned DbgSDNodeOrder) {
6399 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Val: N.getNode())) {
6400 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6401 // stack slot locations.
6402 //
6403 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6404 // debug values here after optimization:
6405 //
6406 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
6407 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6408 //
6409 // Both describe the direct values of their associated variables.
6410 return DAG.getFrameIndexDbgValue(Var: Variable, Expr, FI: FISDN->getIndex(),
6411 /*IsIndirect*/ false, DL: dl, O: DbgSDNodeOrder);
6412 }
6413 return DAG.getDbgValue(Var: Variable, Expr, N: N.getNode(), R: N.getResNo(),
6414 /*IsIndirect*/ false, DL: dl, O: DbgSDNodeOrder);
6415}
6416
6417static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6418 switch (Intrinsic) {
6419 case Intrinsic::smul_fix:
6420 return ISD::SMULFIX;
6421 case Intrinsic::umul_fix:
6422 return ISD::UMULFIX;
6423 case Intrinsic::smul_fix_sat:
6424 return ISD::SMULFIXSAT;
6425 case Intrinsic::umul_fix_sat:
6426 return ISD::UMULFIXSAT;
6427 case Intrinsic::sdiv_fix:
6428 return ISD::SDIVFIX;
6429 case Intrinsic::udiv_fix:
6430 return ISD::UDIVFIX;
6431 case Intrinsic::sdiv_fix_sat:
6432 return ISD::SDIVFIXSAT;
6433 case Intrinsic::udiv_fix_sat:
6434 return ISD::UDIVFIXSAT;
6435 default:
6436 llvm_unreachable("Unhandled fixed point intrinsic");
6437 }
6438}
6439
6440/// Given a @llvm.call.preallocated.setup, return the corresponding
6441/// preallocated call.
6442static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6443 assert(cast<CallBase>(PreallocatedSetup)
6444 ->getCalledFunction()
6445 ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6446 "expected call_preallocated_setup Value");
6447 for (const auto *U : PreallocatedSetup->users()) {
6448 auto *UseCall = cast<CallBase>(Val: U);
6449 const Function *Fn = UseCall->getCalledFunction();
6450 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6451 return UseCall;
6452 }
6453 }
6454 llvm_unreachable("expected corresponding call to preallocated setup/arg");
6455}
6456
6457/// If DI is a debug value with an EntryValue expression, lower it using the
6458/// corresponding physical register of the associated Argument value
6459/// (guaranteed to exist by the verifier).
6460bool SelectionDAGBuilder::visitEntryValueDbgValue(
6461 ArrayRef<const Value *> Values, DILocalVariable *Variable,
6462 DIExpression *Expr, DebugLoc DbgLoc) {
6463 if (!Expr->isEntryValue() || !hasSingleElement(C&: Values))
6464 return false;
6465
6466 // These properties are guaranteed by the verifier.
6467 const Argument *Arg = cast<Argument>(Val: Values[0]);
6468 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6469
6470 auto ArgIt = FuncInfo.ValueMap.find(Val: Arg);
6471 if (ArgIt == FuncInfo.ValueMap.end()) {
6472 LLVM_DEBUG(
6473 dbgs() << "Dropping dbg.value: expression is entry_value but "
6474 "couldn't find an associated register for the Argument\n");
6475 return true;
6476 }
6477 Register ArgVReg = ArgIt->getSecond();
6478
6479 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6480 if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6481 SDDbgValue *SDV = DAG.getVRegDbgValue(
6482 Var: Variable, Expr, VReg: PhysReg, IsIndirect: false /*IsIndidrect*/, DL: DbgLoc, O: SDNodeOrder);
6483 DAG.AddDbgValue(DB: SDV, isParameter: false /*treat as dbg.declare byval parameter*/);
6484 return true;
6485 }
6486 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6487 "couldn't find a physical register\n");
6488 return true;
6489}
6490
6491/// Lower the call to the specified intrinsic function.
6492void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6493 unsigned Intrinsic) {
6494 SDLoc sdl = getCurSDLoc();
6495 switch (Intrinsic) {
6496 case Intrinsic::experimental_convergence_anchor:
6497 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERGENCECTRL_ANCHOR, DL: sdl, VT: MVT::Untyped));
6498 break;
6499 case Intrinsic::experimental_convergence_entry:
6500 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERGENCECTRL_ENTRY, DL: sdl, VT: MVT::Untyped));
6501 break;
6502 case Intrinsic::experimental_convergence_loop: {
6503 auto Bundle = I.getOperandBundle(ID: LLVMContext::OB_convergencectrl);
6504 auto *Token = Bundle->Inputs[0].get();
6505 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CONVERGENCECTRL_LOOP, DL: sdl, VT: MVT::Untyped,
6506 Operand: getValue(V: Token)));
6507 break;
6508 }
6509 }
6510}
6511
6512void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6513 unsigned IntrinsicID) {
6514 // For now, we're only lowering an 'add' histogram.
6515 // We can add others later, e.g. saturating adds, min/max.
6516 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6517 "Tried to lower unsupported histogram type");
6518 SDLoc sdl = getCurSDLoc();
6519 Value *Ptr = I.getOperand(i_nocapture: 0);
6520 SDValue Inc = getValue(V: I.getOperand(i_nocapture: 1));
6521 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 2));
6522
6523 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6524 DataLayout TargetDL = DAG.getDataLayout();
6525 EVT VT = Inc.getValueType();
6526 Align Alignment = DAG.getEVTAlign(MemoryVT: VT);
6527
6528 const MDNode *Ranges = getRangeMetadata(I);
6529
6530 SDValue Root = DAG.getRoot();
6531 SDValue Base;
6532 SDValue Index;
6533 SDValue Scale;
6534 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, SDB: this,
6535 CurBB: I.getParent(), ElemSize: VT.getScalarStoreSize());
6536
6537 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6538
6539 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6540 PtrInfo: MachinePointerInfo(AS),
6541 F: MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6542 Size: MemoryLocation::UnknownSize, BaseAlignment: Alignment, AAInfo: I.getAAMetadata(), Ranges);
6543
6544 if (!UniformBase) {
6545 Base = DAG.getConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
6546 Index = getValue(V: Ptr);
6547 Scale =
6548 DAG.getTargetConstant(Val: 1, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
6549 }
6550
6551 EVT IdxVT = Index.getValueType();
6552 EVT EltTy = IdxVT.getVectorElementType();
6553 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
6554 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
6555 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: sdl, VT: NewIdxVT, Operand: Index);
6556 }
6557
6558 SDValue ID = DAG.getTargetConstant(Val: IntrinsicID, DL: sdl, VT: MVT::i32);
6559
6560 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6561 SDValue Histogram = DAG.getMaskedHistogram(VTs: DAG.getVTList(VT: MVT::Other), MemVT: VT, dl: sdl,
6562 Ops, MMO, IndexType: ISD::SIGNED_SCALED);
6563
6564 setValue(V: &I, NewN: Histogram);
6565 DAG.setRoot(Histogram);
6566}
6567
6568void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6569 unsigned Intrinsic) {
6570 assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6571 "Tried lowering invalid vector extract last");
6572 SDLoc sdl = getCurSDLoc();
6573 const DataLayout &Layout = DAG.getDataLayout();
6574 SDValue Data = getValue(V: I.getOperand(i_nocapture: 0));
6575 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 1));
6576
6577 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6578 EVT ResVT = TLI.getValueType(DL: Layout, Ty: I.getType());
6579
6580 EVT ExtVT = TLI.getVectorIdxTy(DL: Layout);
6581 SDValue Idx = DAG.getNode(Opcode: ISD::VECTOR_FIND_LAST_ACTIVE, DL: sdl, VT: ExtVT, Operand: Mask);
6582 SDValue Result = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: sdl, VT: ResVT, N1: Data, N2: Idx);
6583
6584 Value *Default = I.getOperand(i_nocapture: 2);
6585 if (!isa<PoisonValue>(Val: Default) && !isa<UndefValue>(Val: Default)) {
6586 SDValue PassThru = getValue(V: Default);
6587 EVT BoolVT = Mask.getValueType().getScalarType();
6588 SDValue AnyActive = DAG.getNode(Opcode: ISD::VECREDUCE_OR, DL: sdl, VT: BoolVT, Operand: Mask);
6589 Result = DAG.getSelect(DL: sdl, VT: ResVT, Cond: AnyActive, LHS: Result, RHS: PassThru);
6590 }
6591
6592 setValue(V: &I, NewN: Result);
6593}
6594
6595/// Lower the call to the specified intrinsic function.
6596void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6597 unsigned Intrinsic) {
6598 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6599 SDLoc sdl = getCurSDLoc();
6600 DebugLoc dl = getCurDebugLoc();
6601 SDValue Res;
6602
6603 SDNodeFlags Flags;
6604 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &I))
6605 Flags.copyFMF(FPMO: *FPOp);
6606
6607 switch (Intrinsic) {
6608 default:
6609 // By default, turn this into a target intrinsic node.
6610 visitTargetIntrinsic(I, Intrinsic);
6611 return;
6612 case Intrinsic::vscale: {
6613 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
6614 setValue(V: &I, NewN: DAG.getVScale(DL: sdl, VT, MulImm: APInt(VT.getSizeInBits(), 1)));
6615 return;
6616 }
6617 case Intrinsic::vastart: visitVAStart(I); return;
6618 case Intrinsic::vaend: visitVAEnd(I); return;
6619 case Intrinsic::vacopy: visitVACopy(I); return;
6620 case Intrinsic::returnaddress:
6621 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::RETURNADDR, DL: sdl,
6622 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
6623 Operand: getValue(V: I.getArgOperand(i: 0))));
6624 return;
6625 case Intrinsic::addressofreturnaddress:
6626 setValue(V: &I,
6627 NewN: DAG.getNode(Opcode: ISD::ADDROFRETURNADDR, DL: sdl,
6628 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType())));
6629 return;
6630 case Intrinsic::sponentry:
6631 setValue(V: &I,
6632 NewN: DAG.getNode(Opcode: ISD::SPONENTRY, DL: sdl,
6633 VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType())));
6634 return;
6635 case Intrinsic::frameaddress:
6636 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FRAMEADDR, DL: sdl,
6637 VT: TLI.getFrameIndexTy(DL: DAG.getDataLayout()),
6638 Operand: getValue(V: I.getArgOperand(i: 0))));
6639 return;
6640 case Intrinsic::read_volatile_register:
6641 case Intrinsic::read_register: {
6642 Value *Reg = I.getArgOperand(i: 0);
6643 SDValue Chain = getRoot();
6644 SDValue RegName =
6645 DAG.getMDNode(MD: cast<MDNode>(Val: cast<MetadataAsValue>(Val: Reg)->getMetadata()));
6646 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
6647 Res = DAG.getNode(Opcode: ISD::READ_REGISTER, DL: sdl,
6648 VTList: DAG.getVTList(VT1: VT, VT2: MVT::Other), N1: Chain, N2: RegName);
6649 setValue(V: &I, NewN: Res);
6650 DAG.setRoot(Res.getValue(R: 1));
6651 return;
6652 }
6653 case Intrinsic::write_register: {
6654 Value *Reg = I.getArgOperand(i: 0);
6655 Value *RegValue = I.getArgOperand(i: 1);
6656 SDValue Chain = getRoot();
6657 SDValue RegName =
6658 DAG.getMDNode(MD: cast<MDNode>(Val: cast<MetadataAsValue>(Val: Reg)->getMetadata()));
6659 DAG.setRoot(DAG.getNode(Opcode: ISD::WRITE_REGISTER, DL: sdl, VT: MVT::Other, N1: Chain,
6660 N2: RegName, N3: getValue(V: RegValue)));
6661 return;
6662 }
6663 case Intrinsic::memcpy:
6664 case Intrinsic::memcpy_inline: {
6665 const auto &MCI = cast<MemCpyInst>(Val: I);
6666 SDValue Dst = getValue(V: I.getArgOperand(i: 0));
6667 SDValue Src = getValue(V: I.getArgOperand(i: 1));
6668 SDValue Size = getValue(V: I.getArgOperand(i: 2));
6669 assert((!MCI.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6670 "memcpy_inline needs constant size");
6671 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6672 Align DstAlign = MCI.getDestAlign().valueOrOne();
6673 Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6674 Align Alignment = std::min(a: DstAlign, b: SrcAlign);
6675 bool isVol = MCI.isVolatile();
6676 // FIXME: Support passing different dest/src alignments to the memcpy DAG
6677 // node.
6678 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6679 SDValue MC = DAG.getMemcpy(Chain: Root, dl: sdl, Dst, Src, Size, Alignment, isVol,
6680 AlwaysInline: MCI.isForceInlined(), CI: &I, OverrideTailCall: std::nullopt,
6681 DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
6682 SrcPtrInfo: MachinePointerInfo(I.getArgOperand(i: 1)),
6683 AAInfo: I.getAAMetadata(), BatchAA);
6684 updateDAGForMaybeTailCall(MaybeTC: MC);
6685 return;
6686 }
6687 case Intrinsic::memset:
6688 case Intrinsic::memset_inline: {
6689 const auto &MSII = cast<MemSetInst>(Val: I);
6690 SDValue Dst = getValue(V: I.getArgOperand(i: 0));
6691 SDValue Value = getValue(V: I.getArgOperand(i: 1));
6692 SDValue Size = getValue(V: I.getArgOperand(i: 2));
6693 assert((!MSII.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6694 "memset_inline needs constant size");
6695 // @llvm.memset defines 0 and 1 to both mean no alignment.
6696 Align DstAlign = MSII.getDestAlign().valueOrOne();
6697 bool isVol = MSII.isVolatile();
6698 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6699 SDValue MC = DAG.getMemset(
6700 Chain: Root, dl: sdl, Dst, Src: Value, Size, Alignment: DstAlign, isVol, AlwaysInline: MSII.isForceInlined(),
6701 CI: &I, DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)), AAInfo: I.getAAMetadata());
6702 updateDAGForMaybeTailCall(MaybeTC: MC);
6703 return;
6704 }
6705 case Intrinsic::memmove: {
6706 const auto &MMI = cast<MemMoveInst>(Val: I);
6707 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
6708 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
6709 SDValue Op3 = getValue(V: I.getArgOperand(i: 2));
6710 // @llvm.memmove defines 0 and 1 to both mean no alignment.
6711 Align DstAlign = MMI.getDestAlign().valueOrOne();
6712 Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6713 Align Alignment = std::min(a: DstAlign, b: SrcAlign);
6714 bool isVol = MMI.isVolatile();
6715 // FIXME: Support passing different dest/src alignments to the memmove DAG
6716 // node.
6717 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6718 SDValue MM = DAG.getMemmove(Chain: Root, dl: sdl, Dst: Op1, Src: Op2, Size: Op3, Alignment, isVol, CI: &I,
6719 /* OverrideTailCall */ std::nullopt,
6720 DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
6721 SrcPtrInfo: MachinePointerInfo(I.getArgOperand(i: 1)),
6722 AAInfo: I.getAAMetadata(), BatchAA);
6723 updateDAGForMaybeTailCall(MaybeTC: MM);
6724 return;
6725 }
6726 case Intrinsic::memcpy_element_unordered_atomic: {
6727 auto &MI = cast<AnyMemCpyInst>(Val: I);
6728 SDValue Dst = getValue(V: MI.getRawDest());
6729 SDValue Src = getValue(V: MI.getRawSource());
6730 SDValue Length = getValue(V: MI.getLength());
6731
6732 Type *LengthTy = MI.getLength()->getType();
6733 unsigned ElemSz = MI.getElementSizeInBytes();
6734 bool isTC = I.isTailCall() && isInTailCallPosition(Call: I, TM: DAG.getTarget());
6735 SDValue MC =
6736 DAG.getAtomicMemcpy(Chain: getRoot(), dl: sdl, Dst, Src, Size: Length, SizeTy: LengthTy, ElemSz,
6737 isTailCall: isTC, DstPtrInfo: MachinePointerInfo(MI.getRawDest()),
6738 SrcPtrInfo: MachinePointerInfo(MI.getRawSource()));
6739 updateDAGForMaybeTailCall(MaybeTC: MC);
6740 return;
6741 }
6742 case Intrinsic::memmove_element_unordered_atomic: {
6743 auto &MI = cast<AnyMemMoveInst>(Val: I);
6744 SDValue Dst = getValue(V: MI.getRawDest());
6745 SDValue Src = getValue(V: MI.getRawSource());
6746 SDValue Length = getValue(V: MI.getLength());
6747
6748 Type *LengthTy = MI.getLength()->getType();
6749 unsigned ElemSz = MI.getElementSizeInBytes();
6750 bool isTC = I.isTailCall() && isInTailCallPosition(Call: I, TM: DAG.getTarget());
6751 SDValue MC =
6752 DAG.getAtomicMemmove(Chain: getRoot(), dl: sdl, Dst, Src, Size: Length, SizeTy: LengthTy, ElemSz,
6753 isTailCall: isTC, DstPtrInfo: MachinePointerInfo(MI.getRawDest()),
6754 SrcPtrInfo: MachinePointerInfo(MI.getRawSource()));
6755 updateDAGForMaybeTailCall(MaybeTC: MC);
6756 return;
6757 }
6758 case Intrinsic::memset_element_unordered_atomic: {
6759 auto &MI = cast<AnyMemSetInst>(Val: I);
6760 SDValue Dst = getValue(V: MI.getRawDest());
6761 SDValue Val = getValue(V: MI.getValue());
6762 SDValue Length = getValue(V: MI.getLength());
6763
6764 Type *LengthTy = MI.getLength()->getType();
6765 unsigned ElemSz = MI.getElementSizeInBytes();
6766 bool isTC = I.isTailCall() && isInTailCallPosition(Call: I, TM: DAG.getTarget());
6767 SDValue MC =
6768 DAG.getAtomicMemset(Chain: getRoot(), dl: sdl, Dst, Value: Val, Size: Length, SizeTy: LengthTy, ElemSz,
6769 isTailCall: isTC, DstPtrInfo: MachinePointerInfo(MI.getRawDest()));
6770 updateDAGForMaybeTailCall(MaybeTC: MC);
6771 return;
6772 }
6773 case Intrinsic::call_preallocated_setup: {
6774 const CallBase *PreallocatedCall = FindPreallocatedCall(PreallocatedSetup: &I);
6775 SDValue SrcValue = DAG.getSrcValue(v: PreallocatedCall);
6776 SDValue Res = DAG.getNode(Opcode: ISD::PREALLOCATED_SETUP, DL: sdl, VT: MVT::Other,
6777 N1: getRoot(), N2: SrcValue);
6778 setValue(V: &I, NewN: Res);
6779 DAG.setRoot(Res);
6780 return;
6781 }
6782 case Intrinsic::call_preallocated_arg: {
6783 const CallBase *PreallocatedCall = FindPreallocatedCall(PreallocatedSetup: I.getOperand(i_nocapture: 0));
6784 SDValue SrcValue = DAG.getSrcValue(v: PreallocatedCall);
6785 SDValue Ops[3];
6786 Ops[0] = getRoot();
6787 Ops[1] = SrcValue;
6788 Ops[2] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 1)), DL: sdl,
6789 VT: MVT::i32); // arg index
6790 SDValue Res = DAG.getNode(
6791 Opcode: ISD::PREALLOCATED_ARG, DL: sdl,
6792 VTList: DAG.getVTList(VT1: TLI.getPointerTy(DL: DAG.getDataLayout()), VT2: MVT::Other), Ops);
6793 setValue(V: &I, NewN: Res);
6794 DAG.setRoot(Res.getValue(R: 1));
6795 return;
6796 }
6797
6798 case Intrinsic::eh_typeid_for: {
6799 // Find the type id for the given typeinfo.
6800 GlobalValue *GV = ExtractTypeInfo(V: I.getArgOperand(i: 0));
6801 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(TI: GV);
6802 Res = DAG.getConstant(Val: TypeID, DL: sdl, VT: MVT::i32);
6803 setValue(V: &I, NewN: Res);
6804 return;
6805 }
6806
6807 case Intrinsic::eh_return_i32:
6808 case Intrinsic::eh_return_i64:
6809 DAG.getMachineFunction().setCallsEHReturn(true);
6810 DAG.setRoot(DAG.getNode(Opcode: ISD::EH_RETURN, DL: sdl,
6811 VT: MVT::Other,
6812 N1: getControlRoot(),
6813 N2: getValue(V: I.getArgOperand(i: 0)),
6814 N3: getValue(V: I.getArgOperand(i: 1))));
6815 return;
6816 case Intrinsic::eh_unwind_init:
6817 DAG.getMachineFunction().setCallsUnwindInit(true);
6818 return;
6819 case Intrinsic::eh_dwarf_cfa:
6820 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::EH_DWARF_CFA, DL: sdl,
6821 VT: TLI.getPointerTy(DL: DAG.getDataLayout()),
6822 Operand: getValue(V: I.getArgOperand(i: 0))));
6823 return;
6824 case Intrinsic::eh_sjlj_callsite: {
6825 ConstantInt *CI = cast<ConstantInt>(Val: I.getArgOperand(i: 0));
6826 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6827
6828 FuncInfo.setCurrentCallSite(CI->getZExtValue());
6829 return;
6830 }
6831 case Intrinsic::eh_sjlj_functioncontext: {
6832 // Get and store the index of the function context.
6833 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6834 AllocaInst *FnCtx =
6835 cast<AllocaInst>(Val: I.getArgOperand(i: 0)->stripPointerCasts());
6836 int FI = FuncInfo.StaticAllocaMap[FnCtx];
6837 MFI.setFunctionContextIndex(FI);
6838 return;
6839 }
6840 case Intrinsic::eh_sjlj_setjmp: {
6841 SDValue Ops[2];
6842 Ops[0] = getRoot();
6843 Ops[1] = getValue(V: I.getArgOperand(i: 0));
6844 SDValue Op = DAG.getNode(Opcode: ISD::EH_SJLJ_SETJMP, DL: sdl,
6845 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::Other), Ops);
6846 setValue(V: &I, NewN: Op.getValue(R: 0));
6847 DAG.setRoot(Op.getValue(R: 1));
6848 return;
6849 }
6850 case Intrinsic::eh_sjlj_longjmp:
6851 DAG.setRoot(DAG.getNode(Opcode: ISD::EH_SJLJ_LONGJMP, DL: sdl, VT: MVT::Other,
6852 N1: getRoot(), N2: getValue(V: I.getArgOperand(i: 0))));
6853 return;
6854 case Intrinsic::eh_sjlj_setup_dispatch:
6855 DAG.setRoot(DAG.getNode(Opcode: ISD::EH_SJLJ_SETUP_DISPATCH, DL: sdl, VT: MVT::Other,
6856 Operand: getRoot()));
6857 return;
6858 case Intrinsic::masked_gather:
6859 visitMaskedGather(I);
6860 return;
6861 case Intrinsic::masked_load:
6862 visitMaskedLoad(I);
6863 return;
6864 case Intrinsic::masked_scatter:
6865 visitMaskedScatter(I);
6866 return;
6867 case Intrinsic::masked_store:
6868 visitMaskedStore(I);
6869 return;
6870 case Intrinsic::masked_expandload:
6871 visitMaskedLoad(I, IsExpanding: true /* IsExpanding */);
6872 return;
6873 case Intrinsic::masked_compressstore:
6874 visitMaskedStore(I, IsCompressing: true /* IsCompressing */);
6875 return;
6876 case Intrinsic::powi:
6877 setValue(V: &I, NewN: ExpandPowI(DL: sdl, LHS: getValue(V: I.getArgOperand(i: 0)),
6878 RHS: getValue(V: I.getArgOperand(i: 1)), DAG));
6879 return;
6880 case Intrinsic::log:
6881 setValue(V: &I, NewN: expandLog(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6882 return;
6883 case Intrinsic::log2:
6884 setValue(V: &I,
6885 NewN: expandLog2(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6886 return;
6887 case Intrinsic::log10:
6888 setValue(V: &I,
6889 NewN: expandLog10(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6890 return;
6891 case Intrinsic::exp:
6892 setValue(V: &I, NewN: expandExp(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6893 return;
6894 case Intrinsic::exp2:
6895 setValue(V: &I,
6896 NewN: expandExp2(dl: sdl, Op: getValue(V: I.getArgOperand(i: 0)), DAG, TLI, Flags));
6897 return;
6898 case Intrinsic::pow:
6899 setValue(V: &I, NewN: expandPow(dl: sdl, LHS: getValue(V: I.getArgOperand(i: 0)),
6900 RHS: getValue(V: I.getArgOperand(i: 1)), DAG, TLI, Flags));
6901 return;
6902 case Intrinsic::sqrt:
6903 case Intrinsic::fabs:
6904 case Intrinsic::sin:
6905 case Intrinsic::cos:
6906 case Intrinsic::tan:
6907 case Intrinsic::asin:
6908 case Intrinsic::acos:
6909 case Intrinsic::atan:
6910 case Intrinsic::sinh:
6911 case Intrinsic::cosh:
6912 case Intrinsic::tanh:
6913 case Intrinsic::exp10:
6914 case Intrinsic::floor:
6915 case Intrinsic::ceil:
6916 case Intrinsic::trunc:
6917 case Intrinsic::rint:
6918 case Intrinsic::nearbyint:
6919 case Intrinsic::round:
6920 case Intrinsic::roundeven:
6921 case Intrinsic::canonicalize: {
6922 unsigned Opcode;
6923 // clang-format off
6924 switch (Intrinsic) {
6925 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6926 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
6927 case Intrinsic::fabs: Opcode = ISD::FABS; break;
6928 case Intrinsic::sin: Opcode = ISD::FSIN; break;
6929 case Intrinsic::cos: Opcode = ISD::FCOS; break;
6930 case Intrinsic::tan: Opcode = ISD::FTAN; break;
6931 case Intrinsic::asin: Opcode = ISD::FASIN; break;
6932 case Intrinsic::acos: Opcode = ISD::FACOS; break;
6933 case Intrinsic::atan: Opcode = ISD::FATAN; break;
6934 case Intrinsic::sinh: Opcode = ISD::FSINH; break;
6935 case Intrinsic::cosh: Opcode = ISD::FCOSH; break;
6936 case Intrinsic::tanh: Opcode = ISD::FTANH; break;
6937 case Intrinsic::exp10: Opcode = ISD::FEXP10; break;
6938 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
6939 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
6940 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
6941 case Intrinsic::rint: Opcode = ISD::FRINT; break;
6942 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6943 case Intrinsic::round: Opcode = ISD::FROUND; break;
6944 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6945 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6946 }
6947 // clang-format on
6948
6949 setValue(V: &I, NewN: DAG.getNode(Opcode, DL: sdl,
6950 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
6951 Operand: getValue(V: I.getArgOperand(i: 0)), Flags));
6952 return;
6953 }
6954 case Intrinsic::atan2:
6955 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FATAN2, DL: sdl,
6956 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
6957 N1: getValue(V: I.getArgOperand(i: 0)),
6958 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
6959 return;
6960 case Intrinsic::lround:
6961 case Intrinsic::llround:
6962 case Intrinsic::lrint:
6963 case Intrinsic::llrint: {
6964 unsigned Opcode;
6965 // clang-format off
6966 switch (Intrinsic) {
6967 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6968 case Intrinsic::lround: Opcode = ISD::LROUND; break;
6969 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6970 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
6971 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
6972 }
6973 // clang-format on
6974
6975 EVT RetVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
6976 setValue(V: &I, NewN: DAG.getNode(Opcode, DL: sdl, VT: RetVT,
6977 Operand: getValue(V: I.getArgOperand(i: 0))));
6978 return;
6979 }
6980 case Intrinsic::minnum:
6981 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMINNUM, DL: sdl,
6982 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
6983 N1: getValue(V: I.getArgOperand(i: 0)),
6984 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
6985 return;
6986 case Intrinsic::maxnum:
6987 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMAXNUM, DL: sdl,
6988 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
6989 N1: getValue(V: I.getArgOperand(i: 0)),
6990 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
6991 return;
6992 case Intrinsic::minimum:
6993 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMINIMUM, DL: sdl,
6994 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
6995 N1: getValue(V: I.getArgOperand(i: 0)),
6996 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
6997 return;
6998 case Intrinsic::maximum:
6999 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMAXIMUM, DL: sdl,
7000 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7001 N1: getValue(V: I.getArgOperand(i: 0)),
7002 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7003 return;
7004 case Intrinsic::minimumnum:
7005 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMINIMUMNUM, DL: sdl,
7006 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7007 N1: getValue(V: I.getArgOperand(i: 0)),
7008 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7009 return;
7010 case Intrinsic::maximumnum:
7011 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMAXIMUMNUM, DL: sdl,
7012 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7013 N1: getValue(V: I.getArgOperand(i: 0)),
7014 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7015 return;
7016 case Intrinsic::copysign:
7017 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FCOPYSIGN, DL: sdl,
7018 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7019 N1: getValue(V: I.getArgOperand(i: 0)),
7020 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7021 return;
7022 case Intrinsic::ldexp:
7023 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FLDEXP, DL: sdl,
7024 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7025 N1: getValue(V: I.getArgOperand(i: 0)),
7026 N2: getValue(V: I.getArgOperand(i: 1)), Flags));
7027 return;
7028 case Intrinsic::modf:
7029 case Intrinsic::sincos:
7030 case Intrinsic::sincospi:
7031 case Intrinsic::frexp: {
7032 unsigned Opcode;
7033 switch (Intrinsic) {
7034 default:
7035 llvm_unreachable("unexpected intrinsic");
7036 case Intrinsic::sincos:
7037 Opcode = ISD::FSINCOS;
7038 break;
7039 case Intrinsic::sincospi:
7040 Opcode = ISD::FSINCOSPI;
7041 break;
7042 case Intrinsic::modf:
7043 Opcode = ISD::FMODF;
7044 break;
7045 case Intrinsic::frexp:
7046 Opcode = ISD::FFREXP;
7047 break;
7048 }
7049 SmallVector<EVT, 2> ValueVTs;
7050 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: I.getType(), ValueVTs);
7051 SDVTList VTs = DAG.getVTList(VTs: ValueVTs);
7052 setValue(
7053 V: &I, NewN: DAG.getNode(Opcode, DL: sdl, VTList: VTs, Ops: getValue(V: I.getArgOperand(i: 0)), Flags));
7054 return;
7055 }
7056 case Intrinsic::arithmetic_fence: {
7057 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::ARITH_FENCE, DL: sdl,
7058 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7059 Operand: getValue(V: I.getArgOperand(i: 0)), Flags));
7060 return;
7061 }
7062 case Intrinsic::fma:
7063 setValue(V: &I, NewN: DAG.getNode(
7064 Opcode: ISD::FMA, DL: sdl, VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7065 N1: getValue(V: I.getArgOperand(i: 0)), N2: getValue(V: I.getArgOperand(i: 1)),
7066 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
7067 return;
7068#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
7069 case Intrinsic::INTRINSIC:
7070#include "llvm/IR/ConstrainedOps.def"
7071 visitConstrainedFPIntrinsic(FPI: cast<ConstrainedFPIntrinsic>(Val: I));
7072 return;
7073#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7074#include "llvm/IR/VPIntrinsics.def"
7075 visitVectorPredicationIntrinsic(VPIntrin: cast<VPIntrinsic>(Val: I));
7076 return;
7077 case Intrinsic::fptrunc_round: {
7078 // Get the last argument, the metadata and convert it to an integer in the
7079 // call
7080 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 1))->getMetadata();
7081 std::optional<RoundingMode> RoundMode =
7082 convertStrToRoundingMode(cast<MDString>(Val: MD)->getString());
7083
7084 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7085
7086 // Propagate fast-math-flags from IR to node(s).
7087 SDNodeFlags Flags;
7088 Flags.copyFMF(FPMO: *cast<FPMathOperator>(Val: &I));
7089 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7090
7091 SDValue Result;
7092 Result = DAG.getNode(
7093 Opcode: ISD::FPTRUNC_ROUND, DL: sdl, VT, N1: getValue(V: I.getArgOperand(i: 0)),
7094 N2: DAG.getTargetConstant(Val: (int)*RoundMode, DL: sdl, VT: MVT::i32));
7095 setValue(V: &I, NewN: Result);
7096
7097 return;
7098 }
7099 case Intrinsic::fmuladd: {
7100 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7101 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7102 TLI.isFMAFasterThanFMulAndFAdd(MF: DAG.getMachineFunction(), VT)) {
7103 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMA, DL: sdl,
7104 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7105 N1: getValue(V: I.getArgOperand(i: 0)),
7106 N2: getValue(V: I.getArgOperand(i: 1)),
7107 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
7108 } else if (TLI.isOperationLegalOrCustom(Op: ISD::FMULADD, VT)) {
7109 // TODO: Support splitting the vector.
7110 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FMULADD, DL: sdl,
7111 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7112 N1: getValue(V: I.getArgOperand(i: 0)),
7113 N2: getValue(V: I.getArgOperand(i: 1)),
7114 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
7115 } else {
7116 // TODO: Intrinsic calls should have fast-math-flags.
7117 SDValue Mul = DAG.getNode(
7118 Opcode: ISD::FMUL, DL: sdl, VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7119 N1: getValue(V: I.getArgOperand(i: 0)), N2: getValue(V: I.getArgOperand(i: 1)), Flags);
7120 SDValue Add = DAG.getNode(Opcode: ISD::FADD, DL: sdl,
7121 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7122 N1: Mul, N2: getValue(V: I.getArgOperand(i: 2)), Flags);
7123 setValue(V: &I, NewN: Add);
7124 }
7125 return;
7126 }
7127 case Intrinsic::fptosi_sat: {
7128 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7129 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_SINT_SAT, DL: sdl, VT,
7130 N1: getValue(V: I.getArgOperand(i: 0)),
7131 N2: DAG.getValueType(VT.getScalarType())));
7132 return;
7133 }
7134 case Intrinsic::fptoui_sat: {
7135 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7136 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FP_TO_UINT_SAT, DL: sdl, VT,
7137 N1: getValue(V: I.getArgOperand(i: 0)),
7138 N2: DAG.getValueType(VT.getScalarType())));
7139 return;
7140 }
7141 case Intrinsic::set_rounding:
7142 Res = DAG.getNode(Opcode: ISD::SET_ROUNDING, DL: sdl, VT: MVT::Other,
7143 Ops: {getRoot(), getValue(V: I.getArgOperand(i: 0))});
7144 setValue(V: &I, NewN: Res);
7145 DAG.setRoot(Res.getValue(R: 0));
7146 return;
7147 case Intrinsic::is_fpclass: {
7148 const DataLayout DLayout = DAG.getDataLayout();
7149 EVT DestVT = TLI.getValueType(DL: DLayout, Ty: I.getType());
7150 EVT ArgVT = TLI.getValueType(DL: DLayout, Ty: I.getArgOperand(i: 0)->getType());
7151 FPClassTest Test = static_cast<FPClassTest>(
7152 cast<ConstantInt>(Val: I.getArgOperand(i: 1))->getZExtValue());
7153 MachineFunction &MF = DAG.getMachineFunction();
7154 const Function &F = MF.getFunction();
7155 SDValue Op = getValue(V: I.getArgOperand(i: 0));
7156 SDNodeFlags Flags;
7157 Flags.setNoFPExcept(
7158 !F.getAttributes().hasFnAttr(Kind: llvm::Attribute::StrictFP));
7159 // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7160 // expansion can use illegal types. Making expansion early allows
7161 // legalizing these types prior to selection.
7162 if (!TLI.isOperationLegal(Op: ISD::IS_FPCLASS, VT: ArgVT) &&
7163 !TLI.isOperationCustom(Op: ISD::IS_FPCLASS, VT: ArgVT)) {
7164 SDValue Result = TLI.expandIS_FPCLASS(ResultVT: DestVT, Op, Test, Flags, DL: sdl, DAG);
7165 setValue(V: &I, NewN: Result);
7166 return;
7167 }
7168
7169 SDValue Check = DAG.getTargetConstant(Val: Test, DL: sdl, VT: MVT::i32);
7170 SDValue V = DAG.getNode(Opcode: ISD::IS_FPCLASS, DL: sdl, VT: DestVT, Ops: {Op, Check}, Flags);
7171 setValue(V: &I, NewN: V);
7172 return;
7173 }
7174 case Intrinsic::get_fpenv: {
7175 const DataLayout DLayout = DAG.getDataLayout();
7176 EVT EnvVT = TLI.getValueType(DL: DLayout, Ty: I.getType());
7177 Align TempAlign = DAG.getEVTAlign(MemoryVT: EnvVT);
7178 SDValue Chain = getRoot();
7179 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7180 // and temporary storage in stack.
7181 if (TLI.isOperationLegalOrCustom(Op: ISD::GET_FPENV, VT: EnvVT)) {
7182 Res = DAG.getNode(
7183 Opcode: ISD::GET_FPENV, DL: sdl,
7184 VTList: DAG.getVTList(VT1: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
7185 VT2: MVT::Other),
7186 N: Chain);
7187 } else {
7188 SDValue Temp = DAG.CreateStackTemporary(VT: EnvVT, minAlign: TempAlign.value());
7189 int SPFI = cast<FrameIndexSDNode>(Val: Temp.getNode())->getIndex();
7190 auto MPI =
7191 MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI: SPFI);
7192 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7193 PtrInfo: MPI, F: MachineMemOperand::MOStore, Size: LocationSize::beforeOrAfterPointer(),
7194 BaseAlignment: TempAlign);
7195 Chain = DAG.getGetFPEnv(Chain, dl: sdl, Ptr: Temp, MemVT: EnvVT, MMO);
7196 Res = DAG.getLoad(VT: EnvVT, dl: sdl, Chain, Ptr: Temp, PtrInfo: MPI);
7197 }
7198 setValue(V: &I, NewN: Res);
7199 DAG.setRoot(Res.getValue(R: 1));
7200 return;
7201 }
7202 case Intrinsic::set_fpenv: {
7203 const DataLayout DLayout = DAG.getDataLayout();
7204 SDValue Env = getValue(V: I.getArgOperand(i: 0));
7205 EVT EnvVT = Env.getValueType();
7206 Align TempAlign = DAG.getEVTAlign(MemoryVT: EnvVT);
7207 SDValue Chain = getRoot();
7208 // If SET_FPENV is custom or legal, use it. Otherwise use loading
7209 // environment from memory.
7210 if (TLI.isOperationLegalOrCustom(Op: ISD::SET_FPENV, VT: EnvVT)) {
7211 Chain = DAG.getNode(Opcode: ISD::SET_FPENV, DL: sdl, VT: MVT::Other, N1: Chain, N2: Env);
7212 } else {
7213 // Allocate space in stack, copy environment bits into it and use this
7214 // memory in SET_FPENV_MEM.
7215 SDValue Temp = DAG.CreateStackTemporary(VT: EnvVT, minAlign: TempAlign.value());
7216 int SPFI = cast<FrameIndexSDNode>(Val: Temp.getNode())->getIndex();
7217 auto MPI =
7218 MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI: SPFI);
7219 Chain = DAG.getStore(Chain, dl: sdl, Val: Env, Ptr: Temp, PtrInfo: MPI, Alignment: TempAlign,
7220 MMOFlags: MachineMemOperand::MOStore);
7221 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7222 PtrInfo: MPI, F: MachineMemOperand::MOLoad, Size: LocationSize::beforeOrAfterPointer(),
7223 BaseAlignment: TempAlign);
7224 Chain = DAG.getSetFPEnv(Chain, dl: sdl, Ptr: Temp, MemVT: EnvVT, MMO);
7225 }
7226 DAG.setRoot(Chain);
7227 return;
7228 }
7229 case Intrinsic::reset_fpenv:
7230 DAG.setRoot(DAG.getNode(Opcode: ISD::RESET_FPENV, DL: sdl, VT: MVT::Other, Operand: getRoot()));
7231 return;
7232 case Intrinsic::get_fpmode:
7233 Res = DAG.getNode(
7234 Opcode: ISD::GET_FPMODE, DL: sdl,
7235 VTList: DAG.getVTList(VT1: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()),
7236 VT2: MVT::Other),
7237 N: DAG.getRoot());
7238 setValue(V: &I, NewN: Res);
7239 DAG.setRoot(Res.getValue(R: 1));
7240 return;
7241 case Intrinsic::set_fpmode:
7242 Res = DAG.getNode(Opcode: ISD::SET_FPMODE, DL: sdl, VT: MVT::Other, N1: {DAG.getRoot()},
7243 N2: getValue(V: I.getArgOperand(i: 0)));
7244 DAG.setRoot(Res);
7245 return;
7246 case Intrinsic::reset_fpmode: {
7247 Res = DAG.getNode(Opcode: ISD::RESET_FPMODE, DL: sdl, VT: MVT::Other, Operand: getRoot());
7248 DAG.setRoot(Res);
7249 return;
7250 }
7251 case Intrinsic::pcmarker: {
7252 SDValue Tmp = getValue(V: I.getArgOperand(i: 0));
7253 DAG.setRoot(DAG.getNode(Opcode: ISD::PCMARKER, DL: sdl, VT: MVT::Other, N1: getRoot(), N2: Tmp));
7254 return;
7255 }
7256 case Intrinsic::readcyclecounter: {
7257 SDValue Op = getRoot();
7258 Res = DAG.getNode(Opcode: ISD::READCYCLECOUNTER, DL: sdl,
7259 VTList: DAG.getVTList(VT1: MVT::i64, VT2: MVT::Other), N: Op);
7260 setValue(V: &I, NewN: Res);
7261 DAG.setRoot(Res.getValue(R: 1));
7262 return;
7263 }
7264 case Intrinsic::readsteadycounter: {
7265 SDValue Op = getRoot();
7266 Res = DAG.getNode(Opcode: ISD::READSTEADYCOUNTER, DL: sdl,
7267 VTList: DAG.getVTList(VT1: MVT::i64, VT2: MVT::Other), N: Op);
7268 setValue(V: &I, NewN: Res);
7269 DAG.setRoot(Res.getValue(R: 1));
7270 return;
7271 }
7272 case Intrinsic::bitreverse:
7273 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::BITREVERSE, DL: sdl,
7274 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7275 Operand: getValue(V: I.getArgOperand(i: 0))));
7276 return;
7277 case Intrinsic::bswap:
7278 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::BSWAP, DL: sdl,
7279 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
7280 Operand: getValue(V: I.getArgOperand(i: 0))));
7281 return;
7282 case Intrinsic::cttz: {
7283 SDValue Arg = getValue(V: I.getArgOperand(i: 0));
7284 ConstantInt *CI = cast<ConstantInt>(Val: I.getArgOperand(i: 1));
7285 EVT Ty = Arg.getValueType();
7286 setValue(V: &I, NewN: DAG.getNode(Opcode: CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7287 DL: sdl, VT: Ty, Operand: Arg));
7288 return;
7289 }
7290 case Intrinsic::ctlz: {
7291 SDValue Arg = getValue(V: I.getArgOperand(i: 0));
7292 ConstantInt *CI = cast<ConstantInt>(Val: I.getArgOperand(i: 1));
7293 EVT Ty = Arg.getValueType();
7294 setValue(V: &I, NewN: DAG.getNode(Opcode: CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7295 DL: sdl, VT: Ty, Operand: Arg));
7296 return;
7297 }
7298 case Intrinsic::ctpop: {
7299 SDValue Arg = getValue(V: I.getArgOperand(i: 0));
7300 EVT Ty = Arg.getValueType();
7301 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CTPOP, DL: sdl, VT: Ty, Operand: Arg));
7302 return;
7303 }
7304 case Intrinsic::fshl:
7305 case Intrinsic::fshr: {
7306 bool IsFSHL = Intrinsic == Intrinsic::fshl;
7307 SDValue X = getValue(V: I.getArgOperand(i: 0));
7308 SDValue Y = getValue(V: I.getArgOperand(i: 1));
7309 SDValue Z = getValue(V: I.getArgOperand(i: 2));
7310 EVT VT = X.getValueType();
7311
7312 if (X == Y) {
7313 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7314 setValue(V: &I, NewN: DAG.getNode(Opcode: RotateOpcode, DL: sdl, VT, N1: X, N2: Z));
7315 } else {
7316 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7317 setValue(V: &I, NewN: DAG.getNode(Opcode: FunnelOpcode, DL: sdl, VT, N1: X, N2: Y, N3: Z));
7318 }
7319 return;
7320 }
7321 case Intrinsic::clmul: {
7322 SDValue X = getValue(V: I.getArgOperand(i: 0));
7323 SDValue Y = getValue(V: I.getArgOperand(i: 1));
7324 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::CLMUL, DL: sdl, VT: X.getValueType(), N1: X, N2: Y));
7325 return;
7326 }
7327 case Intrinsic::sadd_sat: {
7328 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7329 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7330 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SADDSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7331 return;
7332 }
7333 case Intrinsic::uadd_sat: {
7334 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7335 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7336 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UADDSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7337 return;
7338 }
7339 case Intrinsic::ssub_sat: {
7340 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7341 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7342 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SSUBSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7343 return;
7344 }
7345 case Intrinsic::usub_sat: {
7346 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7347 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7348 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::USUBSAT, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7349 return;
7350 }
7351 case Intrinsic::sshl_sat:
7352 case Intrinsic::ushl_sat: {
7353 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7354 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7355
7356 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
7357 LHSTy: Op1.getValueType(), DL: DAG.getDataLayout());
7358
7359 // Coerce the shift amount to the right type if we can. This exposes the
7360 // truncate or zext to optimization early.
7361 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
7362 assert(ShiftTy.getSizeInBits() >=
7363 Log2_32_Ceil(Op1.getValueSizeInBits()) &&
7364 "Unexpected shift type");
7365 Op2 = DAG.getZExtOrTrunc(Op: Op2, DL: getCurSDLoc(), VT: ShiftTy);
7366 }
7367
7368 unsigned Opc =
7369 Intrinsic == Intrinsic::sshl_sat ? ISD::SSHLSAT : ISD::USHLSAT;
7370 setValue(V: &I, NewN: DAG.getNode(Opcode: Opc, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7371 return;
7372 }
7373 case Intrinsic::smul_fix:
7374 case Intrinsic::umul_fix:
7375 case Intrinsic::smul_fix_sat:
7376 case Intrinsic::umul_fix_sat: {
7377 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7378 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7379 SDValue Op3 = getValue(V: I.getArgOperand(i: 2));
7380 setValue(V: &I, NewN: DAG.getNode(Opcode: FixedPointIntrinsicToOpcode(Intrinsic), DL: sdl,
7381 VT: Op1.getValueType(), N1: Op1, N2: Op2, N3: Op3));
7382 return;
7383 }
7384 case Intrinsic::sdiv_fix:
7385 case Intrinsic::udiv_fix:
7386 case Intrinsic::sdiv_fix_sat:
7387 case Intrinsic::udiv_fix_sat: {
7388 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7389 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7390 SDValue Op3 = getValue(V: I.getArgOperand(i: 2));
7391 setValue(V: &I, NewN: expandDivFix(Opcode: FixedPointIntrinsicToOpcode(Intrinsic), DL: sdl,
7392 LHS: Op1, RHS: Op2, Scale: Op3, DAG, TLI));
7393 return;
7394 }
7395 case Intrinsic::smax: {
7396 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7397 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7398 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SMAX, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7399 return;
7400 }
7401 case Intrinsic::smin: {
7402 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7403 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7404 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SMIN, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7405 return;
7406 }
7407 case Intrinsic::umax: {
7408 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7409 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7410 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UMAX, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7411 return;
7412 }
7413 case Intrinsic::umin: {
7414 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7415 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7416 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UMIN, DL: sdl, VT: Op1.getValueType(), N1: Op1, N2: Op2));
7417 return;
7418 }
7419 case Intrinsic::abs: {
7420 // TODO: Preserve "int min is poison" arg in SDAG?
7421 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7422 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::ABS, DL: sdl, VT: Op1.getValueType(), Operand: Op1));
7423 return;
7424 }
7425 case Intrinsic::scmp: {
7426 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7427 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7428 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7429 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::SCMP, DL: sdl, VT: DestVT, N1: Op1, N2: Op2));
7430 break;
7431 }
7432 case Intrinsic::ucmp: {
7433 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7434 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7435 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7436 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::UCMP, DL: sdl, VT: DestVT, N1: Op1, N2: Op2));
7437 break;
7438 }
7439 case Intrinsic::stackaddress:
7440 case Intrinsic::stacksave: {
7441 unsigned SDOpcode = Intrinsic == Intrinsic::stackaddress ? ISD::STACKADDRESS
7442 : ISD::STACKSAVE;
7443 SDValue Op = getRoot();
7444 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7445 Res = DAG.getNode(Opcode: SDOpcode, DL: sdl, VTList: DAG.getVTList(VT1: VT, VT2: MVT::Other), N: Op);
7446 setValue(V: &I, NewN: Res);
7447 DAG.setRoot(Res.getValue(R: 1));
7448 return;
7449 }
7450 case Intrinsic::stackrestore:
7451 Res = getValue(V: I.getArgOperand(i: 0));
7452 DAG.setRoot(DAG.getNode(Opcode: ISD::STACKRESTORE, DL: sdl, VT: MVT::Other, N1: getRoot(), N2: Res));
7453 return;
7454 case Intrinsic::get_dynamic_area_offset: {
7455 SDValue Op = getRoot();
7456 EVT ResTy = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7457 Res = DAG.getNode(Opcode: ISD::GET_DYNAMIC_AREA_OFFSET, DL: sdl, VTList: DAG.getVTList(VT: ResTy),
7458 N: Op);
7459 DAG.setRoot(Op);
7460 setValue(V: &I, NewN: Res);
7461 return;
7462 }
7463 case Intrinsic::stackguard: {
7464 MachineFunction &MF = DAG.getMachineFunction();
7465 const Module &M = *MF.getFunction().getParent();
7466 EVT PtrTy = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
7467 SDValue Chain = getRoot();
7468 if (TLI.useLoadStackGuardNode(M)) {
7469 Res = getLoadStackGuard(DAG, DL: sdl, Chain);
7470 Res = DAG.getPtrExtOrTrunc(Op: Res, DL: sdl, VT: PtrTy);
7471 } else {
7472 const Value *Global = TLI.getSDagStackGuard(M, Libcalls: DAG.getLibcalls());
7473 if (!Global) {
7474 LLVMContext &Ctx = *DAG.getContext();
7475 Ctx.diagnose(DI: DiagnosticInfoGeneric("unable to lower stackguard"));
7476 setValue(V: &I, NewN: DAG.getPOISON(VT: PtrTy));
7477 return;
7478 }
7479
7480 Align Align = DAG.getDataLayout().getPrefTypeAlign(Ty: Global->getType());
7481 Res = DAG.getLoad(VT: PtrTy, dl: sdl, Chain, Ptr: getValue(V: Global),
7482 PtrInfo: MachinePointerInfo(Global, 0), Alignment: Align,
7483 MMOFlags: MachineMemOperand::MOVolatile);
7484 }
7485 if (TLI.useStackGuardXorFP())
7486 Res = TLI.emitStackGuardXorFP(DAG, Val: Res, DL: sdl);
7487 DAG.setRoot(Chain);
7488 setValue(V: &I, NewN: Res);
7489 return;
7490 }
7491 case Intrinsic::stackprotector: {
7492 // Emit code into the DAG to store the stack guard onto the stack.
7493 MachineFunction &MF = DAG.getMachineFunction();
7494 MachineFrameInfo &MFI = MF.getFrameInfo();
7495 const Module &M = *MF.getFunction().getParent();
7496 SDValue Src, Chain = getRoot();
7497
7498 if (TLI.useLoadStackGuardNode(M))
7499 Src = getLoadStackGuard(DAG, DL: sdl, Chain);
7500 else
7501 Src = getValue(V: I.getArgOperand(i: 0)); // The guard's value.
7502
7503 AllocaInst *Slot = cast<AllocaInst>(Val: I.getArgOperand(i: 1));
7504
7505 int FI = FuncInfo.StaticAllocaMap[Slot];
7506 MFI.setStackProtectorIndex(FI);
7507 EVT PtrTy = TLI.getFrameIndexTy(DL: DAG.getDataLayout());
7508
7509 SDValue FIN = DAG.getFrameIndex(FI, VT: PtrTy);
7510
7511 // Store the stack protector onto the stack.
7512 Res = DAG.getStore(
7513 Chain, dl: sdl, Val: Src, Ptr: FIN,
7514 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI),
7515 Alignment: MaybeAlign(), MMOFlags: MachineMemOperand::MOVolatile);
7516 setValue(V: &I, NewN: Res);
7517 DAG.setRoot(Res);
7518 return;
7519 }
7520 case Intrinsic::objectsize:
7521 llvm_unreachable("llvm.objectsize.* should have been lowered already");
7522
7523 case Intrinsic::is_constant:
7524 llvm_unreachable("llvm.is.constant.* should have been lowered already");
7525
7526 case Intrinsic::annotation:
7527 case Intrinsic::ptr_annotation:
7528 case Intrinsic::launder_invariant_group:
7529 case Intrinsic::strip_invariant_group:
7530 // Drop the intrinsic, but forward the value
7531 setValue(V: &I, NewN: getValue(V: I.getOperand(i_nocapture: 0)));
7532 return;
7533
7534 case Intrinsic::type_test:
7535 case Intrinsic::public_type_test:
7536 setValue(V: &I, NewN: getValue(V: ConstantInt::getTrue(Ty: I.getType())));
7537 return;
7538
7539 case Intrinsic::assume:
7540 case Intrinsic::experimental_noalias_scope_decl:
7541 case Intrinsic::var_annotation:
7542 case Intrinsic::sideeffect:
7543 // Discard annotate attributes, noalias scope declarations, assumptions, and
7544 // artificial side-effects.
7545 return;
7546
7547 case Intrinsic::codeview_annotation: {
7548 // Emit a label associated with this metadata.
7549 MachineFunction &MF = DAG.getMachineFunction();
7550 MCSymbol *Label = MF.getContext().createTempSymbol(Name: "annotation", AlwaysAddSuffix: true);
7551 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 0))->getMetadata();
7552 MF.addCodeViewAnnotation(Label, MD: cast<MDNode>(Val: MD));
7553 Res = DAG.getLabelNode(Opcode: ISD::ANNOTATION_LABEL, dl: sdl, Root: getRoot(), Label);
7554 DAG.setRoot(Res);
7555 return;
7556 }
7557
7558 case Intrinsic::init_trampoline: {
7559 const Function *F = cast<Function>(Val: I.getArgOperand(i: 1)->stripPointerCasts());
7560
7561 SDValue Ops[6];
7562 Ops[0] = getRoot();
7563 Ops[1] = getValue(V: I.getArgOperand(i: 0));
7564 Ops[2] = getValue(V: I.getArgOperand(i: 1));
7565 Ops[3] = getValue(V: I.getArgOperand(i: 2));
7566 Ops[4] = DAG.getSrcValue(v: I.getArgOperand(i: 0));
7567 Ops[5] = DAG.getSrcValue(v: F);
7568
7569 Res = DAG.getNode(Opcode: ISD::INIT_TRAMPOLINE, DL: sdl, VT: MVT::Other, Ops);
7570
7571 DAG.setRoot(Res);
7572 return;
7573 }
7574 case Intrinsic::adjust_trampoline:
7575 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::ADJUST_TRAMPOLINE, DL: sdl,
7576 VT: TLI.getPointerTy(DL: DAG.getDataLayout()),
7577 Operand: getValue(V: I.getArgOperand(i: 0))));
7578 return;
7579 case Intrinsic::gcroot: {
7580 assert(DAG.getMachineFunction().getFunction().hasGC() &&
7581 "only valid in functions with gc specified, enforced by Verifier");
7582 assert(GFI && "implied by previous");
7583 const Value *Alloca = I.getArgOperand(i: 0)->stripPointerCasts();
7584 const Constant *TypeMap = cast<Constant>(Val: I.getArgOperand(i: 1));
7585
7586 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(Val: getValue(V: Alloca).getNode());
7587 GFI->addStackRoot(Num: FI->getIndex(), Metadata: TypeMap);
7588 return;
7589 }
7590 case Intrinsic::gcread:
7591 case Intrinsic::gcwrite:
7592 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7593 case Intrinsic::get_rounding:
7594 Res = DAG.getNode(Opcode: ISD::GET_ROUNDING, DL: sdl, ResultTys: {MVT::i32, MVT::Other}, Ops: getRoot());
7595 setValue(V: &I, NewN: Res);
7596 DAG.setRoot(Res.getValue(R: 1));
7597 return;
7598
7599 case Intrinsic::expect:
7600 case Intrinsic::expect_with_probability:
7601 // Just replace __builtin_expect(exp, c) and
7602 // __builtin_expect_with_probability(exp, c, p) with EXP.
7603 setValue(V: &I, NewN: getValue(V: I.getArgOperand(i: 0)));
7604 return;
7605
7606 case Intrinsic::ubsantrap:
7607 case Intrinsic::debugtrap:
7608 case Intrinsic::trap: {
7609 StringRef TrapFuncName =
7610 I.getAttributes().getFnAttr(Kind: "trap-func-name").getValueAsString();
7611 if (TrapFuncName.empty()) {
7612 switch (Intrinsic) {
7613 case Intrinsic::trap:
7614 DAG.setRoot(DAG.getNode(Opcode: ISD::TRAP, DL: sdl, VT: MVT::Other, Operand: getRoot()));
7615 break;
7616 case Intrinsic::debugtrap:
7617 DAG.setRoot(DAG.getNode(Opcode: ISD::DEBUGTRAP, DL: sdl, VT: MVT::Other, Operand: getRoot()));
7618 break;
7619 case Intrinsic::ubsantrap:
7620 DAG.setRoot(DAG.getNode(
7621 Opcode: ISD::UBSANTRAP, DL: sdl, VT: MVT::Other, N1: getRoot(),
7622 N2: DAG.getTargetConstant(
7623 Val: cast<ConstantInt>(Val: I.getArgOperand(i: 0))->getZExtValue(), DL: sdl,
7624 VT: MVT::i32)));
7625 break;
7626 default: llvm_unreachable("unknown trap intrinsic");
7627 }
7628 DAG.addNoMergeSiteInfo(Node: DAG.getRoot().getNode(),
7629 NoMerge: I.hasFnAttr(Kind: Attribute::NoMerge));
7630 return;
7631 }
7632 TargetLowering::ArgListTy Args;
7633 if (Intrinsic == Intrinsic::ubsantrap) {
7634 Value *Arg = I.getArgOperand(i: 0);
7635 Args.emplace_back(args&: Arg, args: getValue(V: Arg));
7636 }
7637
7638 TargetLowering::CallLoweringInfo CLI(DAG);
7639 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7640 CC: CallingConv::C, ResultType: I.getType(),
7641 Target: DAG.getExternalSymbol(Sym: TrapFuncName.data(),
7642 VT: TLI.getPointerTy(DL: DAG.getDataLayout())),
7643 ArgsList: std::move(Args));
7644 CLI.NoMerge = I.hasFnAttr(Kind: Attribute::NoMerge);
7645 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7646 DAG.setRoot(Result.second);
7647 return;
7648 }
7649
7650 case Intrinsic::allow_runtime_check:
7651 case Intrinsic::allow_ubsan_check:
7652 setValue(V: &I, NewN: getValue(V: ConstantInt::getTrue(Ty: I.getType())));
7653 return;
7654
7655 case Intrinsic::uadd_with_overflow:
7656 case Intrinsic::sadd_with_overflow:
7657 case Intrinsic::usub_with_overflow:
7658 case Intrinsic::ssub_with_overflow:
7659 case Intrinsic::umul_with_overflow:
7660 case Intrinsic::smul_with_overflow: {
7661 ISD::NodeType Op;
7662 switch (Intrinsic) {
7663 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7664 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7665 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7666 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7667 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7668 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7669 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7670 }
7671 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
7672 SDValue Op2 = getValue(V: I.getArgOperand(i: 1));
7673
7674 EVT ResultVT = Op1.getValueType();
7675 EVT OverflowVT = ResultVT.changeElementType(Context&: *Context, EltVT: MVT::i1);
7676
7677 SDVTList VTs = DAG.getVTList(VT1: ResultVT, VT2: OverflowVT);
7678 setValue(V: &I, NewN: DAG.getNode(Opcode: Op, DL: sdl, VTList: VTs, N1: Op1, N2: Op2));
7679 return;
7680 }
7681 case Intrinsic::prefetch: {
7682 SDValue Ops[5];
7683 unsigned rw = cast<ConstantInt>(Val: I.getArgOperand(i: 1))->getZExtValue();
7684 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7685 Ops[0] = DAG.getRoot();
7686 Ops[1] = getValue(V: I.getArgOperand(i: 0));
7687 Ops[2] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 1)), DL: sdl,
7688 VT: MVT::i32);
7689 Ops[3] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 2)), DL: sdl,
7690 VT: MVT::i32);
7691 Ops[4] = DAG.getTargetConstant(Val: *cast<ConstantInt>(Val: I.getArgOperand(i: 3)), DL: sdl,
7692 VT: MVT::i32);
7693 SDValue Result = DAG.getMemIntrinsicNode(
7694 Opcode: ISD::PREFETCH, dl: sdl, VTList: DAG.getVTList(VT: MVT::Other), Ops,
7695 MemVT: EVT::getIntegerVT(Context&: *Context, BitWidth: 8), PtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
7696 /* align */ Alignment: std::nullopt, Flags);
7697
7698 // Chain the prefetch in parallel with any pending loads, to stay out of
7699 // the way of later optimizations.
7700 PendingLoads.push_back(Elt: Result);
7701 Result = getRoot();
7702 DAG.setRoot(Result);
7703 return;
7704 }
7705 case Intrinsic::lifetime_start:
7706 case Intrinsic::lifetime_end: {
7707 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7708 // Stack coloring is not enabled in O0, discard region information.
7709 if (TM.getOptLevel() == CodeGenOptLevel::None)
7710 return;
7711
7712 const AllocaInst *LifetimeObject = dyn_cast<AllocaInst>(Val: I.getArgOperand(i: 0));
7713 if (!LifetimeObject)
7714 return;
7715
7716 // First check that the Alloca is static, otherwise it won't have a
7717 // valid frame index.
7718 auto SI = FuncInfo.StaticAllocaMap.find(Val: LifetimeObject);
7719 if (SI == FuncInfo.StaticAllocaMap.end())
7720 return;
7721
7722 const int FrameIndex = SI->second;
7723 Res = DAG.getLifetimeNode(IsStart, dl: sdl, Chain: getRoot(), FrameIndex);
7724 DAG.setRoot(Res);
7725 return;
7726 }
7727 case Intrinsic::pseudoprobe: {
7728 auto Guid = cast<ConstantInt>(Val: I.getArgOperand(i: 0))->getZExtValue();
7729 auto Index = cast<ConstantInt>(Val: I.getArgOperand(i: 1))->getZExtValue();
7730 auto Attr = cast<ConstantInt>(Val: I.getArgOperand(i: 2))->getZExtValue();
7731 Res = DAG.getPseudoProbeNode(Dl: sdl, Chain: getRoot(), Guid, Index, Attr);
7732 DAG.setRoot(Res);
7733 return;
7734 }
7735 case Intrinsic::invariant_start:
7736 // Discard region information.
7737 setValue(V: &I,
7738 NewN: DAG.getUNDEF(VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType())));
7739 return;
7740 case Intrinsic::invariant_end:
7741 // Discard region information.
7742 return;
7743 case Intrinsic::clear_cache: {
7744 SDValue InputChain = DAG.getRoot();
7745 SDValue StartVal = getValue(V: I.getArgOperand(i: 0));
7746 SDValue EndVal = getValue(V: I.getArgOperand(i: 1));
7747 Res = DAG.getNode(Opcode: ISD::CLEAR_CACHE, DL: sdl, VTList: DAG.getVTList(VT: MVT::Other),
7748 Ops: {InputChain, StartVal, EndVal});
7749 setValue(V: &I, NewN: Res);
7750 DAG.setRoot(Res);
7751 return;
7752 }
7753 case Intrinsic::donothing:
7754 case Intrinsic::seh_try_begin:
7755 case Intrinsic::seh_scope_begin:
7756 case Intrinsic::seh_try_end:
7757 case Intrinsic::seh_scope_end:
7758 // ignore
7759 return;
7760 case Intrinsic::experimental_stackmap:
7761 visitStackmap(I);
7762 return;
7763 case Intrinsic::experimental_patchpoint_void:
7764 case Intrinsic::experimental_patchpoint:
7765 visitPatchpoint(CB: I);
7766 return;
7767 case Intrinsic::experimental_gc_statepoint:
7768 LowerStatepoint(I: cast<GCStatepointInst>(Val: I));
7769 return;
7770 case Intrinsic::experimental_gc_result:
7771 visitGCResult(I: cast<GCResultInst>(Val: I));
7772 return;
7773 case Intrinsic::experimental_gc_relocate:
7774 visitGCRelocate(Relocate: cast<GCRelocateInst>(Val: I));
7775 return;
7776 case Intrinsic::instrprof_cover:
7777 llvm_unreachable("instrprof failed to lower a cover");
7778 case Intrinsic::instrprof_increment:
7779 llvm_unreachable("instrprof failed to lower an increment");
7780 case Intrinsic::instrprof_timestamp:
7781 llvm_unreachable("instrprof failed to lower a timestamp");
7782 case Intrinsic::instrprof_value_profile:
7783 llvm_unreachable("instrprof failed to lower a value profiling call");
7784 case Intrinsic::instrprof_mcdc_parameters:
7785 llvm_unreachable("instrprof failed to lower mcdc parameters");
7786 case Intrinsic::instrprof_mcdc_tvbitmap_update:
7787 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7788 case Intrinsic::localescape: {
7789 MachineFunction &MF = DAG.getMachineFunction();
7790 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7791
7792 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7793 // is the same on all targets.
7794 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7795 Value *Arg = I.getArgOperand(i: Idx)->stripPointerCasts();
7796 if (isa<ConstantPointerNull>(Val: Arg))
7797 continue; // Skip null pointers. They represent a hole in index space.
7798 AllocaInst *Slot = cast<AllocaInst>(Val: Arg);
7799 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7800 "can only escape static allocas");
7801 int FI = FuncInfo.StaticAllocaMap[Slot];
7802 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7803 FuncName: GlobalValue::dropLLVMManglingEscape(Name: MF.getName()), Idx);
7804 BuildMI(BB&: *FuncInfo.MBB, I: FuncInfo.InsertPt, MIMD: dl,
7805 MCID: TII->get(Opcode: TargetOpcode::LOCAL_ESCAPE))
7806 .addSym(Sym: FrameAllocSym)
7807 .addFrameIndex(Idx: FI);
7808 }
7809
7810 return;
7811 }
7812
7813 case Intrinsic::localrecover: {
7814 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7815 MachineFunction &MF = DAG.getMachineFunction();
7816
7817 // Get the symbol that defines the frame offset.
7818 auto *Fn = cast<Function>(Val: I.getArgOperand(i: 0)->stripPointerCasts());
7819 auto *Idx = cast<ConstantInt>(Val: I.getArgOperand(i: 2));
7820 unsigned IdxVal =
7821 unsigned(Idx->getLimitedValue(Limit: std::numeric_limits<int>::max()));
7822 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7823 FuncName: GlobalValue::dropLLVMManglingEscape(Name: Fn->getName()), Idx: IdxVal);
7824
7825 Value *FP = I.getArgOperand(i: 1);
7826 SDValue FPVal = getValue(V: FP);
7827 EVT PtrVT = FPVal.getValueType();
7828
7829 // Create a MCSymbol for the label to avoid any target lowering
7830 // that would make this PC relative.
7831 SDValue OffsetSym = DAG.getMCSymbol(Sym: FrameAllocSym, VT: PtrVT);
7832 SDValue OffsetVal =
7833 DAG.getNode(Opcode: ISD::LOCAL_RECOVER, DL: sdl, VT: PtrVT, Operand: OffsetSym);
7834
7835 // Add the offset to the FP.
7836 SDValue Add = DAG.getMemBasePlusOffset(Base: FPVal, Offset: OffsetVal, DL: sdl);
7837 setValue(V: &I, NewN: Add);
7838
7839 return;
7840 }
7841
7842 case Intrinsic::fake_use: {
7843 Value *V = I.getArgOperand(i: 0);
7844 SDValue Ops[2];
7845 // For Values not declared or previously used in this basic block, the
7846 // NodeMap will not have an entry, and `getValue` will assert if V has no
7847 // valid register value.
7848 auto FakeUseValue = [&]() -> SDValue {
7849 SDValue &N = NodeMap[V];
7850 if (N.getNode())
7851 return N;
7852
7853 // If there's a virtual register allocated and initialized for this
7854 // value, use it.
7855 if (SDValue copyFromReg = getCopyFromRegs(V, Ty: V->getType()))
7856 return copyFromReg;
7857 // FIXME: Do we want to preserve constants? It seems pointless.
7858 if (isa<Constant>(Val: V))
7859 return getValue(V);
7860 return SDValue();
7861 }();
7862 if (!FakeUseValue || FakeUseValue.isUndef())
7863 return;
7864 Ops[0] = getRoot();
7865 Ops[1] = FakeUseValue;
7866 // Also, do not translate a fake use with an undef operand, or any other
7867 // empty SDValues.
7868 if (!Ops[1] || Ops[1].isUndef())
7869 return;
7870 DAG.setRoot(DAG.getNode(Opcode: ISD::FAKE_USE, DL: sdl, VT: MVT::Other, Ops));
7871 return;
7872 }
7873
7874 case Intrinsic::reloc_none: {
7875 Metadata *MD = cast<MetadataAsValue>(Val: I.getArgOperand(i: 0))->getMetadata();
7876 StringRef SymbolName = cast<MDString>(Val: MD)->getString();
7877 SDValue Ops[2] = {
7878 getRoot(),
7879 DAG.getTargetExternalSymbol(
7880 Sym: SymbolName.data(), VT: TLI.getProgramPointerTy(DL: DAG.getDataLayout()))};
7881 DAG.setRoot(DAG.getNode(Opcode: ISD::RELOC_NONE, DL: sdl, VT: MVT::Other, Ops));
7882 return;
7883 }
7884
7885 case Intrinsic::eh_exceptionpointer:
7886 case Intrinsic::eh_exceptioncode: {
7887 // Get the exception pointer vreg, copy from it, and resize it to fit.
7888 const auto *CPI = cast<CatchPadInst>(Val: I.getArgOperand(i: 0));
7889 MVT PtrVT = TLI.getPointerTy(DL: DAG.getDataLayout());
7890 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(VT: PtrVT);
7891 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, RC: PtrRC);
7892 SDValue N = DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl: sdl, Reg: VReg, VT: PtrVT);
7893 if (Intrinsic == Intrinsic::eh_exceptioncode)
7894 N = DAG.getZExtOrTrunc(Op: N, DL: sdl, VT: MVT::i32);
7895 setValue(V: &I, NewN: N);
7896 return;
7897 }
7898 case Intrinsic::xray_customevent: {
7899 // Here we want to make sure that the intrinsic behaves as if it has a
7900 // specific calling convention.
7901 const auto &Triple = DAG.getTarget().getTargetTriple();
7902 if (!Triple.isAArch64(PointerWidth: 64) && Triple.getArch() != Triple::x86_64)
7903 return;
7904
7905 SmallVector<SDValue, 8> Ops;
7906
7907 // We want to say that we always want the arguments in registers.
7908 SDValue LogEntryVal = getValue(V: I.getArgOperand(i: 0));
7909 SDValue StrSizeVal = getValue(V: I.getArgOperand(i: 1));
7910 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
7911 SDValue Chain = getRoot();
7912 Ops.push_back(Elt: LogEntryVal);
7913 Ops.push_back(Elt: StrSizeVal);
7914 Ops.push_back(Elt: Chain);
7915
7916 // We need to enforce the calling convention for the callsite, so that
7917 // argument ordering is enforced correctly, and that register allocation can
7918 // see that some registers may be assumed clobbered and have to preserve
7919 // them across calls to the intrinsic.
7920 MachineSDNode *MN = DAG.getMachineNode(Opcode: TargetOpcode::PATCHABLE_EVENT_CALL,
7921 dl: sdl, VTs: NodeTys, Ops);
7922 SDValue patchableNode = SDValue(MN, 0);
7923 DAG.setRoot(patchableNode);
7924 setValue(V: &I, NewN: patchableNode);
7925 return;
7926 }
7927 case Intrinsic::xray_typedevent: {
7928 // Here we want to make sure that the intrinsic behaves as if it has a
7929 // specific calling convention.
7930 const auto &Triple = DAG.getTarget().getTargetTriple();
7931 if (!Triple.isAArch64(PointerWidth: 64) && Triple.getArch() != Triple::x86_64)
7932 return;
7933
7934 SmallVector<SDValue, 8> Ops;
7935
7936 // We want to say that we always want the arguments in registers.
7937 // It's unclear to me how manipulating the selection DAG here forces callers
7938 // to provide arguments in registers instead of on the stack.
7939 SDValue LogTypeId = getValue(V: I.getArgOperand(i: 0));
7940 SDValue LogEntryVal = getValue(V: I.getArgOperand(i: 1));
7941 SDValue StrSizeVal = getValue(V: I.getArgOperand(i: 2));
7942 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
7943 SDValue Chain = getRoot();
7944 Ops.push_back(Elt: LogTypeId);
7945 Ops.push_back(Elt: LogEntryVal);
7946 Ops.push_back(Elt: StrSizeVal);
7947 Ops.push_back(Elt: Chain);
7948
7949 // We need to enforce the calling convention for the callsite, so that
7950 // argument ordering is enforced correctly, and that register allocation can
7951 // see that some registers may be assumed clobbered and have to preserve
7952 // them across calls to the intrinsic.
7953 MachineSDNode *MN = DAG.getMachineNode(
7954 Opcode: TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, dl: sdl, VTs: NodeTys, Ops);
7955 SDValue patchableNode = SDValue(MN, 0);
7956 DAG.setRoot(patchableNode);
7957 setValue(V: &I, NewN: patchableNode);
7958 return;
7959 }
7960 case Intrinsic::experimental_deoptimize:
7961 LowerDeoptimizeCall(CI: &I);
7962 return;
7963 case Intrinsic::stepvector:
7964 visitStepVector(I);
7965 return;
7966 case Intrinsic::vector_reduce_fadd:
7967 case Intrinsic::vector_reduce_fmul:
7968 case Intrinsic::vector_reduce_add:
7969 case Intrinsic::vector_reduce_mul:
7970 case Intrinsic::vector_reduce_and:
7971 case Intrinsic::vector_reduce_or:
7972 case Intrinsic::vector_reduce_xor:
7973 case Intrinsic::vector_reduce_smax:
7974 case Intrinsic::vector_reduce_smin:
7975 case Intrinsic::vector_reduce_umax:
7976 case Intrinsic::vector_reduce_umin:
7977 case Intrinsic::vector_reduce_fmax:
7978 case Intrinsic::vector_reduce_fmin:
7979 case Intrinsic::vector_reduce_fmaximum:
7980 case Intrinsic::vector_reduce_fminimum:
7981 visitVectorReduce(I, Intrinsic);
7982 return;
7983
7984 case Intrinsic::icall_branch_funnel: {
7985 SmallVector<SDValue, 16> Ops;
7986 Ops.push_back(Elt: getValue(V: I.getArgOperand(i: 0)));
7987
7988 int64_t Offset;
7989 auto *Base = dyn_cast<GlobalObject>(Val: GetPointerBaseWithConstantOffset(
7990 Ptr: I.getArgOperand(i: 1), Offset, DL: DAG.getDataLayout()));
7991 if (!Base)
7992 report_fatal_error(
7993 reason: "llvm.icall.branch.funnel operand must be a GlobalValue");
7994 Ops.push_back(Elt: DAG.getTargetGlobalAddress(GV: Base, DL: sdl, VT: MVT::i64, offset: 0));
7995
7996 struct BranchFunnelTarget {
7997 int64_t Offset;
7998 SDValue Target;
7999 };
8000 SmallVector<BranchFunnelTarget, 8> Targets;
8001
8002 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
8003 auto *ElemBase = dyn_cast<GlobalObject>(Val: GetPointerBaseWithConstantOffset(
8004 Ptr: I.getArgOperand(i: Op), Offset, DL: DAG.getDataLayout()));
8005 if (ElemBase != Base)
8006 report_fatal_error(reason: "all llvm.icall.branch.funnel operands must refer "
8007 "to the same GlobalValue");
8008
8009 SDValue Val = getValue(V: I.getArgOperand(i: Op + 1));
8010 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
8011 if (!GA)
8012 report_fatal_error(
8013 reason: "llvm.icall.branch.funnel operand must be a GlobalValue");
8014 Targets.push_back(Elt: {.Offset: Offset, .Target: DAG.getTargetGlobalAddress(
8015 GV: GA->getGlobal(), DL: sdl, VT: Val.getValueType(),
8016 offset: GA->getOffset())});
8017 }
8018 llvm::sort(C&: Targets,
8019 Comp: [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
8020 return T1.Offset < T2.Offset;
8021 });
8022
8023 for (auto &T : Targets) {
8024 Ops.push_back(Elt: DAG.getTargetConstant(Val: T.Offset, DL: sdl, VT: MVT::i32));
8025 Ops.push_back(Elt: T.Target);
8026 }
8027
8028 Ops.push_back(Elt: DAG.getRoot()); // Chain
8029 SDValue N(DAG.getMachineNode(Opcode: TargetOpcode::ICALL_BRANCH_FUNNEL, dl: sdl,
8030 VT: MVT::Other, Ops),
8031 0);
8032 DAG.setRoot(N);
8033 setValue(V: &I, NewN: N);
8034 HasTailCall = true;
8035 return;
8036 }
8037
8038 case Intrinsic::wasm_landingpad_index:
8039 // Information this intrinsic contained has been transferred to
8040 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
8041 // delete it now.
8042 return;
8043
8044 case Intrinsic::aarch64_settag:
8045 case Intrinsic::aarch64_settag_zero: {
8046 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8047 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
8048 SDValue Val = TSI.EmitTargetCodeForSetTag(
8049 DAG, dl: sdl, Chain: getRoot(), Addr: getValue(V: I.getArgOperand(i: 0)),
8050 Size: getValue(V: I.getArgOperand(i: 1)), DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
8051 ZeroData: ZeroMemory);
8052 DAG.setRoot(Val);
8053 setValue(V: &I, NewN: Val);
8054 return;
8055 }
8056 case Intrinsic::amdgcn_cs_chain: {
8057 // At this point we don't care if it's amdgpu_cs_chain or
8058 // amdgpu_cs_chain_preserve.
8059 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
8060
8061 Type *RetTy = I.getType();
8062 assert(RetTy->isVoidTy() && "Should not return");
8063
8064 SDValue Callee = getValue(V: I.getOperand(i_nocapture: 0));
8065
8066 // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8067 // We'll also tack the value of the EXEC mask at the end.
8068 TargetLowering::ArgListTy Args;
8069 Args.reserve(n: 3);
8070
8071 for (unsigned Idx : {2, 3, 1}) {
8072 TargetLowering::ArgListEntry Arg(getValue(V: I.getOperand(i_nocapture: Idx)),
8073 I.getOperand(i_nocapture: Idx)->getType());
8074 Arg.setAttributes(Call: &I, ArgIdx: Idx);
8075 Args.push_back(x: Arg);
8076 }
8077
8078 assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8079 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8080 Args[2].IsInReg = true; // EXEC should be inreg
8081
8082 // Forward the flags and any additional arguments.
8083 for (unsigned Idx = 4; Idx < I.arg_size(); ++Idx) {
8084 TargetLowering::ArgListEntry Arg(getValue(V: I.getOperand(i_nocapture: Idx)),
8085 I.getOperand(i_nocapture: Idx)->getType());
8086 Arg.setAttributes(Call: &I, ArgIdx: Idx);
8087 Args.push_back(x: Arg);
8088 }
8089
8090 TargetLowering::CallLoweringInfo CLI(DAG);
8091 CLI.setDebugLoc(getCurSDLoc())
8092 .setChain(getRoot())
8093 .setCallee(CC, ResultType: RetTy, Target: Callee, ArgsList: std::move(Args))
8094 .setNoReturn(true)
8095 .setTailCall(true)
8096 .setConvergent(I.isConvergent());
8097 CLI.CB = &I;
8098 std::pair<SDValue, SDValue> Result =
8099 lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8100 (void)Result;
8101 assert(!Result.first.getNode() && !Result.second.getNode() &&
8102 "Should've lowered as tail call");
8103
8104 HasTailCall = true;
8105 return;
8106 }
8107 case Intrinsic::amdgcn_call_whole_wave: {
8108 TargetLowering::ArgListTy Args;
8109 bool isTailCall = I.isTailCall();
8110
8111 // The first argument is the callee. Skip it when assembling the call args.
8112 for (unsigned Idx = 1; Idx < I.arg_size(); ++Idx) {
8113 TargetLowering::ArgListEntry Arg(getValue(V: I.getArgOperand(i: Idx)),
8114 I.getArgOperand(i: Idx)->getType());
8115 Arg.setAttributes(Call: &I, ArgIdx: Idx);
8116
8117 // If we have an explicit sret argument that is an Instruction, (i.e., it
8118 // might point to function-local memory), we can't meaningfully tail-call.
8119 if (Arg.IsSRet && isa<Instruction>(Val: I.getArgOperand(i: Idx)))
8120 isTailCall = false;
8121
8122 Args.push_back(x: Arg);
8123 }
8124
8125 SDValue ConvControlToken;
8126 if (auto Bundle = I.getOperandBundle(ID: LLVMContext::OB_convergencectrl)) {
8127 auto *Token = Bundle->Inputs[0].get();
8128 ConvControlToken = getValue(V: Token);
8129 }
8130
8131 TargetLowering::CallLoweringInfo CLI(DAG);
8132 CLI.setDebugLoc(getCurSDLoc())
8133 .setChain(getRoot())
8134 .setCallee(CC: CallingConv::AMDGPU_Gfx_WholeWave, ResultType: I.getType(),
8135 Target: getValue(V: I.getArgOperand(i: 0)), ArgsList: std::move(Args))
8136 .setTailCall(isTailCall && canTailCall(CB: I))
8137 .setIsPreallocated(
8138 I.countOperandBundlesOfType(ID: LLVMContext::OB_preallocated) != 0)
8139 .setConvergent(I.isConvergent())
8140 .setConvergenceControlToken(ConvControlToken);
8141 CLI.CB = &I;
8142
8143 std::pair<SDValue, SDValue> Result =
8144 lowerInvokable(CLI, /*EHPadBB=*/nullptr);
8145
8146 if (Result.first.getNode())
8147 setValue(V: &I, NewN: Result.first);
8148 return;
8149 }
8150 case Intrinsic::ptrmask: {
8151 SDValue Ptr = getValue(V: I.getOperand(i_nocapture: 0));
8152 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 1));
8153
8154 // On arm64_32, pointers are 32 bits when stored in memory, but
8155 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to
8156 // match the index type, but the pointer is 64 bits, so the mask must be
8157 // zero-extended up to 64 bits to match the pointer.
8158 EVT PtrVT =
8159 TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i_nocapture: 0)->getType());
8160 EVT MemVT =
8161 TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getOperand(i_nocapture: 0)->getType());
8162 assert(PtrVT == Ptr.getValueType());
8163 if (Mask.getValueType().getFixedSizeInBits() < MemVT.getFixedSizeInBits()) {
8164 // For AMDGPU buffer descriptors the mask is 48 bits, but the pointer is
8165 // 128-bit, so we have to pad the mask with ones for unused bits.
8166 auto HighOnes = DAG.getNode(
8167 Opcode: ISD::SHL, DL: sdl, VT: PtrVT, N1: DAG.getAllOnesConstant(DL: sdl, VT: PtrVT),
8168 N2: DAG.getShiftAmountConstant(Val: Mask.getValueType().getFixedSizeInBits(),
8169 VT: PtrVT, DL: sdl));
8170 Mask = DAG.getNode(Opcode: ISD::OR, DL: sdl, VT: PtrVT,
8171 N1: DAG.getZExtOrTrunc(Op: Mask, DL: sdl, VT: PtrVT), N2: HighOnes);
8172 } else if (Mask.getValueType() != PtrVT)
8173 Mask = DAG.getPtrExtOrTrunc(Op: Mask, DL: sdl, VT: PtrVT);
8174
8175 assert(Mask.getValueType() == PtrVT);
8176 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::AND, DL: sdl, VT: PtrVT, N1: Ptr, N2: Mask));
8177 return;
8178 }
8179 case Intrinsic::threadlocal_address: {
8180 setValue(V: &I, NewN: getValue(V: I.getOperand(i_nocapture: 0)));
8181 return;
8182 }
8183 case Intrinsic::get_active_lane_mask: {
8184 EVT CCVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8185 SDValue Index = getValue(V: I.getOperand(i_nocapture: 0));
8186 SDValue TripCount = getValue(V: I.getOperand(i_nocapture: 1));
8187 EVT ElementVT = Index.getValueType();
8188
8189 if (!TLI.shouldExpandGetActiveLaneMask(VT: CCVT, OpVT: ElementVT)) {
8190 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::GET_ACTIVE_LANE_MASK, DL: sdl, VT: CCVT, N1: Index,
8191 N2: TripCount));
8192 return;
8193 }
8194
8195 EVT VecTy = EVT::getVectorVT(Context&: *DAG.getContext(), VT: ElementVT,
8196 EC: CCVT.getVectorElementCount());
8197
8198 SDValue VectorIndex = DAG.getSplat(VT: VecTy, DL: sdl, Op: Index);
8199 SDValue VectorTripCount = DAG.getSplat(VT: VecTy, DL: sdl, Op: TripCount);
8200 SDValue VectorStep = DAG.getStepVector(DL: sdl, ResVT: VecTy);
8201 SDValue VectorInduction = DAG.getNode(
8202 Opcode: ISD::UADDSAT, DL: sdl, VT: VecTy, N1: VectorIndex, N2: VectorStep);
8203 SDValue SetCC = DAG.getSetCC(DL: sdl, VT: CCVT, LHS: VectorInduction,
8204 RHS: VectorTripCount, Cond: ISD::CondCode::SETULT);
8205 setValue(V: &I, NewN: SetCC);
8206 return;
8207 }
8208 case Intrinsic::experimental_get_vector_length: {
8209 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8210 "Expected positive VF");
8211 unsigned VF = cast<ConstantInt>(Val: I.getOperand(i_nocapture: 1))->getZExtValue();
8212 bool IsScalable = cast<ConstantInt>(Val: I.getOperand(i_nocapture: 2))->isOne();
8213
8214 SDValue Count = getValue(V: I.getOperand(i_nocapture: 0));
8215 EVT CountVT = Count.getValueType();
8216
8217 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8218 visitTargetIntrinsic(I, Intrinsic);
8219 return;
8220 }
8221
8222 // Expand to a umin between the trip count and the maximum elements the type
8223 // can hold.
8224 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8225
8226 // Extend the trip count to at least the result VT.
8227 if (CountVT.bitsLT(VT)) {
8228 Count = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: sdl, VT, Operand: Count);
8229 CountVT = VT;
8230 }
8231
8232 SDValue MaxEVL = DAG.getElementCount(DL: sdl, VT: CountVT,
8233 EC: ElementCount::get(MinVal: VF, Scalable: IsScalable));
8234
8235 SDValue UMin = DAG.getNode(Opcode: ISD::UMIN, DL: sdl, VT: CountVT, N1: Count, N2: MaxEVL);
8236 // Clip to the result type if needed.
8237 SDValue Trunc = DAG.getNode(Opcode: ISD::TRUNCATE, DL: sdl, VT, Operand: UMin);
8238
8239 setValue(V: &I, NewN: Trunc);
8240 return;
8241 }
8242 case Intrinsic::vector_partial_reduce_add: {
8243 SDValue Acc = getValue(V: I.getOperand(i_nocapture: 0));
8244 SDValue Input = getValue(V: I.getOperand(i_nocapture: 1));
8245 setValue(V: &I,
8246 NewN: DAG.getNode(Opcode: ISD::PARTIAL_REDUCE_UMLA, DL: sdl, VT: Acc.getValueType(), N1: Acc,
8247 N2: Input, N3: DAG.getConstant(Val: 1, DL: sdl, VT: Input.getValueType())));
8248 return;
8249 }
8250 case Intrinsic::vector_partial_reduce_fadd: {
8251 SDValue Acc = getValue(V: I.getOperand(i_nocapture: 0));
8252 SDValue Input = getValue(V: I.getOperand(i_nocapture: 1));
8253 setValue(V: &I, NewN: DAG.getNode(
8254 Opcode: ISD::PARTIAL_REDUCE_FMLA, DL: sdl, VT: Acc.getValueType(), N1: Acc,
8255 N2: Input, N3: DAG.getConstantFP(Val: 1.0, DL: sdl, VT: Input.getValueType())));
8256 return;
8257 }
8258 case Intrinsic::experimental_cttz_elts: {
8259 auto DL = getCurSDLoc();
8260 SDValue Op = getValue(V: I.getOperand(i_nocapture: 0));
8261 EVT OpVT = Op.getValueType();
8262
8263 if (!TLI.shouldExpandCttzElements(VT: OpVT)) {
8264 visitTargetIntrinsic(I, Intrinsic);
8265 return;
8266 }
8267
8268 if (OpVT.getScalarType() != MVT::i1) {
8269 // Compare the input vector elements to zero & use to count trailing zeros
8270 SDValue AllZero = DAG.getConstant(Val: 0, DL, VT: OpVT);
8271 OpVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::i1,
8272 EC: OpVT.getVectorElementCount());
8273 Op = DAG.getSetCC(DL, VT: OpVT, LHS: Op, RHS: AllZero, Cond: ISD::SETNE);
8274 }
8275
8276 // If the zero-is-poison flag is set, we can assume the upper limit
8277 // of the result is VF-1.
8278 bool ZeroIsPoison =
8279 !cast<ConstantSDNode>(Val: getValue(V: I.getOperand(i_nocapture: 1)))->isZero();
8280 ConstantRange VScaleRange(1, true); // Dummy value.
8281 if (isa<ScalableVectorType>(Val: I.getOperand(i_nocapture: 0)->getType()))
8282 VScaleRange = getVScaleRange(F: I.getCaller(), BitWidth: 64);
8283 unsigned EltWidth = TLI.getBitWidthForCttzElements(
8284 RetTy: I.getType(), EC: OpVT.getVectorElementCount(), ZeroIsPoison, VScaleRange: &VScaleRange);
8285
8286 MVT NewEltTy = MVT::getIntegerVT(BitWidth: EltWidth);
8287
8288 // Create the new vector type & get the vector length
8289 EVT NewVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: NewEltTy,
8290 EC: OpVT.getVectorElementCount());
8291
8292 SDValue VL =
8293 DAG.getElementCount(DL, VT: NewEltTy, EC: OpVT.getVectorElementCount());
8294
8295 SDValue StepVec = DAG.getStepVector(DL, ResVT: NewVT);
8296 SDValue SplatVL = DAG.getSplat(VT: NewVT, DL, Op: VL);
8297 SDValue StepVL = DAG.getNode(Opcode: ISD::SUB, DL, VT: NewVT, N1: SplatVL, N2: StepVec);
8298 SDValue Ext = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT: NewVT, Operand: Op);
8299 SDValue And = DAG.getNode(Opcode: ISD::AND, DL, VT: NewVT, N1: StepVL, N2: Ext);
8300 SDValue Max = DAG.getNode(Opcode: ISD::VECREDUCE_UMAX, DL, VT: NewEltTy, Operand: And);
8301 SDValue Sub = DAG.getNode(Opcode: ISD::SUB, DL, VT: NewEltTy, N1: VL, N2: Max);
8302
8303 EVT RetTy = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8304 SDValue Ret = DAG.getZExtOrTrunc(Op: Sub, DL, VT: RetTy);
8305
8306 setValue(V: &I, NewN: Ret);
8307 return;
8308 }
8309 case Intrinsic::vector_insert: {
8310 SDValue Vec = getValue(V: I.getOperand(i_nocapture: 0));
8311 SDValue SubVec = getValue(V: I.getOperand(i_nocapture: 1));
8312 SDValue Index = getValue(V: I.getOperand(i_nocapture: 2));
8313
8314 // The intrinsic's index type is i64, but the SDNode requires an index type
8315 // suitable for the target. Convert the index as required.
8316 MVT VectorIdxTy = TLI.getVectorIdxTy(DL: DAG.getDataLayout());
8317 if (Index.getValueType() != VectorIdxTy)
8318 Index = DAG.getVectorIdxConstant(Val: Index->getAsZExtVal(), DL: sdl);
8319
8320 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8321 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::INSERT_SUBVECTOR, DL: sdl, VT: ResultVT, N1: Vec, N2: SubVec,
8322 N3: Index));
8323 return;
8324 }
8325 case Intrinsic::vector_extract: {
8326 SDValue Vec = getValue(V: I.getOperand(i_nocapture: 0));
8327 SDValue Index = getValue(V: I.getOperand(i_nocapture: 1));
8328 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
8329
8330 // The intrinsic's index type is i64, but the SDNode requires an index type
8331 // suitable for the target. Convert the index as required.
8332 MVT VectorIdxTy = TLI.getVectorIdxTy(DL: DAG.getDataLayout());
8333 if (Index.getValueType() != VectorIdxTy)
8334 Index = DAG.getVectorIdxConstant(Val: Index->getAsZExtVal(), DL: sdl);
8335
8336 setValue(V: &I,
8337 NewN: DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: sdl, VT: ResultVT, N1: Vec, N2: Index));
8338 return;
8339 }
8340 case Intrinsic::experimental_vector_match: {
8341 SDValue Op1 = getValue(V: I.getOperand(i_nocapture: 0));
8342 SDValue Op2 = getValue(V: I.getOperand(i_nocapture: 1));
8343 SDValue Mask = getValue(V: I.getOperand(i_nocapture: 2));
8344 EVT Op1VT = Op1.getValueType();
8345 EVT Op2VT = Op2.getValueType();
8346 EVT ResVT = Mask.getValueType();
8347 unsigned SearchSize = Op2VT.getVectorNumElements();
8348
8349 // If the target has native support for this vector match operation, lower
8350 // the intrinsic untouched; otherwise, expand it below.
8351 if (!TLI.shouldExpandVectorMatch(VT: Op1VT, SearchSize)) {
8352 visitTargetIntrinsic(I, Intrinsic);
8353 return;
8354 }
8355
8356 SDValue Ret = DAG.getConstant(Val: 0, DL: sdl, VT: ResVT);
8357
8358 for (unsigned i = 0; i < SearchSize; ++i) {
8359 SDValue Op2Elem = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: sdl,
8360 VT: Op2VT.getVectorElementType(), N1: Op2,
8361 N2: DAG.getVectorIdxConstant(Val: i, DL: sdl));
8362 SDValue Splat = DAG.getNode(Opcode: ISD::SPLAT_VECTOR, DL: sdl, VT: Op1VT, Operand: Op2Elem);
8363 SDValue Cmp = DAG.getSetCC(DL: sdl, VT: ResVT, LHS: Op1, RHS: Splat, Cond: ISD::SETEQ);
8364 Ret = DAG.getNode(Opcode: ISD::OR, DL: sdl, VT: ResVT, N1: Ret, N2: Cmp);
8365 }
8366
8367 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::AND, DL: sdl, VT: ResVT, N1: Ret, N2: Mask));
8368 return;
8369 }
8370 case Intrinsic::vector_reverse:
8371 visitVectorReverse(I);
8372 return;
8373 case Intrinsic::vector_splice_left:
8374 case Intrinsic::vector_splice_right:
8375 visitVectorSplice(I);
8376 return;
8377 case Intrinsic::callbr_landingpad:
8378 visitCallBrLandingPad(I);
8379 return;
8380 case Intrinsic::vector_interleave2:
8381 visitVectorInterleave(I, Factor: 2);
8382 return;
8383 case Intrinsic::vector_interleave3:
8384 visitVectorInterleave(I, Factor: 3);
8385 return;
8386 case Intrinsic::vector_interleave4:
8387 visitVectorInterleave(I, Factor: 4);
8388 return;
8389 case Intrinsic::vector_interleave5:
8390 visitVectorInterleave(I, Factor: 5);
8391 return;
8392 case Intrinsic::vector_interleave6:
8393 visitVectorInterleave(I, Factor: 6);
8394 return;
8395 case Intrinsic::vector_interleave7:
8396 visitVectorInterleave(I, Factor: 7);
8397 return;
8398 case Intrinsic::vector_interleave8:
8399 visitVectorInterleave(I, Factor: 8);
8400 return;
8401 case Intrinsic::vector_deinterleave2:
8402 visitVectorDeinterleave(I, Factor: 2);
8403 return;
8404 case Intrinsic::vector_deinterleave3:
8405 visitVectorDeinterleave(I, Factor: 3);
8406 return;
8407 case Intrinsic::vector_deinterleave4:
8408 visitVectorDeinterleave(I, Factor: 4);
8409 return;
8410 case Intrinsic::vector_deinterleave5:
8411 visitVectorDeinterleave(I, Factor: 5);
8412 return;
8413 case Intrinsic::vector_deinterleave6:
8414 visitVectorDeinterleave(I, Factor: 6);
8415 return;
8416 case Intrinsic::vector_deinterleave7:
8417 visitVectorDeinterleave(I, Factor: 7);
8418 return;
8419 case Intrinsic::vector_deinterleave8:
8420 visitVectorDeinterleave(I, Factor: 8);
8421 return;
8422 case Intrinsic::experimental_vector_compress:
8423 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::VECTOR_COMPRESS, DL: sdl,
8424 VT: getValue(V: I.getArgOperand(i: 0)).getValueType(),
8425 N1: getValue(V: I.getArgOperand(i: 0)),
8426 N2: getValue(V: I.getArgOperand(i: 1)),
8427 N3: getValue(V: I.getArgOperand(i: 2)), Flags));
8428 return;
8429 case Intrinsic::experimental_convergence_anchor:
8430 case Intrinsic::experimental_convergence_entry:
8431 case Intrinsic::experimental_convergence_loop:
8432 visitConvergenceControl(I, Intrinsic);
8433 return;
8434 case Intrinsic::experimental_vector_histogram_add: {
8435 visitVectorHistogram(I, IntrinsicID: Intrinsic);
8436 return;
8437 }
8438 case Intrinsic::experimental_vector_extract_last_active: {
8439 visitVectorExtractLastActive(I, Intrinsic);
8440 return;
8441 }
8442 case Intrinsic::loop_dependence_war_mask:
8443 setValue(V: &I,
8444 NewN: DAG.getNode(Opcode: ISD::LOOP_DEPENDENCE_WAR_MASK, DL: sdl,
8445 VT: EVT::getEVT(Ty: I.getType()), N1: getValue(V: I.getOperand(i_nocapture: 0)),
8446 N2: getValue(V: I.getOperand(i_nocapture: 1)), N3: getValue(V: I.getOperand(i_nocapture: 2)),
8447 N4: DAG.getConstant(Val: 0, DL: sdl, VT: MVT::i64)));
8448 return;
8449 case Intrinsic::loop_dependence_raw_mask:
8450 setValue(V: &I,
8451 NewN: DAG.getNode(Opcode: ISD::LOOP_DEPENDENCE_RAW_MASK, DL: sdl,
8452 VT: EVT::getEVT(Ty: I.getType()), N1: getValue(V: I.getOperand(i_nocapture: 0)),
8453 N2: getValue(V: I.getOperand(i_nocapture: 1)), N3: getValue(V: I.getOperand(i_nocapture: 2)),
8454 N4: DAG.getConstant(Val: 0, DL: sdl, VT: MVT::i64)));
8455 return;
8456 }
8457}
8458
8459void SelectionDAGBuilder::pushFPOpOutChain(SDValue Result,
8460 fp::ExceptionBehavior EB) {
8461 assert(Result.getNode()->getNumValues() == 2);
8462 SDValue OutChain = Result.getValue(R: 1);
8463 assert(OutChain.getValueType() == MVT::Other);
8464
8465 // Instead of updating the root immediately, push the produced chain to the
8466 // appropriate list, deferring the update until the root is requested. In this
8467 // case, the nodes from the lists are chained using TokenFactor, indicating
8468 // that the operations are independent.
8469 //
8470 // In particular, the root is updated before any call that might access the
8471 // floating-point environment, except for constrained intrinsics.
8472 switch (EB) {
8473 case fp::ExceptionBehavior::ebMayTrap:
8474 case fp::ExceptionBehavior::ebIgnore:
8475 PendingConstrainedFP.push_back(Elt: OutChain);
8476 break;
8477 case fp::ExceptionBehavior::ebStrict:
8478 PendingConstrainedFPStrict.push_back(Elt: OutChain);
8479 break;
8480 }
8481}
8482
8483void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8484 const ConstrainedFPIntrinsic &FPI) {
8485 SDLoc sdl = getCurSDLoc();
8486
8487 // We do not need to serialize constrained FP intrinsics against
8488 // each other or against (nonvolatile) loads, so they can be
8489 // chained like loads.
8490 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8491 SDValue Chain = getFPOperationRoot(EB);
8492 SmallVector<SDValue, 4> Opers;
8493 Opers.push_back(Elt: Chain);
8494 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8495 Opers.push_back(Elt: getValue(V: FPI.getArgOperand(i: I)));
8496
8497 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8498 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: FPI.getType());
8499 SDVTList VTs = DAG.getVTList(VT1: VT, VT2: MVT::Other);
8500
8501 SDNodeFlags Flags;
8502 if (EB == fp::ExceptionBehavior::ebIgnore)
8503 Flags.setNoFPExcept(true);
8504
8505 if (auto *FPOp = dyn_cast<FPMathOperator>(Val: &FPI))
8506 Flags.copyFMF(FPMO: *FPOp);
8507
8508 unsigned Opcode;
8509 switch (FPI.getIntrinsicID()) {
8510 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8511#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8512 case Intrinsic::INTRINSIC: \
8513 Opcode = ISD::STRICT_##DAGN; \
8514 break;
8515#include "llvm/IR/ConstrainedOps.def"
8516 case Intrinsic::experimental_constrained_fmuladd: {
8517 Opcode = ISD::STRICT_FMA;
8518 // Break fmuladd into fmul and fadd.
8519 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8520 !TLI.isFMAFasterThanFMulAndFAdd(MF: DAG.getMachineFunction(), VT)) {
8521 Opers.pop_back();
8522 SDValue Mul = DAG.getNode(Opcode: ISD::STRICT_FMUL, DL: sdl, VTList: VTs, Ops: Opers, Flags);
8523 pushFPOpOutChain(Result: Mul, EB);
8524 Opcode = ISD::STRICT_FADD;
8525 Opers.clear();
8526 Opers.push_back(Elt: Mul.getValue(R: 1));
8527 Opers.push_back(Elt: Mul.getValue(R: 0));
8528 Opers.push_back(Elt: getValue(V: FPI.getArgOperand(i: 2)));
8529 }
8530 break;
8531 }
8532 }
8533
8534 // A few strict DAG nodes carry additional operands that are not
8535 // set up by the default code above.
8536 switch (Opcode) {
8537 default: break;
8538 case ISD::STRICT_FP_ROUND:
8539 Opers.push_back(
8540 Elt: DAG.getTargetConstant(Val: 0, DL: sdl, VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
8541 break;
8542 case ISD::STRICT_FSETCC:
8543 case ISD::STRICT_FSETCCS: {
8544 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(Val: &FPI);
8545 ISD::CondCode Condition = getFCmpCondCode(Pred: FPCmp->getPredicate());
8546 if (TM.Options.NoNaNsFPMath)
8547 Condition = getFCmpCodeWithoutNaN(CC: Condition);
8548 Opers.push_back(Elt: DAG.getCondCode(Cond: Condition));
8549 break;
8550 }
8551 }
8552
8553 SDValue Result = DAG.getNode(Opcode, DL: sdl, VTList: VTs, Ops: Opers, Flags);
8554 pushFPOpOutChain(Result, EB);
8555
8556 SDValue FPResult = Result.getValue(R: 0);
8557 setValue(V: &FPI, NewN: FPResult);
8558}
8559
8560static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8561 std::optional<unsigned> ResOPC;
8562 switch (VPIntrin.getIntrinsicID()) {
8563 case Intrinsic::vp_ctlz: {
8564 bool IsZeroUndef = cast<ConstantInt>(Val: VPIntrin.getArgOperand(i: 1))->isOne();
8565 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8566 break;
8567 }
8568 case Intrinsic::vp_cttz: {
8569 bool IsZeroUndef = cast<ConstantInt>(Val: VPIntrin.getArgOperand(i: 1))->isOne();
8570 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8571 break;
8572 }
8573 case Intrinsic::vp_cttz_elts: {
8574 bool IsZeroPoison = cast<ConstantInt>(Val: VPIntrin.getArgOperand(i: 1))->isOne();
8575 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8576 break;
8577 }
8578#define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \
8579 case Intrinsic::VPID: \
8580 ResOPC = ISD::VPSD; \
8581 break;
8582#include "llvm/IR/VPIntrinsics.def"
8583 }
8584
8585 if (!ResOPC)
8586 llvm_unreachable(
8587 "Inconsistency: no SDNode available for this VPIntrinsic!");
8588
8589 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8590 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8591 if (VPIntrin.getFastMathFlags().allowReassoc())
8592 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8593 : ISD::VP_REDUCE_FMUL;
8594 }
8595
8596 return *ResOPC;
8597}
8598
8599void SelectionDAGBuilder::visitVPLoad(
8600 const VPIntrinsic &VPIntrin, EVT VT,
8601 const SmallVectorImpl<SDValue> &OpValues) {
8602 SDLoc DL = getCurSDLoc();
8603 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8604 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8605 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8606 const MDNode *Ranges = getRangeMetadata(I: VPIntrin);
8607 SDValue LD;
8608 // Do not serialize variable-length loads of constant memory with
8609 // anything.
8610 if (!Alignment)
8611 Alignment = DAG.getEVTAlign(MemoryVT: VT);
8612 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
8613 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
8614 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8615 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8616 MachineMemOperand::Flags MMOFlags =
8617 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8618 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8619 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
8620 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: *Alignment, AAInfo, Ranges);
8621 LD = DAG.getLoadVP(VT, dl: DL, Chain: InChain, Ptr: OpValues[0], Mask: OpValues[1], EVL: OpValues[2],
8622 MMO, IsExpanding: false /*IsExpanding */);
8623 if (AddToChain)
8624 PendingLoads.push_back(Elt: LD.getValue(R: 1));
8625 setValue(V: &VPIntrin, NewN: LD);
8626}
8627
8628void SelectionDAGBuilder::visitVPLoadFF(
8629 const VPIntrinsic &VPIntrin, EVT VT, EVT EVLVT,
8630 const SmallVectorImpl<SDValue> &OpValues) {
8631 assert(OpValues.size() == 3 && "Unexpected number of operands");
8632 SDLoc DL = getCurSDLoc();
8633 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8634 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8635 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8636 const MDNode *Ranges = VPIntrin.getMetadata(KindID: LLVMContext::MD_range);
8637 SDValue LD;
8638 // Do not serialize variable-length loads of constant memory with
8639 // anything.
8640 if (!Alignment)
8641 Alignment = DAG.getEVTAlign(MemoryVT: VT);
8642 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
8643 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
8644 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8645 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8646 PtrInfo: MachinePointerInfo(PtrOperand), F: MachineMemOperand::MOLoad,
8647 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: *Alignment, AAInfo, Ranges);
8648 LD = DAG.getLoadFFVP(VT, DL, Chain: InChain, Ptr: OpValues[0], Mask: OpValues[1], EVL: OpValues[2],
8649 MMO);
8650 SDValue Trunc = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: EVLVT, Operand: LD.getValue(R: 1));
8651 if (AddToChain)
8652 PendingLoads.push_back(Elt: LD.getValue(R: 2));
8653 setValue(V: &VPIntrin, NewN: DAG.getMergeValues(Ops: {LD.getValue(R: 0), Trunc}, dl: DL));
8654}
8655
8656void SelectionDAGBuilder::visitVPGather(
8657 const VPIntrinsic &VPIntrin, EVT VT,
8658 const SmallVectorImpl<SDValue> &OpValues) {
8659 SDLoc DL = getCurSDLoc();
8660 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8661 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8662 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8663 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8664 const MDNode *Ranges = getRangeMetadata(I: VPIntrin);
8665 SDValue LD;
8666 if (!Alignment)
8667 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
8668 unsigned AS =
8669 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8670 MachineMemOperand::Flags MMOFlags =
8671 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8672 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8673 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
8674 BaseAlignment: *Alignment, AAInfo, Ranges);
8675 SDValue Base, Index, Scale;
8676 bool UniformBase =
8677 getUniformBase(Ptr: PtrOperand, Base, Index, Scale, SDB: this, CurBB: VPIntrin.getParent(),
8678 ElemSize: VT.getScalarStoreSize());
8679 if (!UniformBase) {
8680 Base = DAG.getConstant(Val: 0, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8681 Index = getValue(V: PtrOperand);
8682 Scale = DAG.getTargetConstant(Val: 1, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8683 }
8684 EVT IdxVT = Index.getValueType();
8685 EVT EltTy = IdxVT.getVectorElementType();
8686 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
8687 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
8688 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT: NewIdxVT, Operand: Index);
8689 }
8690 LD = DAG.getGatherVP(
8691 VTs: DAG.getVTList(VT1: VT, VT2: MVT::Other), VT, dl: DL,
8692 Ops: {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8693 IndexType: ISD::SIGNED_SCALED);
8694 PendingLoads.push_back(Elt: LD.getValue(R: 1));
8695 setValue(V: &VPIntrin, NewN: LD);
8696}
8697
8698void SelectionDAGBuilder::visitVPStore(
8699 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8700 SDLoc DL = getCurSDLoc();
8701 Value *PtrOperand = VPIntrin.getArgOperand(i: 1);
8702 EVT VT = OpValues[0].getValueType();
8703 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8704 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8705 SDValue ST;
8706 if (!Alignment)
8707 Alignment = DAG.getEVTAlign(MemoryVT: VT);
8708 SDValue Ptr = OpValues[1];
8709 SDValue Offset = DAG.getUNDEF(VT: Ptr.getValueType());
8710 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8711 MachineMemOperand::Flags MMOFlags =
8712 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8713 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8714 PtrInfo: MachinePointerInfo(PtrOperand), F: MMOFlags,
8715 Size: LocationSize::beforeOrAfterPointer(), BaseAlignment: *Alignment, AAInfo);
8716 ST = DAG.getStoreVP(Chain: getMemoryRoot(), dl: DL, Val: OpValues[0], Ptr, Offset,
8717 Mask: OpValues[2], EVL: OpValues[3], MemVT: VT, MMO, AM: ISD::UNINDEXED,
8718 /* IsTruncating */ false, /*IsCompressing*/ false);
8719 DAG.setRoot(ST);
8720 setValue(V: &VPIntrin, NewN: ST);
8721}
8722
8723void SelectionDAGBuilder::visitVPScatter(
8724 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8725 SDLoc DL = getCurSDLoc();
8726 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8727 Value *PtrOperand = VPIntrin.getArgOperand(i: 1);
8728 EVT VT = OpValues[0].getValueType();
8729 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8730 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8731 SDValue ST;
8732 if (!Alignment)
8733 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
8734 unsigned AS =
8735 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8736 MachineMemOperand::Flags MMOFlags =
8737 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8738 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8739 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
8740 BaseAlignment: *Alignment, AAInfo);
8741 SDValue Base, Index, Scale;
8742 bool UniformBase =
8743 getUniformBase(Ptr: PtrOperand, Base, Index, Scale, SDB: this, CurBB: VPIntrin.getParent(),
8744 ElemSize: VT.getScalarStoreSize());
8745 if (!UniformBase) {
8746 Base = DAG.getConstant(Val: 0, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8747 Index = getValue(V: PtrOperand);
8748 Scale = DAG.getTargetConstant(Val: 1, DL, VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
8749 }
8750 EVT IdxVT = Index.getValueType();
8751 EVT EltTy = IdxVT.getVectorElementType();
8752 if (TLI.shouldExtendGSIndex(VT: IdxVT, EltTy)) {
8753 EVT NewIdxVT = IdxVT.changeVectorElementType(Context&: *DAG.getContext(), EltVT: EltTy);
8754 Index = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT: NewIdxVT, Operand: Index);
8755 }
8756 ST = DAG.getScatterVP(VTs: DAG.getVTList(VT: MVT::Other), VT, dl: DL,
8757 Ops: {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8758 OpValues[2], OpValues[3]},
8759 MMO, IndexType: ISD::SIGNED_SCALED);
8760 DAG.setRoot(ST);
8761 setValue(V: &VPIntrin, NewN: ST);
8762}
8763
8764void SelectionDAGBuilder::visitVPStridedLoad(
8765 const VPIntrinsic &VPIntrin, EVT VT,
8766 const SmallVectorImpl<SDValue> &OpValues) {
8767 SDLoc DL = getCurSDLoc();
8768 Value *PtrOperand = VPIntrin.getArgOperand(i: 0);
8769 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8770 if (!Alignment)
8771 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
8772 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8773 const MDNode *Ranges = getRangeMetadata(I: VPIntrin);
8774 MemoryLocation ML = MemoryLocation::getAfter(Ptr: PtrOperand, AATags: AAInfo);
8775 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(Loc: ML);
8776 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8777 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8778 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8779 MachineMemOperand::Flags MMOFlags =
8780 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8781 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8782 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
8783 BaseAlignment: *Alignment, AAInfo, Ranges);
8784
8785 SDValue LD = DAG.getStridedLoadVP(VT, DL, Chain: InChain, Ptr: OpValues[0], Stride: OpValues[1],
8786 Mask: OpValues[2], EVL: OpValues[3], MMO,
8787 IsExpanding: false /*IsExpanding*/);
8788
8789 if (AddToChain)
8790 PendingLoads.push_back(Elt: LD.getValue(R: 1));
8791 setValue(V: &VPIntrin, NewN: LD);
8792}
8793
8794void SelectionDAGBuilder::visitVPStridedStore(
8795 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8796 SDLoc DL = getCurSDLoc();
8797 Value *PtrOperand = VPIntrin.getArgOperand(i: 1);
8798 EVT VT = OpValues[0].getValueType();
8799 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8800 if (!Alignment)
8801 Alignment = DAG.getEVTAlign(MemoryVT: VT.getScalarType());
8802 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8803 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8804 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8805 MachineMemOperand::Flags MMOFlags =
8806 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8807 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8808 PtrInfo: MachinePointerInfo(AS), F: MMOFlags, Size: LocationSize::beforeOrAfterPointer(),
8809 BaseAlignment: *Alignment, AAInfo);
8810
8811 SDValue ST = DAG.getStridedStoreVP(
8812 Chain: getMemoryRoot(), DL, Val: OpValues[0], Ptr: OpValues[1],
8813 Offset: DAG.getUNDEF(VT: OpValues[1].getValueType()), Stride: OpValues[2], Mask: OpValues[3],
8814 EVL: OpValues[4], MemVT: VT, MMO, AM: ISD::UNINDEXED, /*IsTruncating*/ false,
8815 /*IsCompressing*/ false);
8816
8817 DAG.setRoot(ST);
8818 setValue(V: &VPIntrin, NewN: ST);
8819}
8820
8821void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8822 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8823 SDLoc DL = getCurSDLoc();
8824
8825 ISD::CondCode Condition;
8826 CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8827 bool IsFP = VPIntrin.getOperand(i_nocapture: 0)->getType()->isFPOrFPVectorTy();
8828 if (IsFP) {
8829 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8830 // flags, but calls that don't return floating-point types can't be
8831 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8832 Condition = getFCmpCondCode(Pred: CondCode);
8833 if (TM.Options.NoNaNsFPMath)
8834 Condition = getFCmpCodeWithoutNaN(CC: Condition);
8835 } else {
8836 Condition = getICmpCondCode(Pred: CondCode);
8837 }
8838
8839 SDValue Op1 = getValue(V: VPIntrin.getOperand(i_nocapture: 0));
8840 SDValue Op2 = getValue(V: VPIntrin.getOperand(i_nocapture: 1));
8841 // #2 is the condition code
8842 SDValue MaskOp = getValue(V: VPIntrin.getOperand(i_nocapture: 3));
8843 SDValue EVL = getValue(V: VPIntrin.getOperand(i_nocapture: 4));
8844 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8845 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8846 "Unexpected target EVL type");
8847 EVL = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL, VT: EVLParamVT, Operand: EVL);
8848
8849 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
8850 Ty: VPIntrin.getType());
8851 setValue(V: &VPIntrin,
8852 NewN: DAG.getSetCCVP(DL, VT: DestVT, LHS: Op1, RHS: Op2, Cond: Condition, Mask: MaskOp, EVL));
8853}
8854
8855void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8856 const VPIntrinsic &VPIntrin) {
8857 SDLoc DL = getCurSDLoc();
8858 unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8859
8860 auto IID = VPIntrin.getIntrinsicID();
8861
8862 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(Val: &VPIntrin))
8863 return visitVPCmp(VPIntrin: *CmpI);
8864
8865 SmallVector<EVT, 4> ValueVTs;
8866 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8867 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: VPIntrin.getType(), ValueVTs);
8868 SDVTList VTs = DAG.getVTList(VTs: ValueVTs);
8869
8870 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IntrinsicID: IID);
8871
8872 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8873 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8874 "Unexpected target EVL type");
8875
8876 // Request operands.
8877 SmallVector<SDValue, 7> OpValues;
8878 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8879 auto Op = getValue(V: VPIntrin.getArgOperand(i: I));
8880 if (I == EVLParamPos)
8881 Op = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL, VT: EVLParamVT, Operand: Op);
8882 OpValues.push_back(Elt: Op);
8883 }
8884
8885 switch (Opcode) {
8886 default: {
8887 SDNodeFlags SDFlags;
8888 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &VPIntrin))
8889 SDFlags.copyFMF(FPMO: *FPMO);
8890 SDValue Result = DAG.getNode(Opcode, DL, VTList: VTs, Ops: OpValues, Flags: SDFlags);
8891 setValue(V: &VPIntrin, NewN: Result);
8892 break;
8893 }
8894 case ISD::VP_LOAD:
8895 visitVPLoad(VPIntrin, VT: ValueVTs[0], OpValues);
8896 break;
8897 case ISD::VP_LOAD_FF:
8898 visitVPLoadFF(VPIntrin, VT: ValueVTs[0], EVLVT: ValueVTs[1], OpValues);
8899 break;
8900 case ISD::VP_GATHER:
8901 visitVPGather(VPIntrin, VT: ValueVTs[0], OpValues);
8902 break;
8903 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8904 visitVPStridedLoad(VPIntrin, VT: ValueVTs[0], OpValues);
8905 break;
8906 case ISD::VP_STORE:
8907 visitVPStore(VPIntrin, OpValues);
8908 break;
8909 case ISD::VP_SCATTER:
8910 visitVPScatter(VPIntrin, OpValues);
8911 break;
8912 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8913 visitVPStridedStore(VPIntrin, OpValues);
8914 break;
8915 case ISD::VP_FMULADD: {
8916 assert(OpValues.size() == 5 && "Unexpected number of operands");
8917 SDNodeFlags SDFlags;
8918 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &VPIntrin))
8919 SDFlags.copyFMF(FPMO: *FPMO);
8920 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8921 TLI.isFMAFasterThanFMulAndFAdd(MF: DAG.getMachineFunction(), ValueVTs[0])) {
8922 setValue(V: &VPIntrin, NewN: DAG.getNode(Opcode: ISD::VP_FMA, DL, VTList: VTs, Ops: OpValues, Flags: SDFlags));
8923 } else {
8924 SDValue Mul = DAG.getNode(
8925 Opcode: ISD::VP_FMUL, DL, VTList: VTs,
8926 Ops: {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, Flags: SDFlags);
8927 SDValue Add =
8928 DAG.getNode(Opcode: ISD::VP_FADD, DL, VTList: VTs,
8929 Ops: {Mul, OpValues[2], OpValues[3], OpValues[4]}, Flags: SDFlags);
8930 setValue(V: &VPIntrin, NewN: Add);
8931 }
8932 break;
8933 }
8934 case ISD::VP_IS_FPCLASS: {
8935 const DataLayout DLayout = DAG.getDataLayout();
8936 EVT DestVT = TLI.getValueType(DL: DLayout, Ty: VPIntrin.getType());
8937 auto Constant = OpValues[1]->getAsZExtVal();
8938 SDValue Check = DAG.getTargetConstant(Val: Constant, DL, VT: MVT::i32);
8939 SDValue V = DAG.getNode(Opcode: ISD::VP_IS_FPCLASS, DL, VT: DestVT,
8940 Ops: {OpValues[0], Check, OpValues[2], OpValues[3]});
8941 setValue(V: &VPIntrin, NewN: V);
8942 return;
8943 }
8944 case ISD::VP_INTTOPTR: {
8945 SDValue N = OpValues[0];
8946 EVT DestVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: VPIntrin.getType());
8947 EVT PtrMemVT = TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: VPIntrin.getType());
8948 N = DAG.getVPPtrExtOrTrunc(DL: getCurSDLoc(), VT: DestVT, Op: N, Mask: OpValues[1],
8949 EVL: OpValues[2]);
8950 N = DAG.getVPZExtOrTrunc(DL: getCurSDLoc(), VT: PtrMemVT, Op: N, Mask: OpValues[1],
8951 EVL: OpValues[2]);
8952 setValue(V: &VPIntrin, NewN: N);
8953 break;
8954 }
8955 case ISD::VP_PTRTOINT: {
8956 SDValue N = OpValues[0];
8957 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
8958 Ty: VPIntrin.getType());
8959 EVT PtrMemVT = TLI.getMemValueType(DL: DAG.getDataLayout(),
8960 Ty: VPIntrin.getOperand(i_nocapture: 0)->getType());
8961 N = DAG.getVPPtrExtOrTrunc(DL: getCurSDLoc(), VT: PtrMemVT, Op: N, Mask: OpValues[1],
8962 EVL: OpValues[2]);
8963 N = DAG.getVPZExtOrTrunc(DL: getCurSDLoc(), VT: DestVT, Op: N, Mask: OpValues[1],
8964 EVL: OpValues[2]);
8965 setValue(V: &VPIntrin, NewN: N);
8966 break;
8967 }
8968 case ISD::VP_ABS:
8969 case ISD::VP_CTLZ:
8970 case ISD::VP_CTLZ_ZERO_UNDEF:
8971 case ISD::VP_CTTZ:
8972 case ISD::VP_CTTZ_ZERO_UNDEF:
8973 case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8974 case ISD::VP_CTTZ_ELTS: {
8975 SDValue Result =
8976 DAG.getNode(Opcode, DL, VTList: VTs, Ops: {OpValues[0], OpValues[2], OpValues[3]});
8977 setValue(V: &VPIntrin, NewN: Result);
8978 break;
8979 }
8980 }
8981}
8982
8983SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8984 const BasicBlock *EHPadBB,
8985 MCSymbol *&BeginLabel) {
8986 MachineFunction &MF = DAG.getMachineFunction();
8987
8988 // Insert a label before the invoke call to mark the try range. This can be
8989 // used to detect deletion of the invoke via the MachineModuleInfo.
8990 BeginLabel = MF.getContext().createTempSymbol();
8991
8992 // For SjLj, keep track of which landing pads go with which invokes
8993 // so as to maintain the ordering of pads in the LSDA.
8994 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
8995 if (CallSiteIndex) {
8996 MF.setCallSiteBeginLabel(BeginLabel, Site: CallSiteIndex);
8997 LPadToCallSiteMap[FuncInfo.getMBB(BB: EHPadBB)].push_back(Elt: CallSiteIndex);
8998
8999 // Now that the call site is handled, stop tracking it.
9000 FuncInfo.setCurrentCallSite(0);
9001 }
9002
9003 return DAG.getEHLabel(dl: getCurSDLoc(), Root: Chain, Label: BeginLabel);
9004}
9005
9006SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
9007 const BasicBlock *EHPadBB,
9008 MCSymbol *BeginLabel) {
9009 assert(BeginLabel && "BeginLabel should've been set");
9010
9011 MachineFunction &MF = DAG.getMachineFunction();
9012
9013 // Insert a label at the end of the invoke call to mark the try range. This
9014 // can be used to detect deletion of the invoke via the MachineModuleInfo.
9015 MCSymbol *EndLabel = MF.getContext().createTempSymbol();
9016 Chain = DAG.getEHLabel(dl: getCurSDLoc(), Root: Chain, Label: EndLabel);
9017
9018 // Inform MachineModuleInfo of range.
9019 auto Pers = classifyEHPersonality(Pers: FuncInfo.Fn->getPersonalityFn());
9020 // There is a platform (e.g. wasm) that uses funclet style IR but does not
9021 // actually use outlined funclets and their LSDA info style.
9022 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
9023 assert(II && "II should've been set");
9024 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
9025 EHInfo->addIPToStateRange(II, InvokeBegin: BeginLabel, InvokeEnd: EndLabel);
9026 } else if (!isScopedEHPersonality(Pers)) {
9027 assert(EHPadBB);
9028 MF.addInvoke(LandingPad: FuncInfo.getMBB(BB: EHPadBB), BeginLabel, EndLabel);
9029 }
9030
9031 return Chain;
9032}
9033
9034std::pair<SDValue, SDValue>
9035SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
9036 const BasicBlock *EHPadBB) {
9037 MCSymbol *BeginLabel = nullptr;
9038
9039 if (EHPadBB) {
9040 // Both PendingLoads and PendingExports must be flushed here;
9041 // this call might not return.
9042 (void)getRoot();
9043 DAG.setRoot(lowerStartEH(Chain: getControlRoot(), EHPadBB, BeginLabel));
9044 CLI.setChain(getRoot());
9045 }
9046
9047 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9048 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
9049
9050 assert((CLI.IsTailCall || Result.second.getNode()) &&
9051 "Non-null chain expected with non-tail call!");
9052 assert((Result.second.getNode() || !Result.first.getNode()) &&
9053 "Null value expected with tail call!");
9054
9055 if (!Result.second.getNode()) {
9056 // As a special case, a null chain means that a tail call has been emitted
9057 // and the DAG root is already updated.
9058 HasTailCall = true;
9059
9060 // Since there's no actual continuation from this block, nothing can be
9061 // relying on us setting vregs for them.
9062 PendingExports.clear();
9063 } else {
9064 DAG.setRoot(Result.second);
9065 }
9066
9067 if (EHPadBB) {
9068 DAG.setRoot(lowerEndEH(Chain: getRoot(), II: cast_or_null<InvokeInst>(Val: CLI.CB), EHPadBB,
9069 BeginLabel));
9070 Result.second = getRoot();
9071 }
9072
9073 return Result;
9074}
9075
9076bool SelectionDAGBuilder::canTailCall(const CallBase &CB) const {
9077 bool isMustTailCall = CB.isMustTailCall();
9078
9079 // Avoid emitting tail calls in functions with the disable-tail-calls
9080 // attribute.
9081 const Function *Caller = CB.getParent()->getParent();
9082 if (!isMustTailCall &&
9083 Caller->getFnAttribute(Kind: "disable-tail-calls").getValueAsBool())
9084 return false;
9085
9086 // We can't tail call inside a function with a swifterror argument. Lowering
9087 // does not support this yet. It would have to move into the swifterror
9088 // register before the call.
9089 if (DAG.getTargetLoweringInfo().supportSwiftError() &&
9090 Caller->getAttributes().hasAttrSomewhere(Kind: Attribute::SwiftError))
9091 return false;
9092
9093 // Check if target-independent constraints permit a tail call here.
9094 // Target-dependent constraints are checked within TLI->LowerCallTo.
9095 return isInTailCallPosition(Call: CB, TM: DAG.getTarget());
9096}
9097
9098void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
9099 bool isTailCall, bool isMustTailCall,
9100 const BasicBlock *EHPadBB,
9101 const TargetLowering::PtrAuthInfo *PAI) {
9102 auto &DL = DAG.getDataLayout();
9103 FunctionType *FTy = CB.getFunctionType();
9104 Type *RetTy = CB.getType();
9105
9106 TargetLowering::ArgListTy Args;
9107 Args.reserve(n: CB.arg_size());
9108
9109 const Value *SwiftErrorVal = nullptr;
9110 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9111
9112 if (isTailCall)
9113 isTailCall = canTailCall(CB);
9114
9115 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
9116 const Value *V = *I;
9117
9118 // Skip empty types
9119 if (V->getType()->isEmptyTy())
9120 continue;
9121
9122 SDValue ArgNode = getValue(V);
9123 TargetLowering::ArgListEntry Entry(ArgNode, V->getType());
9124 Entry.setAttributes(Call: &CB, ArgIdx: I - CB.arg_begin());
9125
9126 // Use swifterror virtual register as input to the call.
9127 if (Entry.IsSwiftError && TLI.supportSwiftError()) {
9128 SwiftErrorVal = V;
9129 // We find the virtual register for the actual swifterror argument.
9130 // Instead of using the Value, we use the virtual register instead.
9131 Entry.Node =
9132 DAG.getRegister(Reg: SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
9133 VT: EVT(TLI.getPointerTy(DL)));
9134 }
9135
9136 Args.push_back(x: Entry);
9137
9138 // If we have an explicit sret argument that is an Instruction, (i.e., it
9139 // might point to function-local memory), we can't meaningfully tail-call.
9140 if (Entry.IsSRet && isa<Instruction>(Val: V))
9141 isTailCall = false;
9142 }
9143
9144 // If call site has a cfguardtarget operand bundle, create and add an
9145 // additional ArgListEntry.
9146 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_cfguardtarget)) {
9147 Value *V = Bundle->Inputs[0];
9148 TargetLowering::ArgListEntry Entry(V, getValue(V));
9149 Entry.IsCFGuardTarget = true;
9150 Args.push_back(x: Entry);
9151 }
9152
9153 // Disable tail calls if there is an swifterror argument. Targets have not
9154 // been updated to support tail calls.
9155 if (TLI.supportSwiftError() && SwiftErrorVal)
9156 isTailCall = false;
9157
9158 ConstantInt *CFIType = nullptr;
9159 if (CB.isIndirectCall()) {
9160 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_kcfi)) {
9161 if (!TLI.supportKCFIBundles())
9162 report_fatal_error(
9163 reason: "Target doesn't support calls with kcfi operand bundles.");
9164 CFIType = cast<ConstantInt>(Val: Bundle->Inputs[0]);
9165 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
9166 }
9167 }
9168
9169 SDValue ConvControlToken;
9170 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_convergencectrl)) {
9171 auto *Token = Bundle->Inputs[0].get();
9172 ConvControlToken = getValue(V: Token);
9173 }
9174
9175 GlobalValue *DeactivationSymbol = nullptr;
9176 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_deactivation_symbol)) {
9177 DeactivationSymbol = cast<GlobalValue>(Val: Bundle->Inputs[0].get());
9178 }
9179
9180 TargetLowering::CallLoweringInfo CLI(DAG);
9181 CLI.setDebugLoc(getCurSDLoc())
9182 .setChain(getRoot())
9183 .setCallee(ResultType: RetTy, FTy, Target: Callee, ArgsList: std::move(Args), Call: CB)
9184 .setTailCall(isTailCall)
9185 .setConvergent(CB.isConvergent())
9186 .setIsPreallocated(
9187 CB.countOperandBundlesOfType(ID: LLVMContext::OB_preallocated) != 0)
9188 .setCFIType(CFIType)
9189 .setConvergenceControlToken(ConvControlToken)
9190 .setDeactivationSymbol(DeactivationSymbol);
9191
9192 // Set the pointer authentication info if we have it.
9193 if (PAI) {
9194 if (!TLI.supportPtrAuthBundles())
9195 report_fatal_error(
9196 reason: "This target doesn't support calls with ptrauth operand bundles.");
9197 CLI.setPtrAuth(*PAI);
9198 }
9199
9200 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9201
9202 if (Result.first.getNode()) {
9203 Result.first = lowerRangeToAssertZExt(DAG, I: CB, Op: Result.first);
9204 Result.first = lowerNoFPClassToAssertNoFPClass(DAG, I: CB, Op: Result.first);
9205 setValue(V: &CB, NewN: Result.first);
9206 }
9207
9208 // The last element of CLI.InVals has the SDValue for swifterror return.
9209 // Here we copy it to a virtual register and update SwiftErrorMap for
9210 // book-keeping.
9211 if (SwiftErrorVal && TLI.supportSwiftError()) {
9212 // Get the last element of InVals.
9213 SDValue Src = CLI.InVals.back();
9214 Register VReg =
9215 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
9216 SDValue CopyNode = CLI.DAG.getCopyToReg(Chain: Result.second, dl: CLI.DL, Reg: VReg, N: Src);
9217 DAG.setRoot(CopyNode);
9218 }
9219}
9220
9221static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
9222 SelectionDAGBuilder &Builder) {
9223 // Check to see if this load can be trivially constant folded, e.g. if the
9224 // input is from a string literal.
9225 if (const Constant *LoadInput = dyn_cast<Constant>(Val: PtrVal)) {
9226 // Cast pointer to the type we really want to load.
9227 Type *LoadTy =
9228 Type::getIntNTy(C&: PtrVal->getContext(), N: LoadVT.getScalarSizeInBits());
9229 if (LoadVT.isVector())
9230 LoadTy = FixedVectorType::get(ElementType: LoadTy, NumElts: LoadVT.getVectorNumElements());
9231 if (const Constant *LoadCst =
9232 ConstantFoldLoadFromConstPtr(C: const_cast<Constant *>(LoadInput),
9233 Ty: LoadTy, DL: Builder.DAG.getDataLayout()))
9234 return Builder.getValue(V: LoadCst);
9235 }
9236
9237 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
9238 // still constant memory, the input chain can be the entry node.
9239 SDValue Root;
9240 bool ConstantMemory = false;
9241
9242 // Do not serialize (non-volatile) loads of constant memory with anything.
9243 if (Builder.BatchAA && Builder.BatchAA->pointsToConstantMemory(P: PtrVal)) {
9244 Root = Builder.DAG.getEntryNode();
9245 ConstantMemory = true;
9246 } else {
9247 // Do not serialize non-volatile loads against each other.
9248 Root = Builder.DAG.getRoot();
9249 }
9250
9251 SDValue Ptr = Builder.getValue(V: PtrVal);
9252 SDValue LoadVal =
9253 Builder.DAG.getLoad(VT: LoadVT, dl: Builder.getCurSDLoc(), Chain: Root, Ptr,
9254 PtrInfo: MachinePointerInfo(PtrVal), Alignment: Align(1));
9255
9256 if (!ConstantMemory)
9257 Builder.PendingLoads.push_back(Elt: LoadVal.getValue(R: 1));
9258 return LoadVal;
9259}
9260
9261/// Record the value for an instruction that produces an integer result,
9262/// converting the type where necessary.
9263void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
9264 SDValue Value,
9265 bool IsSigned) {
9266 EVT VT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
9267 Ty: I.getType(), AllowUnknown: true);
9268 Value = DAG.getExtOrTrunc(IsSigned, Op: Value, DL: getCurSDLoc(), VT);
9269 setValue(V: &I, NewN: Value);
9270}
9271
9272/// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
9273/// true and lower it. Otherwise return false, and it will be lowered like a
9274/// normal call.
9275/// The caller already checked that \p I calls the appropriate LibFunc with a
9276/// correct prototype.
9277bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
9278 const Value *LHS = I.getArgOperand(i: 0), *RHS = I.getArgOperand(i: 1);
9279 const Value *Size = I.getArgOperand(i: 2);
9280 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(Val: getValue(V: Size));
9281 if (CSize && CSize->getZExtValue() == 0) {
9282 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DL: DAG.getDataLayout(),
9283 Ty: I.getType(), AllowUnknown: true);
9284 setValue(V: &I, NewN: DAG.getConstant(Val: 0, DL: getCurSDLoc(), VT: CallVT));
9285 return true;
9286 }
9287
9288 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9289 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9290 DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(), Op1: getValue(V: LHS), Op2: getValue(V: RHS),
9291 Op3: getValue(V: Size), CI: &I);
9292 if (Res.first.getNode()) {
9293 processIntegerCallValue(I, Value: Res.first, IsSigned: true);
9294 PendingLoads.push_back(Elt: Res.second);
9295 return true;
9296 }
9297
9298 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
9299 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
9300 if (!CSize || !isOnlyUsedInZeroEqualityComparison(CxtI: &I))
9301 return false;
9302
9303 // If the target has a fast compare for the given size, it will return a
9304 // preferred load type for that size. Require that the load VT is legal and
9305 // that the target supports unaligned loads of that type. Otherwise, return
9306 // INVALID.
9307 auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9308 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9309 MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9310 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9311 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9312 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9313 // TODO: Check alignment of src and dest ptrs.
9314 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9315 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9316 if (!TLI.isTypeLegal(VT: LVT) ||
9317 !TLI.allowsMisalignedMemoryAccesses(LVT, AddrSpace: SrcAS) ||
9318 !TLI.allowsMisalignedMemoryAccesses(LVT, AddrSpace: DstAS))
9319 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
9320 }
9321
9322 return LVT;
9323 };
9324
9325 // This turns into unaligned loads. We only do this if the target natively
9326 // supports the MVT we'll be loading or if it is small enough (<= 4) that
9327 // we'll only produce a small number of byte loads.
9328 MVT LoadVT;
9329 unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9330 switch (NumBitsToCompare) {
9331 default:
9332 return false;
9333 case 16:
9334 LoadVT = MVT::i16;
9335 break;
9336 case 32:
9337 LoadVT = MVT::i32;
9338 break;
9339 case 64:
9340 case 128:
9341 case 256:
9342 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9343 break;
9344 }
9345
9346 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9347 return false;
9348
9349 SDValue LoadL = getMemCmpLoad(PtrVal: LHS, LoadVT, Builder&: *this);
9350 SDValue LoadR = getMemCmpLoad(PtrVal: RHS, LoadVT, Builder&: *this);
9351
9352 // Bitcast to a wide integer type if the loads are vectors.
9353 if (LoadVT.isVector()) {
9354 EVT CmpVT = EVT::getIntegerVT(Context&: LHS->getContext(), BitWidth: LoadVT.getSizeInBits());
9355 LoadL = DAG.getBitcast(VT: CmpVT, V: LoadL);
9356 LoadR = DAG.getBitcast(VT: CmpVT, V: LoadR);
9357 }
9358
9359 SDValue Cmp = DAG.getSetCC(DL: getCurSDLoc(), VT: MVT::i1, LHS: LoadL, RHS: LoadR, Cond: ISD::SETNE);
9360 processIntegerCallValue(I, Value: Cmp, IsSigned: false);
9361 return true;
9362}
9363
9364/// See if we can lower a memchr call into an optimized form. If so, return
9365/// true and lower it. Otherwise return false, and it will be lowered like a
9366/// normal call.
9367/// The caller already checked that \p I calls the appropriate LibFunc with a
9368/// correct prototype.
9369bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9370 const Value *Src = I.getArgOperand(i: 0);
9371 const Value *Char = I.getArgOperand(i: 1);
9372 const Value *Length = I.getArgOperand(i: 2);
9373
9374 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9375 std::pair<SDValue, SDValue> Res =
9376 TSI.EmitTargetCodeForMemchr(DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(),
9377 Src: getValue(V: Src), Char: getValue(V: Char), Length: getValue(V: Length),
9378 SrcPtrInfo: MachinePointerInfo(Src));
9379 if (Res.first.getNode()) {
9380 setValue(V: &I, NewN: Res.first);
9381 PendingLoads.push_back(Elt: Res.second);
9382 return true;
9383 }
9384
9385 return false;
9386}
9387
9388/// See if we can lower a mempcpy call into an optimized form. If so, return
9389/// true and lower it. Otherwise return false, and it will be lowered like a
9390/// normal call.
9391/// The caller already checked that \p I calls the appropriate LibFunc with a
9392/// correct prototype.
9393bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9394 SDValue Dst = getValue(V: I.getArgOperand(i: 0));
9395 SDValue Src = getValue(V: I.getArgOperand(i: 1));
9396 SDValue Size = getValue(V: I.getArgOperand(i: 2));
9397
9398 Align DstAlign = DAG.InferPtrAlign(Ptr: Dst).valueOrOne();
9399 Align SrcAlign = DAG.InferPtrAlign(Ptr: Src).valueOrOne();
9400 // DAG::getMemcpy needs Alignment to be defined.
9401 Align Alignment = std::min(a: DstAlign, b: SrcAlign);
9402
9403 SDLoc sdl = getCurSDLoc();
9404
9405 // In the mempcpy context we need to pass in a false value for isTailCall
9406 // because the return pointer needs to be adjusted by the size of
9407 // the copied memory.
9408 SDValue Root = getMemoryRoot();
9409 SDValue MC = DAG.getMemcpy(
9410 Chain: Root, dl: sdl, Dst, Src, Size, Alignment, isVol: false, AlwaysInline: false, /*CI=*/nullptr,
9411 OverrideTailCall: std::nullopt, DstPtrInfo: MachinePointerInfo(I.getArgOperand(i: 0)),
9412 SrcPtrInfo: MachinePointerInfo(I.getArgOperand(i: 1)), AAInfo: I.getAAMetadata());
9413 assert(MC.getNode() != nullptr &&
9414 "** memcpy should not be lowered as TailCall in mempcpy context **");
9415 DAG.setRoot(MC);
9416
9417 // Check if Size needs to be truncated or extended.
9418 Size = DAG.getSExtOrTrunc(Op: Size, DL: sdl, VT: Dst.getValueType());
9419
9420 // Adjust return pointer to point just past the last dst byte.
9421 SDValue DstPlusSize = DAG.getMemBasePlusOffset(Base: Dst, Offset: Size, DL: sdl);
9422 setValue(V: &I, NewN: DstPlusSize);
9423 return true;
9424}
9425
9426/// See if we can lower a strcpy call into an optimized form. If so, return
9427/// true and lower it, otherwise return false and it will be lowered like a
9428/// normal call.
9429/// The caller already checked that \p I calls the appropriate LibFunc with a
9430/// correct prototype.
9431bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9432 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9433
9434 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9435 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcpy(
9436 DAG, DL: getCurSDLoc(), Chain: getRoot(), Dest: getValue(V: Arg0), Src: getValue(V: Arg1),
9437 DestPtrInfo: MachinePointerInfo(Arg0), SrcPtrInfo: MachinePointerInfo(Arg1), isStpcpy, CI: &I);
9438 if (Res.first.getNode()) {
9439 setValue(V: &I, NewN: Res.first);
9440 DAG.setRoot(Res.second);
9441 return true;
9442 }
9443
9444 return false;
9445}
9446
9447/// See if we can lower a strcmp call into an optimized form. If so, return
9448/// true and lower it, otherwise return false and it will be lowered like a
9449/// normal call.
9450/// The caller already checked that \p I calls the appropriate LibFunc with a
9451/// correct prototype.
9452bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9453 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9454
9455 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9456 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcmp(
9457 DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(), Op1: getValue(V: Arg0), Op2: getValue(V: Arg1),
9458 Op1PtrInfo: MachinePointerInfo(Arg0), Op2PtrInfo: MachinePointerInfo(Arg1), CI: &I);
9459 if (Res.first.getNode()) {
9460 processIntegerCallValue(I, Value: Res.first, IsSigned: true);
9461 PendingLoads.push_back(Elt: Res.second);
9462 return true;
9463 }
9464
9465 return false;
9466}
9467
9468/// See if we can lower a strlen call into an optimized form. If so, return
9469/// true and lower it, otherwise return false and it will be lowered like a
9470/// normal call.
9471/// The caller already checked that \p I calls the appropriate LibFunc with a
9472/// correct prototype.
9473bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9474 const Value *Arg0 = I.getArgOperand(i: 0);
9475
9476 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9477 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrlen(
9478 DAG, DL: getCurSDLoc(), Chain: DAG.getRoot(), Src: getValue(V: Arg0), CI: &I);
9479 if (Res.first.getNode()) {
9480 processIntegerCallValue(I, Value: Res.first, IsSigned: false);
9481 PendingLoads.push_back(Elt: Res.second);
9482 return true;
9483 }
9484
9485 return false;
9486}
9487
9488/// See if we can lower a strnlen call into an optimized form. If so, return
9489/// true and lower it, otherwise return false and it will be lowered like a
9490/// normal call.
9491/// The caller already checked that \p I calls the appropriate LibFunc with a
9492/// correct prototype.
9493bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9494 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9495
9496 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9497 std::pair<SDValue, SDValue> Res =
9498 TSI.EmitTargetCodeForStrnlen(DAG, DL: getCurSDLoc(), Chain: DAG.getRoot(),
9499 Src: getValue(V: Arg0), MaxLength: getValue(V: Arg1),
9500 SrcPtrInfo: MachinePointerInfo(Arg0));
9501 if (Res.first.getNode()) {
9502 processIntegerCallValue(I, Value: Res.first, IsSigned: false);
9503 PendingLoads.push_back(Elt: Res.second);
9504 return true;
9505 }
9506
9507 return false;
9508}
9509
9510/// See if we can lower a Strstr call into an optimized form. If so, return
9511/// true and lower it, otherwise return false and it will be lowered like a
9512/// normal call.
9513/// The caller already checked that \p I calls the appropriate LibFunc with a
9514/// correct prototype.
9515bool SelectionDAGBuilder::visitStrstrCall(const CallInst &I) {
9516 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9517 const Value *Arg0 = I.getArgOperand(i: 0), *Arg1 = I.getArgOperand(i: 1);
9518 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrstr(
9519 DAG, dl: getCurSDLoc(), Chain: DAG.getRoot(), Op1: getValue(V: Arg0), Op2: getValue(V: Arg1), CI: &I);
9520 if (Res.first) {
9521 processIntegerCallValue(I, Value: Res.first, IsSigned: false);
9522 PendingLoads.push_back(Elt: Res.second);
9523 return true;
9524 }
9525 return false;
9526}
9527
9528/// See if we can lower a unary floating-point operation into an SDNode with
9529/// the specified Opcode. If so, return true and lower it, otherwise return
9530/// false and it will be lowered like a normal call.
9531/// The caller already checked that \p I calls the appropriate LibFunc with a
9532/// correct prototype.
9533bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9534 unsigned Opcode) {
9535 // We already checked this call's prototype; verify it doesn't modify errno.
9536 // Do not perform optimizations for call sites that require strict
9537 // floating-point semantics.
9538 if (!I.onlyReadsMemory() || I.isStrictFP())
9539 return false;
9540
9541 SDNodeFlags Flags;
9542 Flags.copyFMF(FPMO: cast<FPMathOperator>(Val: I));
9543
9544 SDValue Tmp = getValue(V: I.getArgOperand(i: 0));
9545 setValue(V: &I,
9546 NewN: DAG.getNode(Opcode, DL: getCurSDLoc(), VT: Tmp.getValueType(), Operand: Tmp, Flags));
9547 return true;
9548}
9549
9550/// See if we can lower a binary floating-point operation into an SDNode with
9551/// the specified Opcode. If so, return true and lower it. Otherwise return
9552/// false, and it will be lowered like a normal call.
9553/// The caller already checked that \p I calls the appropriate LibFunc with a
9554/// correct prototype.
9555bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9556 unsigned Opcode) {
9557 // We already checked this call's prototype; verify it doesn't modify errno.
9558 // Do not perform optimizations for call sites that require strict
9559 // floating-point semantics.
9560 if (!I.onlyReadsMemory() || I.isStrictFP())
9561 return false;
9562
9563 SDNodeFlags Flags;
9564 Flags.copyFMF(FPMO: cast<FPMathOperator>(Val: I));
9565
9566 SDValue Tmp0 = getValue(V: I.getArgOperand(i: 0));
9567 SDValue Tmp1 = getValue(V: I.getArgOperand(i: 1));
9568 EVT VT = Tmp0.getValueType();
9569 setValue(V: &I, NewN: DAG.getNode(Opcode, DL: getCurSDLoc(), VT, N1: Tmp0, N2: Tmp1, Flags));
9570 return true;
9571}
9572
9573void SelectionDAGBuilder::visitCall(const CallInst &I) {
9574 // Handle inline assembly differently.
9575 if (I.isInlineAsm()) {
9576 visitInlineAsm(Call: I);
9577 return;
9578 }
9579
9580 diagnoseDontCall(CI: I);
9581
9582 if (Function *F = I.getCalledFunction()) {
9583 if (F->isDeclaration()) {
9584 // Is this an LLVM intrinsic?
9585 if (unsigned IID = F->getIntrinsicID()) {
9586 visitIntrinsicCall(I, Intrinsic: IID);
9587 return;
9588 }
9589 }
9590
9591 // Check for well-known libc/libm calls. If the function is internal, it
9592 // can't be a library call. Don't do the check if marked as nobuiltin for
9593 // some reason.
9594 // This code should not handle libcalls that are already canonicalized to
9595 // intrinsics by the middle-end.
9596 LibFunc Func;
9597 if (!I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName() &&
9598 LibInfo->getLibFunc(FDecl: *F, F&: Func) && LibInfo->hasOptimizedCodeGen(F: Func)) {
9599 switch (Func) {
9600 default: break;
9601 case LibFunc_bcmp:
9602 if (visitMemCmpBCmpCall(I))
9603 return;
9604 break;
9605 case LibFunc_copysign:
9606 case LibFunc_copysignf:
9607 case LibFunc_copysignl:
9608 // We already checked this call's prototype; verify it doesn't modify
9609 // errno.
9610 if (I.onlyReadsMemory()) {
9611 SDValue LHS = getValue(V: I.getArgOperand(i: 0));
9612 SDValue RHS = getValue(V: I.getArgOperand(i: 1));
9613 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::FCOPYSIGN, DL: getCurSDLoc(),
9614 VT: LHS.getValueType(), N1: LHS, N2: RHS));
9615 return;
9616 }
9617 break;
9618 case LibFunc_sin:
9619 case LibFunc_sinf:
9620 case LibFunc_sinl:
9621 if (visitUnaryFloatCall(I, Opcode: ISD::FSIN))
9622 return;
9623 break;
9624 case LibFunc_cos:
9625 case LibFunc_cosf:
9626 case LibFunc_cosl:
9627 if (visitUnaryFloatCall(I, Opcode: ISD::FCOS))
9628 return;
9629 break;
9630 case LibFunc_tan:
9631 case LibFunc_tanf:
9632 case LibFunc_tanl:
9633 if (visitUnaryFloatCall(I, Opcode: ISD::FTAN))
9634 return;
9635 break;
9636 case LibFunc_asin:
9637 case LibFunc_asinf:
9638 case LibFunc_asinl:
9639 if (visitUnaryFloatCall(I, Opcode: ISD::FASIN))
9640 return;
9641 break;
9642 case LibFunc_acos:
9643 case LibFunc_acosf:
9644 case LibFunc_acosl:
9645 if (visitUnaryFloatCall(I, Opcode: ISD::FACOS))
9646 return;
9647 break;
9648 case LibFunc_atan:
9649 case LibFunc_atanf:
9650 case LibFunc_atanl:
9651 if (visitUnaryFloatCall(I, Opcode: ISD::FATAN))
9652 return;
9653 break;
9654 case LibFunc_atan2:
9655 case LibFunc_atan2f:
9656 case LibFunc_atan2l:
9657 if (visitBinaryFloatCall(I, Opcode: ISD::FATAN2))
9658 return;
9659 break;
9660 case LibFunc_sinh:
9661 case LibFunc_sinhf:
9662 case LibFunc_sinhl:
9663 if (visitUnaryFloatCall(I, Opcode: ISD::FSINH))
9664 return;
9665 break;
9666 case LibFunc_cosh:
9667 case LibFunc_coshf:
9668 case LibFunc_coshl:
9669 if (visitUnaryFloatCall(I, Opcode: ISD::FCOSH))
9670 return;
9671 break;
9672 case LibFunc_tanh:
9673 case LibFunc_tanhf:
9674 case LibFunc_tanhl:
9675 if (visitUnaryFloatCall(I, Opcode: ISD::FTANH))
9676 return;
9677 break;
9678 case LibFunc_sqrt:
9679 case LibFunc_sqrtf:
9680 case LibFunc_sqrtl:
9681 case LibFunc_sqrt_finite:
9682 case LibFunc_sqrtf_finite:
9683 case LibFunc_sqrtl_finite:
9684 if (visitUnaryFloatCall(I, Opcode: ISD::FSQRT))
9685 return;
9686 break;
9687 case LibFunc_log2:
9688 case LibFunc_log2f:
9689 case LibFunc_log2l:
9690 if (visitUnaryFloatCall(I, Opcode: ISD::FLOG2))
9691 return;
9692 break;
9693 case LibFunc_exp2:
9694 case LibFunc_exp2f:
9695 case LibFunc_exp2l:
9696 if (visitUnaryFloatCall(I, Opcode: ISD::FEXP2))
9697 return;
9698 break;
9699 case LibFunc_exp10:
9700 case LibFunc_exp10f:
9701 case LibFunc_exp10l:
9702 if (visitUnaryFloatCall(I, Opcode: ISD::FEXP10))
9703 return;
9704 break;
9705 case LibFunc_ldexp:
9706 case LibFunc_ldexpf:
9707 case LibFunc_ldexpl:
9708 if (visitBinaryFloatCall(I, Opcode: ISD::FLDEXP))
9709 return;
9710 break;
9711 case LibFunc_strstr:
9712 if (visitStrstrCall(I))
9713 return;
9714 break;
9715 case LibFunc_memcmp:
9716 if (visitMemCmpBCmpCall(I))
9717 return;
9718 break;
9719 case LibFunc_mempcpy:
9720 if (visitMemPCpyCall(I))
9721 return;
9722 break;
9723 case LibFunc_memchr:
9724 if (visitMemChrCall(I))
9725 return;
9726 break;
9727 case LibFunc_strcpy:
9728 if (visitStrCpyCall(I, isStpcpy: false))
9729 return;
9730 break;
9731 case LibFunc_stpcpy:
9732 if (visitStrCpyCall(I, isStpcpy: true))
9733 return;
9734 break;
9735 case LibFunc_strcmp:
9736 if (visitStrCmpCall(I))
9737 return;
9738 break;
9739 case LibFunc_strlen:
9740 if (visitStrLenCall(I))
9741 return;
9742 break;
9743 case LibFunc_strnlen:
9744 if (visitStrNLenCall(I))
9745 return;
9746 break;
9747 }
9748 }
9749 }
9750
9751 if (I.countOperandBundlesOfType(ID: LLVMContext::OB_ptrauth)) {
9752 LowerCallSiteWithPtrAuthBundle(CB: cast<CallBase>(Val: I), /*EHPadBB=*/nullptr);
9753 return;
9754 }
9755
9756 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9757 // have to do anything here to lower funclet bundles.
9758 // CFGuardTarget bundles are lowered in LowerCallTo.
9759 failForInvalidBundles(
9760 I, Name: "calls",
9761 AllowedBundles: {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9762 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9763 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9764 LLVMContext::OB_convergencectrl, LLVMContext::OB_deactivation_symbol});
9765
9766 SDValue Callee = getValue(V: I.getCalledOperand());
9767
9768 if (I.hasDeoptState())
9769 LowerCallSiteWithDeoptBundle(Call: &I, Callee, EHPadBB: nullptr);
9770 else
9771 // Check if we can potentially perform a tail call. More detailed checking
9772 // is be done within LowerCallTo, after more information about the call is
9773 // known.
9774 LowerCallTo(CB: I, Callee, isTailCall: I.isTailCall(), isMustTailCall: I.isMustTailCall());
9775}
9776
9777void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9778 const CallBase &CB, const BasicBlock *EHPadBB) {
9779 auto PAB = CB.getOperandBundle(Name: "ptrauth");
9780 const Value *CalleeV = CB.getCalledOperand();
9781
9782 // Gather the call ptrauth data from the operand bundle:
9783 // [ i32 <key>, i64 <discriminator> ]
9784 const auto *Key = cast<ConstantInt>(Val: PAB->Inputs[0]);
9785 const Value *Discriminator = PAB->Inputs[1];
9786
9787 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9788 assert(Discriminator->getType()->isIntegerTy(64) &&
9789 "Invalid ptrauth discriminator");
9790
9791 // Look through ptrauth constants to find the raw callee.
9792 // Do a direct unauthenticated call if we found it and everything matches.
9793 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(Val: CalleeV))
9794 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9795 DL: DAG.getDataLayout()))
9796 return LowerCallTo(CB, Callee: getValue(V: CalleeCPA->getPointer()), isTailCall: CB.isTailCall(),
9797 isMustTailCall: CB.isMustTailCall(), EHPadBB);
9798
9799 // Functions should never be ptrauth-called directly.
9800 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9801
9802 // Otherwise, do an authenticated indirect call.
9803 TargetLowering::PtrAuthInfo PAI = {.Key: Key->getZExtValue(),
9804 .Discriminator: getValue(V: Discriminator)};
9805
9806 LowerCallTo(CB, Callee: getValue(V: CalleeV), isTailCall: CB.isTailCall(), isMustTailCall: CB.isMustTailCall(),
9807 EHPadBB, PAI: &PAI);
9808}
9809
9810namespace {
9811
9812/// AsmOperandInfo - This contains information for each constraint that we are
9813/// lowering.
9814class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9815public:
9816 /// CallOperand - If this is the result output operand or a clobber
9817 /// this is null, otherwise it is the incoming operand to the CallInst.
9818 /// This gets modified as the asm is processed.
9819 SDValue CallOperand;
9820
9821 /// AssignedRegs - If this is a register or register class operand, this
9822 /// contains the set of register corresponding to the operand.
9823 RegsForValue AssignedRegs;
9824
9825 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9826 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9827 }
9828
9829 /// Whether or not this operand accesses memory
9830 bool hasMemory(const TargetLowering &TLI) const {
9831 // Indirect operand accesses access memory.
9832 if (isIndirect)
9833 return true;
9834
9835 for (const auto &Code : Codes)
9836 if (TLI.getConstraintType(Constraint: Code) == TargetLowering::C_Memory)
9837 return true;
9838
9839 return false;
9840 }
9841};
9842
9843
9844} // end anonymous namespace
9845
9846/// Make sure that the output operand \p OpInfo and its corresponding input
9847/// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9848/// out).
9849static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9850 SDISelAsmOperandInfo &MatchingOpInfo,
9851 SelectionDAG &DAG) {
9852 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9853 return;
9854
9855 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9856 const auto &TLI = DAG.getTargetLoweringInfo();
9857
9858 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9859 TLI.getRegForInlineAsmConstraint(TRI, Constraint: OpInfo.ConstraintCode,
9860 VT: OpInfo.ConstraintVT);
9861 std::pair<unsigned, const TargetRegisterClass *> InputRC =
9862 TLI.getRegForInlineAsmConstraint(TRI, Constraint: MatchingOpInfo.ConstraintCode,
9863 VT: MatchingOpInfo.ConstraintVT);
9864 const bool OutOpIsIntOrFP =
9865 OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
9866 const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
9867 MatchingOpInfo.ConstraintVT.isFloatingPoint();
9868 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
9869 // FIXME: error out in a more elegant fashion
9870 report_fatal_error(reason: "Unsupported asm: input constraint"
9871 " with a matching output constraint of"
9872 " incompatible type!");
9873 }
9874 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9875}
9876
9877/// Get a direct memory input to behave well as an indirect operand.
9878/// This may introduce stores, hence the need for a \p Chain.
9879/// \return The (possibly updated) chain.
9880static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9881 SDISelAsmOperandInfo &OpInfo,
9882 SelectionDAG &DAG) {
9883 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9884
9885 // If we don't have an indirect input, put it in the constpool if we can,
9886 // otherwise spill it to a stack slot.
9887 // TODO: This isn't quite right. We need to handle these according to
9888 // the addressing mode that the constraint wants. Also, this may take
9889 // an additional register for the computation and we don't want that
9890 // either.
9891
9892 // If the operand is a float, integer, or vector constant, spill to a
9893 // constant pool entry to get its address.
9894 const Value *OpVal = OpInfo.CallOperandVal;
9895 if (isa<ConstantFP>(Val: OpVal) || isa<ConstantInt>(Val: OpVal) ||
9896 isa<ConstantVector>(Val: OpVal) || isa<ConstantDataVector>(Val: OpVal)) {
9897 OpInfo.CallOperand = DAG.getConstantPool(
9898 C: cast<Constant>(Val: OpVal), VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
9899 return Chain;
9900 }
9901
9902 // Otherwise, create a stack slot and emit a store to it before the asm.
9903 Type *Ty = OpVal->getType();
9904 auto &DL = DAG.getDataLayout();
9905 TypeSize TySize = DL.getTypeAllocSize(Ty);
9906 MachineFunction &MF = DAG.getMachineFunction();
9907 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
9908 int StackID = 0;
9909 if (TySize.isScalable())
9910 StackID = TFI->getStackIDForScalableVectors();
9911 int SSFI = MF.getFrameInfo().CreateStackObject(Size: TySize.getKnownMinValue(),
9912 Alignment: DL.getPrefTypeAlign(Ty), isSpillSlot: false,
9913 Alloca: nullptr, ID: StackID);
9914 SDValue StackSlot = DAG.getFrameIndex(FI: SSFI, VT: TLI.getFrameIndexTy(DL));
9915 Chain = DAG.getTruncStore(Chain, dl: Location, Val: OpInfo.CallOperand, Ptr: StackSlot,
9916 PtrInfo: MachinePointerInfo::getFixedStack(MF, FI: SSFI),
9917 SVT: TLI.getMemValueType(DL, Ty));
9918 OpInfo.CallOperand = StackSlot;
9919
9920 return Chain;
9921}
9922
9923/// GetRegistersForValue - Assign registers (virtual or physical) for the
9924/// specified operand. We prefer to assign virtual registers, to allow the
9925/// register allocator to handle the assignment process. However, if the asm
9926/// uses features that we can't model on machineinstrs, we have SDISel do the
9927/// allocation. This produces generally horrible, but correct, code.
9928///
9929/// OpInfo describes the operand
9930/// RefOpInfo describes the matching operand if any, the operand otherwise
9931static std::optional<unsigned>
9932getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9933 SDISelAsmOperandInfo &OpInfo,
9934 SDISelAsmOperandInfo &RefOpInfo) {
9935 LLVMContext &Context = *DAG.getContext();
9936 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9937
9938 MachineFunction &MF = DAG.getMachineFunction();
9939 SmallVector<Register, 4> Regs;
9940 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9941
9942 // No work to do for memory/address operands.
9943 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9944 OpInfo.ConstraintType == TargetLowering::C_Address)
9945 return std::nullopt;
9946
9947 // If this is a constraint for a single physreg, or a constraint for a
9948 // register class, find it.
9949 unsigned AssignedReg;
9950 const TargetRegisterClass *RC;
9951 std::tie(args&: AssignedReg, args&: RC) = TLI.getRegForInlineAsmConstraint(
9952 TRI: &TRI, Constraint: RefOpInfo.ConstraintCode, VT: RefOpInfo.ConstraintVT);
9953 // RC is unset only on failure. Return immediately.
9954 if (!RC)
9955 return std::nullopt;
9956
9957 // Get the actual register value type. This is important, because the user
9958 // may have asked for (e.g.) the AX register in i32 type. We need to
9959 // remember that AX is actually i16 to get the right extension.
9960 const MVT RegVT = *TRI.legalclasstypes_begin(RC: *RC);
9961
9962 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9963 // If this is an FP operand in an integer register (or visa versa), or more
9964 // generally if the operand value disagrees with the register class we plan
9965 // to stick it in, fix the operand type.
9966 //
9967 // If this is an input value, the bitcast to the new type is done now.
9968 // Bitcast for output value is done at the end of visitInlineAsm().
9969 if ((OpInfo.Type == InlineAsm::isOutput ||
9970 OpInfo.Type == InlineAsm::isInput) &&
9971 !TRI.isTypeLegalForClass(RC: *RC, T: OpInfo.ConstraintVT)) {
9972 // Try to convert to the first EVT that the reg class contains. If the
9973 // types are identical size, use a bitcast to convert (e.g. two differing
9974 // vector types). Note: output bitcast is done at the end of
9975 // visitInlineAsm().
9976 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9977 // Exclude indirect inputs while they are unsupported because the code
9978 // to perform the load is missing and thus OpInfo.CallOperand still
9979 // refers to the input address rather than the pointed-to value.
9980 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9981 OpInfo.CallOperand =
9982 DAG.getNode(Opcode: ISD::BITCAST, DL, VT: RegVT, Operand: OpInfo.CallOperand);
9983 OpInfo.ConstraintVT = RegVT;
9984 // If the operand is an FP value and we want it in integer registers,
9985 // use the corresponding integer type. This turns an f64 value into
9986 // i64, which can be passed with two i32 values on a 32-bit machine.
9987 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9988 MVT VT = MVT::getIntegerVT(BitWidth: OpInfo.ConstraintVT.getSizeInBits());
9989 if (OpInfo.Type == InlineAsm::isInput)
9990 OpInfo.CallOperand =
9991 DAG.getNode(Opcode: ISD::BITCAST, DL, VT, Operand: OpInfo.CallOperand);
9992 OpInfo.ConstraintVT = VT;
9993 }
9994 }
9995 }
9996
9997 // No need to allocate a matching input constraint since the constraint it's
9998 // matching to has already been allocated.
9999 if (OpInfo.isMatchingInputConstraint())
10000 return std::nullopt;
10001
10002 EVT ValueVT = OpInfo.ConstraintVT;
10003 if (OpInfo.ConstraintVT == MVT::Other)
10004 ValueVT = RegVT;
10005
10006 // Initialize NumRegs.
10007 unsigned NumRegs = 1;
10008 if (OpInfo.ConstraintVT != MVT::Other)
10009 NumRegs = TLI.getNumRegisters(Context, VT: OpInfo.ConstraintVT, RegisterVT: RegVT);
10010
10011 // If this is a constraint for a specific physical register, like {r17},
10012 // assign it now.
10013
10014 // If this associated to a specific register, initialize iterator to correct
10015 // place. If virtual, make sure we have enough registers
10016
10017 // Initialize iterator if necessary
10018 TargetRegisterClass::iterator I = RC->begin();
10019 MachineRegisterInfo &RegInfo = MF.getRegInfo();
10020
10021 // Do not check for single registers.
10022 if (AssignedReg) {
10023 I = std::find(first: I, last: RC->end(), val: AssignedReg);
10024 if (I == RC->end()) {
10025 // RC does not contain the selected register, which indicates a
10026 // mismatch between the register and the required type/bitwidth.
10027 return {AssignedReg};
10028 }
10029 }
10030
10031 for (; NumRegs; --NumRegs, ++I) {
10032 assert(I != RC->end() && "Ran out of registers to allocate!");
10033 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RegClass: RC);
10034 Regs.push_back(Elt: R);
10035 }
10036
10037 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
10038 return std::nullopt;
10039}
10040
10041static unsigned
10042findMatchingInlineAsmOperand(unsigned OperandNo,
10043 const std::vector<SDValue> &AsmNodeOperands) {
10044 // Scan until we find the definition we already emitted of this operand.
10045 unsigned CurOp = InlineAsm::Op_FirstOperand;
10046 for (; OperandNo; --OperandNo) {
10047 // Advance to the next operand.
10048 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
10049 const InlineAsm::Flag F(OpFlag);
10050 assert(
10051 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
10052 "Skipped past definitions?");
10053 CurOp += F.getNumOperandRegisters() + 1;
10054 }
10055 return CurOp;
10056}
10057
10058namespace {
10059
10060class ExtraFlags {
10061 unsigned Flags = 0;
10062
10063public:
10064 explicit ExtraFlags(const CallBase &Call) {
10065 const InlineAsm *IA = cast<InlineAsm>(Val: Call.getCalledOperand());
10066 if (IA->hasSideEffects())
10067 Flags |= InlineAsm::Extra_HasSideEffects;
10068 if (IA->isAlignStack())
10069 Flags |= InlineAsm::Extra_IsAlignStack;
10070 if (IA->canThrow())
10071 Flags |= InlineAsm::Extra_MayUnwind;
10072 if (Call.isConvergent())
10073 Flags |= InlineAsm::Extra_IsConvergent;
10074 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
10075 }
10076
10077 void update(const TargetLowering::AsmOperandInfo &OpInfo) {
10078 // Ideally, we would only check against memory constraints. However, the
10079 // meaning of an Other constraint can be target-specific and we can't easily
10080 // reason about it. Therefore, be conservative and set MayLoad/MayStore
10081 // for Other constraints as well.
10082 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
10083 OpInfo.ConstraintType == TargetLowering::C_Other) {
10084 if (OpInfo.Type == InlineAsm::isInput)
10085 Flags |= InlineAsm::Extra_MayLoad;
10086 else if (OpInfo.Type == InlineAsm::isOutput)
10087 Flags |= InlineAsm::Extra_MayStore;
10088 else if (OpInfo.Type == InlineAsm::isClobber)
10089 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
10090 }
10091 }
10092
10093 unsigned get() const { return Flags; }
10094};
10095
10096} // end anonymous namespace
10097
10098static bool isFunction(SDValue Op) {
10099 if (Op && Op.getOpcode() == ISD::GlobalAddress) {
10100 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Val&: Op)) {
10101 auto Fn = dyn_cast_or_null<Function>(Val: GA->getGlobal());
10102
10103 // In normal "call dllimport func" instruction (non-inlineasm) it force
10104 // indirect access by specifing call opcode. And usually specially print
10105 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
10106 // not do in this way now. (In fact, this is similar with "Data Access"
10107 // action). So here we ignore dllimport function.
10108 if (Fn && !Fn->hasDLLImportStorageClass())
10109 return true;
10110 }
10111 }
10112 return false;
10113}
10114
10115/// visitInlineAsm - Handle a call to an InlineAsm object.
10116void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
10117 const BasicBlock *EHPadBB) {
10118 const InlineAsm *IA = cast<InlineAsm>(Val: Call.getCalledOperand());
10119
10120 /// ConstraintOperands - Information about all of the constraints.
10121 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
10122
10123 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10124 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
10125 DL: DAG.getDataLayout(), TRI: DAG.getSubtarget().getRegisterInfo(), Call);
10126
10127 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
10128 // AsmDialect, MayLoad, MayStore).
10129 bool HasSideEffect = IA->hasSideEffects();
10130 ExtraFlags ExtraInfo(Call);
10131
10132 for (auto &T : TargetConstraints) {
10133 ConstraintOperands.push_back(Elt: SDISelAsmOperandInfo(T));
10134 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
10135
10136 if (OpInfo.CallOperandVal)
10137 OpInfo.CallOperand = getValue(V: OpInfo.CallOperandVal);
10138
10139 if (!HasSideEffect)
10140 HasSideEffect = OpInfo.hasMemory(TLI);
10141
10142 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
10143 // FIXME: Could we compute this on OpInfo rather than T?
10144
10145 // Compute the constraint code and ConstraintType to use.
10146 TLI.ComputeConstraintToUse(OpInfo&: T, Op: SDValue());
10147
10148 if (T.ConstraintType == TargetLowering::C_Immediate &&
10149 OpInfo.CallOperand && !isa<ConstantSDNode>(Val: OpInfo.CallOperand))
10150 // We've delayed emitting a diagnostic like the "n" constraint because
10151 // inlining could cause an integer showing up.
10152 return emitInlineAsmError(Call, Message: "constraint '" + Twine(T.ConstraintCode) +
10153 "' expects an integer constant "
10154 "expression");
10155
10156 ExtraInfo.update(OpInfo: T);
10157 }
10158
10159 // We won't need to flush pending loads if this asm doesn't touch
10160 // memory and is nonvolatile.
10161 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
10162
10163 bool EmitEHLabels = isa<InvokeInst>(Val: Call);
10164 if (EmitEHLabels) {
10165 assert(EHPadBB && "InvokeInst must have an EHPadBB");
10166 }
10167 bool IsCallBr = isa<CallBrInst>(Val: Call);
10168
10169 if (IsCallBr || EmitEHLabels) {
10170 // If this is a callbr or invoke we need to flush pending exports since
10171 // inlineasm_br and invoke are terminators.
10172 // We need to do this before nodes are glued to the inlineasm_br node.
10173 Chain = getControlRoot();
10174 }
10175
10176 MCSymbol *BeginLabel = nullptr;
10177 if (EmitEHLabels) {
10178 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
10179 }
10180
10181 int OpNo = -1;
10182 SmallVector<StringRef> AsmStrs;
10183 IA->collectAsmStrs(AsmStrs);
10184
10185 // Second pass over the constraints: compute which constraint option to use.
10186 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10187 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
10188 OpNo++;
10189
10190 // If this is an output operand with a matching input operand, look up the
10191 // matching input. If their types mismatch, e.g. one is an integer, the
10192 // other is floating point, or their sizes are different, flag it as an
10193 // error.
10194 if (OpInfo.hasMatchingInput()) {
10195 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
10196 patchMatchingInput(OpInfo, MatchingOpInfo&: Input, DAG);
10197 }
10198
10199 // Compute the constraint code and ConstraintType to use.
10200 TLI.ComputeConstraintToUse(OpInfo, Op: OpInfo.CallOperand, DAG: &DAG);
10201
10202 if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
10203 OpInfo.Type == InlineAsm::isClobber) ||
10204 OpInfo.ConstraintType == TargetLowering::C_Address)
10205 continue;
10206
10207 // In Linux PIC model, there are 4 cases about value/label addressing:
10208 //
10209 // 1: Function call or Label jmp inside the module.
10210 // 2: Data access (such as global variable, static variable) inside module.
10211 // 3: Function call or Label jmp outside the module.
10212 // 4: Data access (such as global variable) outside the module.
10213 //
10214 // Due to current llvm inline asm architecture designed to not "recognize"
10215 // the asm code, there are quite troubles for us to treat mem addressing
10216 // differently for same value/adress used in different instuctions.
10217 // For example, in pic model, call a func may in plt way or direclty
10218 // pc-related, but lea/mov a function adress may use got.
10219 //
10220 // Here we try to "recognize" function call for the case 1 and case 3 in
10221 // inline asm. And try to adjust the constraint for them.
10222 //
10223 // TODO: Due to current inline asm didn't encourage to jmp to the outsider
10224 // label, so here we don't handle jmp function label now, but we need to
10225 // enhance it (especilly in PIC model) if we meet meaningful requirements.
10226 if (OpInfo.isIndirect && isFunction(Op: OpInfo.CallOperand) &&
10227 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
10228 TM.getCodeModel() != CodeModel::Large) {
10229 OpInfo.isIndirect = false;
10230 OpInfo.ConstraintType = TargetLowering::C_Address;
10231 }
10232
10233 // If this is a memory input, and if the operand is not indirect, do what we
10234 // need to provide an address for the memory input.
10235 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
10236 !OpInfo.isIndirect) {
10237 assert((OpInfo.isMultipleAlternative ||
10238 (OpInfo.Type == InlineAsm::isInput)) &&
10239 "Can only indirectify direct input operands!");
10240
10241 // Memory operands really want the address of the value.
10242 Chain = getAddressForMemoryInput(Chain, Location: getCurSDLoc(), OpInfo, DAG);
10243
10244 // There is no longer a Value* corresponding to this operand.
10245 OpInfo.CallOperandVal = nullptr;
10246
10247 // It is now an indirect operand.
10248 OpInfo.isIndirect = true;
10249 }
10250
10251 }
10252
10253 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10254 std::vector<SDValue> AsmNodeOperands;
10255 AsmNodeOperands.push_back(x: SDValue()); // reserve space for input chain
10256 AsmNodeOperands.push_back(x: DAG.getTargetExternalSymbol(
10257 Sym: IA->getAsmString().data(), VT: TLI.getProgramPointerTy(DL: DAG.getDataLayout())));
10258
10259 // If we have a !srcloc metadata node associated with it, we want to attach
10260 // this to the ultimately generated inline asm machineinstr. To do this, we
10261 // pass in the third operand as this (potentially null) inline asm MDNode.
10262 const MDNode *SrcLoc = Call.getMetadata(Kind: "srcloc");
10263 AsmNodeOperands.push_back(x: DAG.getMDNode(MD: SrcLoc));
10264
10265 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10266 // bits as operand 3.
10267 AsmNodeOperands.push_back(x: DAG.getTargetConstant(
10268 Val: ExtraInfo.get(), DL: getCurSDLoc(), VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
10269
10270 // Third pass: Loop over operands to prepare DAG-level operands.. As part of
10271 // this, assign virtual and physical registers for inputs and otput.
10272 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10273 // Assign Registers.
10274 SDISelAsmOperandInfo &RefOpInfo =
10275 OpInfo.isMatchingInputConstraint()
10276 ? ConstraintOperands[OpInfo.getMatchedOperand()]
10277 : OpInfo;
10278 const auto RegError =
10279 getRegistersForValue(DAG, DL: getCurSDLoc(), OpInfo, RefOpInfo);
10280 if (RegError) {
10281 const MachineFunction &MF = DAG.getMachineFunction();
10282 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10283 const char *RegName = TRI.getName(RegNo: *RegError);
10284 emitInlineAsmError(Call, Message: "register '" + Twine(RegName) +
10285 "' allocated for constraint '" +
10286 Twine(OpInfo.ConstraintCode) +
10287 "' does not match required type");
10288 return;
10289 }
10290
10291 auto DetectWriteToReservedRegister = [&]() {
10292 const MachineFunction &MF = DAG.getMachineFunction();
10293 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10294 for (Register Reg : OpInfo.AssignedRegs.Regs) {
10295 if (Reg.isPhysical() && TRI.isInlineAsmReadOnlyReg(MF, PhysReg: Reg)) {
10296 const char *RegName = TRI.getName(RegNo: Reg);
10297 emitInlineAsmError(Call, Message: "write to reserved register '" +
10298 Twine(RegName) + "'");
10299 return true;
10300 }
10301 }
10302 return false;
10303 };
10304 assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10305 (OpInfo.Type == InlineAsm::isInput &&
10306 !OpInfo.isMatchingInputConstraint())) &&
10307 "Only address as input operand is allowed.");
10308
10309 switch (OpInfo.Type) {
10310 case InlineAsm::isOutput:
10311 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10312 const InlineAsm::ConstraintCode ConstraintID =
10313 TLI.getInlineAsmMemConstraint(ConstraintCode: OpInfo.ConstraintCode);
10314 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10315 "Failed to convert memory constraint code to constraint id.");
10316
10317 // Add information to the INLINEASM node to know about this output.
10318 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
10319 OpFlags.setMemConstraint(ConstraintID);
10320 AsmNodeOperands.push_back(x: DAG.getTargetConstant(Val: OpFlags, DL: getCurSDLoc(),
10321 VT: MVT::i32));
10322 AsmNodeOperands.push_back(x: OpInfo.CallOperand);
10323 } else {
10324 // Otherwise, this outputs to a register (directly for C_Register /
10325 // C_RegisterClass, and a target-defined fashion for
10326 // C_Immediate/C_Other). Find a register that we can use.
10327 if (OpInfo.AssignedRegs.Regs.empty()) {
10328 emitInlineAsmError(
10329 Call, Message: "couldn't allocate output register for constraint '" +
10330 Twine(OpInfo.ConstraintCode) + "'");
10331 return;
10332 }
10333
10334 if (DetectWriteToReservedRegister())
10335 return;
10336
10337 // Add information to the INLINEASM node to know that this register is
10338 // set.
10339 OpInfo.AssignedRegs.AddInlineAsmOperands(
10340 Code: OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10341 : InlineAsm::Kind::RegDef,
10342 HasMatching: false, MatchingIdx: 0, dl: getCurSDLoc(), DAG, Ops&: AsmNodeOperands);
10343 }
10344 break;
10345
10346 case InlineAsm::isInput:
10347 case InlineAsm::isLabel: {
10348 SDValue InOperandVal = OpInfo.CallOperand;
10349
10350 if (OpInfo.isMatchingInputConstraint()) {
10351 // If this is required to match an output register we have already set,
10352 // just use its register.
10353 auto CurOp = findMatchingInlineAsmOperand(OperandNo: OpInfo.getMatchedOperand(),
10354 AsmNodeOperands);
10355 InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
10356 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10357 if (OpInfo.isIndirect) {
10358 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10359 emitInlineAsmError(Call, Message: "inline asm not supported yet: "
10360 "don't know how to handle tied "
10361 "indirect register inputs");
10362 return;
10363 }
10364
10365 SmallVector<Register, 4> Regs;
10366 MachineFunction &MF = DAG.getMachineFunction();
10367 MachineRegisterInfo &MRI = MF.getRegInfo();
10368 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10369 auto *R = cast<RegisterSDNode>(Val&: AsmNodeOperands[CurOp+1]);
10370 Register TiedReg = R->getReg();
10371 MVT RegVT = R->getSimpleValueType(ResNo: 0);
10372 const TargetRegisterClass *RC =
10373 TiedReg.isVirtual() ? MRI.getRegClass(Reg: TiedReg)
10374 : RegVT != MVT::Untyped ? TLI.getRegClassFor(VT: RegVT)
10375 : TRI.getMinimalPhysRegClass(Reg: TiedReg);
10376 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
10377 Regs.push_back(Elt: MRI.createVirtualRegister(RegClass: RC));
10378
10379 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10380
10381 SDLoc dl = getCurSDLoc();
10382 // Use the produced MatchedRegs object to
10383 MatchedRegs.getCopyToRegs(Val: InOperandVal, DAG, dl, Chain, Glue: &Glue, V: &Call);
10384 MatchedRegs.AddInlineAsmOperands(Code: InlineAsm::Kind::RegUse, HasMatching: true,
10385 MatchingIdx: OpInfo.getMatchedOperand(), dl, DAG,
10386 Ops&: AsmNodeOperands);
10387 break;
10388 }
10389
10390 assert(Flag.isMemKind() && "Unknown matching constraint!");
10391 assert(Flag.getNumOperandRegisters() == 1 &&
10392 "Unexpected number of operands");
10393 // Add information to the INLINEASM node to know about this input.
10394 // See InlineAsm.h isUseOperandTiedToDef.
10395 Flag.clearMemConstraint();
10396 Flag.setMatchingOp(OpInfo.getMatchedOperand());
10397 AsmNodeOperands.push_back(x: DAG.getTargetConstant(
10398 Val: Flag, DL: getCurSDLoc(), VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
10399 AsmNodeOperands.push_back(x: AsmNodeOperands[CurOp+1]);
10400 break;
10401 }
10402
10403 // Treat indirect 'X' constraint as memory.
10404 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10405 OpInfo.isIndirect)
10406 OpInfo.ConstraintType = TargetLowering::C_Memory;
10407
10408 if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10409 OpInfo.ConstraintType == TargetLowering::C_Other) {
10410 std::vector<SDValue> Ops;
10411 TLI.LowerAsmOperandForConstraint(Op: InOperandVal, Constraint: OpInfo.ConstraintCode,
10412 Ops, DAG);
10413 if (Ops.empty()) {
10414 if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10415 if (isa<ConstantSDNode>(Val: InOperandVal)) {
10416 emitInlineAsmError(Call, Message: "value out of range for constraint '" +
10417 Twine(OpInfo.ConstraintCode) + "'");
10418 return;
10419 }
10420
10421 emitInlineAsmError(Call,
10422 Message: "invalid operand for inline asm constraint '" +
10423 Twine(OpInfo.ConstraintCode) + "'");
10424 return;
10425 }
10426
10427 // Add information to the INLINEASM node to know about this input.
10428 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10429 AsmNodeOperands.push_back(x: DAG.getTargetConstant(
10430 Val: ResOpType, DL: getCurSDLoc(), VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
10431 llvm::append_range(C&: AsmNodeOperands, R&: Ops);
10432 break;
10433 }
10434
10435 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10436 assert((OpInfo.isIndirect ||
10437 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10438 "Operand must be indirect to be a mem!");
10439 assert(InOperandVal.getValueType() ==
10440 TLI.getPointerTy(DAG.getDataLayout()) &&
10441 "Memory operands expect pointer values");
10442
10443 const InlineAsm::ConstraintCode ConstraintID =
10444 TLI.getInlineAsmMemConstraint(ConstraintCode: OpInfo.ConstraintCode);
10445 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10446 "Failed to convert memory constraint code to constraint id.");
10447
10448 // Add information to the INLINEASM node to know about this input.
10449 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10450 ResOpType.setMemConstraint(ConstraintID);
10451 AsmNodeOperands.push_back(x: DAG.getTargetConstant(Val: ResOpType,
10452 DL: getCurSDLoc(),
10453 VT: MVT::i32));
10454 AsmNodeOperands.push_back(x: InOperandVal);
10455 break;
10456 }
10457
10458 if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10459 const InlineAsm::ConstraintCode ConstraintID =
10460 TLI.getInlineAsmMemConstraint(ConstraintCode: OpInfo.ConstraintCode);
10461 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10462 "Failed to convert memory constraint code to constraint id.");
10463
10464 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10465
10466 SDValue AsmOp = InOperandVal;
10467 if (isFunction(Op: InOperandVal)) {
10468 auto *GA = cast<GlobalAddressSDNode>(Val&: InOperandVal);
10469 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10470 AsmOp = DAG.getTargetGlobalAddress(GV: GA->getGlobal(), DL: getCurSDLoc(),
10471 VT: InOperandVal.getValueType(),
10472 offset: GA->getOffset());
10473 }
10474
10475 // Add information to the INLINEASM node to know about this input.
10476 ResOpType.setMemConstraint(ConstraintID);
10477
10478 AsmNodeOperands.push_back(
10479 x: DAG.getTargetConstant(Val: ResOpType, DL: getCurSDLoc(), VT: MVT::i32));
10480
10481 AsmNodeOperands.push_back(x: AsmOp);
10482 break;
10483 }
10484
10485 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10486 OpInfo.ConstraintType != TargetLowering::C_Register) {
10487 emitInlineAsmError(Call, Message: "unknown asm constraint '" +
10488 Twine(OpInfo.ConstraintCode) + "'");
10489 return;
10490 }
10491
10492 // TODO: Support this.
10493 if (OpInfo.isIndirect) {
10494 emitInlineAsmError(
10495 Call, Message: "Don't know how to handle indirect register inputs yet "
10496 "for constraint '" +
10497 Twine(OpInfo.ConstraintCode) + "'");
10498 return;
10499 }
10500
10501 // Copy the input into the appropriate registers.
10502 if (OpInfo.AssignedRegs.Regs.empty()) {
10503 emitInlineAsmError(Call,
10504 Message: "couldn't allocate input reg for constraint '" +
10505 Twine(OpInfo.ConstraintCode) + "'");
10506 return;
10507 }
10508
10509 if (DetectWriteToReservedRegister())
10510 return;
10511
10512 SDLoc dl = getCurSDLoc();
10513
10514 OpInfo.AssignedRegs.getCopyToRegs(Val: InOperandVal, DAG, dl, Chain, Glue: &Glue,
10515 V: &Call);
10516
10517 OpInfo.AssignedRegs.AddInlineAsmOperands(Code: InlineAsm::Kind::RegUse, HasMatching: false,
10518 MatchingIdx: 0, dl, DAG, Ops&: AsmNodeOperands);
10519 break;
10520 }
10521 case InlineAsm::isClobber:
10522 // Add the clobbered value to the operand list, so that the register
10523 // allocator is aware that the physreg got clobbered.
10524 if (!OpInfo.AssignedRegs.Regs.empty())
10525 OpInfo.AssignedRegs.AddInlineAsmOperands(Code: InlineAsm::Kind::Clobber,
10526 HasMatching: false, MatchingIdx: 0, dl: getCurSDLoc(), DAG,
10527 Ops&: AsmNodeOperands);
10528 break;
10529 }
10530 }
10531
10532 // Finish up input operands. Set the input chain and add the flag last.
10533 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10534 if (Glue.getNode()) AsmNodeOperands.push_back(x: Glue);
10535
10536 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10537 Chain = DAG.getNode(Opcode: ISDOpc, DL: getCurSDLoc(),
10538 VTList: DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue), Ops: AsmNodeOperands);
10539 Glue = Chain.getValue(R: 1);
10540
10541 // Do additional work to generate outputs.
10542
10543 SmallVector<EVT, 1> ResultVTs;
10544 SmallVector<SDValue, 1> ResultValues;
10545 SmallVector<SDValue, 8> OutChains;
10546
10547 llvm::Type *CallResultType = Call.getType();
10548 ArrayRef<Type *> ResultTypes;
10549 if (StructType *StructResult = dyn_cast<StructType>(Val: CallResultType))
10550 ResultTypes = StructResult->elements();
10551 else if (!CallResultType->isVoidTy())
10552 ResultTypes = ArrayRef(CallResultType);
10553
10554 auto CurResultType = ResultTypes.begin();
10555 auto handleRegAssign = [&](SDValue V) {
10556 assert(CurResultType != ResultTypes.end() && "Unexpected value");
10557 assert((*CurResultType)->isSized() && "Unexpected unsized type");
10558 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: *CurResultType);
10559 ++CurResultType;
10560 // If the type of the inline asm call site return value is different but has
10561 // same size as the type of the asm output bitcast it. One example of this
10562 // is for vectors with different width / number of elements. This can
10563 // happen for register classes that can contain multiple different value
10564 // types. The preg or vreg allocated may not have the same VT as was
10565 // expected.
10566 //
10567 // This can also happen for a return value that disagrees with the register
10568 // class it is put in, eg. a double in a general-purpose register on a
10569 // 32-bit machine.
10570 if (ResultVT != V.getValueType() &&
10571 ResultVT.getSizeInBits() == V.getValueSizeInBits())
10572 V = DAG.getNode(Opcode: ISD::BITCAST, DL: getCurSDLoc(), VT: ResultVT, Operand: V);
10573 else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10574 V.getValueType().isInteger()) {
10575 // If a result value was tied to an input value, the computed result
10576 // may have a wider width than the expected result. Extract the
10577 // relevant portion.
10578 V = DAG.getNode(Opcode: ISD::TRUNCATE, DL: getCurSDLoc(), VT: ResultVT, Operand: V);
10579 }
10580 assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10581 ResultVTs.push_back(Elt: ResultVT);
10582 ResultValues.push_back(Elt: V);
10583 };
10584
10585 // Deal with output operands.
10586 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10587 if (OpInfo.Type == InlineAsm::isOutput) {
10588 SDValue Val;
10589 // Skip trivial output operands.
10590 if (OpInfo.AssignedRegs.Regs.empty())
10591 continue;
10592
10593 switch (OpInfo.ConstraintType) {
10594 case TargetLowering::C_Register:
10595 case TargetLowering::C_RegisterClass:
10596 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, dl: getCurSDLoc(),
10597 Chain, Glue: &Glue, V: &Call);
10598 break;
10599 case TargetLowering::C_Immediate:
10600 case TargetLowering::C_Other:
10601 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, DL: getCurSDLoc(),
10602 OpInfo, DAG);
10603 break;
10604 case TargetLowering::C_Memory:
10605 break; // Already handled.
10606 case TargetLowering::C_Address:
10607 break; // Silence warning.
10608 case TargetLowering::C_Unknown:
10609 assert(false && "Unexpected unknown constraint");
10610 }
10611
10612 // Indirect output manifest as stores. Record output chains.
10613 if (OpInfo.isIndirect) {
10614 const Value *Ptr = OpInfo.CallOperandVal;
10615 assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10616 SDValue Store = DAG.getStore(Chain, dl: getCurSDLoc(), Val, Ptr: getValue(V: Ptr),
10617 PtrInfo: MachinePointerInfo(Ptr));
10618 OutChains.push_back(Elt: Store);
10619 } else {
10620 // generate CopyFromRegs to associated registers.
10621 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10622 if (Val.getOpcode() == ISD::MERGE_VALUES) {
10623 for (const SDValue &V : Val->op_values())
10624 handleRegAssign(V);
10625 } else
10626 handleRegAssign(Val);
10627 }
10628 }
10629 }
10630
10631 // Set results.
10632 if (!ResultValues.empty()) {
10633 assert(CurResultType == ResultTypes.end() &&
10634 "Mismatch in number of ResultTypes");
10635 assert(ResultValues.size() == ResultTypes.size() &&
10636 "Mismatch in number of output operands in asm result");
10637
10638 SDValue V = DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
10639 VTList: DAG.getVTList(VTs: ResultVTs), Ops: ResultValues);
10640 setValue(V: &Call, NewN: V);
10641 }
10642
10643 // Collect store chains.
10644 if (!OutChains.empty())
10645 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: getCurSDLoc(), VT: MVT::Other, Ops: OutChains);
10646
10647 if (EmitEHLabels) {
10648 Chain = lowerEndEH(Chain, II: cast<InvokeInst>(Val: &Call), EHPadBB, BeginLabel);
10649 }
10650
10651 // Only Update Root if inline assembly has a memory effect.
10652 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10653 EmitEHLabels)
10654 DAG.setRoot(Chain);
10655}
10656
10657void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10658 const Twine &Message) {
10659 LLVMContext &Ctx = *DAG.getContext();
10660 Ctx.diagnose(DI: DiagnosticInfoInlineAsm(Call, Message));
10661
10662 // Make sure we leave the DAG in a valid state
10663 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10664 SmallVector<EVT, 1> ValueVTs;
10665 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: Call.getType(), ValueVTs);
10666
10667 if (ValueVTs.empty())
10668 return;
10669
10670 SmallVector<SDValue, 1> Ops;
10671 for (const EVT &VT : ValueVTs)
10672 Ops.push_back(Elt: DAG.getUNDEF(VT));
10673
10674 setValue(V: &Call, NewN: DAG.getMergeValues(Ops, dl: getCurSDLoc()));
10675}
10676
10677void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10678 DAG.setRoot(DAG.getNode(Opcode: ISD::VASTART, DL: getCurSDLoc(),
10679 VT: MVT::Other, N1: getRoot(),
10680 N2: getValue(V: I.getArgOperand(i: 0)),
10681 N3: DAG.getSrcValue(v: I.getArgOperand(i: 0))));
10682}
10683
10684void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10685 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10686 const DataLayout &DL = DAG.getDataLayout();
10687 SDValue V = DAG.getVAArg(
10688 VT: TLI.getMemValueType(DL: DAG.getDataLayout(), Ty: I.getType()), dl: getCurSDLoc(),
10689 Chain: getRoot(), Ptr: getValue(V: I.getOperand(i_nocapture: 0)), SV: DAG.getSrcValue(v: I.getOperand(i_nocapture: 0)),
10690 Align: DL.getABITypeAlign(Ty: I.getType()).value());
10691 DAG.setRoot(V.getValue(R: 1));
10692
10693 if (I.getType()->isPointerTy())
10694 V = DAG.getPtrExtOrTrunc(
10695 Op: V, DL: getCurSDLoc(), VT: TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType()));
10696 setValue(V: &I, NewN: V);
10697}
10698
10699void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10700 DAG.setRoot(DAG.getNode(Opcode: ISD::VAEND, DL: getCurSDLoc(),
10701 VT: MVT::Other, N1: getRoot(),
10702 N2: getValue(V: I.getArgOperand(i: 0)),
10703 N3: DAG.getSrcValue(v: I.getArgOperand(i: 0))));
10704}
10705
10706void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10707 DAG.setRoot(DAG.getNode(Opcode: ISD::VACOPY, DL: getCurSDLoc(),
10708 VT: MVT::Other, N1: getRoot(),
10709 N2: getValue(V: I.getArgOperand(i: 0)),
10710 N3: getValue(V: I.getArgOperand(i: 1)),
10711 N4: DAG.getSrcValue(v: I.getArgOperand(i: 0)),
10712 N5: DAG.getSrcValue(v: I.getArgOperand(i: 1))));
10713}
10714
10715SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10716 const Instruction &I,
10717 SDValue Op) {
10718 std::optional<ConstantRange> CR = getRange(I);
10719
10720 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10721 return Op;
10722
10723 APInt Lo = CR->getUnsignedMin();
10724 if (!Lo.isMinValue())
10725 return Op;
10726
10727 APInt Hi = CR->getUnsignedMax();
10728 unsigned Bits = std::max(a: Hi.getActiveBits(),
10729 b: static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10730
10731 EVT SmallVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: Bits);
10732
10733 SDLoc SL = getCurSDLoc();
10734
10735 SDValue ZExt = DAG.getNode(Opcode: ISD::AssertZext, DL: SL, VT: Op.getValueType(), N1: Op,
10736 N2: DAG.getValueType(SmallVT));
10737 unsigned NumVals = Op.getNode()->getNumValues();
10738 if (NumVals == 1)
10739 return ZExt;
10740
10741 SmallVector<SDValue, 4> Ops;
10742
10743 Ops.push_back(Elt: ZExt);
10744 for (unsigned I = 1; I != NumVals; ++I)
10745 Ops.push_back(Elt: Op.getValue(R: I));
10746
10747 return DAG.getMergeValues(Ops, dl: SL);
10748}
10749
10750SDValue SelectionDAGBuilder::lowerNoFPClassToAssertNoFPClass(
10751 SelectionDAG &DAG, const Instruction &I, SDValue Op) {
10752 FPClassTest Classes = getNoFPClass(I);
10753 if (Classes == fcNone)
10754 return Op;
10755
10756 SDLoc SL = getCurSDLoc();
10757 SDValue TestConst = DAG.getTargetConstant(Val: Classes, DL: SDLoc(), VT: MVT::i32);
10758
10759 if (Op.getOpcode() != ISD::MERGE_VALUES) {
10760 return DAG.getNode(Opcode: ISD::AssertNoFPClass, DL: SL, VT: Op.getValueType(), N1: Op,
10761 N2: TestConst);
10762 }
10763
10764 SmallVector<SDValue, 8> Ops(Op.getNumOperands());
10765 for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
10766 SDValue MergeOp = Op.getOperand(i: I);
10767 Ops[I] = DAG.getNode(Opcode: ISD::AssertNoFPClass, DL: SL, VT: MergeOp.getValueType(),
10768 N1: MergeOp, N2: TestConst);
10769 }
10770
10771 return DAG.getMergeValues(Ops, dl: SL);
10772}
10773
10774/// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10775/// the call being lowered.
10776///
10777/// This is a helper for lowering intrinsics that follow a target calling
10778/// convention or require stack pointer adjustment. Only a subset of the
10779/// intrinsic's operands need to participate in the calling convention.
10780void SelectionDAGBuilder::populateCallLoweringInfo(
10781 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10782 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10783 AttributeSet RetAttrs, bool IsPatchPoint) {
10784 TargetLowering::ArgListTy Args;
10785 Args.reserve(n: NumArgs);
10786
10787 // Populate the argument list.
10788 // Attributes for args start at offset 1, after the return attribute.
10789 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10790 ArgI != ArgE; ++ArgI) {
10791 const Value *V = Call->getOperand(i_nocapture: ArgI);
10792
10793 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10794
10795 TargetLowering::ArgListEntry Entry(getValue(V), V->getType());
10796 Entry.setAttributes(Call, ArgIdx: ArgI);
10797 Args.push_back(x: Entry);
10798 }
10799
10800 CLI.setDebugLoc(getCurSDLoc())
10801 .setChain(getRoot())
10802 .setCallee(CC: Call->getCallingConv(), ResultType: ReturnTy, Target: Callee, ArgsList: std::move(Args),
10803 ResultAttrs: RetAttrs)
10804 .setDiscardResult(Call->use_empty())
10805 .setIsPatchPoint(IsPatchPoint)
10806 .setIsPreallocated(
10807 Call->countOperandBundlesOfType(ID: LLVMContext::OB_preallocated) != 0);
10808}
10809
10810/// Add a stack map intrinsic call's live variable operands to a stackmap
10811/// or patchpoint target node's operand list.
10812///
10813/// Constants are converted to TargetConstants purely as an optimization to
10814/// avoid constant materialization and register allocation.
10815///
10816/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10817/// generate addess computation nodes, and so FinalizeISel can convert the
10818/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10819/// address materialization and register allocation, but may also be required
10820/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10821/// alloca in the entry block, then the runtime may assume that the alloca's
10822/// StackMap location can be read immediately after compilation and that the
10823/// location is valid at any point during execution (this is similar to the
10824/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10825/// only available in a register, then the runtime would need to trap when
10826/// execution reaches the StackMap in order to read the alloca's location.
10827static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10828 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10829 SelectionDAGBuilder &Builder) {
10830 SelectionDAG &DAG = Builder.DAG;
10831 for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10832 SDValue Op = Builder.getValue(V: Call.getArgOperand(i: I));
10833
10834 // Things on the stack are pointer-typed, meaning that they are already
10835 // legal and can be emitted directly to target nodes.
10836 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Val&: Op)) {
10837 Ops.push_back(Elt: DAG.getTargetFrameIndex(FI: FI->getIndex(), VT: Op.getValueType()));
10838 } else {
10839 // Otherwise emit a target independent node to be legalised.
10840 Ops.push_back(Elt: Builder.getValue(V: Call.getArgOperand(i: I)));
10841 }
10842 }
10843}
10844
10845/// Lower llvm.experimental.stackmap.
10846void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10847 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10848 // [live variables...])
10849
10850 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10851
10852 SDValue Chain, InGlue, Callee;
10853 SmallVector<SDValue, 32> Ops;
10854
10855 SDLoc DL = getCurSDLoc();
10856 Callee = getValue(V: CI.getCalledOperand());
10857
10858 // The stackmap intrinsic only records the live variables (the arguments
10859 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10860 // intrinsic, this won't be lowered to a function call. This means we don't
10861 // have to worry about calling conventions and target specific lowering code.
10862 // Instead we perform the call lowering right here.
10863 //
10864 // chain, flag = CALLSEQ_START(chain, 0, 0)
10865 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10866 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10867 //
10868 Chain = DAG.getCALLSEQ_START(Chain: getRoot(), InSize: 0, OutSize: 0, DL);
10869 InGlue = Chain.getValue(R: 1);
10870
10871 // Add the STACKMAP operands, starting with DAG house-keeping.
10872 Ops.push_back(Elt: Chain);
10873 Ops.push_back(Elt: InGlue);
10874
10875 // Add the <id>, <numShadowBytes> operands.
10876 //
10877 // These do not require legalisation, and can be emitted directly to target
10878 // constant nodes.
10879 SDValue ID = getValue(V: CI.getArgOperand(i: 0));
10880 assert(ID.getValueType() == MVT::i64);
10881 SDValue IDConst =
10882 DAG.getTargetConstant(Val: ID->getAsZExtVal(), DL, VT: ID.getValueType());
10883 Ops.push_back(Elt: IDConst);
10884
10885 SDValue Shad = getValue(V: CI.getArgOperand(i: 1));
10886 assert(Shad.getValueType() == MVT::i32);
10887 SDValue ShadConst =
10888 DAG.getTargetConstant(Val: Shad->getAsZExtVal(), DL, VT: Shad.getValueType());
10889 Ops.push_back(Elt: ShadConst);
10890
10891 // Add the live variables.
10892 addStackMapLiveVars(Call: CI, StartIdx: 2, DL, Ops, Builder&: *this);
10893
10894 // Create the STACKMAP node.
10895 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
10896 Chain = DAG.getNode(Opcode: ISD::STACKMAP, DL, VTList: NodeTys, Ops);
10897 InGlue = Chain.getValue(R: 1);
10898
10899 Chain = DAG.getCALLSEQ_END(Chain, Size1: 0, Size2: 0, Glue: InGlue, DL);
10900
10901 // Stackmaps don't generate values, so nothing goes into the NodeMap.
10902
10903 // Set the root to the target-lowered call chain.
10904 DAG.setRoot(Chain);
10905
10906 // Inform the Frame Information that we have a stackmap in this function.
10907 FuncInfo.MF->getFrameInfo().setHasStackMap();
10908}
10909
10910/// Lower llvm.experimental.patchpoint directly to its target opcode.
10911void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10912 const BasicBlock *EHPadBB) {
10913 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10914 // i32 <numBytes>,
10915 // i8* <target>,
10916 // i32 <numArgs>,
10917 // [Args...],
10918 // [live variables...])
10919
10920 CallingConv::ID CC = CB.getCallingConv();
10921 bool IsAnyRegCC = CC == CallingConv::AnyReg;
10922 bool HasDef = !CB.getType()->isVoidTy();
10923 SDLoc dl = getCurSDLoc();
10924 SDValue Callee = getValue(V: CB.getArgOperand(i: PatchPointOpers::TargetPos));
10925
10926 // Handle immediate and symbolic callees.
10927 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Val&: Callee))
10928 Callee = DAG.getIntPtrConstant(Val: ConstCallee->getZExtValue(), DL: dl,
10929 /*isTarget=*/true);
10930 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Val&: Callee))
10931 Callee = DAG.getTargetGlobalAddress(GV: SymbolicCallee->getGlobal(),
10932 DL: SDLoc(SymbolicCallee),
10933 VT: SymbolicCallee->getValueType(ResNo: 0));
10934
10935 // Get the real number of arguments participating in the call <numArgs>
10936 SDValue NArgVal = getValue(V: CB.getArgOperand(i: PatchPointOpers::NArgPos));
10937 unsigned NumArgs = NArgVal->getAsZExtVal();
10938
10939 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10940 // Intrinsics include all meta-operands up to but not including CC.
10941 unsigned NumMetaOpers = PatchPointOpers::CCPos;
10942 assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10943 "Not enough arguments provided to the patchpoint intrinsic");
10944
10945 // For AnyRegCC the arguments are lowered later on manually.
10946 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10947 Type *ReturnTy =
10948 IsAnyRegCC ? Type::getVoidTy(C&: *DAG.getContext()) : CB.getType();
10949
10950 TargetLowering::CallLoweringInfo CLI(DAG);
10951 populateCallLoweringInfo(CLI, Call: &CB, ArgIdx: NumMetaOpers, NumArgs: NumCallArgs, Callee,
10952 ReturnTy, RetAttrs: CB.getAttributes().getRetAttrs(), IsPatchPoint: true);
10953 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10954
10955 SDNode *CallEnd = Result.second.getNode();
10956 if (CallEnd->getOpcode() == ISD::EH_LABEL)
10957 CallEnd = CallEnd->getOperand(Num: 0).getNode();
10958 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10959 CallEnd = CallEnd->getOperand(Num: 0).getNode();
10960
10961 /// Get a call instruction from the call sequence chain.
10962 /// Tail calls are not allowed.
10963 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10964 "Expected a callseq node.");
10965 SDNode *Call = CallEnd->getOperand(Num: 0).getNode();
10966 bool HasGlue = Call->getGluedNode();
10967
10968 // Replace the target specific call node with the patchable intrinsic.
10969 SmallVector<SDValue, 8> Ops;
10970
10971 // Push the chain.
10972 Ops.push_back(Elt: *(Call->op_begin()));
10973
10974 // Optionally, push the glue (if any).
10975 if (HasGlue)
10976 Ops.push_back(Elt: *(Call->op_end() - 1));
10977
10978 // Push the register mask info.
10979 if (HasGlue)
10980 Ops.push_back(Elt: *(Call->op_end() - 2));
10981 else
10982 Ops.push_back(Elt: *(Call->op_end() - 1));
10983
10984 // Add the <id> and <numBytes> constants.
10985 SDValue IDVal = getValue(V: CB.getArgOperand(i: PatchPointOpers::IDPos));
10986 Ops.push_back(Elt: DAG.getTargetConstant(Val: IDVal->getAsZExtVal(), DL: dl, VT: MVT::i64));
10987 SDValue NBytesVal = getValue(V: CB.getArgOperand(i: PatchPointOpers::NBytesPos));
10988 Ops.push_back(Elt: DAG.getTargetConstant(Val: NBytesVal->getAsZExtVal(), DL: dl, VT: MVT::i32));
10989
10990 // Add the callee.
10991 Ops.push_back(Elt: Callee);
10992
10993 // Adjust <numArgs> to account for any arguments that have been passed on the
10994 // stack instead.
10995 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10996 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10997 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10998 Ops.push_back(Elt: DAG.getTargetConstant(Val: NumCallRegArgs, DL: dl, VT: MVT::i32));
10999
11000 // Add the calling convention
11001 Ops.push_back(Elt: DAG.getTargetConstant(Val: (unsigned)CC, DL: dl, VT: MVT::i32));
11002
11003 // Add the arguments we omitted previously. The register allocator should
11004 // place these in any free register.
11005 if (IsAnyRegCC)
11006 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
11007 Ops.push_back(Elt: getValue(V: CB.getArgOperand(i)));
11008
11009 // Push the arguments from the call instruction.
11010 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
11011 Ops.append(in_start: Call->op_begin() + 2, in_end: e);
11012
11013 // Push live variables for the stack map.
11014 addStackMapLiveVars(Call: CB, StartIdx: NumMetaOpers + NumArgs, DL: dl, Ops, Builder&: *this);
11015
11016 SDVTList NodeTys;
11017 if (IsAnyRegCC && HasDef) {
11018 // Create the return types based on the intrinsic definition
11019 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11020 SmallVector<EVT, 3> ValueVTs;
11021 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: CB.getType(), ValueVTs);
11022 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
11023
11024 // There is always a chain and a glue type at the end
11025 ValueVTs.push_back(Elt: MVT::Other);
11026 ValueVTs.push_back(Elt: MVT::Glue);
11027 NodeTys = DAG.getVTList(VTs: ValueVTs);
11028 } else
11029 NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
11030
11031 // Replace the target specific call node with a PATCHPOINT node.
11032 SDValue PPV = DAG.getNode(Opcode: ISD::PATCHPOINT, DL: dl, VTList: NodeTys, Ops);
11033
11034 // Update the NodeMap.
11035 if (HasDef) {
11036 if (IsAnyRegCC)
11037 setValue(V: &CB, NewN: SDValue(PPV.getNode(), 0));
11038 else
11039 setValue(V: &CB, NewN: Result.first);
11040 }
11041
11042 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
11043 // call sequence. Furthermore the location of the chain and glue can change
11044 // when the AnyReg calling convention is used and the intrinsic returns a
11045 // value.
11046 if (IsAnyRegCC && HasDef) {
11047 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
11048 SDValue To[] = {PPV.getValue(R: 1), PPV.getValue(R: 2)};
11049 DAG.ReplaceAllUsesOfValuesWith(From, To, Num: 2);
11050 } else
11051 DAG.ReplaceAllUsesWith(From: Call, To: PPV.getNode());
11052 DAG.DeleteNode(N: Call);
11053
11054 // Inform the Frame Information that we have a patchpoint in this function.
11055 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
11056}
11057
11058void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
11059 unsigned Intrinsic) {
11060 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11061 SDValue Op1 = getValue(V: I.getArgOperand(i: 0));
11062 SDValue Op2;
11063 if (I.arg_size() > 1)
11064 Op2 = getValue(V: I.getArgOperand(i: 1));
11065 SDLoc dl = getCurSDLoc();
11066 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
11067 SDValue Res;
11068 SDNodeFlags SDFlags;
11069 if (auto *FPMO = dyn_cast<FPMathOperator>(Val: &I))
11070 SDFlags.copyFMF(FPMO: *FPMO);
11071
11072 switch (Intrinsic) {
11073 case Intrinsic::vector_reduce_fadd:
11074 if (SDFlags.hasAllowReassociation())
11075 Res = DAG.getNode(Opcode: ISD::FADD, DL: dl, VT, N1: Op1,
11076 N2: DAG.getNode(Opcode: ISD::VECREDUCE_FADD, DL: dl, VT, Operand: Op2, Flags: SDFlags),
11077 Flags: SDFlags);
11078 else
11079 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SEQ_FADD, DL: dl, VT, N1: Op1, N2: Op2, Flags: SDFlags);
11080 break;
11081 case Intrinsic::vector_reduce_fmul:
11082 if (SDFlags.hasAllowReassociation())
11083 Res = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT, N1: Op1,
11084 N2: DAG.getNode(Opcode: ISD::VECREDUCE_FMUL, DL: dl, VT, Operand: Op2, Flags: SDFlags),
11085 Flags: SDFlags);
11086 else
11087 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SEQ_FMUL, DL: dl, VT, N1: Op1, N2: Op2, Flags: SDFlags);
11088 break;
11089 case Intrinsic::vector_reduce_add:
11090 Res = DAG.getNode(Opcode: ISD::VECREDUCE_ADD, DL: dl, VT, Operand: Op1);
11091 break;
11092 case Intrinsic::vector_reduce_mul:
11093 Res = DAG.getNode(Opcode: ISD::VECREDUCE_MUL, DL: dl, VT, Operand: Op1);
11094 break;
11095 case Intrinsic::vector_reduce_and:
11096 Res = DAG.getNode(Opcode: ISD::VECREDUCE_AND, DL: dl, VT, Operand: Op1);
11097 break;
11098 case Intrinsic::vector_reduce_or:
11099 Res = DAG.getNode(Opcode: ISD::VECREDUCE_OR, DL: dl, VT, Operand: Op1);
11100 break;
11101 case Intrinsic::vector_reduce_xor:
11102 Res = DAG.getNode(Opcode: ISD::VECREDUCE_XOR, DL: dl, VT, Operand: Op1);
11103 break;
11104 case Intrinsic::vector_reduce_smax:
11105 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SMAX, DL: dl, VT, Operand: Op1);
11106 break;
11107 case Intrinsic::vector_reduce_smin:
11108 Res = DAG.getNode(Opcode: ISD::VECREDUCE_SMIN, DL: dl, VT, Operand: Op1);
11109 break;
11110 case Intrinsic::vector_reduce_umax:
11111 Res = DAG.getNode(Opcode: ISD::VECREDUCE_UMAX, DL: dl, VT, Operand: Op1);
11112 break;
11113 case Intrinsic::vector_reduce_umin:
11114 Res = DAG.getNode(Opcode: ISD::VECREDUCE_UMIN, DL: dl, VT, Operand: Op1);
11115 break;
11116 case Intrinsic::vector_reduce_fmax:
11117 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMAX, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11118 break;
11119 case Intrinsic::vector_reduce_fmin:
11120 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMIN, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11121 break;
11122 case Intrinsic::vector_reduce_fmaximum:
11123 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMAXIMUM, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11124 break;
11125 case Intrinsic::vector_reduce_fminimum:
11126 Res = DAG.getNode(Opcode: ISD::VECREDUCE_FMINIMUM, DL: dl, VT, Operand: Op1, Flags: SDFlags);
11127 break;
11128 default:
11129 llvm_unreachable("Unhandled vector reduce intrinsic");
11130 }
11131 setValue(V: &I, NewN: Res);
11132}
11133
11134/// Returns an AttributeList representing the attributes applied to the return
11135/// value of the given call.
11136static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
11137 SmallVector<Attribute::AttrKind, 2> Attrs;
11138 if (CLI.RetSExt)
11139 Attrs.push_back(Elt: Attribute::SExt);
11140 if (CLI.RetZExt)
11141 Attrs.push_back(Elt: Attribute::ZExt);
11142 if (CLI.IsInReg)
11143 Attrs.push_back(Elt: Attribute::InReg);
11144
11145 return AttributeList::get(C&: CLI.RetTy->getContext(), Index: AttributeList::ReturnIndex,
11146 Kinds: Attrs);
11147}
11148
11149/// TargetLowering::LowerCallTo - This is the default LowerCallTo
11150/// implementation, which just calls LowerCall.
11151/// FIXME: When all targets are
11152/// migrated to using LowerCall, this hook should be integrated into SDISel.
11153std::pair<SDValue, SDValue>
11154TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
11155 LLVMContext &Context = CLI.RetTy->getContext();
11156
11157 // Handle the incoming return values from the call.
11158 CLI.Ins.clear();
11159 SmallVector<Type *, 4> RetOrigTys;
11160 SmallVector<TypeSize, 4> Offsets;
11161 auto &DL = CLI.DAG.getDataLayout();
11162 ComputeValueTypes(DL, Ty: CLI.OrigRetTy, Types&: RetOrigTys, Offsets: &Offsets);
11163
11164 SmallVector<EVT, 4> RetVTs;
11165 if (CLI.RetTy != CLI.OrigRetTy) {
11166 assert(RetOrigTys.size() == 1 &&
11167 "Only supported for non-aggregate returns");
11168 RetVTs.push_back(Elt: getValueType(DL, Ty: CLI.RetTy));
11169 } else {
11170 for (Type *Ty : RetOrigTys)
11171 RetVTs.push_back(Elt: getValueType(DL, Ty));
11172 }
11173
11174 if (CLI.IsPostTypeLegalization) {
11175 // If we are lowering a libcall after legalization, split the return type.
11176 SmallVector<Type *, 4> OldRetOrigTys;
11177 SmallVector<EVT, 4> OldRetVTs;
11178 SmallVector<TypeSize, 4> OldOffsets;
11179 RetOrigTys.swap(RHS&: OldRetOrigTys);
11180 RetVTs.swap(RHS&: OldRetVTs);
11181 Offsets.swap(RHS&: OldOffsets);
11182
11183 for (size_t i = 0, e = OldRetVTs.size(); i != e; ++i) {
11184 EVT RetVT = OldRetVTs[i];
11185 uint64_t Offset = OldOffsets[i];
11186 MVT RegisterVT = getRegisterType(Context, VT: RetVT);
11187 unsigned NumRegs = getNumRegisters(Context, VT: RetVT);
11188 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
11189 RetOrigTys.append(NumInputs: NumRegs, Elt: OldRetOrigTys[i]);
11190 RetVTs.append(NumInputs: NumRegs, Elt: RegisterVT);
11191 for (unsigned j = 0; j != NumRegs; ++j)
11192 Offsets.push_back(Elt: TypeSize::getFixed(ExactSize: Offset + j * RegisterVTByteSZ));
11193 }
11194 }
11195
11196 SmallVector<ISD::OutputArg, 4> Outs;
11197 GetReturnInfo(CC: CLI.CallConv, ReturnType: CLI.RetTy, attr: getReturnAttrs(CLI), Outs, TLI: *this, DL);
11198
11199 bool CanLowerReturn =
11200 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
11201 CLI.IsVarArg, Outs, Context, RetTy: CLI.RetTy);
11202
11203 SDValue DemoteStackSlot;
11204 int DemoteStackIdx = -100;
11205 if (!CanLowerReturn) {
11206 // FIXME: equivalent assert?
11207 // assert(!CS.hasInAllocaArgument() &&
11208 // "sret demotion is incompatible with inalloca");
11209 uint64_t TySize = DL.getTypeAllocSize(Ty: CLI.RetTy);
11210 Align Alignment = DL.getPrefTypeAlign(Ty: CLI.RetTy);
11211 MachineFunction &MF = CLI.DAG.getMachineFunction();
11212 DemoteStackIdx =
11213 MF.getFrameInfo().CreateStackObject(Size: TySize, Alignment, isSpillSlot: false);
11214 Type *StackSlotPtrType = PointerType::get(C&: Context, AddressSpace: DL.getAllocaAddrSpace());
11215
11216 DemoteStackSlot = CLI.DAG.getFrameIndex(FI: DemoteStackIdx, VT: getFrameIndexTy(DL));
11217 ArgListEntry Entry(DemoteStackSlot, StackSlotPtrType);
11218 Entry.IsSRet = true;
11219 Entry.Alignment = Alignment;
11220 CLI.getArgs().insert(position: CLI.getArgs().begin(), x: Entry);
11221 CLI.NumFixedArgs += 1;
11222 CLI.getArgs()[0].IndirectType = CLI.RetTy;
11223 CLI.RetTy = CLI.OrigRetTy = Type::getVoidTy(C&: Context);
11224
11225 // sret demotion isn't compatible with tail-calls, since the sret argument
11226 // points into the callers stack frame.
11227 CLI.IsTailCall = false;
11228 } else {
11229 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11230 Ty: CLI.RetTy, CallConv: CLI.CallConv, isVarArg: CLI.IsVarArg, DL);
11231 for (unsigned I = 0, E = RetVTs.size(); I != E; ++I) {
11232 ISD::ArgFlagsTy Flags;
11233 if (NeedsRegBlock) {
11234 Flags.setInConsecutiveRegs();
11235 if (I == RetVTs.size() - 1)
11236 Flags.setInConsecutiveRegsLast();
11237 }
11238 EVT VT = RetVTs[I];
11239 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CC: CLI.CallConv, VT);
11240 unsigned NumRegs =
11241 getNumRegistersForCallingConv(Context, CC: CLI.CallConv, VT);
11242 for (unsigned i = 0; i != NumRegs; ++i) {
11243 ISD::InputArg Ret(Flags, RegisterVT, VT, RetOrigTys[I],
11244 CLI.IsReturnValueUsed, ISD::InputArg::NoArgIndex, 0);
11245 if (CLI.RetTy->isPointerTy()) {
11246 Ret.Flags.setPointer();
11247 Ret.Flags.setPointerAddrSpace(
11248 cast<PointerType>(Val: CLI.RetTy)->getAddressSpace());
11249 }
11250 if (CLI.RetSExt)
11251 Ret.Flags.setSExt();
11252 if (CLI.RetZExt)
11253 Ret.Flags.setZExt();
11254 if (CLI.IsInReg)
11255 Ret.Flags.setInReg();
11256 CLI.Ins.push_back(Elt: Ret);
11257 }
11258 }
11259 }
11260
11261 // We push in swifterror return as the last element of CLI.Ins.
11262 ArgListTy &Args = CLI.getArgs();
11263 if (supportSwiftError()) {
11264 for (const ArgListEntry &Arg : Args) {
11265 if (Arg.IsSwiftError) {
11266 ISD::ArgFlagsTy Flags;
11267 Flags.setSwiftError();
11268 ISD::InputArg Ret(Flags, getPointerTy(DL), EVT(getPointerTy(DL)),
11269 PointerType::getUnqual(C&: Context),
11270 /*Used=*/true, ISD::InputArg::NoArgIndex, 0);
11271 CLI.Ins.push_back(Elt: Ret);
11272 }
11273 }
11274 }
11275
11276 // Handle all of the outgoing arguments.
11277 CLI.Outs.clear();
11278 CLI.OutVals.clear();
11279 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11280 SmallVector<Type *, 4> OrigArgTys;
11281 ComputeValueTypes(DL, Ty: Args[i].OrigTy, Types&: OrigArgTys);
11282 // FIXME: Split arguments if CLI.IsPostTypeLegalization
11283 Type *FinalType = Args[i].Ty;
11284 if (Args[i].IsByVal)
11285 FinalType = Args[i].IndirectType;
11286 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11287 Ty: FinalType, CallConv: CLI.CallConv, isVarArg: CLI.IsVarArg, DL);
11288 for (unsigned Value = 0, NumValues = OrigArgTys.size(); Value != NumValues;
11289 ++Value) {
11290 Type *OrigArgTy = OrigArgTys[Value];
11291 Type *ArgTy = OrigArgTy;
11292 if (Args[i].Ty != Args[i].OrigTy) {
11293 assert(Value == 0 && "Only supported for non-aggregate arguments");
11294 ArgTy = Args[i].Ty;
11295 }
11296
11297 EVT VT = getValueType(DL, Ty: ArgTy);
11298 SDValue Op = SDValue(Args[i].Node.getNode(),
11299 Args[i].Node.getResNo() + Value);
11300 ISD::ArgFlagsTy Flags;
11301
11302 // Certain targets (such as MIPS), may have a different ABI alignment
11303 // for a type depending on the context. Give the target a chance to
11304 // specify the alignment it wants.
11305 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11306 Flags.setOrigAlign(OriginalAlignment);
11307
11308 if (i >= CLI.NumFixedArgs)
11309 Flags.setVarArg();
11310 if (ArgTy->isPointerTy()) {
11311 Flags.setPointer();
11312 Flags.setPointerAddrSpace(cast<PointerType>(Val: ArgTy)->getAddressSpace());
11313 }
11314 if (Args[i].IsZExt)
11315 Flags.setZExt();
11316 if (Args[i].IsSExt)
11317 Flags.setSExt();
11318 if (Args[i].IsNoExt)
11319 Flags.setNoExt();
11320 if (Args[i].IsInReg) {
11321 // If we are using vectorcall calling convention, a structure that is
11322 // passed InReg - is surely an HVA
11323 if (CLI.CallConv == CallingConv::X86_VectorCall &&
11324 isa<StructType>(Val: FinalType)) {
11325 // The first value of a structure is marked
11326 if (0 == Value)
11327 Flags.setHvaStart();
11328 Flags.setHva();
11329 }
11330 // Set InReg Flag
11331 Flags.setInReg();
11332 }
11333 if (Args[i].IsSRet)
11334 Flags.setSRet();
11335 if (Args[i].IsSwiftSelf)
11336 Flags.setSwiftSelf();
11337 if (Args[i].IsSwiftAsync)
11338 Flags.setSwiftAsync();
11339 if (Args[i].IsSwiftError)
11340 Flags.setSwiftError();
11341 if (Args[i].IsCFGuardTarget)
11342 Flags.setCFGuardTarget();
11343 if (Args[i].IsByVal)
11344 Flags.setByVal();
11345 if (Args[i].IsByRef)
11346 Flags.setByRef();
11347 if (Args[i].IsPreallocated) {
11348 Flags.setPreallocated();
11349 // Set the byval flag for CCAssignFn callbacks that don't know about
11350 // preallocated. This way we can know how many bytes we should've
11351 // allocated and how many bytes a callee cleanup function will pop. If
11352 // we port preallocated to more targets, we'll have to add custom
11353 // preallocated handling in the various CC lowering callbacks.
11354 Flags.setByVal();
11355 }
11356 if (Args[i].IsInAlloca) {
11357 Flags.setInAlloca();
11358 // Set the byval flag for CCAssignFn callbacks that don't know about
11359 // inalloca. This way we can know how many bytes we should've allocated
11360 // and how many bytes a callee cleanup function will pop. If we port
11361 // inalloca to more targets, we'll have to add custom inalloca handling
11362 // in the various CC lowering callbacks.
11363 Flags.setByVal();
11364 }
11365 Align MemAlign;
11366 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11367 unsigned FrameSize = DL.getTypeAllocSize(Ty: Args[i].IndirectType);
11368 Flags.setByValSize(FrameSize);
11369
11370 // info is not there but there are cases it cannot get right.
11371 if (auto MA = Args[i].Alignment)
11372 MemAlign = *MA;
11373 else
11374 MemAlign = getByValTypeAlignment(Ty: Args[i].IndirectType, DL);
11375 } else if (auto MA = Args[i].Alignment) {
11376 MemAlign = *MA;
11377 } else {
11378 MemAlign = OriginalAlignment;
11379 }
11380 Flags.setMemAlign(MemAlign);
11381 if (Args[i].IsNest)
11382 Flags.setNest();
11383 if (NeedsRegBlock)
11384 Flags.setInConsecutiveRegs();
11385
11386 MVT PartVT = getRegisterTypeForCallingConv(Context, CC: CLI.CallConv, VT);
11387 unsigned NumParts =
11388 getNumRegistersForCallingConv(Context, CC: CLI.CallConv, VT);
11389 SmallVector<SDValue, 4> Parts(NumParts);
11390 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11391
11392 if (Args[i].IsSExt)
11393 ExtendKind = ISD::SIGN_EXTEND;
11394 else if (Args[i].IsZExt)
11395 ExtendKind = ISD::ZERO_EXTEND;
11396
11397 // Conservatively only handle 'returned' on non-vectors that can be lowered,
11398 // for now.
11399 if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11400 CanLowerReturn) {
11401 assert((CLI.RetTy == Args[i].Ty ||
11402 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11403 CLI.RetTy->getPointerAddressSpace() ==
11404 Args[i].Ty->getPointerAddressSpace())) &&
11405 RetVTs.size() == NumValues && "unexpected use of 'returned'");
11406 // Before passing 'returned' to the target lowering code, ensure that
11407 // either the register MVT and the actual EVT are the same size or that
11408 // the return value and argument are extended in the same way; in these
11409 // cases it's safe to pass the argument register value unchanged as the
11410 // return register value (although it's at the target's option whether
11411 // to do so)
11412 // TODO: allow code generation to take advantage of partially preserved
11413 // registers rather than clobbering the entire register when the
11414 // parameter extension method is not compatible with the return
11415 // extension method
11416 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11417 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11418 CLI.RetZExt == Args[i].IsZExt))
11419 Flags.setReturned();
11420 }
11421
11422 getCopyToParts(DAG&: CLI.DAG, DL: CLI.DL, Val: Op, Parts: &Parts[0], NumParts, PartVT, V: CLI.CB,
11423 CallConv: CLI.CallConv, ExtendKind);
11424
11425 for (unsigned j = 0; j != NumParts; ++j) {
11426 // if it isn't first piece, alignment must be 1
11427 // For scalable vectors the scalable part is currently handled
11428 // by individual targets, so we just use the known minimum size here.
11429 ISD::OutputArg MyFlags(
11430 Flags, Parts[j].getValueType().getSimpleVT(), VT, OrigArgTy, i,
11431 j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11432 if (NumParts > 1 && j == 0)
11433 MyFlags.Flags.setSplit();
11434 else if (j != 0) {
11435 MyFlags.Flags.setOrigAlign(Align(1));
11436 if (j == NumParts - 1)
11437 MyFlags.Flags.setSplitEnd();
11438 }
11439
11440 CLI.Outs.push_back(Elt: MyFlags);
11441 CLI.OutVals.push_back(Elt: Parts[j]);
11442 }
11443
11444 if (NeedsRegBlock && Value == NumValues - 1)
11445 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11446 }
11447 }
11448
11449 SmallVector<SDValue, 4> InVals;
11450 CLI.Chain = LowerCall(CLI, InVals);
11451
11452 // Update CLI.InVals to use outside of this function.
11453 CLI.InVals = InVals;
11454
11455 // Verify that the target's LowerCall behaved as expected.
11456 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11457 "LowerCall didn't return a valid chain!");
11458 assert((!CLI.IsTailCall || InVals.empty()) &&
11459 "LowerCall emitted a return value for a tail call!");
11460 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11461 "LowerCall didn't emit the correct number of values!");
11462
11463 // For a tail call, the return value is merely live-out and there aren't
11464 // any nodes in the DAG representing it. Return a special value to
11465 // indicate that a tail call has been emitted and no more Instructions
11466 // should be processed in the current block.
11467 if (CLI.IsTailCall) {
11468 CLI.DAG.setRoot(CLI.Chain);
11469 return std::make_pair(x: SDValue(), y: SDValue());
11470 }
11471
11472#ifndef NDEBUG
11473 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11474 assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11475 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11476 "LowerCall emitted a value with the wrong type!");
11477 }
11478#endif
11479
11480 SmallVector<SDValue, 4> ReturnValues;
11481 if (!CanLowerReturn) {
11482 // The instruction result is the result of loading from the
11483 // hidden sret parameter.
11484 MVT PtrVT = getPointerTy(DL, AS: DL.getAllocaAddrSpace());
11485
11486 unsigned NumValues = RetVTs.size();
11487 ReturnValues.resize(N: NumValues);
11488 SmallVector<SDValue, 4> Chains(NumValues);
11489
11490 // An aggregate return value cannot wrap around the address space, so
11491 // offsets to its parts don't wrap either.
11492 MachineFunction &MF = CLI.DAG.getMachineFunction();
11493 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(ObjectIdx: DemoteStackIdx);
11494 for (unsigned i = 0; i < NumValues; ++i) {
11495 SDValue Add = CLI.DAG.getMemBasePlusOffset(
11496 Base: DemoteStackSlot, Offset: CLI.DAG.getConstant(Val: Offsets[i], DL: CLI.DL, VT: PtrVT),
11497 DL: CLI.DL, Flags: SDNodeFlags::NoUnsignedWrap);
11498 SDValue L = CLI.DAG.getLoad(
11499 VT: RetVTs[i], dl: CLI.DL, Chain: CLI.Chain, Ptr: Add,
11500 PtrInfo: MachinePointerInfo::getFixedStack(MF&: CLI.DAG.getMachineFunction(),
11501 FI: DemoteStackIdx, Offset: Offsets[i]),
11502 Alignment: HiddenSRetAlign);
11503 ReturnValues[i] = L;
11504 Chains[i] = L.getValue(R: 1);
11505 }
11506
11507 CLI.Chain = CLI.DAG.getNode(Opcode: ISD::TokenFactor, DL: CLI.DL, VT: MVT::Other, Ops: Chains);
11508 } else {
11509 // Collect the legal value parts into potentially illegal values
11510 // that correspond to the original function's return values.
11511 std::optional<ISD::NodeType> AssertOp;
11512 if (CLI.RetSExt)
11513 AssertOp = ISD::AssertSext;
11514 else if (CLI.RetZExt)
11515 AssertOp = ISD::AssertZext;
11516 unsigned CurReg = 0;
11517 for (EVT VT : RetVTs) {
11518 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CC: CLI.CallConv, VT);
11519 unsigned NumRegs =
11520 getNumRegistersForCallingConv(Context, CC: CLI.CallConv, VT);
11521
11522 ReturnValues.push_back(Elt: getCopyFromParts(
11523 DAG&: CLI.DAG, DL: CLI.DL, Parts: &InVals[CurReg], NumParts: NumRegs, PartVT: RegisterVT, ValueVT: VT, V: nullptr,
11524 InChain: CLI.Chain, CC: CLI.CallConv, AssertOp));
11525 CurReg += NumRegs;
11526 }
11527
11528 // For a function returning void, there is no return value. We can't create
11529 // such a node, so we just return a null return value in that case. In
11530 // that case, nothing will actually look at the value.
11531 if (ReturnValues.empty())
11532 return std::make_pair(x: SDValue(), y&: CLI.Chain);
11533 }
11534
11535 SDValue Res = CLI.DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: CLI.DL,
11536 VTList: CLI.DAG.getVTList(VTs: RetVTs), Ops: ReturnValues);
11537 return std::make_pair(x&: Res, y&: CLI.Chain);
11538}
11539
11540/// Places new result values for the node in Results (their number
11541/// and types must exactly match those of the original return values of
11542/// the node), or leaves Results empty, which indicates that the node is not
11543/// to be custom lowered after all.
11544void TargetLowering::LowerOperationWrapper(SDNode *N,
11545 SmallVectorImpl<SDValue> &Results,
11546 SelectionDAG &DAG) const {
11547 SDValue Res = LowerOperation(Op: SDValue(N, 0), DAG);
11548
11549 if (!Res.getNode())
11550 return;
11551
11552 // If the original node has one result, take the return value from
11553 // LowerOperation as is. It might not be result number 0.
11554 if (N->getNumValues() == 1) {
11555 Results.push_back(Elt: Res);
11556 return;
11557 }
11558
11559 // If the original node has multiple results, then the return node should
11560 // have the same number of results.
11561 assert((N->getNumValues() == Res->getNumValues()) &&
11562 "Lowering returned the wrong number of results!");
11563
11564 // Places new result values base on N result number.
11565 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11566 Results.push_back(Elt: Res.getValue(R: I));
11567}
11568
11569SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11570 llvm_unreachable("LowerOperation not implemented for this target!");
11571}
11572
11573void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11574 Register Reg,
11575 ISD::NodeType ExtendType) {
11576 SDValue Op = getNonRegisterValue(V);
11577 assert((Op.getOpcode() != ISD::CopyFromReg ||
11578 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11579 "Copy from a reg to the same reg!");
11580 assert(!Reg.isPhysical() && "Is a physreg");
11581
11582 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11583 // If this is an InlineAsm we have to match the registers required, not the
11584 // notional registers required by the type.
11585
11586 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11587 std::nullopt); // This is not an ABI copy.
11588 SDValue Chain = DAG.getEntryNode();
11589
11590 if (ExtendType == ISD::ANY_EXTEND) {
11591 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(Val: V);
11592 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11593 ExtendType = PreferredExtendIt->second;
11594 }
11595 RFV.getCopyToRegs(Val: Op, DAG, dl: getCurSDLoc(), Chain, Glue: nullptr, V, PreferredExtendType: ExtendType);
11596 PendingExports.push_back(Elt: Chain);
11597}
11598
11599#include "llvm/CodeGen/SelectionDAGISel.h"
11600
11601/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11602/// entry block, return true. This includes arguments used by switches, since
11603/// the switch may expand into multiple basic blocks.
11604static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11605 // With FastISel active, we may be splitting blocks, so force creation
11606 // of virtual registers for all non-dead arguments.
11607 if (FastISel)
11608 return A->use_empty();
11609
11610 const BasicBlock &Entry = A->getParent()->front();
11611 for (const User *U : A->users())
11612 if (cast<Instruction>(Val: U)->getParent() != &Entry || isa<SwitchInst>(Val: U))
11613 return false; // Use not in entry block.
11614
11615 return true;
11616}
11617
11618using ArgCopyElisionMapTy =
11619 DenseMap<const Argument *,
11620 std::pair<const AllocaInst *, const StoreInst *>>;
11621
11622/// Scan the entry block of the function in FuncInfo for arguments that look
11623/// like copies into a local alloca. Record any copied arguments in
11624/// ArgCopyElisionCandidates.
11625static void
11626findArgumentCopyElisionCandidates(const DataLayout &DL,
11627 FunctionLoweringInfo *FuncInfo,
11628 ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11629 // Record the state of every static alloca used in the entry block. Argument
11630 // allocas are all used in the entry block, so we need approximately as many
11631 // entries as we have arguments.
11632 enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11633 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11634 unsigned NumArgs = FuncInfo->Fn->arg_size();
11635 StaticAllocas.reserve(NumEntries: NumArgs * 2);
11636
11637 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11638 if (!V)
11639 return nullptr;
11640 V = V->stripPointerCasts();
11641 const auto *AI = dyn_cast<AllocaInst>(Val: V);
11642 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(Val: AI))
11643 return nullptr;
11644 auto Iter = StaticAllocas.insert(KV: {AI, Unknown});
11645 return &Iter.first->second;
11646 };
11647
11648 // Look for stores of arguments to static allocas. Look through bitcasts and
11649 // GEPs to handle type coercions, as long as the alloca is fully initialized
11650 // by the store. Any non-store use of an alloca escapes it and any subsequent
11651 // unanalyzed store might write it.
11652 // FIXME: Handle structs initialized with multiple stores.
11653 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11654 // Look for stores, and handle non-store uses conservatively.
11655 const auto *SI = dyn_cast<StoreInst>(Val: &I);
11656 if (!SI) {
11657 // We will look through cast uses, so ignore them completely.
11658 if (I.isCast())
11659 continue;
11660 // Ignore debug info and pseudo op intrinsics, they don't escape or store
11661 // to allocas.
11662 if (I.isDebugOrPseudoInst())
11663 continue;
11664 // This is an unknown instruction. Assume it escapes or writes to all
11665 // static alloca operands.
11666 for (const Use &U : I.operands()) {
11667 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11668 *Info = StaticAllocaInfo::Clobbered;
11669 }
11670 continue;
11671 }
11672
11673 // If the stored value is a static alloca, mark it as escaped.
11674 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11675 *Info = StaticAllocaInfo::Clobbered;
11676
11677 // Check if the destination is a static alloca.
11678 const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11679 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11680 if (!Info)
11681 continue;
11682 const AllocaInst *AI = cast<AllocaInst>(Val: Dst);
11683
11684 // Skip allocas that have been initialized or clobbered.
11685 if (*Info != StaticAllocaInfo::Unknown)
11686 continue;
11687
11688 // Check if the stored value is an argument, and that this store fully
11689 // initializes the alloca.
11690 // If the argument type has padding bits we can't directly forward a pointer
11691 // as the upper bits may contain garbage.
11692 // Don't elide copies from the same argument twice.
11693 const Value *Val = SI->getValueOperand()->stripPointerCasts();
11694 const auto *Arg = dyn_cast<Argument>(Val);
11695 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL);
11696 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11697 Arg->getType()->isEmptyTy() || !AllocaSize ||
11698 DL.getTypeStoreSize(Ty: Arg->getType()) != *AllocaSize ||
11699 !DL.typeSizeEqualsStoreSize(Ty: Arg->getType()) ||
11700 ArgCopyElisionCandidates.count(Val: Arg)) {
11701 *Info = StaticAllocaInfo::Clobbered;
11702 continue;
11703 }
11704
11705 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11706 << '\n');
11707
11708 // Mark this alloca and store for argument copy elision.
11709 *Info = StaticAllocaInfo::Elidable;
11710 ArgCopyElisionCandidates.insert(KV: {Arg, {AI, SI}});
11711
11712 // Stop scanning if we've seen all arguments. This will happen early in -O0
11713 // builds, which is useful, because -O0 builds have large entry blocks and
11714 // many allocas.
11715 if (ArgCopyElisionCandidates.size() == NumArgs)
11716 break;
11717 }
11718}
11719
11720/// Try to elide argument copies from memory into a local alloca. Succeeds if
11721/// ArgVal is a load from a suitable fixed stack object.
11722static void tryToElideArgumentCopy(
11723 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11724 DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11725 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11726 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11727 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11728 // Check if this is a load from a fixed stack object.
11729 auto *LNode = dyn_cast<LoadSDNode>(Val: ArgVals[0]);
11730 if (!LNode)
11731 return;
11732 auto *FINode = dyn_cast<FrameIndexSDNode>(Val: LNode->getBasePtr().getNode());
11733 if (!FINode)
11734 return;
11735
11736 // Check that the fixed stack object is the right size and alignment.
11737 // Look at the alignment that the user wrote on the alloca instead of looking
11738 // at the stack object.
11739 auto ArgCopyIter = ArgCopyElisionCandidates.find(Val: &Arg);
11740 assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11741 const AllocaInst *AI = ArgCopyIter->second.first;
11742 int FixedIndex = FINode->getIndex();
11743 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11744 int OldIndex = AllocaIndex;
11745 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11746 if (MFI.getObjectSize(ObjectIdx: FixedIndex) != MFI.getObjectSize(ObjectIdx: OldIndex)) {
11747 LLVM_DEBUG(
11748 dbgs() << " argument copy elision failed due to bad fixed stack "
11749 "object size\n");
11750 return;
11751 }
11752 Align RequiredAlignment = AI->getAlign();
11753 if (MFI.getObjectAlign(ObjectIdx: FixedIndex) < RequiredAlignment) {
11754 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
11755 "greater than stack argument alignment ("
11756 << DebugStr(RequiredAlignment) << " vs "
11757 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11758 return;
11759 }
11760
11761 // Perform the elision. Delete the old stack object and replace its only use
11762 // in the variable info map. Mark the stack object as mutable and aliased.
11763 LLVM_DEBUG({
11764 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11765 << " Replacing frame index " << OldIndex << " with " << FixedIndex
11766 << '\n';
11767 });
11768 MFI.RemoveStackObject(ObjectIdx: OldIndex);
11769 MFI.setIsImmutableObjectIndex(ObjectIdx: FixedIndex, IsImmutable: false);
11770 MFI.setIsAliasedObjectIndex(ObjectIdx: FixedIndex, IsAliased: true);
11771 AllocaIndex = FixedIndex;
11772 ArgCopyElisionFrameIndexMap.insert(KV: {OldIndex, FixedIndex});
11773 for (SDValue ArgVal : ArgVals)
11774 Chains.push_back(Elt: ArgVal.getValue(R: 1));
11775
11776 // Avoid emitting code for the store implementing the copy.
11777 const StoreInst *SI = ArgCopyIter->second.second;
11778 ElidedArgCopyInstrs.insert(Ptr: SI);
11779
11780 // Check for uses of the argument again so that we can avoid exporting ArgVal
11781 // if it is't used by anything other than the store.
11782 for (const Value *U : Arg.users()) {
11783 if (U != SI) {
11784 ArgHasUses = true;
11785 break;
11786 }
11787 }
11788}
11789
11790void SelectionDAGISel::LowerArguments(const Function &F) {
11791 SelectionDAG &DAG = SDB->DAG;
11792 SDLoc dl = SDB->getCurSDLoc();
11793 const DataLayout &DL = DAG.getDataLayout();
11794 SmallVector<ISD::InputArg, 16> Ins;
11795
11796 // In Naked functions we aren't going to save any registers.
11797 if (F.hasFnAttribute(Kind: Attribute::Naked))
11798 return;
11799
11800 if (!FuncInfo->CanLowerReturn) {
11801 // Put in an sret pointer parameter before all the other parameters.
11802 MVT ValueVT = TLI->getPointerTy(DL, AS: DL.getAllocaAddrSpace());
11803
11804 ISD::ArgFlagsTy Flags;
11805 Flags.setSRet();
11806 MVT RegisterVT = TLI->getRegisterType(Context&: *DAG.getContext(), VT: ValueVT);
11807 ISD::InputArg RetArg(Flags, RegisterVT, ValueVT, F.getReturnType(), true,
11808 ISD::InputArg::NoArgIndex, 0);
11809 Ins.push_back(Elt: RetArg);
11810 }
11811
11812 // Look for stores of arguments to static allocas. Mark such arguments with a
11813 // flag to ask the target to give us the memory location of that argument if
11814 // available.
11815 ArgCopyElisionMapTy ArgCopyElisionCandidates;
11816 findArgumentCopyElisionCandidates(DL, FuncInfo: FuncInfo.get(),
11817 ArgCopyElisionCandidates);
11818
11819 // Set up the incoming argument description vector.
11820 for (const Argument &Arg : F.args()) {
11821 unsigned ArgNo = Arg.getArgNo();
11822 SmallVector<Type *, 4> Types;
11823 ComputeValueTypes(DL: DAG.getDataLayout(), Ty: Arg.getType(), Types);
11824 bool isArgValueUsed = !Arg.use_empty();
11825 Type *FinalType = Arg.getType();
11826 if (Arg.hasAttribute(Kind: Attribute::ByVal))
11827 FinalType = Arg.getParamByValType();
11828 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11829 Ty: FinalType, CallConv: F.getCallingConv(), isVarArg: F.isVarArg(), DL);
11830 for (unsigned Value = 0, NumValues = Types.size(); Value != NumValues;
11831 ++Value) {
11832 Type *ArgTy = Types[Value];
11833 EVT VT = TLI->getValueType(DL, Ty: ArgTy);
11834 ISD::ArgFlagsTy Flags;
11835
11836 if (ArgTy->isPointerTy()) {
11837 Flags.setPointer();
11838 Flags.setPointerAddrSpace(cast<PointerType>(Val: ArgTy)->getAddressSpace());
11839 }
11840 if (Arg.hasAttribute(Kind: Attribute::ZExt))
11841 Flags.setZExt();
11842 if (Arg.hasAttribute(Kind: Attribute::SExt))
11843 Flags.setSExt();
11844 if (Arg.hasAttribute(Kind: Attribute::InReg)) {
11845 // If we are using vectorcall calling convention, a structure that is
11846 // passed InReg - is surely an HVA
11847 if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11848 isa<StructType>(Val: Arg.getType())) {
11849 // The first value of a structure is marked
11850 if (0 == Value)
11851 Flags.setHvaStart();
11852 Flags.setHva();
11853 }
11854 // Set InReg Flag
11855 Flags.setInReg();
11856 }
11857 if (Arg.hasAttribute(Kind: Attribute::StructRet))
11858 Flags.setSRet();
11859 if (Arg.hasAttribute(Kind: Attribute::SwiftSelf))
11860 Flags.setSwiftSelf();
11861 if (Arg.hasAttribute(Kind: Attribute::SwiftAsync))
11862 Flags.setSwiftAsync();
11863 if (Arg.hasAttribute(Kind: Attribute::SwiftError))
11864 Flags.setSwiftError();
11865 if (Arg.hasAttribute(Kind: Attribute::ByVal))
11866 Flags.setByVal();
11867 if (Arg.hasAttribute(Kind: Attribute::ByRef))
11868 Flags.setByRef();
11869 if (Arg.hasAttribute(Kind: Attribute::InAlloca)) {
11870 Flags.setInAlloca();
11871 // Set the byval flag for CCAssignFn callbacks that don't know about
11872 // inalloca. This way we can know how many bytes we should've allocated
11873 // and how many bytes a callee cleanup function will pop. If we port
11874 // inalloca to more targets, we'll have to add custom inalloca handling
11875 // in the various CC lowering callbacks.
11876 Flags.setByVal();
11877 }
11878 if (Arg.hasAttribute(Kind: Attribute::Preallocated)) {
11879 Flags.setPreallocated();
11880 // Set the byval flag for CCAssignFn callbacks that don't know about
11881 // preallocated. This way we can know how many bytes we should've
11882 // allocated and how many bytes a callee cleanup function will pop. If
11883 // we port preallocated to more targets, we'll have to add custom
11884 // preallocated handling in the various CC lowering callbacks.
11885 Flags.setByVal();
11886 }
11887
11888 // Certain targets (such as MIPS), may have a different ABI alignment
11889 // for a type depending on the context. Give the target a chance to
11890 // specify the alignment it wants.
11891 const Align OriginalAlignment(
11892 TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11893 Flags.setOrigAlign(OriginalAlignment);
11894
11895 Align MemAlign;
11896 Type *ArgMemTy = nullptr;
11897 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11898 Flags.isByRef()) {
11899 if (!ArgMemTy)
11900 ArgMemTy = Arg.getPointeeInMemoryValueType();
11901
11902 uint64_t MemSize = DL.getTypeAllocSize(Ty: ArgMemTy);
11903
11904 // For in-memory arguments, size and alignment should be passed from FE.
11905 // BE will guess if this info is not there but there are cases it cannot
11906 // get right.
11907 if (auto ParamAlign = Arg.getParamStackAlign())
11908 MemAlign = *ParamAlign;
11909 else if ((ParamAlign = Arg.getParamAlign()))
11910 MemAlign = *ParamAlign;
11911 else
11912 MemAlign = TLI->getByValTypeAlignment(Ty: ArgMemTy, DL);
11913 if (Flags.isByRef())
11914 Flags.setByRefSize(MemSize);
11915 else
11916 Flags.setByValSize(MemSize);
11917 } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11918 MemAlign = *ParamAlign;
11919 } else {
11920 MemAlign = OriginalAlignment;
11921 }
11922 Flags.setMemAlign(MemAlign);
11923
11924 if (Arg.hasAttribute(Kind: Attribute::Nest))
11925 Flags.setNest();
11926 if (NeedsRegBlock)
11927 Flags.setInConsecutiveRegs();
11928 if (ArgCopyElisionCandidates.count(Val: &Arg))
11929 Flags.setCopyElisionCandidate();
11930 if (Arg.hasAttribute(Kind: Attribute::Returned))
11931 Flags.setReturned();
11932
11933 MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11934 Context&: *CurDAG->getContext(), CC: F.getCallingConv(), VT);
11935 unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11936 Context&: *CurDAG->getContext(), CC: F.getCallingConv(), VT);
11937 for (unsigned i = 0; i != NumRegs; ++i) {
11938 // For scalable vectors, use the minimum size; individual targets
11939 // are responsible for handling scalable vector arguments and
11940 // return values.
11941 ISD::InputArg MyFlags(
11942 Flags, RegisterVT, VT, ArgTy, isArgValueUsed, ArgNo,
11943 i * RegisterVT.getStoreSize().getKnownMinValue());
11944 if (NumRegs > 1 && i == 0)
11945 MyFlags.Flags.setSplit();
11946 // if it isn't first piece, alignment must be 1
11947 else if (i > 0) {
11948 MyFlags.Flags.setOrigAlign(Align(1));
11949 if (i == NumRegs - 1)
11950 MyFlags.Flags.setSplitEnd();
11951 }
11952 Ins.push_back(Elt: MyFlags);
11953 }
11954 if (NeedsRegBlock && Value == NumValues - 1)
11955 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11956 }
11957 }
11958
11959 // Call the target to set up the argument values.
11960 SmallVector<SDValue, 8> InVals;
11961 SDValue NewRoot = TLI->LowerFormalArguments(
11962 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11963
11964 // Verify that the target's LowerFormalArguments behaved as expected.
11965 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11966 "LowerFormalArguments didn't return a valid chain!");
11967 assert(InVals.size() == Ins.size() &&
11968 "LowerFormalArguments didn't emit the correct number of values!");
11969 LLVM_DEBUG({
11970 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11971 assert(InVals[i].getNode() &&
11972 "LowerFormalArguments emitted a null value!");
11973 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11974 "LowerFormalArguments emitted a value with the wrong type!");
11975 }
11976 });
11977
11978 // Update the DAG with the new chain value resulting from argument lowering.
11979 DAG.setRoot(NewRoot);
11980
11981 // Set up the argument values.
11982 unsigned i = 0;
11983 if (!FuncInfo->CanLowerReturn) {
11984 // Create a virtual register for the sret pointer, and put in a copy
11985 // from the sret argument into it.
11986 MVT VT = TLI->getPointerTy(DL, AS: DL.getAllocaAddrSpace());
11987 MVT RegVT = TLI->getRegisterType(Context&: *CurDAG->getContext(), VT);
11988 std::optional<ISD::NodeType> AssertOp;
11989 SDValue ArgValue =
11990 getCopyFromParts(DAG, DL: dl, Parts: &InVals[0], NumParts: 1, PartVT: RegVT, ValueVT: VT, V: nullptr, InChain: NewRoot,
11991 CC: F.getCallingConv(), AssertOp);
11992
11993 MachineFunction& MF = SDB->DAG.getMachineFunction();
11994 MachineRegisterInfo& RegInfo = MF.getRegInfo();
11995 Register SRetReg =
11996 RegInfo.createVirtualRegister(RegClass: TLI->getRegClassFor(VT: RegVT));
11997 FuncInfo->DemoteRegister = SRetReg;
11998 NewRoot =
11999 SDB->DAG.getCopyToReg(Chain: NewRoot, dl: SDB->getCurSDLoc(), Reg: SRetReg, N: ArgValue);
12000 DAG.setRoot(NewRoot);
12001
12002 // i indexes lowered arguments. Bump it past the hidden sret argument.
12003 ++i;
12004 }
12005
12006 SmallVector<SDValue, 4> Chains;
12007 DenseMap<int, int> ArgCopyElisionFrameIndexMap;
12008 for (const Argument &Arg : F.args()) {
12009 SmallVector<SDValue, 4> ArgValues;
12010 SmallVector<EVT, 4> ValueVTs;
12011 ComputeValueVTs(TLI: *TLI, DL: DAG.getDataLayout(), Ty: Arg.getType(), ValueVTs);
12012 unsigned NumValues = ValueVTs.size();
12013 if (NumValues == 0)
12014 continue;
12015
12016 bool ArgHasUses = !Arg.use_empty();
12017
12018 // Elide the copying store if the target loaded this argument from a
12019 // suitable fixed stack object.
12020 if (Ins[i].Flags.isCopyElisionCandidate()) {
12021 unsigned NumParts = 0;
12022 for (EVT VT : ValueVTs)
12023 NumParts += TLI->getNumRegistersForCallingConv(Context&: *CurDAG->getContext(),
12024 CC: F.getCallingConv(), VT);
12025
12026 tryToElideArgumentCopy(FuncInfo&: *FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
12027 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
12028 ArgVals: ArrayRef(&InVals[i], NumParts), ArgHasUses);
12029 }
12030
12031 // If this argument is unused then remember its value. It is used to generate
12032 // debugging information.
12033 bool isSwiftErrorArg =
12034 TLI->supportSwiftError() &&
12035 Arg.hasAttribute(Kind: Attribute::SwiftError);
12036 if (!ArgHasUses && !isSwiftErrorArg) {
12037 SDB->setUnusedArgValue(V: &Arg, NewN: InVals[i]);
12038
12039 // Also remember any frame index for use in FastISel.
12040 if (FrameIndexSDNode *FI =
12041 dyn_cast<FrameIndexSDNode>(Val: InVals[i].getNode()))
12042 FuncInfo->setArgumentFrameIndex(A: &Arg, FI: FI->getIndex());
12043 }
12044
12045 for (unsigned Val = 0; Val != NumValues; ++Val) {
12046 EVT VT = ValueVTs[Val];
12047 MVT PartVT = TLI->getRegisterTypeForCallingConv(Context&: *CurDAG->getContext(),
12048 CC: F.getCallingConv(), VT);
12049 unsigned NumParts = TLI->getNumRegistersForCallingConv(
12050 Context&: *CurDAG->getContext(), CC: F.getCallingConv(), VT);
12051
12052 // Even an apparent 'unused' swifterror argument needs to be returned. So
12053 // we do generate a copy for it that can be used on return from the
12054 // function.
12055 if (ArgHasUses || isSwiftErrorArg) {
12056 std::optional<ISD::NodeType> AssertOp;
12057 if (Arg.hasAttribute(Kind: Attribute::SExt))
12058 AssertOp = ISD::AssertSext;
12059 else if (Arg.hasAttribute(Kind: Attribute::ZExt))
12060 AssertOp = ISD::AssertZext;
12061
12062 SDValue OutVal =
12063 getCopyFromParts(DAG, DL: dl, Parts: &InVals[i], NumParts, PartVT, ValueVT: VT, V: nullptr,
12064 InChain: NewRoot, CC: F.getCallingConv(), AssertOp);
12065
12066 FPClassTest NoFPClass = Arg.getNoFPClass();
12067 if (NoFPClass != fcNone) {
12068 SDValue SDNoFPClass = DAG.getTargetConstant(
12069 Val: static_cast<uint64_t>(NoFPClass), DL: dl, VT: MVT::i32);
12070 OutVal = DAG.getNode(Opcode: ISD::AssertNoFPClass, DL: dl, VT: OutVal.getValueType(),
12071 N1: OutVal, N2: SDNoFPClass);
12072 }
12073 ArgValues.push_back(Elt: OutVal);
12074 }
12075
12076 i += NumParts;
12077 }
12078
12079 // We don't need to do anything else for unused arguments.
12080 if (ArgValues.empty())
12081 continue;
12082
12083 // Note down frame index.
12084 if (FrameIndexSDNode *FI =
12085 dyn_cast<FrameIndexSDNode>(Val: ArgValues[0].getNode()))
12086 FuncInfo->setArgumentFrameIndex(A: &Arg, FI: FI->getIndex());
12087
12088 SDValue Res = DAG.getMergeValues(Ops: ArrayRef(ArgValues.data(), NumValues),
12089 dl: SDB->getCurSDLoc());
12090
12091 SDB->setValue(V: &Arg, NewN: Res);
12092 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
12093 // We want to associate the argument with the frame index, among
12094 // involved operands, that correspond to the lowest address. The
12095 // getCopyFromParts function, called earlier, is swapping the order of
12096 // the operands to BUILD_PAIR depending on endianness. The result of
12097 // that swapping is that the least significant bits of the argument will
12098 // be in the first operand of the BUILD_PAIR node, and the most
12099 // significant bits will be in the second operand.
12100 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
12101 if (LoadSDNode *LNode =
12102 dyn_cast<LoadSDNode>(Val: Res.getOperand(i: LowAddressOp).getNode()))
12103 if (FrameIndexSDNode *FI =
12104 dyn_cast<FrameIndexSDNode>(Val: LNode->getBasePtr().getNode()))
12105 FuncInfo->setArgumentFrameIndex(A: &Arg, FI: FI->getIndex());
12106 }
12107
12108 // Analyses past this point are naive and don't expect an assertion.
12109 if (Res.getOpcode() == ISD::AssertZext)
12110 Res = Res.getOperand(i: 0);
12111
12112 // Update the SwiftErrorVRegDefMap.
12113 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
12114 Register Reg = cast<RegisterSDNode>(Val: Res.getOperand(i: 1))->getReg();
12115 if (Reg.isVirtual())
12116 SwiftError->setCurrentVReg(MBB: FuncInfo->MBB, SwiftError->getFunctionArg(),
12117 Reg);
12118 }
12119
12120 // If this argument is live outside of the entry block, insert a copy from
12121 // wherever we got it to the vreg that other BB's will reference it as.
12122 if (Res.getOpcode() == ISD::CopyFromReg) {
12123 // If we can, though, try to skip creating an unnecessary vreg.
12124 // FIXME: This isn't very clean... it would be nice to make this more
12125 // general.
12126 Register Reg = cast<RegisterSDNode>(Val: Res.getOperand(i: 1))->getReg();
12127 if (Reg.isVirtual()) {
12128 FuncInfo->ValueMap[&Arg] = Reg;
12129 continue;
12130 }
12131 }
12132 if (!isOnlyUsedInEntryBlock(A: &Arg, FastISel: TM.Options.EnableFastISel)) {
12133 FuncInfo->InitializeRegForValue(V: &Arg);
12134 SDB->CopyToExportRegsIfNeeded(V: &Arg);
12135 }
12136 }
12137
12138 if (!Chains.empty()) {
12139 Chains.push_back(Elt: NewRoot);
12140 NewRoot = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: Chains);
12141 }
12142
12143 DAG.setRoot(NewRoot);
12144
12145 assert(i == InVals.size() && "Argument register count mismatch!");
12146
12147 // If any argument copy elisions occurred and we have debug info, update the
12148 // stale frame indices used in the dbg.declare variable info table.
12149 if (!ArgCopyElisionFrameIndexMap.empty()) {
12150 for (MachineFunction::VariableDbgInfo &VI :
12151 MF->getInStackSlotVariableDbgInfo()) {
12152 auto I = ArgCopyElisionFrameIndexMap.find(Val: VI.getStackSlot());
12153 if (I != ArgCopyElisionFrameIndexMap.end())
12154 VI.updateStackSlot(NewSlot: I->second);
12155 }
12156 }
12157
12158 // Finally, if the target has anything special to do, allow it to do so.
12159 emitFunctionEntryCode();
12160}
12161
12162/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
12163/// ensure constants are generated when needed. Remember the virtual registers
12164/// that need to be added to the Machine PHI nodes as input. We cannot just
12165/// directly add them, because expansion might result in multiple MBB's for one
12166/// BB. As such, the start of the BB might correspond to a different MBB than
12167/// the end.
12168void
12169SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
12170 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12171
12172 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
12173
12174 // Check PHI nodes in successors that expect a value to be available from this
12175 // block.
12176 for (const BasicBlock *SuccBB : successors(I: LLVMBB->getTerminator())) {
12177 if (!isa<PHINode>(Val: SuccBB->begin())) continue;
12178 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(BB: SuccBB);
12179
12180 // If this terminator has multiple identical successors (common for
12181 // switches), only handle each succ once.
12182 if (!SuccsHandled.insert(Ptr: SuccMBB).second)
12183 continue;
12184
12185 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
12186
12187 // At this point we know that there is a 1-1 correspondence between LLVM PHI
12188 // nodes and Machine PHI nodes, but the incoming operands have not been
12189 // emitted yet.
12190 for (const PHINode &PN : SuccBB->phis()) {
12191 // Ignore dead phi's.
12192 if (PN.use_empty())
12193 continue;
12194
12195 // Skip empty types
12196 if (PN.getType()->isEmptyTy())
12197 continue;
12198
12199 Register Reg;
12200 const Value *PHIOp = PN.getIncomingValueForBlock(BB: LLVMBB);
12201
12202 if (const auto *C = dyn_cast<Constant>(Val: PHIOp)) {
12203 Register &RegOut = ConstantsOut[C];
12204 if (!RegOut) {
12205 RegOut = FuncInfo.CreateRegs(V: &PN);
12206 // We need to zero/sign extend ConstantInt phi operands to match
12207 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
12208 ISD::NodeType ExtendType = ISD::ANY_EXTEND;
12209 if (auto *CI = dyn_cast<ConstantInt>(Val: C))
12210 ExtendType = TLI.signExtendConstant(C: CI) ? ISD::SIGN_EXTEND
12211 : ISD::ZERO_EXTEND;
12212 CopyValueToVirtualRegister(V: C, Reg: RegOut, ExtendType);
12213 }
12214 Reg = RegOut;
12215 } else {
12216 DenseMap<const Value *, Register>::iterator I =
12217 FuncInfo.ValueMap.find(Val: PHIOp);
12218 if (I != FuncInfo.ValueMap.end())
12219 Reg = I->second;
12220 else {
12221 assert(isa<AllocaInst>(PHIOp) &&
12222 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
12223 "Didn't codegen value into a register!??");
12224 Reg = FuncInfo.CreateRegs(V: &PN);
12225 CopyValueToVirtualRegister(V: PHIOp, Reg);
12226 }
12227 }
12228
12229 // Remember that this register needs to added to the machine PHI node as
12230 // the input for this MBB.
12231 SmallVector<EVT, 4> ValueVTs;
12232 ComputeValueVTs(TLI, DL: DAG.getDataLayout(), Ty: PN.getType(), ValueVTs);
12233 for (EVT VT : ValueVTs) {
12234 const unsigned NumRegisters = TLI.getNumRegisters(Context&: *DAG.getContext(), VT);
12235 for (unsigned i = 0; i != NumRegisters; ++i)
12236 FuncInfo.PHINodesToUpdate.emplace_back(args: &*MBBI++, args: Reg + i);
12237 Reg += NumRegisters;
12238 }
12239 }
12240 }
12241
12242 ConstantsOut.clear();
12243}
12244
12245MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
12246 MachineFunction::iterator I(MBB);
12247 if (++I == FuncInfo.MF->end())
12248 return nullptr;
12249 return &*I;
12250}
12251
12252/// During lowering new call nodes can be created (such as memset, etc.).
12253/// Those will become new roots of the current DAG, but complications arise
12254/// when they are tail calls. In such cases, the call lowering will update
12255/// the root, but the builder still needs to know that a tail call has been
12256/// lowered in order to avoid generating an additional return.
12257void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12258 // If the node is null, we do have a tail call.
12259 if (MaybeTC.getNode() != nullptr)
12260 DAG.setRoot(MaybeTC);
12261 else
12262 HasTailCall = true;
12263}
12264
12265void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12266 MachineBasicBlock *SwitchMBB,
12267 MachineBasicBlock *DefaultMBB) {
12268 MachineFunction *CurMF = FuncInfo.MF;
12269 MachineBasicBlock *NextMBB = nullptr;
12270 MachineFunction::iterator BBI(W.MBB);
12271 if (++BBI != FuncInfo.MF->end())
12272 NextMBB = &*BBI;
12273
12274 unsigned Size = W.LastCluster - W.FirstCluster + 1;
12275
12276 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12277
12278 if (Size == 2 && W.MBB == SwitchMBB) {
12279 // If any two of the cases has the same destination, and if one value
12280 // is the same as the other, but has one bit unset that the other has set,
12281 // use bit manipulation to do two compares at once. For example:
12282 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12283 // TODO: This could be extended to merge any 2 cases in switches with 3
12284 // cases.
12285 // TODO: Handle cases where W.CaseBB != SwitchBB.
12286 CaseCluster &Small = *W.FirstCluster;
12287 CaseCluster &Big = *W.LastCluster;
12288
12289 if (Small.Low == Small.High && Big.Low == Big.High &&
12290 Small.MBB == Big.MBB) {
12291 const APInt &SmallValue = Small.Low->getValue();
12292 const APInt &BigValue = Big.Low->getValue();
12293
12294 // Check that there is only one bit different.
12295 APInt CommonBit = BigValue ^ SmallValue;
12296 if (CommonBit.isPowerOf2()) {
12297 SDValue CondLHS = getValue(V: Cond);
12298 EVT VT = CondLHS.getValueType();
12299 SDLoc DL = getCurSDLoc();
12300
12301 SDValue Or = DAG.getNode(Opcode: ISD::OR, DL, VT, N1: CondLHS,
12302 N2: DAG.getConstant(Val: CommonBit, DL, VT));
12303 SDValue Cond = DAG.getSetCC(
12304 DL, VT: MVT::i1, LHS: Or, RHS: DAG.getConstant(Val: BigValue | SmallValue, DL, VT),
12305 Cond: ISD::SETEQ);
12306
12307 // Update successor info.
12308 // Both Small and Big will jump to Small.BB, so we sum up the
12309 // probabilities.
12310 addSuccessorWithProb(Src: SwitchMBB, Dst: Small.MBB, Prob: Small.Prob + Big.Prob);
12311 if (BPI)
12312 addSuccessorWithProb(
12313 Src: SwitchMBB, Dst: DefaultMBB,
12314 // The default destination is the first successor in IR.
12315 Prob: BPI->getEdgeProbability(Src: SwitchMBB->getBasicBlock(), IndexInSuccessors: (unsigned)0));
12316 else
12317 addSuccessorWithProb(Src: SwitchMBB, Dst: DefaultMBB);
12318
12319 // Insert the true branch.
12320 SDValue BrCond =
12321 DAG.getNode(Opcode: ISD::BRCOND, DL, VT: MVT::Other, N1: getControlRoot(), N2: Cond,
12322 N3: DAG.getBasicBlock(MBB: Small.MBB));
12323 // Insert the false branch.
12324 BrCond = DAG.getNode(Opcode: ISD::BR, DL, VT: MVT::Other, N1: BrCond,
12325 N2: DAG.getBasicBlock(MBB: DefaultMBB));
12326
12327 DAG.setRoot(BrCond);
12328 return;
12329 }
12330 }
12331 }
12332
12333 if (TM.getOptLevel() != CodeGenOptLevel::None) {
12334 // Here, we order cases by probability so the most likely case will be
12335 // checked first. However, two clusters can have the same probability in
12336 // which case their relative ordering is non-deterministic. So we use Low
12337 // as a tie-breaker as clusters are guaranteed to never overlap.
12338 llvm::sort(Start: W.FirstCluster, End: W.LastCluster + 1,
12339 Comp: [](const CaseCluster &a, const CaseCluster &b) {
12340 return a.Prob != b.Prob ?
12341 a.Prob > b.Prob :
12342 a.Low->getValue().slt(RHS: b.Low->getValue());
12343 });
12344
12345 // Rearrange the case blocks so that the last one falls through if possible
12346 // without changing the order of probabilities.
12347 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12348 --I;
12349 if (I->Prob > W.LastCluster->Prob)
12350 break;
12351 if (I->Kind == CC_Range && I->MBB == NextMBB) {
12352 std::swap(a&: *I, b&: *W.LastCluster);
12353 break;
12354 }
12355 }
12356 }
12357
12358 // Compute total probability.
12359 BranchProbability DefaultProb = W.DefaultProb;
12360 BranchProbability UnhandledProbs = DefaultProb;
12361 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12362 UnhandledProbs += I->Prob;
12363
12364 MachineBasicBlock *CurMBB = W.MBB;
12365 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12366 bool FallthroughUnreachable = false;
12367 MachineBasicBlock *Fallthrough;
12368 if (I == W.LastCluster) {
12369 // For the last cluster, fall through to the default destination.
12370 Fallthrough = DefaultMBB;
12371 FallthroughUnreachable = isa<UnreachableInst>(
12372 Val: DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12373 } else {
12374 Fallthrough = CurMF->CreateMachineBasicBlock(BB: CurMBB->getBasicBlock());
12375 CurMF->insert(MBBI: BBI, MBB: Fallthrough);
12376 // Put Cond in a virtual register to make it available from the new blocks.
12377 ExportFromCurrentBlock(V: Cond);
12378 }
12379 UnhandledProbs -= I->Prob;
12380
12381 switch (I->Kind) {
12382 case CC_JumpTable: {
12383 // FIXME: Optimize away range check based on pivot comparisons.
12384 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12385 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12386
12387 // The jump block hasn't been inserted yet; insert it here.
12388 MachineBasicBlock *JumpMBB = JT->MBB;
12389 CurMF->insert(MBBI: BBI, MBB: JumpMBB);
12390
12391 auto JumpProb = I->Prob;
12392 auto FallthroughProb = UnhandledProbs;
12393
12394 // If the default statement is a target of the jump table, we evenly
12395 // distribute the default probability to successors of CurMBB. Also
12396 // update the probability on the edge from JumpMBB to Fallthrough.
12397 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12398 SE = JumpMBB->succ_end();
12399 SI != SE; ++SI) {
12400 if (*SI == DefaultMBB) {
12401 JumpProb += DefaultProb / 2;
12402 FallthroughProb -= DefaultProb / 2;
12403 JumpMBB->setSuccProbability(I: SI, Prob: DefaultProb / 2);
12404 JumpMBB->normalizeSuccProbs();
12405 break;
12406 }
12407 }
12408
12409 // If the default clause is unreachable, propagate that knowledge into
12410 // JTH->FallthroughUnreachable which will use it to suppress the range
12411 // check.
12412 //
12413 // However, don't do this if we're doing branch target enforcement,
12414 // because a table branch _without_ a range check can be a tempting JOP
12415 // gadget - out-of-bounds inputs that are impossible in correct
12416 // execution become possible again if an attacker can influence the
12417 // control flow. So if an attacker doesn't already have a BTI bypass
12418 // available, we don't want them to be able to get one out of this
12419 // table branch.
12420 if (FallthroughUnreachable) {
12421 Function &CurFunc = CurMF->getFunction();
12422 if (!CurFunc.hasFnAttribute(Kind: "branch-target-enforcement"))
12423 JTH->FallthroughUnreachable = true;
12424 }
12425
12426 if (!JTH->FallthroughUnreachable)
12427 addSuccessorWithProb(Src: CurMBB, Dst: Fallthrough, Prob: FallthroughProb);
12428 addSuccessorWithProb(Src: CurMBB, Dst: JumpMBB, Prob: JumpProb);
12429 CurMBB->normalizeSuccProbs();
12430
12431 // The jump table header will be inserted in our current block, do the
12432 // range check, and fall through to our fallthrough block.
12433 JTH->HeaderBB = CurMBB;
12434 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12435
12436 // If we're in the right place, emit the jump table header right now.
12437 if (CurMBB == SwitchMBB) {
12438 visitJumpTableHeader(JT&: *JT, JTH&: *JTH, SwitchBB: SwitchMBB);
12439 JTH->Emitted = true;
12440 }
12441 break;
12442 }
12443 case CC_BitTests: {
12444 // FIXME: Optimize away range check based on pivot comparisons.
12445 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12446
12447 // The bit test blocks haven't been inserted yet; insert them here.
12448 for (BitTestCase &BTC : BTB->Cases)
12449 CurMF->insert(MBBI: BBI, MBB: BTC.ThisBB);
12450
12451 // Fill in fields of the BitTestBlock.
12452 BTB->Parent = CurMBB;
12453 BTB->Default = Fallthrough;
12454
12455 BTB->DefaultProb = UnhandledProbs;
12456 // If the cases in bit test don't form a contiguous range, we evenly
12457 // distribute the probability on the edge to Fallthrough to two
12458 // successors of CurMBB.
12459 if (!BTB->ContiguousRange) {
12460 BTB->Prob += DefaultProb / 2;
12461 BTB->DefaultProb -= DefaultProb / 2;
12462 }
12463
12464 if (FallthroughUnreachable)
12465 BTB->FallthroughUnreachable = true;
12466
12467 // If we're in the right place, emit the bit test header right now.
12468 if (CurMBB == SwitchMBB) {
12469 visitBitTestHeader(B&: *BTB, SwitchBB: SwitchMBB);
12470 BTB->Emitted = true;
12471 }
12472 break;
12473 }
12474 case CC_Range: {
12475 const Value *RHS, *LHS, *MHS;
12476 ISD::CondCode CC;
12477 if (I->Low == I->High) {
12478 // Check Cond == I->Low.
12479 CC = ISD::SETEQ;
12480 LHS = Cond;
12481 RHS=I->Low;
12482 MHS = nullptr;
12483 } else {
12484 // Check I->Low <= Cond <= I->High.
12485 CC = ISD::SETLE;
12486 LHS = I->Low;
12487 MHS = Cond;
12488 RHS = I->High;
12489 }
12490
12491 // If Fallthrough is unreachable, fold away the comparison.
12492 if (FallthroughUnreachable)
12493 CC = ISD::SETTRUE;
12494
12495 // The false probability is the sum of all unhandled cases.
12496 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12497 getCurSDLoc(), I->Prob, UnhandledProbs);
12498
12499 if (CurMBB == SwitchMBB)
12500 visitSwitchCase(CB, SwitchBB: SwitchMBB);
12501 else
12502 SL->SwitchCases.push_back(x: CB);
12503
12504 break;
12505 }
12506 }
12507 CurMBB = Fallthrough;
12508 }
12509}
12510
12511void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12512 const SwitchWorkListItem &W,
12513 Value *Cond,
12514 MachineBasicBlock *SwitchMBB) {
12515 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12516 "Clusters not sorted?");
12517 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12518
12519 auto [LastLeft, FirstRight, LeftProb, RightProb] =
12520 SL->computeSplitWorkItemInfo(W);
12521
12522 // Use the first element on the right as pivot since we will make less-than
12523 // comparisons against it.
12524 CaseClusterIt PivotCluster = FirstRight;
12525 assert(PivotCluster > W.FirstCluster);
12526 assert(PivotCluster <= W.LastCluster);
12527
12528 CaseClusterIt FirstLeft = W.FirstCluster;
12529 CaseClusterIt LastRight = W.LastCluster;
12530
12531 const ConstantInt *Pivot = PivotCluster->Low;
12532
12533 // New blocks will be inserted immediately after the current one.
12534 MachineFunction::iterator BBI(W.MBB);
12535 ++BBI;
12536
12537 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12538 // we can branch to its destination directly if it's squeezed exactly in
12539 // between the known lower bound and Pivot - 1.
12540 MachineBasicBlock *LeftMBB;
12541 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12542 FirstLeft->Low == W.GE &&
12543 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12544 LeftMBB = FirstLeft->MBB;
12545 } else {
12546 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(BB: W.MBB->getBasicBlock());
12547 FuncInfo.MF->insert(MBBI: BBI, MBB: LeftMBB);
12548 WorkList.push_back(
12549 Elt: {.MBB: LeftMBB, .FirstCluster: FirstLeft, .LastCluster: LastLeft, .GE: W.GE, .LT: Pivot, .DefaultProb: W.DefaultProb / 2});
12550 // Put Cond in a virtual register to make it available from the new blocks.
12551 ExportFromCurrentBlock(V: Cond);
12552 }
12553
12554 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12555 // single cluster, RHS.Low == Pivot, and we can branch to its destination
12556 // directly if RHS.High equals the current upper bound.
12557 MachineBasicBlock *RightMBB;
12558 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12559 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12560 RightMBB = FirstRight->MBB;
12561 } else {
12562 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(BB: W.MBB->getBasicBlock());
12563 FuncInfo.MF->insert(MBBI: BBI, MBB: RightMBB);
12564 WorkList.push_back(
12565 Elt: {.MBB: RightMBB, .FirstCluster: FirstRight, .LastCluster: LastRight, .GE: Pivot, .LT: W.LT, .DefaultProb: W.DefaultProb / 2});
12566 // Put Cond in a virtual register to make it available from the new blocks.
12567 ExportFromCurrentBlock(V: Cond);
12568 }
12569
12570 // Create the CaseBlock record that will be used to lower the branch.
12571 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12572 getCurSDLoc(), LeftProb, RightProb);
12573
12574 if (W.MBB == SwitchMBB)
12575 visitSwitchCase(CB, SwitchBB: SwitchMBB);
12576 else
12577 SL->SwitchCases.push_back(x: CB);
12578}
12579
12580// Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12581// from the swith statement.
12582static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12583 BranchProbability PeeledCaseProb) {
12584 if (PeeledCaseProb == BranchProbability::getOne())
12585 return BranchProbability::getZero();
12586 BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12587
12588 uint32_t Numerator = CaseProb.getNumerator();
12589 uint32_t Denominator = SwitchProb.scale(Num: CaseProb.getDenominator());
12590 return BranchProbability(Numerator, std::max(a: Numerator, b: Denominator));
12591}
12592
12593// Try to peel the top probability case if it exceeds the threshold.
12594// Return current MachineBasicBlock for the switch statement if the peeling
12595// does not occur.
12596// If the peeling is performed, return the newly created MachineBasicBlock
12597// for the peeled switch statement. Also update Clusters to remove the peeled
12598// case. PeeledCaseProb is the BranchProbability for the peeled case.
12599MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12600 const SwitchInst &SI, CaseClusterVector &Clusters,
12601 BranchProbability &PeeledCaseProb) {
12602 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12603 // Don't perform if there is only one cluster or optimizing for size.
12604 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12605 TM.getOptLevel() == CodeGenOptLevel::None ||
12606 SwitchMBB->getParent()->getFunction().hasMinSize())
12607 return SwitchMBB;
12608
12609 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12610 unsigned PeeledCaseIndex = 0;
12611 bool SwitchPeeled = false;
12612 for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12613 CaseCluster &CC = Clusters[Index];
12614 if (CC.Prob < TopCaseProb)
12615 continue;
12616 TopCaseProb = CC.Prob;
12617 PeeledCaseIndex = Index;
12618 SwitchPeeled = true;
12619 }
12620 if (!SwitchPeeled)
12621 return SwitchMBB;
12622
12623 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12624 << TopCaseProb << "\n");
12625
12626 // Record the MBB for the peeled switch statement.
12627 MachineFunction::iterator BBI(SwitchMBB);
12628 ++BBI;
12629 MachineBasicBlock *PeeledSwitchMBB =
12630 FuncInfo.MF->CreateMachineBasicBlock(BB: SwitchMBB->getBasicBlock());
12631 FuncInfo.MF->insert(MBBI: BBI, MBB: PeeledSwitchMBB);
12632
12633 ExportFromCurrentBlock(V: SI.getCondition());
12634 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12635 SwitchWorkListItem W = {.MBB: SwitchMBB, .FirstCluster: PeeledCaseIt, .LastCluster: PeeledCaseIt,
12636 .GE: nullptr, .LT: nullptr, .DefaultProb: TopCaseProb.getCompl()};
12637 lowerWorkItem(W, Cond: SI.getCondition(), SwitchMBB, DefaultMBB: PeeledSwitchMBB);
12638
12639 Clusters.erase(position: PeeledCaseIt);
12640 for (CaseCluster &CC : Clusters) {
12641 LLVM_DEBUG(
12642 dbgs() << "Scale the probablity for one cluster, before scaling: "
12643 << CC.Prob << "\n");
12644 CC.Prob = scaleCaseProbality(CaseProb: CC.Prob, PeeledCaseProb: TopCaseProb);
12645 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12646 }
12647 PeeledCaseProb = TopCaseProb;
12648 return PeeledSwitchMBB;
12649}
12650
12651void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12652 // Extract cases from the switch.
12653 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12654 CaseClusterVector Clusters;
12655 Clusters.reserve(n: SI.getNumCases());
12656 for (auto I : SI.cases()) {
12657 MachineBasicBlock *Succ = FuncInfo.getMBB(BB: I.getCaseSuccessor());
12658 const ConstantInt *CaseVal = I.getCaseValue();
12659 BranchProbability Prob =
12660 BPI ? BPI->getEdgeProbability(Src: SI.getParent(), IndexInSuccessors: I.getSuccessorIndex())
12661 : BranchProbability(1, SI.getNumCases() + 1);
12662 Clusters.push_back(x: CaseCluster::range(Low: CaseVal, High: CaseVal, MBB: Succ, Prob));
12663 }
12664
12665 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(BB: SI.getDefaultDest());
12666
12667 // Cluster adjacent cases with the same destination. We do this at all
12668 // optimization levels because it's cheap to do and will make codegen faster
12669 // if there are many clusters.
12670 sortAndRangeify(Clusters);
12671
12672 // The branch probablity of the peeled case.
12673 BranchProbability PeeledCaseProb = BranchProbability::getZero();
12674 MachineBasicBlock *PeeledSwitchMBB =
12675 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12676
12677 // If there is only the default destination, jump there directly.
12678 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12679 if (Clusters.empty()) {
12680 assert(PeeledSwitchMBB == SwitchMBB);
12681 SwitchMBB->addSuccessor(Succ: DefaultMBB);
12682 if (DefaultMBB != NextBlock(MBB: SwitchMBB)) {
12683 DAG.setRoot(DAG.getNode(Opcode: ISD::BR, DL: getCurSDLoc(), VT: MVT::Other,
12684 N1: getControlRoot(), N2: DAG.getBasicBlock(MBB: DefaultMBB)));
12685 }
12686 return;
12687 }
12688
12689 SL->findJumpTables(Clusters, SI: &SI, SL: getCurSDLoc(), DefaultMBB, PSI: DAG.getPSI(),
12690 BFI: DAG.getBFI());
12691 SL->findBitTestClusters(Clusters, SI: &SI);
12692
12693 LLVM_DEBUG({
12694 dbgs() << "Case clusters: ";
12695 for (const CaseCluster &C : Clusters) {
12696 if (C.Kind == CC_JumpTable)
12697 dbgs() << "JT:";
12698 if (C.Kind == CC_BitTests)
12699 dbgs() << "BT:";
12700
12701 C.Low->getValue().print(dbgs(), true);
12702 if (C.Low != C.High) {
12703 dbgs() << '-';
12704 C.High->getValue().print(dbgs(), true);
12705 }
12706 dbgs() << ' ';
12707 }
12708 dbgs() << '\n';
12709 });
12710
12711 assert(!Clusters.empty());
12712 SwitchWorkList WorkList;
12713 CaseClusterIt First = Clusters.begin();
12714 CaseClusterIt Last = Clusters.end() - 1;
12715 auto DefaultProb = getEdgeProbability(Src: PeeledSwitchMBB, Dst: DefaultMBB);
12716 // Scale the branchprobability for DefaultMBB if the peel occurs and
12717 // DefaultMBB is not replaced.
12718 if (PeeledCaseProb != BranchProbability::getZero() &&
12719 DefaultMBB == FuncInfo.getMBB(BB: SI.getDefaultDest()))
12720 DefaultProb = scaleCaseProbality(CaseProb: DefaultProb, PeeledCaseProb);
12721 WorkList.push_back(
12722 Elt: {.MBB: PeeledSwitchMBB, .FirstCluster: First, .LastCluster: Last, .GE: nullptr, .LT: nullptr, .DefaultProb: DefaultProb});
12723
12724 while (!WorkList.empty()) {
12725 SwitchWorkListItem W = WorkList.pop_back_val();
12726 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12727
12728 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12729 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12730 // For optimized builds, lower large range as a balanced binary tree.
12731 splitWorkItem(WorkList, W, Cond: SI.getCondition(), SwitchMBB);
12732 continue;
12733 }
12734
12735 lowerWorkItem(W, Cond: SI.getCondition(), SwitchMBB, DefaultMBB);
12736 }
12737}
12738
12739void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12740 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12741 auto DL = getCurSDLoc();
12742 EVT ResultVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
12743 setValue(V: &I, NewN: DAG.getStepVector(DL, ResVT: ResultVT));
12744}
12745
12746void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12747 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12748 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
12749
12750 SDLoc DL = getCurSDLoc();
12751 SDValue V = getValue(V: I.getOperand(i_nocapture: 0));
12752 assert(VT == V.getValueType() && "Malformed vector.reverse!");
12753
12754 if (VT.isScalableVector()) {
12755 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::VECTOR_REVERSE, DL, VT, Operand: V));
12756 return;
12757 }
12758
12759 // Use VECTOR_SHUFFLE for the fixed-length vector
12760 // to maintain existing behavior.
12761 SmallVector<int, 8> Mask;
12762 unsigned NumElts = VT.getVectorMinNumElements();
12763 for (unsigned i = 0; i != NumElts; ++i)
12764 Mask.push_back(Elt: NumElts - 1 - i);
12765
12766 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: V, N2: DAG.getUNDEF(VT), Mask));
12767}
12768
12769void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I,
12770 unsigned Factor) {
12771 auto DL = getCurSDLoc();
12772 SDValue InVec = getValue(V: I.getOperand(i_nocapture: 0));
12773
12774 SmallVector<EVT, 4> ValueVTs;
12775 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty: I.getType(),
12776 ValueVTs);
12777
12778 EVT OutVT = ValueVTs[0];
12779 unsigned OutNumElts = OutVT.getVectorMinNumElements();
12780
12781 SmallVector<SDValue, 4> SubVecs(Factor);
12782 for (unsigned i = 0; i != Factor; ++i) {
12783 assert(ValueVTs[i] == OutVT && "Expected VTs to be the same");
12784 SubVecs[i] = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: OutVT, N1: InVec,
12785 N2: DAG.getVectorIdxConstant(Val: OutNumElts * i, DL));
12786 }
12787
12788 // Use VECTOR_SHUFFLE for fixed-length vectors with factor of 2 to benefit
12789 // from existing legalisation and combines.
12790 if (OutVT.isFixedLengthVector() && Factor == 2) {
12791 SDValue Even = DAG.getVectorShuffle(VT: OutVT, dl: DL, N1: SubVecs[0], N2: SubVecs[1],
12792 Mask: createStrideMask(Start: 0, Stride: 2, VF: OutNumElts));
12793 SDValue Odd = DAG.getVectorShuffle(VT: OutVT, dl: DL, N1: SubVecs[0], N2: SubVecs[1],
12794 Mask: createStrideMask(Start: 1, Stride: 2, VF: OutNumElts));
12795 SDValue Res = DAG.getMergeValues(Ops: {Even, Odd}, dl: getCurSDLoc());
12796 setValue(V: &I, NewN: Res);
12797 return;
12798 }
12799
12800 SDValue Res = DAG.getNode(Opcode: ISD::VECTOR_DEINTERLEAVE, DL,
12801 VTList: DAG.getVTList(VTs: ValueVTs), Ops: SubVecs);
12802 setValue(V: &I, NewN: Res);
12803}
12804
12805void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I,
12806 unsigned Factor) {
12807 auto DL = getCurSDLoc();
12808 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12809 EVT InVT = getValue(V: I.getOperand(i_nocapture: 0)).getValueType();
12810 EVT OutVT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
12811
12812 SmallVector<SDValue, 8> InVecs(Factor);
12813 for (unsigned i = 0; i < Factor; ++i) {
12814 InVecs[i] = getValue(V: I.getOperand(i_nocapture: i));
12815 assert(InVecs[i].getValueType() == InVecs[0].getValueType() &&
12816 "Expected VTs to be the same");
12817 }
12818
12819 // Use VECTOR_SHUFFLE for fixed-length vectors with factor of 2 to benefit
12820 // from existing legalisation and combines.
12821 if (OutVT.isFixedLengthVector() && Factor == 2) {
12822 unsigned NumElts = InVT.getVectorMinNumElements();
12823 SDValue V = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: OutVT, Ops: InVecs);
12824 setValue(V: &I, NewN: DAG.getVectorShuffle(VT: OutVT, dl: DL, N1: V, N2: DAG.getUNDEF(VT: OutVT),
12825 Mask: createInterleaveMask(VF: NumElts, NumVecs: 2)));
12826 return;
12827 }
12828
12829 SmallVector<EVT, 8> ValueVTs(Factor, InVT);
12830 SDValue Res =
12831 DAG.getNode(Opcode: ISD::VECTOR_INTERLEAVE, DL, VTList: DAG.getVTList(VTs: ValueVTs), Ops: InVecs);
12832
12833 SmallVector<SDValue, 8> Results(Factor);
12834 for (unsigned i = 0; i < Factor; ++i)
12835 Results[i] = Res.getValue(R: i);
12836
12837 Res = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: OutVT, Ops: Results);
12838 setValue(V: &I, NewN: Res);
12839}
12840
12841void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12842 SmallVector<EVT, 4> ValueVTs;
12843 ComputeValueVTs(TLI: DAG.getTargetLoweringInfo(), DL: DAG.getDataLayout(), Ty: I.getType(),
12844 ValueVTs);
12845 unsigned NumValues = ValueVTs.size();
12846 if (NumValues == 0) return;
12847
12848 SmallVector<SDValue, 4> Values(NumValues);
12849 SDValue Op = getValue(V: I.getOperand(i_nocapture: 0));
12850
12851 for (unsigned i = 0; i != NumValues; ++i)
12852 Values[i] = DAG.getNode(Opcode: ISD::FREEZE, DL: getCurSDLoc(), VT: ValueVTs[i],
12853 Operand: SDValue(Op.getNode(), Op.getResNo() + i));
12854
12855 setValue(V: &I, NewN: DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
12856 VTList: DAG.getVTList(VTs: ValueVTs), Ops: Values));
12857}
12858
12859void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12860 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12861 EVT VT = TLI.getValueType(DL: DAG.getDataLayout(), Ty: I.getType());
12862
12863 SDLoc DL = getCurSDLoc();
12864 SDValue V1 = getValue(V: I.getOperand(i_nocapture: 0));
12865 SDValue V2 = getValue(V: I.getOperand(i_nocapture: 1));
12866 const bool IsLeft = I.getIntrinsicID() == Intrinsic::vector_splice_left;
12867
12868 // VECTOR_SHUFFLE doesn't support a scalable or non-constant mask.
12869 if (VT.isScalableVector() || !isa<ConstantInt>(Val: I.getOperand(i_nocapture: 2))) {
12870 SDValue Offset = DAG.getZExtOrTrunc(
12871 Op: getValue(V: I.getOperand(i_nocapture: 2)), DL, VT: TLI.getVectorIdxTy(DL: DAG.getDataLayout()));
12872 setValue(V: &I, NewN: DAG.getNode(Opcode: IsLeft ? ISD::VECTOR_SPLICE_LEFT
12873 : ISD::VECTOR_SPLICE_RIGHT,
12874 DL, VT, N1: V1, N2: V2, N3: Offset));
12875 return;
12876 }
12877 uint64_t Imm = cast<ConstantInt>(Val: I.getOperand(i_nocapture: 2))->getZExtValue();
12878
12879 unsigned NumElts = VT.getVectorNumElements();
12880
12881 uint64_t Idx = IsLeft ? Imm : NumElts - Imm;
12882
12883 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12884 SmallVector<int, 8> Mask;
12885 for (unsigned i = 0; i < NumElts; ++i)
12886 Mask.push_back(Elt: Idx + i);
12887 setValue(V: &I, NewN: DAG.getVectorShuffle(VT, dl: DL, N1: V1, N2: V2, Mask));
12888}
12889
12890// Consider the following MIR after SelectionDAG, which produces output in
12891// phyregs in the first case or virtregs in the second case.
12892//
12893// INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12894// %5:gr32 = COPY $ebx
12895// %6:gr32 = COPY $edx
12896// %1:gr32 = COPY %6:gr32
12897// %0:gr32 = COPY %5:gr32
12898//
12899// INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12900// %1:gr32 = COPY %6:gr32
12901// %0:gr32 = COPY %5:gr32
12902//
12903// Given %0, we'd like to return $ebx in the first case and %5 in the second.
12904// Given %1, we'd like to return $edx in the first case and %6 in the second.
12905//
12906// If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12907// to a single virtreg (such as %0). The remaining outputs monotonically
12908// increase in virtreg number from there. If a callbr has no outputs, then it
12909// should not have a corresponding callbr landingpad; in fact, the callbr
12910// landingpad would not even be able to refer to such a callbr.
12911static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12912 MachineInstr *MI = MRI.def_begin(RegNo: Reg)->getParent();
12913 // There is definitely at least one copy.
12914 assert(MI->getOpcode() == TargetOpcode::COPY &&
12915 "start of copy chain MUST be COPY");
12916 Reg = MI->getOperand(i: 1).getReg();
12917
12918 // If the copied register in the first copy must be virtual.
12919 assert(Reg.isVirtual() && "expected COPY of virtual register");
12920 MI = MRI.def_begin(RegNo: Reg)->getParent();
12921
12922 // There may be an optional second copy.
12923 if (MI->getOpcode() == TargetOpcode::COPY) {
12924 assert(Reg.isVirtual() && "expected COPY of virtual register");
12925 Reg = MI->getOperand(i: 1).getReg();
12926 assert(Reg.isPhysical() && "expected COPY of physical register");
12927 } else {
12928 // The start of the chain must be an INLINEASM_BR.
12929 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12930 "end of copy chain MUST be INLINEASM_BR");
12931 }
12932
12933 return Reg;
12934}
12935
12936// We must do this walk rather than the simpler
12937// setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12938// otherwise we will end up with copies of virtregs only valid along direct
12939// edges.
12940void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12941 SmallVector<EVT, 8> ResultVTs;
12942 SmallVector<SDValue, 8> ResultValues;
12943 const auto *CBR =
12944 cast<CallBrInst>(Val: I.getParent()->getUniquePredecessor()->getTerminator());
12945
12946 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12947 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12948 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12949
12950 Register InitialDef = FuncInfo.ValueMap[CBR];
12951 SDValue Chain = DAG.getRoot();
12952
12953 // Re-parse the asm constraints string.
12954 TargetLowering::AsmOperandInfoVector TargetConstraints =
12955 TLI.ParseConstraints(DL: DAG.getDataLayout(), TRI, Call: *CBR);
12956 for (auto &T : TargetConstraints) {
12957 SDISelAsmOperandInfo OpInfo(T);
12958 if (OpInfo.Type != InlineAsm::isOutput)
12959 continue;
12960
12961 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12962 // individual constraint.
12963 TLI.ComputeConstraintToUse(OpInfo, Op: OpInfo.CallOperand, DAG: &DAG);
12964
12965 switch (OpInfo.ConstraintType) {
12966 case TargetLowering::C_Register:
12967 case TargetLowering::C_RegisterClass: {
12968 // Fill in OpInfo.AssignedRegs.Regs.
12969 getRegistersForValue(DAG, DL: getCurSDLoc(), OpInfo, RefOpInfo&: OpInfo);
12970
12971 // getRegistersForValue may produce 1 to many registers based on whether
12972 // the OpInfo.ConstraintVT is legal on the target or not.
12973 for (Register &Reg : OpInfo.AssignedRegs.Regs) {
12974 Register OriginalDef = FollowCopyChain(MRI, Reg: InitialDef++);
12975 if (OriginalDef.isPhysical())
12976 FuncInfo.MBB->addLiveIn(PhysReg: OriginalDef);
12977 // Update the assigned registers to use the original defs.
12978 Reg = OriginalDef;
12979 }
12980
12981 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12982 DAG, FuncInfo, dl: getCurSDLoc(), Chain, Glue: nullptr, V: CBR);
12983 ResultValues.push_back(Elt: V);
12984 ResultVTs.push_back(Elt: OpInfo.ConstraintVT);
12985 break;
12986 }
12987 case TargetLowering::C_Other: {
12988 SDValue Flag;
12989 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Glue&: Flag, DL: getCurSDLoc(),
12990 OpInfo, DAG);
12991 ++InitialDef;
12992 ResultValues.push_back(Elt: V);
12993 ResultVTs.push_back(Elt: OpInfo.ConstraintVT);
12994 break;
12995 }
12996 default:
12997 break;
12998 }
12999 }
13000 SDValue V = DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: getCurSDLoc(),
13001 VTList: DAG.getVTList(VTs: ResultVTs), Ops: ResultValues);
13002 setValue(V: &I, NewN: V);
13003}
13004