LLVM 24.0.0git
SelectionDAGBuilder.cpp
Go to the documentation of this file.
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"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.h"
26#include "llvm/Analysis/Loads.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"
65#include "llvm/IR/Constants.h"
66#include "llvm/IR/DataLayout.h"
67#include "llvm/IR/DebugInfo.h"
72#include "llvm/IR/Function.h"
74#include "llvm/IR/InlineAsm.h"
75#include "llvm/IR/InstrTypes.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"
84#include "llvm/IR/Metadata.h"
85#include "llvm/IR/Module.h"
86#include "llvm/IR/Operator.h"
89#include "llvm/IR/Statepoint.h"
90#include "llvm/IR/Type.h"
91#include "llvm/IR/User.h"
92#include "llvm/IR/Value.h"
93#include "llvm/MC/MCAsmInfo.h"
94#include "llvm/MC/MCContext.h"
99#include "llvm/Support/Debug.h"
107#include <cstddef>
108#include <limits>
109#include <optional>
110#include <tuple>
111
112using namespace llvm;
113using namespace PatternMatch;
114using namespace SwitchCG;
115
116#define DEBUG_TYPE "isel"
117
118/// LimitFloatPrecision - Generate low-precision inline sequences for
119/// some float libcalls (6, 8 or 12 bits).
120static unsigned LimitFloatPrecision;
121
122static cl::opt<bool>
123 InsertAssertAlign("insert-assert-align", cl::init(true),
124 cl::desc("Insert the experimental `assertalign` node."),
126
128 LimitFPPrecision("limit-float-precision",
129 cl::desc("Generate low-precision inline sequences "
130 "for some float libcalls"),
132 cl::init(0));
133
135 "switch-peel-threshold", cl::Hidden, cl::init(66),
136 cl::desc("Set the case probability threshold for peeling the case from a "
137 "switch statement. A value greater than 100 will void this "
138 "optimization"));
139
140// Limit the width of DAG chains. This is important in general to prevent
141// DAG-based analysis from blowing up. For example, alias analysis and
142// load clustering may not complete in reasonable time. It is difficult to
143// recognize and avoid this situation within each individual analysis, and
144// future analyses are likely to have the same behavior. Limiting DAG width is
145// the safe approach and will be especially important with global DAGs.
146//
147// MaxParallelChains default is arbitrarily high to avoid affecting
148// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
149// sequence over this should have been converted to llvm.memcpy by the
150// frontend. It is easy to induce this behavior with .ll code such as:
151// %buffer = alloca [4096 x i8]
152// %data = load [4096 x i8]* %argPtr
153// store [4096 x i8] %data, [4096 x i8]* %buffer
154static const unsigned MaxParallelChains = 64;
155
157 const SDValue *Parts, unsigned NumParts,
158 MVT PartVT, EVT ValueVT, const Value *V,
159 SDValue InChain,
160 std::optional<CallingConv::ID> CC);
161
162/// getCopyFromParts - Create a value that contains the specified legal parts
163/// combined into the value they represent. If the parts combine to a type
164/// larger than ValueVT then AssertOp can be used to specify whether the extra
165/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
166/// (ISD::AssertSext).
167static SDValue
168getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
169 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
170 SDValue InChain,
171 std::optional<CallingConv::ID> CC = std::nullopt,
172 std::optional<ISD::NodeType> AssertOp = std::nullopt) {
173 // Let the target assemble the parts if it wants to
174 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
175 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
176 PartVT, ValueVT, CC))
177 return Val;
178
179 if (ValueVT.isVector())
180 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
181 InChain, CC);
182
183 assert(NumParts > 0 && "No parts to assemble!");
184 SDValue Val = Parts[0];
185
186 if (NumParts > 1) {
187 // Assemble the value from multiple parts.
188 if (ValueVT.isInteger()) {
189 unsigned PartBits = PartVT.getSizeInBits();
190 unsigned ValueBits = ValueVT.getSizeInBits();
191
192 // Assemble the power of 2 part.
193 unsigned RoundParts = llvm::bit_floor(NumParts);
194 unsigned RoundBits = PartBits * RoundParts;
195 EVT RoundVT = RoundBits == ValueBits ?
196 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
197 SDValue Lo, Hi;
198
199 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
200
201 if (RoundParts > 2) {
202 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
203 InChain);
204 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
205 PartVT, HalfVT, V, InChain);
206 } else {
207 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
208 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
209 }
210
211 if (DAG.getDataLayout().isBigEndian())
212 std::swap(Lo, Hi);
213
214 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
215
216 if (RoundParts < NumParts) {
217 // Assemble the trailing non-power-of-2 part.
218 unsigned OddParts = NumParts - RoundParts;
219 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
220 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
221 OddVT, V, InChain, CC);
222
223 // Combine the round and odd parts.
224 Lo = Val;
225 if (DAG.getDataLayout().isBigEndian())
226 std::swap(Lo, Hi);
227 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
228 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
229 Hi = DAG.getNode(
230 ISD::SHL, DL, TotalVT, Hi,
231 DAG.getShiftAmountConstant(Lo.getValueSizeInBits(), TotalVT, DL));
232 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
233 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
234 }
235 } else if (PartVT.isFloatingPoint()) {
236 // FP split into multiple FP parts (for ppcf128)
237 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
238 "Unexpected split");
239 SDValue Lo, Hi;
240 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
241 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
242 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
243 std::swap(Lo, Hi);
244 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
245 } else {
246 // FP split into integer parts (soft fp)
247 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
248 !PartVT.isVector() && "Unexpected split");
249 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
250 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
251 InChain, CC);
252 }
253 }
254
255 // There is now one part, held in Val. Correct it to match ValueVT.
256 // PartEVT is the type of the register class that holds the value.
257 // ValueVT is the type of the inline asm operation.
258 EVT PartEVT = Val.getValueType();
259
260 if (PartEVT == ValueVT)
261 return Val;
262
263 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
264 ValueVT.bitsLT(PartEVT)) {
265 // For an FP value in an integer part, we need to truncate to the right
266 // width first.
267 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
268 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
269 }
270
271 // Handle types that have the same size.
272 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
273 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
274
275 // Handle types with different sizes.
276 if (PartEVT.isInteger() && ValueVT.isInteger()) {
277 if (ValueVT.bitsLT(PartEVT)) {
278 // For a truncate, see if we have any information to
279 // indicate whether the truncated bits will always be
280 // zero or sign-extension.
281 if (AssertOp)
282 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
283 DAG.getValueType(ValueVT));
284 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
285 }
286 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
287 }
288
289 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
290 // FP_ROUND's are always exact here.
291 if (ValueVT.bitsLT(Val.getValueType())) {
292
293 SDValue NoChange =
295
296 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
297 llvm::Attribute::StrictFP)) {
298 return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
299 DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
300 NoChange);
301 }
302
303 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
304 }
305
306 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
307 }
308
309 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
310 // then truncating.
311 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
312 ValueVT.bitsLT(PartEVT)) {
313 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
314 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
315 }
316
317 report_fatal_error("Unknown mismatch in getCopyFromParts!");
318}
319
321 const Twine &ErrMsg) {
323 if (!I)
324 return Ctx.emitError(ErrMsg);
325
326 if (const CallInst *CI = dyn_cast<CallInst>(I))
327 if (CI->isInlineAsm()) {
328 return Ctx.diagnose(DiagnosticInfoInlineAsm(
329 *CI, ErrMsg + ", possible invalid constraint for vector type"));
330 }
331
332 return Ctx.emitError(I, ErrMsg);
333}
334
335/// Emit a fatal error if the broken down registers don't match part type
336/// or count.
337static void ensureMatchedVecRegParts(unsigned NumRegs, unsigned NumParts,
338 MVT RegisterVT, MVT PartVT) {
339 if (NumRegs == NumParts && RegisterVT == PartVT)
340 return;
341
343 Twine("Part count doesn't match vector breakdown! ") + Twine(NumRegs) +
344 " registers, " + Twine(NumParts) + " parts, " + RegisterVT.getString() +
345 " RegisterVT, " + PartVT.getString() + " PartVT");
346}
347
348/// getCopyFromPartsVector - Create a value that contains the specified legal
349/// parts combined into the value they represent. If the parts combine to a
350/// type larger than ValueVT then AssertOp can be used to specify whether the
351/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
352/// ValueVT (ISD::AssertSext).
354 const SDValue *Parts, unsigned NumParts,
355 MVT PartVT, EVT ValueVT, const Value *V,
356 SDValue InChain,
357 std::optional<CallingConv::ID> CallConv) {
358 assert(ValueVT.isVector() && "Not a vector value");
359 assert(NumParts > 0 && "No parts to assemble!");
360 const bool IsABIRegCopy = CallConv.has_value();
361
362 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
363 SDValue Val = Parts[0];
364
365 // Handle a multi-element vector.
366 if (NumParts > 1) {
367 EVT IntermediateVT;
368 MVT RegisterVT;
369 unsigned NumIntermediates;
370 unsigned NumRegs;
371
372 if (IsABIRegCopy) {
374 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
375 NumIntermediates, RegisterVT);
376 } else {
377 NumRegs =
378 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
379 NumIntermediates, RegisterVT);
380 }
381
382 ensureMatchedVecRegParts(NumRegs, NumParts, RegisterVT, PartVT);
383 assert(RegisterVT.getSizeInBits() ==
384 Parts[0].getSimpleValueType().getSizeInBits() &&
385 "Part type sizes don't match!");
386
387 // Assemble the parts into intermediate operands.
388 SmallVector<SDValue, 8> Ops(NumIntermediates);
389 if (NumIntermediates == NumParts) {
390 // If the register was not expanded, truncate or copy the value,
391 // as appropriate.
392 for (unsigned i = 0; i != NumParts; ++i)
393 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
394 V, InChain, CallConv);
395 } else if (NumParts > 0) {
396 // If the intermediate type was expanded, build the intermediate
397 // operands from the parts.
398 assert(NumParts % NumIntermediates == 0 &&
399 "Must expand into a divisible number of parts!");
400 unsigned Factor = NumParts / NumIntermediates;
401 for (unsigned i = 0; i != NumIntermediates; ++i)
402 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
403 IntermediateVT, V, InChain, CallConv);
404 }
405
406 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
407 // intermediate operands.
408 EVT BuiltVectorTy =
409 IntermediateVT.isVector()
411 *DAG.getContext(), IntermediateVT.getScalarType(),
412 IntermediateVT.getVectorElementCount() * NumParts)
414 IntermediateVT.getScalarType(),
415 NumIntermediates);
416 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
418 DL, BuiltVectorTy, Ops);
419 }
420
421 // There is now one part, held in Val. Correct it to match ValueVT.
422 EVT PartEVT = Val.getValueType();
423
424 if (PartEVT == ValueVT)
425 return Val;
426
427 if (PartEVT.isVector()) {
428 // Vector/Vector bitcast.
429 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
430 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
431
432 // If the parts vector has more elements than the value vector, then we
433 // have a vector widening case (e.g. <2 x float> -> <4 x float>).
434 // Extract the elements we want.
435 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
438 (PartEVT.getVectorElementCount().isScalable() ==
439 ValueVT.getVectorElementCount().isScalable()) &&
440 "Cannot narrow, it would be a lossy transformation");
441 PartEVT =
443 ValueVT.getVectorElementCount());
444 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
445 DAG.getVectorIdxConstant(0, DL));
446 if (PartEVT == ValueVT)
447 return Val;
448 if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
449 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
450
451 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
452 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
453 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
454 }
455
456 // Promoted vector extract
457 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
458 }
459
460 // Trivial bitcast if the types are the same size and the destination
461 // vector type is legal.
462 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
463 TLI.isTypeLegal(ValueVT))
464 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
465
466 if (ValueVT.getVectorNumElements() != 1) {
467 // Certain ABIs require that vectors are passed as integers. For vectors
468 // are the same size, this is an obvious bitcast.
469 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
470 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
471 } else if (ValueVT.bitsLT(PartEVT)) {
472 const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
473 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
474 // Drop the extra bits.
475 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
476 return DAG.getBitcast(ValueVT, Val);
477 }
478
480 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
481 return DAG.getUNDEF(ValueVT);
482 }
483
484 // Handle cases such as i8 -> <1 x i1>
485 EVT ValueSVT = ValueVT.getVectorElementType();
486 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
487 unsigned ValueSize = ValueSVT.getSizeInBits();
488 if (ValueSize == PartEVT.getSizeInBits()) {
489 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
490 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
491 // It's possible a scalar floating point type gets softened to integer and
492 // then promoted to a larger integer. If PartEVT is the larger integer
493 // we need to truncate it and then bitcast to the FP type.
494 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
495 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
496 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
497 Val = DAG.getBitcast(ValueSVT, Val);
498 } else {
499 Val = ValueVT.isFloatingPoint()
500 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
501 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
502 }
503 }
504
505 return DAG.getBuildVector(ValueVT, DL, Val);
506}
507
508static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
509 SDValue Val, SDValue *Parts, unsigned NumParts,
510 MVT PartVT, const Value *V,
511 std::optional<CallingConv::ID> CallConv);
512
513/// getCopyToParts - Create a series of nodes that contain the specified value
514/// split into legal parts. If the parts contain more bits than Val, then, for
515/// integers, ExtendKind can be used to specify how to generate the extra bits.
516static void
518 unsigned NumParts, MVT PartVT, const Value *V,
519 std::optional<CallingConv::ID> CallConv = std::nullopt,
521 // Let the target split the parts if it wants to
522 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
523 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
524 CallConv))
525 return;
526 EVT ValueVT = Val.getValueType();
527
528 // Handle the vector case separately.
529 if (ValueVT.isVector())
530 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
531 CallConv);
532
533 unsigned OrigNumParts = NumParts;
535 "Copying to an illegal type!");
536
537 if (NumParts == 0)
538 return;
539
540 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
541 EVT PartEVT = PartVT;
542 if (PartEVT == ValueVT) {
543 assert(NumParts == 1 && "No-op copy with multiple parts!");
544 Parts[0] = Val;
545 return;
546 }
547
548 unsigned PartBits = PartVT.getSizeInBits();
549 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
550 // If the parts cover more bits than the value has, promote the value.
551 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
552 assert(NumParts == 1 && "Do not know what to promote to!");
553 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
554 } else {
555 if (ValueVT.isFloatingPoint()) {
556 // FP values need to be bitcast, then extended if they are being put
557 // into a larger container.
558 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
559 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
560 }
561 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
562 ValueVT.isInteger() &&
563 "Unknown mismatch!");
564 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
565 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
566 if (PartVT == MVT::x86mmx)
567 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
568 }
569 } else if (PartBits == ValueVT.getSizeInBits()) {
570 // Different types of the same size.
571 assert(NumParts == 1 && PartEVT != ValueVT);
572 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
573 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
574 // If the parts cover less bits than value has, truncate the value.
575 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
576 ValueVT.isInteger() &&
577 "Unknown mismatch!");
578 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
579 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
580 if (PartVT == MVT::x86mmx)
581 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
582 }
583
584 // The value may have changed - recompute ValueVT.
585 ValueVT = Val.getValueType();
586 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
587 "Failed to tile the value with PartVT!");
588
589 if (NumParts == 1) {
590 if (PartEVT != ValueVT) {
592 "scalar-to-vector conversion failed");
593 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
594 }
595
596 Parts[0] = Val;
597 return;
598 }
599
600 // Expand the value into multiple parts.
601 if (NumParts & (NumParts - 1)) {
602 // The number of parts is not a power of 2. Split off and copy the tail.
603 assert(PartVT.isInteger() && ValueVT.isInteger() &&
604 "Do not know what to expand to!");
605 unsigned RoundParts = llvm::bit_floor(NumParts);
606 unsigned RoundBits = RoundParts * PartBits;
607 unsigned OddParts = NumParts - RoundParts;
608 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
609 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
610
611 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
612 CallConv);
613
614 if (DAG.getDataLayout().isBigEndian())
615 // The odd parts were reversed by getCopyToParts - unreverse them.
616 std::reverse(Parts + RoundParts, Parts + NumParts);
617
618 NumParts = RoundParts;
619 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
620 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
621 }
622
623 // The number of parts is a power of 2. Repeatedly bisect the value using
624 // EXTRACT_ELEMENT.
625 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
627 ValueVT.getSizeInBits()),
628 Val);
629
630 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
631 for (unsigned i = 0; i < NumParts; i += StepSize) {
632 unsigned ThisBits = StepSize * PartBits / 2;
633 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
634 SDValue &Part0 = Parts[i];
635 SDValue &Part1 = Parts[i+StepSize/2];
636
637 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
638 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
639 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
640 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
641
642 if (ThisBits == PartBits && ThisVT != PartVT) {
643 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
644 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
645 }
646 }
647 }
648
649 if (DAG.getDataLayout().isBigEndian())
650 std::reverse(Parts, Parts + OrigNumParts);
651}
652
654 const SDLoc &DL, EVT PartVT) {
655 if (!PartVT.isVector())
656 return SDValue();
657
658 EVT ValueVT = Val.getValueType();
659 EVT PartEVT = PartVT.getVectorElementType();
660 EVT ValueEVT = ValueVT.getVectorElementType();
661 ElementCount PartNumElts = PartVT.getVectorElementCount();
662 ElementCount ValueNumElts = ValueVT.getVectorElementCount();
663
664 // We only support widening vectors with equivalent element types and
665 // fixed/scalable properties. If a target needs to widen a fixed-length type
666 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
667 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
668 PartNumElts.isScalable() != ValueNumElts.isScalable())
669 return SDValue();
670
671 // Have a try for bf16 because some targets share its ABI with fp16.
672 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
674 "Cannot widen to illegal type");
675 Val = DAG.getNode(
677 ValueVT.changeVectorElementType(*DAG.getContext(), MVT::f16), Val);
678 } else if (PartEVT != ValueEVT) {
679 return SDValue();
680 }
681
682 // Widening a scalable vector to another scalable vector is done by inserting
683 // the vector into a larger undef one.
684 if (PartNumElts.isScalable())
685 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
686 Val, DAG.getVectorIdxConstant(0, DL));
687
688 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
689 // undef elements.
691 DAG.ExtractVectorElements(Val, Ops);
692 SDValue EltUndef = DAG.getUNDEF(PartEVT);
693 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
694
695 // FIXME: Use CONCAT for 2x -> 4x.
696 return DAG.getBuildVector(PartVT, DL, Ops);
697}
698
699/// getCopyToPartsVector - Create a series of nodes that contain the specified
700/// value split into legal parts.
701static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
702 SDValue Val, SDValue *Parts, unsigned NumParts,
703 MVT PartVT, const Value *V,
704 std::optional<CallingConv::ID> CallConv) {
705 EVT ValueVT = Val.getValueType();
706 assert(ValueVT.isVector() && "Not a vector");
707 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
708 const bool IsABIRegCopy = CallConv.has_value();
709
710 if (NumParts == 1) {
711 EVT PartEVT = PartVT;
712 if (PartEVT == ValueVT) {
713 // Nothing to do.
714 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
715 // Bitconvert vector->vector case.
716 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
717 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
718 Val = Widened;
719 } else if (PartVT.isVector() &&
721 ValueVT.getVectorElementType()) &&
722 PartEVT.getVectorElementCount() ==
723 ValueVT.getVectorElementCount()) {
724
725 // Promoted vector extract
726 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
727 } else if (PartEVT.isVector() &&
728 PartEVT.getVectorElementType() !=
729 ValueVT.getVectorElementType() &&
730 TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
732 // Combination of widening and promotion.
733 EVT WidenVT =
735 PartVT.getVectorElementCount());
736 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
737 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
738 } else {
739 // Don't extract an integer from a float vector. This can happen if the
740 // FP type gets softened to integer and then promoted. The promotion
741 // prevents it from being picked up by the earlier bitcast case.
742 if (ValueVT.getVectorElementCount().isScalar() &&
743 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
744 // If we reach this condition and PartVT is FP, this means that
745 // ValueVT is also FP and both have a different size, otherwise we
746 // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
747 // would be invalid since that would mean the smaller FP type has to
748 // be extended to the larger one.
749 if (PartVT.isFloatingPoint()) {
750 Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
751 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
752 } else
753 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
754 DAG.getVectorIdxConstant(0, DL));
755 } else {
756 uint64_t ValueSize = ValueVT.getFixedSizeInBits();
757 assert(PartVT.getFixedSizeInBits() > ValueSize &&
758 "lossy conversion of vector to scalar type");
759 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
760 Val = DAG.getBitcast(IntermediateType, Val);
761 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
762 }
763 }
764
765 assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
766 Parts[0] = Val;
767 return;
768 }
769
770 // Handle a multi-element vector.
771 EVT IntermediateVT;
772 MVT RegisterVT;
773 unsigned NumIntermediates;
774 unsigned NumRegs;
775 if (IsABIRegCopy) {
777 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
778 RegisterVT);
779 } else {
780 NumRegs =
781 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
782 NumIntermediates, RegisterVT);
783 }
784
785 ensureMatchedVecRegParts(NumRegs, NumParts, RegisterVT, PartVT);
786 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
787 "Mixing scalable and fixed vectors when copying in parts");
788
789 std::optional<ElementCount> DestEltCnt;
790
791 if (IntermediateVT.isVector())
792 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
793 else
794 DestEltCnt = ElementCount::getFixed(NumIntermediates);
795
796 EVT BuiltVectorTy = EVT::getVectorVT(
797 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
798
799 if (ValueVT == BuiltVectorTy) {
800 // Nothing to do.
801 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
802 // Bitconvert vector->vector case.
803 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
804 } else {
805 if (BuiltVectorTy.getVectorElementType().bitsGT(
806 ValueVT.getVectorElementType())) {
807 // Integer promotion.
808 ValueVT = EVT::getVectorVT(*DAG.getContext(),
809 BuiltVectorTy.getVectorElementType(),
810 ValueVT.getVectorElementCount());
811 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
812 }
813
814 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
815 Val = Widened;
816 }
817 }
818
819 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
820
821 // Split the vector into intermediate operands.
822 SmallVector<SDValue, 8> Ops(NumIntermediates);
823 for (unsigned i = 0; i != NumIntermediates; ++i) {
824 if (IntermediateVT.isVector()) {
825 // This does something sensible for scalable vectors - see the
826 // definition of EXTRACT_SUBVECTOR for further details.
827 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
828 Ops[i] =
829 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
830 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
831 } else {
832 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
833 DAG.getVectorIdxConstant(i, DL));
834 }
835 }
836
837 // Split the intermediate operands into legal parts.
838 if (NumParts == NumIntermediates) {
839 // If the register was not expanded, promote or copy the value,
840 // as appropriate.
841 for (unsigned i = 0; i != NumParts; ++i)
842 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
843 } else if (NumParts > 0) {
844 // If the intermediate type was expanded, split each the value into
845 // legal parts.
846 assert(NumIntermediates != 0 && "division by zero");
847 assert(NumParts % NumIntermediates == 0 &&
848 "Must expand into a divisible number of parts!");
849 unsigned Factor = NumParts / NumIntermediates;
850 for (unsigned i = 0; i != NumIntermediates; ++i)
851 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
852 CallConv);
853 }
854}
855
856static void failForInvalidBundles(const CallBase &I, StringRef Name,
857 ArrayRef<uint32_t> AllowedBundles) {
858 if (I.hasOperandBundlesOtherThan(AllowedBundles)) {
859 ListSeparator LS;
860 std::string Error;
862 for (unsigned i = 0, e = I.getNumOperandBundles(); i != e; ++i) {
863 OperandBundleUse U = I.getOperandBundleAt(i);
864 if (!is_contained(AllowedBundles, U.getTagID()))
865 OS << LS << U.getTagName();
866 }
868 Twine("cannot lower ", Name)
869 .concat(Twine(" with arbitrary operand bundles: ", Error)));
870 }
871}
872
874 EVT valuevt, std::optional<CallingConv::ID> CC)
875 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
876 RegCount(1, regs.size()), CallConv(CC) {}
877
879 const DataLayout &DL, Register Reg, Type *Ty,
880 std::optional<CallingConv::ID> CC) {
881 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
882
883 CallConv = CC;
884
885 for (EVT ValueVT : ValueVTs) {
886 unsigned NumRegs =
888 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
889 : TLI.getNumRegisters(Context, ValueVT);
890 MVT RegisterVT =
892 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
893 : TLI.getRegisterType(Context, ValueVT);
894 for (unsigned i = 0; i != NumRegs; ++i)
895 Regs.push_back(Reg + i);
896 RegVTs.push_back(RegisterVT);
897 RegCount.push_back(NumRegs);
898 Reg = Reg.id() + NumRegs;
899 }
900}
901
903 FunctionLoweringInfo &FuncInfo,
904 const SDLoc &dl, SDValue &Chain,
905 SDValue *Glue, const Value *V) const {
906 // A Value with type {} or [0 x %t] needs no registers.
907 if (ValueVTs.empty())
908 return SDValue();
909
910 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
911
912 // Assemble the legal parts into the final values.
915 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
916 // Copy the legal parts from the registers.
917 EVT ValueVT = ValueVTs[Value];
918 unsigned NumRegs = RegCount[Value];
919 MVT RegisterVT = isABIMangled()
921 *DAG.getContext(), *CallConv, RegVTs[Value])
922 : RegVTs[Value];
923
924 Parts.resize(NumRegs);
925 for (unsigned i = 0; i != NumRegs; ++i) {
926 SDValue P;
927 if (!Glue) {
928 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
929 } else {
930 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
931 *Glue = P.getValue(2);
932 }
933
934 Chain = P.getValue(1);
935 Parts[i] = P;
936
937 // If the source register was virtual and if we know something about it,
938 // add an assert node.
939 if (!Regs[Part + i].isVirtual() || !RegisterVT.isInteger())
940 continue;
941
943 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
944 if (!LOI)
945 continue;
946
947 unsigned RegSize = RegisterVT.getScalarSizeInBits();
948 unsigned NumSignBits = LOI->NumSignBits;
949 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
950
951 if (NumZeroBits == RegSize) {
952 // The current value is a zero.
953 // Explicitly express that as it would be easier for
954 // optimizations to kick in.
955 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
956 continue;
957 }
958
959 // FIXME: We capture more information than the dag can represent. For
960 // now, just use the tightest assertzext/assertsext possible.
961 bool isSExt;
962 EVT FromVT(MVT::Other);
963 if (NumZeroBits) {
964 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
965 isSExt = false;
966 } else if (NumSignBits > 1) {
967 FromVT =
968 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
969 isSExt = true;
970 } else {
971 continue;
972 }
973 // Add an assertion node.
974 assert(FromVT != MVT::Other);
975 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
976 RegisterVT, P, DAG.getValueType(FromVT));
977 }
978
979 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
980 RegisterVT, ValueVT, V, Chain, CallConv);
981 Part += NumRegs;
982 Parts.clear();
983 }
984
985 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
986}
987
989 const SDLoc &dl, SDValue &Chain, SDValue *Glue,
990 const Value *V,
991 ISD::NodeType PreferredExtendType) const {
992 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
993 ISD::NodeType ExtendKind = PreferredExtendType;
994
995 // Get the list of the values's legal parts.
996 unsigned NumRegs = Regs.size();
997 SmallVector<SDValue, 8> Parts(NumRegs);
998 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
999 unsigned NumParts = RegCount[Value];
1000
1001 MVT RegisterVT = isABIMangled()
1003 *DAG.getContext(), *CallConv, RegVTs[Value])
1004 : RegVTs[Value];
1005
1007 if (TLI.isZExtFree(peekThroughFreeze(Val), RegisterVT))
1009
1010 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
1011 NumParts, RegisterVT, V, CallConv, ExtendKind);
1012 Part += NumParts;
1013 }
1014
1015 // Copy the parts into the registers.
1016 SmallVector<SDValue, 8> Chains(NumRegs);
1017 for (unsigned i = 0; i != NumRegs; ++i) {
1018 SDValue Part;
1019 if (!Glue) {
1020 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
1021 } else {
1022 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
1023 *Glue = Part.getValue(1);
1024 }
1025
1026 Chains[i] = Part.getValue(0);
1027 }
1028
1029 if (NumRegs == 1 || Glue)
1030 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1031 // flagged to it. That is the CopyToReg nodes and the user are considered
1032 // a single scheduling unit. If we create a TokenFactor and return it as
1033 // chain, then the TokenFactor is both a predecessor (operand) of the
1034 // user as well as a successor (the TF operands are flagged to the user).
1035 // c1, f1 = CopyToReg
1036 // c2, f2 = CopyToReg
1037 // c3 = TokenFactor c1, c2
1038 // ...
1039 // = op c3, ..., f2
1040 Chain = Chains[NumRegs-1];
1041 else
1042 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1043}
1044
1046 unsigned MatchingIdx, const SDLoc &dl,
1047 SelectionDAG &DAG,
1048 std::vector<SDValue> &Ops) const {
1049 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1050
1051 InlineAsm::Flag Flag(Code, Regs.size());
1052 if (HasMatching)
1053 Flag.setMatchingOp(MatchingIdx);
1054 else if (!Regs.empty() && Regs.front().isVirtual()) {
1055 // Put the register class of the virtual registers in the flag word. That
1056 // way, later passes can recompute register class constraints for inline
1057 // assembly as well as normal instructions.
1058 // Don't do this for tied operands that can use the regclass information
1059 // from the def.
1061 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1062 Flag.setRegClass(RC->getID());
1063 }
1064
1065 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1066 Ops.push_back(Res);
1067
1068 if (Code == InlineAsm::Kind::Clobber) {
1069 // Clobbers should always have a 1:1 mapping with registers, and may
1070 // reference registers that have illegal (e.g. vector) types. Hence, we
1071 // shouldn't try to apply any sort of splitting logic to them.
1072 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1073 "No 1:1 mapping from clobbers to regs?");
1075 (void)SP;
1076 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1077 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1078 assert(
1079 (Regs[I] != SP ||
1081 "If we clobbered the stack pointer, MFI should know about it.");
1082 }
1083 return;
1084 }
1085
1086 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1087 MVT RegisterVT = RegVTs[Value];
1088 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1089 RegisterVT);
1090 for (unsigned i = 0; i != NumRegs; ++i) {
1091 assert(Reg < Regs.size() && "Mismatch in # registers expected");
1092 Register TheReg = Regs[Reg++];
1093 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1094 }
1095 }
1096}
1097
1101 unsigned I = 0;
1102 for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1103 unsigned RegCount = std::get<0>(CountAndVT);
1104 MVT RegisterVT = std::get<1>(CountAndVT);
1105 TypeSize RegisterSize = RegisterVT.getSizeInBits();
1106 for (unsigned E = I + RegCount; I != E; ++I)
1107 OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1108 }
1109 return OutVec;
1110}
1111
1113 AssumptionCache *ac, const TargetLibraryInfo *li,
1114 const TargetTransformInfo &TTI) {
1115 BatchAA = aa;
1116 AC = ac;
1117 GFI = gfi;
1118 LibInfo = li;
1119 Context = DAG.getContext();
1120 LPadToCallSiteMap.clear();
1121 this->TTI = &TTI;
1122 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1123 AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1124 *DAG.getMachineFunction().getFunction().getParent());
1125 CanDescribeGlobalAddressInLocationList =
1126 canDescribeGlobalAddressInLocationList(DAG.getMachineFunction());
1127}
1128
1130 NodeMap.clear();
1131 UnusedArgNodeMap.clear();
1132 PendingLoads.clear();
1133 PendingExports.clear();
1134 PendingConstrainedFP.clear();
1135 PendingConstrainedFPStrict.clear();
1136 CurInst = nullptr;
1137 HasTailCall = false;
1138 SDNodeOrder = LowestSDNodeOrder;
1139 StatepointLowering.clear();
1140}
1141
1143 DanglingDebugInfoMap.clear();
1144}
1145
1146// Update DAG root to include dependencies on Pending chains.
1147SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1148 SDValue Root = DAG.getRoot();
1149
1150 if (Pending.empty())
1151 return Root;
1152
1153 // Add current root to PendingChains, unless we already indirectly
1154 // depend on it.
1155 if (Root.getOpcode() != ISD::EntryToken) {
1156 unsigned i = 0, e = Pending.size();
1157 for (; i != e; ++i) {
1158 assert(Pending[i].getNode()->getNumOperands() > 1);
1159 if (Pending[i].getNode()->getOperand(0) == Root)
1160 break; // Don't add the root if we already indirectly depend on it.
1161 }
1162
1163 if (i == e)
1164 Pending.push_back(Root);
1165 }
1166
1167 if (Pending.size() == 1)
1168 Root = Pending[0];
1169 else
1170 Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1171
1172 DAG.setRoot(Root);
1173 Pending.clear();
1174 return Root;
1175}
1176
1180
1182 // If the new exception behavior differs from that of the pending
1183 // ones, chain up them and update the root.
1184 switch (EB) {
1187 // Floating-point exceptions produced by such operations are not intended
1188 // to be observed, so the sequence of these operations does not need to be
1189 // preserved.
1190 //
1191 // They however must not be mixed with the instructions that have strict
1192 // exception behavior. Placing an operation with 'ebIgnore' behavior between
1193 // 'ebStrict' operations could distort the observed exception behavior.
1194 if (!PendingConstrainedFPStrict.empty()) {
1195 assert(PendingConstrainedFP.empty());
1196 updateRoot(PendingConstrainedFPStrict);
1197 }
1198 break;
1200 // Floating-point exception produced by these operations may be observed, so
1201 // they must be correctly chained. If trapping on FP exceptions is
1202 // disabled, the exceptions can be observed only by functions that read
1203 // exception flags, like 'llvm.get_fpenv' or 'fetestexcept'. It means that
1204 // the order of operations is not significant between barriers.
1205 //
1206 // If trapping is enabled, each operation becomes an implicit observation
1207 // point, so the operations must be sequenced according their original
1208 // source order.
1209 if (!PendingConstrainedFP.empty()) {
1210 assert(PendingConstrainedFPStrict.empty());
1211 updateRoot(PendingConstrainedFP);
1212 }
1213 // TODO: Add support for trapping-enabled scenarios.
1214 }
1215 return DAG.getRoot();
1216}
1217
1219 // Chain up all pending constrained intrinsics together with all
1220 // pending loads, by simply appending them to PendingLoads and
1221 // then calling getMemoryRoot().
1222 PendingLoads.reserve(PendingLoads.size() +
1223 PendingConstrainedFP.size() +
1224 PendingConstrainedFPStrict.size());
1225 PendingLoads.append(PendingConstrainedFP.begin(),
1226 PendingConstrainedFP.end());
1227 PendingLoads.append(PendingConstrainedFPStrict.begin(),
1228 PendingConstrainedFPStrict.end());
1229 PendingConstrainedFP.clear();
1230 PendingConstrainedFPStrict.clear();
1231 return getMemoryRoot();
1232}
1233
1235 // We need to emit pending fpexcept.strict constrained intrinsics,
1236 // so append them to the PendingExports list.
1237 PendingExports.append(PendingConstrainedFPStrict.begin(),
1238 PendingConstrainedFPStrict.end());
1239 PendingConstrainedFPStrict.clear();
1240 return updateRoot(PendingExports);
1241}
1242
1244 DILocalVariable *Variable,
1246 DebugLoc DL) {
1247 assert(Variable && "Missing variable");
1248
1249 // Check if address has undef value.
1250 if (!Address || isa<UndefValue>(Address) ||
1251 (Address->use_empty() && !isa<Argument>(Address))) {
1252 LLVM_DEBUG(
1253 dbgs()
1254 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1255 return;
1256 }
1257
1258 bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1259
1260 SDValue &N = NodeMap[Address];
1261 if (!N.getNode() && isa<Argument>(Address))
1262 // Check unused arguments map.
1263 N = UnusedArgNodeMap[Address];
1264 SDDbgValue *SDV;
1265 if (N.getNode()) {
1266 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1267 Address = BCI->getOperand(0);
1268 // Parameters are handled specially.
1269 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1270 if (IsParameter && FINode) {
1271 // Byval parameter. We have a frame index at this point.
1272 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1273 /*IsIndirect*/ true, DL, SDNodeOrder);
1274 } else if (isa<Argument>(Address)) {
1275 // Address is an argument, so try to emit its dbg value using
1276 // virtual register info from the FuncInfo.ValueMap.
1277 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1278 FuncArgumentDbgValueKind::Declare, N);
1279 return;
1280 } else {
1281 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1282 true, DL, SDNodeOrder);
1283 }
1284 DAG.AddDbgValue(SDV, IsParameter);
1285 } else {
1286 // If Address is an argument then try to emit its dbg value using
1287 // virtual register info from the FuncInfo.ValueMap.
1288 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1289 FuncArgumentDbgValueKind::Declare, N)) {
1290 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1291 << " (could not emit func-arg dbg_value)\n");
1292 }
1293 }
1294}
1295
1297 // Add SDDbgValue nodes for any var locs here. Do so before updating
1298 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1299 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1300 // Add SDDbgValue nodes for any var locs here. Do so before updating
1301 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1302 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1303 It != End; ++It) {
1304 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1305 dropDanglingDebugInfo(Var, It->Expr);
1306 if (It->Values.isKillLocation(It->Expr)) {
1307 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1308 continue;
1309 }
1310 SmallVector<Value *> Values(It->Values.location_ops());
1311 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1312 It->Values.hasArgList())) {
1313 SmallVector<Value *, 4> Vals(It->Values.location_ops());
1315 FnVarLocs->getDILocalVariable(It->VariableID),
1316 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1317 }
1318 }
1319 }
1320
1321 // We must skip DbgVariableRecords if they've already been processed above as
1322 // we have just emitted the debug values resulting from assignment tracking
1323 // analysis, making any existing DbgVariableRecords redundant (and probably
1324 // less correct). We still need to process DbgLabelRecords. This does sink
1325 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1326 // be important as it does so deterministcally and ordering between
1327 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1328 // printing).
1329 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1330 // Is there is any debug-info attached to this instruction, in the form of
1331 // DbgRecord non-instruction debug-info records.
1332 for (DbgRecord &DR : I.getDbgRecordRange()) {
1333 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1334 assert(DLR->getLabel() && "Missing label");
1335 SDDbgLabel *SDV =
1336 DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1337 DAG.AddDbgLabel(SDV);
1338 continue;
1339 }
1340
1341 if (SkipDbgVariableRecords)
1342 continue;
1344 DILocalVariable *Variable = DVR.getVariable();
1347
1349 if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1350 continue;
1351 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1352 << "\n");
1354 DVR.getDebugLoc());
1355 continue;
1356 }
1357
1358 // A DbgVariableRecord with no locations is a kill location.
1360 if (Values.empty()) {
1362 SDNodeOrder);
1363 continue;
1364 }
1365
1366 // A DbgVariableRecord with an undef or absent location is also a kill
1367 // location.
1368 if (llvm::any_of(Values,
1369 [](Value *V) { return !V || isa<UndefValue>(V); })) {
1371 SDNodeOrder);
1372 continue;
1373 }
1374
1375 bool IsVariadic = DVR.hasArgList();
1376 if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1377 SDNodeOrder, IsVariadic)) {
1378 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1379 DVR.getDebugLoc(), SDNodeOrder);
1380 }
1381 }
1382}
1383
1385 visitDbgInfo(I);
1386
1387 // Set up outgoing PHI node register values before emitting the terminator.
1388 if (I.isTerminator()) {
1389 HandlePHINodesInSuccessorBlocks(I.getParent());
1390 }
1391
1392 ++SDNodeOrder;
1393 CurInst = &I;
1394
1395 // Set inserted listener only if required.
1396 bool NodeInserted = false;
1397 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1398 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1399 MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1400 if (PCSectionsMD || MMRA) {
1401 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1402 DAG, [&](SDNode *) { NodeInserted = true; });
1403 }
1404
1405 visit(I.getOpcode(), I);
1406
1407 if (!I.isTerminator() && !HasTailCall &&
1408 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1410
1411 // Handle metadata.
1412 if (PCSectionsMD || MMRA) {
1413 auto It = NodeMap.find(&I);
1414 if (It != NodeMap.end()) {
1415 if (PCSectionsMD)
1416 DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1417 if (MMRA)
1418 DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1419 } else if (NodeInserted) {
1420 // This should not happen; if it does, don't let it go unnoticed so we can
1421 // fix it. Relevant visit*() function is probably missing a setValue().
1422 errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1423 << I.getModule()->getName() << "]\n";
1424 LLVM_DEBUG(I.dump());
1425 assert(false);
1426 }
1427 }
1428
1429 CurInst = nullptr;
1430}
1431
1432void SelectionDAGBuilder::visitPHI(const PHINode &) {
1433 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1434}
1435
1436void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1437 // Note: this doesn't use InstVisitor, because it has to work with
1438 // ConstantExpr's in addition to instructions.
1439 switch (Opcode) {
1440 default: llvm_unreachable("Unknown instruction type encountered!");
1441 // Build the switch statement using the Instruction.def file.
1442#define HANDLE_INST(NUM, OPCODE, CLASS) \
1443 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1444#include "llvm/IR/Instruction.def"
1445 }
1446}
1447
1449 DILocalVariable *Variable,
1450 DebugLoc DL, unsigned Order,
1453 // For variadic dbg_values we will now insert poison.
1454 // FIXME: We can potentially recover these!
1456 for (const Value *V : Values) {
1457 auto *Poison = PoisonValue::get(V->getType());
1458 Locs.push_back(SDDbgOperand::fromConst(Poison));
1459 }
1460 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1461 /*IsIndirect=*/false, DL, Order,
1462 /*IsVariadic=*/true);
1463 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1464 return true;
1465}
1466
1468 DILocalVariable *Var,
1469 DIExpression *Expr,
1470 bool IsVariadic, DebugLoc DL,
1471 unsigned Order) {
1472 if (IsVariadic) {
1473 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1474 return;
1475 }
1476 // TODO: Dangling debug info will eventually either be resolved or produce
1477 // a poison DBG_VALUE. However in the resolution case, a gap may appear
1478 // between the original dbg.value location and its resolved DBG_VALUE,
1479 // which we should ideally fill with an extra poison DBG_VALUE.
1480 assert(Values.size() == 1);
1481 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1482}
1483
1485 const DIExpression *Expr) {
1486 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1487 DIVariable *DanglingVariable = DDI.getVariable();
1488 DIExpression *DanglingExpr = DDI.getExpression();
1489 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1490 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1491 << printDDI(nullptr, DDI) << "\n");
1492 return true;
1493 }
1494 return false;
1495 };
1496
1497 for (auto &DDIMI : DanglingDebugInfoMap) {
1498 DanglingDebugInfoVector &DDIV = DDIMI.second;
1499
1500 // If debug info is to be dropped, run it through final checks to see
1501 // whether it can be salvaged.
1502 for (auto &DDI : DDIV)
1503 if (isMatchingDbgValue(DDI))
1504 salvageUnresolvedDbgValue(DDIMI.first, DDI);
1505
1506 erase_if(DDIV, isMatchingDbgValue);
1507 }
1508}
1509
1510// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1511// generate the debug data structures now that we've seen its definition.
1513 SDValue Val) {
1514 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1515 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1516 return;
1517
1518 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1519 for (auto &DDI : DDIV) {
1520 DebugLoc DL = DDI.getDebugLoc();
1521 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1522 DILocalVariable *Variable = DDI.getVariable();
1523 DIExpression *Expr = DDI.getExpression();
1524 assert(Variable->isValidLocationForIntrinsic(DL) &&
1525 "Expected inlined-at fields to agree");
1526 SDDbgValue *SDV;
1527 if (Val.getNode()) {
1528 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1529 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1530 // we couldn't resolve it directly when examining the DbgValue intrinsic
1531 // in the first place we should not be more successful here). Unless we
1532 // have some test case that prove this to be correct we should avoid
1533 // calling EmitFuncArgumentDbgValue here.
1534 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1535 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1536 FuncArgumentDbgValueKind::Value, Val)) {
1537 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1538 << printDDI(V, DDI) << "\n");
1539 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1540 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1541 // inserted after the definition of Val when emitting the instructions
1542 // after ISel. An alternative could be to teach
1543 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1544 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1545 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1546 << ValSDNodeOrder << "\n");
1547 SDV = getDbgValue(Val, Variable, Expr, DL,
1548 std::max(DbgSDNodeOrder, ValSDNodeOrder));
1549 DAG.AddDbgValue(SDV, false);
1550 } else
1551 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1552 << printDDI(V, DDI)
1553 << " in EmitFuncArgumentDbgValue\n");
1554 } else {
1555 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1556 << "\n");
1557 auto Poison = PoisonValue::get(V->getType());
1558 auto SDV =
1559 DAG.getConstantDbgValue(Variable, Expr, Poison, DL, DbgSDNodeOrder);
1560 DAG.AddDbgValue(SDV, false);
1561 }
1562 }
1563 DDIV.clear();
1564}
1565
1566/// If \p V is the address of a describable global, possibly displaced by a
1567/// constant, return the global and fold the displacement into location operand
1568/// \p OpIdx of \p Expr. The displacement rides along in the expression rather
1569/// than in the operand, so that it survives into a DBG_INSTR_REF.
1570static const GlobalValue *
1571getGlobalAddressDbgOperand(const Value *V, DIExpression *&Expr, unsigned OpIdx,
1572 const MachineFunction &MF) {
1573 const auto *C = dyn_cast<Constant>(V);
1574 if (!C)
1575 return nullptr;
1576 int64_t Offset;
1578 if (GV && Offset) {
1581 Expr = DIExpression::appendOpsToArg(Expr, Ops, OpIdx, /*StackValue=*/false);
1582 }
1583 return GV;
1584}
1585
1587 DanglingDebugInfo &DDI) {
1588 // TODO: For the variadic implementation, instead of only checking the fail
1589 // state of `handleDebugValue`, we need know specifically which values were
1590 // invalid, so that we attempt to salvage only those values when processing
1591 // a DIArgList.
1592 const Value *OrigV = V;
1593 DILocalVariable *Var = DDI.getVariable();
1594 DIExpression *Expr = DDI.getExpression();
1595 DebugLoc DL = DDI.getDebugLoc();
1596 unsigned SDOrder = DDI.getSDNodeOrder();
1597
1598 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1599 // that DW_OP_stack_value is desired.
1600 bool StackValue = true;
1601
1602 // handleDebugValue holds out for a register with the address of a global
1603 // that a location list could not name. With no such register forthcoming,
1604 // naming the global still beats dropping the location.
1605 auto HandleGlobalAddress = [&] {
1606 DIExpression *GVExpr = Expr;
1607 const GlobalValue *GV =
1608 getGlobalAddressDbgOperand(V, GVExpr, 0, DAG.getMachineFunction());
1609 if (!GV)
1610 return false;
1611 SDDbgValue *SDV = DAG.getDbgValueList(
1612 Var, GVExpr, SDDbgOperand::fromGlobalAddr(GV), /*Dependencies=*/{},
1613 /*IsIndirect=*/false, DL, SDOrder, /*IsVariadic=*/false);
1614 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1615 return true;
1616 };
1617
1618 // Can this Value can be encoded without any further work?
1619 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false) ||
1620 HandleGlobalAddress())
1621 return;
1622
1623 // Attempt to salvage back through as many instructions as possible. Bail if
1624 // a non-instruction is seen, such as a constant expression or global
1625 // variable. FIXME: Further work could recover those too.
1626 while (isa<Instruction>(V)) {
1627 const Instruction &VAsInst = *cast<const Instruction>(V);
1628 // Temporary "0", awaiting real implementation.
1630 SmallVector<Value *, 4> AdditionalValues;
1631 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1632 Expr->getNumLocationOperands(), Ops,
1633 AdditionalValues);
1634 // If we cannot salvage any further, and haven't yet found a suitable debug
1635 // expression, bail out.
1636 if (!V)
1637 break;
1638
1639 // TODO: If AdditionalValues isn't empty, then the salvage can only be
1640 // represented with a DBG_VALUE_LIST, so we give up. When we have support
1641 // here for variadic dbg_values, remove that condition.
1642 if (!AdditionalValues.empty())
1643 break;
1644
1645 // New value and expr now represent this debuginfo.
1647
1648 // Some kind of simplification occurred: check whether the operand of the
1649 // salvaged debug expression can be encoded in this DAG.
1650 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false) ||
1651 HandleGlobalAddress()) {
1652 LLVM_DEBUG(
1653 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n"
1654 << *OrigV << "\nBy stripping back to:\n " << *V << "\n");
1655 return;
1656 }
1657 }
1658
1659 // This was the final opportunity to salvage this debug information, and it
1660 // couldn't be done. Place a poison DBG_VALUE at this location to terminate
1661 // any earlier variable location.
1662 assert(OrigV && "V shouldn't be null");
1663 auto *Poison = PoisonValue::get(OrigV->getType());
1664 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Poison, DL, SDNodeOrder);
1665 DAG.AddDbgValue(SDV, false);
1666 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n "
1667 << printDDI(OrigV, DDI) << "\n");
1668}
1669
1671 DIExpression *Expr,
1672 DebugLoc DbgLoc,
1673 unsigned Order) {
1674 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1677 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1678 /*IsVariadic*/ false);
1679}
1680
1682 DILocalVariable *Var,
1683 DIExpression *Expr, DebugLoc DbgLoc,
1684 unsigned Order, bool IsVariadic) {
1685 if (Values.empty())
1686 return true;
1687
1688 // Filter EntryValue locations out early.
1689 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1690 return true;
1691
1692 SmallVector<SDDbgOperand> LocationOps;
1693 SmallVector<SDNode *> Dependencies;
1694 for (const auto &[OpIdx, V] : enumerate(Values)) {
1695 // Constant value.
1698 LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1699 continue;
1700 }
1701
1702 // Look through IntToPtr constants.
1703 if (auto *CE = dyn_cast<ConstantExpr>(V))
1704 if (CE->getOpcode() == Instruction::IntToPtr) {
1705 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1706 continue;
1707 }
1708
1709 // The address of a global is a link-time constant, and so is a constant
1710 // displacement from one. A global whose address cannot be described this
1711 // way falls through to be described by whatever materializes it instead.
1712 // So does one that a location list could not name, should the variable
1713 // need one; salvageUnresolvedDbgValue names it if nothing materializes it.
1714 if (CanDescribeGlobalAddressInLocationList)
1716 V, Expr, OpIdx, DAG.getMachineFunction())) {
1718 continue;
1719 }
1720
1721 // If the Value is a frame index, we can create a FrameIndex debug value
1722 // without relying on the DAG at all.
1723 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1724 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1725 if (SI != FuncInfo.StaticAllocaMap.end()) {
1726 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1727 continue;
1728 }
1729 }
1730
1731 // Do not use getValue() in here; we don't want to generate code at
1732 // this point if it hasn't been done yet.
1733 SDValue N = NodeMap[V];
1734 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1735 N = UnusedArgNodeMap[V];
1736
1737 if (N.getNode()) {
1738 // Only emit func arg dbg value for non-variadic dbg.values for now.
1739 if (!IsVariadic &&
1740 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1741 FuncArgumentDbgValueKind::Value, N))
1742 return true;
1743 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1744 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1745 // describe stack slot locations.
1746 //
1747 // Consider "int x = 0; int *px = &x;". There are two kinds of
1748 // interesting debug values here after optimization:
1749 //
1750 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
1751 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1752 //
1753 // Both describe the direct values of their associated variables.
1754 Dependencies.push_back(N.getNode());
1755 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1756 continue;
1757 }
1758 LocationOps.emplace_back(
1759 SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1760 continue;
1761 }
1762
1763 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1764 // Special rules apply for the first dbg.values of parameter variables in a
1765 // function. Identify them by the fact they reference Argument Values, that
1766 // they're parameters, and they are parameters of the current function. We
1767 // need to let them dangle until they get an SDNode.
1768 bool IsParamOfFunc =
1769 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1770 if (IsParamOfFunc)
1771 return false;
1772
1773 // The value is not used in this block yet (or it would have an SDNode).
1774 // We still want the value to appear for the user if possible -- if it has
1775 // an associated VReg, we can refer to that instead.
1776 auto VMI = FuncInfo.ValueMap.find(V);
1777 if (VMI != FuncInfo.ValueMap.end()) {
1778 Register Reg = VMI->second;
1779 // If this is a PHI node, it may be split up into several MI PHI nodes
1780 // (in FunctionLoweringInfo::set).
1781 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1782 V->getType(), std::nullopt);
1783 if (RFV.occupiesMultipleRegs()) {
1784 // FIXME: We could potentially support variadic dbg_values here.
1785 if (IsVariadic)
1786 return false;
1787 unsigned Offset = 0;
1788 unsigned BitsToDescribe = 0;
1789 if (auto VarSize = Var->getSizeInBits())
1790 BitsToDescribe = *VarSize;
1791 if (auto Fragment = Expr->getFragmentInfo())
1792 BitsToDescribe = Fragment->SizeInBits;
1793 for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1794 // Bail out if all bits are described already.
1795 if (Offset >= BitsToDescribe)
1796 break;
1797 // TODO: handle scalable vectors.
1798 unsigned RegisterSize = RegAndSize.second;
1799 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1800 ? BitsToDescribe - Offset
1801 : RegisterSize;
1802 auto FragmentExpr = DIExpression::createFragmentExpression(
1803 Expr, Offset, FragmentSize);
1804 if (!FragmentExpr)
1805 continue;
1806 SDDbgValue *SDV = DAG.getVRegDbgValue(
1807 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1808 DAG.AddDbgValue(SDV, false);
1809 Offset += RegisterSize;
1810 }
1811 return true;
1812 }
1813 // We can use simple vreg locations for variadic dbg_values as well.
1814 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1815 continue;
1816 }
1817 // We failed to create a SDDbgOperand for V.
1818 return false;
1819 }
1820
1821 // We have created a SDDbgOperand for each Value in Values.
1822 assert(!LocationOps.empty());
1823 SDDbgValue *SDV =
1824 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1825 /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1826 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1827 return true;
1828}
1829
1831 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1832 for (auto &Pair : DanglingDebugInfoMap)
1833 for (auto &DDI : Pair.second)
1834 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1836}
1837
1838/// getCopyFromRegs - If there was virtual register allocated for the value V
1839/// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1841 auto It = FuncInfo.ValueMap.find(V);
1842 SDValue Result;
1843
1844 if (It != FuncInfo.ValueMap.end()) {
1845 Register InReg = It->second;
1846
1847 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1848 DAG.getDataLayout(), InReg, Ty,
1849 std::nullopt); // This is not an ABI copy.
1850 SDValue Chain = DAG.getEntryNode();
1851 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1852 V);
1853 resolveDanglingDebugInfo(V, Result);
1854 }
1855
1856 return Result;
1857}
1858
1859/// getValue - Return an SDValue for the given Value.
1861 // If we already have an SDValue for this value, use it. It's important
1862 // to do this first, so that we don't create a CopyFromReg if we already
1863 // have a regular SDValue.
1864 SDValue &N = NodeMap[V];
1865 if (N.getNode()) return N;
1866
1867 // If there's a virtual register allocated and initialized for this
1868 // value, use it.
1869 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1870 return copyFromReg;
1871
1872 // Otherwise create a new SDValue and remember it.
1873 SDValue Val = getValueImpl(V);
1874 NodeMap[V] = Val;
1876 return Val;
1877}
1878
1879void SelectionDAGBuilder::setValueToPoison(const Value *V, const SDLoc &dl) {
1880 if (V->getType()->isVoidTy())
1881 return;
1882
1883 SmallVector<EVT, 4> ValueVTs;
1884 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
1885 V->getType(), ValueVTs);
1886 if (ValueVTs.empty())
1887 return;
1888 setValue(V, DAG.getErrorMergeValues(ValueVTs, SDValue(), dl));
1889}
1890
1891/// getNonRegisterValue - Return an SDValue for the given Value, but
1892/// don't look in FuncInfo.ValueMap for a virtual register.
1894 // If we already have an SDValue for this value, use it.
1895 SDValue &N = NodeMap[V];
1896 if (N.getNode()) {
1897 if (isIntOrFPConstant(N)) {
1898 // Remove the debug location from the node as the node is about to be used
1899 // in a location which may differ from the original debug location. This
1900 // is relevant to Constant and ConstantFP nodes because they can appear
1901 // as constant expressions inside PHI nodes.
1902 N->setDebugLoc(DebugLoc());
1903 }
1904 return N;
1905 }
1906
1907 // Otherwise create a new SDValue and remember it.
1908 SDValue Val = getValueImpl(V);
1909 NodeMap[V] = Val;
1911 return Val;
1912}
1913
1914/// getValueImpl - Helper function for getValue and getNonRegisterValue.
1915/// Create an SDValue for the given value.
1917 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1918
1919 if (const Constant *C = dyn_cast<Constant>(V)) {
1920 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1921
1922 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1923 SDLoc DL = getCurSDLoc();
1924
1925 // DAG.getConstant() may attempt to legalise the vector constant which can
1926 // significantly change the combines applied to the DAG. To reduce the
1927 // divergence when enabling ConstantInt based vectors we try to construct
1928 // the DAG in the same way as shufflevector based splats. TODO: The
1929 // divergence sometimes leads to better optimisations. Ideally we should
1930 // prevent DAG.getConstant() from legalising too early but there are some
1931 // degradations preventing this.
1932 if (VT.isScalableVector())
1933 return DAG.getNode(
1934 ISD::SPLAT_VECTOR, DL, VT,
1935 DAG.getConstant(CI->getValue(), DL, VT.getVectorElementType()));
1936 if (VT.isFixedLengthVector())
1937 return DAG.getSplatBuildVector(
1938 VT, DL,
1939 DAG.getConstant(CI->getValue(), DL, VT.getVectorElementType()));
1940 return DAG.getConstant(*CI, DL, VT);
1941 }
1942
1943 if (const ConstantByte *CB = dyn_cast<ConstantByte>(C))
1944 return DAG.getConstant(CB->getValue(), getCurSDLoc(), VT);
1945
1946 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1947 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1948
1949 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) {
1950 return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT,
1951 getValue(CPA->getPointer()), getValue(CPA->getKey()),
1952 getValue(CPA->getAddrDiscriminator()),
1953 getValue(CPA->getDiscriminator()));
1954 }
1955
1957 return DAG.getConstant(0, getCurSDLoc(), VT);
1958
1959 if (match(C, m_VScale()))
1960 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1961
1962 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1963 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1964
1965 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1966 return isa<PoisonValue>(C) ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
1967
1968 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1969 visit(CE->getOpcode(), *CE);
1970 SDValue N1 = NodeMap[V];
1971 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1972 return N1;
1973 }
1974
1976 SmallVector<SDValue, 4> Constants;
1977 for (const Use &U : C->operands()) {
1978 SDNode *Val = getValue(U).getNode();
1979 // If the operand is an empty aggregate, there are no values.
1980 if (!Val) continue;
1981 // Add each leaf value from the operand to the Constants list
1982 // to form a flattened list of all the values.
1983 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1984 Constants.push_back(SDValue(Val, i));
1985 }
1986
1987 return DAG.getMergeValues(Constants, getCurSDLoc());
1988 }
1989
1990 if (const ConstantDataSequential *CDS =
1993 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i) {
1994 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1995 // Add each leaf value from the operand to the Constants list
1996 // to form a flattened list of all the values.
1997 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1998 Ops.push_back(SDValue(Val, i));
1999 }
2000
2001 if (isa<ArrayType>(CDS->getType()))
2002 return DAG.getMergeValues(Ops, getCurSDLoc());
2003 return DAG.getBuildVector(VT, getCurSDLoc(), Ops);
2004 }
2005
2006 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
2008 "Unknown struct or array constant!");
2009
2010 SmallVector<EVT, 4> ValueVTs;
2011 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
2012 unsigned NumElts = ValueVTs.size();
2013 if (NumElts == 0)
2014 return SDValue(); // empty struct
2015 SmallVector<SDValue, 4> Constants(NumElts);
2016 for (unsigned i = 0; i != NumElts; ++i) {
2017 EVT EltVT = ValueVTs[i];
2018 if (isa<UndefValue>(C))
2019 Constants[i] = DAG.getUNDEF(EltVT);
2020 else if (EltVT.isFloatingPoint())
2021 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
2022 else
2023 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
2024 }
2025
2026 return DAG.getMergeValues(Constants, getCurSDLoc());
2027 }
2028
2029 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
2030 return DAG.getBlockAddress(BA, VT);
2031
2032 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
2033 return getValue(Equiv->getGlobalValue());
2034
2035 if (const auto *NC = dyn_cast<NoCFIValue>(C))
2036 return getValue(NC->getGlobalValue());
2037
2038 if (VT == MVT::aarch64svcount) {
2039 assert(C->isNullValue() && "Can only zero this target type!");
2040 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
2041 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
2042 }
2043
2044 if (VT.isRISCVVectorTuple()) {
2045 assert(C->isNullValue() && "Can only zero this target type!");
2046 return DAG.getNode(
2048 DAG.getNode(
2050 EVT::getVectorVT(*DAG.getContext(), MVT::i8,
2051 VT.getSizeInBits().getKnownMinValue() / 8, true),
2052 DAG.getConstant(0, getCurSDLoc(), MVT::getIntegerVT(8))));
2053 }
2054
2055 if (VT == MVT::externref || VT == MVT::funcref) {
2056 assert(C->isNullValue() && "Can only zero this target type!");
2057 // The zero value of a WebAssembly reference type is the null reference,
2058 // materialized with ref.null.
2059 Intrinsic::ID IID = VT == MVT::externref ? Intrinsic::wasm_ref_null_extern
2060 : Intrinsic::wasm_ref_null_func;
2061 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VT,
2062 DAG.getTargetConstant(IID, getCurSDLoc(), MVT::i32));
2063 }
2064
2065 VectorType *VecTy = cast<VectorType>(V->getType());
2066
2067 // Now that we know the number and type of the elements, get that number of
2068 // elements into the Ops array based on what kind of constant it is.
2069 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
2071 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
2072 for (unsigned i = 0; i != NumElements; ++i)
2073 Ops.push_back(getValue(CV->getOperand(i)));
2074
2075 return DAG.getBuildVector(VT, getCurSDLoc(), Ops);
2076 }
2077
2079 EVT EltVT =
2080 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
2081
2082 SDValue Op;
2083 if (EltVT.isFloatingPoint())
2084 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
2085 else
2086 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
2087
2088 return DAG.getSplat(VT, getCurSDLoc(), Op);
2089 }
2090
2091 llvm_unreachable("Unknown vector constant");
2092 }
2093
2094 // If this is a static alloca, generate it as the frameindex instead of
2095 // computation.
2096 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
2097 auto SI = FuncInfo.StaticAllocaMap.find(AI);
2098 if (SI != FuncInfo.StaticAllocaMap.end())
2099 return DAG.getFrameIndex(
2100 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
2101 }
2102
2103 // If this is an instruction which fast-isel has deferred, select it now.
2104 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
2105 Register InReg = FuncInfo.InitializeRegForValue(Inst);
2106 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
2107 Inst->getType(), std::nullopt);
2108 SDValue Chain = DAG.getEntryNode();
2109 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
2110 }
2111
2112 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
2113 return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
2114
2115 if (const auto *BB = dyn_cast<BasicBlock>(V))
2116 return DAG.getBasicBlock(FuncInfo.getMBB(BB));
2117
2118 llvm_unreachable("Can't get register for value!");
2119}
2120
2121void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
2123 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
2124 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
2125 bool IsSEH = isAsynchronousEHPersonality(Pers);
2126 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
2127 if (IsSEH) {
2128 // For SEH, EHCont Guard needs to know that this catchpad is a target.
2129 CatchPadMBB->setIsEHContTarget(true);
2131 } else
2132 CatchPadMBB->setIsEHScopeEntry();
2133 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
2134 if (IsMSVCCXX || IsCoreCLR)
2135 CatchPadMBB->setIsEHFuncletEntry();
2136}
2137
2138void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
2139 // Update machine-CFG edge.
2140 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor());
2141 FuncInfo.MBB->addSuccessor(TargetMBB);
2142
2143 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2144 bool IsSEH = isAsynchronousEHPersonality(Pers);
2145 if (IsSEH) {
2146 // If this is not a fall-through branch or optimizations are switched off,
2147 // emit the branch.
2148 if (TargetMBB != NextBlock(FuncInfo.MBB) ||
2149 TM.getOptLevel() == CodeGenOptLevel::None)
2150 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2151 getControlRoot(), DAG.getBasicBlock(TargetMBB)));
2152 return;
2153 }
2154
2155 // For non-SEH, EHCont Guard needs to know that this catchret is a target.
2156 TargetMBB->setIsEHContTarget(true);
2157 DAG.getMachineFunction().setHasEHContTarget(true);
2158
2159 // Figure out the funclet membership for the catchret's successor.
2160 // This will be used by the FuncletLayout pass to determine how to order the
2161 // BB's.
2162 // A 'catchret' returns to the outer scope's color.
2163 Value *ParentPad = I.getCatchSwitchParentPad();
2164 const BasicBlock *SuccessorColor;
2165 if (isa<ConstantTokenNone>(ParentPad))
2166 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2167 else
2168 SuccessorColor = cast<Instruction>(ParentPad)->getParent();
2169 assert(SuccessorColor && "No parent funclet for catchret!");
2170 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor);
2171 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2172
2173 // Create the terminator node.
2174 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2175 getControlRoot(), DAG.getBasicBlock(TargetMBB),
2176 DAG.getBasicBlock(SuccessorColorMBB));
2177 DAG.setRoot(Ret);
2178}
2179
2180void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2181 // Don't emit any special code for the cleanuppad instruction. It just marks
2182 // the start of an EH scope/funclet.
2183 FuncInfo.MBB->setIsEHScopeEntry();
2184 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2185 if (Pers != EHPersonality::Wasm_CXX && Pers != EHPersonality::Wasm_D) {
2186 FuncInfo.MBB->setIsEHFuncletEntry();
2187 FuncInfo.MBB->setIsCleanupFuncletEntry();
2188 }
2189}
2190
2191/// When an invoke or a cleanupret unwinds to the next EH pad, there are
2192/// many places it could ultimately go. In the IR, we have a single unwind
2193/// destination, but in the machine CFG, we enumerate all the possible blocks.
2194/// This function skips over imaginary basic blocks that hold catchswitch
2195/// instructions, and finds all the "real" machine
2196/// basic block destinations. As those destinations may not be successors of
2197/// EHPadBB, here we also calculate the edge probability to those destinations.
2198/// The passed-in Prob is the edge probability to EHPadBB.
2200 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2201 BranchProbability Prob,
2202 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2203 &UnwindDests) {
2204 EHPersonality Personality =
2206 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2207 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2208 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2209 bool IsWasmD = Personality == EHPersonality::Wasm_D;
2210 bool IsSEH = isAsynchronousEHPersonality(Personality);
2211
2212 while (EHPadBB) {
2214 BasicBlock *NewEHPadBB = nullptr;
2215 if (isa<LandingPadInst>(Pad)) {
2216 // Stop on landingpads. They are not funclets.
2217 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2218 break;
2219 } else if (isa<CleanupPadInst>(Pad)) {
2220 // Stop on cleanup pads. Cleanups are always funclet entries for all known
2221 // personalities except Wasm. And in Wasm this becomes a catch_all(_ref),
2222 // which always catches an exception.
2223 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2224 UnwindDests.back().first->setIsEHScopeEntry();
2225 // In Wasm, EH scopes are not funclets
2226 if (!IsWasmCXX && !IsWasmD)
2227 UnwindDests.back().first->setIsEHFuncletEntry();
2228 break;
2229 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2230 // Add the catchpad handlers to the possible destinations.
2231 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2232 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2233 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2234 if (IsMSVCCXX || IsCoreCLR)
2235 UnwindDests.back().first->setIsEHFuncletEntry();
2236 if (!IsSEH)
2237 UnwindDests.back().first->setIsEHScopeEntry();
2238 }
2239 NewEHPadBB = CatchSwitch->getUnwindDest();
2240 } else {
2241 continue;
2242 }
2243
2244 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2245 if (BPI && NewEHPadBB)
2246 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2247 EHPadBB = NewEHPadBB;
2248 }
2249}
2250
2251void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2252 // Update successor info.
2254 auto UnwindDest = I.getUnwindDest();
2255 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2256 BranchProbability UnwindDestProb =
2257 (BPI && UnwindDest)
2258 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2260 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2261 for (auto &UnwindDest : UnwindDests) {
2262 UnwindDest.first->setIsEHPad();
2263 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2264 }
2265 FuncInfo.MBB->normalizeSuccProbs();
2266
2267 // Create the terminator node.
2268 MachineBasicBlock *CleanupPadMBB =
2269 FuncInfo.getMBB(I.getCleanupPad()->getParent());
2270 SDValue Ret = DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other,
2271 getControlRoot(), DAG.getBasicBlock(CleanupPadMBB));
2272 DAG.setRoot(Ret);
2273}
2274
2275void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2276 report_fatal_error("visitCatchSwitch not yet implemented!");
2277}
2278
2279void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2280 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2281 auto &DL = DAG.getDataLayout();
2282 SDValue Chain = getControlRoot();
2285
2286 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2287 // lower
2288 //
2289 // %val = call <ty> @llvm.experimental.deoptimize()
2290 // ret <ty> %val
2291 //
2292 // differently.
2293 if (I.getParent()->getTerminatingDeoptimizeCall()) {
2295 return;
2296 }
2297
2298 if (!FuncInfo.CanLowerReturn) {
2299 Register DemoteReg = FuncInfo.DemoteRegister;
2300
2301 // Emit a store of the return value through the virtual register.
2302 // Leave Outs empty so that LowerReturn won't try to load return
2303 // registers the usual way.
2304 MVT PtrValueVT = TLI.getPointerTy(DL, DL.getAllocaAddrSpace());
2305 SDValue RetPtr =
2306 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVT);
2307 Type *RetTy = I.getOperand(0)->getType();
2308 Align BaseAlign = DL.getPrefTypeAlign(RetTy);
2309 RetPtr =
2310 TLI.annotateStackObjectPointer(RetPtr, DAG, getCurSDLoc(), BaseAlign);
2311 SDValue RetOp = getValue(I.getOperand(0));
2312
2313 SmallVector<EVT, 4> ValueVTs, MemVTs;
2314 SmallVector<uint64_t, 4> Offsets;
2315 ComputeValueVTs(TLI, DL, RetTy, ValueVTs, &MemVTs, &Offsets, 0);
2316 unsigned NumValues = ValueVTs.size();
2317
2318 SmallVector<SDValue, 4> Chains(NumValues);
2319 for (unsigned i = 0; i != NumValues; ++i) {
2320 // An aggregate return value cannot wrap around the address space, so
2321 // offsets to its parts don't wrap either.
2322 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2323 TypeSize::getFixed(Offsets[i]));
2324
2325 SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2326 if (MemVTs[i] != ValueVTs[i])
2327 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2328 Chains[i] = DAG.getStore(
2329 Chain, getCurSDLoc(), Val,
2330 // FIXME: better loc info would be nice.
2331 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2332 commonAlignment(BaseAlign, Offsets[i]));
2333 }
2334
2335 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2336 MVT::Other, Chains);
2337 } else if (I.getNumOperands() != 0) {
2339 ComputeValueTypes(DL, I.getOperand(0)->getType(), Types);
2340 unsigned NumValues = Types.size();
2341 if (NumValues) {
2342 SDValue RetOp = getValue(I.getOperand(0));
2343
2344 const Function *F = I.getParent()->getParent();
2345
2346 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2347 I.getOperand(0)->getType(), F->getCallingConv(),
2348 /*IsVarArg*/ false, DL);
2349
2351 if (F->getAttributes().hasRetAttr(Attribute::SExt))
2353 else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2355
2356 LLVMContext &Context = F->getContext();
2357 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2358
2359 for (unsigned j = 0; j != NumValues; ++j) {
2360 EVT VT = TLI.getValueType(DL, Types[j]);
2361
2362 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2363 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2364
2365 CallingConv::ID CC = F->getCallingConv();
2366
2367 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2368 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2369 SmallVector<SDValue, 4> Parts(NumParts);
2371 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2372 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2373
2374 // 'inreg' on function refers to return value
2375 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2376 if (RetInReg)
2377 Flags.setInReg();
2378
2379 if (I.getOperand(0)->getType()->isPointerTy()) {
2380 Flags.setPointer();
2381 Flags.setPointerAddrSpace(
2382 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2383 }
2384
2385 if (NeedsRegBlock) {
2386 Flags.setInConsecutiveRegs();
2387 if (j == NumValues - 1)
2388 Flags.setInConsecutiveRegsLast();
2389 }
2390
2391 // Propagate extension type if any
2393 Flags.setSExt();
2394 else if (ExtendKind == ISD::ZERO_EXTEND)
2395 Flags.setZExt();
2396 else if (F->getAttributes().hasRetAttr(Attribute::NoExt))
2397 Flags.setNoExt();
2398
2399 for (unsigned i = 0; i < NumParts; ++i) {
2400 Outs.push_back(ISD::OutputArg(Flags,
2401 Parts[i].getValueType().getSimpleVT(),
2402 VT, Types[j], 0, 0));
2403 OutVals.push_back(Parts[i]);
2404 }
2405 }
2406 }
2407 }
2408
2409 // Push in swifterror virtual register as the last element of Outs. This makes
2410 // sure swifterror virtual register will be returned in the swifterror
2411 // physical register.
2412 const Function *F = I.getParent()->getParent();
2413 if (TLI.supportSwiftError() &&
2414 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2415 assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2416 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2417 Flags.setSwiftError();
2418 Outs.push_back(ISD::OutputArg(Flags, /*vt=*/TLI.getPointerTy(DL),
2419 /*argvt=*/EVT(TLI.getPointerTy(DL)),
2420 PointerType::getUnqual(*DAG.getContext()),
2421 /*origidx=*/1, /*partOffs=*/0));
2422 // Create SDNode for the swifterror virtual register.
2423 OutVals.push_back(
2424 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2425 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2426 EVT(TLI.getPointerTy(DL))));
2427 }
2428
2429 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2430 CallingConv::ID CallConv =
2431 DAG.getMachineFunction().getFunction().getCallingConv();
2432 Chain = DAG.getTargetLoweringInfo().LowerReturn(
2433 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2434
2435 // Verify that the target's LowerReturn behaved as expected.
2436 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2437 "LowerReturn didn't return a valid chain!");
2438
2439 // Update the DAG with the new chain value resulting from return lowering.
2440 DAG.setRoot(Chain);
2441}
2442
2443/// CopyToExportRegsIfNeeded - If the given value has virtual registers
2444/// created for it, emit nodes to copy the value into the virtual
2445/// registers.
2447 // Skip empty types
2448 if (V->getType()->isEmptyTy())
2449 return;
2450
2451 auto VMI = FuncInfo.ValueMap.find(V);
2452 if (VMI != FuncInfo.ValueMap.end()) {
2453 assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2454 "Unused value assigned virtual registers!");
2455 CopyValueToVirtualRegister(V, VMI->second);
2456 }
2457}
2458
2459/// ExportFromCurrentBlock - If this condition isn't known to be exported from
2460/// the current basic block, add it to ValueMap now so that we'll get a
2461/// CopyTo/FromReg.
2463 // No need to export constants.
2464 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2465
2466 // Already exported?
2467 if (FuncInfo.isExportedInst(V)) return;
2468
2469 Register Reg = FuncInfo.InitializeRegForValue(V);
2471}
2472
2474 const BasicBlock *FromBB) {
2475 // The operands of the setcc have to be in this block. We don't know
2476 // how to export them from some other block.
2477 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2478 // Can export from current BB.
2479 if (VI->getParent() == FromBB)
2480 return true;
2481
2482 // Is already exported, noop.
2483 return FuncInfo.isExportedInst(V);
2484 }
2485
2486 // If this is an argument, we can export it if the BB is the entry block or
2487 // if it is already exported.
2488 if (isa<Argument>(V)) {
2489 if (FromBB->isEntryBlock())
2490 return true;
2491
2492 // Otherwise, can only export this if it is already exported.
2493 return FuncInfo.isExportedInst(V);
2494 }
2495
2496 // Otherwise, constants can always be exported.
2497 return true;
2498}
2499
2500/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2502SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2503 const MachineBasicBlock *Dst) const {
2505 const BasicBlock *SrcBB = Src->getBasicBlock();
2506 const BasicBlock *DstBB = Dst->getBasicBlock();
2507 if (!BPI) {
2508 // If BPI is not available, set the default probability as 1 / N, where N is
2509 // the number of successors.
2510 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2511 return BranchProbability(1, SuccSize);
2512 }
2513 return BPI->getEdgeProbability(SrcBB, DstBB);
2514}
2515
2516void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2517 MachineBasicBlock *Dst,
2518 BranchProbability Prob) {
2519 if (!FuncInfo.BPI)
2520 Src->addSuccessorWithoutProb(Dst);
2521 else {
2522 if (Prob.isUnknown())
2523 Prob = getEdgeProbability(Src, Dst);
2524 Src->addSuccessor(Dst, Prob);
2525 }
2526}
2527
2528static bool InBlock(const Value *V, const BasicBlock *BB) {
2529 if (const Instruction *I = dyn_cast<Instruction>(V))
2530 return I->getParent() == BB;
2531 return true;
2532}
2533
2534/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2535/// This function emits a branch and is used at the leaves of an OR or an
2536/// AND operator tree.
2537void
2540 MachineBasicBlock *FBB,
2541 MachineBasicBlock *CurBB,
2542 MachineBasicBlock *SwitchBB,
2543 BranchProbability TProb,
2544 BranchProbability FProb,
2545 bool InvertCond) {
2546 const BasicBlock *BB = CurBB->getBasicBlock();
2547
2548 // If the leaf of the tree is a comparison, merge the condition into
2549 // the caseblock.
2550 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2551 // The operands of the cmp have to be in this block. We don't know
2552 // how to export them from some other block. If this is the first block
2553 // of the sequence, no exporting is needed.
2554 if (CurBB == SwitchBB ||
2555 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2556 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2557 ISD::CondCode Condition;
2558 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2559 ICmpInst::Predicate Pred =
2560 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2561 Condition = getICmpCondCode(Pred);
2562 } else {
2563 const FCmpInst *FC = cast<FCmpInst>(Cond);
2564 FCmpInst::Predicate Pred =
2565 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2566 Condition = getFCmpCondCode(Pred);
2567 if (FC->hasNoNaNs() ||
2568 (isKnownNeverNaN(FC->getOperand(0),
2569 SimplifyQuery(DAG.getDataLayout(), FC)) &&
2570 isKnownNeverNaN(FC->getOperand(1),
2571 SimplifyQuery(DAG.getDataLayout(), FC))))
2572 Condition = getFCmpCodeWithoutNaN(Condition);
2573 }
2574
2575 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2576 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2577 SL->SwitchCases.push_back(CB);
2578 return;
2579 }
2580 }
2581
2582 // Create a CaseBlock record representing this branch.
2583 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2584 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2585 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2586 SL->SwitchCases.push_back(CB);
2587}
2588
2589// Collect dependencies on V recursively. This is used for the cost analysis in
2590// `shouldKeepJumpConditionsTogether`.
2594 unsigned Depth = 0) {
2595 // Return false if we have an incomplete count.
2597 return false;
2598
2599 auto *I = dyn_cast<Instruction>(V);
2600 if (I == nullptr)
2601 return true;
2602
2603 if (Necessary != nullptr) {
2604 // This instruction is necessary for the other side of the condition so
2605 // don't count it.
2606 if (Necessary->contains(I))
2607 return true;
2608 }
2609
2610 // Already added this dep.
2611 if (!Deps->try_emplace(I, false).second)
2612 return true;
2613
2614 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2615 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2616 Depth + 1))
2617 return false;
2618 return true;
2619}
2620
2623 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2625 if (Params.BaseCost < 0)
2626 return false;
2627
2628 // Baseline cost.
2629 InstructionCost CostThresh = Params.BaseCost;
2630
2631 BranchProbabilityInfo *BPI = nullptr;
2632 if (Params.LikelyBias || Params.UnlikelyBias)
2633 BPI = FuncInfo.BPI;
2634 if (BPI != nullptr) {
2635 // See if we are either likely to get an early out or compute both lhs/rhs
2636 // of the condition.
2637 BasicBlock *IfTrue = I.getSuccessor(0);
2638 BasicBlock *IfFalse = I.getSuccessor(1);
2640 std::swap(IfTrue, IfFalse);
2641
2642 std::optional<bool> Likely;
2643 if (BPI->isEdgeHot(I.getParent(), IfTrue))
2644 Likely = true;
2645 else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2646 Likely = false;
2647
2648 if (Likely) {
2649 if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2650 // Its likely we will have to compute both lhs and rhs of condition
2651 CostThresh += Params.LikelyBias;
2652 else {
2653 if (Params.UnlikelyBias < 0)
2654 return false;
2655 // Its likely we will get an early out.
2656 CostThresh -= Params.UnlikelyBias;
2657 }
2658 }
2659 }
2660
2661 if (CostThresh <= 0)
2662 return false;
2663
2664 // Collect "all" instructions that lhs condition is dependent on.
2665 // Use map for stable iteration (to avoid non-determanism of iteration of
2666 // SmallPtrSet). The `bool` value is just a dummy.
2668 collectInstructionDeps(&LhsDeps, Lhs);
2669 // Collect "all" instructions that rhs condition is dependent on AND are
2670 // dependencies of lhs. This gives us an estimate on which instructions we
2671 // stand to save by splitting the condition.
2672 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2673 return false;
2674 // Add the compare instruction itself unless its a dependency on the LHS.
2675 if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2676 if (!LhsDeps.contains(RhsI))
2677 RhsDeps.try_emplace(RhsI, false);
2678
2679 InstructionCost CostOfIncluding = 0;
2680 // See if this instruction will need to computed independently of whether RHS
2681 // is.
2682 Value *BrCond = I.getCondition();
2683 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2684 for (const auto *U : Ins->users()) {
2685 // If user is independent of RHS calculation we don't need to count it.
2686 if (auto *UIns = dyn_cast<Instruction>(U))
2687 if (UIns != BrCond && !RhsDeps.contains(UIns))
2688 return false;
2689 }
2690 return true;
2691 };
2692
2693 // Prune instructions from RHS Deps that are dependencies of unrelated
2694 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2695 // arbitrary and just meant to cap the how much time we spend in the pruning
2696 // loop. Its highly unlikely to come into affect.
2697 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2698 // Stop after a certain point. No incorrectness from including too many
2699 // instructions.
2700 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2701 const Instruction *ToDrop = nullptr;
2702 for (const auto &InsPair : RhsDeps) {
2703 if (!ShouldCountInsn(InsPair.first)) {
2704 ToDrop = InsPair.first;
2705 break;
2706 }
2707 }
2708 if (ToDrop == nullptr)
2709 break;
2710 RhsDeps.erase(ToDrop);
2711 }
2712
2713 for (const auto &InsPair : RhsDeps) {
2714 // Finally accumulate latency that we can only attribute to computing the
2715 // RHS condition. Use latency because we are essentially trying to calculate
2716 // the cost of the dependency chain.
2717 // Possible TODO: We could try to estimate ILP and make this more precise.
2718 CostOfIncluding += TTI->getInstructionCost(
2719 InsPair.first, TargetTransformInfo::TCK_Latency);
2720
2721 if (CostOfIncluding > CostThresh)
2722 return false;
2723 }
2724 return true;
2725}
2726
2729 MachineBasicBlock *FBB,
2730 MachineBasicBlock *CurBB,
2731 MachineBasicBlock *SwitchBB,
2733 BranchProbability TProb,
2734 BranchProbability FProb,
2735 bool InvertCond) {
2736 // Skip over not part of the tree and remember to invert op and operands at
2737 // next level.
2738 Value *NotCond;
2739 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2740 InBlock(NotCond, CurBB->getBasicBlock())) {
2741 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2742 !InvertCond);
2743 return;
2744 }
2745
2747 const Value *BOpOp0, *BOpOp1;
2748 // Compute the effective opcode for Cond, taking into account whether it needs
2749 // to be inverted, e.g.
2750 // and (not (or A, B)), C
2751 // gets lowered as
2752 // and (and (not A, not B), C)
2754 if (BOp) {
2755 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2756 ? Instruction::And
2757 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2758 ? Instruction::Or
2760 if (InvertCond) {
2761 if (BOpc == Instruction::And)
2762 BOpc = Instruction::Or;
2763 else if (BOpc == Instruction::Or)
2764 BOpc = Instruction::And;
2765 }
2766 }
2767
2768 // If this node is not part of the or/and tree, emit it as a branch.
2769 // Note that all nodes in the tree should have same opcode.
2770 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2771 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2772 !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2773 !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2774 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2775 TProb, FProb, InvertCond);
2776 return;
2777 }
2778
2779 // Create TmpBB after CurBB.
2780 MachineFunction::iterator BBI(CurBB);
2781 MachineFunction &MF = DAG.getMachineFunction();
2783 CurBB->getParent()->insert(++BBI, TmpBB);
2784
2785 if (Opc == Instruction::Or) {
2786 // Codegen X | Y as:
2787 // BB1:
2788 // jmp_if_X TBB
2789 // jmp TmpBB
2790 // TmpBB:
2791 // jmp_if_Y TBB
2792 // jmp FBB
2793 //
2794
2795 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2796 // The requirement is that
2797 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2798 // = TrueProb for original BB.
2799 // Assuming the original probabilities are A and B, one choice is to set
2800 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2801 // A/(1+B) and 2B/(1+B). This choice assumes that
2802 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2803 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2804 // TmpBB, but the math is more complicated.
2805
2806 auto NewTrueProb = TProb / 2;
2807 auto NewFalseProb = TProb / 2 + FProb;
2808 // Emit the LHS condition.
2809 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2810 NewFalseProb, InvertCond);
2811
2812 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2813 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2815 // Emit the RHS condition into TmpBB.
2816 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2817 Probs[1], InvertCond);
2818 } else {
2819 assert(Opc == Instruction::And && "Unknown merge op!");
2820 // Codegen X & Y as:
2821 // BB1:
2822 // jmp_if_X TmpBB
2823 // jmp FBB
2824 // TmpBB:
2825 // jmp_if_Y TBB
2826 // jmp FBB
2827 //
2828 // This requires creation of TmpBB after CurBB.
2829
2830 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2831 // The requirement is that
2832 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2833 // = FalseProb for original BB.
2834 // Assuming the original probabilities are A and B, one choice is to set
2835 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2836 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2837 // TrueProb for BB1 * FalseProb for TmpBB.
2838
2839 auto NewTrueProb = TProb + FProb / 2;
2840 auto NewFalseProb = FProb / 2;
2841 // Emit the LHS condition.
2842 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2843 NewFalseProb, InvertCond);
2844
2845 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2846 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2848 // Emit the RHS condition into TmpBB.
2849 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2850 Probs[1], InvertCond);
2851 }
2852}
2853
2854/// If the set of cases should be emitted as a series of branches, return true.
2855/// If we should emit this as a bunch of and/or'd together conditions, return
2856/// false.
2857bool
2858SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2859 if (Cases.size() != 2) return true;
2860
2861 // If this is two comparisons of the same values or'd or and'd together, they
2862 // will get folded into a single comparison, so don't emit two blocks.
2863 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2864 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2865 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2866 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2867 return false;
2868 }
2869
2870 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2871 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2872 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2873 Cases[0].CC == Cases[1].CC &&
2874 isa<Constant>(Cases[0].CmpRHS) &&
2875 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2876 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2877 return false;
2878 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2879 return false;
2880 }
2881
2882 return true;
2883}
2884
2885void SelectionDAGBuilder::visitUncondBr(const UncondBrInst &I) {
2887
2888 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2889
2890 // Update machine-CFG edges.
2891 BrMBB->addSuccessor(Succ0MBB);
2892
2893 // If this is not a fall-through branch or optimizations are switched off,
2894 // emit the branch.
2895 if (Succ0MBB != NextBlock(BrMBB) ||
2897 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2898 DAG.getBasicBlock(Succ0MBB));
2899 setValue(&I, Br);
2900 DAG.setRoot(Br);
2901 }
2902}
2903
2904void SelectionDAGBuilder::visitCondBr(const CondBrInst &I) {
2905 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2906
2907 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2908
2909 // If this condition is one of the special cases we handle, do special stuff
2910 // now.
2911 const Value *CondVal = I.getCondition();
2912 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1));
2913
2914 // If this is a series of conditions that are or'd or and'd together, emit
2915 // this as a sequence of branches instead of setcc's with and/or operations.
2916 // As long as jumps are not expensive (exceptions for multi-use logic ops,
2917 // unpredictable branches, and vector extracts because those jumps are likely
2918 // expensive for any target), this should improve performance.
2919 // For example, instead of something like:
2920 // cmp A, B
2921 // C = seteq
2922 // cmp D, E
2923 // F = setle
2924 // or C, F
2925 // jnz foo
2926 // Emit:
2927 // cmp A, B
2928 // je foo
2929 // cmp D, E
2930 // jle foo
2931 bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2932 const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2933 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2934 BOp->hasOneUse() && !IsUnpredictable) {
2935 Value *Vec;
2936 const Value *BOp0, *BOp1;
2938 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2939 Opcode = Instruction::And;
2940 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2941 Opcode = Instruction::Or;
2942
2943 if (Opcode &&
2944 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2945 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2947 FuncInfo, I, Opcode, BOp0, BOp1,
2948 DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2949 Opcode, BOp0, BOp1, FuncInfo.Fn))) {
2950 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2951 getEdgeProbability(BrMBB, Succ0MBB),
2952 getEdgeProbability(BrMBB, Succ1MBB),
2953 /*InvertCond=*/false);
2954 // If the compares in later blocks need to use values not currently
2955 // exported from this block, export them now. This block should always
2956 // be the first entry.
2957 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2958
2959 // Allow some cases to be rejected.
2960 if (ShouldEmitAsBranches(SL->SwitchCases)) {
2961 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2962 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2963 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2964 }
2965
2966 // Emit the branch for this block.
2967 visitSwitchCase(SL->SwitchCases[0], BrMBB);
2968 SL->SwitchCases.erase(SL->SwitchCases.begin());
2969 return;
2970 }
2971
2972 // Okay, we decided not to do this, remove any inserted MBB's and clear
2973 // SwitchCases.
2974 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2975 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2976
2977 SL->SwitchCases.clear();
2978 }
2979 }
2980
2981 // Create a CaseBlock record representing this branch.
2982 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2983 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2985 IsUnpredictable);
2986
2987 // Use visitSwitchCase to actually insert the fast branch sequence for this
2988 // cond branch.
2989 visitSwitchCase(CB, BrMBB);
2990}
2991
2992/// visitSwitchCase - Emits the necessary code to represent a single node in
2993/// the binary search tree resulting from lowering a switch instruction.
2995 MachineBasicBlock *SwitchBB) {
2996 SDValue Cond;
2997 SDValue CondLHS = getValue(CB.CmpLHS);
2998 SDLoc dl = CB.DL;
2999
3000 if (CB.CC == ISD::SETTRUE) {
3001 // Branch or fall through to TrueBB.
3002 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
3003 SwitchBB->normalizeSuccProbs();
3004 if (CB.TrueBB != NextBlock(SwitchBB)) {
3005 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
3006 DAG.getBasicBlock(CB.TrueBB)));
3007 }
3008 return;
3009 }
3010
3011 auto &TLI = DAG.getTargetLoweringInfo();
3012 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
3013
3014 // Build the setcc now.
3015 if (!CB.CmpMHS) {
3016 // Fold "(X == true)" to X and "(X == false)" to !X to
3017 // handle common cases produced by branch lowering.
3018 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
3019 CB.CC == ISD::SETEQ)
3020 Cond = CondLHS;
3021 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
3022 CB.CC == ISD::SETEQ) {
3023 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
3024 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
3025 } else {
3026 SDValue CondRHS = getValue(CB.CmpRHS);
3027
3028 // If a pointer's DAG type is larger than its memory type then the DAG
3029 // values are zero-extended. This breaks signed comparisons so truncate
3030 // back to the underlying type before doing the compare.
3031 if (CondLHS.getValueType() != MemVT) {
3032 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
3033 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
3034 }
3035 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
3036 }
3037 } else {
3038 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
3039
3040 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
3041 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
3042
3043 SDValue CmpOp = getValue(CB.CmpMHS);
3044 EVT VT = CmpOp.getValueType();
3045
3046 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
3047 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
3048 ISD::SETLE);
3049 } else {
3050 SDValue SUB = DAG.getNode(ISD::SUB, dl,
3051 VT, CmpOp, DAG.getConstant(Low, dl, VT));
3052 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
3053 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
3054 }
3055 }
3056
3057 // Update successor info
3058 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
3059 // TrueBB and FalseBB are always different unless the incoming IR is
3060 // degenerate. This only happens when running llc on weird IR.
3061 if (CB.TrueBB != CB.FalseBB)
3062 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
3063 SwitchBB->normalizeSuccProbs();
3064
3065 // If the lhs block is the next block, invert the condition so that we can
3066 // fall through to the lhs instead of the rhs block.
3067 if (CB.TrueBB == NextBlock(SwitchBB)) {
3068 std::swap(CB.TrueBB, CB.FalseBB);
3069 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
3070 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
3071 }
3072
3073 SDNodeFlags Flags;
3075 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3076 Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
3077
3078 setValue(CurInst, BrCond);
3079
3080 // Insert the false branch. Do this even if it's a fall through branch,
3081 // this makes it easier to do DAG optimizations which require inverting
3082 // the branch condition.
3083 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3084 DAG.getBasicBlock(CB.FalseBB));
3085
3086 DAG.setRoot(BrCond);
3087}
3088
3089/// visitJumpTable - Emit JumpTable node in the current MBB
3091 // Emit the code for the jump table
3092 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3093 assert(JT.Reg && "Should lower JT Header first!");
3094 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
3095 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
3096 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
3097 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
3098 Index.getValue(1), Table, Index);
3099 DAG.setRoot(BrJumpTable);
3100}
3101
3102/// visitJumpTableHeader - This function emits necessary code to produce index
3103/// in the JumpTable from switch case.
3105 JumpTableHeader &JTH,
3106 MachineBasicBlock *SwitchBB) {
3107 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3108 const SDLoc &dl = *JT.SL;
3109
3110 // Subtract the lowest switch case value from the value being switched on.
3111 SDValue SwitchOp = getValue(JTH.SValue);
3112 EVT VT = SwitchOp.getValueType();
3113 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3114 DAG.getConstant(JTH.First, dl, VT));
3115
3116 // The SDNode we just created, which holds the value being switched on minus
3117 // the smallest case value, needs to be copied to a virtual register so it
3118 // can be used as an index into the jump table in a subsequent basic block.
3119 // This value may be smaller or larger than the target's pointer type, and
3120 // therefore require extension or truncating.
3121 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3122 SwitchOp =
3123 DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3124
3125 Register JumpTableReg =
3126 FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3127 SDValue CopyTo =
3128 DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3129 JT.Reg = JumpTableReg;
3130
3131 if (!JTH.FallthroughUnreachable) {
3132 // Emit the range check for the jump table, and branch to the default block
3133 // for the switch statement if the value being switched on exceeds the
3134 // largest case in the switch.
3135 SDValue CMP = DAG.getSetCC(
3136 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3137 Sub.getValueType()),
3138 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3139
3140 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3141 MVT::Other, CopyTo, CMP,
3142 DAG.getBasicBlock(JT.Default));
3143
3144 // Avoid emitting unnecessary branches to the next block.
3145 if (JT.MBB != NextBlock(SwitchBB))
3146 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3147 DAG.getBasicBlock(JT.MBB));
3148
3149 DAG.setRoot(BrCond);
3150 } else {
3151 // Avoid emitting unnecessary branches to the next block.
3152 if (JT.MBB != NextBlock(SwitchBB))
3153 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3154 DAG.getBasicBlock(JT.MBB)));
3155 else
3156 DAG.setRoot(CopyTo);
3157 }
3158}
3159
3160/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3161/// variable if there exists one.
3163 SDValue &Chain) {
3164 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3165 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3166 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3168 Value *Global =
3171 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3172 if (Global) {
3173 MachinePointerInfo MPInfo(Global);
3177 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
3178 DAG.setNodeMemRefs(Node, {MemRef});
3179 }
3180 if (PtrTy != PtrMemTy)
3181 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3182 return SDValue(Node, 0);
3183}
3184
3185/// Codegen a new tail for a stack protector check ParentMBB which has had its
3186/// tail spliced into a stack protector check success bb.
3187///
3188/// For a high level explanation of how this fits into the stack protector
3189/// generation see the comment on the declaration of class
3190/// StackProtectorDescriptor.
3192 MachineBasicBlock *ParentBB) {
3193
3194 // First create the loads to the guard/stack slot for the comparison.
3195 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3196 auto &DL = DAG.getDataLayout();
3197 EVT PtrTy = TLI.getFrameIndexTy(DL);
3198 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3199
3200 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3201 int FI = MFI.getStackProtectorIndex();
3202
3203 SDValue Guard;
3204 SDLoc dl = getCurSDLoc();
3205 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3206 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3207 Align Align = DL.getPrefTypeAlign(
3208 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3209
3210 // Generate code to load the content of the guard slot.
3211 SDValue GuardVal = DAG.getLoad(
3212 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3213 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3215
3216 // If cookie mixing is enabled, unmix the stored GuardVal to get back the
3217 // original cookie for comparison. The prologue stored (FP - Cookie) or
3218 // (FP XOR Cookie), so we apply the same operation again to unmix:
3219 // FP - (FP - Cookie) = Cookie, or (FP XOR Cookie) XOR FP = Cookie.
3220 if (TLI.useStackGuardMixFP())
3221 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3222
3223 // If we're using function-based instrumentation, call the guard check
3224 // function
3226 // Get the guard check function from the target and verify it exists since
3227 // we're using function-based instrumentation
3228 const Function *GuardCheckFn =
3229 TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3230 assert(GuardCheckFn && "Guard check function is null");
3231
3232 // The target provides a guard check function to validate the guard value.
3233 // Generate a call to that function with the content of the guard slot as
3234 // argument.
3235 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3236 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3237
3239 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3240 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3241 Entry.IsInReg = true;
3242 Args.push_back(Entry);
3243
3246 .setChain(DAG.getEntryNode())
3247 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3248 getValue(GuardCheckFn), std::move(Args));
3249
3250 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3251 DAG.setRoot(Result.second);
3252 return;
3253 }
3254
3255 // Load the fresh guard value for comparison.
3256 // For targets that mix the cookie in LOAD_STACK_GUARD expansion, we need to
3257 // load directly without using LOAD_STACK_GUARD to avoid unwanted mixing.
3258 SDValue Chain = DAG.getEntryNode();
3259 if (TLI.useStackGuardMixFP()) {
3260 // Mixing targets: load cookie directly to avoid mixing in LOAD_STACK_GUARD
3261 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3262 SDValue GuardPtr = getValue(IRGuard);
3263 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3264 MachinePointerInfo(IRGuard, 0), Align,
3266 } else {
3267 LLVMContext &Ctx = *DAG.getContext();
3268 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3269 Guard = DAG.getPOISON(PtrMemTy);
3270 }
3271 } else {
3272 // Non-mixing targets: use LOAD_STACK_GUARD or direct load as usual
3273 if (TLI.useLoadStackGuardNode(M)) {
3274 Guard = getLoadStackGuard(DAG, dl, Chain);
3275 } else {
3276 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3277 SDValue GuardPtr = getValue(IRGuard);
3278 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3279 MachinePointerInfo(IRGuard, 0), Align,
3281 } else {
3282 LLVMContext &Ctx = *DAG.getContext();
3283 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3284 Guard = DAG.getPOISON(PtrMemTy);
3285 }
3286 }
3287 }
3288
3289 // Now both Guard (fresh cookie) and GuardVal (unmixed from stored value)
3290 // contain unmixed cookie values that can be compared directly.
3291
3292 // Perform the comparison via a getsetcc.
3293 SDValue Cmp = DAG.getSetCC(
3294 dl, TLI.getSetCCResultType(DL, *DAG.getContext(), Guard.getValueType()),
3295 Guard, GuardVal, ISD::SETNE);
3296
3297 // If the guard/stackslot do not equal, branch to failure MBB.
3298 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3299 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3300 // Otherwise branch to success MBB.
3301 SDValue Br = DAG.getNode(ISD::BR, dl,
3302 MVT::Other, BrCond,
3303 DAG.getBasicBlock(SPD.getSuccessMBB()));
3304
3305 DAG.setRoot(Br);
3306}
3307
3308/// Codegen the failure basic block for a stack protector check.
3309///
3310/// A failure stack protector machine basic block consists simply of a call to
3311/// __stack_chk_fail().
3312///
3313/// For a high level explanation of how this fits into the stack protector
3314/// generation see the comment on the declaration of class
3315/// StackProtectorDescriptor.
3318
3319 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3320 MachineBasicBlock *ParentBB = SPD.getParentMBB();
3321 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3322 SDValue Chain;
3323
3324 // For -Oz builds with a guard check function, we use function-based
3325 // instrumentation. Otherwise, if we have a guard check function, we call it
3326 // in the failure block.
3327 auto *GuardCheckFn = TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3328 if (GuardCheckFn && !SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3329 // First create the loads to the guard/stack slot for the comparison.
3330 auto &DL = DAG.getDataLayout();
3331 EVT PtrTy = TLI.getFrameIndexTy(DL);
3332 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3333
3334 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3335 int FI = MFI.getStackProtectorIndex();
3336
3337 SDLoc dl = getCurSDLoc();
3338 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3339 Align Align = DL.getPrefTypeAlign(
3340 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3341
3342 // Generate code to load the content of the guard slot.
3343 SDValue GuardVal = DAG.getLoad(
3344 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3345 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3347
3348 if (TLI.useStackGuardMixFP())
3349 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3350
3351 // The target provides a guard check function to validate the guard value.
3352 // Generate a call to that function with the content of the guard slot as
3353 // argument.
3354 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3355 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3356
3358 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3359 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3360 Entry.IsInReg = true;
3361 Args.push_back(Entry);
3362
3365 .setChain(DAG.getEntryNode())
3366 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3367 getValue(GuardCheckFn), std::move(Args));
3368
3369 Chain = TLI.LowerCallTo(CLI).second;
3370 } else {
3372 CallOptions.setDiscardResult(true);
3373 Chain = TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3374 {}, CallOptions, getCurSDLoc())
3375 .second;
3376 }
3377
3378 // Emit a trap instruction if we are required to do so.
3379 const TargetOptions &TargetOpts = DAG.getTarget().Options;
3380 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3381 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3382
3383 DAG.setRoot(Chain);
3384}
3385
3386/// visitBitTestHeader - This function emits necessary code to produce value
3387/// suitable for "bit tests"
3389 MachineBasicBlock *SwitchBB) {
3390 SDLoc dl = getCurSDLoc();
3391
3392 // Subtract the minimum value.
3393 SDValue SwitchOp = getValue(B.SValue);
3394 EVT VT = SwitchOp.getValueType();
3395 SDValue RangeSub =
3396 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3397
3398 // Determine the type of the test operands.
3399 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3400 bool UsePtrType = false;
3401 if (!TLI.isTypeLegal(VT)) {
3402 UsePtrType = true;
3403 } else {
3404 for (const BitTestCase &Case : B.Cases)
3405 if (!isUIntN(VT.getSizeInBits(), Case.Mask)) {
3406 // Switch table case range are encoded into series of masks.
3407 // Just use pointer type, it's guaranteed to fit.
3408 UsePtrType = true;
3409 break;
3410 }
3411 }
3412 SDValue Sub = RangeSub;
3413 if (UsePtrType) {
3414 VT = TLI.getPointerTy(DAG.getDataLayout());
3415 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3416 }
3417
3418 B.RegVT = VT.getSimpleVT();
3419 B.Reg = FuncInfo.CreateReg(B.RegVT);
3420 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3421
3422 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3423
3424 if (!B.FallthroughUnreachable)
3425 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3426 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3427 SwitchBB->normalizeSuccProbs();
3428
3429 SDValue Root = CopyTo;
3430 if (!B.FallthroughUnreachable) {
3431 // Conditional branch to the default block.
3432 SDValue RangeCmp = DAG.getSetCC(dl,
3433 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3434 RangeSub.getValueType()),
3435 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3436 ISD::SETUGT);
3437
3438 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3439 DAG.getBasicBlock(B.Default));
3440 }
3441
3442 // Avoid emitting unnecessary branches to the next block.
3443 if (MBB != NextBlock(SwitchBB))
3444 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3445
3446 DAG.setRoot(Root);
3447}
3448
3449/// visitBitTestCase - this function produces one "bit test"
3451 MachineBasicBlock *NextMBB,
3452 BranchProbability BranchProbToNext,
3453 Register Reg, BitTestCase &B,
3454 MachineBasicBlock *SwitchBB) {
3455 SDLoc dl = getCurSDLoc();
3456 MVT VT = BB.RegVT;
3457 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3458 SDValue Cmp;
3459 unsigned PopCount = llvm::popcount(B.Mask);
3460 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3461 if (PopCount == 1) {
3462 // Testing for a single bit; just compare the shift count with what it
3463 // would need to be to shift a 1 bit in that position.
3464 Cmp = DAG.getSetCC(
3465 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3466 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3467 ISD::SETEQ);
3468 } else if (PopCount == BB.Range) {
3469 // There is only one zero bit in the range, test for it directly.
3470 Cmp = DAG.getSetCC(
3471 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3472 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3473 } else {
3474 // Make desired shift
3475 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3476 DAG.getConstant(1, dl, VT), ShiftOp);
3477
3478 // Emit bit tests and jumps
3479 SDValue AndOp = DAG.getNode(ISD::AND, dl,
3480 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3481 Cmp = DAG.getSetCC(
3482 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3483 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3484 }
3485
3486 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3487 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3488 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3489 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3490 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3491 // one as they are relative probabilities (and thus work more like weights),
3492 // and hence we need to normalize them to let the sum of them become one.
3493 SwitchBB->normalizeSuccProbs();
3494
3495 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3496 MVT::Other, getControlRoot(),
3497 Cmp, DAG.getBasicBlock(B.TargetBB));
3498
3499 // Avoid emitting unnecessary branches to the next block.
3500 if (NextMBB != NextBlock(SwitchBB))
3501 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3502 DAG.getBasicBlock(NextMBB));
3503
3504 DAG.setRoot(BrAnd);
3505}
3506
3507void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3508 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3509
3510 // Retrieve successors. Look through artificial IR level blocks like
3511 // catchswitch for successors.
3512 MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0));
3513 const BasicBlock *EHPadBB = I.getSuccessor(1);
3514 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB);
3515
3516 // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3517 // have to do anything here to lower funclet bundles.
3518 failForInvalidBundles(I, "invokes",
3524
3525 const Value *Callee(I.getCalledOperand());
3526 const Function *Fn = dyn_cast<Function>(Callee);
3527 if (isa<InlineAsm>(Callee))
3528 visitInlineAsm(I, EHPadBB);
3529 else if (Fn && Fn->isIntrinsic()) {
3530 switch (Fn->getIntrinsicID()) {
3531 default:
3532 llvm_unreachable("Cannot invoke this intrinsic");
3533 case Intrinsic::donothing:
3534 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3535 case Intrinsic::seh_try_begin:
3536 case Intrinsic::seh_scope_begin:
3537 case Intrinsic::seh_try_end:
3538 case Intrinsic::seh_scope_end:
3539 if (EHPadMBB)
3540 // a block referenced by EH table
3541 // so dtor-funclet not removed by opts
3542 EHPadMBB->setMachineBlockAddressTaken();
3543 break;
3544 case Intrinsic::experimental_patchpoint_void:
3545 case Intrinsic::experimental_patchpoint:
3546 visitPatchpoint(I, EHPadBB);
3547 break;
3548 case Intrinsic::experimental_gc_statepoint:
3550 break;
3551 // wasm_throw, wasm_rethrow: This is usually done in visitTargetIntrinsic,
3552 // but these intrinsics are special because they can be invoked, so we
3553 // manually lower it to a DAG node here.
3554 case Intrinsic::wasm_throw: {
3556 std::array<SDValue, 4> Ops = {
3557 getControlRoot(), // inchain for the terminator node
3558 DAG.getTargetConstant(Intrinsic::wasm_throw, getCurSDLoc(),
3560 getValue(I.getArgOperand(0)), // tag
3561 getValue(I.getArgOperand(1)) // thrown value
3562 };
3563 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3564 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3565 break;
3566 }
3567 case Intrinsic::wasm_rethrow: {
3568 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3569 std::array<SDValue, 2> Ops = {
3570 getControlRoot(), // inchain for the terminator node
3571 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3572 TLI.getPointerTy(DAG.getDataLayout()))};
3573 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3574 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3575 break;
3576 }
3577 }
3578 } else if (I.hasDeoptState()) {
3579 // Currently we do not lower any intrinsic calls with deopt operand bundles.
3580 // Eventually we will support lowering the @llvm.experimental.deoptimize
3581 // intrinsic, and right now there are no plans to support other intrinsics
3582 // with deopt state.
3583 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3584 } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3586 } else {
3587 LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3588 }
3589
3590 // If the value of the invoke is used outside of its defining block, make it
3591 // available as a virtual register.
3592 // We already took care of the exported value for the statepoint instruction
3593 // during call to the LowerStatepoint.
3594 if (!isa<GCStatepointInst>(I)) {
3596 }
3597
3599 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3600 BranchProbability EHPadBBProb =
3601 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3603 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3604
3605 // Update successor info.
3606 addSuccessorWithProb(InvokeMBB, Return);
3607 for (auto &UnwindDest : UnwindDests) {
3608 UnwindDest.first->setIsEHPad();
3609 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3610 }
3611 InvokeMBB->normalizeSuccProbs();
3612
3613 // Drop into normal successor.
3614 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3615 DAG.getBasicBlock(Return)));
3616}
3617
3618/// The intrinsics currently supported by callbr are implicit control flow
3619/// intrinsics such as amdgcn.kill.
3620/// - they should be called (no "dontcall-" attributes)
3621/// - they do not touch memory on the target (= !TLI.getTgtMemIntrinsic())
3622/// - they do not need custom argument handling (no
3623/// TLI.CollectTargetIntrinsicOperands())
3624void SelectionDAGBuilder::visitCallBrIntrinsic(const CallBrInst &I) {
3625#ifndef NDEBUG
3627 DAG.getTargetLoweringInfo().getTgtMemIntrinsic(
3628 Infos, I, DAG.getMachineFunction(), I.getIntrinsicID());
3629 assert(Infos.empty() && "Intrinsic touches memory");
3630#endif
3631
3632 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
3633
3635 getTargetIntrinsicOperands(I, HasChain, OnlyLoad);
3636 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
3637
3638 // Create the node.
3639 SDValue Result =
3640 getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
3641 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
3642
3643 setValue(&I, Result);
3644}
3645
3646void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3647 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3648
3649 if (I.isInlineAsm()) {
3650 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3651 // have to do anything here to lower funclet bundles.
3652 failForInvalidBundles(I, "callbrs",
3654 visitInlineAsm(I);
3655 } else {
3656 assert(!I.hasOperandBundles() &&
3657 "Can't have operand bundles for intrinsics");
3658 visitCallBrIntrinsic(I);
3659 }
3661
3662 // Retrieve successors.
3663 SmallPtrSet<BasicBlock *, 8> Dests;
3664 Dests.insert(I.getDefaultDest());
3665 MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest());
3666
3667 // Update successor info.
3668 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3669 // TODO: For most of the cases where there is an intrinsic callbr, we're
3670 // having exactly one indirect target, which will be unreachable. As soon as
3671 // this changes, we might need to enhance
3672 // Target->setIsInlineAsmBrIndirectTarget or add something similar for
3673 // intrinsic indirect branches.
3674 if (I.isInlineAsm()) {
3675 for (BasicBlock *Dest : I.getIndirectDests()) {
3676 MachineBasicBlock *Target = FuncInfo.getMBB(Dest);
3677 Target->setIsInlineAsmBrIndirectTarget();
3678 // If we introduce a type of asm goto statement that is permitted to use
3679 // an indirect call instruction to jump to its labels, then we should add
3680 // a call to Target->setMachineBlockAddressTaken() here, to mark the
3681 // target block as requiring a BTI.
3682
3683 Target->setLabelMustBeEmitted();
3684 // Don't add duplicate machine successors.
3685 if (Dests.insert(Dest).second)
3686 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3687 }
3688 }
3689 CallBrMBB->normalizeSuccProbs();
3690
3691 // Drop into default successor.
3692 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3693 MVT::Other, getControlRoot(),
3694 DAG.getBasicBlock(Return)));
3695}
3696
3697void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3698 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3699}
3700
3701void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3702 assert(FuncInfo.MBB->isEHPad() &&
3703 "Call to landingpad not in landing pad!");
3704
3705 // If there aren't registers to copy the values into (e.g., during SjLj
3706 // exceptions), then don't bother to create these DAG nodes.
3707 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3708 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3709 if (TLI.getExceptionPointerRegister(FuncInfo.ExceptionModel, PersonalityFn) ==
3710 0 &&
3711 TLI.getExceptionSelectorRegister(FuncInfo.ExceptionModel,
3712 PersonalityFn) == 0)
3713 return;
3714
3715 // If landingpad's return type is token type, we don't create DAG nodes
3716 // for its exception pointer and selector value. The extraction of exception
3717 // pointer or selector value from token type landingpads is not currently
3718 // supported.
3719 if (LP.getType()->isTokenTy())
3720 return;
3721
3722 // LangRef leaves the result type target-specific, so diagnose types this
3723 // lowering cannot represent instead of asserting.
3724 SDLoc dl = getCurSDLoc();
3726 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
3727 *LP.getFunction(),
3728 "landingpad result type must be a struct of an exception pointer and "
3729 "an integer selector",
3730 dl.getDebugLoc()));
3731 setValueToPoison(&LP, dl);
3732 return;
3733 }
3734
3735 SmallVector<EVT, 2> ValueVTs;
3736 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3737 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3738
3739 // Get the two live-in registers as SDValues. The physregs have already been
3740 // copied into virtual registers.
3741 SDValue Ops[2];
3742 if (FuncInfo.ExceptionPointerVirtReg) {
3743 Ops[0] = DAG.getZExtOrTrunc(
3744 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3745 FuncInfo.ExceptionPointerVirtReg,
3746 TLI.getPointerTy(DAG.getDataLayout())),
3747 dl, ValueVTs[0]);
3748 } else {
3749 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3750 }
3751 Ops[1] = DAG.getZExtOrTrunc(
3752 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3753 FuncInfo.ExceptionSelectorVirtReg,
3754 TLI.getPointerTy(DAG.getDataLayout())),
3755 dl, ValueVTs[1]);
3756
3757 // Merge into one.
3758 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3759 DAG.getVTList(ValueVTs), Ops);
3760 setValue(&LP, Res);
3761}
3762
3765 // Update JTCases.
3766 for (JumpTableBlock &JTB : SL->JTCases)
3767 if (JTB.first.HeaderBB == First)
3768 JTB.first.HeaderBB = Last;
3769
3770 // Update BitTestCases.
3771 for (BitTestBlock &BTB : SL->BitTestCases)
3772 if (BTB.Parent == First)
3773 BTB.Parent = Last;
3774}
3775
3776void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3777 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3778
3779 // Update machine-CFG edges with unique successors.
3781 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3782 BasicBlock *BB = I.getSuccessor(i);
3783 bool Inserted = Done.insert(BB).second;
3784 if (!Inserted)
3785 continue;
3786
3787 MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3788 addSuccessorWithProb(IndirectBrMBB, Succ);
3789 }
3790 IndirectBrMBB->normalizeSuccProbs();
3791
3793 MVT::Other, getControlRoot(),
3794 getValue(I.getAddress())));
3795}
3796
3797void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3798 if (!I.shouldLowerToTrap(DAG.getTarget().Options.TrapUnreachable,
3799 DAG.getTarget().Options.NoTrapAfterNoreturn))
3800 return;
3801
3802 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3803}
3804
3805void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3806 SDNodeFlags Flags;
3807 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3808 Flags.copyFMF(*FPOp);
3809
3810 SDValue Op = getValue(I.getOperand(0));
3811 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3812 Op, Flags);
3813 setValue(&I, UnNodeValue);
3814}
3815
3816void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3817 SDNodeFlags Flags;
3818 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3819 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3820 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3821 }
3822 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3823 Flags.setExact(ExactOp->isExact());
3824 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3825 Flags.setDisjoint(DisjointOp->isDisjoint());
3826 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3827 Flags.copyFMF(*FPOp);
3828
3829 SDValue Op1 = getValue(I.getOperand(0));
3830 SDValue Op2 = getValue(I.getOperand(1));
3831 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3832 Op1, Op2, Flags);
3833 setValue(&I, BinNodeValue);
3834}
3835
3836void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3837 SDValue Op1 = getValue(I.getOperand(0));
3838 SDValue Op2 = getValue(I.getOperand(1));
3839
3840 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3841 Op1.getValueType(), DAG.getDataLayout());
3842
3843 // Coerce the shift amount to the right type if we can. This exposes the
3844 // truncate or zext to optimization early.
3845 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3847 "Unexpected shift type");
3848 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3849 }
3850
3851 bool nuw = false;
3852 bool nsw = false;
3853 bool exact = false;
3854
3855 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3856
3857 if (const OverflowingBinaryOperator *OFBinOp =
3859 nuw = OFBinOp->hasNoUnsignedWrap();
3860 nsw = OFBinOp->hasNoSignedWrap();
3861 }
3862 if (const PossiblyExactOperator *ExactOp =
3864 exact = ExactOp->isExact();
3865 }
3866 SDNodeFlags Flags;
3867 Flags.setExact(exact);
3868 Flags.setNoSignedWrap(nsw);
3869 Flags.setNoUnsignedWrap(nuw);
3870 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3871 Flags);
3872 setValue(&I, Res);
3873}
3874
3875void SelectionDAGBuilder::visitSDiv(const User &I) {
3876 SDValue Op1 = getValue(I.getOperand(0));
3877 SDValue Op2 = getValue(I.getOperand(1));
3878
3879 SDNodeFlags Flags;
3880 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3881 cast<PossiblyExactOperator>(&I)->isExact());
3882 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3883 Op2, Flags));
3884}
3885
3886void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3887 ICmpInst::Predicate predicate = I.getPredicate();
3888 SDValue Op1 = getValue(I.getOperand(0));
3889 SDValue Op2 = getValue(I.getOperand(1));
3890 ISD::CondCode Opcode = getICmpCondCode(predicate);
3891
3892 auto &TLI = DAG.getTargetLoweringInfo();
3893 EVT MemVT =
3894 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3895
3896 // If a pointer's DAG type is larger than its memory type then the DAG values
3897 // are zero-extended. This breaks signed comparisons so truncate back to the
3898 // underlying type before doing the compare.
3899 if (Op1.getValueType() != MemVT) {
3900 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3901 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3902 }
3903
3904 SDNodeFlags Flags;
3905 Flags.setSameSign(I.hasSameSign());
3906
3907 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3908 I.getType());
3909 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode,
3910 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3911}
3912
3913void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3914 FCmpInst::Predicate predicate = I.getPredicate();
3915 SDValue Op1 = getValue(I.getOperand(0));
3916 SDValue Op2 = getValue(I.getOperand(1));
3917
3918 ISD::CondCode Condition = getFCmpCondCode(predicate);
3919 auto *FPMO = cast<FPMathOperator>(&I);
3920 if (FPMO->hasNoNaNs() ||
3921 (DAG.isKnownNeverNaN(Op1) && DAG.isKnownNeverNaN(Op2)))
3922 Condition = getFCmpCodeWithoutNaN(Condition);
3923
3924 SDNodeFlags Flags;
3925 Flags.copyFMF(*FPMO);
3926
3927 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3928 I.getType());
3929 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition,
3930 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3931}
3932
3933// Check if the condition of the select has one use or two users that are both
3934// selects with the same condition.
3935static bool hasOnlySelectUsers(const Value *Cond) {
3936 return llvm::all_of(Cond->users(), [](const Value *V) {
3937 return isa<SelectInst>(V);
3938 });
3939}
3940
3941void SelectionDAGBuilder::visitSelect(const User &I) {
3942 SmallVector<EVT, 4> ValueVTs;
3943 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3944 ValueVTs);
3945 unsigned NumValues = ValueVTs.size();
3946 if (NumValues == 0) return;
3947
3949 SDValue Cond = getValue(I.getOperand(0));
3950 SDValue LHSVal = getValue(I.getOperand(1));
3951 SDValue RHSVal = getValue(I.getOperand(2));
3952 SmallVector<SDValue, 1> BaseOps(1, Cond);
3954 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3955
3956 bool IsUnaryAbs = false;
3957 bool Negate = false;
3958
3959 SDNodeFlags Flags;
3960 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3961 Flags.copyFMF(*FPOp);
3962
3963 Flags.setUnpredictable(
3964 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3965
3966 // Min/max matching is only viable if all output VTs are the same.
3967 if (all_equal(ValueVTs)) {
3968 EVT VT = ValueVTs[0];
3969 LLVMContext &Ctx = *DAG.getContext();
3970 auto &TLI = DAG.getTargetLoweringInfo();
3971
3972 // We care about the legality of the operation after it has been type
3973 // legalized.
3974 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3975 VT = TLI.getTypeToTransformTo(Ctx, VT);
3976
3977 // If the vselect is legal, assume we want to leave this as a vector setcc +
3978 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3979 // min/max is legal on the scalar type.
3980 bool UseScalarMinMax = VT.isVector() &&
3982
3983 // ValueTracking's select pattern matching does not account for -0.0,
3984 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3985 // -0.0 is less than +0.0.
3986 const Value *LHS, *RHS;
3987 auto SPR = matchSelectPattern(&I, LHS, RHS);
3989 switch (SPR.Flavor) {
3990 case SPF_UMAX: Opc = ISD::UMAX; break;
3991 case SPF_UMIN: Opc = ISD::UMIN; break;
3992 case SPF_SMAX: Opc = ISD::SMAX; break;
3993 case SPF_SMIN: Opc = ISD::SMIN; break;
3994 case SPF_FMINNUM:
3996 break;
3997
3998 switch (SPR.NaNBehavior) {
3999 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
4000 case SPNB_RETURNS_ANY:
4001 case SPNB_RETURNS_NAN:
4002 break;
4003 case SPNB_RETURNS_OTHER:
4005 Flags.setNoSignedZeros(true);
4006 break;
4007 }
4008 break;
4009 case SPF_FMAXNUM:
4011 break;
4012
4013 switch (SPR.NaNBehavior) {
4014 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
4015 case SPNB_RETURNS_NAN:
4016 case SPNB_RETURNS_ANY:
4017 break;
4018 case SPNB_RETURNS_OTHER:
4020 Flags.setNoSignedZeros(true);
4021 break;
4022 }
4023 break;
4024 case SPF_NABS:
4025 Negate = true;
4026 [[fallthrough]];
4027 case SPF_ABS:
4028 IsUnaryAbs = true;
4029 Opc = ISD::ABS;
4030 break;
4031 default: break;
4032 }
4033
4034 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
4035 (TLI.isOperationLegalOrCustom(Opc, VT) ||
4036 (UseScalarMinMax &&
4038 // If the underlying comparison instruction is used by any other
4039 // instruction, the consumed instructions won't be destroyed, so it is
4040 // not profitable to convert to a min/max.
4042 OpCode = Opc;
4043 LHSVal = getValue(LHS);
4044 RHSVal = getValue(RHS);
4045 BaseOps.clear();
4046 }
4047
4048 if (IsUnaryAbs) {
4049 OpCode = Opc;
4050 LHSVal = getValue(LHS);
4051 BaseOps.clear();
4052 }
4053 }
4054
4055 if (IsUnaryAbs) {
4056 for (unsigned i = 0; i != NumValues; ++i) {
4057 SDLoc dl = getCurSDLoc();
4058 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
4059 Values[i] =
4060 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
4061 if (Negate)
4062 Values[i] = DAG.getNegative(Values[i], dl, VT);
4063 }
4064 } else {
4065 for (unsigned i = 0; i != NumValues; ++i) {
4066 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
4067 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
4068 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
4069 Values[i] = DAG.getNode(
4070 OpCode, getCurSDLoc(),
4071 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
4072 }
4073 }
4074
4076 DAG.getVTList(ValueVTs), Values));
4077}
4078
4079void SelectionDAGBuilder::visitTrunc(const User &I) {
4080 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
4081 SDValue N = getValue(I.getOperand(0));
4082 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4083 I.getType());
4084 SDNodeFlags Flags;
4085 if (auto *Trunc = dyn_cast<TruncInst>(&I)) {
4086 Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
4087 Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
4088 }
4089
4090 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N, Flags));
4091}
4092
4093void SelectionDAGBuilder::visitZExt(const User &I) {
4094 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4095 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
4096 SDValue N = getValue(I.getOperand(0));
4097 auto &TLI = DAG.getTargetLoweringInfo();
4098 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4099
4100 SDNodeFlags Flags;
4101 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
4102 Flags.setNonNeg(PNI->hasNonNeg());
4103
4104 // Eagerly use nonneg information to canonicalize towards sign_extend if
4105 // that is the target's preference.
4106 // TODO: Let the target do this later.
4107 if (Flags.hasNonNeg() &&
4108 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
4109 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4110 return;
4111 }
4112
4113 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4114}
4115
4116void SelectionDAGBuilder::visitSExt(const User &I) {
4117 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4118 // SExt also can't be a cast to bool for same reason. So, nothing much to do
4119 SDValue N = getValue(I.getOperand(0));
4120 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4121 I.getType());
4122 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4123}
4124
4125void SelectionDAGBuilder::visitFPTrunc(const User &I) {
4126 // FPTrunc is never a no-op cast, no need to check
4127 SDValue N = getValue(I.getOperand(0));
4128 SDLoc dl = getCurSDLoc();
4129 SDNodeFlags Flags;
4130 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4131 Flags.copyFMF(*FPOp);
4132 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4133 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4134 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
4135 DAG.getTargetConstant(
4136 0, dl, TLI.getPointerTy(DAG.getDataLayout())),
4137 Flags));
4138}
4139
4140void SelectionDAGBuilder::visitFPExt(const User &I) {
4141 // FPExt is never a no-op cast, no need to check
4142 SDValue N = getValue(I.getOperand(0));
4143 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4144 I.getType());
4145 SDNodeFlags Flags;
4146 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4147 Flags.copyFMF(*FPOp);
4148 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4149}
4150
4151void SelectionDAGBuilder::visitFPToUI(const User &I) {
4152 // FPToUI is never a no-op cast, no need to check
4153 SDValue N = getValue(I.getOperand(0));
4154 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4155 I.getType());
4156 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
4157}
4158
4159void SelectionDAGBuilder::visitFPToSI(const User &I) {
4160 // FPToSI is never a no-op cast, no need to check
4161 SDValue N = getValue(I.getOperand(0));
4162 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4163 I.getType());
4164 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
4165}
4166
4167void SelectionDAGBuilder::visitUIToFP(const User &I) {
4168 // UIToFP is never a no-op cast, no need to check
4169 SDValue N = getValue(I.getOperand(0));
4170 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4171 I.getType());
4172 SDNodeFlags Flags;
4173 Flags.setNonNeg(cast<PossiblyNonNegInst>(&I)->hasNonNeg());
4174 Flags.copyFMF(*cast<FPMathOperator>(&I));
4175
4176 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4177}
4178
4179void SelectionDAGBuilder::visitSIToFP(const User &I) {
4180 // SIToFP is never a no-op cast, no need to check
4181 SDValue N = getValue(I.getOperand(0));
4182 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4183 I.getType());
4184 SDNodeFlags Flags;
4185 Flags.copyFMF(*cast<FPMathOperator>(&I));
4186
4187 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4188}
4189
4190void SelectionDAGBuilder::visitPtrToAddr(const User &I) {
4191 SDValue N = getValue(I.getOperand(0));
4192 // By definition the type of the ptrtoaddr must be equal to the address type.
4193 const auto &TLI = DAG.getTargetLoweringInfo();
4194 EVT AddrVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4195 // The address width must be smaller or equal to the pointer representation
4196 // width, so we lower ptrtoaddr as a truncate (possibly folded to a no-op).
4197 N = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), AddrVT, N);
4198 setValue(&I, N);
4199}
4200
4201void SelectionDAGBuilder::visitPtrToInt(const User &I) {
4202 // What to do depends on the size of the integer and the size of the pointer.
4203 // We can either truncate, zero extend, or no-op, accordingly.
4204 SDValue N = getValue(I.getOperand(0));
4205 auto &TLI = DAG.getTargetLoweringInfo();
4206 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4207 I.getType());
4208 EVT PtrMemVT =
4209 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
4210 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4211 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
4212 setValue(&I, N);
4213}
4214
4215void SelectionDAGBuilder::visitIntToPtr(const User &I) {
4216 // What to do depends on the size of the integer and the size of the pointer.
4217 // We can either truncate, zero extend, or no-op, accordingly.
4218 SDValue N = getValue(I.getOperand(0));
4219 auto &TLI = DAG.getTargetLoweringInfo();
4220 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4221 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4222 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4223 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
4224 setValue(&I, N);
4225}
4226
4227void SelectionDAGBuilder::visitBitCast(const User &I) {
4228 SDValue N = getValue(I.getOperand(0));
4229 SDLoc dl = getCurSDLoc();
4230 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4231 I.getType());
4232
4233 // BitCast assures us that source and destination are the same size so this is
4234 // either a BITCAST or a no-op.
4235 if (DestVT != N.getValueType())
4236 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
4237 DestVT, N)); // convert types.
4238 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
4239 // might fold any kind of constant expression to an integer constant and that
4240 // is not what we are looking for. Only recognize a bitcast of a genuine
4241 // constant integer as an opaque constant.
4242 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
4243 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
4244 /*isOpaque*/true));
4245 else
4246 setValue(&I, N); // noop cast.
4247}
4248
4249void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
4250 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4251 const Value *SV = I.getOperand(0);
4252 SDValue N = getValue(SV);
4253 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4254
4255 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
4256 unsigned DestAS = I.getType()->getPointerAddressSpace();
4257
4258 if (!TM.isNoopAddrSpaceCast(DAG.getDataLayout(), SrcAS, DestAS)) {
4259 SDNodeFlags Flags;
4260 if (const auto *ASC = dyn_cast<AddrSpaceCastInst>(&I))
4261 Flags.setNonNull(ASC->hasNonNull());
4262 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS, Flags);
4263 }
4264
4265 setValue(&I, N);
4266}
4267
4268void SelectionDAGBuilder::visitInsertElement(const User &I) {
4269 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4270 SDValue InVec = getValue(I.getOperand(0));
4271 SDValue InVal = getValue(I.getOperand(1));
4272 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
4273 TLI.getVectorIdxTy(DAG.getDataLayout()));
4275 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4276 InVec, InVal, InIdx));
4277}
4278
4279void SelectionDAGBuilder::visitBitInsert(const User &I) {
4280 SDValue Base = getValue(I.getOperand(0));
4281 SDValue Val = getValue(I.getOperand(1));
4282 SDValue Offset = getValue(I.getOperand(2));
4283 EVT BaseVT = Base.getValueType();
4284 EVT ValVT = Val.getValueType();
4285 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4286 SDLoc dl = getCurSDLoc();
4287
4288 assert(BaseVT.getSizeInBits() >= ValVT.getSizeInBits() &&
4289 "bitinsert val wider than base should be rejected by verifier");
4290
4291 // If Val is a float, cast it to an integer of the same bitwidth
4292 // so DAG.getZExtOrTrunc can process it safely.
4293 if (!ValVT.isInteger()) {
4294 ValVT = ValVT.changeTypeToInteger();
4295 Val = DAG.getBitcast(ValVT, Val);
4296 }
4297
4298 // Legalize shift amount to the target's shift amount type.
4299 EVT ShiftAmtTy = TLI.getShiftAmountTy(BaseVT, DAG.getDataLayout());
4300 SDValue LegalShiftAmount = DAG.getZExtOrTrunc(Offset, dl, ShiftAmtTy);
4301
4302 unsigned BaseBitWidth = BaseVT.getScalarSizeInBits();
4303 unsigned ValBitWidth = ValVT.getScalarSizeInBits();
4304 APInt InsertMask = APInt::getLowBitsSet(BaseBitWidth, ValBitWidth);
4305 SDValue ShiftedMask =
4306 DAG.getNode(ISD::SHL, dl, BaseVT, DAG.getConstant(InsertMask, dl, BaseVT),
4307 LegalShiftAmount);
4308 SDValue ClearMask = DAG.getNOT(dl, ShiftedMask, BaseVT);
4309 SDValue ClearedBase = DAG.getNode(ISD::AND, dl, BaseVT, Base, ClearMask);
4310
4311 SDValue ExtVal = DAG.getZExtOrTrunc(Val, dl, BaseVT);
4312 SDValue ShiftedVal =
4313 DAG.getNode(ISD::SHL, dl, BaseVT, ExtVal, LegalShiftAmount);
4314 SDValue Result = DAG.getNode(ISD::OR, dl, BaseVT, ClearedBase, ShiftedVal);
4315 setValue(&I, Result);
4316}
4317
4318void SelectionDAGBuilder::visitBitExtract(const User &I) {
4319 SDValue Src = getValue(I.getOperand(0));
4320 SDValue Offset = getValue(I.getOperand(1));
4321 EVT SrcVT = Src.getValueType();
4322 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4323 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4324 SDLoc dl = getCurSDLoc();
4325
4326 assert(ResultVT.getSizeInBits() <= SrcVT.getSizeInBits() &&
4327 "bitextract result wider than source should be rejected by verifier");
4328
4329 // Legalize shift amount to the target's shift amount type.
4330 EVT ShiftAmtTy = TLI.getShiftAmountTy(SrcVT, DAG.getDataLayout());
4331 SDValue LegalShiftAmount = DAG.getZExtOrTrunc(Offset, dl, ShiftAmtTy);
4332
4333 // Shift right by Offset - brings target field to bit 0
4334 SDValue Shifted = DAG.getNode(ISD::SRL, dl, SrcVT, Src, LegalShiftAmount);
4335
4336 SDValue Result;
4337 if (!ResultVT.isInteger()) {
4338 // Drop into the integer domain to safely truncate the shifted bits
4339 EVT IntResultVT = ResultVT.changeTypeToInteger();
4340 Result = DAG.getNode(ISD::TRUNCATE, dl, IntResultVT, Shifted);
4341 Result = DAG.getBitcast(ResultVT, Result);
4342 } else {
4343 // Normal integer path
4344 Result = DAG.getNode(ISD::TRUNCATE, dl, ResultVT, Shifted);
4345 }
4346
4347 setValue(&I, Result);
4348}
4349
4350void SelectionDAGBuilder::visitExtractElement(const User &I) {
4351 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4352 SDValue InVec = getValue(I.getOperand(0));
4353 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
4354 TLI.getVectorIdxTy(DAG.getDataLayout()));
4356 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4357 InVec, InIdx));
4358}
4359
4360void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4361 SDValue Src1 = getValue(I.getOperand(0));
4362 SDValue Src2 = getValue(I.getOperand(1));
4363 ArrayRef<int> Mask;
4364 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4365 Mask = SVI->getShuffleMask();
4366 else
4367 Mask = cast<ConstantExpr>(I).getShuffleMask();
4368 SDLoc DL = getCurSDLoc();
4369 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4370 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4371 EVT SrcVT = Src1.getValueType();
4372
4373 if (all_of(Mask, equal_to(0)) && VT.isScalableVector()) {
4374 // Canonical splat form of first element of first input vector.
4375 SDValue FirstElt =
4376 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4377 DAG.getVectorIdxConstant(0, DL));
4378 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4379 return;
4380 }
4381
4382 // For now, we only handle splats for scalable vectors.
4383 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4384 // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4385 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4386
4387 unsigned SrcNumElts = SrcVT.getVectorNumElements();
4388 unsigned MaskNumElts = Mask.size();
4389
4390 if (SrcNumElts == MaskNumElts) {
4391 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4392 return;
4393 }
4394
4395 // Normalize the shuffle vector since mask and vector length don't match.
4396 if (SrcNumElts < MaskNumElts) {
4397 // Mask is longer than the source vectors. We can use concatenate vector to
4398 // make the mask and vectors lengths match.
4399
4400 if (MaskNumElts % SrcNumElts == 0) {
4401 // Mask length is a multiple of the source vector length.
4402 // Check if the shuffle is some kind of concatenation of the input
4403 // vectors.
4404 unsigned NumConcat = MaskNumElts / SrcNumElts;
4405 bool IsConcat = true;
4406 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4407 for (unsigned i = 0; i != MaskNumElts; ++i) {
4408 int Idx = Mask[i];
4409 if (Idx < 0)
4410 continue;
4411 // Ensure the indices in each SrcVT sized piece are sequential and that
4412 // the same source is used for the whole piece.
4413 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4414 (ConcatSrcs[i / SrcNumElts] >= 0 &&
4415 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4416 IsConcat = false;
4417 break;
4418 }
4419 // Remember which source this index came from.
4420 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4421 }
4422
4423 // The shuffle is concatenating multiple vectors together. Just emit
4424 // a CONCAT_VECTORS operation.
4425 if (IsConcat) {
4426 SmallVector<SDValue, 8> ConcatOps;
4427 for (auto Src : ConcatSrcs) {
4428 if (Src < 0)
4429 ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4430 else if (Src == 0)
4431 ConcatOps.push_back(Src1);
4432 else
4433 ConcatOps.push_back(Src2);
4434 }
4435 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4436 return;
4437 }
4438 }
4439
4440 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4441 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4442 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4443 PaddedMaskNumElts);
4444
4445 // Pad both vectors with undefs to make them the same length as the mask.
4446 SDValue UndefVal = DAG.getUNDEF(SrcVT);
4447
4448 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4449 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4450 MOps1[0] = Src1;
4451 MOps2[0] = Src2;
4452
4453 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4454 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4455
4456 // Readjust mask for new input vector length.
4457 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4458 for (unsigned i = 0; i != MaskNumElts; ++i) {
4459 int Idx = Mask[i];
4460 if (Idx >= (int)SrcNumElts)
4461 Idx -= SrcNumElts - PaddedMaskNumElts;
4462 MappedOps[i] = Idx;
4463 }
4464
4465 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4466
4467 // If the concatenated vector was padded, extract a subvector with the
4468 // correct number of elements.
4469 if (MaskNumElts != PaddedMaskNumElts)
4470 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4471 DAG.getVectorIdxConstant(0, DL));
4472
4473 setValue(&I, Result);
4474 return;
4475 }
4476
4477 assert(SrcNumElts > MaskNumElts);
4478
4479 // Analyze the access pattern of the vector to see if we can extract
4480 // two subvectors and do the shuffle.
4481 int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4482 bool CanExtract = true;
4483 for (int Idx : Mask) {
4484 unsigned Input = 0;
4485 if (Idx < 0)
4486 continue;
4487
4488 if (Idx >= (int)SrcNumElts) {
4489 Input = 1;
4490 Idx -= SrcNumElts;
4491 }
4492
4493 // If all the indices come from the same MaskNumElts sized portion of
4494 // the sources we can use extract. Also make sure the extract wouldn't
4495 // extract past the end of the source.
4496 int NewStartIdx = alignDown(Idx, MaskNumElts);
4497 if (NewStartIdx + MaskNumElts > SrcNumElts ||
4498 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4499 CanExtract = false;
4500 // Make sure we always update StartIdx as we use it to track if all
4501 // elements are undef.
4502 StartIdx[Input] = NewStartIdx;
4503 }
4504
4505 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4506 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4507 return;
4508 }
4509 if (CanExtract) {
4510 // Extract appropriate subvector and generate a vector shuffle
4511 for (unsigned Input = 0; Input < 2; ++Input) {
4512 SDValue &Src = Input == 0 ? Src1 : Src2;
4513 if (StartIdx[Input] < 0)
4514 Src = DAG.getUNDEF(VT);
4515 else {
4516 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4517 DAG.getVectorIdxConstant(StartIdx[Input], DL));
4518 }
4519 }
4520
4521 // Calculate new mask.
4522 SmallVector<int, 8> MappedOps(Mask);
4523 for (int &Idx : MappedOps) {
4524 if (Idx >= (int)SrcNumElts)
4525 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4526 else if (Idx >= 0)
4527 Idx -= StartIdx[0];
4528 }
4529
4530 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4531 return;
4532 }
4533
4534 // We can't use either concat vectors or extract subvectors so fall back to
4535 // replacing the shuffle with extract and build vector.
4536 // to insert and build vector.
4537 EVT EltVT = VT.getVectorElementType();
4539 for (int Idx : Mask) {
4540 SDValue Res;
4541
4542 if (Idx < 0) {
4543 Res = DAG.getUNDEF(EltVT);
4544 } else {
4545 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4546 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4547
4548 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4549 DAG.getVectorIdxConstant(Idx, DL));
4550 }
4551
4552 Ops.push_back(Res);
4553 }
4554
4555 setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4556}
4557
4558void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4559 ArrayRef<unsigned> Indices = I.getIndices();
4560 const Value *Op0 = I.getOperand(0);
4561 const Value *Op1 = I.getOperand(1);
4562 Type *AggTy = I.getType();
4563 Type *ValTy = Op1->getType();
4564 bool IntoUndef = isa<UndefValue>(Op0);
4565 bool FromUndef = isa<UndefValue>(Op1);
4566
4567 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4568
4569 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4570 SmallVector<EVT, 4> AggValueVTs;
4571 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4572 SmallVector<EVT, 4> ValValueVTs;
4573 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4574
4575 unsigned NumAggValues = AggValueVTs.size();
4576 unsigned NumValValues = ValValueVTs.size();
4577 SmallVector<SDValue, 4> Values(NumAggValues);
4578
4579 // Ignore an insertvalue that produces an empty object
4580 if (!NumAggValues) {
4581 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4582 return;
4583 }
4584
4585 SDValue Agg = getValue(Op0);
4586 unsigned i = 0;
4587 // Copy the beginning value(s) from the original aggregate.
4588 for (; i != LinearIndex; ++i)
4589 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4590 SDValue(Agg.getNode(), Agg.getResNo() + i);
4591 // Copy values from the inserted value(s).
4592 if (NumValValues) {
4593 SDValue Val = getValue(Op1);
4594 for (; i != LinearIndex + NumValValues; ++i)
4595 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4596 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4597 }
4598 // Copy remaining value(s) from the original aggregate.
4599 for (; i != NumAggValues; ++i)
4600 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4601 SDValue(Agg.getNode(), Agg.getResNo() + i);
4602
4604 DAG.getVTList(AggValueVTs), Values));
4605}
4606
4607void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4608 ArrayRef<unsigned> Indices = I.getIndices();
4609 const Value *Op0 = I.getOperand(0);
4610 Type *AggTy = Op0->getType();
4611 Type *ValTy = I.getType();
4612 bool OutOfUndef = isa<UndefValue>(Op0);
4613
4614 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4615
4616 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4617 SmallVector<EVT, 4> ValValueVTs;
4618 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4619
4620 unsigned NumValValues = ValValueVTs.size();
4621
4622 // Ignore a extractvalue that produces an empty object
4623 if (!NumValValues) {
4624 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4625 return;
4626 }
4627
4628 SmallVector<SDValue, 4> Values(NumValValues);
4629
4630 SDValue Agg = getValue(Op0);
4631 // Copy out the selected value(s).
4632 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4633 Values[i - LinearIndex] =
4634 OutOfUndef ?
4635 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4636 SDValue(Agg.getNode(), Agg.getResNo() + i);
4637
4639 DAG.getVTList(ValValueVTs), Values));
4640}
4641
4642void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4643 Value *Op0 = I.getOperand(0);
4644 // Note that the pointer operand may be a vector of pointers. Take the scalar
4645 // element which holds a pointer.
4646 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4647 SDValue N = getValue(Op0);
4648 SDLoc dl = getCurSDLoc();
4649 auto &TLI = DAG.getTargetLoweringInfo();
4650 GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4651
4652 // For a vector GEP, keep the prefix scalar as long as possible, then
4653 // convert any scalars encountered after the first vector operand to vectors.
4654 bool IsVectorGEP = I.getType()->isVectorTy();
4655 ElementCount VectorElementCount =
4656 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4658
4660 GTI != E; ++GTI) {
4661 const Value *Idx = GTI.getOperand();
4662 if (StructType *StTy = GTI.getStructTypeOrNull()) {
4663 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4664 if (Field) {
4665 // N = N + Offset
4667 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4668
4669 // In an inbounds GEP with an offset that is nonnegative even when
4670 // interpreted as signed, assume there is no unsigned overflow.
4671 SDNodeFlags Flags;
4672 if (NW.hasNoUnsignedWrap() ||
4673 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4675 Flags.setInBounds(NW.isInBounds());
4676
4677 N = DAG.getMemBasePlusOffset(
4678 N, DAG.getConstant(Offset, dl, N.getValueType()), dl, Flags);
4679 }
4680 } else {
4681 // IdxSize is the width of the arithmetic according to IR semantics.
4682 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4683 // (and fix up the result later).
4684 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4685 MVT IdxTy = MVT::getIntegerVT(IdxSize);
4686 TypeSize ElementSize =
4687 GTI.getSequentialElementStride(DAG.getDataLayout());
4688 // We intentionally mask away the high bits here; ElementSize may not
4689 // fit in IdxTy.
4690 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4691 /*isSigned=*/false, /*implicitTrunc=*/true);
4692 bool ElementScalable = ElementSize.isScalable();
4693
4694 // If this is a scalar constant or a splat vector of constants,
4695 // handle it quickly.
4696 const auto *C = dyn_cast<Constant>(Idx);
4697 if (C && isa<VectorType>(C->getType()))
4698 C = C->getSplatValue();
4699
4700 const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4701 if (CI && CI->isZero())
4702 continue;
4703 if (CI && !ElementScalable) {
4704 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4705 LLVMContext &Context = *DAG.getContext();
4706 SDValue OffsVal;
4707 if (N.getValueType().isVector())
4708 OffsVal = DAG.getConstant(
4709 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4710 else
4711 OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4712
4713 // In an inbounds GEP with an offset that is nonnegative even when
4714 // interpreted as signed, assume there is no unsigned overflow.
4715 SDNodeFlags Flags;
4716 if (NW.hasNoUnsignedWrap() ||
4717 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4718 Flags.setNoUnsignedWrap(true);
4719 Flags.setInBounds(NW.isInBounds());
4720
4721 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4722
4723 N = DAG.getMemBasePlusOffset(N, OffsVal, dl, Flags);
4724 continue;
4725 }
4726
4727 // N = N + Idx * ElementMul;
4728 SDValue IdxN = getValue(Idx);
4729
4730 if (IdxN.getValueType().isVector() != N.getValueType().isVector()) {
4731 if (N.getValueType().isVector()) {
4732 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4733 VectorElementCount);
4734 IdxN = DAG.getSplat(VT, dl, IdxN);
4735 } else {
4736 EVT VT =
4737 EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4738 N = DAG.getSplat(VT, dl, N);
4739 }
4740 }
4741
4742 // If the index is smaller or larger than intptr_t, truncate or extend
4743 // it.
4744 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4745
4746 SDNodeFlags ScaleFlags;
4747 // The multiplication of an index by the type size does not wrap the
4748 // pointer index type in a signed sense (mul nsw).
4750
4751 // The multiplication of an index by the type size does not wrap the
4752 // pointer index type in an unsigned sense (mul nuw).
4753 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4754
4755 if (ElementScalable) {
4756 EVT VScaleTy = N.getValueType().getScalarType();
4757 SDValue VScale = DAG.getNode(
4758 ISD::VSCALE, dl, VScaleTy,
4759 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4760 if (N.getValueType().isVector())
4761 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4762 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale,
4763 ScaleFlags);
4764 } else {
4765 // If this is a multiply by a power of two, turn it into a shl
4766 // immediately. This is a very common case.
4767 if (ElementMul != 1) {
4768 if (ElementMul.isPowerOf2()) {
4769 unsigned Amt = ElementMul.logBase2();
4770 IdxN = DAG.getNode(
4771 ISD::SHL, dl, N.getValueType(), IdxN,
4772 DAG.getShiftAmountConstant(Amt, N.getValueType(), dl),
4773 ScaleFlags);
4774 } else {
4775 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4776 IdxN.getValueType());
4777 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, Scale,
4778 ScaleFlags);
4779 }
4780 }
4781 }
4782
4783 // The successive addition of the current address, truncated to the
4784 // pointer index type and interpreted as an unsigned number, and each
4785 // offset, also interpreted as an unsigned number, does not wrap the
4786 // pointer index type (add nuw).
4787 SDNodeFlags AddFlags;
4788 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4789 AddFlags.setInBounds(NW.isInBounds());
4790
4791 N = DAG.getMemBasePlusOffset(N, IdxN, dl, AddFlags);
4792 }
4793 }
4794
4795 if (IsVectorGEP && !N.getValueType().isVector()) {
4796 EVT VT = EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4797 N = DAG.getSplat(VT, dl, N);
4798 }
4799
4800 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4801 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4802 if (IsVectorGEP) {
4803 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4804 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4805 }
4806
4807 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4808 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4809
4810 setValue(&I, N);
4811}
4812
4813void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4814 // If this is a fixed sized alloca in the entry block of the function,
4815 // allocate it statically on the stack.
4816 if (FuncInfo.StaticAllocaMap.count(&I))
4817 return; // getValue will auto-populate this.
4818
4819 SDLoc dl = getCurSDLoc();
4820 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4821 auto &DL = DAG.getDataLayout();
4822 TypeSize TySize = I.getAllocationBaseSize(DL);
4823 MaybeAlign Alignment = I.getAlign();
4824
4825 SDValue AllocSize = getValue(I.getArraySize());
4826
4827 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4828 if (AllocSize.getValueType() != IntPtr)
4829 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4830
4831 AllocSize = DAG.getNode(
4832 ISD::MUL, dl, IntPtr, AllocSize,
4833 DAG.getZExtOrTrunc(DAG.getTypeSize(dl, MVT::i64, TySize), dl, IntPtr));
4834
4835 // Handle alignment. If the requested alignment is less than or equal to
4836 // the stack alignment, ignore it. If the size is greater than or equal to
4837 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4838 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4839 if (*Alignment <= StackAlign)
4840 Alignment = std::nullopt;
4841
4842 const uint64_t StackAlignMask = StackAlign.value() - 1U;
4843 // Round the size of the allocation up to the stack alignment size
4844 // by add SA-1 to the size. This doesn't overflow because we're computing
4845 // an address inside an alloca.
4846 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4847 DAG.getConstant(StackAlignMask, dl, IntPtr),
4849
4850 // Mask out the low bits for alignment purposes.
4851 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4852 DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4853
4854 SDValue Ops[] = {
4855 getRoot(), AllocSize,
4856 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4857 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4858 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4859 setValue(&I, DSA);
4860 DAG.setRoot(DSA.getValue(1));
4861
4862 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4863}
4864
4865static const MDNode *getRangeMetadata(const Instruction &I) {
4866 return I.getMetadata(LLVMContext::MD_range);
4867}
4868
4869static std::optional<ConstantRange> getRange(const Instruction &I) {
4870 if (const auto *CB = dyn_cast<CallBase>(&I))
4871 if (std::optional<ConstantRange> CR = CB->getRange())
4872 return CR;
4873 if (const MDNode *Range = getRangeMetadata(I))
4875 return std::nullopt;
4876}
4877
4879 if (const auto *CB = dyn_cast<CallBase>(&I))
4880 return CB->getRetNoFPClass();
4881 return fcNone;
4882}
4883
4884void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4885 if (I.isAtomic())
4886 return visitAtomicLoad(I);
4887
4888 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4889 const Value *SV = I.getOperand(0);
4890 if (TLI.supportSwiftError()) {
4891 // Swifterror values can come from either a function parameter with
4892 // swifterror attribute or an alloca with swifterror attribute.
4893 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4894 if (Arg->hasSwiftErrorAttr())
4895 return visitLoadFromSwiftError(I);
4896 }
4897
4898 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4899 if (Alloca->isSwiftError())
4900 return visitLoadFromSwiftError(I);
4901 }
4902 }
4903
4904 SDValue Ptr = getValue(SV);
4905
4906 Type *Ty = I.getType();
4907 SmallVector<EVT, 4> ValueVTs, MemVTs;
4909 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4910 unsigned NumValues = ValueVTs.size();
4911 if (NumValues == 0)
4912 return;
4913
4914 Align Alignment = I.getAlign();
4915 AAMDNodes AAInfo = I.getAAMetadata();
4916 const MDNode *Ranges = getRangeMetadata(I);
4917 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
4918 bool isVolatile = I.isVolatile();
4919 MachineMemOperand::Flags MMOFlags =
4920 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4921
4922 SDValue Root;
4923 bool ConstantMemory = false;
4924 if (isVolatile)
4925 // Serialize volatile loads with other side effects.
4926 Root = getRoot();
4927 else if (NumValues > MaxParallelChains)
4928 Root = getMemoryRoot();
4929 else if (BatchAA &&
4930 BatchAA->pointsToConstantMemory(MemoryLocation(
4931 SV,
4932 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4933 AAInfo))) {
4934 // Do not serialize (non-volatile) loads of constant memory with anything.
4935 Root = DAG.getEntryNode();
4936 ConstantMemory = true;
4938 } else {
4939 // Do not serialize non-volatile loads against each other.
4940 Root = DAG.getRoot();
4941 }
4942
4943 SDLoc dl = getCurSDLoc();
4944
4945 if (isVolatile)
4946 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4947
4949 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4950
4951 unsigned ChainI = 0;
4952 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4953 // Serializing loads here may result in excessive register pressure, and
4954 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4955 // could recover a bit by hoisting nodes upward in the chain by recognizing
4956 // they are side-effect free or do not alias. The optimizer should really
4957 // avoid this case by converting large object/array copies to llvm.memcpy
4958 // (MaxParallelChains should always remain as failsafe).
4959 if (ChainI == MaxParallelChains) {
4960 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4961 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4962 ArrayRef(Chains.data(), ChainI));
4963 Root = Chain;
4964 ChainI = 0;
4965 }
4966
4967 // TODO: MachinePointerInfo only supports a fixed length offset.
4968 MachinePointerInfo PtrInfo =
4969 !Offsets[i].isScalable() || Offsets[i].isZero()
4970 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4971 : MachinePointerInfo();
4972
4973 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4974 SDValue L =
4975 DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, MMOFlags,
4976 MMOMetadata(AAInfo, Ranges, MemCacheHint));
4977 Chains[ChainI] = L.getValue(1);
4978
4979 if (MemVTs[i] != ValueVTs[i])
4980 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4981
4982 if (MDNode *NoFPClassMD = I.getMetadata(LLVMContext::MD_nofpclass)) {
4983 uint64_t FPTestInt =
4984 cast<ConstantInt>(
4985 cast<ConstantAsMetadata>(NoFPClassMD->getOperand(0))->getValue())
4986 ->getZExtValue();
4987 if (FPTestInt != fcNone) {
4988 SDValue FPTestConst =
4989 DAG.getTargetConstant(FPTestInt, SDLoc(), MVT::i32);
4990 L = DAG.getNode(ISD::AssertNoFPClass, dl, L.getValueType(), L,
4991 FPTestConst);
4992 }
4993 }
4994 Values[i] = L;
4995 }
4996
4997 if (!ConstantMemory) {
4998 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4999 ArrayRef(Chains.data(), ChainI));
5000 if (isVolatile)
5001 DAG.setRoot(Chain);
5002 else
5003 PendingLoads.push_back(Chain);
5004 }
5005
5006 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
5007 DAG.getVTList(ValueVTs), Values));
5008}
5009
5010void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
5011 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
5012 "call visitStoreToSwiftError when backend supports swifterror");
5013
5014 SmallVector<EVT, 4> ValueVTs;
5015 SmallVector<uint64_t, 4> Offsets;
5016 const Value *SrcV = I.getOperand(0);
5017 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
5018 SrcV->getType(), ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
5019 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
5020 "expect a single EVT for swifterror");
5021
5022 SDValue Src = getValue(SrcV);
5023 // Create a virtual register, then update the virtual register.
5024 Register VReg =
5025 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
5026 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
5027 // Chain can be getRoot or getControlRoot.
5028 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
5029 SDValue(Src.getNode(), Src.getResNo()));
5030 DAG.setRoot(CopyNode);
5031}
5032
5033void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
5034 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
5035 "call visitLoadFromSwiftError when backend supports swifterror");
5036
5037 assert(!I.isVolatile() &&
5038 !I.hasMetadata(LLVMContext::MD_nontemporal) &&
5039 !I.hasMetadata(LLVMContext::MD_invariant_load) &&
5040 "Support volatile, non temporal, invariant for load_from_swift_error");
5041
5042 const Value *SV = I.getOperand(0);
5043 Type *Ty = I.getType();
5044 assert(
5045 (!BatchAA ||
5046 !BatchAA->pointsToConstantMemory(MemoryLocation(
5047 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
5048 I.getAAMetadata()))) &&
5049 "load_from_swift_error should not be constant memory");
5050
5051 SmallVector<EVT, 4> ValueVTs;
5052 SmallVector<uint64_t, 4> Offsets;
5053 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
5054 ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
5055 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
5056 "expect a single EVT for swifterror");
5057
5058 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
5059 SDValue L = DAG.getCopyFromReg(
5060 getRoot(), getCurSDLoc(),
5061 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
5062
5063 setValue(&I, L);
5064}
5065
5066void SelectionDAGBuilder::visitStore(const StoreInst &I) {
5067 if (I.isAtomic())
5068 return visitAtomicStore(I);
5069
5070 const Value *SrcV = I.getOperand(0);
5071 const Value *PtrV = I.getOperand(1);
5072
5073 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5074 if (TLI.supportSwiftError()) {
5075 // Swifterror values can come from either a function parameter with
5076 // swifterror attribute or an alloca with swifterror attribute.
5077 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
5078 if (Arg->hasSwiftErrorAttr())
5079 return visitStoreToSwiftError(I);
5080 }
5081
5082 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
5083 if (Alloca->isSwiftError())
5084 return visitStoreToSwiftError(I);
5085 }
5086 }
5087
5088 SmallVector<EVT, 4> ValueVTs, MemVTs;
5090 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
5091 SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
5092 unsigned NumValues = ValueVTs.size();
5093 if (NumValues == 0)
5094 return;
5095
5096 // Get the lowered operands. Note that we do this after
5097 // checking if NumResults is zero, because with zero results
5098 // the operands won't have values in the map.
5099 SDValue Src = getValue(SrcV);
5100 SDValue Ptr = getValue(PtrV);
5101
5102 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
5103 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
5104 SDLoc dl = getCurSDLoc();
5105 Align Alignment = I.getAlign();
5106 AAMDNodes AAInfo = I.getAAMetadata();
5107 const MDNode *MemCacheHint =
5108 getMemCacheHintMetadata(I, I.getPointerOperandIndex());
5109
5110 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5111
5112 unsigned ChainI = 0;
5113 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
5114 // See visitLoad comments.
5115 if (ChainI == MaxParallelChains) {
5116 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5117 ArrayRef(Chains.data(), ChainI));
5118 Root = Chain;
5119 ChainI = 0;
5120 }
5121
5122 // TODO: MachinePointerInfo only supports a fixed length offset.
5123 MachinePointerInfo PtrInfo =
5124 !Offsets[i].isScalable() || Offsets[i].isZero()
5125 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
5126 : MachinePointerInfo();
5127
5128 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
5129 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
5130 if (MemVTs[i] != ValueVTs[i])
5131 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
5132 SDValue St =
5133 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags,
5134 MMOMetadata(AAInfo, /*Ranges=*/nullptr, MemCacheHint));
5135 Chains[ChainI] = St;
5136 }
5137
5138 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5139 ArrayRef(Chains.data(), ChainI));
5140 setValue(&I, StoreNode);
5141 DAG.setRoot(StoreNode);
5142}
5143
5144void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
5145 bool IsCompressing) {
5146 SDLoc sdl = getCurSDLoc();
5147
5148 Value *Src0Operand = I.getArgOperand(0);
5149 Value *PtrOperand = I.getArgOperand(1);
5150 Value *MaskOperand = I.getArgOperand(2);
5151 Align Alignment = I.getParamAlign(1).valueOrOne();
5152
5153 SDValue Ptr = getValue(PtrOperand);
5154 SDValue Src0 = getValue(Src0Operand);
5155 SDValue Mask = getValue(MaskOperand);
5156 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5157
5158 EVT VT = Src0.getValueType();
5159
5160 const auto &TLI = DAG.getTargetLoweringInfo();
5161
5162 auto MMOFlags = MachineMemOperand::MOStore;
5163 MMOFlags |= TLI.getTargetMMOFlags(I);
5164 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5166
5167 const MDNode *MemCacheHint = getMemCacheHintMetadata(I, /*OperandNo=*/1);
5168
5169 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5170 MachinePointerInfo(PtrOperand), MMOFlags,
5171 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5172 MMOMetadata(I.getAAMetadata(), /*Ranges=*/nullptr, MemCacheHint));
5173
5174 SDValue StoreNode =
5175 !IsCompressing && TTI->hasConditionalLoadStoreForType(
5176 I.getArgOperand(0)->getType(), /*IsStore=*/true)
5177 ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
5178 Mask)
5179 : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
5180 VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
5181 IsCompressing);
5182 DAG.setRoot(StoreNode);
5183 setValue(&I, StoreNode);
5184}
5185
5186// Get a uniform base for the Gather/Scatter intrinsic.
5187// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
5188// We try to represent it as a base pointer + vector of indices.
5189// Usually, the vector of pointers comes from a 'getelementptr' instruction.
5190// The first operand of the GEP may be a single pointer or a vector of pointers
5191// Example:
5192// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
5193// or
5194// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
5195// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
5196//
5197// When the first GEP operand is a single pointer - it is the uniform base we
5198// are looking for. If first operand of the GEP is a splat vector - we
5199// extract the splat value and use it as a uniform base.
5200// In all other cases the function returns 'false'.
5201static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
5202 SDValue &Scale, SelectionDAGBuilder *SDB,
5203 const BasicBlock *CurBB, uint64_t ElemSize) {
5204 SelectionDAG& DAG = SDB->DAG;
5205 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5206 const DataLayout &DL = DAG.getDataLayout();
5207
5208 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
5209
5210 // Handle splat constant pointer.
5211 if (auto *C = dyn_cast<Constant>(Ptr)) {
5212 C = C->getSplatValue();
5213 if (!C)
5214 return false;
5215
5216 Base = SDB->getValue(C);
5217
5218 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
5219 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
5220 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
5221 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5222 return true;
5223 }
5224
5226 if (!GEP || GEP->getParent() != CurBB)
5227 return false;
5228
5229 if (GEP->getNumOperands() != 2)
5230 return false;
5231
5232 const Value *BasePtr = GEP->getPointerOperand();
5233 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
5234
5235 // Make sure the base is scalar and the index is a vector.
5236 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
5237 return false;
5238
5239 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
5240 if (ScaleVal.isScalable())
5241 return false;
5242
5243 // Target may not support the required addressing mode.
5244 if (ScaleVal != 1 &&
5245 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
5246 return false;
5247
5248 Base = SDB->getValue(BasePtr);
5249 Index = SDB->getValue(IndexVal);
5250
5251 Scale =
5252 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5253 return true;
5254}
5255
5256void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
5257 SDLoc sdl = getCurSDLoc();
5258
5259 // llvm.masked.scatter.*(Src0, Ptrs, Mask)
5260 const Value *Ptr = I.getArgOperand(1);
5261 SDValue Src0 = getValue(I.getArgOperand(0));
5262 SDValue Mask = getValue(I.getArgOperand(2));
5263 EVT VT = Src0.getValueType();
5264 Align Alignment = I.getParamAlign(1).valueOrOne();
5265 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5266
5267 SDValue Base;
5268 SDValue Index;
5269 SDValue Scale;
5270 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5271 I.getParent(), VT.getScalarStoreSize());
5272
5273 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5274 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5275 MachinePointerInfo(AS), MachineMemOperand::MOStore,
5276 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
5277 if (!UniformBase) {
5278 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5279 Index = getValue(Ptr);
5280 Scale =
5281 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5282 }
5283
5284 EVT IdxVT = Index.getValueType();
5285 EVT EltTy = IdxVT.getVectorElementType();
5286 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5287 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5288 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5289 }
5290
5291 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
5292 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
5293 Ops, MMO, ISD::SIGNED_SCALED, false);
5294 DAG.setRoot(Scatter);
5295 setValue(&I, Scatter);
5296}
5297
5298void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
5299 SDLoc sdl = getCurSDLoc();
5300
5301 Value *PtrOperand = I.getArgOperand(0);
5302 Value *MaskOperand = I.getArgOperand(1);
5303 Value *Src0Operand = I.getArgOperand(2);
5304 Align Alignment = I.getParamAlign(0).valueOrOne();
5305
5306 SDValue Ptr = getValue(PtrOperand);
5307 SDValue Src0 = getValue(Src0Operand);
5308 SDValue Mask = getValue(MaskOperand);
5309 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5310
5311 EVT VT = Src0.getValueType();
5312 AAMDNodes AAInfo = I.getAAMetadata();
5313 const MDNode *Ranges = getRangeMetadata(I);
5314 const MDNode *MemCacheHint = getMemCacheHintMetadata(I, /*OperandNo=*/0);
5315
5316 // Do not serialize masked loads of constant memory with anything.
5317 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
5318 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
5319
5320 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
5321
5322 const auto &TLI = DAG.getTargetLoweringInfo();
5323
5324 auto MMOFlags = MachineMemOperand::MOLoad;
5325 MMOFlags |= TLI.getTargetMMOFlags(I);
5326 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5328 if (I.hasMetadata(LLVMContext::MD_invariant_load))
5330
5331 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5332 MachinePointerInfo(PtrOperand), MMOFlags,
5333 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5334 MMOMetadata(AAInfo, Ranges, MemCacheHint));
5335
5336 // The Load/Res may point to different values and both of them are output
5337 // variables.
5338 SDValue Load;
5339 SDValue Res;
5340 if (!IsExpanding &&
5341 TTI->hasConditionalLoadStoreForType(Src0Operand->getType(),
5342 /*IsStore=*/false))
5343 Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
5344 else
5345 Res = Load =
5346 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
5347 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5348 if (AddToChain)
5349 PendingLoads.push_back(Load.getValue(1));
5350 setValue(&I, Res);
5351}
5352
5353void SelectionDAGBuilder::visitSpeculativeLoad(const CallInst &I) {
5354 SDLoc sdl = getCurSDLoc();
5355 Value *PtrOperand = I.getArgOperand(0);
5356 // The remaining arguments (num_accessible_bytes or oracle function + args)
5357 // are IR-level semantics only; they are not needed at codegen.
5358 SDValue Ptr = getValue(PtrOperand);
5359
5360 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5361 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5362 Align Alignment = I.getParamAlign(0).valueOrOne();
5363 AAMDNodes AAInfo = I.getAAMetadata();
5364
5365 SDValue InChain = DAG.getRoot();
5366
5367 // Use MOLoad but NOT MODereferenceable - the memory may not be
5368 // fully dereferenceable.
5369 auto MMOFlags = MachineMemOperand::MOLoad;
5370 MMOFlags |= TLI.getTargetMMOFlags(I);
5371 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5373 if (I.hasMetadata(LLVMContext::MD_invariant_load))
5375
5376 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5377 MachinePointerInfo(PtrOperand), MMOFlags,
5378 LocationSize::precise(VT.getStoreSize()), Alignment, AAInfo);
5379
5380 SDValue Load = DAG.getLoad(VT, sdl, InChain, Ptr, MMO);
5381 PendingLoads.push_back(Load.getValue(1));
5382 setValue(&I, Load);
5383}
5384
5385void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5386 SDLoc sdl = getCurSDLoc();
5387
5388 // @llvm.masked.gather.*(Ptrs, Mask, Src0)
5389 const Value *Ptr = I.getArgOperand(0);
5390 SDValue Src0 = getValue(I.getArgOperand(2));
5391 SDValue Mask = getValue(I.getArgOperand(1));
5392
5393 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5394 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5395 Align Alignment = I.getParamAlign(0).valueOrOne();
5396
5397 const MDNode *Ranges = getRangeMetadata(I);
5398
5399 SDValue Root = DAG.getRoot();
5400 SDValue Base;
5401 SDValue Index;
5402 SDValue Scale;
5403 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5404 I.getParent(), VT.getScalarStoreSize());
5405 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5406 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5407 MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5409 MMOMetadata(I.getAAMetadata(), Ranges));
5410
5411 if (!UniformBase) {
5412 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5413 Index = getValue(Ptr);
5414 Scale =
5415 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5416 }
5417
5418 EVT IdxVT = Index.getValueType();
5419 EVT EltTy = IdxVT.getVectorElementType();
5420 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5421 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5422 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5423 }
5424
5425 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5426 SDValue Gather =
5427 DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, Ops, MMO,
5429
5430 PendingLoads.push_back(Gather.getValue(1));
5431 setValue(&I, Gather);
5432}
5433
5434void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5435 SDLoc dl = getCurSDLoc();
5436 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5437 AtomicOrdering FailureOrdering = I.getFailureOrdering();
5438 SyncScope::ID SSID = I.getSyncScopeID();
5439
5440 SDValue InChain = getRoot();
5441
5442 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5443 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5444
5445 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5446 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5447
5448 MachineFunction &MF = DAG.getMachineFunction();
5449 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5450 MachineMemOperand *MMO = MF.getMachineMemOperand(
5451 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5452 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5453 SSID, SuccessOrdering, FailureOrdering);
5454
5455 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5456 dl, MemVT, VTs, InChain,
5457 getValue(I.getPointerOperand()),
5458 getValue(I.getCompareOperand()),
5459 getValue(I.getNewValOperand()), MMO);
5460
5461 SDValue OutChain = L.getValue(2);
5462
5463 setValue(&I, L);
5464 DAG.setRoot(OutChain);
5465}
5466
5467void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5468 SDLoc dl = getCurSDLoc();
5470 switch (I.getOperation()) {
5471 default: llvm_unreachable("Unknown atomicrmw operation");
5489 break;
5492 break;
5495 break;
5498 break;
5501 break;
5504 break;
5507 break;
5510 break;
5511 }
5512 AtomicOrdering Ordering = I.getOrdering();
5513 SyncScope::ID SSID = I.getSyncScopeID();
5514
5515 SDValue InChain = getRoot();
5516
5517 auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5518 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5519 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5520
5521 MachineFunction &MF = DAG.getMachineFunction();
5522 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5523 MachineMemOperand *MMO = MF.getMachineMemOperand(
5524 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5525 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5526 SSID, Ordering);
5527
5528 SDValue L =
5529 DAG.getAtomic(NT, dl, MemVT, InChain,
5530 getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5531 MMO);
5532
5533 SDValue OutChain = L.getValue(1);
5534
5535 setValue(&I, L);
5536 DAG.setRoot(OutChain);
5537}
5538
5539void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5540 SDLoc dl = getCurSDLoc();
5541 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5542 SDValue Ops[3];
5543 Ops[0] = getRoot();
5544 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5545 TLI.getFenceOperandTy(DAG.getDataLayout()));
5546 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5547 TLI.getFenceOperandTy(DAG.getDataLayout()));
5548 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5549 setValue(&I, N);
5550 DAG.setRoot(N);
5551}
5552
5553void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5554 SDLoc dl = getCurSDLoc();
5555 AtomicOrdering Order = I.getOrdering();
5556 SyncScope::ID SSID = I.getSyncScopeID();
5557
5558 SDValue InChain = getRoot();
5559
5560 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5561 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5562 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5563
5564 if (!TLI.isAtomicAlignmentSupported(I.getAlign(), MemVT.getSizeInBits() / 8))
5565 report_fatal_error("Cannot generate unaligned atomic load");
5566
5567 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5568
5569 const MDNode *Ranges = getRangeMetadata(I);
5570 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5571 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5572 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5573 I.getAlign(), MMOMetadata(AAMDNodes(), Ranges, MemCacheHint), SSID,
5574 Order);
5575
5576 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5577
5578 SDValue Ptr = getValue(I.getPointerOperand());
5579 SDValue L =
5580 DAG.getAtomicLoad(ISD::NON_EXTLOAD, dl, MemVT, MemVT, InChain, Ptr, MMO);
5581
5582 SDValue OutChain = L.getValue(1);
5583 if (MemVT != VT)
5584 L = DAG.getPtrExtOrTrunc(L, dl, VT);
5585
5586 setValue(&I, L);
5587 DAG.setRoot(OutChain);
5588}
5589
5590void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5591 SDLoc dl = getCurSDLoc();
5592
5593 AtomicOrdering Ordering = I.getOrdering();
5594 SyncScope::ID SSID = I.getSyncScopeID();
5595
5596 SDValue InChain = getRoot();
5597
5598 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5599 EVT MemVT =
5600 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5601
5602 if (!TLI.isAtomicAlignmentSupported(I.getAlign(), MemVT.getSizeInBits() / 8))
5603 report_fatal_error("Cannot generate unaligned atomic store");
5604
5605 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5606
5607 MachineFunction &MF = DAG.getMachineFunction();
5608 const MDNode *MemCacheHint =
5609 getMemCacheHintMetadata(I, I.getPointerOperandIndex());
5610 MachineMemOperand *MMO = MF.getMachineMemOperand(
5611 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5612 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5613 SSID, Ordering);
5614
5615 SDValue Val = getValue(I.getValueOperand());
5616 if (Val.getValueType() != MemVT)
5617 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5618 SDValue Ptr = getValue(I.getPointerOperand());
5619
5620 SDValue OutChain =
5621 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5622
5623 setValue(&I, OutChain);
5624 DAG.setRoot(OutChain);
5625}
5626
5627/// Check if this intrinsic call depends on the chain (1st return value)
5628/// and if it only *loads* memory.
5629/// Ignore the callsite's attributes. A specific call site may be marked with
5630/// readnone, but the lowering code will expect the chain based on the
5631/// definition.
5632std::pair<bool, bool>
5633SelectionDAGBuilder::getTargetIntrinsicCallProperties(const CallBase &I) {
5634 const Function *F = I.getCalledFunction();
5635 bool HasChain = !F->doesNotAccessMemory();
5636 bool OnlyLoad =
5637 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5638
5639 return {HasChain, OnlyLoad};
5640}
5641
5642SmallVector<SDValue, 8> SelectionDAGBuilder::getTargetIntrinsicOperands(
5643 const CallBase &I, bool HasChain, bool OnlyLoad,
5644 TargetLowering::IntrinsicInfo *TgtMemIntrinsicInfo) {
5645 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5646
5647 // Build the operand list.
5649 if (HasChain) { // If this intrinsic has side-effects, chainify it.
5650 if (OnlyLoad) {
5651 // We don't need to serialize loads against other loads.
5652 Ops.push_back(DAG.getRoot());
5653 } else {
5654 Ops.push_back(getRoot());
5655 }
5656 }
5657
5658 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5659 if (!TgtMemIntrinsicInfo || TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_VOID ||
5660 TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_W_CHAIN)
5661 Ops.push_back(DAG.getTargetConstant(I.getIntrinsicID(), getCurSDLoc(),
5662 TLI.getPointerTy(DAG.getDataLayout())));
5663
5664 // Add all operands of the call to the operand list.
5665 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5666 const Value *Arg = I.getArgOperand(i);
5667 if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5668 Ops.push_back(getValue(Arg));
5669 continue;
5670 }
5671
5672 // Use TargetConstant instead of a regular constant for immarg.
5673 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5674 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5675 assert(CI->getBitWidth() <= 64 &&
5676 "large intrinsic immediates not handled");
5677 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5678 } else {
5679 Ops.push_back(
5680 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5681 }
5682 }
5683
5684 if (std::optional<OperandBundleUse> Bundle =
5685 I.getOperandBundle(LLVMContext::OB_deactivation_symbol)) {
5686 auto *Sym = Bundle->Inputs[0].get();
5687 SDValue SDSym = getValue(Sym);
5688 SDSym = DAG.getDeactivationSymbol(cast<GlobalValue>(Sym));
5689 Ops.push_back(SDSym);
5690 }
5691
5692 if (std::optional<OperandBundleUse> Bundle =
5693 I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5694 Value *Token = Bundle->Inputs[0].get();
5695 SDValue ConvControlToken = getValue(Token);
5696 assert(Ops.back().getValueType() != MVT::Glue &&
5697 "Did not expect another glue node here.");
5698 ConvControlToken =
5699 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5700 Ops.push_back(ConvControlToken);
5701 }
5702
5703 return Ops;
5704}
5705
5706SDVTList SelectionDAGBuilder::getTargetIntrinsicVTList(const CallBase &I,
5707 bool HasChain) {
5708 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5709
5710 SmallVector<EVT, 4> ValueVTs;
5711 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5712
5713 if (HasChain)
5714 ValueVTs.push_back(MVT::Other);
5715
5716 return DAG.getVTList(ValueVTs);
5717}
5718
5719/// Get an INTRINSIC node for a target intrinsic which does not touch memory.
5720SDValue SelectionDAGBuilder::getTargetNonMemIntrinsicNode(
5721 const Type &IntrinsicVT, bool HasChain, ArrayRef<SDValue> Ops,
5722 const SDVTList &VTs) {
5723 if (!HasChain)
5724 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5725 if (!IntrinsicVT.isVoidTy())
5726 return DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5727 return DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5728}
5729
5730/// Set root, convert return type if necessary and check alignment.
5731SDValue SelectionDAGBuilder::handleTargetIntrinsicRet(const CallBase &I,
5732 bool HasChain,
5733 bool OnlyLoad,
5734 SDValue Result) {
5735 if (HasChain) {
5736 SDValue Chain = Result.getValue(Result.getNode()->getNumValues() - 1);
5737 if (OnlyLoad)
5738 PendingLoads.push_back(Chain);
5739 else
5740 DAG.setRoot(Chain);
5741 }
5742
5743 if (I.getType()->isVoidTy())
5744 return Result;
5745
5746 if (MaybeAlign Alignment = I.getRetAlign(); InsertAssertAlign && Alignment) {
5747 // Insert `assertalign` node if there's an alignment.
5748 Result = DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5749 } else if (!isa<VectorType>(I.getType())) {
5750 Result = lowerRangeToAssertZExt(DAG, I, Result);
5751 }
5752
5753 return Result;
5754}
5755
5756/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5757/// node.
5758void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5759 unsigned Intrinsic) {
5760 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
5761 Intrinsic::ID IntrinsicID = static_cast<Intrinsic::ID>(Intrinsic);
5762
5763 if (!DAG.getMachineFunction().getSubtarget().isIntrinsicSupported(
5764 Intrinsic)) {
5765 SDLoc DL = getCurSDLoc();
5766 DAG.getContext()->diagnose(DiagnosticInfoUnsupportedTargetIntrinsic(
5767 *I.getFunction(), IntrinsicID, DL.getDebugLoc()));
5768
5769 // The intrinsic is not available on this subtarget. Preserve the chain for
5770 // side-effecting intrinsics and lower any result to poison so that
5771 // compilation can continue and collect further diagnostics.
5772 if (HasChain && !OnlyLoad)
5773 DAG.setRoot(getRoot());
5774
5776 return;
5777 }
5778
5779 // Infos is set by getTgtMemIntrinsic.
5781 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5782 TLI.getTgtMemIntrinsic(Infos, I, DAG.getMachineFunction(), Intrinsic);
5783 // Use the first (primary) info determines the node opcode.
5784 TargetLowering::IntrinsicInfo *Info = !Infos.empty() ? &Infos[0] : nullptr;
5785
5787 getTargetIntrinsicOperands(I, HasChain, OnlyLoad, Info);
5788 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
5789
5790 // Propagate fast-math-flags from IR to node(s).
5791 SDNodeFlags Flags;
5792 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5793 Flags.copyFMF(*FPMO);
5794 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5795
5796 // Create the node.
5797 SDValue Result;
5798
5799 // In some cases, custom collection of operands from CallInst I may be needed.
5801 if (!Infos.empty()) {
5802 // This is target intrinsic that touches memory
5803 // Create MachineMemOperands for each memory access described by the target.
5804 MachineFunction &MF = DAG.getMachineFunction();
5806 for (const auto &Info : Infos) {
5807 // TODO: We currently just fallback to address space 0 if
5808 // getTgtMemIntrinsic didn't yield anything useful.
5809 MachinePointerInfo MPI;
5810 if (Info.ptrVal)
5811 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5812 else if (Info.fallbackAddressSpace)
5813 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5814 EVT MemVT = Info.memVT;
5815 LocationSize Size = LocationSize::precise(Info.size);
5816 if (Size.hasValue() && !Size.getValue())
5818 Align Alignment = Info.align.value_or(DAG.getEVTAlign(MemVT));
5819 MachineMemOperand *MMO = MF.getMachineMemOperand(
5820 MPI, Info.flags, Size, Alignment, I.getAAMetadata(), Info.ssid,
5821 Info.order, Info.failureOrder);
5822 MMOs.push_back(MMO);
5823 }
5824
5825 Result = DAG.getMemIntrinsicNode(Info->opc, getCurSDLoc(), VTs, Ops,
5826 Info->memVT, MMOs);
5827 } else {
5828 Result = getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
5829 }
5830
5831 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
5832
5833 setValue(&I, Result);
5834}
5835
5836/// GetSignificand - Get the significand and build it into a floating-point
5837/// number with exponent of 1:
5838///
5839/// Op = (Op & 0x007fffff) | 0x3f800000;
5840///
5841/// where Op is the hexadecimal representation of floating point value.
5843 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5844 DAG.getConstant(0x007fffff, dl, MVT::i32));
5845 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5846 DAG.getConstant(0x3f800000, dl, MVT::i32));
5847 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5848}
5849
5850/// GetExponent - Get the exponent:
5851///
5852/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5853///
5854/// where Op is the hexadecimal representation of floating point value.
5856 const TargetLowering &TLI, const SDLoc &dl) {
5857 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5858 DAG.getConstant(0x7f800000, dl, MVT::i32));
5859 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
5860 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5861 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5862 DAG.getConstant(127, dl, MVT::i32));
5863 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5864}
5865
5866/// getF32Constant - Get 32-bit floating point constant.
5867static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5868 const SDLoc &dl) {
5869 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5870 MVT::f32);
5871}
5872
5874 SelectionDAG &DAG) {
5875 // TODO: What fast-math-flags should be set on the floating-point nodes?
5876
5877 // IntegerPartOfX = ((int32_t)(t0);
5878 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5879
5880 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
5881 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5882 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5883
5884 // IntegerPartOfX <<= 23;
5885 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5886 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5887
5888 SDValue TwoToFractionalPartOfX;
5889 if (LimitFloatPrecision <= 6) {
5890 // For floating-point precision of 6:
5891 //
5892 // TwoToFractionalPartOfX =
5893 // 0.997535578f +
5894 // (0.735607626f + 0.252464424f * x) * x;
5895 //
5896 // error 0.0144103317, which is 6 bits
5897 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5898 getF32Constant(DAG, 0x3e814304, dl));
5899 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5900 getF32Constant(DAG, 0x3f3c50c8, dl));
5901 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5902 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5903 getF32Constant(DAG, 0x3f7f5e7e, dl));
5904 } else if (LimitFloatPrecision <= 12) {
5905 // For floating-point precision of 12:
5906 //
5907 // TwoToFractionalPartOfX =
5908 // 0.999892986f +
5909 // (0.696457318f +
5910 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
5911 //
5912 // error 0.000107046256, which is 13 to 14 bits
5913 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5914 getF32Constant(DAG, 0x3da235e3, dl));
5915 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5916 getF32Constant(DAG, 0x3e65b8f3, dl));
5917 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5918 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5919 getF32Constant(DAG, 0x3f324b07, dl));
5920 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5921 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5922 getF32Constant(DAG, 0x3f7ff8fd, dl));
5923 } else { // LimitFloatPrecision <= 18
5924 // For floating-point precision of 18:
5925 //
5926 // TwoToFractionalPartOfX =
5927 // 0.999999982f +
5928 // (0.693148872f +
5929 // (0.240227044f +
5930 // (0.554906021e-1f +
5931 // (0.961591928e-2f +
5932 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5933 // error 2.47208000*10^(-7), which is better than 18 bits
5934 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5935 getF32Constant(DAG, 0x3924b03e, dl));
5936 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5937 getF32Constant(DAG, 0x3ab24b87, dl));
5938 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5939 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5940 getF32Constant(DAG, 0x3c1d8c17, dl));
5941 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5942 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5943 getF32Constant(DAG, 0x3d634a1d, dl));
5944 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5945 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5946 getF32Constant(DAG, 0x3e75fe14, dl));
5947 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5948 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5949 getF32Constant(DAG, 0x3f317234, dl));
5950 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5951 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5952 getF32Constant(DAG, 0x3f800000, dl));
5953 }
5954
5955 // Add the exponent into the result in integer domain.
5956 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5957 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5958 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5959}
5960
5961/// expandExp - Lower an exp intrinsic. Handles the special sequences for
5962/// limited-precision mode.
5964 const TargetLowering &TLI, SDNodeFlags Flags) {
5965 if (Op.getValueType() == MVT::f32 &&
5967
5968 // Put the exponent in the right bit position for later addition to the
5969 // final result:
5970 //
5971 // t0 = Op * log2(e)
5972
5973 // TODO: What fast-math-flags should be set here?
5974 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5975 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5976 return getLimitedPrecisionExp2(t0, dl, DAG);
5977 }
5978
5979 // No special expansion.
5980 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5981}
5982
5983/// expandLog - Lower a log intrinsic. Handles the special sequences for
5984/// limited-precision mode.
5986 const TargetLowering &TLI, SDNodeFlags Flags) {
5987 // TODO: What fast-math-flags should be set on the floating-point nodes?
5988
5989 if (Op.getValueType() == MVT::f32 &&
5991 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5992
5993 // Scale the exponent by log(2).
5994 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5995 SDValue LogOfExponent =
5996 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5997 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5998
5999 // Get the significand and build it into a floating-point number with
6000 // exponent of 1.
6001 SDValue X = GetSignificand(DAG, Op1, dl);
6002
6003 SDValue LogOfMantissa;
6004 if (LimitFloatPrecision <= 6) {
6005 // For floating-point precision of 6:
6006 //
6007 // LogofMantissa =
6008 // -1.1609546f +
6009 // (1.4034025f - 0.23903021f * x) * x;
6010 //
6011 // error 0.0034276066, which is better than 8 bits
6012 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6013 getF32Constant(DAG, 0xbe74c456, dl));
6014 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6015 getF32Constant(DAG, 0x3fb3a2b1, dl));
6016 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6017 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6018 getF32Constant(DAG, 0x3f949a29, dl));
6019 } else if (LimitFloatPrecision <= 12) {
6020 // For floating-point precision of 12:
6021 //
6022 // LogOfMantissa =
6023 // -1.7417939f +
6024 // (2.8212026f +
6025 // (-1.4699568f +
6026 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
6027 //
6028 // error 0.000061011436, which is 14 bits
6029 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6030 getF32Constant(DAG, 0xbd67b6d6, dl));
6031 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6032 getF32Constant(DAG, 0x3ee4f4b8, dl));
6033 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6034 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6035 getF32Constant(DAG, 0x3fbc278b, dl));
6036 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6037 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6038 getF32Constant(DAG, 0x40348e95, dl));
6039 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6040 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6041 getF32Constant(DAG, 0x3fdef31a, dl));
6042 } else { // LimitFloatPrecision <= 18
6043 // For floating-point precision of 18:
6044 //
6045 // LogOfMantissa =
6046 // -2.1072184f +
6047 // (4.2372794f +
6048 // (-3.7029485f +
6049 // (2.2781945f +
6050 // (-0.87823314f +
6051 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
6052 //
6053 // error 0.0000023660568, which is better than 18 bits
6054 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6055 getF32Constant(DAG, 0xbc91e5ac, dl));
6056 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6057 getF32Constant(DAG, 0x3e4350aa, dl));
6058 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6059 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6060 getF32Constant(DAG, 0x3f60d3e3, dl));
6061 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6062 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6063 getF32Constant(DAG, 0x4011cdf0, dl));
6064 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6065 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6066 getF32Constant(DAG, 0x406cfd1c, dl));
6067 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6068 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
6069 getF32Constant(DAG, 0x408797cb, dl));
6070 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
6071 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
6072 getF32Constant(DAG, 0x4006dcab, dl));
6073 }
6074
6075 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
6076 }
6077
6078 // No special expansion.
6079 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
6080}
6081
6082/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
6083/// limited-precision mode.
6085 const TargetLowering &TLI, SDNodeFlags Flags) {
6086 // TODO: What fast-math-flags should be set on the floating-point nodes?
6087
6088 if (Op.getValueType() == MVT::f32 &&
6090 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6091
6092 // Get the exponent.
6093 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
6094
6095 // Get the significand and build it into a floating-point number with
6096 // exponent of 1.
6097 SDValue X = GetSignificand(DAG, Op1, dl);
6098
6099 // Different possible minimax approximations of significand in
6100 // floating-point for various degrees of accuracy over [1,2].
6101 SDValue Log2ofMantissa;
6102 if (LimitFloatPrecision <= 6) {
6103 // For floating-point precision of 6:
6104 //
6105 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
6106 //
6107 // error 0.0049451742, which is more than 7 bits
6108 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6109 getF32Constant(DAG, 0xbeb08fe0, dl));
6110 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6111 getF32Constant(DAG, 0x40019463, dl));
6112 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6113 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6114 getF32Constant(DAG, 0x3fd6633d, dl));
6115 } else if (LimitFloatPrecision <= 12) {
6116 // For floating-point precision of 12:
6117 //
6118 // Log2ofMantissa =
6119 // -2.51285454f +
6120 // (4.07009056f +
6121 // (-2.12067489f +
6122 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
6123 //
6124 // error 0.0000876136000, which is better than 13 bits
6125 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6126 getF32Constant(DAG, 0xbda7262e, dl));
6127 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6128 getF32Constant(DAG, 0x3f25280b, dl));
6129 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6130 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6131 getF32Constant(DAG, 0x4007b923, dl));
6132 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6133 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6134 getF32Constant(DAG, 0x40823e2f, dl));
6135 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6136 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6137 getF32Constant(DAG, 0x4020d29c, dl));
6138 } else { // LimitFloatPrecision <= 18
6139 // For floating-point precision of 18:
6140 //
6141 // Log2ofMantissa =
6142 // -3.0400495f +
6143 // (6.1129976f +
6144 // (-5.3420409f +
6145 // (3.2865683f +
6146 // (-1.2669343f +
6147 // (0.27515199f -
6148 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
6149 //
6150 // error 0.0000018516, which is better than 18 bits
6151 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6152 getF32Constant(DAG, 0xbcd2769e, dl));
6153 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6154 getF32Constant(DAG, 0x3e8ce0b9, dl));
6155 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6156 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6157 getF32Constant(DAG, 0x3fa22ae7, dl));
6158 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6159 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6160 getF32Constant(DAG, 0x40525723, dl));
6161 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6162 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6163 getF32Constant(DAG, 0x40aaf200, dl));
6164 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6165 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
6166 getF32Constant(DAG, 0x40c39dad, dl));
6167 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
6168 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
6169 getF32Constant(DAG, 0x4042902c, dl));
6170 }
6171
6172 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
6173 }
6174
6175 // No special expansion.
6176 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
6177}
6178
6179/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
6180/// limited-precision mode.
6182 const TargetLowering &TLI, SDNodeFlags Flags) {
6183 // TODO: What fast-math-flags should be set on the floating-point nodes?
6184
6185 if (Op.getValueType() == MVT::f32 &&
6187 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6188
6189 // Scale the exponent by log10(2) [0.30102999f].
6190 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
6191 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
6192 getF32Constant(DAG, 0x3e9a209a, dl));
6193
6194 // Get the significand and build it into a floating-point number with
6195 // exponent of 1.
6196 SDValue X = GetSignificand(DAG, Op1, dl);
6197
6198 SDValue Log10ofMantissa;
6199 if (LimitFloatPrecision <= 6) {
6200 // For floating-point precision of 6:
6201 //
6202 // Log10ofMantissa =
6203 // -0.50419619f +
6204 // (0.60948995f - 0.10380950f * x) * x;
6205 //
6206 // error 0.0014886165, which is 6 bits
6207 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6208 getF32Constant(DAG, 0xbdd49a13, dl));
6209 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6210 getF32Constant(DAG, 0x3f1c0789, dl));
6211 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6212 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6213 getF32Constant(DAG, 0x3f011300, dl));
6214 } else if (LimitFloatPrecision <= 12) {
6215 // For floating-point precision of 12:
6216 //
6217 // Log10ofMantissa =
6218 // -0.64831180f +
6219 // (0.91751397f +
6220 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
6221 //
6222 // error 0.00019228036, which is better than 12 bits
6223 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6224 getF32Constant(DAG, 0x3d431f31, dl));
6225 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6226 getF32Constant(DAG, 0x3ea21fb2, dl));
6227 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6228 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6229 getF32Constant(DAG, 0x3f6ae232, dl));
6230 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6231 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6232 getF32Constant(DAG, 0x3f25f7c3, dl));
6233 } else { // LimitFloatPrecision <= 18
6234 // For floating-point precision of 18:
6235 //
6236 // Log10ofMantissa =
6237 // -0.84299375f +
6238 // (1.5327582f +
6239 // (-1.0688956f +
6240 // (0.49102474f +
6241 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
6242 //
6243 // error 0.0000037995730, which is better than 18 bits
6244 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6245 getF32Constant(DAG, 0x3c5d51ce, dl));
6246 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6247 getF32Constant(DAG, 0x3e00685a, dl));
6248 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6249 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6250 getF32Constant(DAG, 0x3efb6798, dl));
6251 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6252 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6253 getF32Constant(DAG, 0x3f88d192, dl));
6254 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6255 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
6256 getF32Constant(DAG, 0x3fc4316c, dl));
6257 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6258 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
6259 getF32Constant(DAG, 0x3f57ce70, dl));
6260 }
6261
6262 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
6263 }
6264
6265 // No special expansion.
6266 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
6267}
6268
6269/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
6270/// limited-precision mode.
6272 const TargetLowering &TLI, SDNodeFlags Flags) {
6273 if (Op.getValueType() == MVT::f32 &&
6275 return getLimitedPrecisionExp2(Op, dl, DAG);
6276
6277 // No special expansion.
6278 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
6279}
6280
6281/// visitPow - Lower a pow intrinsic. Handles the special sequences for
6282/// limited-precision mode with x == 10.0f.
6284 SelectionDAG &DAG, const TargetLowering &TLI,
6285 SDNodeFlags Flags) {
6286 bool IsExp10 = false;
6287 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
6290 APFloat Ten(10.0f);
6291 IsExp10 = LHSC->isExactlyValue(Ten);
6292 }
6293 }
6294
6295 // TODO: What fast-math-flags should be set on the FMUL node?
6296 if (IsExp10) {
6297 // Put the exponent in the right bit position for later addition to the
6298 // final result:
6299 //
6300 // #define LOG2OF10 3.3219281f
6301 // t0 = Op * LOG2OF10;
6302 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
6303 getF32Constant(DAG, 0x40549a78, dl));
6304 return getLimitedPrecisionExp2(t0, dl, DAG);
6305 }
6306
6307 // No special expansion.
6308 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
6309}
6310
6311/// ExpandPowI - Expand a llvm.powi intrinsic.
6313 SelectionDAG &DAG) {
6314 // If RHS is a constant, we can expand this out to a multiplication tree if
6315 // it's beneficial on the target, otherwise we end up lowering to a call to
6316 // __powidf2 (for example).
6318 unsigned Val = RHSC->getSExtValue();
6319
6320 // powi(x, 0) -> 1.0
6321 if (Val == 0)
6322 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
6323
6325 Val, DAG.shouldOptForSize())) {
6326 // Get the exponent as a positive value.
6327 if ((int)Val < 0)
6328 Val = -Val;
6329 // We use the simple binary decomposition method to generate the multiply
6330 // sequence. There are more optimal ways to do this (for example,
6331 // powi(x,15) generates one more multiply than it should), but this has
6332 // the benefit of being both really simple and much better than a libcall.
6333 SDValue Res; // Logically starts equal to 1.0
6334 SDValue CurSquare = LHS;
6335 // TODO: Intrinsics should have fast-math-flags that propagate to these
6336 // nodes.
6337 while (Val) {
6338 if (Val & 1) {
6339 if (Res.getNode())
6340 Res =
6341 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
6342 else
6343 Res = CurSquare; // 1.0*CurSquare.
6344 }
6345
6346 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
6347 CurSquare, CurSquare);
6348 Val >>= 1;
6349 }
6350
6351 // If the original was negative, invert the result, producing 1/(x*x*x).
6352 if (RHSC->getSExtValue() < 0)
6353 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
6354 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
6355 return Res;
6356 }
6357 }
6358
6359 // Otherwise, expand to a libcall.
6360 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
6361}
6362
6363static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
6364 SDValue LHS, SDValue RHS, SDValue Scale,
6365 SelectionDAG &DAG, const TargetLowering &TLI) {
6366 EVT VT = LHS.getValueType();
6367 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
6368 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
6369 LLVMContext &Ctx = *DAG.getContext();
6370
6371 // If the type is legal but the operation isn't, this node might survive all
6372 // the way to operation legalization. If we end up there and we do not have
6373 // the ability to widen the type (if VT*2 is not legal), we cannot expand the
6374 // node.
6375
6376 // Coax the legalizer into expanding the node during type legalization instead
6377 // by bumping the size by one bit. This will force it to Promote, enabling the
6378 // early expansion and avoiding the need to expand later.
6379
6380 // We don't have to do this if Scale is 0; that can always be expanded, unless
6381 // it's a saturating signed operation. Those can experience true integer
6382 // division overflow, a case which we must avoid.
6383
6384 // FIXME: We wouldn't have to do this (or any of the early
6385 // expansion/promotion) if it was possible to expand a libcall of an
6386 // illegal type during operation legalization. But it's not, so things
6387 // get a bit hacky.
6388 unsigned ScaleInt = Scale->getAsZExtVal();
6389 if ((ScaleInt > 0 || (Saturating && Signed)) &&
6390 (TLI.isTypeLegal(VT) ||
6391 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
6393 Opcode, VT, ScaleInt);
6394 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
6395 EVT PromVT;
6396 if (VT.isScalarInteger())
6397 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
6398 else if (VT.isVector()) {
6399 PromVT = VT.getVectorElementType();
6400 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
6401 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
6402 } else
6403 llvm_unreachable("Wrong VT for DIVFIX?");
6404 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
6405 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
6406 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
6407 // For saturating operations, we need to shift up the LHS to get the
6408 // proper saturation width, and then shift down again afterwards.
6409 if (Saturating)
6410 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
6411 DAG.getConstant(1, DL, ShiftTy));
6412 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
6413 if (Saturating)
6414 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
6415 DAG.getConstant(1, DL, ShiftTy));
6416 return DAG.getZExtOrTrunc(Res, DL, VT);
6417 }
6418 }
6419
6420 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
6421}
6422
6423// getUnderlyingArgRegs - Find underlying registers used for a truncated,
6424// bitcasted, or split argument. Returns a list of <Register, size in bits>
6425static void
6426getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
6427 const SDValue &N) {
6428 switch (N.getOpcode()) {
6429 case ISD::CopyFromReg: {
6430 SDValue Op = N.getOperand(1);
6431 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
6432 Op.getValueType().getSizeInBits());
6433 return;
6434 }
6435 case ISD::BITCAST:
6436 case ISD::AssertZext:
6437 case ISD::AssertSext:
6438 case ISD::TRUNCATE:
6439 getUnderlyingArgRegs(Regs, N.getOperand(0));
6440 return;
6441 case ISD::BUILD_PAIR:
6442 case ISD::BUILD_VECTOR:
6444 for (SDValue Op : N->op_values())
6445 getUnderlyingArgRegs(Regs, Op);
6446 return;
6447 default:
6448 return;
6449 }
6450}
6451
6452/// If the DbgValueInst is a dbg_value of a function argument, create the
6453/// corresponding DBG_VALUE machine instruction for it now. At the end of
6454/// instruction selection, they will be inserted to the entry BB.
6455/// We don't currently support this for variadic dbg_values, as they shouldn't
6456/// appear for function arguments or in the prologue.
6457bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6458 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6459 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6460 const Argument *Arg = dyn_cast<Argument>(V);
6461 if (!Arg)
6462 return false;
6463
6464 MachineFunction &MF = DAG.getMachineFunction();
6465 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6466
6467 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6468 // we've been asked to pursue.
6469 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6470 bool Indirect) {
6471 if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6472 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6473 // pointing at the VReg, which will be patched up later.
6474 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6476 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6477 /* isKill */ false, /* isDead */ false,
6478 /* isUndef */ false, /* isEarlyClobber */ false,
6479 /* SubReg */ 0, /* isDebug */ true)});
6480
6481 auto *NewDIExpr = FragExpr;
6482 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6483 // the DIExpression.
6484 if (Indirect)
6485 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6487 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6488 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6489 } else {
6490 // Create a completely standard DBG_VALUE.
6491 auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6492 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6493 }
6494 };
6495
6496 if (Kind == FuncArgumentDbgValueKind::Value) {
6497 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6498 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6499 // the entry block.
6500 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6501 if (!IsInEntryBlock)
6502 return false;
6503
6504 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6505 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6506 // variable that also is a param.
6507 //
6508 // Although, if we are at the top of the entry block already, we can still
6509 // emit using ArgDbgValue. This might catch some situations when the
6510 // dbg.value refers to an argument that isn't used in the entry block, so
6511 // any CopyToReg node would be optimized out and the only way to express
6512 // this DBG_VALUE is by using the physical reg (or FI) as done in this
6513 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
6514 // we should only emit as ArgDbgValue if the Variable is an argument to the
6515 // current function, and the dbg.value intrinsic is found in the entry
6516 // block.
6517 bool VariableIsFunctionInputArg = Variable->isParameter() &&
6518 !DL->getInlinedAt();
6519 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6520 if (!IsInPrologue && !VariableIsFunctionInputArg)
6521 return false;
6522
6523 // Here we assume that a function argument on IR level only can be used to
6524 // describe one input parameter on source level. If we for example have
6525 // source code like this
6526 //
6527 // struct A { long x, y; };
6528 // void foo(struct A a, long b) {
6529 // ...
6530 // b = a.x;
6531 // ...
6532 // }
6533 //
6534 // and IR like this
6535 //
6536 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
6537 // entry:
6538 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6539 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6540 // call void @llvm.dbg.value(metadata i32 %b, "b",
6541 // ...
6542 // call void @llvm.dbg.value(metadata i32 %a1, "b"
6543 // ...
6544 //
6545 // then the last dbg.value is describing a parameter "b" using a value that
6546 // is an argument. But since we already has used %a1 to describe a parameter
6547 // we should not handle that last dbg.value here (that would result in an
6548 // incorrect hoisting of the DBG_VALUE to the function entry).
6549 // Notice that we allow one dbg.value per IR level argument, to accommodate
6550 // for the situation with fragments above.
6551 // If there is no node for the value being handled, we return true to skip
6552 // the normal generation of debug info, as it would kill existing debug
6553 // info for the parameter in case of duplicates.
6554 if (VariableIsFunctionInputArg) {
6555 unsigned ArgNo = Arg->getArgNo();
6556 if (ArgNo >= FuncInfo.DescribedArgs.size())
6557 FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6558 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6559 return !NodeMap[V].getNode();
6560 FuncInfo.DescribedArgs.set(ArgNo);
6561 }
6562 }
6563
6564 bool IsIndirect = false;
6565 std::optional<MachineOperand> Op;
6566 // Some arguments' frame index is recorded during argument lowering.
6567 int FI = FuncInfo.getArgumentFrameIndex(Arg);
6568 if (FI != std::numeric_limits<int>::max())
6570
6572 if (!Op && N.getNode()) {
6573 getUnderlyingArgRegs(ArgRegsAndSizes, N);
6574 Register Reg;
6575 if (ArgRegsAndSizes.size() == 1)
6576 Reg = ArgRegsAndSizes.front().first;
6577
6578 if (Reg && Reg.isVirtual()) {
6579 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6580 Register PR = RegInfo.getLiveInPhysReg(Reg);
6581 if (PR)
6582 Reg = PR;
6583 }
6584 if (Reg) {
6586 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6587 }
6588 }
6589
6590 if (!Op && N.getNode()) {
6591 // Check if frame index is available.
6592 SDValue LCandidate = peekThroughBitcasts(N);
6593 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6594 if (FrameIndexSDNode *FINode =
6595 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6596 Op = MachineOperand::CreateFI(FINode->getIndex());
6597 }
6598
6599 if (!Op) {
6600 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6601 auto splitMultiRegDbgValue =
6602 [&](ArrayRef<std::pair<Register, TypeSize>> SplitRegs) -> bool {
6603 unsigned Offset = 0;
6604 for (const auto &[Reg, RegSizeInBits] : SplitRegs) {
6605 // FIXME: Scalable sizes are not supported in fragment expressions.
6606 if (RegSizeInBits.isScalable())
6607 return false;
6608
6609 // If the expression is already a fragment, the current register
6610 // offset+size might extend beyond the fragment. In this case, only
6611 // the register bits that are inside the fragment are relevant.
6612 int RegFragmentSizeInBits = RegSizeInBits.getFixedValue();
6613 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6614 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6615 // The register is entirely outside the expression fragment,
6616 // so is irrelevant for debug info.
6617 if (Offset >= ExprFragmentSizeInBits)
6618 break;
6619 // The register is partially outside the expression fragment, only
6620 // the low bits within the fragment are relevant for debug info.
6621 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6622 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6623 }
6624 }
6625
6626 auto FragmentExpr = DIExpression::createFragmentExpression(
6627 Expr, Offset, RegFragmentSizeInBits);
6628 Offset += RegSizeInBits.getFixedValue();
6629 // If a valid fragment expression cannot be created, the variable's
6630 // correct value cannot be determined and so it is set as poison.
6631 if (!FragmentExpr) {
6632 SDDbgValue *SDV = DAG.getConstantDbgValue(
6633 Variable, Expr, PoisonValue::get(V->getType()), DL, SDNodeOrder);
6634 DAG.AddDbgValue(SDV, false);
6635 continue;
6636 }
6637 MachineInstr *NewMI = MakeVRegDbgValue(
6638 Reg, *FragmentExpr, Kind != FuncArgumentDbgValueKind::Value);
6639 FuncInfo.ArgDbgValues.push_back(NewMI);
6640 }
6641
6642 return true;
6643 };
6644
6645 // Check if ValueMap has reg number.
6647 VMI = FuncInfo.ValueMap.find(V);
6648 if (VMI != FuncInfo.ValueMap.end()) {
6649 const auto &TLI = DAG.getTargetLoweringInfo();
6650 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6651 V->getType(), std::nullopt);
6652 if (RFV.occupiesMultipleRegs())
6653 return splitMultiRegDbgValue(RFV.getRegsAndSizes());
6654
6655 Op = MachineOperand::CreateReg(VMI->second, false);
6656 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6657 } else if (ArgRegsAndSizes.size() > 1) {
6658 // This was split due to the calling convention, and no virtual register
6659 // mapping exists for the value.
6660 return splitMultiRegDbgValue(ArgRegsAndSizes);
6661 }
6662 }
6663
6664 if (!Op)
6665 return false;
6666
6667 assert(Variable->isValidLocationForIntrinsic(DL) &&
6668 "Expected inlined-at fields to agree");
6669 MachineInstr *NewMI = nullptr;
6670
6671 if (Op->isReg())
6672 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6673 else
6674 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6675 Variable, Expr);
6676
6677 // Otherwise, use ArgDbgValues.
6678 FuncInfo.ArgDbgValues.push_back(NewMI);
6679 return true;
6680}
6681
6682/// Return the appropriate SDDbgValue based on N.
6683SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6684 DILocalVariable *Variable,
6685 DIExpression *Expr,
6686 const DebugLoc &dl,
6687 unsigned DbgSDNodeOrder) {
6688 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6689 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6690 // stack slot locations.
6691 //
6692 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6693 // debug values here after optimization:
6694 //
6695 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
6696 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6697 //
6698 // Both describe the direct values of their associated variables.
6699 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6700 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6701 }
6702 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6703 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6704}
6705
6706static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6707 switch (Intrinsic) {
6708 case Intrinsic::smul_fix:
6709 return ISD::SMULFIX;
6710 case Intrinsic::umul_fix:
6711 return ISD::UMULFIX;
6712 case Intrinsic::smul_fix_sat:
6713 return ISD::SMULFIXSAT;
6714 case Intrinsic::umul_fix_sat:
6715 return ISD::UMULFIXSAT;
6716 case Intrinsic::sdiv_fix:
6717 return ISD::SDIVFIX;
6718 case Intrinsic::udiv_fix:
6719 return ISD::UDIVFIX;
6720 case Intrinsic::sdiv_fix_sat:
6721 return ISD::SDIVFIXSAT;
6722 case Intrinsic::udiv_fix_sat:
6723 return ISD::UDIVFIXSAT;
6724 default:
6725 llvm_unreachable("Unhandled fixed point intrinsic");
6726 }
6727}
6728
6729/// Given a @llvm.call.preallocated.setup, return the corresponding
6730/// preallocated call.
6731static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6732 assert(cast<CallBase>(PreallocatedSetup)
6734 ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6735 "expected call_preallocated_setup Value");
6736 for (const auto *U : PreallocatedSetup->users()) {
6737 auto *UseCall = cast<CallBase>(U);
6738 const Function *Fn = UseCall->getCalledFunction();
6739 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6740 return UseCall;
6741 }
6742 }
6743 llvm_unreachable("expected corresponding call to preallocated setup/arg");
6744}
6745
6746/// If DI is a debug value with an EntryValue expression, lower it using the
6747/// corresponding physical register of the associated Argument value
6748/// (guaranteed to exist by the verifier).
6749bool SelectionDAGBuilder::visitEntryValueDbgValue(
6751 DIExpression *Expr, DebugLoc DbgLoc) {
6752 if (!Expr->isEntryValue() || !hasSingleElement(Values))
6753 return false;
6754
6755 // These properties are guaranteed by the verifier.
6756 const Argument *Arg = cast<Argument>(Values[0]);
6757 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6758
6759 auto ArgIt = FuncInfo.ValueMap.find(Arg);
6760 if (ArgIt == FuncInfo.ValueMap.end()) {
6761 LLVM_DEBUG(
6762 dbgs() << "Dropping dbg.value: expression is entry_value but "
6763 "couldn't find an associated register for the Argument\n");
6764 return true;
6765 }
6766 Register ArgVReg = ArgIt->getSecond();
6767
6768 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6769 if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6770 SDDbgValue *SDV = DAG.getVRegDbgValue(
6771 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6772 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6773 return true;
6774 }
6775 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6776 "couldn't find a physical register\n");
6777 return true;
6778}
6779
6780/// Lower the call to the specified intrinsic function.
6781void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6782 unsigned Intrinsic) {
6783 SDLoc sdl = getCurSDLoc();
6784 switch (Intrinsic) {
6785 case Intrinsic::experimental_convergence_anchor:
6786 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6787 break;
6788 case Intrinsic::experimental_convergence_entry:
6789 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6790 break;
6791 case Intrinsic::experimental_convergence_loop: {
6792 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6793 auto *Token = Bundle->Inputs[0].get();
6794 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6795 getValue(Token)));
6796 break;
6797 }
6798 }
6799}
6800
6801void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6802 unsigned IntrinsicID) {
6803 // For now, we're only lowering an 'add' histogram.
6804 // We can add others later, e.g. saturating adds, min/max.
6805 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6806 "Tried to lower unsupported histogram type");
6807 SDLoc sdl = getCurSDLoc();
6808 Value *Ptr = I.getOperand(0);
6809 SDValue Inc = getValue(I.getOperand(1));
6810 SDValue Mask = getValue(I.getOperand(2));
6811
6812 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6813 EVT VT = Inc.getValueType();
6814 Align Alignment = DAG.getEVTAlign(VT);
6815
6816 const MDNode *Ranges = getRangeMetadata(I);
6817
6818 SDValue Root = DAG.getRoot();
6819 SDValue Base;
6820 SDValue Index;
6821 SDValue Scale;
6822 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
6823 I.getParent(), VT.getScalarStoreSize());
6824
6825 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6826
6827 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6828 MachinePointerInfo(AS),
6830 MemoryLocation::UnknownSize, Alignment,
6831 MMOMetadata(I.getAAMetadata(), Ranges));
6832
6833 if (!UniformBase) {
6834 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6835 Index = getValue(Ptr);
6836 Scale =
6837 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6838 }
6839
6840 EVT IdxVT = Index.getValueType();
6841
6842 // Avoid using e.g. i32 as index type when the increment must be performed
6843 // on i64's.
6844 bool MustExtendIndex = VT.getScalarSizeInBits() > IdxVT.getScalarSizeInBits();
6845 EVT EltTy = MustExtendIndex ? VT : IdxVT.getVectorElementType();
6846 if (MustExtendIndex || TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6847 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
6848 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6849 }
6850
6851 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6852
6853 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6854 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6855 Ops, MMO, ISD::SIGNED_SCALED);
6856
6857 setValue(&I, Histogram);
6858 DAG.setRoot(Histogram);
6859}
6860
6861void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6862 unsigned Intrinsic) {
6863 assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6864 "Tried lowering invalid vector extract last");
6865 SDLoc sdl = getCurSDLoc();
6866 const DataLayout &Layout = DAG.getDataLayout();
6867 SDValue Data = getValue(I.getOperand(0));
6868 SDValue Mask = getValue(I.getOperand(1));
6869
6870 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6871 EVT ResVT = TLI.getValueType(Layout, I.getType());
6872
6873 EVT ExtVT = TLI.getVectorIdxTy(Layout);
6874 SDValue Idx = DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, sdl, ExtVT, Mask);
6875 SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl, ResVT, Data, Idx);
6876
6877 Value *Default = I.getOperand(2);
6879 SDValue PassThru = getValue(Default);
6880 EVT BoolVT = Mask.getValueType().getScalarType();
6881 SDValue AnyActive = DAG.getNode(ISD::VECREDUCE_OR, sdl, BoolVT, Mask);
6882 Result = DAG.getSelect(sdl, ResVT, AnyActive, Result, PassThru);
6883 }
6884
6885 setValue(&I, Result);
6886}
6887
6888/// Lower the call to the specified intrinsic function.
6889void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6890 unsigned Intrinsic) {
6891 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6892 SDLoc sdl = getCurSDLoc();
6893 DebugLoc dl = getCurDebugLoc();
6894 SDValue Res;
6895
6896 SDNodeFlags Flags;
6897 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6898 Flags.copyFMF(*FPOp);
6899
6900 switch (Intrinsic) {
6901 default:
6902 // By default, turn this into a target intrinsic node.
6903 visitTargetIntrinsic(I, Intrinsic);
6904 return;
6905 case Intrinsic::vscale: {
6906 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6907 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6908 return;
6909 }
6910 case Intrinsic::vastart: visitVAStart(I); return;
6911 case Intrinsic::vaend: visitVAEnd(I); return;
6912 case Intrinsic::vacopy: visitVACopy(I); return;
6913 case Intrinsic::returnaddress:
6914 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6915 TLI.getValueType(DAG.getDataLayout(), I.getType()),
6916 getValue(I.getArgOperand(0))));
6917 return;
6918 case Intrinsic::addressofreturnaddress:
6919 setValue(&I,
6920 DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6921 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6922 return;
6923 case Intrinsic::sponentry:
6924 setValue(&I,
6925 DAG.getNode(ISD::SPONENTRY, sdl,
6926 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6927 return;
6928 case Intrinsic::frameaddress:
6929 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6930 TLI.getFrameIndexTy(DAG.getDataLayout()),
6931 getValue(I.getArgOperand(0))));
6932 return;
6933 case Intrinsic::read_volatile_register:
6934 case Intrinsic::read_register: {
6935 Value *Reg = I.getArgOperand(0);
6936 SDValue Chain = getRoot();
6937 SDValue RegName =
6938 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6939 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6940 Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6941 DAG.getVTList(VT, MVT::Other), Chain, RegName);
6942 setValue(&I, Res);
6943 DAG.setRoot(Res.getValue(1));
6944 return;
6945 }
6946 case Intrinsic::write_register: {
6947 Value *Reg = I.getArgOperand(0);
6948 Value *RegValue = I.getArgOperand(1);
6949 SDValue Chain = getRoot();
6950 SDValue RegName =
6951 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6952 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6953 RegName, getValue(RegValue)));
6954 return;
6955 }
6956 case Intrinsic::write_volatile_register: {
6957 Value *Reg = I.getArgOperand(0);
6958 Value *RegValue = I.getArgOperand(1);
6959 SDValue Chain = getRoot();
6960 const MDNode *MD = cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata());
6961 SDValue RegName = DAG.getMDNode(MD);
6962 EVT VT = TLI.getValueType(DAG.getDataLayout(), RegValue->getType());
6963 SDValue WriteChain = DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other,
6964 Chain, RegName, getValue(RegValue));
6965 // FAKE_USE of the physical register marks it live after the WRITE_REGISTER,
6966 // preventing the backend from dead-eliminating the write. This is
6967 // preferred over READ_REGISTER, which would emit extra register copies
6968 // (e.g. fmov xN, dN for FP/SIMD registers).
6969 const MDString *RegStr = cast<MDString>(MD->getOperand(0));
6970 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
6971 const MachineFunction &MF = DAG.getMachineFunction();
6972 Register PhysReg =
6973 TLI.getRegisterByName(RegStr->getString().data(), Ty, MF);
6974 if (PhysReg.isValid()) {
6975 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6976 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysReg);
6977 MVT RegVT = *TRI->legalclasstypes_begin(*RC);
6978 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other,
6979 {WriteChain, DAG.getRegister(PhysReg, RegVT)}));
6980 } else {
6981 DAG.setRoot(WriteChain);
6982 }
6983 return;
6984 }
6985 case Intrinsic::memcpy:
6986 case Intrinsic::memcpy_inline: {
6987 const auto &MCI = cast<MemCpyInst>(I);
6988 SDValue Dst = getValue(I.getArgOperand(0));
6989 SDValue Src = getValue(I.getArgOperand(1));
6990 SDValue Size = getValue(I.getArgOperand(2));
6991 assert((!MCI.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6992 "memcpy_inline needs constant size");
6993 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6994 Align DstAlign = MCI.getDestAlign().valueOrOne();
6995 Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6996 bool isVol = MCI.isVolatile();
6997 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6998 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, DstAlign, SrcAlign,
6999 isVol, MCI.isForceInlined(), &I, std::nullopt,
7000 MachinePointerInfo(I.getArgOperand(0)),
7001 MachinePointerInfo(I.getArgOperand(1)),
7002 I.getAAMetadata(), BatchAA);
7003 updateDAGForMaybeTailCall(MC);
7004 return;
7005 }
7006 case Intrinsic::memset:
7007 case Intrinsic::memset_inline: {
7008 const auto &MSII = cast<MemSetInst>(I);
7009 SDValue Dst = getValue(I.getArgOperand(0));
7010 SDValue Value = getValue(I.getArgOperand(1));
7011 SDValue Size = getValue(I.getArgOperand(2));
7012 assert((!MSII.isForceInlined() || isa<ConstantSDNode>(Size)) &&
7013 "memset_inline needs constant size");
7014 // @llvm.memset defines 0 and 1 to both mean no alignment.
7015 Align DstAlign = MSII.getDestAlign().valueOrOne();
7016 bool isVol = MSII.isVolatile();
7017 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7018 SDValue MC = DAG.getMemset(
7019 Root, sdl, Dst, Value, Size, DstAlign, isVol, MSII.isForceInlined(),
7020 &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
7021 updateDAGForMaybeTailCall(MC);
7022 return;
7023 }
7024 case Intrinsic::memmove: {
7025 const auto &MMI = cast<MemMoveInst>(I);
7026 SDValue Op1 = getValue(I.getArgOperand(0));
7027 SDValue Op2 = getValue(I.getArgOperand(1));
7028 SDValue Op3 = getValue(I.getArgOperand(2));
7029 // @llvm.memmove defines 0 and 1 to both mean no alignment.
7030 Align DstAlign = MMI.getDestAlign().valueOrOne();
7031 Align SrcAlign = MMI.getSourceAlign().valueOrOne();
7032 bool isVol = MMI.isVolatile();
7033 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7034 SDValue MM = DAG.getMemmove(
7035 Root, sdl, Op1, Op2, Op3, DstAlign, SrcAlign, isVol, &I,
7036 /* OverrideTailCall */ std::nullopt,
7037 MachinePointerInfo(I.getArgOperand(0)),
7038 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), BatchAA);
7039 updateDAGForMaybeTailCall(MM);
7040 return;
7041 }
7042 case Intrinsic::memcpy_element_unordered_atomic: {
7043 auto &MI = cast<AnyMemCpyInst>(I);
7044 SDValue Dst = getValue(MI.getRawDest());
7045 SDValue Src = getValue(MI.getRawSource());
7046 SDValue Length = getValue(MI.getLength());
7047
7048 Type *LengthTy = MI.getLength()->getType();
7049 unsigned ElemSz = MI.getElementSizeInBytes();
7050 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7051 SDValue MC =
7052 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
7053 isTC, MachinePointerInfo(MI.getRawDest()),
7054 MachinePointerInfo(MI.getRawSource()));
7055 updateDAGForMaybeTailCall(MC);
7056 return;
7057 }
7058 case Intrinsic::memmove_element_unordered_atomic: {
7059 auto &MI = cast<AnyMemMoveInst>(I);
7060 SDValue Dst = getValue(MI.getRawDest());
7061 SDValue Src = getValue(MI.getRawSource());
7062 SDValue Length = getValue(MI.getLength());
7063
7064 Type *LengthTy = MI.getLength()->getType();
7065 unsigned ElemSz = MI.getElementSizeInBytes();
7066 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7067 SDValue MC =
7068 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
7069 isTC, MachinePointerInfo(MI.getRawDest()),
7070 MachinePointerInfo(MI.getRawSource()));
7071 updateDAGForMaybeTailCall(MC);
7072 return;
7073 }
7074 case Intrinsic::memset_element_unordered_atomic: {
7075 auto &MI = cast<AnyMemSetInst>(I);
7076 SDValue Dst = getValue(MI.getRawDest());
7077 SDValue Val = getValue(MI.getValue());
7078 SDValue Length = getValue(MI.getLength());
7079
7080 Type *LengthTy = MI.getLength()->getType();
7081 unsigned ElemSz = MI.getElementSizeInBytes();
7082 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7083 SDValue MC =
7084 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
7085 isTC, MachinePointerInfo(MI.getRawDest()));
7086 updateDAGForMaybeTailCall(MC);
7087 return;
7088 }
7089 case Intrinsic::call_preallocated_setup: {
7090 const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
7091 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
7092 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
7093 getRoot(), SrcValue);
7094 setValue(&I, Res);
7095 DAG.setRoot(Res);
7096 return;
7097 }
7098 case Intrinsic::call_preallocated_arg: {
7099 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
7100 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
7101 SDValue Ops[3];
7102 Ops[0] = getRoot();
7103 Ops[1] = SrcValue;
7104 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7105 MVT::i32); // arg index
7106 SDValue Res = DAG.getNode(
7108 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
7109 setValue(&I, Res);
7110 DAG.setRoot(Res.getValue(1));
7111 return;
7112 }
7113
7114 case Intrinsic::eh_typeid_for: {
7115 // Find the type id for the given typeinfo.
7116 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
7117 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
7118 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
7119 setValue(&I, Res);
7120 return;
7121 }
7122
7123 case Intrinsic::eh_return_i32:
7124 case Intrinsic::eh_return_i64:
7125 DAG.getMachineFunction().setCallsEHReturn(true);
7126 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
7127 MVT::Other,
7129 getValue(I.getArgOperand(0)),
7130 getValue(I.getArgOperand(1))));
7131 return;
7132 case Intrinsic::eh_unwind_init:
7133 DAG.getMachineFunction().setCallsUnwindInit(true);
7134 return;
7135 case Intrinsic::eh_dwarf_cfa:
7136 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
7137 TLI.getPointerTy(DAG.getDataLayout()),
7138 getValue(I.getArgOperand(0))));
7139 return;
7140 case Intrinsic::eh_sjlj_callsite: {
7141 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
7142 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
7143
7144 FuncInfo.setCurrentCallSite(CI->getZExtValue());
7145 return;
7146 }
7147 case Intrinsic::eh_sjlj_functioncontext: {
7148 // Get and store the index of the function context.
7149 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7150 AllocaInst *FnCtx =
7151 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
7152 int FI = FuncInfo.StaticAllocaMap[FnCtx];
7154 return;
7155 }
7156 case Intrinsic::eh_sjlj_setjmp: {
7157 SDValue Ops[2];
7158 Ops[0] = getRoot();
7159 Ops[1] = getValue(I.getArgOperand(0));
7160 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
7161 DAG.getVTList(MVT::i32, MVT::Other), Ops);
7162 setValue(&I, Op.getValue(0));
7163 DAG.setRoot(Op.getValue(1));
7164 return;
7165 }
7166 case Intrinsic::eh_sjlj_longjmp:
7167 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
7168 getRoot(), getValue(I.getArgOperand(0))));
7169 return;
7170 case Intrinsic::eh_sjlj_setup_dispatch:
7171 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
7172 getRoot()));
7173 return;
7174 case Intrinsic::masked_gather:
7175 visitMaskedGather(I);
7176 return;
7177 case Intrinsic::masked_load:
7178 visitMaskedLoad(I);
7179 return;
7180 case Intrinsic::masked_scatter:
7181 visitMaskedScatter(I);
7182 return;
7183 case Intrinsic::masked_store:
7184 visitMaskedStore(I);
7185 return;
7186 case Intrinsic::masked_expandload:
7187 visitMaskedLoad(I, true /* IsExpanding */);
7188 return;
7189 case Intrinsic::masked_compressstore:
7190 visitMaskedStore(I, true /* IsCompressing */);
7191 return;
7192 case Intrinsic::speculative_load:
7193 visitSpeculativeLoad(I);
7194 return;
7195 case Intrinsic::powi:
7196 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
7197 getValue(I.getArgOperand(1)), DAG));
7198 return;
7199 case Intrinsic::log:
7200 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7201 return;
7202 case Intrinsic::log2:
7203 setValue(&I,
7204 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7205 return;
7206 case Intrinsic::log10:
7207 setValue(&I,
7208 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7209 return;
7210 case Intrinsic::exp:
7211 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7212 return;
7213 case Intrinsic::exp2:
7214 setValue(&I,
7215 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7216 return;
7217 case Intrinsic::pow:
7218 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
7219 getValue(I.getArgOperand(1)), DAG, TLI, Flags));
7220 return;
7221 case Intrinsic::sqrt:
7222 case Intrinsic::fabs:
7223 case Intrinsic::sin:
7224 case Intrinsic::cos:
7225 case Intrinsic::tan:
7226 case Intrinsic::asin:
7227 case Intrinsic::acos:
7228 case Intrinsic::atan:
7229 case Intrinsic::sinh:
7230 case Intrinsic::cosh:
7231 case Intrinsic::tanh:
7232 case Intrinsic::exp10:
7233 case Intrinsic::floor:
7234 case Intrinsic::ceil:
7235 case Intrinsic::trunc:
7236 case Intrinsic::rint:
7237 case Intrinsic::nearbyint:
7238 case Intrinsic::round:
7239 case Intrinsic::roundeven:
7240 case Intrinsic::canonicalize: {
7241 unsigned Opcode;
7242 // clang-format off
7243 switch (Intrinsic) {
7244 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7245 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
7246 case Intrinsic::fabs: Opcode = ISD::FABS; break;
7247 case Intrinsic::sin: Opcode = ISD::FSIN; break;
7248 case Intrinsic::cos: Opcode = ISD::FCOS; break;
7249 case Intrinsic::tan: Opcode = ISD::FTAN; break;
7250 case Intrinsic::asin: Opcode = ISD::FASIN; break;
7251 case Intrinsic::acos: Opcode = ISD::FACOS; break;
7252 case Intrinsic::atan: Opcode = ISD::FATAN; break;
7253 case Intrinsic::sinh: Opcode = ISD::FSINH; break;
7254 case Intrinsic::cosh: Opcode = ISD::FCOSH; break;
7255 case Intrinsic::tanh: Opcode = ISD::FTANH; break;
7256 case Intrinsic::exp10: Opcode = ISD::FEXP10; break;
7257 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
7258 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
7259 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
7260 case Intrinsic::rint: Opcode = ISD::FRINT; break;
7261 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
7262 case Intrinsic::round: Opcode = ISD::FROUND; break;
7263 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
7264 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
7265 }
7266 // clang-format on
7267
7268 setValue(&I, DAG.getNode(Opcode, sdl,
7269 getValue(I.getArgOperand(0)).getValueType(),
7270 getValue(I.getArgOperand(0)), Flags));
7271 return;
7272 }
7273 case Intrinsic::atan2:
7274 setValue(&I, DAG.getNode(ISD::FATAN2, sdl,
7275 getValue(I.getArgOperand(0)).getValueType(),
7276 getValue(I.getArgOperand(0)),
7277 getValue(I.getArgOperand(1)), Flags));
7278 return;
7279 case Intrinsic::lround:
7280 case Intrinsic::llround:
7281 case Intrinsic::lrint:
7282 case Intrinsic::llrint: {
7283 unsigned Opcode;
7284 // clang-format off
7285 switch (Intrinsic) {
7286 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7287 case Intrinsic::lround: Opcode = ISD::LROUND; break;
7288 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
7289 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
7290 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
7291 }
7292 // clang-format on
7293
7294 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7295 setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
7296 getValue(I.getArgOperand(0))));
7297 return;
7298 }
7299 case Intrinsic::minnum:
7300 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
7301 getValue(I.getArgOperand(0)).getValueType(),
7302 getValue(I.getArgOperand(0)),
7303 getValue(I.getArgOperand(1)), Flags));
7304 return;
7305 case Intrinsic::maxnum:
7306 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
7307 getValue(I.getArgOperand(0)).getValueType(),
7308 getValue(I.getArgOperand(0)),
7309 getValue(I.getArgOperand(1)), Flags));
7310 return;
7311 case Intrinsic::minimum:
7312 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
7313 getValue(I.getArgOperand(0)).getValueType(),
7314 getValue(I.getArgOperand(0)),
7315 getValue(I.getArgOperand(1)), Flags));
7316 return;
7317 case Intrinsic::maximum:
7318 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
7319 getValue(I.getArgOperand(0)).getValueType(),
7320 getValue(I.getArgOperand(0)),
7321 getValue(I.getArgOperand(1)), Flags));
7322 return;
7323 case Intrinsic::minimumnum:
7324 setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
7325 getValue(I.getArgOperand(0)).getValueType(),
7326 getValue(I.getArgOperand(0)),
7327 getValue(I.getArgOperand(1)), Flags));
7328 return;
7329 case Intrinsic::maximumnum:
7330 setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
7331 getValue(I.getArgOperand(0)).getValueType(),
7332 getValue(I.getArgOperand(0)),
7333 getValue(I.getArgOperand(1)), Flags));
7334 return;
7335 case Intrinsic::copysign:
7336 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
7337 getValue(I.getArgOperand(0)).getValueType(),
7338 getValue(I.getArgOperand(0)),
7339 getValue(I.getArgOperand(1)), Flags));
7340 return;
7341 case Intrinsic::ldexp:
7342 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
7343 getValue(I.getArgOperand(0)).getValueType(),
7344 getValue(I.getArgOperand(0)),
7345 getValue(I.getArgOperand(1)), Flags));
7346 return;
7347 case Intrinsic::modf:
7348 case Intrinsic::sincos:
7349 case Intrinsic::sincospi:
7350 case Intrinsic::frexp: {
7351 unsigned Opcode;
7352 switch (Intrinsic) {
7353 default:
7354 llvm_unreachable("unexpected intrinsic");
7355 case Intrinsic::sincos:
7356 Opcode = ISD::FSINCOS;
7357 break;
7358 case Intrinsic::sincospi:
7359 Opcode = ISD::FSINCOSPI;
7360 break;
7361 case Intrinsic::modf:
7362 Opcode = ISD::FMODF;
7363 break;
7364 case Intrinsic::frexp:
7365 Opcode = ISD::FFREXP;
7366 break;
7367 }
7368 SmallVector<EVT, 2> ValueVTs;
7369 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
7370 SDVTList VTs = DAG.getVTList(ValueVTs);
7371 setValue(
7372 &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags));
7373 return;
7374 }
7375 case Intrinsic::arithmetic_fence: {
7376 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
7377 getValue(I.getArgOperand(0)).getValueType(),
7378 getValue(I.getArgOperand(0)), Flags));
7379 return;
7380 }
7381 case Intrinsic::fma:
7382 setValue(&I, DAG.getNode(
7383 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
7384 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
7385 getValue(I.getArgOperand(2)), Flags));
7386 return;
7387#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
7388 case Intrinsic::INTRINSIC:
7389#include "llvm/IR/ConstrainedOps.def"
7390 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
7391 return;
7392#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7393#include "llvm/IR/VPIntrinsics.def"
7394 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
7395 return;
7396 case Intrinsic::fptrunc_round: {
7397 // Get the last argument, the metadata and convert it to an integer in the
7398 // call
7399 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7400 std::optional<RoundingMode> RoundMode =
7401 convertStrToRoundingMode(cast<MDString>(MD)->getString());
7402
7403 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7404
7405 // Propagate fast-math-flags from IR to node(s).
7406 SDNodeFlags Flags;
7407 Flags.copyFMF(*cast<FPMathOperator>(&I));
7408 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7409
7410 SDValue Result;
7411 Result = DAG.getNode(
7412 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
7413 DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
7414 setValue(&I, Result);
7415
7416 return;
7417 }
7418 case Intrinsic::fmuladd: {
7419 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7420 if (TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7421 setValue(&I, DAG.getNode(ISD::FMA, sdl,
7422 getValue(I.getArgOperand(0)).getValueType(),
7423 getValue(I.getArgOperand(0)),
7424 getValue(I.getArgOperand(1)),
7425 getValue(I.getArgOperand(2)), Flags));
7426 } else if (TLI.isOperationLegalOrCustom(ISD::FMULADD, VT)) {
7427 // TODO: Support splitting the vector.
7428 setValue(&I, DAG.getNode(ISD::FMULADD, sdl,
7429 getValue(I.getArgOperand(0)).getValueType(),
7430 getValue(I.getArgOperand(0)),
7431 getValue(I.getArgOperand(1)),
7432 getValue(I.getArgOperand(2)), Flags));
7433 } else {
7434 // TODO: Intrinsic calls should have fast-math-flags.
7435 SDValue Mul = DAG.getNode(
7436 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
7437 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
7438 SDValue Add = DAG.getNode(ISD::FADD, sdl,
7439 getValue(I.getArgOperand(0)).getValueType(),
7440 Mul, getValue(I.getArgOperand(2)), Flags);
7441 setValue(&I, Add);
7442 }
7443 return;
7444 }
7445 case Intrinsic::fptosi_sat: {
7446 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7447 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7448 getValue(I.getArgOperand(0)),
7449 DAG.getValueType(VT.getScalarType())));
7450 return;
7451 }
7452 case Intrinsic::fptoui_sat: {
7453 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7454 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7455 getValue(I.getArgOperand(0)),
7456 DAG.getValueType(VT.getScalarType())));
7457 return;
7458 }
7459 case Intrinsic::convert_from_arbitrary_fp: {
7460 // Extract format metadata and convert to semantics enum.
7461 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7462 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7463 StringRef FormatStr = cast<MDString>(MD)->getString();
7464 const fltSemantics *SrcSem =
7466 if (!SrcSem) {
7467 DAG.getContext()->emitError(
7468 "convert_from_arbitrary_fp: not implemented format '" + FormatStr +
7469 "'");
7470 setValue(&I, DAG.getPOISON(DstVT));
7471 return;
7472 }
7474
7475 SDValue IntVal = getValue(I.getArgOperand(0));
7476
7477 // Emit ISD::CONVERT_FROM_ARBITRARY_FP node.
7478 SDValue SemConst =
7479 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7480 setValue(&I, DAG.getNode(ISD::CONVERT_FROM_ARBITRARY_FP, sdl, DstVT, IntVal,
7481 SemConst));
7482 return;
7483 }
7484 case Intrinsic::convert_to_arbitrary_fp: {
7485 // Extract format metadata and convert to semantics enum.
7486 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7487 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7488 StringRef FormatStr = cast<MDString>(MD)->getString();
7489 const fltSemantics *DstSem =
7491 if (!DstSem) {
7492 DAG.getContext()->emitError(
7493 "convert_to_arbitrary_fp: not implemented format '" + FormatStr +
7494 "'");
7495 setValue(&I, DAG.getPOISON(DstVT));
7496 return;
7497 }
7499
7500 Metadata *RoundMD =
7501 cast<MetadataAsValue>(I.getArgOperand(2))->getMetadata();
7502 StringRef RoundStr = cast<MDString>(RoundMD)->getString();
7503 std::optional<RoundingMode> RoundMode = convertStrToRoundingMode(RoundStr);
7504 assert(RoundMode && *RoundMode != RoundingMode::Dynamic &&
7505 "Dynamic rounding mode should have been rejected by the verifier");
7506
7507 uint64_t Saturate =
7508 cast<ConstantInt>(I.getArgOperand(3))->getZExtValue() ? 1 : 0;
7509
7510 SDValue FloatVal = getValue(I.getArgOperand(0));
7511
7512 SDValue SemConst =
7513 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7514 SDValue RoundConst =
7515 DAG.getTargetConstant(static_cast<int>(*RoundMode), sdl, MVT::i32);
7516 SDValue SatConst = DAG.getTargetConstant(Saturate, sdl, MVT::i32);
7517 setValue(&I, DAG.getNode(ISD::CONVERT_TO_ARBITRARY_FP, sdl, DstVT, FloatVal,
7518 SemConst, RoundConst, SatConst));
7519 return;
7520 }
7521 case Intrinsic::set_rounding:
7522 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7523 {getRoot(), getValue(I.getArgOperand(0))});
7524 setValue(&I, Res);
7525 DAG.setRoot(Res.getValue(0));
7526 return;
7527 case Intrinsic::is_fpclass: {
7528 const DataLayout DLayout = DAG.getDataLayout();
7529 EVT DestVT = TLI.getValueType(DLayout, I.getType());
7530 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7531 FPClassTest Test = static_cast<FPClassTest>(
7532 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7533 MachineFunction &MF = DAG.getMachineFunction();
7534 const Function &F = MF.getFunction();
7535 SDValue Op = getValue(I.getArgOperand(0));
7536 SDNodeFlags Flags;
7537 Flags.setNoFPExcept(
7538 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7539 // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7540 // expansion can use illegal types. Making expansion early allows
7541 // legalizing these types prior to selection.
7542 if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7543 !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) {
7544 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7545 setValue(&I, Result);
7546 return;
7547 }
7548
7549 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7550 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7551 setValue(&I, V);
7552 return;
7553 }
7554 case Intrinsic::get_fpenv: {
7555 const DataLayout DLayout = DAG.getDataLayout();
7556 EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7557 Align TempAlign = DAG.getEVTAlign(EnvVT);
7558 SDValue Chain = getRoot();
7559 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7560 // and temporary storage in stack.
7561 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7562 Res = DAG.getNode(
7563 ISD::GET_FPENV, sdl,
7564 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7565 MVT::Other),
7566 Chain);
7567 } else {
7568 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7569 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7570 auto MPI =
7571 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7572 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7574 TempAlign);
7575 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7576 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7577 }
7578 setValue(&I, Res);
7579 DAG.setRoot(Res.getValue(1));
7580 return;
7581 }
7582 case Intrinsic::set_fpenv: {
7583 SDValue Env = getValue(I.getArgOperand(0));
7584 EVT EnvVT = Env.getValueType();
7585 Align TempAlign = DAG.getEVTAlign(EnvVT);
7586 SDValue Chain = getRoot();
7587 // If SET_FPENV is custom or legal, use it. Otherwise use loading
7588 // environment from memory.
7589 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7590 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7591 } else {
7592 // Allocate space in stack, copy environment bits into it and use this
7593 // memory in SET_FPENV_MEM.
7594 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7595 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7596 auto MPI =
7597 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7598 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7600 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7602 TempAlign);
7603 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7604 }
7605 DAG.setRoot(Chain);
7606 return;
7607 }
7608 case Intrinsic::reset_fpenv:
7609 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7610 return;
7611 case Intrinsic::get_fpmode:
7612 Res = DAG.getNode(
7613 ISD::GET_FPMODE, sdl,
7614 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7615 MVT::Other),
7616 DAG.getRoot());
7617 setValue(&I, Res);
7618 DAG.setRoot(Res.getValue(1));
7619 return;
7620 case Intrinsic::set_fpmode:
7621 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7622 getValue(I.getArgOperand(0)));
7623 DAG.setRoot(Res);
7624 return;
7625 case Intrinsic::reset_fpmode: {
7626 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7627 DAG.setRoot(Res);
7628 return;
7629 }
7630 case Intrinsic::pcmarker: {
7631 SDValue Tmp = getValue(I.getArgOperand(0));
7632 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7633 return;
7634 }
7635 case Intrinsic::readcyclecounter: {
7636 SDValue Op = getRoot();
7637 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7638 DAG.getVTList(MVT::i64, MVT::Other), Op);
7639 setValue(&I, Res);
7640 DAG.setRoot(Res.getValue(1));
7641 return;
7642 }
7643 case Intrinsic::readsteadycounter: {
7644 SDValue Op = getRoot();
7645 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7646 DAG.getVTList(MVT::i64, MVT::Other), Op);
7647 setValue(&I, Res);
7648 DAG.setRoot(Res.getValue(1));
7649 return;
7650 }
7651 case Intrinsic::bitreverse:
7652 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7653 getValue(I.getArgOperand(0)).getValueType(),
7654 getValue(I.getArgOperand(0))));
7655 return;
7656 case Intrinsic::bswap:
7657 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7658 getValue(I.getArgOperand(0)).getValueType(),
7659 getValue(I.getArgOperand(0))));
7660 return;
7661 case Intrinsic::cttz: {
7662 SDValue Arg = getValue(I.getArgOperand(0));
7663 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7664 EVT Ty = Arg.getValueType();
7665 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_POISON,
7666 sdl, Ty, Arg));
7667 return;
7668 }
7669 case Intrinsic::ctlz: {
7670 SDValue Arg = getValue(I.getArgOperand(0));
7671 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7672 EVT Ty = Arg.getValueType();
7673 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_POISON,
7674 sdl, Ty, Arg));
7675 return;
7676 }
7677 case Intrinsic::ctpop: {
7678 SDValue Arg = getValue(I.getArgOperand(0));
7679 EVT Ty = Arg.getValueType();
7680 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7681 return;
7682 }
7683 case Intrinsic::fshl:
7684 case Intrinsic::fshr: {
7685 bool IsFSHL = Intrinsic == Intrinsic::fshl;
7686 SDValue X = getValue(I.getArgOperand(0));
7687 SDValue Y = getValue(I.getArgOperand(1));
7688 SDValue Z = getValue(I.getArgOperand(2));
7689 EVT VT = X.getValueType();
7690
7691 if (X == Y) {
7692 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7693 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7694 } else {
7695 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7696 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7697 }
7698 return;
7699 }
7700 case Intrinsic::clmul: {
7701 SDValue X = getValue(I.getArgOperand(0));
7702 SDValue Y = getValue(I.getArgOperand(1));
7703 setValue(&I, DAG.getNode(ISD::CLMUL, sdl, X.getValueType(), X, Y));
7704 return;
7705 }
7706 case Intrinsic::pext: {
7707 SDValue X = getValue(I.getArgOperand(0));
7708 SDValue Y = getValue(I.getArgOperand(1));
7709 setValue(&I, DAG.getNode(ISD::PEXT, sdl, X.getValueType(), X, Y));
7710 return;
7711 }
7712 case Intrinsic::pdep: {
7713 SDValue X = getValue(I.getArgOperand(0));
7714 SDValue Y = getValue(I.getArgOperand(1));
7715 setValue(&I, DAG.getNode(ISD::PDEP, sdl, X.getValueType(), X, Y));
7716 return;
7717 }
7718 case Intrinsic::smulh:
7719 case Intrinsic::umulh: {
7720 auto Opc = Intrinsic == Intrinsic::smulh ? ISD::MULHS : ISD::MULHU;
7721 SDValue X = getValue(I.getArgOperand(0));
7722 SDValue Y = getValue(I.getArgOperand(1));
7723 setValue(&I, DAG.getNode(Opc, sdl, X.getValueType(), X, Y));
7724 return;
7725 }
7726 case Intrinsic::sadd_sat: {
7727 SDValue Op1 = getValue(I.getArgOperand(0));
7728 SDValue Op2 = getValue(I.getArgOperand(1));
7729 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7730 return;
7731 }
7732 case Intrinsic::uadd_sat: {
7733 SDValue Op1 = getValue(I.getArgOperand(0));
7734 SDValue Op2 = getValue(I.getArgOperand(1));
7735 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7736 return;
7737 }
7738 case Intrinsic::ssub_sat: {
7739 SDValue Op1 = getValue(I.getArgOperand(0));
7740 SDValue Op2 = getValue(I.getArgOperand(1));
7741 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7742 return;
7743 }
7744 case Intrinsic::usub_sat: {
7745 SDValue Op1 = getValue(I.getArgOperand(0));
7746 SDValue Op2 = getValue(I.getArgOperand(1));
7747 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7748 return;
7749 }
7750 case Intrinsic::sshl_sat:
7751 case Intrinsic::ushl_sat: {
7752 SDValue Op1 = getValue(I.getArgOperand(0));
7753 SDValue Op2 = getValue(I.getArgOperand(1));
7754
7755 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
7756 Op1.getValueType(), DAG.getDataLayout());
7757
7758 // Coerce the shift amount to the right type if we can. This exposes the
7759 // truncate or zext to optimization early.
7760 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
7761 assert(ShiftTy.getSizeInBits() >=
7763 "Unexpected shift type");
7764 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
7765 }
7766
7767 unsigned Opc =
7768 Intrinsic == Intrinsic::sshl_sat ? ISD::SSHLSAT : ISD::USHLSAT;
7769 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1, Op2));
7770 return;
7771 }
7772 case Intrinsic::smul_fix:
7773 case Intrinsic::umul_fix:
7774 case Intrinsic::smul_fix_sat:
7775 case Intrinsic::umul_fix_sat: {
7776 SDValue Op1 = getValue(I.getArgOperand(0));
7777 SDValue Op2 = getValue(I.getArgOperand(1));
7778 SDValue Op3 = getValue(I.getArgOperand(2));
7779 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7780 Op1.getValueType(), Op1, Op2, Op3));
7781 return;
7782 }
7783 case Intrinsic::sdiv_fix:
7784 case Intrinsic::udiv_fix:
7785 case Intrinsic::sdiv_fix_sat:
7786 case Intrinsic::udiv_fix_sat: {
7787 SDValue Op1 = getValue(I.getArgOperand(0));
7788 SDValue Op2 = getValue(I.getArgOperand(1));
7789 SDValue Op3 = getValue(I.getArgOperand(2));
7791 Op1, Op2, Op3, DAG, TLI));
7792 return;
7793 }
7794 case Intrinsic::smax: {
7795 SDValue Op1 = getValue(I.getArgOperand(0));
7796 SDValue Op2 = getValue(I.getArgOperand(1));
7797 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7798 return;
7799 }
7800 case Intrinsic::smin: {
7801 SDValue Op1 = getValue(I.getArgOperand(0));
7802 SDValue Op2 = getValue(I.getArgOperand(1));
7803 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7804 return;
7805 }
7806 case Intrinsic::umax: {
7807 SDValue Op1 = getValue(I.getArgOperand(0));
7808 SDValue Op2 = getValue(I.getArgOperand(1));
7809 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7810 return;
7811 }
7812 case Intrinsic::umin: {
7813 SDValue Op1 = getValue(I.getArgOperand(0));
7814 SDValue Op2 = getValue(I.getArgOperand(1));
7815 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7816 return;
7817 }
7818 case Intrinsic::abs: {
7819 SDValue Op1 = getValue(I.getArgOperand(0));
7820 bool IntMinIsPoison = cast<ConstantInt>(I.getArgOperand(1))->isOne();
7821 unsigned Opc = IntMinIsPoison ? ISD::ABS_MIN_POISON : ISD::ABS;
7822 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1));
7823 return;
7824 }
7825 case Intrinsic::scmp: {
7826 SDValue Op1 = getValue(I.getArgOperand(0));
7827 SDValue Op2 = getValue(I.getArgOperand(1));
7828 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7829 setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7830 break;
7831 }
7832 case Intrinsic::ucmp: {
7833 SDValue Op1 = getValue(I.getArgOperand(0));
7834 SDValue Op2 = getValue(I.getArgOperand(1));
7835 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7836 setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7837 break;
7838 }
7839 case Intrinsic::stackaddress:
7840 case Intrinsic::stacksave: {
7841 unsigned SDOpcode = Intrinsic == Intrinsic::stackaddress ? ISD::STACKADDRESS
7843 SDValue Op = getRoot();
7844 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7845 Res = DAG.getNode(SDOpcode, sdl, DAG.getVTList(VT, MVT::Other), Op);
7846 setValue(&I, Res);
7847 DAG.setRoot(Res.getValue(1));
7848 return;
7849 }
7850 case Intrinsic::stackrestore:
7851 Res = getValue(I.getArgOperand(0));
7852 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7853 return;
7854 case Intrinsic::get_dynamic_area_offset: {
7855 SDValue Op = getRoot();
7856 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7857 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7858 Op);
7859 DAG.setRoot(Op);
7860 setValue(&I, Res);
7861 return;
7862 }
7863 case Intrinsic::stackguard: {
7864 MachineFunction &MF = DAG.getMachineFunction();
7865 const Module &M = *MF.getFunction().getParent();
7866 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7867 SDValue Chain = getRoot();
7868 if (TLI.useLoadStackGuardNode(M)) {
7869 Res = getLoadStackGuard(DAG, sdl, Chain);
7870 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7871 } else {
7872 const Value *Global = TLI.getSDagStackGuard(M, DAG.getLibcalls());
7873 if (!Global) {
7874 LLVMContext &Ctx = *DAG.getContext();
7875 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
7876 setValue(&I, DAG.getPOISON(PtrTy));
7877 return;
7878 }
7879
7880 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7881 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7882 MachinePointerInfo(Global, 0), Align,
7884 }
7885 // Mix the cookie with FP if enabled. Skip if using LOAD_STACK_GUARD
7886 // with post-RA mixing (AArch64 MSVCRT), as the mixing will be done during
7887 // post-RA expansion of LOAD_STACK_GUARD.
7888 if (TLI.useStackGuardMixFP() && !TLI.useLoadStackGuardNode(M))
7889 Res = TLI.emitStackGuardMixFP(DAG, Res, sdl);
7890 DAG.setRoot(Chain);
7891 setValue(&I, Res);
7892 return;
7893 }
7894 case Intrinsic::stackprotector: {
7895 // Emit code into the DAG to store the stack guard onto the stack.
7896 MachineFunction &MF = DAG.getMachineFunction();
7897 MachineFrameInfo &MFI = MF.getFrameInfo();
7898 const Module &M = *MF.getFunction().getParent();
7899 SDValue Src, Chain = getRoot();
7900
7901 if (TLI.useLoadStackGuardNode(M))
7902 Src = getLoadStackGuard(DAG, sdl, Chain);
7903 else
7904 Src = getValue(I.getArgOperand(0)); // The guard's value.
7905
7906 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7907
7908 int FI = FuncInfo.StaticAllocaMap[Slot];
7909 MFI.setStackProtectorIndex(FI);
7910 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7911
7912 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7913
7914 // Store the stack protector onto the stack.
7915 Res = DAG.getStore(
7916 Chain, sdl, Src, FIN,
7917 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7918 MaybeAlign(), MachineMemOperand::MOVolatile);
7919 setValue(&I, Res);
7920 DAG.setRoot(Res);
7921 return;
7922 }
7923 case Intrinsic::objectsize:
7924 llvm_unreachable("llvm.objectsize.* should have been lowered already");
7925
7926 case Intrinsic::is_constant:
7927 llvm_unreachable("llvm.is.constant.* should have been lowered already");
7928
7929 case Intrinsic::annotation:
7930 case Intrinsic::ptr_annotation:
7931 case Intrinsic::launder_invariant_group:
7932 // Drop the intrinsic, but forward the value
7933 setValue(&I, getValue(I.getOperand(0)));
7934 return;
7935
7936 case Intrinsic::type_test:
7937 case Intrinsic::public_type_test:
7938 case Intrinsic::type_checked_load:
7939 case Intrinsic::type_checked_load_relative: {
7940 // These intrinsics are expected to be lowered by the LowerTypeTests pass
7941 // before code generation. Surviving until here usually indicates a
7942 // misconfiguration, for instance when devirtualization is enabled but LTO
7943 // does not actually run.
7944 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
7945 *I.getFunction(),
7946 Intrinsic::getBaseName(Intrinsic) +
7947 " intrinsic must be lowered by the LowerTypeTests pass "
7948 "before code generation",
7949 sdl.getDebugLoc()));
7950
7951 // Lower the result to poison so that compilation can continue and collect
7952 // any further diagnostics.
7953 setValueToPoison(&I, sdl);
7954 return;
7955 }
7956
7957 case Intrinsic::assume:
7958 case Intrinsic::experimental_noalias_scope_decl:
7959 case Intrinsic::var_annotation:
7960 case Intrinsic::sideeffect:
7961 // Discard annotate attributes, noalias scope declarations, assumptions, and
7962 // artificial side-effects.
7963 return;
7964
7965 case Intrinsic::codeview_annotation: {
7966 // Emit a label associated with this metadata.
7967 MachineFunction &MF = DAG.getMachineFunction();
7968 MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7969 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7970 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7971 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7972 DAG.setRoot(Res);
7973 return;
7974 }
7975
7976 case Intrinsic::init_trampoline: {
7977 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7978
7979 SDValue Ops[6];
7980 Ops[0] = getRoot();
7981 Ops[1] = getValue(I.getArgOperand(0));
7982 Ops[2] = getValue(I.getArgOperand(1));
7983 Ops[3] = getValue(I.getArgOperand(2));
7984 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7985 Ops[5] = DAG.getSrcValue(F);
7986
7987 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7988
7989 DAG.setRoot(Res);
7990 return;
7991 }
7992 case Intrinsic::adjust_trampoline:
7993 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7994 TLI.getPointerTy(DAG.getDataLayout()),
7995 getValue(I.getArgOperand(0))));
7996 return;
7997 case Intrinsic::gcroot: {
7998 assert(DAG.getMachineFunction().getFunction().hasGC() &&
7999 "only valid in functions with gc specified, enforced by Verifier");
8000 assert(GFI && "implied by previous");
8001 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
8002 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
8003
8004 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
8005 GFI->addStackRoot(FI->getIndex(), TypeMap);
8006 return;
8007 }
8008 case Intrinsic::gcread:
8009 case Intrinsic::gcwrite:
8010 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
8011 case Intrinsic::get_rounding:
8012 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
8013 setValue(&I, Res);
8014 DAG.setRoot(Res.getValue(1));
8015 return;
8016
8017 case Intrinsic::expect:
8018 case Intrinsic::expect_with_probability:
8019 // Just replace __builtin_expect(exp, c) and
8020 // __builtin_expect_with_probability(exp, c, p) with EXP.
8021 setValue(&I, getValue(I.getArgOperand(0)));
8022 return;
8023
8024 case Intrinsic::ubsantrap:
8025 case Intrinsic::debugtrap:
8026 case Intrinsic::trap: {
8027 StringRef TrapFuncName =
8028 I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
8029 if (TrapFuncName.empty()) {
8030 switch (Intrinsic) {
8031 case Intrinsic::trap:
8032 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
8033 break;
8034 case Intrinsic::debugtrap:
8035 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
8036 break;
8037 case Intrinsic::ubsantrap:
8038 DAG.setRoot(DAG.getNode(
8039 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
8040 DAG.getTargetConstant(
8041 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
8042 MVT::i32)));
8043 break;
8044 default: llvm_unreachable("unknown trap intrinsic");
8045 }
8046 DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
8047 I.hasFnAttr(Attribute::NoMerge));
8048 return;
8049 }
8051 if (Intrinsic == Intrinsic::ubsantrap) {
8052 Value *Arg = I.getArgOperand(0);
8053 Args.emplace_back(Arg, getValue(Arg),
8054 LibInfo->getExtAttrForI8Param(/*Signed=*/false));
8055 }
8056
8057 TargetLowering::CallLoweringInfo CLI(DAG);
8058 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
8059 CallingConv::C, I.getType(),
8060 DAG.getExternalSymbol(TrapFuncName.data(),
8061 TLI.getPointerTy(DAG.getDataLayout())),
8062 std::move(Args));
8063 CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
8064 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8065 DAG.setRoot(Result.second);
8066 return;
8067 }
8068
8069 case Intrinsic::allow_runtime_check:
8070 case Intrinsic::allow_ubsan_check:
8071 setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
8072 return;
8073
8074 case Intrinsic::uadd_with_overflow:
8075 case Intrinsic::sadd_with_overflow:
8076 case Intrinsic::usub_with_overflow:
8077 case Intrinsic::ssub_with_overflow:
8078 case Intrinsic::umul_with_overflow:
8079 case Intrinsic::smul_with_overflow: {
8081 switch (Intrinsic) {
8082 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8083 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
8084 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
8085 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
8086 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
8087 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
8088 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
8089 }
8090 SDValue Op1 = getValue(I.getArgOperand(0));
8091 SDValue Op2 = getValue(I.getArgOperand(1));
8092
8093 EVT ResultVT = Op1.getValueType();
8094 EVT OverflowVT = ResultVT.changeElementType(*Context, MVT::i1);
8095
8096 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
8097 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
8098 return;
8099 }
8100 case Intrinsic::prefetch: {
8101 SDValue Ops[5];
8102 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
8104 Ops[0] = DAG.getRoot();
8105 Ops[1] = getValue(I.getArgOperand(0));
8106 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
8107 MVT::i32);
8108 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
8109 MVT::i32);
8110 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
8111 MVT::i32);
8112 SDValue Result = DAG.getMemIntrinsicNode(
8113 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
8114 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
8115 /* align */ std::nullopt, Flags);
8116
8117 // Chain the prefetch in parallel with any pending loads, to stay out of
8118 // the way of later optimizations.
8119 PendingLoads.push_back(Result);
8120 Result = getRoot();
8121 DAG.setRoot(Result);
8122 return;
8123 }
8124 case Intrinsic::lifetime_start:
8125 case Intrinsic::lifetime_end: {
8126 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
8127 // Stack coloring is not enabled in O0, discard region information.
8128 if (TM.getOptLevel() == CodeGenOptLevel::None)
8129 return;
8130
8131 const AllocaInst *LifetimeObject = dyn_cast<AllocaInst>(I.getArgOperand(0));
8132 if (!LifetimeObject)
8133 return;
8134
8135 // First check that the Alloca is static, otherwise it won't have a
8136 // valid frame index.
8137 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
8138 if (SI == FuncInfo.StaticAllocaMap.end())
8139 return;
8140
8141 const int FrameIndex = SI->second;
8142 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex);
8143 DAG.setRoot(Res);
8144 return;
8145 }
8146 case Intrinsic::pseudoprobe: {
8147 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
8148 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
8149 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
8150 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
8151 DAG.setRoot(Res);
8152 return;
8153 }
8154 case Intrinsic::invariant_start:
8155 // Discard region information.
8156 setValue(&I,
8157 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
8158 return;
8159 case Intrinsic::invariant_end:
8160 // Discard region information.
8161 return;
8162 case Intrinsic::clear_cache: {
8163 SDValue InputChain = DAG.getRoot();
8164 SDValue StartVal = getValue(I.getArgOperand(0));
8165 SDValue EndVal = getValue(I.getArgOperand(1));
8166 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
8167 {InputChain, StartVal, EndVal});
8168 setValue(&I, Res);
8169 DAG.setRoot(Res);
8170 return;
8171 }
8172 case Intrinsic::donothing:
8173 case Intrinsic::seh_try_begin:
8174 case Intrinsic::seh_scope_begin:
8175 case Intrinsic::seh_try_end:
8176 case Intrinsic::seh_scope_end:
8177 // ignore
8178 return;
8179 case Intrinsic::experimental_stackmap:
8180 visitStackmap(I);
8181 return;
8182 case Intrinsic::experimental_patchpoint_void:
8183 case Intrinsic::experimental_patchpoint:
8184 visitPatchpoint(I);
8185 return;
8186 case Intrinsic::experimental_gc_statepoint:
8188 return;
8189 case Intrinsic::experimental_gc_result:
8190 visitGCResult(cast<GCResultInst>(I));
8191 return;
8192 case Intrinsic::experimental_gc_relocate:
8193 visitGCRelocate(cast<GCRelocateInst>(I));
8194 return;
8195 case Intrinsic::instrprof_cover:
8196 llvm_unreachable("instrprof failed to lower a cover");
8197 case Intrinsic::instrprof_increment:
8198 llvm_unreachable("instrprof failed to lower an increment");
8199 case Intrinsic::instrprof_timestamp:
8200 llvm_unreachable("instrprof failed to lower a timestamp");
8201 case Intrinsic::instrprof_value_profile:
8202 llvm_unreachable("instrprof failed to lower a value profiling call");
8203 case Intrinsic::instrprof_mcdc_parameters:
8204 llvm_unreachable("instrprof failed to lower mcdc parameters");
8205 case Intrinsic::instrprof_mcdc_tvbitmap_update:
8206 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
8207 case Intrinsic::localescape: {
8208 MachineFunction &MF = DAG.getMachineFunction();
8209 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
8210
8211 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
8212 // is the same on all targets.
8213 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
8214 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
8215 if (isa<ConstantPointerNull>(Arg))
8216 continue; // Skip null pointers. They represent a hole in index space.
8217 AllocaInst *Slot = cast<AllocaInst>(Arg);
8218 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
8219 "can only escape static allocas");
8220 int FI = FuncInfo.StaticAllocaMap[Slot];
8221 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8223 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
8224 TII->get(TargetOpcode::LOCAL_ESCAPE))
8225 .addSym(FrameAllocSym)
8226 .addFrameIndex(FI);
8227 }
8228
8229 return;
8230 }
8231
8232 case Intrinsic::localrecover: {
8233 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
8234 MachineFunction &MF = DAG.getMachineFunction();
8235
8236 // Get the symbol that defines the frame offset.
8237 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
8238 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
8239 unsigned IdxVal =
8240 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
8241 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8243
8244 Value *FP = I.getArgOperand(1);
8245 SDValue FPVal = getValue(FP);
8246 EVT PtrVT = FPVal.getValueType();
8247
8248 // Create a MCSymbol for the label to avoid any target lowering
8249 // that would make this PC relative.
8250 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
8251 SDValue OffsetVal =
8252 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
8253
8254 // Add the offset to the FP.
8255 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
8256 setValue(&I, Add);
8257
8258 return;
8259 }
8260
8261 case Intrinsic::fake_use: {
8262 Value *V = I.getArgOperand(0);
8263 SDValue Ops[2];
8264 // For Values not declared or previously used in this basic block, the
8265 // NodeMap will not have an entry, and `getValue` will assert if V has no
8266 // valid register value.
8267 auto FakeUseValue = [&]() -> SDValue {
8268 SDValue &N = NodeMap[V];
8269 if (N.getNode())
8270 return N;
8271
8272 // If there's a virtual register allocated and initialized for this
8273 // value, use it.
8274 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
8275 return copyFromReg;
8276 // FIXME: Do we want to preserve constants? It seems pointless.
8277 if (isa<Constant>(V))
8278 return getValue(V);
8279 return SDValue();
8280 }();
8281 if (!FakeUseValue || FakeUseValue.isUndef())
8282 return;
8283 Ops[0] = getRoot();
8284 Ops[1] = FakeUseValue;
8285 // Also, do not translate a fake use with an undef operand, or any other
8286 // empty SDValues.
8287 if (!Ops[1] || Ops[1].isUndef())
8288 return;
8289 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
8290 return;
8291 }
8292
8293 case Intrinsic::reloc_none: {
8294 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
8295 StringRef SymbolName = cast<MDString>(MD)->getString();
8296 SDValue Ops[2] = {
8297 getRoot(),
8298 DAG.getTargetExternalSymbol(
8299 SymbolName.data(), TLI.getProgramPointerTy(DAG.getDataLayout()))};
8300 DAG.setRoot(DAG.getNode(ISD::RELOC_NONE, sdl, MVT::Other, Ops));
8301 return;
8302 }
8303
8304 case Intrinsic::cond_loop: {
8305 SDValue InputChain = DAG.getRoot();
8306 SDValue P = getValue(I.getArgOperand(0));
8307 Res = DAG.getNode(ISD::COND_LOOP, sdl, DAG.getVTList(MVT::Other),
8308 {InputChain, P});
8309 setValue(&I, Res);
8310 DAG.setRoot(Res);
8311 return;
8312 }
8313
8314 case Intrinsic::eh_exceptionpointer:
8315 case Intrinsic::eh_exceptioncode: {
8316 // Get the exception pointer vreg, copy from it, and resize it to fit.
8317 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
8318 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
8319 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
8320 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
8321 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
8322 if (Intrinsic == Intrinsic::eh_exceptioncode)
8323 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
8324 setValue(&I, N);
8325 return;
8326 }
8327 case Intrinsic::xray_customevent: {
8328 // Here we want to make sure that the intrinsic behaves as if it has a
8329 // specific calling convention.
8330 const auto &Triple = DAG.getTarget().getTargetTriple();
8331 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8332 Triple.getArch() != Triple::hexagon)
8333 return;
8334
8336
8337 // We want to say that we always want the arguments in registers.
8338 SDValue LogEntryVal = getValue(I.getArgOperand(0));
8339 SDValue StrSizeVal = getValue(I.getArgOperand(1));
8340 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8341 SDValue Chain = getRoot();
8342 Ops.push_back(LogEntryVal);
8343 Ops.push_back(StrSizeVal);
8344 Ops.push_back(Chain);
8345
8346 // We need to enforce the calling convention for the callsite, so that
8347 // argument ordering is enforced correctly, and that register allocation can
8348 // see that some registers may be assumed clobbered and have to preserve
8349 // them across calls to the intrinsic.
8350 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
8351 sdl, NodeTys, Ops);
8352 SDValue patchableNode = SDValue(MN, 0);
8353 DAG.setRoot(patchableNode);
8354 setValue(&I, patchableNode);
8355 return;
8356 }
8357 case Intrinsic::xray_typedevent: {
8358 // Here we want to make sure that the intrinsic behaves as if it has a
8359 // specific calling convention.
8360 const auto &Triple = DAG.getTarget().getTargetTriple();
8361 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8362 Triple.getArch() != Triple::hexagon)
8363 return;
8364
8366
8367 // We want to say that we always want the arguments in registers.
8368 // It's unclear to me how manipulating the selection DAG here forces callers
8369 // to provide arguments in registers instead of on the stack.
8370 SDValue LogTypeId = getValue(I.getArgOperand(0));
8371 SDValue LogEntryVal = getValue(I.getArgOperand(1));
8372 SDValue StrSizeVal = getValue(I.getArgOperand(2));
8373 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8374 SDValue Chain = getRoot();
8375 Ops.push_back(LogTypeId);
8376 Ops.push_back(LogEntryVal);
8377 Ops.push_back(StrSizeVal);
8378 Ops.push_back(Chain);
8379
8380 // We need to enforce the calling convention for the callsite, so that
8381 // argument ordering is enforced correctly, and that register allocation can
8382 // see that some registers may be assumed clobbered and have to preserve
8383 // them across calls to the intrinsic.
8384 MachineSDNode *MN = DAG.getMachineNode(
8385 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
8386 SDValue patchableNode = SDValue(MN, 0);
8387 DAG.setRoot(patchableNode);
8388 setValue(&I, patchableNode);
8389 return;
8390 }
8391 case Intrinsic::experimental_deoptimize:
8393 return;
8394 case Intrinsic::stepvector:
8395 visitStepVector(I);
8396 return;
8397 case Intrinsic::vector_reduce_fadd:
8398 case Intrinsic::vector_reduce_fmul:
8399 case Intrinsic::vector_reduce_add:
8400 case Intrinsic::vector_reduce_mul:
8401 case Intrinsic::vector_reduce_and:
8402 case Intrinsic::vector_reduce_or:
8403 case Intrinsic::vector_reduce_xor:
8404 case Intrinsic::vector_reduce_smax:
8405 case Intrinsic::vector_reduce_smin:
8406 case Intrinsic::vector_reduce_umax:
8407 case Intrinsic::vector_reduce_umin:
8408 case Intrinsic::vector_reduce_fmax:
8409 case Intrinsic::vector_reduce_fmin:
8410 case Intrinsic::vector_reduce_fmaximum:
8411 case Intrinsic::vector_reduce_fminimum:
8412 case Intrinsic::vector_reduce_fmaximumnum:
8413 case Intrinsic::vector_reduce_fminimumnum:
8414 visitVectorReduce(I, Intrinsic);
8415 return;
8416
8417 case Intrinsic::icall_branch_funnel: {
8419 Ops.push_back(getValue(I.getArgOperand(0)));
8420
8421 int64_t Offset;
8423 I.getArgOperand(1), Offset, DAG.getDataLayout()));
8424 if (!Base)
8426 "llvm.icall.branch.funnel operand must be a GlobalValue");
8427 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
8428
8429 struct BranchFunnelTarget {
8430 int64_t Offset;
8431 SDValue Target;
8432 };
8434
8435 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
8437 I.getArgOperand(Op), Offset, DAG.getDataLayout()));
8438 if (ElemBase != Base)
8439 report_fatal_error("all llvm.icall.branch.funnel operands must refer "
8440 "to the same GlobalValue");
8441
8442 SDValue Val = getValue(I.getArgOperand(Op + 1));
8443 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
8444 if (!GA)
8446 "llvm.icall.branch.funnel operand must be a GlobalValue");
8447 Targets.push_back({Offset, DAG.getTargetGlobalAddress(
8448 GA->getGlobal(), sdl, Val.getValueType(),
8449 GA->getOffset())});
8450 }
8451 llvm::sort(Targets,
8452 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
8453 return T1.Offset < T2.Offset;
8454 });
8455
8456 for (auto &T : Targets) {
8457 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
8458 Ops.push_back(T.Target);
8459 }
8460
8461 Ops.push_back(DAG.getRoot()); // Chain
8462 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
8463 MVT::Other, Ops),
8464 0);
8465 DAG.setRoot(N);
8466 setValue(&I, N);
8467 HasTailCall = true;
8468 return;
8469 }
8470
8471 case Intrinsic::wasm_landingpad_index:
8472 // Information this intrinsic contained has been transferred to
8473 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
8474 // delete it now.
8475 return;
8476
8477 case Intrinsic::aarch64_settag:
8478 case Intrinsic::aarch64_settag_zero: {
8479 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8480 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
8481 SDValue Val = TSI.EmitTargetCodeForSetTag(
8482 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
8483 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
8484 ZeroMemory);
8485 DAG.setRoot(Val);
8486 setValue(&I, Val);
8487 return;
8488 }
8489 case Intrinsic::amdgcn_cs_chain: {
8490 // At this point we don't care if it's amdgpu_cs_chain or
8491 // amdgpu_cs_chain_preserve.
8493
8494 Type *RetTy = I.getType();
8495 assert(RetTy->isVoidTy() && "Should not return");
8496
8497 SDValue Callee = getValue(I.getOperand(0));
8498
8499 // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8500 // We'll also tack the value of the EXEC mask at the end.
8502 Args.reserve(3);
8503
8504 for (unsigned Idx : {2, 3, 1}) {
8505 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8506 I.getOperand(Idx)->getType());
8507 Arg.setAttributes(&I, Idx);
8508 Args.push_back(Arg);
8509 }
8510
8511 assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8512 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8513 Args[2].IsInReg = true; // EXEC should be inreg
8514
8515 // Forward the flags and any additional arguments.
8516 for (unsigned Idx = 4; Idx < I.arg_size(); ++Idx) {
8517 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8518 I.getOperand(Idx)->getType());
8519 Arg.setAttributes(&I, Idx);
8520 Args.push_back(Arg);
8521 }
8522
8523 TargetLowering::CallLoweringInfo CLI(DAG);
8524 CLI.setDebugLoc(getCurSDLoc())
8525 .setChain(getRoot())
8526 .setCallee(CC, RetTy, Callee, std::move(Args))
8527 .setNoReturn(true)
8528 .setTailCall(true)
8529 .setConvergent(I.isConvergent());
8530 CLI.CB = &I;
8531 std::pair<SDValue, SDValue> Result =
8532 lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8533 (void)Result;
8534 assert(!Result.first.getNode() && !Result.second.getNode() &&
8535 "Should've lowered as tail call");
8536
8537 HasTailCall = true;
8538 return;
8539 }
8540 case Intrinsic::amdgcn_call_whole_wave: {
8542 bool isTailCall = I.isTailCall();
8543
8544 // The first argument is the callee. Skip it when assembling the call args.
8545 for (unsigned Idx = 1; Idx < I.arg_size(); ++Idx) {
8546 TargetLowering::ArgListEntry Arg(getValue(I.getArgOperand(Idx)),
8547 I.getArgOperand(Idx)->getType());
8548 Arg.setAttributes(&I, Idx);
8549
8550 // If we have an explicit sret argument that is an Instruction, (i.e., it
8551 // might point to function-local memory), we can't meaningfully tail-call.
8552 if (Arg.IsSRet && isa<Instruction>(I.getArgOperand(Idx)))
8553 isTailCall = false;
8554
8555 Args.push_back(Arg);
8556 }
8557
8558 SDValue ConvControlToken;
8559 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8560 auto *Token = Bundle->Inputs[0].get();
8561 ConvControlToken = getValue(Token);
8562 }
8563
8564 TargetLowering::CallLoweringInfo CLI(DAG);
8565 CLI.setDebugLoc(getCurSDLoc())
8566 .setChain(getRoot())
8567 .setCallee(CallingConv::AMDGPU_Gfx_WholeWave, I.getType(),
8568 getValue(I.getArgOperand(0)), std::move(Args))
8569 .setTailCall(isTailCall && canTailCall(I))
8570 .setIsPreallocated(
8571 I.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8572 .setConvergent(I.isConvergent())
8573 .setConvergenceControlToken(ConvControlToken);
8574 CLI.CB = &I;
8575
8576 std::pair<SDValue, SDValue> Result =
8577 lowerInvokable(CLI, /*EHPadBB=*/nullptr);
8578
8579 if (Result.first.getNode())
8580 setValue(&I, Result.first);
8581 return;
8582 }
8583 case Intrinsic::ptrmask: {
8584 SDValue Ptr = getValue(I.getOperand(0));
8585 SDValue Mask = getValue(I.getOperand(1));
8586
8587 // On arm64_32, pointers are 32 bits when stored in memory, but
8588 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to
8589 // match the index type, but the pointer is 64 bits, so the mask must be
8590 // zero-extended up to 64 bits to match the pointer.
8591 EVT PtrVT =
8592 TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8593 EVT MemVT =
8594 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8595 assert(PtrVT == Ptr.getValueType());
8596 if (Mask.getValueType().getFixedSizeInBits() < MemVT.getFixedSizeInBits()) {
8597 // For AMDGPU buffer descriptors the mask is 48 bits, but the pointer is
8598 // 128-bit, so we have to pad the mask with ones for unused bits.
8599 auto HighOnes = DAG.getNode(
8600 ISD::SHL, sdl, PtrVT, DAG.getAllOnesConstant(sdl, PtrVT),
8601 DAG.getShiftAmountConstant(Mask.getValueType().getFixedSizeInBits(),
8602 PtrVT, sdl));
8603 Mask = DAG.getNode(ISD::OR, sdl, PtrVT,
8604 DAG.getZExtOrTrunc(Mask, sdl, PtrVT), HighOnes);
8605 } else if (Mask.getValueType() != PtrVT)
8606 Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
8607
8608 assert(Mask.getValueType() == PtrVT);
8609 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
8610 return;
8611 }
8612 case Intrinsic::threadlocal_address: {
8613 setValue(&I, getValue(I.getOperand(0)));
8614 return;
8615 }
8616 case Intrinsic::get_active_lane_mask: {
8617 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8618 SDValue Index = getValue(I.getOperand(0));
8619 SDValue TripCount = getValue(I.getOperand(1));
8620 EVT ElementVT = Index.getValueType();
8621
8622 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
8623 setValue(&I, DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, sdl, CCVT, Index,
8624 TripCount));
8625 return;
8626 }
8627
8628 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
8629 CCVT.getVectorElementCount());
8630
8631 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
8632 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
8633 SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
8634 SDValue VectorInduction = DAG.getNode(
8635 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
8636 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
8637 VectorTripCount, ISD::CondCode::SETULT);
8638 setValue(&I, SetCC);
8639 return;
8640 }
8641 case Intrinsic::mask_beforefirst: {
8642 SDValue Op = getValue(I.getOperand(0));
8643 setValue(&I,
8644 DAG.getNode(ISD::MASK_BEFOREFIRST, sdl, Op.getValueType(), Op));
8645 return;
8646 }
8647 case Intrinsic::experimental_get_vector_length: {
8648 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8649 "Expected positive VF");
8650 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
8651 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
8652
8653 SDValue Count = getValue(I.getOperand(0));
8654 EVT CountVT = Count.getValueType();
8655
8656 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8657 visitTargetIntrinsic(I, Intrinsic);
8658 return;
8659 }
8660
8661 // Expand to a umin between the trip count and the maximum elements the type
8662 // can hold.
8663 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8664
8665 // Extend the trip count to at least the result VT.
8666 if (CountVT.bitsLT(VT)) {
8667 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
8668 CountVT = VT;
8669 }
8670
8671 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
8672 ElementCount::get(VF, IsScalable));
8673
8674 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8675 // Clip to the result type if needed.
8676 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8677
8678 setValue(&I, Trunc);
8679 return;
8680 }
8681 case Intrinsic::vector_partial_reduce_add: {
8682 SDValue Acc = getValue(I.getOperand(0));
8683 SDValue Input = getValue(I.getOperand(1));
8684 setValue(&I,
8685 DAG.getNode(ISD::PARTIAL_REDUCE_UMLA, sdl, Acc.getValueType(), Acc,
8686 Input, DAG.getConstant(1, sdl, Input.getValueType())));
8687 return;
8688 }
8689 case Intrinsic::vector_partial_reduce_fadd: {
8690 SDNodeFlags Flags;
8691 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
8692 Flags.copyFMF(*FPOp);
8693 SDValue Acc = getValue(I.getOperand(0));
8694 SDValue Input = getValue(I.getOperand(1));
8695 setValue(&I, DAG.getNode(ISD::PARTIAL_REDUCE_FMLA, sdl, Acc.getValueType(),
8696 Acc, Input,
8697 DAG.getConstantFP(1.0, sdl, Input.getValueType()),
8698 Flags));
8699 return;
8700 }
8701 case Intrinsic::experimental_cttz_elts: {
8702 SDValue Op = getValue(I.getOperand(0));
8703 EVT OpVT = Op.getValueType();
8704 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8705 bool ZeroIsPoison =
8706 !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8707 if (OpVT.getVectorElementType() != MVT::i1) {
8708 // Compare the input vector elements to zero & use to count trailing
8709 // zeros.
8710 SDValue AllZero = DAG.getConstant(0, sdl, OpVT);
8711 EVT I1OpVT = OpVT.changeVectorElementType(*DAG.getContext(), MVT::i1);
8712 Op = DAG.getSetCC(sdl, I1OpVT, Op, AllZero, ISD::SETNE);
8713 }
8714 setValue(&I, DAG.getNode(ZeroIsPoison ? ISD::CTTZ_ELTS_ZERO_POISON
8716 sdl, RetTy, Op));
8717 return;
8718 }
8719 case Intrinsic::vector_insert: {
8720 SDValue Vec = getValue(I.getOperand(0));
8721 SDValue SubVec = getValue(I.getOperand(1));
8722 SDValue Index = getValue(I.getOperand(2));
8723
8724 // The intrinsic's index type is i64, but the SDNode requires an index type
8725 // suitable for the target. Convert the index as required.
8726 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8727 if (Index.getValueType() != VectorIdxTy)
8728 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8729
8730 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8731 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8732 Index));
8733 return;
8734 }
8735 case Intrinsic::vector_extract: {
8736 SDValue Vec = getValue(I.getOperand(0));
8737 SDValue Index = getValue(I.getOperand(1));
8738 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8739
8740 // The intrinsic's index type is i64, but the SDNode requires an index type
8741 // suitable for the target. Convert the index as required.
8742 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8743 if (Index.getValueType() != VectorIdxTy)
8744 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8745
8746 setValue(&I,
8747 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8748 return;
8749 }
8750 case Intrinsic::experimental_vector_match: {
8751 SDValue Op1 = getValue(I.getOperand(0));
8752 SDValue Op2 = getValue(I.getOperand(1));
8753 SDValue Mask = getValue(I.getOperand(2));
8754 EVT ResVT = Mask.getValueType();
8755 setValue(&I, DAG.getNode(ISD::VECTOR_MATCH, sdl, ResVT, Op1, Op2, Mask));
8756 return;
8757 }
8758 case Intrinsic::vector_reverse:
8759 visitVectorReverse(I);
8760 return;
8761 case Intrinsic::vector_splice_left:
8762 case Intrinsic::vector_splice_right:
8763 visitVectorSplice(I);
8764 return;
8765 case Intrinsic::callbr_landingpad:
8766 visitCallBrLandingPad(I);
8767 return;
8768 case Intrinsic::vector_interleave2:
8769 visitVectorInterleave(I, 2);
8770 return;
8771 case Intrinsic::vector_interleave3:
8772 visitVectorInterleave(I, 3);
8773 return;
8774 case Intrinsic::vector_interleave4:
8775 visitVectorInterleave(I, 4);
8776 return;
8777 case Intrinsic::vector_interleave5:
8778 visitVectorInterleave(I, 5);
8779 return;
8780 case Intrinsic::vector_interleave6:
8781 visitVectorInterleave(I, 6);
8782 return;
8783 case Intrinsic::vector_interleave7:
8784 visitVectorInterleave(I, 7);
8785 return;
8786 case Intrinsic::vector_interleave8:
8787 visitVectorInterleave(I, 8);
8788 return;
8789 case Intrinsic::vector_deinterleave2:
8790 visitVectorDeinterleave(I, 2);
8791 return;
8792 case Intrinsic::vector_deinterleave3:
8793 visitVectorDeinterleave(I, 3);
8794 return;
8795 case Intrinsic::vector_deinterleave4:
8796 visitVectorDeinterleave(I, 4);
8797 return;
8798 case Intrinsic::vector_deinterleave5:
8799 visitVectorDeinterleave(I, 5);
8800 return;
8801 case Intrinsic::vector_deinterleave6:
8802 visitVectorDeinterleave(I, 6);
8803 return;
8804 case Intrinsic::vector_deinterleave7:
8805 visitVectorDeinterleave(I, 7);
8806 return;
8807 case Intrinsic::vector_deinterleave8:
8808 visitVectorDeinterleave(I, 8);
8809 return;
8810 case Intrinsic::vector_repeat: {
8811 SDValue Vec = getValue(I.getOperand(0));
8812 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8813 setValue(&I, DAG.getNode(ISD::VECTOR_REPEAT, sdl, ResultVT, Vec));
8814 return;
8815 }
8816 case Intrinsic::experimental_vector_compress:
8817 setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8818 getValue(I.getArgOperand(0)).getValueType(),
8819 getValue(I.getArgOperand(0)),
8820 getValue(I.getArgOperand(1)),
8821 getValue(I.getArgOperand(2)), Flags));
8822 return;
8823 case Intrinsic::experimental_convergence_anchor:
8824 case Intrinsic::experimental_convergence_entry:
8825 case Intrinsic::experimental_convergence_loop:
8826 visitConvergenceControl(I, Intrinsic);
8827 return;
8828 case Intrinsic::experimental_vector_histogram_add: {
8829 visitVectorHistogram(I, Intrinsic);
8830 return;
8831 }
8832 case Intrinsic::experimental_vector_extract_last_active: {
8833 visitVectorExtractLastActive(I, Intrinsic);
8834 return;
8835 }
8836 case Intrinsic::loop_dependence_war_mask:
8837 setValue(&I,
8839 EVT::getEVT(I.getType()), getValue(I.getOperand(0)),
8840 getValue(I.getOperand(1)), getValue(I.getOperand(2)),
8841 DAG.getConstant(0, sdl, MVT::i64)));
8842 return;
8843 case Intrinsic::loop_dependence_raw_mask:
8844 setValue(&I,
8846 EVT::getEVT(I.getType()), getValue(I.getOperand(0)),
8847 getValue(I.getOperand(1)), getValue(I.getOperand(2)),
8848 DAG.getConstant(0, sdl, MVT::i64)));
8849 return;
8850 case Intrinsic::masked_udiv:
8851 setValue(&I,
8852 DAG.getNode(ISD::MASKED_UDIV, sdl, EVT::getEVT(I.getType()),
8853 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8854 getValue(I.getOperand(2))));
8855 return;
8856 case Intrinsic::masked_sdiv:
8857 setValue(&I,
8858 DAG.getNode(ISD::MASKED_SDIV, sdl, EVT::getEVT(I.getType()),
8859 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8860 getValue(I.getOperand(2))));
8861 return;
8862 case Intrinsic::masked_urem:
8863 setValue(&I,
8864 DAG.getNode(ISD::MASKED_UREM, sdl, EVT::getEVT(I.getType()),
8865 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8866 getValue(I.getOperand(2))));
8867 return;
8868 case Intrinsic::masked_srem:
8869 setValue(&I,
8870 DAG.getNode(ISD::MASKED_SREM, sdl, EVT::getEVT(I.getType()),
8871 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8872 getValue(I.getOperand(2))));
8873 return;
8874 }
8875}
8876
8877void SelectionDAGBuilder::pushFPOpOutChain(SDValue Result,
8879 assert(Result.getNode()->getNumValues() == 2);
8880 SDValue OutChain = Result.getValue(1);
8881 assert(OutChain.getValueType() == MVT::Other);
8882
8883 // Instead of updating the root immediately, push the produced chain to the
8884 // appropriate list, deferring the update until the root is requested. In this
8885 // case, the nodes from the lists are chained using TokenFactor, indicating
8886 // that the operations are independent.
8887 //
8888 // In particular, the root is updated before any call that might access the
8889 // floating-point environment, except for constrained intrinsics.
8890 switch (EB) {
8893 PendingConstrainedFP.push_back(OutChain);
8894 break;
8896 PendingConstrainedFPStrict.push_back(OutChain);
8897 break;
8898 }
8899}
8900
8901void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8902 const ConstrainedFPIntrinsic &FPI) {
8903 SDLoc sdl = getCurSDLoc();
8904
8905 // We do not need to serialize constrained FP intrinsics against
8906 // each other or against (nonvolatile) loads, so they can be
8907 // chained like loads.
8909 SDValue Chain = getFPOperationRoot(EB);
8911 Opers.push_back(Chain);
8912 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8913 Opers.push_back(getValue(FPI.getArgOperand(I)));
8914
8915 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8916 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8917 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8918
8919 SDNodeFlags Flags;
8921 Flags.setNoFPExcept(true);
8922
8923 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8924 Flags.copyFMF(*FPOp);
8925
8926 unsigned Opcode;
8927 switch (FPI.getIntrinsicID()) {
8928 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8929#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8930 case Intrinsic::INTRINSIC: \
8931 Opcode = ISD::STRICT_##DAGN; \
8932 break;
8933#include "llvm/IR/ConstrainedOps.def"
8934 case Intrinsic::experimental_constrained_fmuladd: {
8935 Opcode = ISD::STRICT_FMA;
8936 // Break fmuladd into fmul and fadd.
8937 if (!TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8938 Opers.pop_back();
8939 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8940 pushFPOpOutChain(Mul, EB);
8941 Opcode = ISD::STRICT_FADD;
8942 Opers.clear();
8943 Opers.push_back(Mul.getValue(1));
8944 Opers.push_back(Mul.getValue(0));
8945 Opers.push_back(getValue(FPI.getArgOperand(2)));
8946 }
8947 break;
8948 }
8949 }
8950
8951 // A few strict DAG nodes carry additional operands that are not
8952 // set up by the default code above.
8953 switch (Opcode) {
8954 default: break;
8956 Opers.push_back(
8957 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8958 break;
8959 case ISD::STRICT_FSETCC:
8960 case ISD::STRICT_FSETCCS: {
8961 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8962 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8963 if (DAG.isKnownNeverNaN(Opers[1]) && DAG.isKnownNeverNaN(Opers[2]))
8964 Condition = getFCmpCodeWithoutNaN(Condition);
8965 Opers.push_back(DAG.getCondCode(Condition));
8966 break;
8967 }
8968 }
8969
8970 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8971 pushFPOpOutChain(Result, EB);
8972
8973 SDValue FPResult = Result.getValue(0);
8974 setValue(&FPI, FPResult);
8975}
8976
8977static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8978 std::optional<unsigned> ResOPC;
8979 switch (VPIntrin.getIntrinsicID()) {
8980 case Intrinsic::vp_cttz_elts: {
8981 bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8982 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_POISON : ISD::VP_CTTZ_ELTS;
8983 break;
8984 }
8985#define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \
8986 case Intrinsic::VPID: \
8987 ResOPC = ISD::VPSD; \
8988 break;
8989#include "llvm/IR/VPIntrinsics.def"
8990 }
8991
8992 if (!ResOPC)
8994 "Inconsistency: no SDNode available for this VPIntrinsic!");
8995
8996 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8997 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8998 if (VPIntrin.getFastMathFlags().allowReassoc())
8999 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
9000 : ISD::VP_REDUCE_FMUL;
9001 }
9002
9003 return *ResOPC;
9004}
9005
9006void SelectionDAGBuilder::visitVPLoad(
9007 const VPIntrinsic &VPIntrin, EVT VT,
9008 const SmallVectorImpl<SDValue> &OpValues) {
9009 SDLoc DL = getCurSDLoc();
9010 Value *PtrOperand = VPIntrin.getArgOperand(0);
9011 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9012 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9013 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9014 SDValue LD;
9015 // Do not serialize variable-length loads of constant memory with
9016 // anything.
9017 if (!Alignment)
9018 Alignment = DAG.getEVTAlign(VT);
9019 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9020 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9021 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9022 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9023 MachineMemOperand::Flags MMOFlags =
9024 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9025 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9026 MachinePointerInfo(PtrOperand), MMOFlags,
9028 MMOMetadata(AAInfo, Ranges));
9029 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
9030 MMO, false /*IsExpanding */);
9031 if (AddToChain)
9032 PendingLoads.push_back(LD.getValue(1));
9033 setValue(&VPIntrin, LD);
9034}
9035
9036void SelectionDAGBuilder::visitVPLoadFF(
9037 const VPIntrinsic &VPIntrin, EVT VT, EVT EVLVT,
9038 const SmallVectorImpl<SDValue> &OpValues) {
9039 assert(OpValues.size() == 3 && "Unexpected number of operands");
9040 SDLoc DL = getCurSDLoc();
9041 Value *PtrOperand = VPIntrin.getArgOperand(0);
9042 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9043 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9044 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
9045 SDValue LD;
9046 // Do not serialize variable-length loads of constant memory with
9047 // anything.
9048 if (!Alignment)
9049 Alignment = DAG.getEVTAlign(VT);
9050 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9051 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9052 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9053 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9054 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
9056 MMOMetadata(AAInfo, Ranges));
9057 LD = DAG.getLoadFFVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
9058 MMO);
9059 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, EVLVT, LD.getValue(1));
9060 if (AddToChain)
9061 PendingLoads.push_back(LD.getValue(2));
9062 setValue(&VPIntrin, DAG.getMergeValues({LD.getValue(0), Trunc}, DL));
9063}
9064
9065void SelectionDAGBuilder::visitVPGather(
9066 const VPIntrinsic &VPIntrin, EVT VT,
9067 const SmallVectorImpl<SDValue> &OpValues) {
9068 SDLoc DL = getCurSDLoc();
9069 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9070 Value *PtrOperand = VPIntrin.getArgOperand(0);
9071 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9072 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9073 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9074 SDValue LD;
9075 if (!Alignment)
9076 Alignment = DAG.getEVTAlign(VT.getScalarType());
9077 unsigned AS =
9078 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
9079 MachineMemOperand::Flags MMOFlags =
9080 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9081 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9082 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9083 *Alignment, MMOMetadata(AAInfo, Ranges));
9084 SDValue Base, Index, Scale;
9085 bool UniformBase =
9086 getUniformBase(PtrOperand, Base, Index, Scale, this, VPIntrin.getParent(),
9087 VT.getScalarStoreSize());
9088 if (!UniformBase) {
9089 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
9090 Index = getValue(PtrOperand);
9091 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
9092 }
9093 EVT IdxVT = Index.getValueType();
9094 EVT EltTy = IdxVT.getVectorElementType();
9095 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
9096 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
9097 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
9098 }
9099 LD = DAG.getGatherVP(
9100 DAG.getVTList(VT, MVT::Other), VT, DL,
9101 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
9103 PendingLoads.push_back(LD.getValue(1));
9104 setValue(&VPIntrin, LD);
9105}
9106
9107void SelectionDAGBuilder::visitVPStore(
9108 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9109 SDLoc DL = getCurSDLoc();
9110 Value *PtrOperand = VPIntrin.getArgOperand(1);
9111 EVT VT = OpValues[0].getValueType();
9112 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9113 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9114 SDValue ST;
9115 if (!Alignment)
9116 Alignment = DAG.getEVTAlign(VT);
9117 SDValue Ptr = OpValues[1];
9118 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
9119 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9120 MachineMemOperand::Flags MMOFlags =
9121 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9122 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9123 MachinePointerInfo(PtrOperand), MMOFlags,
9124 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
9125 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
9126 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
9127 /* IsTruncating */ false, /*IsCompressing*/ false);
9128 DAG.setRoot(ST);
9129 setValue(&VPIntrin, ST);
9130}
9131
9132void SelectionDAGBuilder::visitVPScatter(
9133 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9134 SDLoc DL = getCurSDLoc();
9135 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9136 Value *PtrOperand = VPIntrin.getArgOperand(1);
9137 EVT VT = OpValues[0].getValueType();
9138 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9139 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9140 SDValue ST;
9141 if (!Alignment)
9142 Alignment = DAG.getEVTAlign(VT.getScalarType());
9143 unsigned AS =
9144 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
9145 MachineMemOperand::Flags MMOFlags =
9146 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9147 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9148 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9149 *Alignment, AAInfo);
9150 SDValue Base, Index, Scale;
9151 bool UniformBase =
9152 getUniformBase(PtrOperand, Base, Index, Scale, this, VPIntrin.getParent(),
9153 VT.getScalarStoreSize());
9154 if (!UniformBase) {
9155 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
9156 Index = getValue(PtrOperand);
9157 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
9158 }
9159 EVT IdxVT = Index.getValueType();
9160 EVT EltTy = IdxVT.getVectorElementType();
9161 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
9162 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
9163 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
9164 }
9165 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
9166 {getMemoryRoot(), OpValues[0], Base, Index, Scale,
9167 OpValues[2], OpValues[3]},
9168 MMO, ISD::SIGNED_SCALED);
9169 DAG.setRoot(ST);
9170 setValue(&VPIntrin, ST);
9171}
9172
9173void SelectionDAGBuilder::visitVPStridedLoad(
9174 const VPIntrinsic &VPIntrin, EVT VT,
9175 const SmallVectorImpl<SDValue> &OpValues) {
9176 SDLoc DL = getCurSDLoc();
9177 Value *PtrOperand = VPIntrin.getArgOperand(0);
9178 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9179 if (!Alignment)
9180 Alignment = DAG.getEVTAlign(VT.getScalarType());
9181 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9182 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9183 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9184 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9185 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9186 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9187 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9188 MachineMemOperand::Flags MMOFlags =
9189 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9190 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9191 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9192 *Alignment, MMOMetadata(AAInfo, Ranges));
9193
9194 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
9195 OpValues[2], OpValues[3], MMO,
9196 false /*IsExpanding*/);
9197
9198 if (AddToChain)
9199 PendingLoads.push_back(LD.getValue(1));
9200 setValue(&VPIntrin, LD);
9201}
9202
9203void SelectionDAGBuilder::visitVPStridedStore(
9204 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9205 SDLoc DL = getCurSDLoc();
9206 Value *PtrOperand = VPIntrin.getArgOperand(1);
9207 EVT VT = OpValues[0].getValueType();
9208 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9209 if (!Alignment)
9210 Alignment = DAG.getEVTAlign(VT.getScalarType());
9211 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9212 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9213 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9214 MachineMemOperand::Flags MMOFlags =
9215 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9216 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9217 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9218 *Alignment, AAInfo);
9219
9220 SDValue ST = DAG.getStridedStoreVP(
9221 getMemoryRoot(), DL, OpValues[0], OpValues[1],
9222 DAG.getPOISON(OpValues[1].getValueType()), OpValues[2], OpValues[3],
9223 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
9224 /*IsCompressing*/ false);
9225
9226 DAG.setRoot(ST);
9227 setValue(&VPIntrin, ST);
9228}
9229
9230void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
9231 const VPIntrinsic &VPIntrin) {
9232 SDLoc DL = getCurSDLoc();
9233 unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
9234
9235 auto IID = VPIntrin.getIntrinsicID();
9236
9237 SmallVector<EVT, 4> ValueVTs;
9238 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9239 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
9240 SDVTList VTs = DAG.getVTList(ValueVTs);
9241
9242 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
9243
9244 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
9245 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
9246 "Unexpected target EVL type");
9247
9248 // Request operands.
9249 SmallVector<SDValue, 7> OpValues;
9250 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
9251 auto Op = getValue(VPIntrin.getArgOperand(I));
9252 if (I == EVLParamPos)
9253 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
9254 OpValues.push_back(Op);
9255 }
9256
9257 switch (Opcode) {
9258 default: {
9259 SDNodeFlags SDFlags;
9260 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
9261 SDFlags.copyFMF(*FPMO);
9262 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
9263 setValue(&VPIntrin, Result);
9264 break;
9265 }
9266 case ISD::VP_LOAD:
9267 visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
9268 break;
9269 case ISD::VP_LOAD_FF:
9270 visitVPLoadFF(VPIntrin, ValueVTs[0], ValueVTs[1], OpValues);
9271 break;
9272 case ISD::VP_GATHER:
9273 visitVPGather(VPIntrin, ValueVTs[0], OpValues);
9274 break;
9275 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
9276 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
9277 break;
9278 case ISD::VP_STORE:
9279 visitVPStore(VPIntrin, OpValues);
9280 break;
9281 case ISD::VP_SCATTER:
9282 visitVPScatter(VPIntrin, OpValues);
9283 break;
9284 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
9285 visitVPStridedStore(VPIntrin, OpValues);
9286 break;
9287 case ISD::VP_CTTZ_ELTS_ZERO_POISON:
9288 case ISD::VP_CTTZ_ELTS: {
9289 SDValue Result =
9290 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
9291 setValue(&VPIntrin, Result);
9292 break;
9293 }
9294 }
9295}
9296
9298 const BasicBlock *EHPadBB,
9299 MCSymbol *&BeginLabel) {
9300 MachineFunction &MF = DAG.getMachineFunction();
9301
9302 // Skip emitting EH_LABEL on targets whose exception tables don't reference
9303 // them (32-bit x86 SEH, Wasm).
9305 FuncInfo.ExceptionModel)) {
9306 BeginLabel = nullptr;
9307 return Chain;
9308 }
9309
9310 // Insert a label before the invoke call to mark the try range. This can be
9311 // used to detect deletion of the invoke via the MachineModuleInfo.
9312 BeginLabel = MF.getContext().createTempSymbol();
9313
9314 // For SjLj, keep track of which landing pads go with which invokes
9315 // so as to maintain the ordering of pads in the LSDA.
9316 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
9317 if (CallSiteIndex) {
9318 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
9319 LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
9320
9321 // Now that the call site is handled, stop tracking it.
9322 FuncInfo.setCurrentCallSite(0);
9323 }
9324
9325 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
9326}
9327
9328SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
9329 const BasicBlock *EHPadBB,
9330 MCSymbol *BeginLabel) {
9331 // No labels were emitted.
9332 if (!BeginLabel)
9333 return Chain;
9334
9336
9337 // Insert a label at the end of the invoke call to mark the try range. This
9338 // can be used to detect deletion of the invoke via the MachineModuleInfo.
9339 MCSymbol *EndLabel = MF.getContext().createTempSymbol();
9340 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
9341
9342 // Inform MachineModuleInfo of range.
9344 // There is a platform (e.g. wasm) that uses funclet style IR but does not
9345 // actually use outlined funclets and their LSDA info style.
9346 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
9347 assert(II && "II should've been set");
9348 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
9349 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
9350 } else if (!isScopedEHPersonality(Pers)) {
9351 assert(EHPadBB);
9352 MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
9353 }
9354
9355 return Chain;
9356}
9357
9358std::pair<SDValue, SDValue>
9360 const BasicBlock *EHPadBB) {
9361 MCSymbol *BeginLabel = nullptr;
9362
9363 if (EHPadBB) {
9364 // Both PendingLoads and PendingExports must be flushed here;
9365 // this call might not return.
9366 (void)getRoot();
9367 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
9368 CLI.setChain(getRoot());
9369 }
9370
9371 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9372 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
9373
9374 assert((CLI.IsTailCall || Result.second.getNode()) &&
9375 "Non-null chain expected with non-tail call!");
9376 assert((Result.second.getNode() || !Result.first.getNode()) &&
9377 "Null value expected with tail call!");
9378
9379 if (!Result.second.getNode()) {
9380 // As a special case, a null chain means that a tail call has been emitted
9381 // and the DAG root is already updated.
9382 HasTailCall = true;
9383
9384 // Since there's no actual continuation from this block, nothing can be
9385 // relying on us setting vregs for them.
9386 PendingExports.clear();
9387 } else {
9388 DAG.setRoot(Result.second);
9389 }
9390
9391 if (EHPadBB) {
9392 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
9393 BeginLabel));
9394 Result.second = getRoot();
9395 }
9396
9397 return Result;
9398}
9399
9401 bool isMustTailCall = CB.isMustTailCall();
9402
9403 // Avoid emitting tail calls in functions with the disable-tail-calls
9404 // attribute.
9405 const Function *Caller = CB.getParent()->getParent();
9406 if (!isMustTailCall &&
9407 Caller->getFnAttribute("disable-tail-calls").getValueAsBool())
9408 return false;
9409
9410 // We can't tail call inside a function with a swifterror argument. Lowering
9411 // does not support this yet. It would have to move into the swifterror
9412 // register before the call.
9413 if (DAG.hasSwiftErrorArg())
9414 return false;
9415
9416 // Check if target-independent constraints permit a tail call here.
9417 // Target-dependent constraints are checked within TLI->LowerCallTo.
9418 return isInTailCallPosition(CB, DAG.getTarget());
9419}
9420
9422 bool isTailCall, bool isMustTailCall,
9423 const BasicBlock *EHPadBB,
9424 const TargetLowering::PtrAuthInfo *PAI) {
9425 auto &DL = DAG.getDataLayout();
9426 FunctionType *FTy = CB.getFunctionType();
9427 Type *RetTy = CB.getType();
9428
9430 Args.reserve(CB.arg_size());
9431
9432 const Value *SwiftErrorVal = nullptr;
9433 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9434
9435 if (isTailCall)
9436 isTailCall = canTailCall(CB);
9437
9438 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
9439 const Value *V = *I;
9440
9441 // Skip empty types
9442 if (V->getType()->isEmptyTy())
9443 continue;
9444
9445 SDValue ArgNode = getValue(V);
9446 TargetLowering::ArgListEntry Entry(ArgNode, V->getType());
9447 Entry.setAttributes(&CB, I - CB.arg_begin());
9448
9449 // Use swifterror virtual register as input to the call.
9450 if (Entry.IsSwiftError && TLI.supportSwiftError()) {
9451 SwiftErrorVal = V;
9452 // We find the virtual register for the actual swifterror argument.
9453 // Instead of using the Value, we use the virtual register instead.
9454 Entry.Node =
9455 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
9456 EVT(TLI.getPointerTy(DL)));
9457 }
9458
9459 Args.push_back(Entry);
9460
9461 // If we have an explicit sret argument that is an Instruction, (i.e., it
9462 // might point to function-local memory), we can't meaningfully tail-call.
9463 if (Entry.IsSRet && isa<Instruction>(V))
9464 isTailCall = false;
9465 }
9466
9467 // If call site has a cfguardtarget operand bundle, create and add an
9468 // additional ArgListEntry.
9469 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
9470 Value *V = Bundle->Inputs[0];
9472 Entry.IsCFGuardTarget = true;
9473 Args.push_back(Entry);
9474 }
9475
9476 // Disable tail calls if there is an swifterror argument. Targets have not
9477 // been updated to support tail calls.
9478 if (TLI.supportSwiftError() && SwiftErrorVal)
9479 isTailCall = false;
9480
9481 ConstantInt *CFIType = nullptr;
9482 if (CB.isIndirectCall()) {
9483 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
9484 if (!TLI.supportKCFIBundles())
9486 "Target doesn't support calls with kcfi operand bundles.");
9487 CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
9488 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
9489 }
9490 }
9491
9492 SDValue ConvControlToken;
9493 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
9494 auto *Token = Bundle->Inputs[0].get();
9495 ConvControlToken = getValue(Token);
9496 }
9497
9498 GlobalValue *DeactivationSymbol = nullptr;
9500 DeactivationSymbol = cast<GlobalValue>(Bundle->Inputs[0].get());
9501 }
9502
9505 .setChain(getRoot())
9506 .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
9507 .setTailCall(isTailCall)
9511 .setCFIType(CFIType)
9512 .setConvergenceControlToken(ConvControlToken)
9513 .setDeactivationSymbol(DeactivationSymbol);
9514
9515 // Set the pointer authentication info if we have it.
9516 if (PAI) {
9517 if (!TLI.supportPtrAuthBundles())
9519 "This target doesn't support calls with ptrauth operand bundles.");
9520 CLI.setPtrAuth(*PAI);
9521 }
9522
9523 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9524
9525 if (Result.first.getNode()) {
9526 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
9527 Result.first = lowerNoFPClassToAssertNoFPClass(DAG, CB, Result.first);
9528 setValue(&CB, Result.first);
9529 }
9530
9531 // The last element of CLI.InVals has the SDValue for swifterror return.
9532 // Here we copy it to a virtual register and update SwiftErrorMap for
9533 // book-keeping.
9534 if (SwiftErrorVal && TLI.supportSwiftError()) {
9535 // Get the last element of InVals.
9536 SDValue Src = CLI.InVals.back();
9537 Register VReg =
9538 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
9539 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
9540 DAG.setRoot(CopyNode);
9541 }
9542}
9543
9544static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
9545 SelectionDAGBuilder &Builder) {
9546 // Check to see if this load can be trivially constant folded, e.g. if the
9547 // input is from a string literal.
9548 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
9549 // Cast pointer to the type we really want to load.
9550 Type *LoadTy =
9551 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
9552 if (LoadVT.isVector())
9553 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
9554 if (const Constant *LoadCst =
9555 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
9556 LoadTy, Builder.DAG.getDataLayout()))
9557 return Builder.getValue(LoadCst);
9558 }
9559
9560 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
9561 // still constant memory, the input chain can be the entry node.
9562 SDValue Root;
9563 bool ConstantMemory = false;
9564
9565 // Do not serialize (non-volatile) loads of constant memory with anything.
9566 if (Builder.BatchAA && Builder.BatchAA->pointsToConstantMemory(PtrVal)) {
9567 Root = Builder.DAG.getEntryNode();
9568 ConstantMemory = true;
9569 } else {
9570 // Do not serialize non-volatile loads against each other.
9571 Root = Builder.DAG.getRoot();
9572 }
9573
9574 SDValue Ptr = Builder.getValue(PtrVal);
9575 SDValue LoadVal =
9576 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
9577 MachinePointerInfo(PtrVal), Align(1));
9578
9579 if (!ConstantMemory)
9580 Builder.PendingLoads.push_back(LoadVal.getValue(1));
9581 return LoadVal;
9582}
9583
9584/// Record the value for an instruction that produces an integer result,
9585/// converting the type where necessary.
9586void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
9587 SDValue Value,
9588 bool IsSigned) {
9589 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9590 I.getType(), true);
9591 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
9592 setValue(&I, Value);
9593}
9594
9595/// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
9596/// true and lower it. Otherwise return false, and it will be lowered like a
9597/// normal call.
9598/// The caller already checked that \p I calls the appropriate LibFunc with a
9599/// correct prototype.
9600bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
9601 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
9602 const Value *Size = I.getArgOperand(2);
9603 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
9604 if (CSize && CSize->getZExtValue() == 0) {
9605 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9606 I.getType(), true);
9607 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
9608 return true;
9609 }
9610
9611 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9612 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9613 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
9614 getValue(Size), &I);
9615 if (Res.first.getNode()) {
9616 processIntegerCallValue(I, Res.first, true);
9617 PendingLoads.push_back(Res.second);
9618 return true;
9619 }
9620
9621 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
9622 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
9623 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
9624 return false;
9625
9626 // If the target has a fast compare for the given size, it will return a
9627 // preferred load type for that size. Require that the load VT is legal and
9628 // that the target supports unaligned loads of that type. Otherwise, return
9629 // INVALID.
9630 auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9631 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9632 MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9633 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9634 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9635 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9636 // TODO: Check alignment of src and dest ptrs.
9637 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9638 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9639 if (!TLI.isTypeLegal(LVT) ||
9640 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
9641 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
9643 }
9644
9645 return LVT;
9646 };
9647
9648 // This turns into unaligned loads. We only do this if the target natively
9649 // supports the MVT we'll be loading or if it is small enough (<= 4) that
9650 // we'll only produce a small number of byte loads.
9651 MVT LoadVT;
9652 unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9653 switch (NumBitsToCompare) {
9654 default:
9655 return false;
9656 case 16:
9657 LoadVT = MVT::i16;
9658 break;
9659 case 32:
9660 LoadVT = MVT::i32;
9661 break;
9662 case 64:
9663 case 128:
9664 case 256:
9665 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9666 break;
9667 }
9668
9669 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9670 return false;
9671
9672 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9673 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9674
9675 // Bitcast to a wide integer type if the loads are vectors.
9676 if (LoadVT.isVector()) {
9677 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9678 LoadL = DAG.getBitcast(CmpVT, LoadL);
9679 LoadR = DAG.getBitcast(CmpVT, LoadR);
9680 }
9681
9682 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9683 processIntegerCallValue(I, Cmp, false);
9684 return true;
9685}
9686
9687/// See if we can lower a memchr call into an optimized form. If so, return
9688/// true and lower it. Otherwise return false, and it will be lowered like a
9689/// normal call.
9690/// The caller already checked that \p I calls the appropriate LibFunc with a
9691/// correct prototype.
9692bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9693 const Value *Src = I.getArgOperand(0);
9694 const Value *Char = I.getArgOperand(1);
9695 const Value *Length = I.getArgOperand(2);
9696
9697 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9698 std::pair<SDValue, SDValue> Res =
9699 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9700 getValue(Src), getValue(Char), getValue(Length),
9701 MachinePointerInfo(Src));
9702 if (Res.first.getNode()) {
9703 setValue(&I, Res.first);
9704 PendingLoads.push_back(Res.second);
9705 return true;
9706 }
9707
9708 return false;
9709}
9710
9711/// See if we can lower a memccpy call into an optimized form. If so, return
9712/// true and lower it, otherwise return false and it will be lowered like a
9713/// normal call.
9714/// The caller already checked that \p I calls the appropriate LibFunc with a
9715/// correct prototype.
9716bool SelectionDAGBuilder::visitMemCCpyCall(const CallInst &I) {
9717 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9718 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemccpy(
9719 DAG, getCurSDLoc(), DAG.getRoot(), getValue(I.getArgOperand(0)),
9720 getValue(I.getArgOperand(1)), getValue(I.getArgOperand(2)),
9721 getValue(I.getArgOperand(3)), &I);
9722
9723 if (Res.first) {
9724 processIntegerCallValue(I, Res.first, true);
9725 PendingLoads.push_back(Res.second);
9726 return true;
9727 }
9728 return false;
9729}
9730
9731/// See if we can lower a mempcpy call into an optimized form. If so, return
9732/// true and lower it. Otherwise return false, and it will be lowered like a
9733/// normal call.
9734/// The caller already checked that \p I calls the appropriate LibFunc with a
9735/// correct prototype.
9736bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9737 SDValue Dst = getValue(I.getArgOperand(0));
9738 SDValue Src = getValue(I.getArgOperand(1));
9739 SDValue Size = getValue(I.getArgOperand(2));
9740
9741 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9742 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9743
9744 SDLoc sdl = getCurSDLoc();
9745
9746 // In the mempcpy context we need to pass in a false value for isTailCall
9747 // because the return pointer needs to be adjusted by the size of
9748 // the copied memory.
9749 SDValue Root = getMemoryRoot();
9750 SDValue MC = DAG.getMemcpy(
9751 Root, sdl, Dst, Src, Size, DstAlign, SrcAlign, false, false,
9752 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9753 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9754 assert(MC.getNode() != nullptr &&
9755 "** memcpy should not be lowered as TailCall in mempcpy context **");
9756 DAG.setRoot(MC);
9757
9758 // Check if Size needs to be truncated or extended.
9759 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9760
9761 // Adjust return pointer to point just past the last dst byte.
9762 SDValue DstPlusSize = DAG.getMemBasePlusOffset(Dst, Size, sdl);
9763 setValue(&I, DstPlusSize);
9764 return true;
9765}
9766
9767/// See if we can lower a strcpy call into an optimized form. If so, return
9768/// true and lower it, otherwise return false and it will be lowered like a
9769/// normal call.
9770/// The caller already checked that \p I calls the appropriate LibFunc with a
9771/// correct prototype.
9772bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9773 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9774
9775 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9776 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcpy(
9777 DAG, getCurSDLoc(), getRoot(), getValue(Arg0), getValue(Arg1),
9778 MachinePointerInfo(Arg0), MachinePointerInfo(Arg1), isStpcpy, &I);
9779 if (Res.first.getNode()) {
9780 setValue(&I, Res.first);
9781 DAG.setRoot(Res.second);
9782 return true;
9783 }
9784
9785 return false;
9786}
9787
9788/// See if we can lower a strcmp call into an optimized form. If so, return
9789/// true and lower it, otherwise return false and it will be lowered like a
9790/// normal call.
9791/// The caller already checked that \p I calls the appropriate LibFunc with a
9792/// correct prototype.
9793bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9794 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9795
9796 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9797 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcmp(
9798 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), getValue(Arg1),
9799 MachinePointerInfo(Arg0), MachinePointerInfo(Arg1), &I);
9800 if (Res.first.getNode()) {
9801 processIntegerCallValue(I, Res.first, true);
9802 PendingLoads.push_back(Res.second);
9803 return true;
9804 }
9805
9806 return false;
9807}
9808
9809/// See if we can lower a strlen call into an optimized form. If so, return
9810/// true and lower it, otherwise return false and it will be lowered like a
9811/// normal call.
9812/// The caller already checked that \p I calls the appropriate LibFunc with a
9813/// correct prototype.
9814bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9815 const Value *Arg0 = I.getArgOperand(0);
9816
9817 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9818 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrlen(
9819 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), &I);
9820 if (Res.first.getNode()) {
9821 processIntegerCallValue(I, Res.first, false);
9822 PendingLoads.push_back(Res.second);
9823 return true;
9824 }
9825
9826 return false;
9827}
9828
9829/// See if we can lower a strnlen call into an optimized form. If so, return
9830/// true and lower it, otherwise return false and it will be lowered like a
9831/// normal call.
9832/// The caller already checked that \p I calls the appropriate LibFunc with a
9833/// correct prototype.
9834bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9835 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9836
9837 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9838 std::pair<SDValue, SDValue> Res =
9839 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9840 getValue(Arg0), getValue(Arg1),
9841 MachinePointerInfo(Arg0));
9842 if (Res.first.getNode()) {
9843 processIntegerCallValue(I, Res.first, false);
9844 PendingLoads.push_back(Res.second);
9845 return true;
9846 }
9847
9848 return false;
9849}
9850
9851/// See if we can lower a Strstr call into an optimized form. If so, return
9852/// true and lower it, otherwise return false and it will be lowered like a
9853/// normal call.
9854/// The caller already checked that \p I calls the appropriate LibFunc with a
9855/// correct prototype.
9856bool SelectionDAGBuilder::visitStrstrCall(const CallInst &I) {
9857 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9858 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9859 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrstr(
9860 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), getValue(Arg1), &I);
9861 if (Res.first) {
9862 processIntegerCallValue(I, Res.first, false);
9863 PendingLoads.push_back(Res.second);
9864 return true;
9865 }
9866 return false;
9867}
9868
9869/// See if we can lower a unary floating-point operation into an SDNode with
9870/// the specified Opcode. If so, return true and lower it, otherwise return
9871/// false and it will be lowered like a normal call.
9872/// The caller already checked that \p I calls the appropriate LibFunc with a
9873/// correct prototype.
9874bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9875 unsigned Opcode) {
9876 // We already checked this call's prototype; verify it doesn't modify errno.
9877 // Do not perform optimizations for call sites that require strict
9878 // floating-point semantics.
9879 if (!I.onlyReadsMemory() || I.isStrictFP())
9880 return false;
9881
9882 SDNodeFlags Flags;
9883 Flags.copyFMF(cast<FPMathOperator>(I));
9884
9885 SDValue Tmp = getValue(I.getArgOperand(0));
9886 setValue(&I,
9887 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9888 return true;
9889}
9890
9891/// See if we can lower a binary floating-point operation into an SDNode with
9892/// the specified Opcode. If so, return true and lower it. Otherwise return
9893/// false, and it will be lowered like a normal call.
9894/// The caller already checked that \p I calls the appropriate LibFunc with a
9895/// correct prototype.
9896bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9897 unsigned Opcode) {
9898 // We already checked this call's prototype; verify it doesn't modify errno.
9899 // Do not perform optimizations for call sites that require strict
9900 // floating-point semantics.
9901 if (!I.onlyReadsMemory() || I.isStrictFP())
9902 return false;
9903
9904 SDNodeFlags Flags;
9905 Flags.copyFMF(cast<FPMathOperator>(I));
9906
9907 SDValue Tmp0 = getValue(I.getArgOperand(0));
9908 SDValue Tmp1 = getValue(I.getArgOperand(1));
9909 EVT VT = Tmp0.getValueType();
9910 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9911 return true;
9912}
9913
9914void SelectionDAGBuilder::visitCall(const CallInst &I) {
9915 // Handle inline assembly differently.
9916 if (I.isInlineAsm()) {
9917 visitInlineAsm(I);
9918 return;
9919 }
9920
9922
9923 if (Function *F = I.getCalledFunction()) {
9924 if (F->isDeclaration()) {
9925 // Is this an LLVM intrinsic?
9926 if (unsigned IID = F->getIntrinsicID()) {
9927 visitIntrinsicCall(I, IID);
9928 return;
9929 }
9930 }
9931
9932 // Check for well-known libc/libm calls. If the function is internal, it
9933 // can't be a library call. Don't do the check if marked as nobuiltin for
9934 // some reason.
9935 // This code should not handle libcalls that are already canonicalized to
9936 // intrinsics by the middle-end.
9937 LibFunc Func = !I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName()
9938 ? LibInfo->getLibFunc(*F)
9939 : NotLibFunc;
9940 if (LibInfo->hasOptimizedCodeGen(Func)) {
9941 switch (Func) {
9942 default: break;
9943 case LibFunc_bcmp:
9944 if (visitMemCmpBCmpCall(I))
9945 return;
9946 break;
9947 case LibFunc_copysign:
9948 case LibFunc_copysignf:
9949 case LibFunc_copysignl:
9950 // We already checked this call's prototype; verify it doesn't modify
9951 // errno.
9952 if (I.onlyReadsMemory()) {
9953 SDValue LHS = getValue(I.getArgOperand(0));
9954 SDValue RHS = getValue(I.getArgOperand(1));
9956 LHS.getValueType(), LHS, RHS));
9957 return;
9958 }
9959 break;
9960 case LibFunc_sin:
9961 case LibFunc_sinf:
9962 case LibFunc_sinl:
9963 if (visitUnaryFloatCall(I, ISD::FSIN))
9964 return;
9965 break;
9966 case LibFunc_cos:
9967 case LibFunc_cosf:
9968 case LibFunc_cosl:
9969 if (visitUnaryFloatCall(I, ISD::FCOS))
9970 return;
9971 break;
9972 case LibFunc_tan:
9973 case LibFunc_tanf:
9974 case LibFunc_tanl:
9975 if (visitUnaryFloatCall(I, ISD::FTAN))
9976 return;
9977 break;
9978 case LibFunc_asin:
9979 case LibFunc_asinf:
9980 case LibFunc_asinl:
9981 if (visitUnaryFloatCall(I, ISD::FASIN))
9982 return;
9983 break;
9984 case LibFunc_acos:
9985 case LibFunc_acosf:
9986 case LibFunc_acosl:
9987 if (visitUnaryFloatCall(I, ISD::FACOS))
9988 return;
9989 break;
9990 case LibFunc_atan:
9991 case LibFunc_atanf:
9992 case LibFunc_atanl:
9993 if (visitUnaryFloatCall(I, ISD::FATAN))
9994 return;
9995 break;
9996 case LibFunc_atan2:
9997 case LibFunc_atan2f:
9998 case LibFunc_atan2l:
9999 if (visitBinaryFloatCall(I, ISD::FATAN2))
10000 return;
10001 break;
10002 case LibFunc_sinh:
10003 case LibFunc_sinhf:
10004 case LibFunc_sinhl:
10005 if (visitUnaryFloatCall(I, ISD::FSINH))
10006 return;
10007 break;
10008 case LibFunc_cosh:
10009 case LibFunc_coshf:
10010 case LibFunc_coshl:
10011 if (visitUnaryFloatCall(I, ISD::FCOSH))
10012 return;
10013 break;
10014 case LibFunc_tanh:
10015 case LibFunc_tanhf:
10016 case LibFunc_tanhl:
10017 if (visitUnaryFloatCall(I, ISD::FTANH))
10018 return;
10019 break;
10020 case LibFunc_sqrt:
10021 case LibFunc_sqrtf:
10022 case LibFunc_sqrtl:
10023 case LibFunc_sqrt_finite:
10024 case LibFunc_sqrtf_finite:
10025 case LibFunc_sqrtl_finite:
10026 if (visitUnaryFloatCall(I, ISD::FSQRT))
10027 return;
10028 break;
10029 case LibFunc_log2:
10030 case LibFunc_log2f:
10031 case LibFunc_log2l:
10032 if (visitUnaryFloatCall(I, ISD::FLOG2))
10033 return;
10034 break;
10035 case LibFunc_exp2:
10036 case LibFunc_exp2f:
10037 case LibFunc_exp2l:
10038 if (visitUnaryFloatCall(I, ISD::FEXP2))
10039 return;
10040 break;
10041 case LibFunc_exp10:
10042 case LibFunc_exp10f:
10043 case LibFunc_exp10l:
10044 if (visitUnaryFloatCall(I, ISD::FEXP10))
10045 return;
10046 break;
10047 case LibFunc_ldexp:
10048 case LibFunc_ldexpf:
10049 case LibFunc_ldexpl:
10050 if (visitBinaryFloatCall(I, ISD::FLDEXP))
10051 return;
10052 break;
10053 case LibFunc_strstr:
10054 if (visitStrstrCall(I))
10055 return;
10056 break;
10057 case LibFunc_memcmp:
10058 if (visitMemCmpBCmpCall(I))
10059 return;
10060 break;
10061 case LibFunc_memccpy:
10062 if (visitMemCCpyCall(I))
10063 return;
10064 break;
10065 case LibFunc_mempcpy:
10066 if (visitMemPCpyCall(I))
10067 return;
10068 break;
10069 case LibFunc_memchr:
10070 if (visitMemChrCall(I))
10071 return;
10072 break;
10073 case LibFunc_strcpy:
10074 if (visitStrCpyCall(I, false))
10075 return;
10076 break;
10077 case LibFunc_stpcpy:
10078 if (visitStrCpyCall(I, true))
10079 return;
10080 break;
10081 case LibFunc_strcmp:
10082 if (visitStrCmpCall(I))
10083 return;
10084 break;
10085 case LibFunc_strlen:
10086 if (visitStrLenCall(I))
10087 return;
10088 break;
10089 case LibFunc_strnlen:
10090 if (visitStrNLenCall(I))
10091 return;
10092 break;
10093 }
10094 }
10095 }
10096
10097 if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
10098 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
10099 return;
10100 }
10101
10102 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
10103 // have to do anything here to lower funclet bundles.
10104 // CFGuardTarget bundles are lowered in LowerCallTo.
10106 I, "calls",
10111
10112 SDValue Callee = getValue(I.getCalledOperand());
10113
10114 if (I.hasDeoptState())
10115 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
10116 else
10117 // Check if we can potentially perform a tail call. More detailed checking
10118 // is be done within LowerCallTo, after more information about the call is
10119 // known.
10120 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
10121}
10122
10124 const CallBase &CB, const BasicBlock *EHPadBB) {
10125 auto PAB = CB.getOperandBundle("ptrauth");
10126 const Value *CalleeV = CB.getCalledOperand();
10127
10128 // Gather the call ptrauth data from the operand bundle:
10129 // [ i32 <key>, i64 <discriminator> ]
10130 const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
10131 const Value *Discriminator = PAB->Inputs[1];
10132
10133 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
10134 assert(Discriminator->getType()->isIntegerTy(64) &&
10135 "Invalid ptrauth discriminator");
10136
10137 // Look through ptrauth constants to find the raw callee.
10138 // Do a direct unauthenticated call if we found it and everything matches.
10139 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
10140 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
10141 DAG.getDataLayout()))
10142 return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
10143 CB.isMustTailCall(), EHPadBB);
10144
10145 // Functions should never be ptrauth-called directly.
10146 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
10147
10148 // Otherwise, do an authenticated indirect call.
10149 TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
10150 getValue(Discriminator)};
10151
10152 LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
10153 EHPadBB, &PAI);
10154}
10155
10156namespace {
10157
10158/// AsmOperandInfo - This contains information for each constraint that we are
10159/// lowering.
10160class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
10161public:
10162 /// CallOperand - If this is the result output operand or a clobber
10163 /// this is null, otherwise it is the incoming operand to the CallInst.
10164 /// This gets modified as the asm is processed.
10165 SDValue CallOperand;
10166
10167 /// AssignedRegs - If this is a register or register class operand, this
10168 /// contains the set of register corresponding to the operand.
10169 RegsForValue AssignedRegs;
10170
10171 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
10172 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
10173 }
10174
10175 /// Whether or not this operand accesses memory
10176 bool hasMemory(const TargetLowering &TLI) const {
10177 // Indirect operand accesses access memory.
10178 if (isIndirect)
10179 return true;
10180
10181 for (const auto &Code : Codes)
10183 return true;
10184
10185 return false;
10186 }
10187};
10188
10189
10190} // end anonymous namespace
10191
10192/// Make sure that the output operand \p OpInfo and its corresponding input
10193/// operand \p MatchingOpInfo have compatible constraint types (otherwise error
10194/// out).
10195static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
10196 SDISelAsmOperandInfo &MatchingOpInfo,
10197 SelectionDAG &DAG) {
10198 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
10199 return;
10200
10202 const auto &TLI = DAG.getTargetLoweringInfo();
10203
10204 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
10205 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
10206 OpInfo.ConstraintVT);
10207 std::pair<unsigned, const TargetRegisterClass *> InputRC =
10208 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
10209 MatchingOpInfo.ConstraintVT);
10210 const bool OutOpIsIntOrFP =
10211 OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
10212 const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
10213 MatchingOpInfo.ConstraintVT.isFloatingPoint();
10214 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
10215 // FIXME: error out in a more elegant fashion
10216 report_fatal_error("Unsupported asm: input constraint"
10217 " with a matching output constraint of"
10218 " incompatible type!");
10219 }
10220 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
10221}
10222
10223/// Get a direct memory input to behave well as an indirect operand.
10224/// This may introduce stores, hence the need for a \p Chain.
10225/// \return The (possibly updated) chain.
10226static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
10227 SDISelAsmOperandInfo &OpInfo,
10228 SelectionDAG &DAG) {
10229 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10230
10231 // If we don't have an indirect input, put it in the constpool if we can,
10232 // otherwise spill it to a stack slot.
10233 // TODO: This isn't quite right. We need to handle these according to
10234 // the addressing mode that the constraint wants. Also, this may take
10235 // an additional register for the computation and we don't want that
10236 // either.
10237
10238 // If the operand is a float, integer, or vector constant, spill to a
10239 // constant pool entry to get its address.
10240 const Value *OpVal = OpInfo.CallOperandVal;
10241 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
10243 OpInfo.CallOperand = DAG.getConstantPool(
10244 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
10245 return Chain;
10246 }
10247
10248 // Otherwise, create a stack slot and emit a store to it before the asm.
10249 Type *Ty = OpVal->getType();
10250 auto &DL = DAG.getDataLayout();
10251 TypeSize TySize = DL.getTypeAllocSize(Ty);
10254 int StackID = 0;
10255 if (TySize.isScalable())
10256 StackID = TFI->getStackIDForScalableVectors();
10257 int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
10258 DL.getPrefTypeAlign(Ty), false,
10259 nullptr, StackID);
10260 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
10261 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
10263 TLI.getMemValueType(DL, Ty));
10264 OpInfo.CallOperand = StackSlot;
10265
10266 return Chain;
10267}
10268
10269/// GetRegistersForValue - Assign registers (virtual or physical) for the
10270/// specified operand. We prefer to assign virtual registers, to allow the
10271/// register allocator to handle the assignment process. However, if the asm
10272/// uses features that we can't model on machineinstrs, we have SDISel do the
10273/// allocation. This produces generally horrible, but correct, code.
10274///
10275/// OpInfo describes the operand
10276/// RefOpInfo describes the matching operand if any, the operand otherwise
10277static std::optional<unsigned>
10279 SDISelAsmOperandInfo &OpInfo,
10280 SDISelAsmOperandInfo &RefOpInfo) {
10281 LLVMContext &Context = *DAG.getContext();
10282 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10283
10287
10288 // No work to do for memory/address operands.
10289 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
10290 OpInfo.ConstraintType == TargetLowering::C_Address)
10291 return std::nullopt;
10292
10293 // If this is a constraint for a single physreg, or a constraint for a
10294 // register class, find it.
10295 unsigned AssignedReg;
10296 const TargetRegisterClass *RC;
10297 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
10298 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
10299 // RC is unset only on failure. Return immediately.
10300 if (!RC)
10301 return std::nullopt;
10302
10303 // Get the actual register value type. This is important, because the user
10304 // may have asked for (e.g.) the AX register in i32 type. We need to
10305 // remember that AX is actually i16 to get the right extension.
10306 const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
10307
10308 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
10309 // If this is an FP operand in an integer register (or visa versa), or more
10310 // generally if the operand value disagrees with the register class we plan
10311 // to stick it in, fix the operand type.
10312 //
10313 // If this is an input value, the bitcast to the new type is done now.
10314 // Bitcast for output value is done at the end of visitInlineAsm().
10315 if ((OpInfo.Type == InlineAsm::isOutput ||
10316 OpInfo.Type == InlineAsm::isInput) &&
10317 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
10318 // Try to convert to the first EVT that the reg class contains. If the
10319 // types are identical size, use a bitcast to convert (e.g. two differing
10320 // vector types). Note: output bitcast is done at the end of
10321 // visitInlineAsm().
10322 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
10323 // Exclude indirect inputs while they are unsupported because the code
10324 // to perform the load is missing and thus OpInfo.CallOperand still
10325 // refers to the input address rather than the pointed-to value.
10326 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
10327 OpInfo.CallOperand =
10328 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
10329 OpInfo.ConstraintVT = RegVT;
10330 // If the operand is an FP value and we want it in integer registers,
10331 // use the corresponding integer type. This turns an f64 value into
10332 // i64, which can be passed with two i32 values on a 32-bit machine.
10333 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
10334 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
10335 // No integer type of that size to bitcast to (e.g. f80).
10336 if (!VT.isValid())
10337 return std::nullopt;
10338 if (OpInfo.Type == InlineAsm::isInput)
10339 OpInfo.CallOperand =
10340 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
10341 OpInfo.ConstraintVT = VT;
10342 }
10343 }
10344 }
10345
10346 // No need to allocate a matching input constraint since the constraint it's
10347 // matching to has already been allocated.
10348 if (OpInfo.isMatchingInputConstraint())
10349 return std::nullopt;
10350
10351 EVT ValueVT = OpInfo.ConstraintVT;
10352 if (OpInfo.ConstraintVT == MVT::Other)
10353 ValueVT = RegVT;
10354
10355 // Initialize NumRegs.
10356 unsigned NumRegs = 1;
10357 if (OpInfo.ConstraintVT != MVT::Other)
10358 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
10359
10360 // If this is a constraint for a specific physical register, like {r17},
10361 // assign it now.
10362
10363 // If this associated to a specific register, initialize iterator to correct
10364 // place. If virtual, make sure we have enough registers
10365
10366 // Initialize iterator if necessary
10369
10370 // Do not check for single registers.
10371 if (AssignedReg) {
10372 I = std::find(I, RC->end(), AssignedReg);
10373 if (I == RC->end()) {
10374 // RC does not contain the selected register, which indicates a
10375 // mismatch between the register and the required type/bitwidth.
10376 return {AssignedReg};
10377 }
10378 }
10379
10380 for (; NumRegs; --NumRegs, ++I) {
10381 assert(I != RC->end() && "Ran out of registers to allocate!");
10382 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
10383 Regs.push_back(R);
10384 }
10385
10386 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
10387 return std::nullopt;
10388}
10389
10390static unsigned
10392 const std::vector<SDValue> &AsmNodeOperands) {
10393 // Scan until we find the definition we already emitted of this operand.
10394 unsigned CurOp = InlineAsm::Op_FirstOperand;
10395 for (; OperandNo; --OperandNo) {
10396 // Advance to the next operand.
10397 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
10398 const InlineAsm::Flag F(OpFlag);
10399 assert(
10400 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
10401 "Skipped past definitions?");
10402 CurOp += F.getNumOperandRegisters() + 1;
10403 }
10404 return CurOp;
10405}
10406
10407namespace {
10408
10409class ExtraFlags {
10410 unsigned Flags = 0;
10411
10412public:
10413 explicit ExtraFlags(const CallBase &Call) {
10414 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
10415 if (IA->hasSideEffects())
10417 if (IA->isAlignStack())
10419 if (IA->canThrow())
10421 if (Call.isConvergent())
10423 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
10424 }
10425
10426 void update(const TargetLowering::AsmOperandInfo &OpInfo) {
10427 // Ideally, we would only check against memory constraints. However, the
10428 // meaning of an Other constraint can be target-specific and we can't easily
10429 // reason about it. Therefore, be conservative and set MayLoad/MayStore
10430 // for Other constraints as well.
10433 if (OpInfo.Type == InlineAsm::isInput)
10435 else if (OpInfo.Type == InlineAsm::isOutput)
10437 else if (OpInfo.Type == InlineAsm::isClobber)
10439 }
10440 }
10441
10442 unsigned get() const { return Flags; }
10443};
10444
10445} // end anonymous namespace
10446
10447static bool isFunction(SDValue Op) {
10448 if (Op && Op.getOpcode() == ISD::GlobalAddress) {
10449 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10450 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
10451
10452 // In normal "call dllimport func" instruction (non-inlineasm) it force
10453 // indirect access by specifing call opcode. And usually specially print
10454 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
10455 // not do in this way now. (In fact, this is similar with "Data Access"
10456 // action). So here we ignore dllimport function.
10457 if (Fn && !Fn->hasDLLImportStorageClass())
10458 return true;
10459 }
10460 }
10461 return false;
10462}
10463
10464namespace {
10465
10466struct ConstraintDecisionInfo {
10467 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
10468 std::vector<SDValue> AsmNodeOperands;
10469 SDValue Glue, Chain;
10470 bool HasSideEffect = false;
10471 MCSymbol *BeginLabel = nullptr;
10472
10473 SmallVector<char> Buffer;
10474 raw_svector_ostream ErrorMsg;
10475
10476 ConstraintDecisionInfo() : ErrorMsg(Buffer) {}
10477};
10478
10479} // end anonymous namespace
10480
10481/// Construct operand info objects.
10482static bool
10483constructOperandInfo(ConstraintDecisionInfo &Info,
10484 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10485 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10486 ExtraFlags &ExtraInfo) {
10487 for (auto &T : TargetConstraints) {
10488 Info.ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
10489 SDISelAsmOperandInfo &OpInfo = Info.ConstraintOperands.back();
10490
10491 if (OpInfo.CallOperandVal)
10492 OpInfo.CallOperand = Builder.getValue(OpInfo.CallOperandVal);
10493
10494 if (!Info.HasSideEffect)
10495 Info.HasSideEffect = OpInfo.hasMemory(TLI);
10496
10497 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
10498 // FIXME: Could we compute this on OpInfo rather than T?
10499
10500 // Compute the constraint code and ConstraintType to use.
10502
10503 if (T.ConstraintType == TargetLowering::C_Immediate && OpInfo.CallOperand &&
10504 !isa<ConstantSDNode>(OpInfo.CallOperand)) {
10505 // We've delayed emitting a diagnostic like the "n" constraint because
10506 // inlining could cause an integer showing up.
10507 Info.ErrorMsg << "constraint '" << T.ConstraintCode
10508 << "' expects an integer constant expression";
10509 return true;
10510 }
10511
10512 ExtraInfo.update(T);
10513 }
10514
10515 return false;
10516}
10517
10518/// Compute which constraint option to use for each operand.
10519static void
10520computeConstraintToUse(ConstraintDecisionInfo &Info, const CallBase &Call,
10521 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10522 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10523 const TargetMachine &TM, SelectionDAG &DAG) {
10524 const auto *IA = cast<InlineAsm>(Call.getCalledOperand());
10526 IA->collectAsmStrs(AsmStrs);
10527
10528 int OpNo = -1;
10529 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10530 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
10531 OpNo++;
10532
10533 // If this is an output operand with a matching input operand, look up the
10534 // matching input. If their types mismatch, e.g. one is an integer, the
10535 // other is floating point, or their sizes are different, flag it as an
10536 // error.
10537 if (OpInfo.hasMatchingInput()) {
10538 SDISelAsmOperandInfo &Input =
10539 Info.ConstraintOperands[OpInfo.MatchingInput];
10540 patchMatchingInput(OpInfo, Input, DAG);
10541 }
10542
10543 // Compute the constraint code and ConstraintType to use.
10544 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
10545
10546 if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
10547 OpInfo.Type == InlineAsm::isClobber) ||
10548 OpInfo.ConstraintType == TargetLowering::C_Address)
10549 continue;
10550
10551 // In Linux PIC model, there are 4 cases about value/label addressing:
10552 //
10553 // 1: Function call or Label jmp inside the module.
10554 // 2: Data access (such as global variable, static variable) inside module.
10555 // 3: Function call or Label jmp outside the module.
10556 // 4: Data access (such as global variable) outside the module.
10557 //
10558 // Due to current llvm inline asm architecture designed to not "recognize"
10559 // the asm code, there are quite troubles for us to treat mem addressing
10560 // differently for same value/adress used in different instructions.
10561 // For example, in pic model, call a func may in plt way or direclty
10562 // pc-related, but lea/mov a function adress may use got.
10563 //
10564 // Here we try to "recognize" function call for the case 1 and case 3 in
10565 // inline asm. And try to adjust the constraint for them.
10566 //
10567 // TODO: Due to current inline asm didn't encourage to jmp to the outsider
10568 // label, so here we don't handle jmp function label now, but we need to
10569 // enhance it (especilly in PIC model) if we meet meaningful requirements.
10570 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
10571 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
10573 OpInfo.isIndirect = false;
10574 OpInfo.ConstraintType = TargetLowering::C_Address;
10575 }
10576
10577 // If this is a memory input, and if the operand is not indirect, do what we
10578 // need to provide an address for the memory input.
10579 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
10580 !OpInfo.isIndirect) {
10581 assert((OpInfo.isMultipleAlternative ||
10582 (OpInfo.Type == InlineAsm::isInput)) &&
10583 "Can only indirectify direct input operands!");
10584
10585 // Memory operands really want the address of the value.
10586 Info.Chain = getAddressForMemoryInput(Info.Chain, Builder.getCurSDLoc(),
10587 OpInfo, DAG);
10588
10589 // There is no longer a Value* corresponding to this operand.
10590 OpInfo.CallOperandVal = nullptr;
10591
10592 // It is now an indirect operand.
10593 OpInfo.isIndirect = true;
10594 }
10595 }
10596}
10597
10598/// Prepare DAG-level operands. As part of this, assign virtual and physical
10599/// registers for inputs and output.
10600static bool prepareDAGLevelOperands(ConstraintDecisionInfo &Info,
10601 const CallBase &Call,
10602 SelectionDAGBuilder &Builder,
10603 const TargetLowering &TLI,
10604 SelectionDAG &DAG) {
10605 SDLoc DL = Builder.getCurSDLoc();
10606 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10607 // Assign Registers.
10608 SDISelAsmOperandInfo &RefOpInfo =
10609 OpInfo.isMatchingInputConstraint()
10610 ? Info.ConstraintOperands[OpInfo.getMatchedOperand()]
10611 : OpInfo;
10612 const auto RegError = getRegistersForValue(DAG, DL, OpInfo, RefOpInfo);
10613 if (RegError) {
10614 const MachineFunction &MF = DAG.getMachineFunction();
10616 const char *RegName = TRI.getName(*RegError);
10617 Info.ErrorMsg << "register '" << RegName << "' allocated for constraint '"
10618 << OpInfo.ConstraintCode
10619 << "' does not match required type";
10620 return true;
10621 }
10622
10623 auto DetectWriteToReservedRegister = [&]() {
10624 const MachineFunction &MF = DAG.getMachineFunction();
10626
10627 for (Register Reg : OpInfo.AssignedRegs.Regs) {
10628 if (Reg.isPhysical() && TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
10629 Info.ErrorMsg << "write to reserved register '"
10630 << TRI.getRegAsmName(Reg) << "'";
10631 return true;
10632 }
10633 }
10634
10635 return false;
10636 };
10637 assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10638 (OpInfo.Type == InlineAsm::isInput &&
10639 !OpInfo.isMatchingInputConstraint())) &&
10640 "Only address as input operand is allowed.");
10641
10642 switch (OpInfo.Type) {
10644 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10645 const InlineAsm::ConstraintCode ConstraintID =
10646 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10648 "Failed to convert memory constraint code to constraint id.");
10649
10650 // Add information to the INLINEASM node to know about this output.
10652 OpFlags.setMemConstraint(ConstraintID);
10653 Info.AsmNodeOperands.push_back(
10654 DAG.getTargetConstant(OpFlags, DL, MVT::i32));
10655 Info.AsmNodeOperands.push_back(OpInfo.CallOperand);
10656 } else {
10657 // Otherwise, this outputs to a register (directly for C_Register /
10658 // C_RegisterClass, and a target-defined fashion for
10659 // C_Immediate/C_Other). Find a register that we can use.
10660 if (OpInfo.AssignedRegs.Regs.empty()) {
10661 Info.ErrorMsg << "could not allocate output register for "
10662 << "constraint '" << OpInfo.ConstraintCode << "'";
10663 return true;
10664 }
10665
10666 if (DetectWriteToReservedRegister())
10667 return true;
10668
10669 // Add information to the INLINEASM node to know that this register is
10670 // set.
10671 OpInfo.AssignedRegs.AddInlineAsmOperands(
10672 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10674 false, 0, DL, DAG, Info.AsmNodeOperands);
10675 }
10676 break;
10677
10678 case InlineAsm::isInput:
10679 case InlineAsm::isLabel: {
10680 SDValue InOperandVal = OpInfo.CallOperand;
10681
10682 if (OpInfo.isMatchingInputConstraint()) {
10683 // If this is required to match an output register we have already set,
10684 // just use its register.
10685 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10686 Info.AsmNodeOperands);
10687 InlineAsm::Flag Flag(Info.AsmNodeOperands[CurOp]->getAsZExtVal());
10688 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10689 if (OpInfo.isIndirect) {
10690 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10691 Info.ErrorMsg << "inline asm not supported yet: cannot handle "
10692 << "tied indirect register inputs";
10693 return true;
10694 }
10695
10700 auto *R = cast<RegisterSDNode>(Info.AsmNodeOperands[CurOp + 1]);
10701 Register TiedReg = R->getReg();
10702 MVT RegVT = R->getSimpleValueType(0);
10703 const TargetRegisterClass *RC =
10704 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg)
10705 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10706 : TRI.getMinimalPhysRegClass(TiedReg);
10707 for (unsigned I = 0, E = Flag.getNumOperandRegisters(); I != E; ++I)
10708 Regs.push_back(MRI.createVirtualRegister(RC));
10709
10710 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10711
10712 // Use the produced MatchedRegs object to
10713 MatchedRegs.getCopyToRegs(InOperandVal, DAG, DL, Info.Chain,
10714 &Info.Glue, &Call);
10716 OpInfo.getMatchedOperand(), DL, DAG,
10717 Info.AsmNodeOperands);
10718 break;
10719 }
10720
10721 assert(Flag.isMemKind() && "Unknown matching constraint!");
10722 assert(Flag.getNumOperandRegisters() == 1 &&
10723 "Unexpected number of operands");
10724
10725 // Add information to the INLINEASM node to know about this input.
10726 // See InlineAsm.h isUseOperandTiedToDef.
10727 Flag.clearMemConstraint();
10728 Flag.setMatchingOp(OpInfo.getMatchedOperand());
10729 Info.AsmNodeOperands.push_back(DAG.getTargetConstant(
10730 Flag, DL, TLI.getPointerTy(DAG.getDataLayout())));
10731 Info.AsmNodeOperands.push_back(Info.AsmNodeOperands[CurOp + 1]);
10732 break;
10733 }
10734
10735 // Treat indirect 'X' constraint as memory.
10736 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10737 OpInfo.isIndirect)
10738 OpInfo.ConstraintType = TargetLowering::C_Memory;
10739
10740 if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10741 OpInfo.ConstraintType == TargetLowering::C_Other) {
10742 std::vector<SDValue> Ops;
10743 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10744 Ops, DAG);
10745 if (Ops.empty()) {
10746 if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10747 if (isa<ConstantSDNode>(InOperandVal)) {
10748 Info.ErrorMsg << "value out of range for constraint '"
10749 << OpInfo.ConstraintCode << "'";
10750 return true;
10751 }
10752
10753 Info.ErrorMsg << "invalid operand for inline asm constraint '"
10754 << OpInfo.ConstraintCode << "'";
10755 return true;
10756 }
10757
10758 // Add information to the INLINEASM node to know about this input.
10759 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10760 Info.AsmNodeOperands.push_back(DAG.getTargetConstant(
10761 ResOpType, DL, TLI.getPointerTy(DAG.getDataLayout())));
10762 llvm::append_range(Info.AsmNodeOperands, Ops);
10763 break;
10764 }
10765
10766 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10767 assert((OpInfo.isIndirect ||
10768 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10769 "Operand must be indirect to be a mem!");
10770 assert(InOperandVal.getValueType() ==
10771 TLI.getPointerTy(DAG.getDataLayout()) &&
10772 "Memory operands expect pointer values");
10773
10774 const InlineAsm::ConstraintCode ConstraintID =
10775 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10777 "Failed to convert memory constraint code to constraint id.");
10778
10779 // Add information to the INLINEASM node to know about this input.
10781 ResOpType.setMemConstraint(ConstraintID);
10782 Info.AsmNodeOperands.push_back(
10783 DAG.getTargetConstant(ResOpType, DL, MVT::i32));
10784 Info.AsmNodeOperands.push_back(InOperandVal);
10785 break;
10786 }
10787
10788 if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10789 const InlineAsm::ConstraintCode ConstraintID =
10790 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10792 "Failed to convert memory constraint code to constraint id.");
10793
10795
10796 SDValue AsmOp = InOperandVal;
10797 if (TLI.supportsInlineAsmFuncOperands() && isFunction(InOperandVal)) {
10798 auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10799 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10800 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10801 InOperandVal.getValueType(),
10802 GA->getOffset());
10803 }
10804
10805 // Add information to the INLINEASM node to know about this input.
10806 ResOpType.setMemConstraint(ConstraintID);
10807
10808 Info.AsmNodeOperands.push_back(
10809 DAG.getTargetConstant(ResOpType, DL, MVT::i32));
10810 Info.AsmNodeOperands.push_back(AsmOp);
10811 break;
10812 }
10813
10814 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10815 OpInfo.ConstraintType != TargetLowering::C_Register) {
10816 Info.ErrorMsg << "unknown asm constraint '" << OpInfo.ConstraintCode
10817 << "'";
10818 return true;
10819 }
10820
10821 // TODO: Support this.
10822 if (OpInfo.isIndirect) {
10823 Info.ErrorMsg << "cannot handle indirect register inputs yet for "
10824 << "constraint '" << OpInfo.ConstraintCode << "'";
10825 return true;
10826 }
10827
10828 // Copy the input into the appropriate registers.
10829 if (OpInfo.AssignedRegs.Regs.empty()) {
10830 Info.ErrorMsg << "could not allocate input reg for constraint '"
10831 << OpInfo.ConstraintCode << "'";
10832 return true;
10833 }
10834
10835 if (DetectWriteToReservedRegister())
10836 return true;
10837
10838 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, DL, Info.Chain,
10839 &Info.Glue, &Call);
10840 OpInfo.AssignedRegs.AddInlineAsmOperands(
10841 InlineAsm::Kind::RegUse, false, 0, DL, DAG, Info.AsmNodeOperands);
10842 break;
10843 }
10844
10846 // Add the clobbered value to the operand list, so that the register
10847 // allocator is aware that the physreg got clobbered.
10848 if (!OpInfo.AssignedRegs.Regs.empty())
10849 OpInfo.AssignedRegs.AddInlineAsmOperands(
10850 InlineAsm::Kind::Clobber, false, 0, DL, DAG, Info.AsmNodeOperands);
10851 break;
10852 }
10853 }
10854
10855 return false;
10856}
10857
10858/// DetermineConstraints - Find the constraints to use for inline asm operands.
10859static bool
10860determineConstraints(ConstraintDecisionInfo &Info,
10861 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10862 const CallBase &Call, SelectionDAGBuilder &Builder,
10863 const TargetLowering &TLI, const TargetMachine &TM,
10864 SelectionDAG &DAG, const BasicBlock *EHPadBB) {
10865 const auto *IA = cast<InlineAsm>(Call.getCalledOperand());
10866 ExtraFlags ExtraInfo(Call);
10867
10868 // First pass: Construct operand info objects.
10869 Info.HasSideEffect = IA->hasSideEffects();
10870 if (constructOperandInfo(Info, TargetConstraints, Builder, TLI, ExtraInfo))
10871 return true;
10872
10873 // We won't need to flush pending loads if this asm doesn't touch
10874 // memory and is nonvolatile.
10875 Info.Chain = Info.HasSideEffect ? Builder.getRoot() : DAG.getRoot();
10876
10877 bool IsCallBr = isa<CallBrInst>(Call);
10878 bool EmitEHLabels = isa<InvokeInst>(Call);
10879 if (IsCallBr || EmitEHLabels)
10880 // If this is a callbr or invoke we need to flush pending exports since
10881 // inlineasm_br and invoke are terminators.
10882 // We need to do this before nodes are glued to the inlineasm_br node.
10883 Info.Chain = Builder.getControlRoot();
10884
10885 if (EmitEHLabels)
10886 Info.Chain = Builder.lowerStartEH(Info.Chain, EHPadBB, Info.BeginLabel);
10887
10888 // Second pass: Compute which constraint option to use.
10889 computeConstraintToUse(Info, Call, TargetConstraints, Builder, TLI, TM, DAG);
10890
10891 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10892 Info.AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
10893 Info.AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
10894 IA->getAsmString().data(), TLI.getProgramPointerTy(DAG.getDataLayout())));
10895
10896 // If we have a !srcloc metadata node associated with it, we want to attach
10897 // this to the ultimately generated inline asm machineinstr. To do this, we
10898 // pass in the third operand as this (potentially null) inline asm MDNode.
10899 const MDNode *SrcLoc = Call.getMetadata("srcloc");
10900 Info.AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
10901
10902 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10903 // bits as operand 3.
10904 Info.AsmNodeOperands.push_back(
10905 DAG.getTargetConstant(ExtraInfo.get(), Builder.getCurSDLoc(),
10906 TLI.getPointerTy(DAG.getDataLayout())));
10907
10908 // Third pass: Prepare DAG-level operands
10909 return prepareDAGLevelOperands(Info, Call, Builder, TLI, DAG);
10910}
10911
10912/// visitInlineAsm - Handle a call to an InlineAsm object.
10913void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
10914 const BasicBlock *EHPadBB) {
10915 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10917 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
10918
10919 assert((!isa<InvokeInst>(Call) || EHPadBB) &&
10920 "InvokeInst must have an EHPadBB");
10921
10922 ConstraintDecisionInfo Info;
10923 if (determineConstraints(Info, TargetConstraints, Call, *this, TLI, TM, DAG,
10924 EHPadBB))
10925 return emitInlineAsmError(Call, Info.ErrorMsg.str());
10926
10927 SDValue Glue = Info.Glue;
10928 SDValue Chain = Info.Chain;
10929
10930 // Finish up input operands. Set the input chain and add the flag last.
10931 Info.AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10932 if (Glue.getNode())
10933 Info.AsmNodeOperands.push_back(Glue);
10934
10935 bool IsCallBr = isa<CallBrInst>(Call);
10936 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10937 Chain =
10938 DAG.getNode(ISDOpc, getCurSDLoc(), DAG.getVTList(MVT::Other, MVT::Glue),
10939 Info.AsmNodeOperands);
10940 Glue = Chain.getValue(1);
10941
10942 // Do additional work to generate outputs.
10943
10944 SmallVector<EVT, 1> ResultVTs;
10945 SmallVector<SDValue, 1> ResultValues;
10946 SmallVector<SDValue, 8> OutChains;
10947
10948 llvm::Type *CallResultType = Call.getType();
10949 ArrayRef<Type *> ResultTypes;
10950 if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10951 ResultTypes = StructResult->elements();
10952 else if (!CallResultType->isVoidTy())
10953 ResultTypes = ArrayRef(CallResultType);
10954
10955 auto CurResultType = ResultTypes.begin();
10956 auto handleRegAssign = [&](SDValue V) {
10957 assert(CurResultType != ResultTypes.end() && "Unexpected value");
10958 assert((*CurResultType)->isSized() && "Unexpected unsized type");
10959 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10960 ++CurResultType;
10961 // If the type of the inline asm call site return value is different but has
10962 // same size as the type of the asm output bitcast it. One example of this
10963 // is for vectors with different width / number of elements. This can
10964 // happen for register classes that can contain multiple different value
10965 // types. The preg or vreg allocated may not have the same VT as was
10966 // expected.
10967 //
10968 // This can also happen for a return value that disagrees with the register
10969 // class it is put in, eg. a double in a general-purpose register on a
10970 // 32-bit machine.
10971 if (ResultVT != V.getValueType() &&
10972 ResultVT.getSizeInBits() == V.getValueSizeInBits())
10973 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10974 else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10975 V.getValueType().isInteger()) {
10976 // If a result value was tied to an input value, the computed result
10977 // may have a wider width than the expected result. Extract the
10978 // relevant portion.
10979 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10980 }
10981 assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10982 ResultVTs.push_back(ResultVT);
10983 ResultValues.push_back(V);
10984 };
10985
10986 // Deal with output operands.
10987 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10988 if (OpInfo.Type == InlineAsm::isOutput) {
10989 SDValue Val;
10990 // Skip trivial output operands.
10991 if (OpInfo.AssignedRegs.Regs.empty())
10992 continue;
10993
10994 switch (OpInfo.ConstraintType) {
10997 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10998 Chain, &Glue, &Call);
10999 break;
11002 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
11003 OpInfo, DAG);
11004 break;
11006 break; // Already handled.
11008 break; // Silence warning.
11010 assert(false && "Unexpected unknown constraint");
11011 }
11012
11013 // Indirect output manifest as stores. Record output chains.
11014 if (OpInfo.isIndirect) {
11015 const Value *Ptr = OpInfo.CallOperandVal;
11016 assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
11017 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
11018 MachinePointerInfo(Ptr));
11019 OutChains.push_back(Store);
11020 } else {
11021 // generate CopyFromRegs to associated registers.
11022 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
11023 if (Val.getOpcode() == ISD::MERGE_VALUES) {
11024 for (const SDValue &V : Val->op_values())
11025 handleRegAssign(V);
11026 } else
11027 handleRegAssign(Val);
11028 }
11029 }
11030 }
11031
11032 // Set results.
11033 if (!ResultValues.empty()) {
11034 assert(CurResultType == ResultTypes.end() &&
11035 "Mismatch in number of ResultTypes");
11036 assert(ResultValues.size() == ResultTypes.size() &&
11037 "Mismatch in number of output operands in asm result");
11038
11039 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11040 DAG.getVTList(ResultVTs), ResultValues);
11041 setValue(&Call, V);
11042 }
11043
11044 // Collect store chains.
11045 if (!OutChains.empty())
11046 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
11047
11048 if (const auto *II = dyn_cast<InvokeInst>(&Call))
11049 Chain = lowerEndEH(Chain, II, EHPadBB, Info.BeginLabel);
11050
11051 // Only Update Root if inline assembly has a memory effect.
11052 if (ResultValues.empty() || Info.HasSideEffect || !OutChains.empty() ||
11053 IsCallBr || isa<InvokeInst>(Call))
11054 DAG.setRoot(Chain);
11055}
11056
11057void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
11058 const Twine &Message) {
11059 LLVMContext &Ctx = *DAG.getContext();
11060 Ctx.diagnose(DiagnosticInfoInlineAsm(Call, Message));
11061
11062 // Make sure we leave the DAG in a valid state
11063 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11064 SmallVector<EVT, 1> ValueVTs;
11065 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
11066
11067 if (ValueVTs.empty())
11068 return;
11069
11071 for (const EVT &VT : ValueVTs)
11072 Ops.push_back(DAG.getUNDEF(VT));
11073
11074 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
11075}
11076
11077void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
11078 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
11079 MVT::Other, getRoot(),
11080 getValue(I.getArgOperand(0)),
11081 DAG.getSrcValue(I.getArgOperand(0))));
11082}
11083
11084void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
11085 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11086 const DataLayout &DL = DAG.getDataLayout();
11087 SDValue V = DAG.getVAArg(
11088 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
11089 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
11090 DL.getABITypeAlign(I.getType()).value());
11091 DAG.setRoot(V.getValue(1));
11092
11093 if (I.getType()->isPointerTy())
11094 V = DAG.getPtrExtOrTrunc(
11095 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
11096 setValue(&I, V);
11097}
11098
11099void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
11100 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
11101 MVT::Other, getRoot(),
11102 getValue(I.getArgOperand(0)),
11103 DAG.getSrcValue(I.getArgOperand(0))));
11104}
11105
11106void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
11107 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
11108 MVT::Other, getRoot(),
11109 getValue(I.getArgOperand(0)),
11110 getValue(I.getArgOperand(1)),
11111 DAG.getSrcValue(I.getArgOperand(0)),
11112 DAG.getSrcValue(I.getArgOperand(1))));
11113}
11114
11116 const Instruction &I,
11117 SDValue Op) {
11118 std::optional<ConstantRange> CR = getRange(I);
11119
11120 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
11121 return Op;
11122
11123 APInt Hi = CR->getUnsignedMax();
11124 unsigned Bits = std::max(Hi.getActiveBits(),
11125 static_cast<unsigned>(IntegerType::MIN_INT_BITS));
11126
11127 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
11128
11129 SDLoc SL = getCurSDLoc();
11130
11131 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
11132 DAG.getValueType(SmallVT));
11133 unsigned NumVals = Op.getNode()->getNumValues();
11134 if (NumVals == 1)
11135 return ZExt;
11136
11138
11139 Ops.push_back(ZExt);
11140 for (unsigned I = 1; I != NumVals; ++I)
11141 Ops.push_back(Op.getValue(I));
11142
11143 return DAG.getMergeValues(Ops, SL);
11144}
11145
11147 SelectionDAG &DAG, const Instruction &I, SDValue Op) {
11148 FPClassTest Classes = getNoFPClass(I);
11149 if (Classes == fcNone)
11150 return Op;
11151
11152 SDLoc SL = getCurSDLoc();
11153 SDValue TestConst = DAG.getTargetConstant(Classes, SDLoc(), MVT::i32);
11154
11155 if (Op.getOpcode() != ISD::MERGE_VALUES) {
11156 return DAG.getNode(ISD::AssertNoFPClass, SL, Op.getValueType(), Op,
11157 TestConst);
11158 }
11159
11160 SmallVector<SDValue, 8> Ops(Op.getNumOperands());
11161 for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
11162 SDValue MergeOp = Op.getOperand(I);
11163 Ops[I] = DAG.getNode(ISD::AssertNoFPClass, SL, MergeOp.getValueType(),
11164 MergeOp, TestConst);
11165 }
11166
11167 return DAG.getMergeValues(Ops, SL);
11168}
11169
11170/// Populate a CallLowerinInfo (into \p CLI) based on the properties of
11171/// the call being lowered.
11172///
11173/// This is a helper for lowering intrinsics that follow a target calling
11174/// convention or require stack pointer adjustment. Only a subset of the
11175/// intrinsic's operands need to participate in the calling convention.
11178 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
11179 AttributeSet RetAttrs, bool IsPatchPoint) {
11181 Args.reserve(NumArgs);
11182
11183 // Populate the argument list.
11184 // Attributes for args start at offset 1, after the return attribute.
11185 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
11186 ArgI != ArgE; ++ArgI) {
11187 const Value *V = Call->getOperand(ArgI);
11188
11189 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
11190
11191 TargetLowering::ArgListEntry Entry(getValue(V), V->getType());
11192 Entry.setAttributes(Call, ArgI);
11193 Args.push_back(Entry);
11194 }
11195
11197 .setChain(getRoot())
11198 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
11199 RetAttrs)
11200 .setDiscardResult(Call->use_empty())
11201 .setIsPatchPoint(IsPatchPoint)
11203 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
11204}
11205
11206/// Add a stack map intrinsic call's live variable operands to a stackmap
11207/// or patchpoint target node's operand list.
11208///
11209/// Constants are converted to TargetConstants purely as an optimization to
11210/// avoid constant materialization and register allocation.
11211///
11212/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
11213/// generate addess computation nodes, and so FinalizeISel can convert the
11214/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
11215/// address materialization and register allocation, but may also be required
11216/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
11217/// alloca in the entry block, then the runtime may assume that the alloca's
11218/// StackMap location can be read immediately after compilation and that the
11219/// location is valid at any point during execution (this is similar to the
11220/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
11221/// only available in a register, then the runtime would need to trap when
11222/// execution reaches the StackMap in order to read the alloca's location.
11223static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
11225 SelectionDAGBuilder &Builder) {
11226 SelectionDAG &DAG = Builder.DAG;
11227 for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
11228 SDValue Op = Builder.getValue(Call.getArgOperand(I));
11229
11230 // Things on the stack are pointer-typed, meaning that they are already
11231 // legal and can be emitted directly to target nodes.
11233 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
11234 } else {
11235 // Otherwise emit a target independent node to be legalised.
11236 Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
11237 }
11238 }
11239}
11240
11241/// Lower llvm.experimental.stackmap.
11242void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
11243 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
11244 // [live variables...])
11245
11246 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
11247
11248 SDValue Chain, InGlue, Callee;
11250
11251 SDLoc DL = getCurSDLoc();
11253
11254 // The stackmap intrinsic only records the live variables (the arguments
11255 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
11256 // intrinsic, this won't be lowered to a function call. This means we don't
11257 // have to worry about calling conventions and target specific lowering code.
11258 // Instead we perform the call lowering right here.
11259 //
11260 // chain, flag = CALLSEQ_START(chain, 0, 0)
11261 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
11262 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
11263 //
11264 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
11265 InGlue = Chain.getValue(1);
11266
11267 // Add the STACKMAP operands, starting with DAG house-keeping.
11268 Ops.push_back(Chain);
11269 Ops.push_back(InGlue);
11270
11271 // Add the <id>, <numShadowBytes> operands.
11272 //
11273 // These do not require legalisation, and can be emitted directly to target
11274 // constant nodes.
11275 SDValue ID = getValue(CI.getArgOperand(0));
11276 assert(ID.getValueType() == MVT::i64);
11277 SDValue IDConst =
11278 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
11279 Ops.push_back(IDConst);
11280
11281 SDValue Shad = getValue(CI.getArgOperand(1));
11282 assert(Shad.getValueType() == MVT::i32);
11283 SDValue ShadConst =
11284 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
11285 Ops.push_back(ShadConst);
11286
11287 // Add the live variables.
11288 addStackMapLiveVars(CI, 2, DL, Ops, *this);
11289
11290 // Create the STACKMAP node.
11291 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11292 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
11293 InGlue = Chain.getValue(1);
11294
11295 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
11296
11297 // Stackmaps don't generate values, so nothing goes into the NodeMap.
11298
11299 // Set the root to the target-lowered call chain.
11300 DAG.setRoot(Chain);
11301
11302 // Inform the Frame Information that we have a stackmap in this function.
11303 FuncInfo.MF->getFrameInfo().setHasStackMap();
11304}
11305
11306/// Lower llvm.experimental.patchpoint directly to its target opcode.
11307void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
11308 const BasicBlock *EHPadBB) {
11309 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
11310 // i32 <numBytes>,
11311 // i8* <target>,
11312 // i32 <numArgs>,
11313 // [Args...],
11314 // [live variables...])
11315
11317 bool IsAnyRegCC = CC == CallingConv::AnyReg;
11318 bool HasDef = !CB.getType()->isVoidTy();
11319 SDLoc dl = getCurSDLoc();
11321
11322 // Handle immediate and symbolic callees.
11323 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
11324 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
11325 /*isTarget=*/true);
11326 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
11327 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
11328 SDLoc(SymbolicCallee),
11329 SymbolicCallee->getValueType(0));
11330
11331 // Get the real number of arguments participating in the call <numArgs>
11332 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
11333 unsigned NumArgs = NArgVal->getAsZExtVal();
11334
11335 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
11336 // Intrinsics include all meta-operands up to but not including CC.
11337 unsigned NumMetaOpers = PatchPointOpers::CCPos;
11338 assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
11339 "Not enough arguments provided to the patchpoint intrinsic");
11340
11341 // For AnyRegCC the arguments are lowered later on manually.
11342 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
11343 Type *ReturnTy =
11344 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
11345
11346 TargetLowering::CallLoweringInfo CLI(DAG);
11347 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
11348 ReturnTy, CB.getAttributes().getRetAttrs(), true);
11349 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
11350
11351 SDNode *CallEnd = Result.second.getNode();
11352 if (CallEnd->getOpcode() == ISD::EH_LABEL)
11353 CallEnd = CallEnd->getOperand(0).getNode();
11354 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
11355 CallEnd = CallEnd->getOperand(0).getNode();
11356
11357 /// Get a call instruction from the call sequence chain.
11358 /// Tail calls are not allowed.
11359 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
11360 "Expected a callseq node.");
11361 SDNode *Call = CallEnd->getOperand(0).getNode();
11362 bool HasGlue = Call->getGluedNode();
11363
11364 // Replace the target specific call node with the patchable intrinsic.
11366
11367 // Push the chain.
11368 Ops.push_back(*(Call->op_begin()));
11369
11370 // Optionally, push the glue (if any).
11371 if (HasGlue)
11372 Ops.push_back(*(Call->op_end() - 1));
11373
11374 // Push the register mask info.
11375 if (HasGlue)
11376 Ops.push_back(*(Call->op_end() - 2));
11377 else
11378 Ops.push_back(*(Call->op_end() - 1));
11379
11380 // Add the <id> and <numBytes> constants.
11381 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
11382 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
11383 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
11384 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
11385
11386 // Add the callee.
11387 Ops.push_back(Callee);
11388
11389 // Adjust <numArgs> to account for any arguments that have been passed on the
11390 // stack instead.
11391 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
11392 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
11393 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
11394 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
11395
11396 // Add the calling convention
11397 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
11398
11399 // Add the arguments we omitted previously. The register allocator should
11400 // place these in any free register.
11401 if (IsAnyRegCC)
11402 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
11403 Ops.push_back(getValue(CB.getArgOperand(i)));
11404
11405 // Push the arguments from the call instruction.
11406 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
11407 Ops.append(Call->op_begin() + 2, e);
11408
11409 // Push live variables for the stack map.
11410 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
11411
11412 SDVTList NodeTys;
11413 if (IsAnyRegCC && HasDef) {
11414 // Create the return types based on the intrinsic definition
11415 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11416 SmallVector<EVT, 3> ValueVTs;
11417 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
11418 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
11419
11420 // There is always a chain and a glue type at the end
11421 ValueVTs.push_back(MVT::Other);
11422 ValueVTs.push_back(MVT::Glue);
11423 NodeTys = DAG.getVTList(ValueVTs);
11424 } else
11425 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11426
11427 // Replace the target specific call node with a PATCHPOINT node.
11428 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
11429
11430 // Update the NodeMap.
11431 if (HasDef) {
11432 if (IsAnyRegCC)
11433 setValue(&CB, SDValue(PPV.getNode(), 0));
11434 else
11435 setValue(&CB, Result.first);
11436 }
11437
11438 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
11439 // call sequence. Furthermore the location of the chain and glue can change
11440 // when the AnyReg calling convention is used and the intrinsic returns a
11441 // value.
11442 if (IsAnyRegCC && HasDef) {
11443 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
11444 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
11445 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11446 } else
11447 DAG.ReplaceAllUsesWith(Call, PPV.getNode());
11448 DAG.DeleteNode(Call);
11449
11450 // Inform the Frame Information that we have a patchpoint in this function.
11451 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
11452}
11453
11454void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
11455 unsigned Intrinsic) {
11456 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11457 SDValue Op1 = getValue(I.getArgOperand(0));
11458 SDValue Op2;
11459 if (I.arg_size() > 1)
11460 Op2 = getValue(I.getArgOperand(1));
11461 SDLoc dl = getCurSDLoc();
11462 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11463 SDValue Res;
11464 SDNodeFlags SDFlags;
11465 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
11466 SDFlags.copyFMF(*FPMO);
11467
11468 switch (Intrinsic) {
11469 case Intrinsic::vector_reduce_fadd:
11470 if (SDFlags.hasAllowReassociation())
11471 Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
11472 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
11473 SDFlags);
11474 else
11475 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
11476 break;
11477 case Intrinsic::vector_reduce_fmul:
11478 if (SDFlags.hasAllowReassociation())
11479 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
11480 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
11481 SDFlags);
11482 else
11483 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
11484 break;
11485 case Intrinsic::vector_reduce_add:
11486 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
11487 break;
11488 case Intrinsic::vector_reduce_mul:
11489 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
11490 break;
11491 case Intrinsic::vector_reduce_and:
11492 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
11493 break;
11494 case Intrinsic::vector_reduce_or:
11495 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
11496 break;
11497 case Intrinsic::vector_reduce_xor:
11498 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
11499 break;
11500 case Intrinsic::vector_reduce_smax:
11501 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
11502 break;
11503 case Intrinsic::vector_reduce_smin:
11504 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
11505 break;
11506 case Intrinsic::vector_reduce_umax:
11507 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
11508 break;
11509 case Intrinsic::vector_reduce_umin:
11510 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
11511 break;
11512 case Intrinsic::vector_reduce_fmax:
11513 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
11514 break;
11515 case Intrinsic::vector_reduce_fmin:
11516 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
11517 break;
11518 case Intrinsic::vector_reduce_fmaximum:
11519 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
11520 break;
11521 case Intrinsic::vector_reduce_fminimum:
11522 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
11523 break;
11524 case Intrinsic::vector_reduce_fmaximumnum:
11525 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUMNUM, dl, VT, Op1, SDFlags);
11526 break;
11527 case Intrinsic::vector_reduce_fminimumnum:
11528 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUMNUM, dl, VT, Op1, SDFlags);
11529 break;
11530 default:
11531 llvm_unreachable("Unhandled vector reduce intrinsic");
11532 }
11533 setValue(&I, Res);
11534}
11535
11536/// Returns an AttributeList representing the attributes applied to the return
11537/// value of the given call.
11540 if (CLI.RetSExt)
11541 Attrs.push_back(Attribute::SExt);
11542 if (CLI.RetZExt)
11543 Attrs.push_back(Attribute::ZExt);
11544 if (CLI.IsInReg)
11545 Attrs.push_back(Attribute::InReg);
11546
11547 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
11548 Attrs);
11549}
11550
11551/// TargetLowering::LowerCallTo - This is the default LowerCallTo
11552/// implementation, which just calls LowerCall.
11553/// FIXME: When all targets are
11554/// migrated to using LowerCall, this hook should be integrated into SDISel.
11555std::pair<SDValue, SDValue>
11557 LLVMContext &Context = CLI.RetTy->getContext();
11558
11559 // Handle the incoming return values from the call.
11560 CLI.Ins.clear();
11561 SmallVector<Type *, 4> RetOrigTys;
11563 auto &DL = CLI.DAG.getDataLayout();
11564 ComputeValueTypes(DL, CLI.OrigRetTy, RetOrigTys, &Offsets);
11565
11566 SmallVector<EVT, 4> RetVTs;
11567 if (CLI.RetTy != CLI.OrigRetTy) {
11568 assert(RetOrigTys.size() == 1 &&
11569 "Only supported for non-aggregate returns");
11570 RetVTs.push_back(getValueType(DL, CLI.RetTy));
11571 } else {
11572 for (Type *Ty : RetOrigTys)
11573 RetVTs.push_back(getValueType(DL, Ty));
11574 }
11575
11576 if (CLI.IsPostTypeLegalization) {
11577 // If we are lowering a libcall after legalization, split the return type.
11578 SmallVector<Type *, 4> OldRetOrigTys;
11579 SmallVector<EVT, 4> OldRetVTs;
11580 SmallVector<TypeSize, 4> OldOffsets;
11581 RetOrigTys.swap(OldRetOrigTys);
11582 RetVTs.swap(OldRetVTs);
11583 Offsets.swap(OldOffsets);
11584
11585 for (size_t i = 0, e = OldRetVTs.size(); i != e; ++i) {
11586 EVT RetVT = OldRetVTs[i];
11587 uint64_t Offset = OldOffsets[i];
11588 MVT RegisterVT = getRegisterType(Context, RetVT);
11589 unsigned NumRegs = getNumRegisters(Context, RetVT);
11590 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
11591 RetOrigTys.append(NumRegs, OldRetOrigTys[i]);
11592 RetVTs.append(NumRegs, RegisterVT);
11593 for (unsigned j = 0; j != NumRegs; ++j)
11594 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
11595 }
11596 }
11597
11599 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
11600
11601 bool CanLowerReturn =
11603 CLI.IsVarArg, Outs, Context, CLI.RetTy);
11604
11605 SDValue DemoteStackSlot;
11606 int DemoteStackIdx = -100;
11607 if (!CanLowerReturn) {
11608 // FIXME: equivalent assert?
11609 // assert(!CS.hasInAllocaArgument() &&
11610 // "sret demotion is incompatible with inalloca");
11611 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
11612 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
11614 DemoteStackIdx =
11615 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
11616 Type *StackSlotPtrType = PointerType::get(Context, DL.getAllocaAddrSpace());
11617
11618 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
11619 ArgListEntry Entry(DemoteStackSlot, StackSlotPtrType);
11620 Entry.IsSRet = true;
11621 Entry.Alignment = Alignment;
11622 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
11623 CLI.NumFixedArgs += 1;
11624 CLI.getArgs()[0].IndirectType = CLI.RetTy;
11625 CLI.RetTy = CLI.OrigRetTy = Type::getVoidTy(Context);
11626
11627 // sret demotion isn't compatible with tail-calls, since the sret argument
11628 // points into the callers stack frame.
11629 CLI.IsTailCall = false;
11630 } else {
11631 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11632 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
11633 for (unsigned I = 0, E = RetVTs.size(); I != E; ++I) {
11634 ISD::ArgFlagsTy Flags;
11635 if (NeedsRegBlock) {
11636 Flags.setInConsecutiveRegs();
11637 if (I == RetVTs.size() - 1)
11638 Flags.setInConsecutiveRegsLast();
11639 }
11640 EVT VT = RetVTs[I];
11641 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11642 unsigned NumRegs =
11643 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11644 for (unsigned i = 0; i != NumRegs; ++i) {
11645 ISD::InputArg Ret(Flags, RegisterVT, VT, RetOrigTys[I],
11647 if (CLI.RetTy->isPointerTy()) {
11648 Ret.Flags.setPointer();
11650 cast<PointerType>(CLI.RetTy)->getAddressSpace());
11651 }
11652 if (CLI.RetSExt)
11653 Ret.Flags.setSExt();
11654 if (CLI.RetZExt)
11655 Ret.Flags.setZExt();
11656 if (CLI.IsInReg)
11657 Ret.Flags.setInReg();
11658 CLI.Ins.push_back(Ret);
11659 }
11660 }
11661 }
11662
11663 // We push in swifterror return as the last element of CLI.Ins.
11664 ArgListTy &Args = CLI.getArgs();
11665 if (supportSwiftError()) {
11666 for (const ArgListEntry &Arg : Args) {
11667 if (Arg.IsSwiftError) {
11668 ISD::ArgFlagsTy Flags;
11669 Flags.setSwiftError();
11671 PointerType::getUnqual(Context),
11672 /*Used=*/true, ISD::InputArg::NoArgIndex, 0);
11673 CLI.Ins.push_back(Ret);
11674 }
11675 }
11676 }
11677
11678 // Handle all of the outgoing arguments.
11679 CLI.Outs.clear();
11680 CLI.OutVals.clear();
11681 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11682 SmallVector<Type *, 4> OrigArgTys;
11683 ComputeValueTypes(DL, Args[i].OrigTy, OrigArgTys);
11684 // FIXME: Split arguments if CLI.IsPostTypeLegalization
11685 Type *FinalType = Args[i].Ty;
11686 if (Args[i].IsByVal)
11687 FinalType = Args[i].IndirectType;
11688 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11689 FinalType, CLI.CallConv, CLI.IsVarArg, DL);
11690 for (unsigned Value = 0, NumValues = OrigArgTys.size(); Value != NumValues;
11691 ++Value) {
11692 Type *OrigArgTy = OrigArgTys[Value];
11693 Type *ArgTy = OrigArgTy;
11694 if (Args[i].Ty != Args[i].OrigTy) {
11695 assert(Value == 0 && "Only supported for non-aggregate arguments");
11696 ArgTy = Args[i].Ty;
11697 }
11698
11699 EVT VT = getValueType(DL, ArgTy);
11700 SDValue Op = SDValue(Args[i].Node.getNode(),
11701 Args[i].Node.getResNo() + Value);
11702 ISD::ArgFlagsTy Flags;
11703
11704 // Certain targets (such as MIPS), may have a different ABI alignment
11705 // for a type depending on the context. Give the target a chance to
11706 // specify the alignment it wants.
11707 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11708 Flags.setOrigAlign(OriginalAlignment);
11709
11710 if (i >= CLI.NumFixedArgs)
11711 Flags.setVarArg();
11712 if (ArgTy->isPointerTy()) {
11713 Flags.setPointer();
11714 Flags.setPointerAddrSpace(cast<PointerType>(ArgTy)->getAddressSpace());
11715 }
11716 if (Args[i].IsZExt)
11717 Flags.setZExt();
11718 if (Args[i].IsSExt)
11719 Flags.setSExt();
11720 if (Args[i].IsNoExt)
11721 Flags.setNoExt();
11722 if (Args[i].IsInReg) {
11723 // If we are using vectorcall calling convention, a structure that is
11724 // passed InReg - is surely an HVA
11726 isa<StructType>(FinalType)) {
11727 // The first value of a structure is marked
11728 if (0 == Value)
11729 Flags.setHvaStart();
11730 Flags.setHva();
11731 }
11732 // Set InReg Flag
11733 Flags.setInReg();
11734 }
11735 if (Args[i].IsSRet)
11736 Flags.setSRet();
11737 if (Args[i].IsSwiftSelf)
11738 Flags.setSwiftSelf();
11739 if (Args[i].IsSwiftAsync)
11740 Flags.setSwiftAsync();
11741 if (Args[i].IsSwiftError)
11742 Flags.setSwiftError();
11743 if (Args[i].IsCFGuardTarget)
11744 Flags.setCFGuardTarget();
11745 if (Args[i].IsByVal)
11746 Flags.setByVal();
11747 if (Args[i].IsByRef)
11748 Flags.setByRef();
11749 if (Args[i].IsPreallocated) {
11750 Flags.setPreallocated();
11751 // Set the byval flag for CCAssignFn callbacks that don't know about
11752 // preallocated. This way we can know how many bytes we should've
11753 // allocated and how many bytes a callee cleanup function will pop. If
11754 // we port preallocated to more targets, we'll have to add custom
11755 // preallocated handling in the various CC lowering callbacks.
11756 Flags.setByVal();
11757 }
11758 if (Args[i].IsInAlloca) {
11759 Flags.setInAlloca();
11760 // Set the byval flag for CCAssignFn callbacks that don't know about
11761 // inalloca. This way we can know how many bytes we should've allocated
11762 // and how many bytes a callee cleanup function will pop. If we port
11763 // inalloca to more targets, we'll have to add custom inalloca handling
11764 // in the various CC lowering callbacks.
11765 Flags.setByVal();
11766 }
11767 Align MemAlign;
11768 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11769 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11770 Flags.setByValSize(FrameSize);
11771
11772 // info is not there but there are cases it cannot get right.
11773 if (auto MA = Args[i].Alignment)
11774 MemAlign = *MA;
11775 else
11776 MemAlign = getByValTypeAlignment(Args[i].IndirectType, DL);
11777 } else if (auto MA = Args[i].Alignment) {
11778 MemAlign = *MA;
11779 } else {
11780 MemAlign = OriginalAlignment;
11781 }
11782 Flags.setMemAlign(MemAlign);
11783 if (Args[i].IsNest)
11784 Flags.setNest();
11785 if (NeedsRegBlock)
11786 Flags.setInConsecutiveRegs();
11787
11788 MVT PartVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11789 unsigned NumParts =
11790 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11791 SmallVector<SDValue, 4> Parts(NumParts);
11793
11794 if (Args[i].IsSExt)
11796 else if (Args[i].IsZExt)
11798
11799 // Conservatively only handle 'returned' on non-vectors that can be lowered,
11800 // for now.
11801 if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11803 assert((CLI.RetTy == Args[i].Ty ||
11804 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11806 Args[i].Ty->getPointerAddressSpace())) &&
11807 RetVTs.size() == NumValues && "unexpected use of 'returned'");
11808 // Before passing 'returned' to the target lowering code, ensure that
11809 // either the register MVT and the actual EVT are the same size or that
11810 // the return value and argument are extended in the same way; in these
11811 // cases it's safe to pass the argument register value unchanged as the
11812 // return register value (although it's at the target's option whether
11813 // to do so)
11814 // TODO: allow code generation to take advantage of partially preserved
11815 // registers rather than clobbering the entire register when the
11816 // parameter extension method is not compatible with the return
11817 // extension method
11818 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11819 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11820 CLI.RetZExt == Args[i].IsZExt))
11821 Flags.setReturned();
11822 }
11823
11824 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11825 CLI.CallConv, ExtendKind);
11826
11827 for (unsigned j = 0; j != NumParts; ++j) {
11828 // if it isn't first piece, alignment must be 1
11829 // For scalable vectors the scalable part is currently handled
11830 // by individual targets, so we just use the known minimum size here.
11831 ISD::OutputArg MyFlags(
11832 Flags, Parts[j].getValueType().getSimpleVT(), VT, OrigArgTy, i,
11833 j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11834 if (NumParts > 1 && j == 0)
11835 MyFlags.Flags.setSplit();
11836 else if (j != 0) {
11837 MyFlags.Flags.setOrigAlign(Align(1));
11838 if (j == NumParts - 1)
11839 MyFlags.Flags.setSplitEnd();
11840 }
11841
11842 CLI.Outs.push_back(MyFlags);
11843 CLI.OutVals.push_back(Parts[j]);
11844 }
11845
11846 if (NeedsRegBlock && Value == NumValues - 1)
11847 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11848 }
11849 }
11850
11852 CLI.Chain = LowerCall(CLI, InVals);
11853
11854 // Update CLI.InVals to use outside of this function.
11855 CLI.InVals = InVals;
11856
11857 // Verify that the target's LowerCall behaved as expected.
11858 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11859 "LowerCall didn't return a valid chain!");
11860 assert((!CLI.IsTailCall || InVals.empty()) &&
11861 "LowerCall emitted a return value for a tail call!");
11862 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11863 "LowerCall didn't emit the correct number of values!");
11864
11865 // For a tail call, the return value is merely live-out and there aren't
11866 // any nodes in the DAG representing it. Return a special value to
11867 // indicate that a tail call has been emitted and no more Instructions
11868 // should be processed in the current block.
11869 if (CLI.IsTailCall) {
11870 CLI.DAG.setRoot(CLI.Chain);
11871 return std::make_pair(SDValue(), SDValue());
11872 }
11873
11874#ifndef NDEBUG
11875 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11876 assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11877 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11878 "LowerCall emitted a value with the wrong type!");
11879 }
11880#endif
11881
11882 SmallVector<SDValue, 4> ReturnValues;
11883 if (!CanLowerReturn) {
11884 // The instruction result is the result of loading from the
11885 // hidden sret parameter.
11886 MVT PtrVT = getPointerTy(DL, DL.getAllocaAddrSpace());
11887
11888 unsigned NumValues = RetVTs.size();
11889 ReturnValues.resize(NumValues);
11890 SmallVector<SDValue, 4> Chains(NumValues);
11891
11892 // An aggregate return value cannot wrap around the address space, so
11893 // offsets to its parts don't wrap either.
11895 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11896 for (unsigned i = 0; i < NumValues; ++i) {
11898 DemoteStackSlot, CLI.DAG.getConstant(Offsets[i], CLI.DL, PtrVT),
11900 SDValue L = CLI.DAG.getLoad(
11901 RetVTs[i], CLI.DL, CLI.Chain, Add,
11903 DemoteStackIdx, Offsets[i]),
11904 HiddenSRetAlign);
11905 ReturnValues[i] = L;
11906 Chains[i] = L.getValue(1);
11907 }
11908
11909 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11910 } else {
11911 // Collect the legal value parts into potentially illegal values
11912 // that correspond to the original function's return values.
11913 std::optional<ISD::NodeType> AssertOp;
11914 if (CLI.RetSExt)
11915 AssertOp = ISD::AssertSext;
11916 else if (CLI.RetZExt)
11917 AssertOp = ISD::AssertZext;
11918 unsigned CurReg = 0;
11919 for (EVT VT : RetVTs) {
11920 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11921 unsigned NumRegs =
11922 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11923
11924 ReturnValues.push_back(getCopyFromParts(
11925 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11926 CLI.Chain, CLI.CallConv, AssertOp));
11927 CurReg += NumRegs;
11928 }
11929
11930 // For a function returning void, there is no return value. We can't create
11931 // such a node, so we just return a null return value in that case. In
11932 // that case, nothing will actually look at the value.
11933 if (ReturnValues.empty())
11934 return std::make_pair(SDValue(), CLI.Chain);
11935 }
11936
11937 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11938 CLI.DAG.getVTList(RetVTs), ReturnValues);
11939 return std::make_pair(Res, CLI.Chain);
11940}
11941
11942/// Places new result values for the node in Results (their number
11943/// and types must exactly match those of the original return values of
11944/// the node), or leaves Results empty, which indicates that the node is not
11945/// to be custom lowered after all.
11948 SelectionDAG &DAG) const {
11949 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11950
11951 if (!Res.getNode())
11952 return;
11953
11954 // If the original node has one result, take the return value from
11955 // LowerOperation as is. It might not be result number 0.
11956 if (N->getNumValues() == 1) {
11957 Results.push_back(Res);
11958 return;
11959 }
11960
11961 // If the original node has multiple results, then the return node should
11962 // have the same number of results.
11963 assert((N->getNumValues() == Res->getNumValues()) &&
11964 "Lowering returned the wrong number of results!");
11965
11966 // Places new result values base on N result number.
11967 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11968 Results.push_back(Res.getValue(I));
11969}
11970
11972 llvm_unreachable("LowerOperation not implemented for this target!");
11973}
11974
11976 Register Reg,
11977 ISD::NodeType ExtendType) {
11979 assert((Op.getOpcode() != ISD::CopyFromReg ||
11980 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11981 "Copy from a reg to the same reg!");
11982 assert(!Reg.isPhysical() && "Is a physreg");
11983
11984 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11985 // If this is an InlineAsm we have to match the registers required, not the
11986 // notional registers required by the type.
11987
11988 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11989 std::nullopt); // This is not an ABI copy.
11990 SDValue Chain = DAG.getEntryNode();
11991
11992 if (ExtendType == ISD::ANY_EXTEND) {
11993 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11994 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11995 ExtendType = PreferredExtendIt->second;
11996 }
11997 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11998 PendingExports.push_back(Chain);
11999}
12000
12002
12003/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
12004/// entry block, return true. This includes arguments used by switches, since
12005/// the switch may expand into multiple basic blocks.
12006static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
12007 // With FastISel active, we may be splitting blocks, so force creation
12008 // of virtual registers for all non-dead arguments.
12009 if (FastISel)
12010 return A->use_empty();
12011
12012 const BasicBlock &Entry = A->getParent()->front();
12013 for (const User *U : A->users())
12014 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
12015 return false; // Use not in entry block.
12016
12017 return true;
12018}
12019
12021 DenseMap<const Argument *,
12022 std::pair<const AllocaInst *, const StoreInst *>>;
12023
12024/// Scan the entry block of the function in FuncInfo for arguments that look
12025/// like copies into a local alloca. Record any copied arguments in
12026/// ArgCopyElisionCandidates.
12027static void
12029 FunctionLoweringInfo *FuncInfo,
12030 ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
12031 // Record the state of every static alloca used in the entry block. Argument
12032 // allocas are all used in the entry block, so we need approximately as many
12033 // entries as we have arguments.
12034 enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
12036 unsigned NumArgs = FuncInfo->Fn->arg_size();
12037 StaticAllocas.reserve(NumArgs * 2);
12038
12039 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
12040 if (!V)
12041 return nullptr;
12042 V = V->stripPointerCasts();
12043 const auto *AI = dyn_cast<AllocaInst>(V);
12044 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
12045 return nullptr;
12046 auto Iter = StaticAllocas.insert({AI, Unknown});
12047 return &Iter.first->second;
12048 };
12049
12050 // Look for stores of arguments to static allocas. Look through bitcasts and
12051 // GEPs to handle type coercions, as long as the alloca is fully initialized
12052 // by the store. Any non-store use of an alloca escapes it and any subsequent
12053 // unanalyzed store might write it.
12054 // FIXME: Handle structs initialized with multiple stores.
12055 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
12056 // Look for stores, and handle non-store uses conservatively.
12057 const auto *SI = dyn_cast<StoreInst>(&I);
12058 if (!SI) {
12059 // We will look through cast uses, so ignore them completely.
12060 if (I.isCast())
12061 continue;
12062 // Ignore pseudo op intrinsics, they don't escape or store to allocas.
12064 continue;
12065 // This is an unknown instruction. Assume it escapes or writes to all
12066 // static alloca operands.
12067 for (const Use &U : I.operands()) {
12068 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
12069 *Info = StaticAllocaInfo::Clobbered;
12070 }
12071 continue;
12072 }
12073
12074 // If the stored value is a static alloca, mark it as escaped.
12075 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
12076 *Info = StaticAllocaInfo::Clobbered;
12077
12078 // Check if the destination is a static alloca.
12079 const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
12080 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
12081 if (!Info)
12082 continue;
12083 const AllocaInst *AI = cast<AllocaInst>(Dst);
12084
12085 // Skip allocas that have been initialized or clobbered.
12086 if (*Info != StaticAllocaInfo::Unknown)
12087 continue;
12088
12089 // Check if the stored value is an argument, and that this store fully
12090 // initializes the alloca.
12091 // If the argument type has padding bits we can't directly forward a pointer
12092 // as the upper bits may contain garbage.
12093 // Don't elide copies from the same argument twice.
12094 const Value *Val = SI->getValueOperand()->stripPointerCasts();
12095 const auto *Arg = dyn_cast<Argument>(Val);
12096 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL);
12097 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
12098 Arg->getType()->isEmptyTy() || !AllocaSize ||
12099 DL.getTypeStoreSize(Arg->getType()) != *AllocaSize ||
12100 !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
12101 ArgCopyElisionCandidates.count(Arg)) {
12102 *Info = StaticAllocaInfo::Clobbered;
12103 continue;
12104 }
12105
12106 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
12107 << '\n');
12108
12109 // Mark this alloca and store for argument copy elision.
12110 *Info = StaticAllocaInfo::Elidable;
12111 ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
12112
12113 // Stop scanning if we've seen all arguments. This will happen early in -O0
12114 // builds, which is useful, because -O0 builds have large entry blocks and
12115 // many allocas.
12116 if (ArgCopyElisionCandidates.size() == NumArgs)
12117 break;
12118 }
12119}
12120
12121/// Try to elide argument copies from memory into a local alloca. Succeeds if
12122/// ArgVal is a load from a suitable fixed stack object.
12125 DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
12126 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
12127 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
12128 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
12129 // Check if this is a load from a fixed stack object.
12130 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
12131 if (!LNode)
12132 return;
12133 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
12134 if (!FINode)
12135 return;
12136
12137 // Check that the fixed stack object is the right size and alignment.
12138 // Look at the alignment that the user wrote on the alloca instead of looking
12139 // at the stack object.
12140 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
12141 assert(ArgCopyIter != ArgCopyElisionCandidates.end());
12142 const AllocaInst *AI = ArgCopyIter->second.first;
12143 int FixedIndex = FINode->getIndex();
12144 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
12145 int OldIndex = AllocaIndex;
12146 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
12147 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
12148 LLVM_DEBUG(
12149 dbgs() << " argument copy elision failed due to bad fixed stack "
12150 "object size\n");
12151 return;
12152 }
12153 Align RequiredAlignment = AI->getAlign();
12154 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
12155 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
12156 "greater than stack argument alignment ("
12157 << DebugStr(RequiredAlignment) << " vs "
12158 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
12159 return;
12160 }
12161
12162 // Perform the elision. Delete the old stack object and replace its only use
12163 // in the variable info map. Mark the stack object as mutable and aliased.
12164 LLVM_DEBUG({
12165 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
12166 << " Replacing frame index " << OldIndex << " with " << FixedIndex
12167 << '\n';
12168 });
12169 MFI.RemoveStackObject(OldIndex);
12170 MFI.setIsImmutableObjectIndex(FixedIndex, false);
12171 MFI.setIsAliasedObjectIndex(FixedIndex, true);
12172 AllocaIndex = FixedIndex;
12173 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
12174 for (SDValue ArgVal : ArgVals)
12175 Chains.push_back(ArgVal.getValue(1));
12176
12177 // Avoid emitting code for the store implementing the copy.
12178 const StoreInst *SI = ArgCopyIter->second.second;
12179 ElidedArgCopyInstrs.insert(SI);
12180
12181 // Check for uses of the argument again so that we can avoid exporting ArgVal
12182 // if it is't used by anything other than the store.
12183 for (const Value *U : Arg.users()) {
12184 if (U != SI) {
12185 ArgHasUses = true;
12186 break;
12187 }
12188 }
12189}
12190
12191void SelectionDAGISel::LowerArguments(const Function &F, bool FastISel) {
12192 SelectionDAG &DAG = SDB->DAG;
12193 SDLoc dl = SDB->getCurSDLoc();
12194 const DataLayout &DL = DAG.getDataLayout();
12196
12197 // In Naked functions we aren't going to save any registers.
12198 if (F.hasFnAttribute(Attribute::Naked))
12199 return;
12200
12201 if (!FuncInfo->CanLowerReturn) {
12202 // Put in an sret pointer parameter before all the other parameters.
12203 MVT ValueVT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
12204
12205 ISD::ArgFlagsTy Flags;
12206 Flags.setSRet();
12207 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVT);
12208 ISD::InputArg RetArg(Flags, RegisterVT, ValueVT, F.getReturnType(), true,
12210 Ins.push_back(RetArg);
12211 }
12212
12213 // Look for stores of arguments to static allocas. Mark such arguments with a
12214 // flag to ask the target to give us the memory location of that argument if
12215 // available.
12216 ArgCopyElisionMapTy ArgCopyElisionCandidates;
12218 ArgCopyElisionCandidates);
12219
12220 // Set up the incoming argument description vector.
12221 for (const Argument &Arg : F.args()) {
12222 unsigned ArgNo = Arg.getArgNo();
12224 ComputeValueTypes(DAG.getDataLayout(), Arg.getType(), Types);
12225 bool isArgValueUsed = !Arg.use_empty();
12226 Type *FinalType = Arg.getType();
12227 if (Arg.hasAttribute(Attribute::ByVal))
12228 FinalType = Arg.getParamByValType();
12229 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
12230 FinalType, F.getCallingConv(), F.isVarArg(), DL);
12231 for (unsigned Value = 0, NumValues = Types.size(); Value != NumValues;
12232 ++Value) {
12233 Type *ArgTy = Types[Value];
12234 EVT VT = TLI->getValueType(DL, ArgTy);
12235 ISD::ArgFlagsTy Flags;
12236
12237 if (ArgTy->isPointerTy()) {
12238 Flags.setPointer();
12239 Flags.setPointerAddrSpace(cast<PointerType>(ArgTy)->getAddressSpace());
12240 }
12241 if (Arg.hasAttribute(Attribute::ZExt))
12242 Flags.setZExt();
12243 if (Arg.hasAttribute(Attribute::SExt))
12244 Flags.setSExt();
12245 if (Arg.hasAttribute(Attribute::InReg)) {
12246 // If we are using vectorcall calling convention, a structure that is
12247 // passed InReg - is surely an HVA
12248 if (F.getCallingConv() == CallingConv::X86_VectorCall &&
12249 isa<StructType>(Arg.getType())) {
12250 // The first value of a structure is marked
12251 if (0 == Value)
12252 Flags.setHvaStart();
12253 Flags.setHva();
12254 }
12255 // Set InReg Flag
12256 Flags.setInReg();
12257 }
12258 if (Arg.hasAttribute(Attribute::StructRet))
12259 Flags.setSRet();
12260 if (Arg.hasAttribute(Attribute::SwiftSelf))
12261 Flags.setSwiftSelf();
12262 if (Arg.hasAttribute(Attribute::SwiftAsync))
12263 Flags.setSwiftAsync();
12264 if (Arg.hasAttribute(Attribute::SwiftError))
12265 Flags.setSwiftError();
12266 if (Arg.hasAttribute(Attribute::ByVal))
12267 Flags.setByVal();
12268 if (Arg.hasAttribute(Attribute::ByRef))
12269 Flags.setByRef();
12270 if (Arg.hasAttribute(Attribute::InAlloca)) {
12271 Flags.setInAlloca();
12272 // Set the byval flag for CCAssignFn callbacks that don't know about
12273 // inalloca. This way we can know how many bytes we should've allocated
12274 // and how many bytes a callee cleanup function will pop. If we port
12275 // inalloca to more targets, we'll have to add custom inalloca handling
12276 // in the various CC lowering callbacks.
12277 Flags.setByVal();
12278 }
12279 if (Arg.hasAttribute(Attribute::Preallocated)) {
12280 Flags.setPreallocated();
12281 // Set the byval flag for CCAssignFn callbacks that don't know about
12282 // preallocated. This way we can know how many bytes we should've
12283 // allocated and how many bytes a callee cleanup function will pop. If
12284 // we port preallocated to more targets, we'll have to add custom
12285 // preallocated handling in the various CC lowering callbacks.
12286 Flags.setByVal();
12287 }
12288
12289 // Certain targets (such as MIPS), may have a different ABI alignment
12290 // for a type depending on the context. Give the target a chance to
12291 // specify the alignment it wants.
12292 const Align OriginalAlignment(
12293 TLI->getABIAlignmentForCallingConv(ArgTy, DL));
12294 Flags.setOrigAlign(OriginalAlignment);
12295
12296 Align MemAlign;
12297 Type *ArgMemTy = nullptr;
12298 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
12299 Flags.isByRef()) {
12300 if (!ArgMemTy)
12301 ArgMemTy = Arg.getPointeeInMemoryValueType();
12302
12303 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
12304
12305 // For in-memory arguments, size and alignment should be passed from FE.
12306 // BE will guess if this info is not there but there are cases it cannot
12307 // get right.
12308 if (auto ParamAlign = Arg.getParamStackAlign())
12309 MemAlign = *ParamAlign;
12310 else if ((ParamAlign = Arg.getParamAlign()))
12311 MemAlign = *ParamAlign;
12312 else
12313 MemAlign = TLI->getByValTypeAlignment(ArgMemTy, DL);
12314 if (Flags.isByRef())
12315 Flags.setByRefSize(MemSize);
12316 else
12317 Flags.setByValSize(MemSize);
12318 } else if (auto ParamAlign = Arg.getParamStackAlign()) {
12319 MemAlign = *ParamAlign;
12320 } else {
12321 MemAlign = OriginalAlignment;
12322 }
12323 Flags.setMemAlign(MemAlign);
12324
12325 if (Arg.hasAttribute(Attribute::Nest))
12326 Flags.setNest();
12327 if (NeedsRegBlock)
12328 Flags.setInConsecutiveRegs();
12329 if (ArgCopyElisionCandidates.count(&Arg))
12330 Flags.setCopyElisionCandidate();
12331 if (Arg.hasAttribute(Attribute::Returned))
12332 Flags.setReturned();
12333
12334 MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
12335 *CurDAG->getContext(), F.getCallingConv(), VT);
12336 unsigned NumRegs = TLI->getNumRegistersForCallingConv(
12337 *CurDAG->getContext(), F.getCallingConv(), VT);
12338 for (unsigned i = 0; i != NumRegs; ++i) {
12339 // For scalable vectors, use the minimum size; individual targets
12340 // are responsible for handling scalable vector arguments and
12341 // return values.
12342 ISD::InputArg MyFlags(
12343 Flags, RegisterVT, VT, ArgTy, isArgValueUsed, ArgNo,
12344 i * RegisterVT.getStoreSize().getKnownMinValue());
12345 if (NumRegs > 1 && i == 0)
12346 MyFlags.Flags.setSplit();
12347 // if it isn't first piece, alignment must be 1
12348 else if (i > 0) {
12349 MyFlags.Flags.setOrigAlign(Align(1));
12350 if (i == NumRegs - 1)
12351 MyFlags.Flags.setSplitEnd();
12352 }
12353 Ins.push_back(MyFlags);
12354 }
12355 if (NeedsRegBlock && Value == NumValues - 1)
12356 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
12357 }
12358 }
12359
12360 // Call the target to set up the argument values.
12362 SDValue NewRoot = TLI->LowerFormalArguments(
12363 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
12364
12365 // Verify that the target's LowerFormalArguments behaved as expected.
12366 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
12367 "LowerFormalArguments didn't return a valid chain!");
12368 assert(InVals.size() == Ins.size() &&
12369 "LowerFormalArguments didn't emit the correct number of values!");
12370 assert(all_of(InVals, [](SDValue InVal) { return InVal.getNode(); }) &&
12371 "LowerFormalArguments emitted a null value!");
12372
12373 // Update the DAG with the new chain value resulting from argument lowering.
12374 DAG.setRoot(NewRoot);
12375
12376 // Set up the argument values.
12377 unsigned i = 0;
12378 if (!FuncInfo->CanLowerReturn) {
12379 // Create a virtual register for the sret pointer, and put in a copy
12380 // from the sret argument into it.
12381 MVT VT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
12382 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
12383 std::optional<ISD::NodeType> AssertOp;
12384 SDValue ArgValue =
12385 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
12386 F.getCallingConv(), AssertOp);
12387
12388 MachineFunction& MF = SDB->DAG.getMachineFunction();
12389 MachineRegisterInfo& RegInfo = MF.getRegInfo();
12390 Register SRetReg =
12391 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
12392 FuncInfo->DemoteRegister = SRetReg;
12393 NewRoot =
12394 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
12395 DAG.setRoot(NewRoot);
12396
12397 // i indexes lowered arguments. Bump it past the hidden sret argument.
12398 ++i;
12399 }
12400
12402 DenseMap<int, int> ArgCopyElisionFrameIndexMap;
12403 for (const Argument &Arg : F.args()) {
12404 SmallVector<SDValue, 4> ArgValues;
12405 SmallVector<EVT, 4> ValueVTs;
12406 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
12407 unsigned NumValues = ValueVTs.size();
12408 if (NumValues == 0)
12409 continue;
12410
12411 bool ArgHasUses = !Arg.use_empty();
12412
12413 // Elide the copying store if the target loaded this argument from a
12414 // suitable fixed stack object.
12415 if (Ins[i].Flags.isCopyElisionCandidate()) {
12416 unsigned NumParts = 0;
12417 for (EVT VT : ValueVTs)
12418 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
12419 F.getCallingConv(), VT);
12420
12421 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
12422 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
12423 ArrayRef(&InVals[i], NumParts), ArgHasUses);
12424 }
12425
12426 // If this argument is unused then remember its value. It is used to generate
12427 // debugging information.
12428 bool isSwiftErrorArg =
12429 TLI->supportSwiftError() &&
12430 Arg.hasAttribute(Attribute::SwiftError);
12431 if (!ArgHasUses && !isSwiftErrorArg) {
12432 SDB->setUnusedArgValue(&Arg, InVals[i]);
12433
12434 // Also remember any frame index for use in FastISel.
12435 if (FrameIndexSDNode *FI =
12437 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12438 }
12439
12440 for (unsigned Val = 0; Val != NumValues; ++Val) {
12441 EVT VT = ValueVTs[Val];
12442 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
12443 F.getCallingConv(), VT);
12444 unsigned NumParts = TLI->getNumRegistersForCallingConv(
12445 *CurDAG->getContext(), F.getCallingConv(), VT);
12446
12447 // Even an apparent 'unused' swifterror argument needs to be returned. So
12448 // we do generate a copy for it that can be used on return from the
12449 // function.
12450 if (ArgHasUses || isSwiftErrorArg) {
12451 std::optional<ISD::NodeType> AssertOp;
12452 if (Arg.hasAttribute(Attribute::SExt))
12453 AssertOp = ISD::AssertSext;
12454 else if (Arg.hasAttribute(Attribute::ZExt))
12455 AssertOp = ISD::AssertZext;
12456
12457 SDValue OutVal =
12458 getCopyFromParts(DAG, dl, &InVals[i], NumParts, PartVT, VT, nullptr,
12459 NewRoot, F.getCallingConv(), AssertOp);
12460
12461 FPClassTest NoFPClass = Arg.getNoFPClass();
12462 if (NoFPClass != fcNone) {
12463 SDValue SDNoFPClass = DAG.getTargetConstant(
12464 static_cast<uint64_t>(NoFPClass), dl, MVT::i32);
12465 OutVal = DAG.getNode(ISD::AssertNoFPClass, dl, OutVal.getValueType(),
12466 OutVal, SDNoFPClass);
12467 }
12468 ArgValues.push_back(OutVal);
12469 }
12470
12471 i += NumParts;
12472 }
12473
12474 // We don't need to do anything else for unused arguments.
12475 if (ArgValues.empty())
12476 continue;
12477
12478 // Note down frame index.
12479 if (FrameIndexSDNode *FI =
12480 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
12481 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12482
12483 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
12484 SDB->getCurSDLoc());
12485
12486 SDB->setValue(&Arg, Res);
12487 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
12488 // We want to associate the argument with the frame index, among
12489 // involved operands, that correspond to the lowest address. The
12490 // getCopyFromParts function, called earlier, is swapping the order of
12491 // the operands to BUILD_PAIR depending on endianness. The result of
12492 // that swapping is that the least significant bits of the argument will
12493 // be in the first operand of the BUILD_PAIR node, and the most
12494 // significant bits will be in the second operand.
12495 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
12496 if (LoadSDNode *LNode =
12497 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
12498 if (FrameIndexSDNode *FI =
12499 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
12500 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12501 }
12502
12503 // Analyses past this point are naive and don't expect an assertion.
12504 if (Res.getOpcode() == ISD::AssertZext)
12505 Res = Res.getOperand(0);
12506
12507 // Update the SwiftErrorVRegDefMap.
12508 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
12509 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
12510 if (Reg.isVirtual())
12511 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
12512 Reg);
12513 }
12514
12515 // If this argument is live outside of the entry block, insert a copy from
12516 // wherever we got it to the vreg that other BB's will reference it as.
12517 if (Res.getOpcode() == ISD::CopyFromReg) {
12518 // If we can, though, try to skip creating an unnecessary vreg.
12519 // FIXME: This isn't very clean... it would be nice to make this more
12520 // general.
12521 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
12522 if (Reg.isVirtual()) {
12523 FuncInfo->ValueMap[&Arg] = Reg;
12524 continue;
12525 }
12526 }
12527 if (!isOnlyUsedInEntryBlock(&Arg, FastISel)) {
12528 FuncInfo->InitializeRegForValue(&Arg);
12529 SDB->CopyToExportRegsIfNeeded(&Arg);
12530 }
12531 }
12532
12533 if (!Chains.empty()) {
12534 Chains.push_back(NewRoot);
12535 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
12536 }
12537
12538 DAG.setRoot(NewRoot);
12539
12540 assert(i == InVals.size() && "Argument register count mismatch!");
12541
12542 // If any argument copy elisions occurred and we have debug info, update the
12543 // stale frame indices used in the dbg.declare variable info table.
12544 if (!ArgCopyElisionFrameIndexMap.empty()) {
12545 for (MachineFunction::VariableDbgInfo &VI :
12546 MF->getInStackSlotVariableDbgInfo()) {
12547 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
12548 if (I != ArgCopyElisionFrameIndexMap.end())
12549 VI.updateStackSlot(I->second);
12550 }
12551 }
12552
12553 // Finally, if the target has anything special to do, allow it to do so.
12555}
12556
12557/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
12558/// ensure constants are generated when needed. Remember the virtual registers
12559/// that need to be added to the Machine PHI nodes as input. We cannot just
12560/// directly add them, because expansion might result in multiple MBB's for one
12561/// BB. As such, the start of the BB might correspond to a different MBB than
12562/// the end.
12563void
12564SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
12565 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12566
12567 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
12568
12569 // Check PHI nodes in successors that expect a value to be available from this
12570 // block.
12571 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
12572 if (!isa<PHINode>(SuccBB->begin())) continue;
12573 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
12574
12575 // If this terminator has multiple identical successors (common for
12576 // switches), only handle each succ once.
12577 if (!SuccsHandled.insert(SuccMBB).second)
12578 continue;
12579
12581
12582 // At this point we know that there is a 1-1 correspondence between LLVM PHI
12583 // nodes and Machine PHI nodes, but the incoming operands have not been
12584 // emitted yet.
12585 for (const PHINode &PN : SuccBB->phis()) {
12586 // Ignore dead phi's.
12587 if (PN.use_empty())
12588 continue;
12589
12590 // Skip empty types
12591 if (PN.getType()->isEmptyTy())
12592 continue;
12593
12594 Register Reg;
12595 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
12596
12597 if (const auto *C = dyn_cast<Constant>(PHIOp)) {
12598 Register &RegOut = ConstantsOut[C];
12599 if (!RegOut) {
12600 RegOut = FuncInfo.CreateRegs(PHIOp);
12601 // We need to zero/sign extend ConstantInt phi operands to match
12602 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
12603 ISD::NodeType ExtendType = ISD::ANY_EXTEND;
12604 if (auto *CI = dyn_cast<ConstantInt>(C))
12605 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
12607 CopyValueToVirtualRegister(C, RegOut, ExtendType);
12608 }
12609 Reg = RegOut;
12610 } else {
12611 auto I = FuncInfo.ValueMap.find(PHIOp);
12612 if (I != FuncInfo.ValueMap.end())
12613 Reg = I->second;
12614 else {
12615 assert(isa<AllocaInst>(PHIOp) &&
12616 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
12617 "Didn't codegen value into a register!??");
12618 Reg = FuncInfo.CreateRegs(PHIOp);
12620 }
12621 }
12622
12623 // Remember that this register needs to added to the machine PHI node as
12624 // the input for this MBB.
12625 SmallVector<EVT, 4> ValueVTs;
12626 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
12627 for (EVT VT : ValueVTs) {
12628 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
12629 for (unsigned i = 0; i != NumRegisters; ++i)
12630 FuncInfo.PHINodesToUpdate.emplace_back(&*MBBI++, Reg + i);
12631 Reg += NumRegisters;
12632 }
12633 }
12634 }
12635
12636 ConstantsOut.clear();
12637}
12638
12639MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
12641 if (++I == FuncInfo.MF->end())
12642 return nullptr;
12643 return &*I;
12644}
12645
12646/// During lowering new call nodes can be created (such as memset, etc.).
12647/// Those will become new roots of the current DAG, but complications arise
12648/// when they are tail calls. In such cases, the call lowering will update
12649/// the root, but the builder still needs to know that a tail call has been
12650/// lowered in order to avoid generating an additional return.
12651void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12652 // If the node is null, we do have a tail call.
12653 if (MaybeTC.getNode() != nullptr)
12654 DAG.setRoot(MaybeTC);
12655 else
12656 HasTailCall = true;
12657}
12658
12659void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12660 MachineBasicBlock *SwitchMBB,
12661 MachineBasicBlock *DefaultMBB) {
12662 MachineFunction *CurMF = FuncInfo.MF;
12663 MachineBasicBlock *NextMBB = nullptr;
12665 if (++BBI != FuncInfo.MF->end())
12666 NextMBB = &*BBI;
12667
12668 unsigned Size = W.LastCluster - W.FirstCluster + 1;
12669
12670 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12671
12672 if (Size == 2 && W.MBB == SwitchMBB) {
12673 // If any two of the cases has the same destination, and if one value
12674 // is the same as the other, but has one bit unset that the other has set,
12675 // use bit manipulation to do two compares at once. For example:
12676 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12677 // TODO: This could be extended to merge any 2 cases in switches with 3
12678 // cases.
12679 // TODO: Handle cases where W.CaseBB != SwitchBB.
12680 CaseCluster &Small = *W.FirstCluster;
12681 CaseCluster &Big = *W.LastCluster;
12682
12683 if (Small.Low == Small.High && Big.Low == Big.High &&
12684 Small.MBB == Big.MBB) {
12685 const APInt &SmallValue = Small.Low->getValue();
12686 const APInt &BigValue = Big.Low->getValue();
12687
12688 // Check that there is only one bit different.
12689 APInt CommonBit = BigValue ^ SmallValue;
12690 if (CommonBit.isPowerOf2()) {
12691 SDValue CondLHS = getValue(Cond);
12692 EVT VT = CondLHS.getValueType();
12693 SDLoc DL = getCurSDLoc();
12694
12695 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
12696 DAG.getConstant(CommonBit, DL, VT));
12697 SDValue Cond = DAG.getSetCC(
12698 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
12699 ISD::SETEQ);
12700
12701 // Update successor info.
12702 // Both Small and Big will jump to Small.BB, so we sum up the
12703 // probabilities.
12704 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
12705 if (BPI)
12706 addSuccessorWithProb(
12707 SwitchMBB, DefaultMBB,
12708 // The default destination is the first successor in IR.
12709 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12710 else
12711 addSuccessorWithProb(SwitchMBB, DefaultMBB);
12712
12713 // Insert the true branch.
12714 SDValue BrCond =
12715 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12716 DAG.getBasicBlock(Small.MBB));
12717 // Insert the false branch.
12718 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12719 DAG.getBasicBlock(DefaultMBB));
12720
12721 DAG.setRoot(BrCond);
12722 return;
12723 }
12724 }
12725 }
12726
12727 if (TM.getOptLevel() != CodeGenOptLevel::None) {
12728 // Here, we order cases by probability so the most likely case will be
12729 // checked first. However, two clusters can have the same probability in
12730 // which case their relative ordering is non-deterministic. So we use Low
12731 // as a tie-breaker as clusters are guaranteed to never overlap.
12732 llvm::sort(W.FirstCluster, W.LastCluster + 1,
12733 [](const CaseCluster &a, const CaseCluster &b) {
12734 return a.Prob != b.Prob ?
12735 a.Prob > b.Prob :
12736 a.Low->getValue().slt(b.Low->getValue());
12737 });
12738
12739 // Rearrange the case blocks so that the last one falls through if possible
12740 // without changing the order of probabilities.
12741 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12742 --I;
12743 if (I->Prob > W.LastCluster->Prob)
12744 break;
12745 if (I->Kind == CC_Range && I->MBB == NextMBB) {
12746 std::swap(*I, *W.LastCluster);
12747 break;
12748 }
12749 }
12750 }
12751
12752 // Compute total probability.
12753 BranchProbability DefaultProb = W.DefaultProb;
12754 BranchProbability UnhandledProbs = DefaultProb;
12755 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12756 UnhandledProbs += I->Prob;
12757
12758 MachineBasicBlock *CurMBB = W.MBB;
12759 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12760 bool FallthroughUnreachable = false;
12761 MachineBasicBlock *Fallthrough;
12762 if (I == W.LastCluster) {
12763 // For the last cluster, fall through to the default destination.
12764 Fallthrough = DefaultMBB;
12765 FallthroughUnreachable =
12767 } else {
12768 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12769 CurMF->insert(BBI, Fallthrough);
12770 // Put Cond in a virtual register to make it available from the new blocks.
12772 }
12773 UnhandledProbs -= I->Prob;
12774
12775 switch (I->Kind) {
12776 case CC_JumpTable: {
12777 // FIXME: Optimize away range check based on pivot comparisons.
12778 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12779 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12780
12781 // The jump block hasn't been inserted yet; insert it here.
12782 MachineBasicBlock *JumpMBB = JT->MBB;
12783 CurMF->insert(BBI, JumpMBB);
12784
12785 auto JumpProb = I->Prob;
12786 auto FallthroughProb = UnhandledProbs;
12787
12788 // If the default statement is a target of the jump table, we evenly
12789 // distribute the default probability to successors of CurMBB. Also
12790 // update the probability on the edge from JumpMBB to Fallthrough.
12791 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12792 SE = JumpMBB->succ_end();
12793 SI != SE; ++SI) {
12794 if (*SI == DefaultMBB) {
12795 JumpProb += DefaultProb / 2;
12796 FallthroughProb -= DefaultProb / 2;
12797 JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12798 JumpMBB->normalizeSuccProbs();
12799 break;
12800 }
12801 }
12802
12803 // If the default clause is unreachable, propagate that knowledge into
12804 // JTH->FallthroughUnreachable which will use it to suppress the range
12805 // check.
12806 //
12807 // However, don't do this if we're doing branch target enforcement
12808 // (e.g. Arm BTI, or the cf-protection-branch module flag used by
12809 // RISC-V Zicfilp and X86 IBT), because a table branch _without_ a
12810 // range check can be a tempting JOP gadget - out-of-bounds inputs
12811 // that are impossible in correct execution become possible again if
12812 // an attacker can influence the control flow. So if an attacker
12813 // doesn't already have a branch target enforcement bypass available,
12814 // we don't want them to be able to get one out of this table branch.
12815 if (FallthroughUnreachable) {
12816 Function &CurFunc = CurMF->getFunction();
12817 bool HasCFBranch = false;
12818 if (auto *CFBranch = mdconst::extract_or_null<ConstantInt>(
12819 CurFunc.getParent()->getModuleFlag("cf-protection-branch")))
12820 HasCFBranch = !CFBranch->isZero();
12821 if (!HasCFBranch &&
12822 !CurFunc.hasFnAttribute("branch-target-enforcement"))
12823 JTH->FallthroughUnreachable = true;
12824 }
12825
12826 if (!JTH->FallthroughUnreachable)
12827 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12828 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12829 CurMBB->normalizeSuccProbs();
12830
12831 // The jump table header will be inserted in our current block, do the
12832 // range check, and fall through to our fallthrough block.
12833 JTH->HeaderBB = CurMBB;
12834 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12835
12836 // If we're in the right place, emit the jump table header right now.
12837 if (CurMBB == SwitchMBB) {
12838 visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12839 JTH->Emitted = true;
12840 }
12841 break;
12842 }
12843 case CC_BitTests: {
12844 // FIXME: Optimize away range check based on pivot comparisons.
12845 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12846
12847 // The bit test blocks haven't been inserted yet; insert them here.
12848 for (BitTestCase &BTC : BTB->Cases)
12849 CurMF->insert(BBI, BTC.ThisBB);
12850
12851 // Fill in fields of the BitTestBlock.
12852 BTB->Parent = CurMBB;
12853 BTB->Default = Fallthrough;
12854
12855 BTB->DefaultProb = UnhandledProbs;
12856 // If the cases in bit test don't form a contiguous range, we evenly
12857 // distribute the probability on the edge to Fallthrough to two
12858 // successors of CurMBB.
12859 if (!BTB->ContiguousRange) {
12860 BTB->Prob += DefaultProb / 2;
12861 BTB->DefaultProb -= DefaultProb / 2;
12862 }
12863
12864 if (FallthroughUnreachable)
12865 BTB->FallthroughUnreachable = true;
12866
12867 // If we're in the right place, emit the bit test header right now.
12868 if (CurMBB == SwitchMBB) {
12869 visitBitTestHeader(*BTB, SwitchMBB);
12870 BTB->Emitted = true;
12871 }
12872 break;
12873 }
12874 case CC_Range: {
12875 const Value *RHS, *LHS, *MHS;
12877 if (I->Low == I->High) {
12878 // Check Cond == I->Low.
12879 CC = ISD::SETEQ;
12880 LHS = Cond;
12881 RHS=I->Low;
12882 MHS = nullptr;
12883 } else {
12884 // Check I->Low <= Cond <= I->High.
12885 CC = ISD::SETLE;
12886 LHS = I->Low;
12887 MHS = Cond;
12888 RHS = I->High;
12889 }
12890
12891 // If Fallthrough is unreachable, fold away the comparison.
12892 if (FallthroughUnreachable)
12893 CC = ISD::SETTRUE;
12894
12895 // The false probability is the sum of all unhandled cases.
12896 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12897 getCurSDLoc(), I->Prob, UnhandledProbs);
12898
12899 if (CurMBB == SwitchMBB)
12900 visitSwitchCase(CB, SwitchMBB);
12901 else
12902 SL->SwitchCases.push_back(CB);
12903
12904 break;
12905 }
12906 }
12907 CurMBB = Fallthrough;
12908 }
12909}
12910
12911void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12912 const SwitchWorkListItem &W,
12913 Value *Cond,
12914 MachineBasicBlock *SwitchMBB) {
12915 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12916 "Clusters not sorted?");
12917 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12918
12919 auto [LastLeft, FirstRight, LeftProb, RightProb] =
12920 SL->computeSplitWorkItemInfo(W);
12921
12922 // Use the first element on the right as pivot since we will make less-than
12923 // comparisons against it.
12924 CaseClusterIt PivotCluster = FirstRight;
12925 assert(PivotCluster > W.FirstCluster);
12926 assert(PivotCluster <= W.LastCluster);
12927
12928 CaseClusterIt FirstLeft = W.FirstCluster;
12929 CaseClusterIt LastRight = W.LastCluster;
12930
12931 const ConstantInt *Pivot = PivotCluster->Low;
12932
12933 // New blocks will be inserted immediately after the current one.
12935 ++BBI;
12936
12937 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12938 // we can branch to its destination directly if it's squeezed exactly in
12939 // between the known lower bound and Pivot - 1.
12940 MachineBasicBlock *LeftMBB;
12941 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12942 FirstLeft->Low == W.GE &&
12943 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12944 LeftMBB = FirstLeft->MBB;
12945 } else {
12946 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12947 FuncInfo.MF->insert(BBI, LeftMBB);
12948 WorkList.push_back(
12949 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12950 // Put Cond in a virtual register to make it available from the new blocks.
12952 }
12953
12954 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12955 // single cluster, RHS.Low == Pivot, and we can branch to its destination
12956 // directly if RHS.High equals the current upper bound.
12957 MachineBasicBlock *RightMBB;
12958 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12959 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12960 RightMBB = FirstRight->MBB;
12961 } else {
12962 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12963 FuncInfo.MF->insert(BBI, RightMBB);
12964 WorkList.push_back(
12965 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12966 // Put Cond in a virtual register to make it available from the new blocks.
12968 }
12969
12970 // Create the CaseBlock record that will be used to lower the branch.
12971 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12972 getCurSDLoc(), LeftProb, RightProb);
12973
12974 if (W.MBB == SwitchMBB)
12975 visitSwitchCase(CB, SwitchMBB);
12976 else
12977 SL->SwitchCases.push_back(CB);
12978}
12979
12980// Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12981// from the swith statement.
12983 BranchProbability PeeledCaseProb) {
12984 if (PeeledCaseProb == BranchProbability::getOne())
12986 BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12987
12988 uint32_t Numerator = CaseProb.getNumerator();
12989 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12990 return BranchProbability(Numerator, std::max(Numerator, Denominator));
12991}
12992
12993// Try to peel the top probability case if it exceeds the threshold.
12994// Return current MachineBasicBlock for the switch statement if the peeling
12995// does not occur.
12996// If the peeling is performed, return the newly created MachineBasicBlock
12997// for the peeled switch statement. Also update Clusters to remove the peeled
12998// case. PeeledCaseProb is the BranchProbability for the peeled case.
12999MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
13000 const SwitchInst &SI, CaseClusterVector &Clusters,
13001 BranchProbability &PeeledCaseProb) {
13002 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
13003 // Don't perform if there is only one cluster or optimizing for size.
13004 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
13005 TM.getOptLevel() == CodeGenOptLevel::None ||
13006 SwitchMBB->getParent()->getFunction().hasMinSize())
13007 return SwitchMBB;
13008
13009 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
13010 unsigned PeeledCaseIndex = 0;
13011 bool SwitchPeeled = false;
13012 for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
13013 CaseCluster &CC = Clusters[Index];
13014 if (CC.Prob < TopCaseProb)
13015 continue;
13016 TopCaseProb = CC.Prob;
13017 PeeledCaseIndex = Index;
13018 SwitchPeeled = true;
13019 }
13020 if (!SwitchPeeled)
13021 return SwitchMBB;
13022
13023 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
13024 << TopCaseProb << "\n");
13025
13026 // Record the MBB for the peeled switch statement.
13027 MachineFunction::iterator BBI(SwitchMBB);
13028 ++BBI;
13029 MachineBasicBlock *PeeledSwitchMBB =
13030 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
13031 FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
13032
13033 ExportFromCurrentBlock(SI.getCondition());
13034 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
13035 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
13036 nullptr, nullptr, TopCaseProb.getCompl()};
13037 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
13038
13039 Clusters.erase(PeeledCaseIt);
13040 for (CaseCluster &CC : Clusters) {
13041 LLVM_DEBUG(
13042 dbgs() << "Scale the probablity for one cluster, before scaling: "
13043 << CC.Prob << "\n");
13044 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
13045 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
13046 }
13047 PeeledCaseProb = TopCaseProb;
13048 return PeeledSwitchMBB;
13049}
13050
13051void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
13052 // Extract cases from the switch.
13053 BranchProbabilityInfo *BPI = FuncInfo.BPI;
13054 CaseClusterVector Clusters;
13055 Clusters.reserve(SI.getNumCases());
13056 for (auto I : SI.cases()) {
13057 MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
13058 const ConstantInt *CaseVal = I.getCaseValue();
13059 BranchProbability Prob =
13060 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
13061 : BranchProbability(1, SI.getNumCases() + 1);
13062 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
13063 }
13064
13065 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
13066
13067 // Cluster adjacent cases with the same destination. We do this at all
13068 // optimization levels because it's cheap to do and will make codegen faster
13069 // if there are many clusters.
13070 sortAndRangeify(Clusters);
13071
13072 // The branch probablity of the peeled case.
13073 BranchProbability PeeledCaseProb = BranchProbability::getZero();
13074 MachineBasicBlock *PeeledSwitchMBB =
13075 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
13076
13077 // If there is only the default destination, jump there directly.
13078 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
13079 if (Clusters.empty()) {
13080 assert(PeeledSwitchMBB == SwitchMBB);
13081 SwitchMBB->addSuccessor(DefaultMBB);
13082 if (DefaultMBB != NextBlock(SwitchMBB)) {
13083 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
13084 getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
13085 }
13086 return;
13087 }
13088
13089 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
13090 DAG.getBFI());
13091 SL->findBitTestClusters(Clusters, &SI);
13092
13093 LLVM_DEBUG({
13094 dbgs() << "Case clusters: ";
13095 for (const CaseCluster &C : Clusters) {
13096 if (C.Kind == CC_JumpTable)
13097 dbgs() << "JT:";
13098 if (C.Kind == CC_BitTests)
13099 dbgs() << "BT:";
13100
13101 C.Low->getValue().print(dbgs(), true);
13102 if (C.Low != C.High) {
13103 dbgs() << '-';
13104 C.High->getValue().print(dbgs(), true);
13105 }
13106 dbgs() << ' ';
13107 }
13108 dbgs() << '\n';
13109 });
13110
13111 assert(!Clusters.empty());
13112 SwitchWorkList WorkList;
13113 CaseClusterIt First = Clusters.begin();
13114 CaseClusterIt Last = Clusters.end() - 1;
13115 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
13116 // Scale the branchprobability for DefaultMBB if the peel occurs and
13117 // DefaultMBB is not replaced.
13118 if (PeeledCaseProb != BranchProbability::getZero() &&
13119 DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
13120 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
13121 WorkList.push_back(
13122 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
13123
13124 while (!WorkList.empty()) {
13125 SwitchWorkListItem W = WorkList.pop_back_val();
13126 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
13127
13128 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
13129 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
13130 // For optimized builds, lower large range as a balanced binary tree.
13131 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
13132 continue;
13133 }
13134
13135 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
13136 }
13137}
13138
13139void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
13140 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13141 auto DL = getCurSDLoc();
13142 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13143 setValue(&I, DAG.getStepVector(DL, ResultVT));
13144}
13145
13146void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
13147 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13148 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13149
13150 SDLoc DL = getCurSDLoc();
13151 SDValue V = getValue(I.getOperand(0));
13152 assert(VT == V.getValueType() && "Malformed vector.reverse!");
13153
13154 if (VT.isScalableVector()) {
13155 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
13156 return;
13157 }
13158
13159 // Use VECTOR_SHUFFLE for the fixed-length vector
13160 // to maintain existing behavior.
13161 SmallVector<int, 8> Mask;
13162 unsigned NumElts = VT.getVectorMinNumElements();
13163 for (unsigned i = 0; i != NumElts; ++i)
13164 Mask.push_back(NumElts - 1 - i);
13165
13166 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
13167}
13168
13169void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I,
13170 unsigned Factor) {
13171 auto DL = getCurSDLoc();
13172 SDValue InVec = getValue(I.getOperand(0));
13173
13174 SmallVector<EVT, 4> ValueVTs;
13175 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
13176 ValueVTs);
13177
13178 EVT OutVT = ValueVTs[0];
13179 unsigned OutNumElts = OutVT.getVectorMinNumElements();
13180
13181 SmallVector<SDValue, 4> SubVecs(Factor);
13182 for (unsigned i = 0; i != Factor; ++i) {
13183 assert(ValueVTs[i] == OutVT && "Expected VTs to be the same");
13184 SubVecs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
13185 DAG.getVectorIdxConstant(OutNumElts * i, DL));
13186 }
13187
13188 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
13189 DAG.getVTList(ValueVTs), SubVecs);
13190 setValue(&I, Res);
13191}
13192
13193void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I,
13194 unsigned Factor) {
13195 auto DL = getCurSDLoc();
13196 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13197 EVT InVT = getValue(I.getOperand(0)).getValueType();
13198 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13199
13200 SmallVector<SDValue, 8> InVecs(Factor);
13201 for (unsigned i = 0; i < Factor; ++i) {
13202 InVecs[i] = getValue(I.getOperand(i));
13203 assert(InVecs[i].getValueType() == InVecs[0].getValueType() &&
13204 "Expected VTs to be the same");
13205 }
13206
13207 SmallVector<EVT, 8> ValueVTs(Factor, InVT);
13208 SDValue Res =
13209 DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, DAG.getVTList(ValueVTs), InVecs);
13210
13212 for (unsigned i = 0; i < Factor; ++i)
13213 Results[i] = Res.getValue(i);
13214
13215 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Results);
13216 setValue(&I, Res);
13217}
13218
13219void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
13220 SmallVector<EVT, 4> ValueVTs;
13221 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
13222 ValueVTs);
13223 unsigned NumValues = ValueVTs.size();
13224 if (NumValues == 0) return;
13225
13227 SDValue Op = getValue(I.getOperand(0));
13228
13229 for (unsigned i = 0; i != NumValues; ++i)
13230 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
13231 SDValue(Op.getNode(), Op.getResNo() + i));
13232
13234 DAG.getVTList(ValueVTs), Values));
13235}
13236
13237void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
13238 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13239 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13240
13241 SDLoc DL = getCurSDLoc();
13242 SDValue V1 = getValue(I.getOperand(0));
13243 SDValue V2 = getValue(I.getOperand(1));
13244 const bool IsLeft = I.getIntrinsicID() == Intrinsic::vector_splice_left;
13245
13246 // VECTOR_SHUFFLE doesn't support a scalable or non-constant mask.
13247 if (VT.isScalableVector() || !isa<ConstantInt>(I.getOperand(2))) {
13248 SDValue Offset = DAG.getZExtOrTrunc(
13249 getValue(I.getOperand(2)), DL, TLI.getVectorIdxTy(DAG.getDataLayout()));
13250 setValue(&I, DAG.getNode(IsLeft ? ISD::VECTOR_SPLICE_LEFT
13252 DL, VT, V1, V2, Offset));
13253 return;
13254 }
13255 uint64_t Imm = cast<ConstantInt>(I.getOperand(2))->getZExtValue();
13256
13257 unsigned NumElts = VT.getVectorNumElements();
13258
13259 uint64_t Idx = IsLeft ? Imm : NumElts - Imm;
13260
13261 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
13262 SmallVector<int, 8> Mask;
13263 for (unsigned i = 0; i < NumElts; ++i)
13264 Mask.push_back(Idx + i);
13265 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
13266}
13267
13268// Consider the following MIR after SelectionDAG, which produces output in
13269// phyregs in the first case or virtregs in the second case.
13270//
13271// INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
13272// %5:gr32 = COPY $ebx
13273// %6:gr32 = COPY $edx
13274// %1:gr32 = COPY %6:gr32
13275// %0:gr32 = COPY %5:gr32
13276//
13277// INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
13278// %1:gr32 = COPY %6:gr32
13279// %0:gr32 = COPY %5:gr32
13280//
13281// Given %0, we'd like to return $ebx in the first case and %5 in the second.
13282// Given %1, we'd like to return $edx in the first case and %6 in the second.
13283//
13284// If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
13285// to a single virtreg (such as %0). The remaining outputs monotonically
13286// increase in virtreg number from there. If a callbr has no outputs, then it
13287// should not have a corresponding callbr landingpad; in fact, the callbr
13288// landingpad would not even be able to refer to such a callbr.
13290 MachineInstr *MI = MRI.def_begin(Reg)->getParent();
13291 // There is definitely at least one copy.
13292 assert(MI->getOpcode() == TargetOpcode::COPY &&
13293 "start of copy chain MUST be COPY");
13294 Reg = MI->getOperand(1).getReg();
13295
13296 // If the copied register in the first copy must be virtual.
13297 assert(Reg.isVirtual() && "expected COPY of virtual register");
13298 MI = MRI.def_begin(Reg)->getParent();
13299
13300 // There may be an optional second copy.
13301 if (MI->getOpcode() == TargetOpcode::COPY) {
13302 assert(Reg.isVirtual() && "expected COPY of virtual register");
13303 Reg = MI->getOperand(1).getReg();
13304 assert(Reg.isPhysical() && "expected COPY of physical register");
13305 } else {
13306 // The start of the chain must be an INLINEASM_BR.
13307 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
13308 "end of copy chain MUST be INLINEASM_BR");
13309 }
13310
13311 return Reg;
13312}
13313
13314// We must do this walk rather than the simpler
13315// setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
13316// otherwise we will end up with copies of virtregs only valid along direct
13317// edges.
13318void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
13319 SmallVector<EVT, 8> ResultVTs;
13320 SmallVector<SDValue, 8> ResultValues;
13321 const auto *CBR =
13322 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
13323
13324 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13325 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
13326 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
13327
13328 Register InitialDef = FuncInfo.ValueMap[CBR];
13329 SDValue Chain = DAG.getRoot();
13330
13331 // Re-parse the asm constraints string.
13332 TargetLowering::AsmOperandInfoVector TargetConstraints =
13333 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
13334 for (auto &T : TargetConstraints) {
13335 SDISelAsmOperandInfo OpInfo(T);
13336 if (OpInfo.Type != InlineAsm::isOutput)
13337 continue;
13338
13339 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
13340 // individual constraint.
13341 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
13342
13343 switch (OpInfo.ConstraintType) {
13346 // Fill in OpInfo.AssignedRegs.Regs.
13347 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
13348
13349 // getRegistersForValue may produce 1 to many registers based on whether
13350 // the OpInfo.ConstraintVT is legal on the target or not.
13351 for (Register &Reg : OpInfo.AssignedRegs.Regs) {
13352 Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
13353 if (OriginalDef.isPhysical())
13354 FuncInfo.MBB->addLiveIn(OriginalDef);
13355 // Update the assigned registers to use the original defs.
13356 Reg = OriginalDef;
13357 }
13358
13359 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
13360 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
13361 ResultValues.push_back(V);
13362 ResultVTs.push_back(OpInfo.ConstraintVT);
13363 break;
13364 }
13366 SDValue Flag;
13367 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
13368 OpInfo, DAG);
13369 ++InitialDef;
13370 ResultValues.push_back(V);
13371 ResultVTs.push_back(OpInfo.ConstraintVT);
13372 break;
13373 }
13374 default:
13375 break;
13376 }
13377 }
13378 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
13379 DAG.getVTList(ResultVTs), ResultValues);
13380 setValue(&I, V);
13381}
static unsigned getIntrinsicID(const SDNode *N)
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
uint64_t uint64_t
uint64_t Imm
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
Function Alias Analysis Results
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil translate DXIL Translate Metadata
static AttributeList getReturnAttrs(FastISel::CallLoweringInfo &CLI)
Returns an AttributeList representing the attributes applied to the return value of the given call.
Definition FastISel.cpp:947
#define Check(C,...)
static Value * getCondition(Instruction *I)
Hexagon Common GEP
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
static void getRegistersForValue(MachineFunction &MF, MachineIRBuilder &MIRBuilder, GISelAsmOperandInfo &OpInfo, GISelAsmOperandInfo &RefOpInfo)
Assign virtual/physical registers for the specified register operand.
static void computeConstraintToUse(const TargetLowering *TLI, TargetLowering::AsmOperandInfo &OpInfo)
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
lazy value info
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isUndef(const MachineInstr &MI)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static const Function * getCalledFunction(const Value *V)
This file provides utility analysis objects describing memory locations.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
This file contains the declarations for metadata subclasses.
Type::TypeID TypeID
#define T
#define T1
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static unsigned getAddressSpace(const Value *V, unsigned MaxLookup)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t High
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
#define P(N)
if(PassOpts->AAPipeline)
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
MachineInstr *& Lo
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file contains some templates that are useful if you are working with the STL at all.
static bool hasOnlySelectUsers(const Value *Cond)
static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, SDValue &Chain)
Create a LOAD_STACK_GUARD node, and let it carry the target specific global variable if there exists ...
static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, SDValue &Scale, SelectionDAGBuilder *SDB, const BasicBlock *CurBB, uint64_t ElemSize)
static void failForInvalidBundles(const CallBase &I, StringRef Name, ArrayRef< uint32_t > AllowedBundles)
static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, const SDLoc &DL, SmallVectorImpl< SDValue > &Ops, SelectionDAGBuilder &Builder)
Add a stack map intrinsic call's live variable operands to a stackmap or patchpoint target node's ope...
static const unsigned MaxParallelChains
static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
visitPow - Lower a pow intrinsic.
static const CallBase * FindPreallocatedCall(const Value *PreallocatedSetup)
Given a @llvm.call.preallocated.setup, return the corresponding preallocated call.
static cl::opt< unsigned > SwitchPeelThreshold("switch-peel-threshold", cl::Hidden, cl::init(66), cl::desc("Set the case probability threshold for peeling the case from a " "switch statement. A value greater than 100 will void this " "optimization"))
static cl::opt< bool > InsertAssertAlign("insert-assert-align", cl::init(true), cl::desc("Insert the experimental `assertalign` node."), cl::ReallyHidden)
static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin)
static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, DILocalVariable *Variable, DebugLoc DL, unsigned Order, SmallVectorImpl< Value * > &Values, DIExpression *Expression)
static bool prepareDAGLevelOperands(ConstraintDecisionInfo &Info, const CallBase &Call, SelectionDAGBuilder &Builder, const TargetLowering &TLI, SelectionDAG &DAG)
Prepare DAG-level operands.
static unsigned findMatchingInlineAsmOperand(unsigned OperandNo, const std::vector< SDValue > &AsmNodeOperands)
static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, SDISelAsmOperandInfo &MatchingOpInfo, SelectionDAG &DAG)
Make sure that the output operand OpInfo and its corresponding input operand MatchingOpInfo have comp...
static void findUnwindDestinations(FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, BranchProbability Prob, SmallVectorImpl< std::pair< MachineBasicBlock *, BranchProbability > > &UnwindDests)
When an invoke or a cleanupret unwinds to the next EH pad, there are many places it could ultimately ...
static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic)
static BranchProbability scaleCaseProbality(BranchProbability CaseProb, BranchProbability PeeledCaseProb)
static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandExp2 - Lower an exp2 intrinsic.
static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue Scale, SelectionDAG &DAG, const TargetLowering &TLI)
static const GlobalValue * getGlobalAddressDbgOperand(const Value *V, DIExpression *&Expr, unsigned OpIdx, const MachineFunction &MF)
If V is the address of a describable global, possibly displaced by a constant, return the global and ...
static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, const SDLoc &dl)
getF32Constant - Get 32-bit floating point constant.
static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, const SDLoc &DL, EVT PartVT)
static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandLog10 - Lower a log10 intrinsic.
DenseMap< const Argument *, std::pair< const AllocaInst *, const StoreInst * > > ArgCopyElisionMapTy
static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, const Value *V, std::optional< CallingConv::ID > CallConv)
getCopyToPartsVector - Create a series of nodes that contain the specified value split into legal par...
static void getUnderlyingArgRegs(SmallVectorImpl< std::pair< Register, TypeSize > > &Regs, const SDValue &N)
static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, const Value *V, std::optional< CallingConv::ID > CallConv=std::nullopt, ISD::NodeType ExtendKind=ISD::ANY_EXTEND)
getCopyToParts - Create a series of nodes that contain the specified value split into legal parts.
static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, SelectionDAGBuilder &Builder)
static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandLog2 - Lower a log2 intrinsic.
static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, SDISelAsmOperandInfo &OpInfo, SelectionDAG &DAG)
Get a direct memory input to behave well as an indirect operand.
static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel)
isOnlyUsedInEntryBlock - If the specified argument is only used in the entry block,...
static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, const Twine &ErrMsg)
static bool collectInstructionDeps(SmallMapVector< const Instruction *, bool, 8 > *Deps, const Value *V, SmallMapVector< const Instruction *, bool, 8 > *Necessary=nullptr, unsigned Depth=0)
static void findArgumentCopyElisionCandidates(const DataLayout &DL, FunctionLoweringInfo *FuncInfo, ArgCopyElisionMapTy &ArgCopyElisionCandidates)
Scan the entry block of the function in FuncInfo for arguments that look like copies into a local all...
static bool isFunction(SDValue Op)
static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI, const SDLoc &dl)
GetExponent - Get the exponent:
static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg)
static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, SelectionDAG &DAG)
ExpandPowI - Expand a llvm.powi intrinsic.
static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandLog - Lower a log intrinsic.
static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, SDValue InChain, std::optional< CallingConv::ID > CC=std::nullopt, std::optional< ISD::NodeType > AssertOp=std::nullopt)
getCopyFromParts - Create a value that contains the specified legal parts combined into the value the...
static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, SelectionDAG &DAG)
static bool determineConstraints(ConstraintDecisionInfo &Info, TargetLowering::AsmOperandInfoVector &TargetConstraints, const CallBase &Call, SelectionDAGBuilder &Builder, const TargetLowering &TLI, const TargetMachine &TM, SelectionDAG &DAG, const BasicBlock *EHPadBB)
DetermineConstraints - Find the constraints to use for inline asm operands.
static bool constructOperandInfo(ConstraintDecisionInfo &Info, TargetLowering::AsmOperandInfoVector &TargetConstraints, SelectionDAGBuilder &Builder, const TargetLowering &TLI, ExtraFlags &ExtraInfo)
Construct operand info objects.
static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl)
GetSignificand - Get the significand and build it into a floating-point number with exponent of 1:
static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandExp - Lower an exp intrinsic.
static const MDNode * getRangeMetadata(const Instruction &I)
static cl::opt< unsigned, true > LimitFPPrecision("limit-float-precision", cl::desc("Generate low-precision inline sequences " "for some float libcalls"), cl::location(LimitFloatPrecision), cl::Hidden, cl::init(0))
static void tryToElideArgumentCopy(FunctionLoweringInfo &FuncInfo, SmallVectorImpl< SDValue > &Chains, DenseMap< int, int > &ArgCopyElisionFrameIndexMap, SmallPtrSetImpl< const Instruction * > &ElidedArgCopyInstrs, ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, ArrayRef< SDValue > ArgVals, bool &ArgHasUses)
Try to elide argument copies from memory into a local alloca.
static void ensureMatchedVecRegParts(unsigned NumRegs, unsigned NumParts, MVT RegisterVT, MVT PartVT)
Emit a fatal error if the broken down registers don't match part type or count.
static unsigned LimitFloatPrecision
LimitFloatPrecision - Generate low-precision inline sequences for some float libcalls (6,...
static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, SDValue InChain, std::optional< CallingConv::ID > CC)
getCopyFromPartsVector - Create a value that contains the specified legal parts combined into the val...
static bool InBlock(const Value *V, const BasicBlock *BB)
static FPClassTest getNoFPClass(const Instruction &I)
static LLVM_ATTRIBUTE_ALWAYS_INLINE MVT::SimpleValueType getSimpleVT(const uint8_t *MatcherTable, size_t &MatcherIndex)
getSimpleVT - Decode a value in MatcherTable, if it's a VBR encoded value, use GetVBR to decode it.
This file defines the SmallPtrSet class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
TTI::PartialReductionExtendKind ExtendKind
uint16_t RegSizeInBits(const MCRegisterInfo &MRI, MCRegister RegNo)
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static LLVM_ABI Semantics SemanticsToEnum(const llvm::fltSemantics &Sem)
Definition APFloat.cpp:184
static LLVM_ABI const fltSemantics * getArbitraryFPSemantics(StringRef Format)
Returns the fltSemantics for a given arbitrary FP format string, or nullptr if invalid.
Definition APFloat.cpp:6165
Class for arbitrary precision integers.
Definition APInt.h:78
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
an instruction to allocate memory on the stack
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Check if an argument has a given attribute.
Definition Function.cpp:332
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Definition Argument.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
A cache of @llvm.assume calls within a function.
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:406
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
This class represents a no-op cast from one type to another.
The address of a basic block.
Definition Constants.h:1088
Analysis providing branch probability information.
LLVM_ABI BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
LLVM_ABI bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const
Test if an edge is hot relative to other out-edges of the Src.
static constexpr BranchProbability getOne()
static uint32_t getDenominator()
static constexpr BranchProbability getUnknown()
static constexpr BranchProbability getZero()
uint32_t getNumerator() const
LLVM_ABI uint64_t scale(uint64_t Num) const
Scale a large integer.
BranchProbability getCompl() const
static void normalizeProbabilities(ProbabilityIter Begin, ProbabilityIter End)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
CallingConv::ID getCallingConv() const
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
bool isConvergent() const
Determine if the invoke is convergent.
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
LLVM_ABI bool isTailCall() const
Tests if this call site is marked as a tail call.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
This class represents a function call, abstracting a target machine's calling convention.
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
Conditional Branch instruction.
Class for constant bytes.
Definition Constants.h:281
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A signed pointer, in the ptrauth sense.
Definition Constants.h:1223
uint64_t getZExtValue() const
Constant Vector Declarations.
Definition Constants.h:674
This is an important base class in LLVM.
Definition Constant.h:44
This is the common base class for constrained floating point intrinsics.
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI unsigned getNonMetadataArgCount() const
DWARF expression.
LLVM_ABI bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static bool fragmentsOverlap(const FragmentInfo &A, const FragmentInfo &B)
Check if fragments overlap between a pair of FragmentInfos.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
static LLVM_ABI std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
LLVM_ABI uint64_t getNumLocationOperands() const
Return the number of unique location operands referred to (via DW_OP_LLVM_arg) in this expression; th...
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
static LLVM_ABI const DIExpression * convertToUndefExpression(const DIExpression *Expr)
Removes all elements from Expr that do not apply to an undef debug value, which includes every operat...
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
static LLVM_ABI DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false, bool EntryValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
Base class for variables.
LLVM_ABI std::optional< uint64_t > getSizeInBits() const
Determines the size of the variable's type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isBigEndian() const
Definition DataLayout.h:218
Records a position in IR for a source label (DILabel).
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
LLVM_ABI iterator_range< location_op_iterator > location_ops() const
Get the locations corresponding to the variable referenced by the debug info intrinsic.
A debug info location.
Definition DebugLoc.h:126
LLVM_ABI DILocation * getInlinedAt() const
Definition DebugLoc.cpp:58
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:679
void reserve(size_type NumEntries)
Grow the DenseMap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:721
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Diagnostic information for inline asm reporting.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:312
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Class representing an expression and its matching format.
This instruction extracts a struct member or array element value from an aggregate value.
This instruction compares its operands according to the predicate given to the constructor.
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:67
bool allowReassoc() const
Flag queries.
Definition FMF.h:64
An instruction for ordering other memory operations.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
This class represents a freeze function that returns random concrete value if an operand is either a ...
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
BranchProbabilityInfo * BPI
MachineBasicBlock * getMBB(const BasicBlock *BB) const
DenseMap< const AllocaInst *, int > StaticAllocaMap
StaticAllocaMap - Keep track of frame indices for fixed sized allocas in the entry block.
const LiveOutInfo * GetLiveOutRegInfo(Register Reg)
GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the register is a PHI destinat...
MachineBasicBlock * MBB
MBB - The current block.
Class to represent function types.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Type * getParamType(unsigned i) const
Parameter type accessors.
Type * getReturnType() const
Data structure describing the variable locations in a function.
const BasicBlock & getEntryBlock() const
Definition Function.h:794
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:247
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
check if an attributes is in the list of attributes.
Definition Function.cpp:743
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
Constant * getPersonalityFn() const
Get the personality function associated with this function.
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:252
size_t arg_size() const
Definition Function.h:886
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
Garbage collection metadata for a single function.
Definition GCMetadata.h:80
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
bool isInBounds() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
bool hasDLLImportStorageClass() const
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
void setMemConstraint(ConstraintCode C)
setMemConstraint - Augment an existing flag with the constraint code for a memory constraint.
Definition InlineAsm.h:414
This instruction inserts a struct field of array element value into an aggregate value.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
@ MIN_INT_BITS
Minimum number of bits that can be specified.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
static LocationSize precise(uint64_t Value)
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
static LocationSize upperBound(uint64_t Value)
bool usesPerInvokeEHLabels(ExceptionHandling EH) const
Returns true if the exception tables reference the per-invoke EH labels emitted around invokes.
Definition MCAsmInfo.h:684
LLVM_ABI MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
LLVM_ABI MCSymbol * getOrCreateFrameAllocSymbol(const Twine &FuncName, unsigned Idx)
Gets a symbol that will be defined to the final stack offset of a local variable after codegen.
const MCAsmInfo & getAsmInfo() const
Definition MCContext.h:411
unsigned getID() const
getID() - Return the register class ID number.
const MCPhysReg * iterator
iterator begin() const
begin/end - Return all of the registers in this class.
iterator end() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:615
Machine Value Type.
@ INVALID_SIMPLE_VALUE_TYPE
uint64_t getScalarSizeInBits() const
unsigned getVectorNumElements() const
bool isVector() const
Return true if this is a vector value type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
std::string getString() const
Return the value type as a string, e.g. i32.
ElementCount getVectorElementCount() const
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
bool bitsGE(MVT VT) const
Return true if this has no less bits than VT.
bool isScalarInteger() const
Return true if this is an integer, not including vectors.
static MVT getVectorVT(MVT VT, unsigned NumElements)
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
bool isValid() const
Return true if this is a valid simple valuetype.
static MVT getIntegerVT(unsigned BitWidth)
void normalizeSuccProbs()
Normalize probabilities of all successors so that the sum of them becomes one.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void setSuccProbability(succ_iterator I, BranchProbability Prob)
Set successor probability of a given iterator.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
SmallVectorImpl< MachineBasicBlock * >::iterator succ_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void setIsEHContTarget(bool V=true)
Indicates if this is a target of Windows EH Continuation Guard.
void setIsEHFuncletEntry(bool V=true)
Indicates if this is the entry block of an EH funclet.
MachineInstrBundleIterator< MachineInstr > iterator
void setIsEHScopeEntry(bool V=true)
Indicates if this is the entry block of an EH scope, i.e., the block that that used to have a catchpa...
void setMachineBlockAddressTaken()
Set this block to indicate that its address is used as something other than the target of a terminato...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void setIsImmutableObjectIndex(int ObjectIdx, bool IsImmutable)
Marks the immutability of an object.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
bool hasOpaqueSPAdjustment() const
Returns true if the function contains opaque dynamic stack adjustments.
int getStackProtectorIndex() const
Return the index for the stack protector object.
void setIsAliasedObjectIndex(int ObjectIdx, bool IsAliased)
Set "maybe pointed to by an LLVM IR value" for an object.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
void RemoveStackObject(int ObjectIdx)
Remove or mark dead a statically sized stack object.
void setFunctionContextIndex(int I)
const WinEHFuncInfo * getWinEHFuncInfo() const
getWinEHFuncInfo - Return information about how the current function uses Windows exception handling.
bool useDebugInstrRef() const
Returns true if the function's variable locations are tracked with instruction referencing.
void setCallSiteBeginLabel(MCSymbol *BeginLabel, unsigned Site)
Map the begin label for a call site.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
void addCodeViewAnnotation(MCSymbol *Label, MDNode *MD)
Record annotations associated with a particular label.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
void setHasEHContTarget(bool V)
void addInvoke(MachineBasicBlock *LandingPad, MCSymbol *BeginLabel, MCSymbol *EndLabel)
Provide the begin and end labels of an invoke style call and associate it with a try landing pad bloc...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
Representation of each machine instruction.
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MONonTemporal
The memory access is non-temporal.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
static MachineOperand CreateFI(int Idx)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI MCRegister getLiveInPhysReg(Register VReg) const
getLiveInPhysReg - If VReg is a live-in virtual register, return the corresponding live-in physical r...
An SDNode that represents everything that will be needed to construct a MachineInstr.
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition MapVector.h:118
bool contains(const KeyT &Key) const
Definition MapVector.h:148
static MemoryLocation getAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location after Ptr, while remaining within the underlying objec...
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:184
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:358
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
Resume the propagation of an exception.
Return a value (possibly void), from a function.
Holds the information from a dbg_label node through SDISel.
static SDDbgOperand fromNode(SDNode *Node, unsigned ResNo)
static SDDbgOperand fromFrameIdx(unsigned FrameIdx)
static SDDbgOperand fromVReg(Register VReg)
static SDDbgOperand fromConst(const Value *Const)
static SDDbgOperand fromGlobalAddr(const GlobalValue *GV)
Holds the information from a dbg_value node through SDISel.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
const DebugLoc & getDebugLoc() const
Represents one node in the SelectionDAG.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
iterator_range< value_op_iterator > op_values() const
unsigned getIROrder() const
Return the node ordering.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getOpcode() const
SelectionDAGBuilder - This is the common target-independent lowering implementation that is parameter...
SDValue getValue(const Value *V)
getValue - Return an SDValue for the given Value.
bool shouldKeepJumpConditionsTogether(const FunctionLoweringInfo &FuncInfo, const CondBrInst &I, Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, TargetLoweringBase::CondMergingParams Params) const
DenseMap< const Constant *, Register > ConstantsOut
void addDanglingDebugInfo(SmallVectorImpl< Value * > &Values, DILocalVariable *Var, DIExpression *Expr, bool IsVariadic, DebugLoc DL, unsigned Order)
Register a dbg_value which relies on a Value which we have not yet seen.
void visitDbgInfo(const Instruction &I)
void clearDanglingDebugInfo()
Clear the dangling debug information map.
SDValue lowerStartEH(SDValue Chain, const BasicBlock *EHPadBB, MCSymbol *&BeginLabel)
void LowerCallTo(const CallBase &CB, SDValue Callee, bool IsTailCall, bool IsMustTailCall, const BasicBlock *EHPadBB=nullptr, const TargetLowering::PtrAuthInfo *PAI=nullptr)
void clear()
Clear out the current SelectionDAG and the associated state and prepare this SelectionDAGBuilder obje...
void visitBitTestHeader(SwitchCG::BitTestBlock &B, MachineBasicBlock *SwitchBB)
visitBitTestHeader - This function emits necessary code to produce value suitable for "bit tests"
void LowerStatepoint(const GCStatepointInst &I, const BasicBlock *EHPadBB=nullptr)
std::unique_ptr< SDAGSwitchLowering > SL
SDValue lowerRangeToAssertZExt(SelectionDAG &DAG, const Instruction &I, SDValue Op)
bool HasTailCall
This is set to true if a call in the current block has been translated as a tail call.
bool ShouldEmitAsBranches(const std::vector< SwitchCG::CaseBlock > &Cases)
If the set of cases should be emitted as a series of branches, return true.
void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB, MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB, BranchProbability TProb, BranchProbability FProb, bool InvertCond)
EmitBranchForMergedCondition - Helper method for FindMergedConditions.
void LowerDeoptimizeCall(const CallInst *CI)
void LowerCallSiteWithDeoptBundle(const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB)
SwiftErrorValueTracking & SwiftError
Information about the swifterror values used throughout the function.
SDValue getNonRegisterValue(const Value *V)
getNonRegisterValue - Return an SDValue for the given Value, but don't look in FuncInfo....
const TargetTransformInfo * TTI
DenseMap< MachineBasicBlock *, SmallVector< unsigned, 4 > > LPadToCallSiteMap
Map a landing pad to the call site indexes.
SDValue lowerNoFPClassToAssertNoFPClass(SelectionDAG &DAG, const Instruction &I, SDValue Op)
void handleDebugDeclare(Value *Address, DILocalVariable *Variable, DIExpression *Expression, DebugLoc DL)
StatepointLoweringState StatepointLowering
State used while lowering a statepoint sequence (gc_statepoint, gc_relocate, and gc_result).
void setValueToPoison(const Value *V, const SDLoc &dl)
void visitBitTestCase(SwitchCG::BitTestBlock &BB, MachineBasicBlock *NextMBB, BranchProbability BranchProbToNext, Register Reg, SwitchCG::BitTestCase &B, MachineBasicBlock *SwitchBB)
visitBitTestCase - this function produces one "bit test"
bool canTailCall(const CallBase &CB) const
void populateCallLoweringInfo(TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, AttributeSet RetAttrs, bool IsPatchPoint)
Populate a CallLowerinInfo (into CLI) based on the properties of the call being lowered.
void CopyValueToVirtualRegister(const Value *V, Register Reg, ISD::NodeType ExtendType=ISD::ANY_EXTEND)
void salvageUnresolvedDbgValue(const Value *V, DanglingDebugInfo &DDI)
For the given dangling debuginfo record, perform last-ditch efforts to resolve the debuginfo to somet...
SmallVector< SDValue, 8 > PendingLoads
Loads are not emitted to the program immediately.
GCFunctionInfo * GFI
Garbage collection metadata for the function.
void init(GCFunctionInfo *gfi, BatchAAResults *BatchAA, AssumptionCache *AC, const TargetLibraryInfo *li, const TargetTransformInfo &TTI)
SDValue getRoot()
Similar to getMemoryRoot, but also flushes PendingConstrainedFP(Strict) items.
void ExportFromCurrentBlock(const Value *V)
ExportFromCurrentBlock - If this condition isn't known to be exported from the current basic block,...
void resolveOrClearDbgInfo()
Evict any dangling debug information, attempting to salvage it first.
std::pair< SDValue, SDValue > lowerInvokable(TargetLowering::CallLoweringInfo &CLI, const BasicBlock *EHPadBB=nullptr)
SDValue getMemoryRoot()
Return the current virtual root of the Selection DAG, flushing any PendingLoad items.
void resolveDanglingDebugInfo(const Value *V, SDValue Val)
If we saw an earlier dbg_value referring to V, generate the debug data structures now that we've seen...
void visit(const Instruction &I)
void dropDanglingDebugInfo(const DILocalVariable *Variable, const DIExpression *Expr)
If we have dangling debug info that describes Variable, or an overlapping part of variable considerin...
SDValue getCopyFromRegs(const Value *V, Type *Ty)
If there was virtual register allocated for the value V emit CopyFromReg of the specified type Ty.
void CopyToExportRegsIfNeeded(const Value *V)
CopyToExportRegsIfNeeded - If the given value has virtual registers created for it,...
void handleKillDebugValue(DILocalVariable *Var, DIExpression *Expr, DebugLoc DbgLoc, unsigned Order)
Create a record for a kill location debug intrinsic.
void visitJumpTable(SwitchCG::JumpTable &JT)
visitJumpTable - Emit JumpTable node in the current MBB
SDValue getFPOperationRoot(fp::ExceptionBehavior EB)
Return the current virtual root of the Selection DAG, flushing PendingConstrainedFP or PendingConstra...
void visitJumpTableHeader(SwitchCG::JumpTable &JT, SwitchCG::JumpTableHeader &JTH, MachineBasicBlock *SwitchBB)
visitJumpTableHeader - This function emits necessary code to produce index in the JumpTable from swit...
void LowerCallSiteWithPtrAuthBundle(const CallBase &CB, const BasicBlock *EHPadBB)
static const unsigned LowestSDNodeOrder
Lowest valid SDNodeOrder.
FunctionLoweringInfo & FuncInfo
Information about the function as a whole.
void setValue(const Value *V, SDValue NewN)
void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB, MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB, Instruction::BinaryOps Opc, BranchProbability TProb, BranchProbability FProb, bool InvertCond)
const TargetLibraryInfo * LibInfo
bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB)
void visitSPDescriptorParent(StackProtectorDescriptor &SPD, MachineBasicBlock *ParentBB)
Codegen a new tail for a stack protector check ParentMBB which has had its tail spliced into a stack ...
bool handleDebugValue(ArrayRef< const Value * > Values, DILocalVariable *Var, DIExpression *Expr, DebugLoc DbgLoc, unsigned Order, bool IsVariadic)
For a given list of Values, attempt to create and record a SDDbgValue in the SelectionDAG.
SDValue getControlRoot()
Similar to getRoot, but instead of flushing all the PendingLoad items, flush all the PendingExports (...
void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last)
When an MBB was split during scheduling, update the references that need to refer to the last resulti...
SDValue getValueImpl(const Value *V)
getValueImpl - Helper function for getValue and getNonRegisterValue.
void visitSwitchCase(SwitchCG::CaseBlock &CB, MachineBasicBlock *SwitchBB)
visitSwitchCase - Emits the necessary code to represent a single node in the binary search tree resul...
void visitSPDescriptorFailure(StackProtectorDescriptor &SPD)
Codegen the failure basic block for a stack protector check.
std::unique_ptr< FunctionLoweringInfo > FuncInfo
SmallPtrSet< const Instruction *, 4 > ElidedArgCopyInstrs
const TargetLowering * TLI
MachineRegisterInfo * RegInfo
std::unique_ptr< SwiftErrorValueTracking > SwiftError
virtual void emitFunctionEntryCode()
std::unique_ptr< SelectionDAGBuilder > SDB
virtual std::pair< SDValue, SDValue > EmitTargetCodeForMemccpy(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, SDValue C, SDValue Size, const CallInst *CI) const
Emit target-specific code that performs a memccpy, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrnlen(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, SDValue Src, SDValue MaxLength, MachinePointerInfo SrcPtrInfo) const
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrlen(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, SDValue Src, const CallInst *CI) const
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrstr(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Op1, SDValue Op2, const CallInst *CI) const
Emit target-specific code that performs a strstr, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForMemchr(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Src, SDValue Char, SDValue Length, MachinePointerInfo SrcPtrInfo) const
Emit target-specific code that performs a memchr, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrcmp(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Op1, SDValue Op2, MachinePointerInfo Op1PtrInfo, MachinePointerInfo Op2PtrInfo, const CallInst *CI) const
Emit target-specific code that performs a strcmp, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForMemcmp(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Op1, SDValue Op2, SDValue Op3, const CallInst *CI) const
Emit target-specific code that performs a memcmp/bcmp, in cases where that is faster than a libcall.
virtual SDValue EmitTargetCodeForSetTag(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Addr, SDValue Size, MachinePointerInfo DstPtrInfo, bool ZeroData) const
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrcpy(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, SDValue Dest, SDValue Src, MachinePointerInfo DestPtrInfo, MachinePointerInfo SrcPtrInfo, bool isStpcpy, const CallInst *CI) const
Emit target-specific code that performs a strcpy or stpcpy, in cases where that is faster than a libc...
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT, unsigned Opcode)
Convert Op, which must be of integer type, to the integer type VT, by either any/sign/zero-extending ...
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI void ExtractVectorElements(SDValue Op, SmallVectorImpl< SDValue > &Args, unsigned Start=0, unsigned Count=0, EVT EltVT=EVT())
Append the extracted elements from Start to Count out of the vector Op in Args.
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
LLVM_ABI bool shouldOptForSize() const
const TargetLowering & getTargetLoweringInfo() const
static constexpr unsigned MaxRecursionDepth
LLVM_ABI void AddDbgValue(SDDbgValue *DB, bool isParameter)
Add a dbg_value SDNode.
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
LLVM_ABI SDDbgValue * getDbgValueList(DIVariable *Var, DIExpression *Expr, ArrayRef< SDDbgOperand > Locs, ArrayRef< SDNode * > Dependencies, bool IsIndirect, const DebugLoc &DL, unsigned O, bool IsVariadic)
Creates a SDDbgValue node from a list of locations.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
const DataLayout & getDataLayout() const
SDValue getTargetFrameIndex(int FI, EVT VT)
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
LLVM_ABI SDValue getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI SDValue getBasicBlock(MachineBasicBlock *MBB)
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getEHLabel(const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI SDValue getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either truncating it or perform...
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
const LibcallLoweringInfo & getLibcalls() const
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
MachineFunction & getMachineFunction() const
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVMContext * getContext() const
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void swap(SmallVectorImpl &RHS)
void resize(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Encapsulates all of the information needed to generate a stack protector check, and signals to isel w...
MachineBasicBlock * getSuccessMBB()
MachineBasicBlock * getFailureMBB()
MachineBasicBlock * getParentMBB()
bool shouldEmitFunctionBasedCheckStackProtector() const
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Multiway switch.
Information about stack frame layout on the target.
virtual TargetStackID::Value getStackIDForScalableVectors() const
Returns the StackID that scalable vectors should be associated with.
Provides information about what library functions are available for the current target.
virtual Align getByValTypeAlignment(Type *Ty, const DataLayout &DL) const
Returns the desired alignment for ByVal or InAlloca aggregate function arguments in the caller parame...
virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT) const
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
EVT getMemValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
virtual bool isAtomicAlignmentSupported(Align Alignment, uint64_t SizeInBytes) const
Return true if the target supports an atomic access of SizeInBytes bytes at the given Alignment.
Function * getSSPStackGuardCheck(const Module &M, const LibcallLoweringInfo &Libcalls) const
If the target has a standard stack protection check function that performs validation and error handl...
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
LegalizeAction
This enum indicates whether operations are valid for a target, and if not, what action should be used...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
virtual bool isLegalScaleForGatherScatter(uint64_t Scale, uint64_t ElemSize) const
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
virtual MachineMemOperand::Flags getTargetMMOFlags(const Instruction &I) const
This callback is used to inspect load/store instructions and add target-specific MachineMemOperand fl...
virtual Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception typeid on entry to a la...
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
virtual bool useStackGuardMixFP() const
If this function returns true, stack protection checks should mix the frame pointer (or whichever poi...
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
virtual unsigned getNumRegisters(LLVMContext &Context, EVT VT, std::optional< MVT > RegisterVT=std::nullopt) const
Return the number of registers that this ValueType will eventually require.
MachineMemOperand::Flags getLoadMemOperandFlags(const LoadInst &LI, const DataLayout &DL, AssumptionCache *AC=nullptr, const TargetLibraryInfo *LibInfo=nullptr, CodeGenOptLevel OptLevel=CodeGenOptLevel::Default) const
virtual bool shouldExtendGSIndex(EVT VT, EVT &EltTy) const
Returns true if the index type for a masked gather/scatter requires extending.
virtual unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
LegalizeAction getFixedPointOperationAction(unsigned Op, EVT VT, unsigned Scale) const
Some fixed point operations may be natively supported by the target but only for specific scales.
MachineMemOperand::Flags getAtomicMemOperandFlags(const Instruction &AI, const DataLayout &DL) const
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
bool isOperationCustom(unsigned Op, EVT VT) const
Return true if the operation uses custom lowering, regardless of whether the type is legal or not.
bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const
When splitting a value of the specified type into parts, does the Lo or Hi part come first?
EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const
Returns the type for the shift amount of a shift opcode.
virtual Align getABIAlignmentForCallingConv(Type *ArgTy, const DataLayout &DL) const
Certain targets have context sensitive alignment requirements, where one type has the alignment requi...
MachineMemOperand::Flags getVPIntrinsicMemOperandFlags(const VPIntrinsic &VPIntrin) const
virtual bool shouldExpandGetActiveLaneMask(EVT VT, EVT OpVT) const
Return true if the @llvm.get.active.lane.mask intrinsic should be expanded using generic code in Sele...
virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const
Return the ValueType of the result of SETCC operations.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
MVT getProgramPointerTy(const DataLayout &DL) const
Return the type for code pointers, which is determined by the program address space specified through...
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const
virtual MVT getFenceOperandTy(const DataLayout &DL) const
Return the type for operands of fence.
virtual bool shouldExpandGetVectorLength(EVT CountVT, unsigned VF, bool IsScalable) const
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Vector types are broken down into some number of legal first class types.
virtual MVT hasFastEqualityCompare(unsigned NumBits) const
Return the preferred operand type if the target has a quick way to compare integer values of the give...
MachineMemOperand::Flags getStoreMemOperandFlags(const StoreInst &SI, const DataLayout &DL) const
virtual void getTgtMemIntrinsic(SmallVectorImpl< IntrinsicInfo > &Infos, const CallBase &I, MachineFunction &MF, unsigned Intrinsic) const
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
virtual bool signExtendConstant(const ConstantInt *C) const
Return true if this constant should be sign extended when promoting to a larger type.
virtual Value * getSDagStackGuard(const Module &M, const LibcallLoweringInfo &Libcalls) const
Return the variable that's previously inserted by insertSSPDeclarations, if any, otherwise return nul...
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
std::vector< ArgListEntry > ArgListTy
virtual Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception address on entry to an ...
bool isBeneficialToExpandPowI(int64_t Exponent, bool OptForSize) const
Return true if it is beneficial to expand an @llvm.powi.
MVT getFrameIndexTy(const DataLayout &DL) const
Return the type for frame index, which is determined by the alloca address space specified through th...
virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS=0) const
Return the in-memory pointer type for the given address space, defaults to the pointer type from the ...
virtual MVT getVPExplicitVectorLengthTy() const
Returns the type to be used for the EVL/AVL operand of VP nodes: ISD::VP_UDIV, ISD::VP_SDIV,...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual bool supportKCFIBundles() const
Return true if the target supports kcfi operand bundles.
virtual bool supportPtrAuthBundles() const
Return true if the target supports ptrauth operand bundles.
virtual bool supportSwiftError() const
Return true if the target supports swifterror attribute.
virtual SDValue visitMaskedLoad(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, MachineMemOperand *MMO, SDValue &NewLoad, SDValue Ptr, SDValue PassThru, SDValue Mask) const
virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT, ISD::NodeType) const
Return the type that should be used to zero or sign extend a zeroext/signext integer return value.
virtual Register getRegisterByName(const char *RegName, LLT Ty, const MachineFunction &MF) const
Return the register ID of the name passed in.
virtual InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const
std::vector< AsmOperandInfo > AsmOperandInfoVector
SDValue expandIS_FPCLASS(EVT ResultVT, SDValue Op, FPClassTest Test, SDNodeFlags Flags, const SDLoc &DL, SelectionDAG &DAG) const
Expand check for floating point class.
virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL, SelectionDAG &DAG) const
This callback is used to prepare for a volatile or atomic load.
virtual SDValue emitStackGuardMixFP(SelectionDAG &DAG, SDValue Val, const SDLoc &DL) const
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual bool splitValueIntoRegisterParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, std::optional< CallingConv::ID > CC) const
Target-specific splitting of values into parts that fit a register storing a legal type.
virtual SDValue joinRegisterPartsIntoValue(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, std::optional< CallingConv::ID > CC) const
Target-specific combining of register parts into its original value.
virtual SDValue LowerCall(CallLoweringInfo &, SmallVectorImpl< SDValue > &) const
This hook must be implemented to lower calls into the specified DAG.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
virtual bool supportsInlineAsmFuncOperands() const
Return true if a function used as an inline asm address operand (e.g.
virtual SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Glue, const SDLoc &DL, const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, const CallBase &Call) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const
This callback is invoked for operations that are unsupported by the target, which are registered to u...
virtual bool functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv, bool isVarArg, const DataLayout &DL) const
For some targets, an LLVM struct type must be broken down into multiple simple types,...
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo,...
virtual void CollectTargetIntrinsicOperands(const CallInst &I, SmallVectorImpl< SDValue > &Ops, SelectionDAG &DAG) const
virtual SDValue visitMaskedStore(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, MachineMemOperand *MMO, SDValue Ptr, SDValue Val, SDValue Mask) const
virtual bool useLoadStackGuardNode(const Module &M) const
If this function returns true, SelectionDAGBuilder emits a LOAD_STACK_GUARD node when it is lowering ...
SDValue annotateStackObjectPointer(SDValue Ptr, SelectionDAG &DAG, const SDLoc &DL, Align Alignment) const
Annotate a stack object pointer with known-bits assertions.
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
virtual void LowerOperationWrapper(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const
This callback is invoked by the type legalizer to legalize nodes with an illegal operand type but leg...
virtual bool isInlineAsmTargetBranch(const SmallVectorImpl< StringRef > &AsmStrs, unsigned OpNo) const
On x86, return true if the operand with index OpNo is a CALL or JUMP instruction, which can use eithe...
virtual MVT getJumpTableRegTy(const DataLayout &DL) const
virtual bool CanLowerReturn(CallingConv::ID, MachineFunction &, bool, const SmallVectorImpl< ISD::OutputArg > &, LLVMContext &, const Type *RetTy) const
This hook should be implemented to check whether the return values described by the Outs array can fi...
Primary interface to the complete machine description for the target machine.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
CodeModel::Model getCodeModel() const
Returns the code model.
unsigned NoTrapAfterNoreturn
Do not emit a trap instruction for 'unreachable' IR instructions behind noreturn calls,...
unsigned TrapUnreachable
Emit target-specific trap instruction for 'unreachable' IR instructions.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_Latency
The latency of instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI bool isEmptyTy() const
Return true if this type is empty, that is, it has no elements or all of its elements are empty.
Definition Type.cpp:170
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:231
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
Unconditional Branch instruction.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_iterator op_begin()
Definition User.h:259
unsigned getNumOperands() const
Definition User.h:229
op_iterator op_end()
Definition User.h:261
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
This is the common base class for vector predication intrinsics.
static LLVM_ABI std::optional< unsigned > getVectorLengthParamPos(Intrinsic::ID IntrinsicID)
LLVM_ABI MaybeAlign getPointerAlignment() const
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:708
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
Base class of all SIMD vector types.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:231
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
const ParentTy * getParent() const
Definition ilist_node.h:34
A raw_ostream that writes to an std::string.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ CONVERGENCECTRL_ANCHOR
The llvm.experimental.convergence.* intrinsics.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:47
@ SET_FPENV
Sets the current floating-point environment.
@ ATOMIC_LOAD_FMINIMUMNUM
@ LOOP_DEPENDENCE_RAW_MASK
@ MASK_BEFOREFIRST
Has one mask vector operand.
@ VECREDUCE_SEQ_FADD
Generic reduction nodes.
@ COND_LOOP
COND_LOOP is a conditional branch to self, used for implementing efficient conditional traps.
@ EH_SJLJ_LONGJMP
OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer) This corresponds to the eh.sjlj.longjmp intrinsic.
Definition ISDOpcodes.h:170
@ VECREDUCE_FMINIMUMNUM
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ STACKADDRESS
STACKADDRESS - Represents the llvm.stackaddress intrinsic.
Definition ISDOpcodes.h:129
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:805
@ SMULFIX
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition ISDOpcodes.h:397
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ RESET_FPENV
Set floating-point environment to default state.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ SMULFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:403
@ SET_FPMODE
Sets the current dynamic floating-point control modes.
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:879
@ CTTZ_ELTS
Returns the number of number of trailing (least significant) zero elements in a vector.
@ ATOMIC_LOAD_USUB_COND
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ VECTOR_FIND_LAST_ACTIVE
Finds the index of the last active mask element Operands: Mask.
@ FMODF
FMODF - Decomposes the operand into integral and fractional parts, each having the same type and sign...
@ FATAN2
FATAN2 - atan2, inspired by libm.
@ FSINCOSPI
FSINCOSPI - Compute both the sine and cosine times pi more accurately than FSINCOS(pi*x),...
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ EH_SJLJ_SETUP_DISPATCH
OUTCHAIN = EH_SJLJ_SETUP_DISPATCH(INCHAIN) The target initializes the dispatch table here.
Definition ISDOpcodes.h:174
@ GlobalAddress
Definition ISDOpcodes.h:90
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:906
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ VECREDUCE_FMAXIMUM
FMINIMUM/FMAXIMUM nodes propatate NaNs and signed zeroes using the llvm.minimum and llvm....
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:765
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ RESET_FPMODE
Sets default dynamic floating-point control modes.
@ FMULADD
FMULADD - Performs a * b + c, with, or without, intermediate rounding.
Definition ISDOpcodes.h:533
@ FPTRUNC_ROUND
FPTRUNC_ROUND - This corresponds to the fptrunc_round intrinsic.
Definition ISDOpcodes.h:520
@ FAKE_USE
FAKE_USE represents a use of the operand but does not do anything.
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:796
@ INIT_TRAMPOLINE
INIT_TRAMPOLINE - This corresponds to the init_trampoline intrinsic.
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ SDIVFIX
RESULT = [US]DIVFIX(LHS, RHS, SCALE) - Perform fixed point division on 2 integers with the same width...
Definition ISDOpcodes.h:410
@ CONVERT_FROM_ARBITRARY_FP
CONVERT_FROM_ARBITRARY_FP - This operator converts from an arbitrary floating-point represented as an...
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
@ ATOMIC_LOAD_USUB_SAT
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:814
@ EH_RETURN
OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER) - This node represents 'eh_return' gcc dwarf builtin,...
Definition ISDOpcodes.h:158
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
@ SET_ROUNDING
Set rounding mode.
@ CONVERGENCECTRL_GLUE
This does not correspond to any convergence control intrinsic.
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:870
@ PREALLOCATED_SETUP
PREALLOCATED_SETUP - This has 2 operands: an input chain and a SRCVALUE with the preallocated call Va...
@ READSTEADYCOUNTER
READSTEADYCOUNTER - This corresponds to the readfixedcounter intrinsic.
@ ADDROFRETURNADDR
ADDROFRETURNADDR - Represents the llvm.addressofreturnaddress intrinsic.
Definition ISDOpcodes.h:119
@ CONVERGENCECTRL_ENTRY
@ BR
Control flow instructions. These all have token chains.
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ PARTIAL_REDUCE_FMLA
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ VECREDUCE_FMAXIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM nodes do not propagate NaNs and order signed zeroes using the llvm....
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ PREALLOCATED_ARG
PREALLOCATED_ARG - This has 3 operands: an input chain, a SRCVALUE with the preallocated call Value,...
@ BRIND
BRIND - Indirect branch.
@ BR_JT
BR_JT - Jumptable branch.
@ VECTOR_INTERLEAVE
VECTOR_INTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor to...
Definition ISDOpcodes.h:640
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:822
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:682
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ GET_ACTIVE_LANE_MASK
GET_ACTIVE_LANE_MASK - this corrosponds to the llvm.get.active.lane.mask intrinsic.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
Definition ISDOpcodes.h:996
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:714
@ CLEANUPRET
CLEANUPRET - Represents a return from a cleanup block funclet.
@ ATOMIC_LOAD_FMAXIMUM
@ GET_FPMODE
Reads the current dynamic floating-point control modes.
@ GET_FPENV
Gets the current floating-point environment.
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:787
@ AssertNoFPClass
AssertNoFPClass - These nodes record if a register contains a float value that is known to be not som...
Definition ISDOpcodes.h:80
@ PtrAuthGlobalAddress
A ptrauth constant.
Definition ISDOpcodes.h:102
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition ISDOpcodes.h:50
@ READ_REGISTER
READ_REGISTER, WRITE_REGISTER - This node represents llvm.register on the DAG, which implements the n...
Definition ISDOpcodes.h:141
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:876
@ DEBUGTRAP
DEBUGTRAP - Trap intended to get the attention of a debugger.
@ VSCALE
VSCALE(IMM) - Returns the runtime scaling factor used to calculate the number of elements within a sc...
@ LOCAL_RECOVER
LOCAL_RECOVER - Represents the llvm.localrecover intrinsic.
Definition ISDOpcodes.h:137
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ UBSANTRAP
UBSANTRAP - Trap with an immediate describing the kind of sanitizer failure.
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:389
@ PATCHPOINT
The llvm.experimental.patchpoint.
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:359
@ ATOMIC_LOAD_FMINIMUM
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:663
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:745
@ MASKED_UDIV
Masked vector arithmetic that returns poison on disabled lanes.
@ VECTOR_REVERSE
VECTOR_REVERSE(VECTOR) - Returns a vector, of the same type as VECTOR, whose elements are shuffled us...
Definition ISDOpcodes.h:650
@ SDIVFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:416
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:831
@ PCMARKER
PCMARKER - This corresponds to the pcmarker intrinsic.
@ INLINEASM_BR
INLINEASM_BR - Branching version of inline asm. Used by asm-goto.
@ ATOMIC_LOAD_FMAXIMUMNUM
@ EH_DWARF_CFA
EH_DWARF_CFA - This node represents the pointer to the DWARF Canonical Frame Address (CFA),...
Definition ISDOpcodes.h:152
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ ATOMIC_LOAD_UDEC_WRAP
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:801
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:505
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:952
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ RELOC_NONE
Issue a no-op relocation against a given symbol at the current location.
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:757
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ SCMP
[US]CMP - 3-way comparison of signed or unsigned integers.
Definition ISDOpcodes.h:753
@ VECTOR_MATCH
VECTOR_MATCH - this corresponds to the llvm.experimental.vector.match intrinsic.
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:667
@ STRICT_FADD
Constrained versions of the binary floating point operators.
Definition ISDOpcodes.h:430
@ STACKMAP
The llvm.experimental.stackmap intrinsic.
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:243
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:813
@ FFREXP
FFREXP - frexp, extract fractional and exponent component of a floating-point value.
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:985
@ VECTOR_COMPRESS
VECTOR_COMPRESS(Vec, Mask, Passthru) consecutively place vector elements based on mask e....
Definition ISDOpcodes.h:709
@ SPONENTRY
SPONENTRY - Represents the llvm.sponentry intrinsic.
Definition ISDOpcodes.h:124
@ CLEAR_CACHE
llvm.clear_cache intrinsic Operands: Input Chain, Start Addres, End Address Outputs: Output Chain
@ CONVERGENCECTRL_LOOP
@ INLINEASM
INLINEASM - Represents an inline asm block.
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:971
@ VECREDUCE_FMINIMUM
@ EH_SJLJ_SETJMP
RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer) This corresponds to the eh.sjlj....
Definition ISDOpcodes.h:164
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:882
@ BRCOND
BRCOND - Conditional branch.
@ VECREDUCE_SEQ_FMUL
@ CONVERT_TO_ARBITRARY_FP
CONVERT_TO_ARBITRARY_FP - Converts a native FP value to an arbitrary floating-point format,...
@ CATCHRET
CATCHRET - Represents a return from a catch block funclet.
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ ATOMIC_LOAD_UINC_WRAP
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ VECTOR_REPEAT
VECTOR_REPEAT(FIXED_LENGTH_VECTOR) Repeatedly copies the elements of the source fixed-length vector t...
Definition ISDOpcodes.h:645
@ VECTOR_DEINTERLEAVE
VECTOR_DEINTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor ...
Definition ISDOpcodes.h:629
@ GET_DYNAMIC_AREA_OFFSET
GET_DYNAMIC_AREA_OFFSET - get offset from native SP to the address of the most recent dynamic alloca.
@ CTTZ_ELTS_ZERO_POISON
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
@ ADJUST_TRAMPOLINE
ADJUST_TRAMPOLINE - This corresponds to the adjust_trampoline intrinsic.
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:769
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
@ LOOP_DEPENDENCE_WAR_MASK
The llvm.loop.dependence.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_VScale()
Matches a call to llvm.vscale().
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
Offsets
Offsets in bytes from the start of the input buffer.
std::pair< JumpTableHeader, JumpTable > JumpTableBlock
LLVM_ABI void sortAndRangeify(CaseClusterVector &Clusters)
Sort Clusters and merge adjacent cases.
std::vector< CaseCluster > CaseClusterVector
@ CC_Range
A cluster of adjacent case labels with the same destination, or just one case.
@ CC_JumpTable
A cluster of cases suitable for jump table lowering.
@ CC_BitTests
A cluster of cases suitable for bit test lowering.
SmallVector< SwitchWorkListItem, 4 > SwitchWorkList
CaseClusterVector::iterator CaseClusterIt
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition Dwarf.h:149
ExceptionBehavior
Exception behavior used for floating point operations.
Definition FPEnv.h:39
@ ebStrict
This corresponds to "fpexcept.strict".
Definition FPEnv.h:42
@ ebMayTrap
This corresponds to "fpexcept.maytrap".
Definition FPEnv.h:41
@ ebIgnore
This corresponds to "fpexcept.ignore".
Definition FPEnv.h:40
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:694
constexpr float log2ef
Definition MathExtras.h:52
constexpr double e
constexpr float ln2f
Definition MathExtras.h:50
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
Type * getValueType(Value *V, bool ReVec, bool LookThroughCmp)
Returns the "element type" of the given value/instruction V.
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
LLVM_ABI bool canDescribeGlobalAddressInLocationList(const MachineFunction &MF)
Test if the debug info for MF can name a describable global address in a location list too,...
Definition Analysis.cpp:642
LLVM_ABI ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred)
getICmpCondCode - Return the ISD condition code corresponding to the given LLVM IR integer condition ...
Definition Analysis.cpp:248
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:61
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
SDValue peekThroughFreeze(SDValue V)
Return the non-frozen source operand of V if it exists.
LLVM_ABI void GetReturnInfo(CallingConv::ID CC, Type *ReturnType, AttributeList attr, SmallVectorImpl< ISD::OutputArg > &Outs, const TargetLowering &TLI, const DataLayout &DL)
Given an LLVM IR type and return type attributes, compute the return value EVTs and flags,...
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Unknown
Not known to have no common set bits.
LLVM_ABI void ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL, Type *Ty, SmallVectorImpl< EVT > &ValueVTs, SmallVectorImpl< EVT > *MemVTs=nullptr, SmallVectorImpl< TypeSize > *Offsets=nullptr, TypeSize StartingOffset=TypeSize::getZero())
ComputeValueVTs - Given an LLVM IR type, compute a sequence of EVTs that represent all the individual...
Definition Analysis.cpp:121
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
LLVM_ABI void diagnoseDontCall(const CallInst &CI)
auto successors(const MachineBasicBlock *BB)
LLVM_ABI bool isExceptionPointerAndSelectorType(Type *Ty)
Return true if landingpad result type Ty is a struct of an exception pointer (pointer or integer) and...
Definition Analysis.cpp:201
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
bool isIntOrFPConstant(SDValue V)
Return true if V is either a integer or FP constant.
static ConstantRange getRange(Value *Op, SCCPSolver &Solver, const SmallPtrSetImpl< Value * > &InsertedValues)
Helper for getting ranges from Solver.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
auto cast_or_null(const Y &Val)
Definition Casting.h:714
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI LLT getLLTForMVT(MVT Ty)
Get a rough equivalent of an LLT for a given MVT.
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1167
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI void ComputeValueTypes(const DataLayout &DL, Type *Ty, SmallVectorImpl< Type * > &Types, SmallVectorImpl< TypeSize > *Offsets=nullptr, TypeSize StartingOffset=TypeSize::getZero())
Given an LLVM IR type, compute non-aggregate subtypes.
Definition Analysis.cpp:74
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
@ SPF_FMINNUM
Unsigned maximum.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
detail::zippy< detail::zip_first, T, U, Args... > zip_first(T &&t, U &&u, Args &&...args)
zip iterator that, for the sake of efficiency, assumes the first iteratee to be the shortest.
Definition STLExtras.h:869
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI const MDNode * getMemCacheHintMetadata(const Instruction &I, unsigned OperandNo=0)
Return the cache hint metadata node for memory operand OperandNo on I, or nullptr when the instructio...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
generic_gep_type_iterator<> gep_type_iterator
auto succ_size(const MachineBasicBlock *BB)
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
Definition STLExtras.h:300
LLVM_ABI ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred)
getFCmpCondCode - Return the ISD condition code corresponding to the given LLVM IR floating-point con...
Definition Analysis.cpp:214
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI Value * salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Ops, SmallVectorImpl< Value * > &AdditionalValues)
Definition Local.cpp:2306
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Global
Append to llvm.global_dtors.
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
LLVM_ABI bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Or
Bitwise or logical OR of integers.
@ Mul
Product of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CtxI)
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
LLVM_ABI bool isInTailCallPosition(const CallBase &Call, const TargetMachine &TM, bool ReturnsFirstArg=false)
Test if the given instruction is in a position to be optimized with a tail-call.
Definition Analysis.cpp:656
DWARFExpression::Operation Op
@ Dynamic
Denotes mode unknown at compile time.
LLVM_ABI ISD::CondCode getFCmpCodeWithoutNaN(ISD::CondCode CC)
getFCmpCodeWithoutNaN - Given an ISD condition code comparing floats, return the equivalent code if w...
Definition Analysis.cpp:236
LLVM_ABI const GlobalValue * getDescribableGlobalAddress(const Constant *C, int64_t &Offset, const MachineFunction &MF)
If C is the address of a global, possibly displaced by a constant, return that global and set Offset ...
Definition Analysis.cpp:623
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
LLVM_ABI std::optional< RoundingMode > convertStrToRoundingMode(StringRef)
Returns a valid RoundingMode enumerator when given a string that is valid as input in constrained int...
Definition FPEnv.cpp:25
gep_type_iterator gep_type_begin(const User *GEP)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
LLVM_ABI GlobalValue * ExtractTypeInfo(Value *V)
ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Definition Analysis.cpp:183
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
LLVM_ABI Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
LLVM_ABI unsigned ComputeLinearIndex(Type *Ty, const unsigned *Indices, const unsigned *IndicesEnd, unsigned CurIndex=0)
Compute the linearized index of a member in a nested aggregate/struct/array.
Definition Analysis.cpp:35
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
#define NC
Definition regutils.h:42
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:129
uint64_t getScalarStoreSize() const
Definition ValueTypes.h:425
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
ElementCount getVectorElementCount() const
Definition ValueTypes.h:373
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:382
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
EVT changeVectorElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a vector type whose attributes match ourselves with the exception of the element type...
Definition ValueTypes.h:98
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
bool isRISCVVectorTuple() const
Return true if this is a vector value type.
Definition ValueTypes.h:197
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:404
bool isFixedLengthVector() const
Definition ValueTypes.h:199
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
Definition ValueTypes.h:315
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:187
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
EVT changeElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a type whose attributes match ourselves with the exception of the element type that i...
Definition ValueTypes.h:121
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
void setPointerAddrSpace(unsigned AS)
InputArg - This struct carries flags and type information about a single incoming (formal) argument o...
static const unsigned NoArgIndex
Sentinel value for implicit machine-level input arguments.
OutputArg - This struct carries flags and a value for a single outgoing (actual) argument or outgoing...
ConstraintPrefix Type
Type - The basic type of the constraint: input/output/clobber/label.
Definition InlineAsm.h:128
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getUnknownStack(MachineFunction &MF)
Stack memory without other information.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
A lightweight accessor for an operand bundle meant to be passed around by value.
This struct represents the registers (physical or virtual) that a particular set of values is assigne...
SmallVector< std::pair< Register, TypeSize >, 4 > getRegsAndSizes() const
Return a list of registers and their sizes.
RegsForValue()=default
SmallVector< unsigned, 4 > RegCount
This list holds the number of registers for each value.
SmallVector< EVT, 4 > ValueVTs
The value types of the values, which may not be legal, and may need be promoted or synthesized from o...
SmallVector< Register, 4 > Regs
This list holds the registers assigned to the values.
void AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, unsigned MatchingIdx, const SDLoc &dl, SelectionDAG &DAG, std::vector< SDValue > &Ops) const
Add this value to the specified inlineasm node operand list.
SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo, const SDLoc &dl, SDValue &Chain, SDValue *Glue, const Value *V=nullptr) const
Emit a series of CopyFromReg nodes that copies from this value and returns the result as a ValueVTs v...
SmallVector< MVT, 4 > RegVTs
The value types of the registers.
void getCopyToRegs(SDValue Val, SelectionDAG &DAG, const SDLoc &dl, SDValue &Chain, SDValue *Glue, const Value *V=nullptr, ISD::NodeType PreferredExtendType=ISD::ANY_EXTEND) const
Emit a series of CopyToReg nodes that copies the specified value into the registers specified by this...
std::optional< CallingConv::ID > CallConv
Records if this value needs to be treated in an ABI dependant manner, different to normal type legali...
bool occupiesMultipleRegs() const
Check if the total RegCount is greater than one.
These are IR-level optimization flags that may be propagated to SDNodes.
void copyFMF(const FPMathOperator &FPMO)
Propagate the fast-math-flags from an IR FPMathOperator.
void setUnpredictable(bool b)
bool hasAllowReassociation() const
void setNoUnsignedWrap(bool b)
void setNoSignedWrap(bool b)
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342
This structure is used to communicate between SelectionDAGBuilder and SDISel for the code generation ...
SDLoc DL
The debug location of the instruction this CaseBlock was produced from.
static CaseCluster range(const ConstantInt *Low, const ConstantInt *High, MachineBasicBlock *MBB, BranchProbability Prob)
Register Reg
The virtual register containing the index of the jump table entry to jump to.
MachineBasicBlock * Default
The MBB of the default bb, which is a successor of the range check MBB.
unsigned JTI
The JumpTableIndex for this jump table in the function.
MachineBasicBlock * MBB
The MBB into which to emit the code for the indirect jump.
std::optional< SDLoc > SL
The debug location of the instruction this JumpTable was produced from.
This contains information for each constraint that we are lowering.
TargetLowering::ConstraintType ConstraintType
Information about the constraint code, e.g.
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setConvergent(bool Value=true)
CallLoweringInfo & setDeactivationSymbol(GlobalValue *Sym)
CallLoweringInfo & setCFIType(const ConstantInt *Type)
SmallVector< ISD::InputArg, 32 > Ins
Type * OrigRetTy
Original unlegalized return type.
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setIsPatchPoint(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setTailCall(bool Value=true)
CallLoweringInfo & setIsPreallocated(bool Value=true)
CallLoweringInfo & setConvergenceControlToken(SDValue Token)
SmallVector< ISD::OutputArg, 32 > Outs
Type * RetTy
Same as OrigRetTy, or partially legalized for soft float libcalls.
CallLoweringInfo & setChain(SDValue InChain)
CallLoweringInfo & setPtrAuth(PtrAuthInfo Value)
CallLoweringInfo & setCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList, AttributeSet ResultAttrs={})
This structure is used to pass arguments to makeLibCall function.
MakeLibCallOptions & setDiscardResult(bool Value=true)
This structure contains the information necessary for lowering pointer-authenticating indirect calls.
LLVM_ABI void addIPToStateRange(const InvokeInst *II, MCSymbol *InvokeBegin, MCSymbol *InvokeEnd)