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/IntrinsicsBPF.h"
82#include "llvm/IR/IntrinsicsWebAssembly.h"
83#include "llvm/IR/LLVMContext.h"
85#include "llvm/IR/Metadata.h"
86#include "llvm/IR/Module.h"
87#include "llvm/IR/Operator.h"
90#include "llvm/IR/Statepoint.h"
91#include "llvm/IR/Type.h"
92#include "llvm/IR/User.h"
93#include "llvm/IR/Value.h"
94#include "llvm/MC/MCAsmInfo.h"
95#include "llvm/MC/MCContext.h"
100#include "llvm/Support/Debug.h"
108#include <cstddef>
109#include <limits>
110#include <optional>
111#include <tuple>
112
113using namespace llvm;
114using namespace PatternMatch;
115using namespace SwitchCG;
116
117#define DEBUG_TYPE "isel"
118
119/// LimitFloatPrecision - Generate low-precision inline sequences for
120/// some float libcalls (6, 8 or 12 bits).
121static unsigned LimitFloatPrecision;
122
123static cl::opt<bool>
124 InsertAssertAlign("insert-assert-align", cl::init(true),
125 cl::desc("Insert the experimental `assertalign` node."),
127
129 LimitFPPrecision("limit-float-precision",
130 cl::desc("Generate low-precision inline sequences "
131 "for some float libcalls"),
133 cl::init(0));
134
136 "switch-peel-threshold", cl::Hidden, cl::init(66),
137 cl::desc("Set the case probability threshold for peeling the case from a "
138 "switch statement. A value greater than 100 will void this "
139 "optimization"));
140
141// Limit the width of DAG chains. This is important in general to prevent
142// DAG-based analysis from blowing up. For example, alias analysis and
143// load clustering may not complete in reasonable time. It is difficult to
144// recognize and avoid this situation within each individual analysis, and
145// future analyses are likely to have the same behavior. Limiting DAG width is
146// the safe approach and will be especially important with global DAGs.
147//
148// MaxParallelChains default is arbitrarily high to avoid affecting
149// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
150// sequence over this should have been converted to llvm.memcpy by the
151// frontend. It is easy to induce this behavior with .ll code such as:
152// %buffer = alloca [4096 x i8]
153// %data = load [4096 x i8]* %argPtr
154// store [4096 x i8] %data, [4096 x i8]* %buffer
155static const unsigned MaxParallelChains = 64;
156
158 const SDValue *Parts, unsigned NumParts,
159 MVT PartVT, EVT ValueVT, const Value *V,
160 SDValue InChain,
161 std::optional<CallingConv::ID> CC);
162
163/// getCopyFromParts - Create a value that contains the specified legal parts
164/// combined into the value they represent. If the parts combine to a type
165/// larger than ValueVT then AssertOp can be used to specify whether the extra
166/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
167/// (ISD::AssertSext).
168static SDValue
169getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
170 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
171 SDValue InChain,
172 std::optional<CallingConv::ID> CC = std::nullopt,
173 std::optional<ISD::NodeType> AssertOp = std::nullopt) {
174 // Let the target assemble the parts if it wants to
176 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
177 PartVT, ValueVT, CC))
178 return Val;
179
180 if (ValueVT.isVector())
181 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
182 InChain, CC);
183
184 assert(NumParts > 0 && "No parts to assemble!");
185 SDValue Val = Parts[0];
186
187 if (NumParts > 1) {
188 // Assemble the value from multiple parts.
189 if (ValueVT.isInteger()) {
190 unsigned PartBits = PartVT.getSizeInBits();
191 unsigned ValueBits = ValueVT.getSizeInBits();
192
193 // Assemble the power of 2 part.
194 unsigned RoundParts = llvm::bit_floor(NumParts);
195 unsigned RoundBits = PartBits * RoundParts;
196 EVT RoundVT = RoundBits == ValueBits ?
197 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
198 SDValue Lo, Hi;
199
200 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
201
202 if (RoundParts > 2) {
203 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
204 InChain);
205 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
206 PartVT, HalfVT, V, InChain);
207 } else {
208 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
209 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
210 }
211
212 if (DAG.getDataLayout().isBigEndian())
213 std::swap(Lo, Hi);
214
215 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
216
217 if (RoundParts < NumParts) {
218 // Assemble the trailing non-power-of-2 part.
219 unsigned OddParts = NumParts - RoundParts;
220 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
221 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
222 OddVT, V, InChain, CC);
223
224 // Combine the round and odd parts.
225 Lo = Val;
226 if (DAG.getDataLayout().isBigEndian())
227 std::swap(Lo, Hi);
228 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
229 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
230 Hi = DAG.getNode(
231 ISD::SHL, DL, TotalVT, Hi,
232 DAG.getShiftAmountConstant(Lo.getValueSizeInBits(), TotalVT, DL));
233 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
234 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
235 }
236 } else if (PartVT.isFloatingPoint()) {
237 // FP split into multiple FP parts (for ppcf128)
238 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
239 "Unexpected split");
240 SDValue Lo, Hi;
241 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
242 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
243 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
244 std::swap(Lo, Hi);
245 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
246 } else {
247 // FP split into integer parts (soft fp)
248 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
249 !PartVT.isVector() && "Unexpected split");
250 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
251 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
252 InChain, CC);
253 }
254 }
255
256 // There is now one part, held in Val. Correct it to match ValueVT.
257 // PartEVT is the type of the register class that holds the value.
258 // ValueVT is the type of the inline asm operation.
259 EVT PartEVT = Val.getValueType();
260
261 if (PartEVT == ValueVT)
262 return Val;
263
264 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
265 ValueVT.bitsLT(PartEVT)) {
266 // For an FP value in an integer part, we need to truncate to the right
267 // width first.
268 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
269 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
270 }
271
272 // Handle types that have the same size.
273 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
274 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
275
276 // Handle types with different sizes.
277 if (PartEVT.isInteger() && ValueVT.isInteger()) {
278 if (ValueVT.bitsLT(PartEVT)) {
279 // For a truncate, see if we have any information to
280 // indicate whether the truncated bits will always be
281 // zero or sign-extension.
282 if (AssertOp)
283 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
284 DAG.getValueType(ValueVT));
285 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
286 }
287 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
288 }
289
290 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
291 // FP_ROUND's are always exact here.
292 if (ValueVT.bitsLT(Val.getValueType())) {
293
294 SDValue NoChange =
295 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
296
297 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
298 llvm::Attribute::StrictFP)) {
299 return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
300 DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
301 NoChange);
302 }
303
304 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
305 }
306
307 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
308 }
309
310 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
311 // then truncating.
312 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
313 ValueVT.bitsLT(PartEVT)) {
314 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
315 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
316 }
317
318 report_fatal_error("Unknown mismatch in getCopyFromParts!");
319}
320
322 const Twine &ErrMsg) {
324 if (!I)
325 return Ctx.emitError(ErrMsg);
326
327 if (const CallInst *CI = dyn_cast<CallInst>(I))
328 if (CI->isInlineAsm()) {
329 return Ctx.diagnose(DiagnosticInfoInlineAsm(
330 *CI, ErrMsg + ", possible invalid constraint for vector type"));
331 }
332
333 return Ctx.emitError(I, ErrMsg);
334}
335
336/// Emit a fatal error if the broken down registers don't match part type
337/// or count.
338static void ensureMatchedVecRegParts(unsigned NumRegs, unsigned NumParts,
339 MVT RegisterVT, MVT PartVT) {
340 if (NumRegs == NumParts && RegisterVT == PartVT)
341 return;
342
344 Twine("Part count doesn't match vector breakdown! ") + Twine(NumRegs) +
345 " registers, " + Twine(NumParts) + " parts, " + RegisterVT.getString() +
346 " RegisterVT, " + PartVT.getString() + " PartVT");
347}
348
349/// getCopyFromPartsVector - Create a value that contains the specified legal
350/// parts combined into the value they represent. If the parts combine to a
351/// type larger than ValueVT then AssertOp can be used to specify whether the
352/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
353/// ValueVT (ISD::AssertSext).
355 const SDValue *Parts, unsigned NumParts,
356 MVT PartVT, EVT ValueVT, const Value *V,
357 SDValue InChain,
358 std::optional<CallingConv::ID> CallConv) {
359 assert(ValueVT.isVector() && "Not a vector value");
360 assert(NumParts > 0 && "No parts to assemble!");
361 const bool IsABIRegCopy = CallConv.has_value();
362
364 SDValue Val = Parts[0];
365
366 // Handle a multi-element vector.
367 if (NumParts > 1) {
368 EVT IntermediateVT;
369 MVT RegisterVT;
370 unsigned NumIntermediates;
371 unsigned NumRegs;
372
373 if (IsABIRegCopy) {
374 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
375 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
376 NumIntermediates, RegisterVT);
377 } else {
378 NumRegs =
379 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
380 NumIntermediates, RegisterVT);
381 }
382
383 ensureMatchedVecRegParts(NumRegs, NumParts, RegisterVT, PartVT);
384 assert(RegisterVT.getSizeInBits() ==
385 Parts[0].getSimpleValueType().getSizeInBits() &&
386 "Part type sizes don't match!");
387
388 // Assemble the parts into intermediate operands.
389 SmallVector<SDValue, 8> Ops(NumIntermediates);
390 if (NumIntermediates == NumParts) {
391 // If the register was not expanded, truncate or copy the value,
392 // as appropriate.
393 for (unsigned i = 0; i != NumParts; ++i)
394 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
395 V, InChain, CallConv);
396 } else if (NumParts > 0) {
397 // If the intermediate type was expanded, build the intermediate
398 // operands from the parts.
399 assert(NumParts % NumIntermediates == 0 &&
400 "Must expand into a divisible number of parts!");
401 unsigned Factor = NumParts / NumIntermediates;
402 for (unsigned i = 0; i != NumIntermediates; ++i)
403 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
404 IntermediateVT, V, InChain, CallConv);
405 }
406
407 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
408 // intermediate operands.
409 EVT BuiltVectorTy =
410 IntermediateVT.isVector()
412 *DAG.getContext(), IntermediateVT.getScalarType(),
413 IntermediateVT.getVectorElementCount() * NumParts)
415 IntermediateVT.getScalarType(),
416 NumIntermediates);
417 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
419 DL, BuiltVectorTy, Ops);
420 }
421
422 // There is now one part, held in Val. Correct it to match ValueVT.
423 EVT PartEVT = Val.getValueType();
424
425 if (PartEVT == ValueVT)
426 return Val;
427
428 if (PartEVT.isVector()) {
429 // Vector/Vector bitcast.
430 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
431 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
432
433 // If the parts vector has more elements than the value vector, then we
434 // have a vector widening case (e.g. <2 x float> -> <4 x float>).
435 // Extract the elements we want.
436 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
439 (PartEVT.getVectorElementCount().isScalable() ==
440 ValueVT.getVectorElementCount().isScalable()) &&
441 "Cannot narrow, it would be a lossy transformation");
442 PartEVT =
444 ValueVT.getVectorElementCount());
445 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
446 DAG.getVectorIdxConstant(0, DL));
447 if (PartEVT == ValueVT)
448 return Val;
449 if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
450 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
451
452 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
453 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
454 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
455 }
456
457 // Promoted vector extract
458 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
459 }
460
461 // Trivial bitcast if the types are the same size and the destination
462 // vector type is legal.
463 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
464 TLI.isTypeLegal(ValueVT))
465 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
466
467 if (ValueVT.getVectorNumElements() != 1) {
468 // Certain ABIs require that vectors are passed as integers. For vectors
469 // are the same size, this is an obvious bitcast.
470 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
471 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
472 } else if (ValueVT.bitsLT(PartEVT)) {
473 const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
474 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
475 // Drop the extra bits.
476 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
477 return DAG.getBitcast(ValueVT, Val);
478 }
479
481 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
482 return DAG.getUNDEF(ValueVT);
483 }
484
485 // Handle cases such as i8 -> <1 x i1>
486 EVT ValueSVT = ValueVT.getVectorElementType();
487 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
488 unsigned ValueSize = ValueSVT.getSizeInBits();
489 if (ValueSize == PartEVT.getSizeInBits()) {
490 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
491 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
492 // It's possible a scalar floating point type gets softened to integer and
493 // then promoted to a larger integer. If PartEVT is the larger integer
494 // we need to truncate it and then bitcast to the FP type.
495 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
496 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
497 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
498 Val = DAG.getBitcast(ValueSVT, Val);
499 } else {
500 Val = ValueVT.isFloatingPoint()
501 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
502 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
503 }
504 }
505
506 return DAG.getBuildVector(ValueVT, DL, Val);
507}
508
509static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
510 SDValue Val, SDValue *Parts, unsigned NumParts,
511 MVT PartVT, const Value *V,
512 std::optional<CallingConv::ID> CallConv);
513
514/// getCopyToParts - Create a series of nodes that contain the specified value
515/// split into legal parts. If the parts contain more bits than Val, then, for
516/// integers, ExtendKind can be used to specify how to generate the extra bits.
517static void
519 unsigned NumParts, MVT PartVT, const Value *V,
520 std::optional<CallingConv::ID> CallConv = std::nullopt,
522 // Let the target split the parts if it wants to
524 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
525 CallConv))
526 return;
527 EVT ValueVT = Val.getValueType();
528
529 // Handle the vector case separately.
530 if (ValueVT.isVector())
531 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
532 CallConv);
533
534 unsigned OrigNumParts = NumParts;
536 "Copying to an illegal type!");
537
538 if (NumParts == 0)
539 return;
540
541 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
542 EVT PartEVT = PartVT;
543 if (PartEVT == ValueVT) {
544 assert(NumParts == 1 && "No-op copy with multiple parts!");
545 Parts[0] = Val;
546 return;
547 }
548
549 unsigned PartBits = PartVT.getSizeInBits();
550 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
551 // If the parts cover more bits than the value has, promote the value.
552 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
553 assert(NumParts == 1 && "Do not know what to promote to!");
554 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
555 } else {
556 if (ValueVT.isFloatingPoint()) {
557 // FP values need to be bitcast, then extended if they are being put
558 // into a larger container.
559 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
560 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
561 }
562 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
563 ValueVT.isInteger() &&
564 "Unknown mismatch!");
565 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
566 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
567 if (PartVT == MVT::x86mmx)
568 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
569 }
570 } else if (PartBits == ValueVT.getSizeInBits()) {
571 // Different types of the same size.
572 assert(NumParts == 1 && PartEVT != ValueVT);
573 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
574 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
575 // If the parts cover less bits than value has, truncate the value.
576 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
577 ValueVT.isInteger() &&
578 "Unknown mismatch!");
579 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
580 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
581 if (PartVT == MVT::x86mmx)
582 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
583 }
584
585 // The value may have changed - recompute ValueVT.
586 ValueVT = Val.getValueType();
587 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
588 "Failed to tile the value with PartVT!");
589
590 if (NumParts == 1) {
591 if (PartEVT != ValueVT) {
593 "scalar-to-vector conversion failed");
594 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
595 }
596
597 Parts[0] = Val;
598 return;
599 }
600
601 // Expand the value into multiple parts.
602 if (NumParts & (NumParts - 1)) {
603 // The number of parts is not a power of 2. Split off and copy the tail.
604 assert(PartVT.isInteger() && ValueVT.isInteger() &&
605 "Do not know what to expand to!");
606 unsigned RoundParts = llvm::bit_floor(NumParts);
607 unsigned RoundBits = RoundParts * PartBits;
608 unsigned OddParts = NumParts - RoundParts;
609 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
610 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
611
612 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
613 CallConv);
614
615 if (DAG.getDataLayout().isBigEndian())
616 // The odd parts were reversed by getCopyToParts - unreverse them.
617 std::reverse(Parts + RoundParts, Parts + NumParts);
618
619 NumParts = RoundParts;
620 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
621 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
622 }
623
624 // The number of parts is a power of 2. Repeatedly bisect the value using
625 // EXTRACT_ELEMENT.
626 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
628 ValueVT.getSizeInBits()),
629 Val);
630
631 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
632 for (unsigned i = 0; i < NumParts; i += StepSize) {
633 unsigned ThisBits = StepSize * PartBits / 2;
634 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
635 SDValue &Part0 = Parts[i];
636 SDValue &Part1 = Parts[i+StepSize/2];
637
638 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
639 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
640 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
641 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
642
643 if (ThisBits == PartBits && ThisVT != PartVT) {
644 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
645 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
646 }
647 }
648 }
649
650 if (DAG.getDataLayout().isBigEndian())
651 std::reverse(Parts, Parts + OrigNumParts);
652}
653
655 const SDLoc &DL, EVT PartVT) {
656 if (!PartVT.isVector())
657 return SDValue();
658
659 EVT ValueVT = Val.getValueType();
660 EVT PartEVT = PartVT.getVectorElementType();
661 EVT ValueEVT = ValueVT.getVectorElementType();
662 ElementCount PartNumElts = PartVT.getVectorElementCount();
663 ElementCount ValueNumElts = ValueVT.getVectorElementCount();
664
665 // We only support widening vectors with equivalent element types and
666 // fixed/scalable properties. If a target needs to widen a fixed-length type
667 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
668 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
669 PartNumElts.isScalable() != ValueNumElts.isScalable())
670 return SDValue();
671
672 // Have a try for bf16 because some targets share its ABI with fp16.
673 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
675 "Cannot widen to illegal type");
676 Val = DAG.getNode(
678 ValueVT.changeVectorElementType(*DAG.getContext(), MVT::f16), Val);
679 } else if (PartEVT != ValueEVT) {
680 return SDValue();
681 }
682
683 // Widening a scalable vector to another scalable vector is done by inserting
684 // the vector into a larger undef one.
685 if (PartNumElts.isScalable())
686 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
687 Val, DAG.getVectorIdxConstant(0, DL));
688
689 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
690 // undef elements.
692 DAG.ExtractVectorElements(Val, Ops);
693 SDValue EltUndef = DAG.getUNDEF(PartEVT);
694 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
695
696 // FIXME: Use CONCAT for 2x -> 4x.
697 return DAG.getBuildVector(PartVT, DL, Ops);
698}
699
700/// getCopyToPartsVector - Create a series of nodes that contain the specified
701/// value split into legal parts.
702static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
703 SDValue Val, SDValue *Parts, unsigned NumParts,
704 MVT PartVT, const Value *V,
705 std::optional<CallingConv::ID> CallConv) {
706 EVT ValueVT = Val.getValueType();
707 assert(ValueVT.isVector() && "Not a vector");
709 const bool IsABIRegCopy = CallConv.has_value();
710
711 if (NumParts == 1) {
712 EVT PartEVT = PartVT;
713 if (PartEVT == ValueVT) {
714 // Nothing to do.
715 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
716 // Bitconvert vector->vector case.
717 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
718 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
719 Val = Widened;
720 } else if (PartVT.isVector() &&
722 ValueVT.getVectorElementType()) &&
723 PartEVT.getVectorElementCount() ==
724 ValueVT.getVectorElementCount()) {
725
726 // Promoted vector extract
727 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
728 } else if (PartEVT.isVector() &&
729 PartEVT.getVectorElementType() !=
730 ValueVT.getVectorElementType() &&
731 TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
733 // Combination of widening and promotion.
734 EVT WidenVT =
736 PartVT.getVectorElementCount());
737 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
738 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
739 } else {
740 // Don't extract an integer from a float vector. This can happen if the
741 // FP type gets softened to integer and then promoted. The promotion
742 // prevents it from being picked up by the earlier bitcast case.
743 if (ValueVT.getVectorElementCount().isScalar() &&
744 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
745 // If we reach this condition and PartVT is FP, this means that
746 // ValueVT is also FP and both have a different size, otherwise we
747 // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
748 // would be invalid since that would mean the smaller FP type has to
749 // be extended to the larger one.
750 if (PartVT.isFloatingPoint()) {
751 Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
752 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
753 } else
754 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
755 DAG.getVectorIdxConstant(0, DL));
756 } else {
757 uint64_t ValueSize = ValueVT.getFixedSizeInBits();
758 assert(PartVT.getFixedSizeInBits() > ValueSize &&
759 "lossy conversion of vector to scalar type");
760 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
761 Val = DAG.getBitcast(IntermediateType, Val);
762 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
763 }
764 }
765
766 assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
767 Parts[0] = Val;
768 return;
769 }
770
771 // Handle a multi-element vector.
772 EVT IntermediateVT;
773 MVT RegisterVT;
774 unsigned NumIntermediates;
775 unsigned NumRegs;
776 if (IsABIRegCopy) {
777 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
778 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
779 RegisterVT);
780 } else {
781 NumRegs =
782 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
783 NumIntermediates, RegisterVT);
784 }
785
786 ensureMatchedVecRegParts(NumRegs, NumParts, RegisterVT, PartVT);
787 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
788 "Mixing scalable and fixed vectors when copying in parts");
789
790 std::optional<ElementCount> DestEltCnt;
791
792 if (IntermediateVT.isVector())
793 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
794 else
795 DestEltCnt = ElementCount::getFixed(NumIntermediates);
796
797 EVT BuiltVectorTy = EVT::getVectorVT(
798 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
799
800 if (ValueVT == BuiltVectorTy) {
801 // Nothing to do.
802 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
803 // Bitconvert vector->vector case.
804 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
805 } else {
806 if (BuiltVectorTy.getVectorElementType().bitsGT(
807 ValueVT.getVectorElementType())) {
808 // Integer promotion.
809 ValueVT = EVT::getVectorVT(*DAG.getContext(),
810 BuiltVectorTy.getVectorElementType(),
811 ValueVT.getVectorElementCount());
812 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
813 }
814
815 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
816 Val = Widened;
817 }
818 }
819
820 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
821
822 // Split the vector into intermediate operands.
823 SmallVector<SDValue, 8> Ops(NumIntermediates);
824 for (unsigned i = 0; i != NumIntermediates; ++i) {
825 if (IntermediateVT.isVector()) {
826 // This does something sensible for scalable vectors - see the
827 // definition of EXTRACT_SUBVECTOR for further details.
828 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
829 Ops[i] =
830 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
831 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
832 } else {
833 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
834 DAG.getVectorIdxConstant(i, DL));
835 }
836 }
837
838 // Split the intermediate operands into legal parts.
839 if (NumParts == NumIntermediates) {
840 // If the register was not expanded, promote or copy the value,
841 // as appropriate.
842 for (unsigned i = 0; i != NumParts; ++i)
843 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
844 } else if (NumParts > 0) {
845 // If the intermediate type was expanded, split each the value into
846 // legal parts.
847 assert(NumIntermediates != 0 && "division by zero");
848 assert(NumParts % NumIntermediates == 0 &&
849 "Must expand into a divisible number of parts!");
850 unsigned Factor = NumParts / NumIntermediates;
851 for (unsigned i = 0; i != NumIntermediates; ++i)
852 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
853 CallConv);
854 }
855}
856
857static void failForInvalidBundles(const CallBase &I, StringRef Name,
858 ArrayRef<uint32_t> AllowedBundles) {
859 if (I.hasOperandBundlesOtherThan(AllowedBundles)) {
860 ListSeparator LS;
861 std::string Error;
863 for (unsigned i = 0, e = I.getNumOperandBundles(); i != e; ++i) {
864 OperandBundleUse U = I.getOperandBundleAt(i);
865 if (!is_contained(AllowedBundles, U.getTagID()))
866 OS << LS << U.getTagName();
867 }
869 Twine("cannot lower ", Name)
870 .concat(Twine(" with arbitrary operand bundles: ", Error)));
871 }
872}
873
875 EVT valuevt, std::optional<CallingConv::ID> CC)
876 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
877 RegCount(1, regs.size()), CallConv(CC) {}
878
880 const DataLayout &DL, Register Reg, Type *Ty,
881 std::optional<CallingConv::ID> CC) {
883
884 CallConv = CC;
885
886 for (EVT ValueVT : ValueVTs) {
887 unsigned NumRegs =
889 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
890 : TLI.getNumRegisters(Context, ValueVT);
891 MVT RegisterVT =
893 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
894 : TLI.getRegisterType(Context, ValueVT);
895 for (unsigned i = 0; i != NumRegs; ++i)
896 Regs.push_back(Reg + i);
897 RegVTs.push_back(RegisterVT);
898 RegCount.push_back(NumRegs);
899 Reg = Reg.id() + NumRegs;
900 }
901}
902
904 FunctionLoweringInfo &FuncInfo,
905 const SDLoc &dl, SDValue &Chain,
906 SDValue *Glue, const Value *V) const {
907 // A Value with type {} or [0 x %t] needs no registers.
908 if (ValueVTs.empty())
909 return SDValue();
910
912
913 // Assemble the legal parts into the final values.
916 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
917 // Copy the legal parts from the registers.
918 EVT ValueVT = ValueVTs[Value];
919 unsigned NumRegs = RegCount[Value];
920 MVT RegisterVT = isABIMangled()
921 ? TLI.getRegisterTypeForCallingConv(
922 *DAG.getContext(), *CallConv, RegVTs[Value])
923 : RegVTs[Value];
924
925 Parts.resize(NumRegs);
926 for (unsigned i = 0; i != NumRegs; ++i) {
927 SDValue P;
928 if (!Glue) {
929 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
930 } else {
931 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
932 *Glue = P.getValue(2);
933 }
934
935 Chain = P.getValue(1);
936 Parts[i] = P;
937
938 // If the source register was virtual and if we know something about it,
939 // add an assert node.
940 if (!Regs[Part + i].isVirtual() || !RegisterVT.isInteger())
941 continue;
942
944 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
945 if (!LOI)
946 continue;
947
948 unsigned RegSize = RegisterVT.getScalarSizeInBits();
949 unsigned NumSignBits = LOI->NumSignBits;
950 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
951
952 if (NumZeroBits == RegSize) {
953 // The current value is a zero.
954 // Explicitly express that as it would be easier for
955 // optimizations to kick in.
956 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
957 continue;
958 }
959
960 // FIXME: We capture more information than the dag can represent. For
961 // now, just use the tightest assertzext/assertsext possible.
962 bool isSExt;
963 EVT FromVT(MVT::Other);
964 if (NumZeroBits) {
965 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
966 isSExt = false;
967 } else if (NumSignBits > 1) {
968 FromVT =
969 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
970 isSExt = true;
971 } else {
972 continue;
973 }
974 // Add an assertion node.
975 assert(FromVT != MVT::Other);
976 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
977 RegisterVT, P, DAG.getValueType(FromVT));
978 }
979
980 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
981 RegisterVT, ValueVT, V, Chain, CallConv);
982 Part += NumRegs;
983 Parts.clear();
984 }
985
986 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
987}
988
990 const SDLoc &dl, SDValue &Chain, SDValue *Glue,
991 const Value *V,
992 ISD::NodeType PreferredExtendType) const {
994 ISD::NodeType ExtendKind = PreferredExtendType;
995
996 // Get the list of the values's legal parts.
997 unsigned NumRegs = Regs.size();
998 SmallVector<SDValue, 8> Parts(NumRegs);
999 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
1000 unsigned NumParts = RegCount[Value];
1001
1002 MVT RegisterVT = isABIMangled()
1003 ? TLI.getRegisterTypeForCallingConv(
1004 *DAG.getContext(), *CallConv, RegVTs[Value])
1005 : RegVTs[Value];
1006
1008 if (TLI.isZExtFree(peekThroughFreeze(Val), RegisterVT))
1010
1011 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
1012 NumParts, RegisterVT, V, CallConv, ExtendKind);
1013 Part += NumParts;
1014 }
1015
1016 // Copy the parts into the registers.
1017 SmallVector<SDValue, 8> Chains(NumRegs);
1018 for (unsigned i = 0; i != NumRegs; ++i) {
1019 SDValue Part;
1020 if (!Glue) {
1021 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
1022 } else {
1023 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
1024 *Glue = Part.getValue(1);
1025 }
1026
1027 Chains[i] = Part.getValue(0);
1028 }
1029
1030 if (NumRegs == 1 || Glue)
1031 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1032 // flagged to it. That is the CopyToReg nodes and the user are considered
1033 // a single scheduling unit. If we create a TokenFactor and return it as
1034 // chain, then the TokenFactor is both a predecessor (operand) of the
1035 // user as well as a successor (the TF operands are flagged to the user).
1036 // c1, f1 = CopyToReg
1037 // c2, f2 = CopyToReg
1038 // c3 = TokenFactor c1, c2
1039 // ...
1040 // = op c3, ..., f2
1041 Chain = Chains[NumRegs-1];
1042 else
1043 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1044}
1045
1047 unsigned MatchingIdx, const SDLoc &dl,
1048 SelectionDAG &DAG,
1049 std::vector<SDValue> &Ops) const {
1051
1052 InlineAsm::Flag Flag(Code, Regs.size());
1053 if (HasMatching)
1054 Flag.setMatchingOp(MatchingIdx);
1055 else if (!Regs.empty() && Regs.front().isVirtual()) {
1056 // Put the register class of the virtual registers in the flag word. That
1057 // way, later passes can recompute register class constraints for inline
1058 // assembly as well as normal instructions.
1059 // Don't do this for tied operands that can use the regclass information
1060 // from the def.
1062 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1063 Flag.setRegClass(RC->getID());
1064 }
1065
1066 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1067 Ops.push_back(Res);
1068
1069 if (Code == InlineAsm::Kind::Clobber) {
1070 // Clobbers should always have a 1:1 mapping with registers, and may
1071 // reference registers that have illegal (e.g. vector) types. Hence, we
1072 // shouldn't try to apply any sort of splitting logic to them.
1073 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1074 "No 1:1 mapping from clobbers to regs?");
1075 Register SP = TLI.getStackPointerRegisterToSaveRestore();
1076 (void)SP;
1077 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1078 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1079 assert(
1080 (Regs[I] != SP ||
1082 "If we clobbered the stack pointer, MFI should know about it.");
1083 }
1084 return;
1085 }
1086
1087 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1088 MVT RegisterVT = RegVTs[Value];
1089 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1090 RegisterVT);
1091 for (unsigned i = 0; i != NumRegs; ++i) {
1092 assert(Reg < Regs.size() && "Mismatch in # registers expected");
1093 Register TheReg = Regs[Reg++];
1094 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1095 }
1096 }
1097}
1098
1102 unsigned I = 0;
1103 for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1104 unsigned RegCount = std::get<0>(CountAndVT);
1105 MVT RegisterVT = std::get<1>(CountAndVT);
1106 TypeSize RegisterSize = RegisterVT.getSizeInBits();
1107 for (unsigned E = I + RegCount; I != E; ++I)
1108 OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1109 }
1110 return OutVec;
1111}
1112
1114 AssumptionCache *ac, const TargetLibraryInfo *li,
1115 const TargetTransformInfo &TTI) {
1116 BatchAA = aa;
1117 AC = ac;
1118 GFI = gfi;
1119 LibInfo = li;
1120 Context = DAG.getContext();
1121 LPadToCallSiteMap.clear();
1122 this->TTI = &TTI;
1123 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1124 AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1125 *DAG.getMachineFunction().getFunction().getParent());
1126 CanDescribeGlobalAddressInLocationList =
1127 canDescribeGlobalAddressInLocationList(DAG.getMachineFunction());
1128}
1129
1131 NodeMap.clear();
1132 UnusedArgNodeMap.clear();
1133 PendingLoads.clear();
1134 PendingExports.clear();
1135 PendingConstrainedFP.clear();
1136 PendingConstrainedFPStrict.clear();
1137 CurInst = nullptr;
1138 HasTailCall = false;
1139 SDNodeOrder = LowestSDNodeOrder;
1140 StatepointLowering.clear();
1141}
1142
1144 DanglingDebugInfoMap.clear();
1145}
1146
1147// Update DAG root to include dependencies on Pending chains.
1148SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1149 SDValue Root = DAG.getRoot();
1150
1151 if (Pending.empty())
1152 return Root;
1153
1154 // Add current root to PendingChains, unless we already indirectly
1155 // depend on it.
1156 if (Root.getOpcode() != ISD::EntryToken) {
1157 unsigned i = 0, e = Pending.size();
1158 for (; i != e; ++i) {
1159 assert(Pending[i].getNode()->getNumOperands() > 1);
1160 if (Pending[i].getNode()->getOperand(0) == Root)
1161 break; // Don't add the root if we already indirectly depend on it.
1162 }
1163
1164 if (i == e)
1165 Pending.push_back(Root);
1166 }
1167
1168 if (Pending.size() == 1)
1169 Root = Pending[0];
1170 else
1171 Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1172
1173 DAG.setRoot(Root);
1174 Pending.clear();
1175 return Root;
1176}
1177
1181
1183 // If the new exception behavior differs from that of the pending
1184 // ones, chain up them and update the root.
1185 switch (EB) {
1188 // Floating-point exceptions produced by such operations are not intended
1189 // to be observed, so the sequence of these operations does not need to be
1190 // preserved.
1191 //
1192 // They however must not be mixed with the instructions that have strict
1193 // exception behavior. Placing an operation with 'ebIgnore' behavior between
1194 // 'ebStrict' operations could distort the observed exception behavior.
1195 if (!PendingConstrainedFPStrict.empty()) {
1196 assert(PendingConstrainedFP.empty());
1197 updateRoot(PendingConstrainedFPStrict);
1198 }
1199 break;
1201 // Floating-point exception produced by these operations may be observed, so
1202 // they must be correctly chained. If trapping on FP exceptions is
1203 // disabled, the exceptions can be observed only by functions that read
1204 // exception flags, like 'llvm.get_fpenv' or 'fetestexcept'. It means that
1205 // the order of operations is not significant between barriers.
1206 //
1207 // If trapping is enabled, each operation becomes an implicit observation
1208 // point, so the operations must be sequenced according their original
1209 // source order.
1210 if (!PendingConstrainedFP.empty()) {
1211 assert(PendingConstrainedFPStrict.empty());
1212 updateRoot(PendingConstrainedFP);
1213 }
1214 // TODO: Add support for trapping-enabled scenarios.
1215 }
1216 return DAG.getRoot();
1217}
1218
1220 // Chain up all pending constrained intrinsics together with all
1221 // pending loads, by simply appending them to PendingLoads and
1222 // then calling getMemoryRoot().
1223 PendingLoads.reserve(PendingLoads.size() +
1224 PendingConstrainedFP.size() +
1225 PendingConstrainedFPStrict.size());
1226 PendingLoads.append(PendingConstrainedFP.begin(),
1227 PendingConstrainedFP.end());
1228 PendingLoads.append(PendingConstrainedFPStrict.begin(),
1229 PendingConstrainedFPStrict.end());
1230 PendingConstrainedFP.clear();
1231 PendingConstrainedFPStrict.clear();
1232 return getMemoryRoot();
1233}
1234
1236 // We need to emit pending fpexcept.strict constrained intrinsics,
1237 // so append them to the PendingExports list.
1238 PendingExports.append(PendingConstrainedFPStrict.begin(),
1239 PendingConstrainedFPStrict.end());
1240 PendingConstrainedFPStrict.clear();
1241 return updateRoot(PendingExports);
1242}
1243
1245 DILocalVariable *Variable,
1247 DebugLoc DL) {
1248 assert(Variable && "Missing variable");
1249
1250 // Check if address has undef value.
1251 if (!Address || isa<UndefValue>(Address) ||
1252 (Address->use_empty() && !isa<Argument>(Address))) {
1253 LLVM_DEBUG(
1254 dbgs()
1255 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1256 return;
1257 }
1258
1259 bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1260
1261 SDValue &N = NodeMap[Address];
1262 if (!N.getNode() && isa<Argument>(Address))
1263 // Check unused arguments map.
1264 N = UnusedArgNodeMap[Address];
1265 SDDbgValue *SDV;
1266 if (N.getNode()) {
1267 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1268 Address = BCI->getOperand(0);
1269 // Parameters are handled specially.
1270 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1271 if (IsParameter && FINode) {
1272 // Byval parameter. We have a frame index at this point.
1273 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1274 /*IsIndirect*/ true, DL, SDNodeOrder);
1275 } else if (isa<Argument>(Address)) {
1276 // Address is an argument, so try to emit its dbg value using
1277 // virtual register info from the FuncInfo.ValueMap.
1278 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1279 FuncArgumentDbgValueKind::Declare, N);
1280 return;
1281 } else {
1282 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1283 true, DL, SDNodeOrder);
1284 }
1285 DAG.AddDbgValue(SDV, IsParameter);
1286 } else {
1287 // If Address is an argument then try to emit its dbg value using
1288 // virtual register info from the FuncInfo.ValueMap.
1289 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1290 FuncArgumentDbgValueKind::Declare, N)) {
1291 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1292 << " (could not emit func-arg dbg_value)\n");
1293 }
1294 }
1295}
1296
1298 // Add SDDbgValue nodes for any var locs here. Do so before updating
1299 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1300 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1301 // Add SDDbgValue nodes for any var locs here. Do so before updating
1302 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1303 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1304 It != End; ++It) {
1305 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1306 dropDanglingDebugInfo(Var, It->Expr);
1307 if (It->Values.isKillLocation(It->Expr)) {
1308 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1309 continue;
1310 }
1311 SmallVector<Value *> Values(It->Values.location_ops());
1312 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1313 It->Values.hasArgList())) {
1314 SmallVector<Value *, 4> Vals(It->Values.location_ops());
1316 FnVarLocs->getDILocalVariable(It->VariableID),
1317 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1318 }
1319 }
1320 }
1321
1322 // We must skip DbgVariableRecords if they've already been processed above as
1323 // we have just emitted the debug values resulting from assignment tracking
1324 // analysis, making any existing DbgVariableRecords redundant (and probably
1325 // less correct). We still need to process DbgLabelRecords. This does sink
1326 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1327 // be important as it does so deterministcally and ordering between
1328 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1329 // printing).
1330 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1331 // Is there is any debug-info attached to this instruction, in the form of
1332 // DbgRecord non-instruction debug-info records.
1333 for (DbgRecord &DR : I.getDbgRecordRange()) {
1334 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1335 assert(DLR->getLabel() && "Missing label");
1336 SDDbgLabel *SDV =
1337 DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1338 DAG.AddDbgLabel(SDV);
1339 continue;
1340 }
1341
1342 if (SkipDbgVariableRecords)
1343 continue;
1345 DILocalVariable *Variable = DVR.getVariable();
1348
1350 if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1351 continue;
1352 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1353 << "\n");
1355 DVR.getDebugLoc());
1356 continue;
1357 }
1358
1359 // A DbgVariableRecord with no locations is a kill location.
1361 if (Values.empty()) {
1363 SDNodeOrder);
1364 continue;
1365 }
1366
1367 // A DbgVariableRecord with an undef or absent location is also a kill
1368 // location.
1369 if (llvm::any_of(Values,
1370 [](Value *V) { return !V || isa<UndefValue>(V); })) {
1372 SDNodeOrder);
1373 continue;
1374 }
1375
1376 bool IsVariadic = DVR.hasArgList();
1377 if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1378 SDNodeOrder, IsVariadic)) {
1379 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1380 DVR.getDebugLoc(), SDNodeOrder);
1381 }
1382 }
1383}
1384
1386 visitDbgInfo(I);
1387
1388 // Set up outgoing PHI node register values before emitting the terminator.
1389 if (I.isTerminator()) {
1390 HandlePHINodesInSuccessorBlocks(I.getParent());
1391 }
1392
1393 ++SDNodeOrder;
1394 CurInst = &I;
1395
1396 // Set inserted listener only if required.
1397 bool NodeInserted = false;
1398 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1399 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1400 MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1401 if (PCSectionsMD || MMRA) {
1402 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1403 DAG, [&](SDNode *) { NodeInserted = true; });
1404 }
1405
1406 visit(I.getOpcode(), I);
1407
1408 if (!I.isTerminator() && !HasTailCall &&
1409 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1411
1412 // Handle metadata.
1413 if (PCSectionsMD || MMRA) {
1414 auto It = NodeMap.find(&I);
1415 if (It != NodeMap.end()) {
1416 if (PCSectionsMD)
1417 DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1418 if (MMRA)
1419 DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1420 } else if (NodeInserted) {
1421 // This should not happen; if it does, don't let it go unnoticed so we can
1422 // fix it. Relevant visit*() function is probably missing a setValue().
1423 errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1424 << I.getModule()->getName() << "]\n";
1425 LLVM_DEBUG(I.dump());
1426 assert(false);
1427 }
1428 }
1429
1430 CurInst = nullptr;
1431}
1432
1433void SelectionDAGBuilder::visitPHI(const PHINode &) {
1434 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1435}
1436
1437void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1438 // Note: this doesn't use InstVisitor, because it has to work with
1439 // ConstantExpr's in addition to instructions.
1440 switch (Opcode) {
1441 default: llvm_unreachable("Unknown instruction type encountered!");
1442 // Build the switch statement using the Instruction.def file.
1443#define HANDLE_INST(NUM, OPCODE, CLASS) \
1444 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1445#include "llvm/IR/Instruction.def"
1446 }
1447}
1448
1450 DILocalVariable *Variable,
1451 DebugLoc DL, unsigned Order,
1454 // For variadic dbg_values we will now insert poison.
1455 // FIXME: We can potentially recover these!
1457 for (const Value *V : Values) {
1458 auto *Poison = PoisonValue::get(V->getType());
1459 Locs.push_back(SDDbgOperand::fromConst(Poison));
1460 }
1461 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1462 /*IsIndirect=*/false, DL, Order,
1463 /*IsVariadic=*/true);
1464 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1465 return true;
1466}
1467
1469 DILocalVariable *Var,
1470 DIExpression *Expr,
1471 bool IsVariadic, DebugLoc DL,
1472 unsigned Order) {
1473 if (IsVariadic) {
1474 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1475 return;
1476 }
1477 // TODO: Dangling debug info will eventually either be resolved or produce
1478 // a poison DBG_VALUE. However in the resolution case, a gap may appear
1479 // between the original dbg.value location and its resolved DBG_VALUE,
1480 // which we should ideally fill with an extra poison DBG_VALUE.
1481 assert(Values.size() == 1);
1482 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1483}
1484
1486 const DIExpression *Expr) {
1487 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1488 DIVariable *DanglingVariable = DDI.getVariable();
1489 DIExpression *DanglingExpr = DDI.getExpression();
1490 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1491 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1492 << printDDI(nullptr, DDI) << "\n");
1493 return true;
1494 }
1495 return false;
1496 };
1497
1498 for (auto &DDIMI : DanglingDebugInfoMap) {
1499 DanglingDebugInfoVector &DDIV = DDIMI.second;
1500
1501 // If debug info is to be dropped, run it through final checks to see
1502 // whether it can be salvaged.
1503 for (auto &DDI : DDIV)
1504 if (isMatchingDbgValue(DDI))
1505 salvageUnresolvedDbgValue(DDIMI.first, DDI);
1506
1507 erase_if(DDIV, isMatchingDbgValue);
1508 }
1509}
1510
1511// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1512// generate the debug data structures now that we've seen its definition.
1514 SDValue Val) {
1515 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1516 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1517 return;
1518
1519 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1520 for (auto &DDI : DDIV) {
1521 DebugLoc DL = DDI.getDebugLoc();
1522 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1523 DILocalVariable *Variable = DDI.getVariable();
1524 DIExpression *Expr = DDI.getExpression();
1525 assert(Variable->isValidLocationForIntrinsic(DL) &&
1526 "Expected inlined-at fields to agree");
1527 SDDbgValue *SDV;
1528 if (Val.getNode()) {
1529 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1530 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1531 // we couldn't resolve it directly when examining the DbgValue intrinsic
1532 // in the first place we should not be more successful here). Unless we
1533 // have some test case that prove this to be correct we should avoid
1534 // calling EmitFuncArgumentDbgValue here.
1535 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1536 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1537 FuncArgumentDbgValueKind::Value, Val)) {
1538 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1539 << printDDI(V, DDI) << "\n");
1540 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1541 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1542 // inserted after the definition of Val when emitting the instructions
1543 // after ISel. An alternative could be to teach
1544 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1545 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1546 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1547 << ValSDNodeOrder << "\n");
1548 SDV = getDbgValue(Val, Variable, Expr, DL,
1549 std::max(DbgSDNodeOrder, ValSDNodeOrder));
1550 DAG.AddDbgValue(SDV, false);
1551 } else
1552 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1553 << printDDI(V, DDI)
1554 << " in EmitFuncArgumentDbgValue\n");
1555 } else {
1556 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1557 << "\n");
1558 auto Poison = PoisonValue::get(V->getType());
1559 auto SDV =
1560 DAG.getConstantDbgValue(Variable, Expr, Poison, DL, DbgSDNodeOrder);
1561 DAG.AddDbgValue(SDV, false);
1562 }
1563 }
1564 DDIV.clear();
1565}
1566
1567/// If \p V is the address of a describable global, possibly displaced by a
1568/// constant, return the global and fold the displacement into location operand
1569/// \p OpIdx of \p Expr. The displacement rides along in the expression rather
1570/// than in the operand, so that it survives into a DBG_INSTR_REF.
1571static const GlobalValue *
1572getGlobalAddressDbgOperand(const Value *V, DIExpression *&Expr, unsigned OpIdx,
1573 const MachineFunction &MF) {
1574 const auto *C = dyn_cast<Constant>(V);
1575 if (!C)
1576 return nullptr;
1577 int64_t Offset;
1579 if (GV && Offset) {
1582 Expr = DIExpression::appendOpsToArg(Expr, Ops, OpIdx, /*StackValue=*/false);
1583 }
1584 return GV;
1585}
1586
1588 DanglingDebugInfo &DDI) {
1589 // TODO: For the variadic implementation, instead of only checking the fail
1590 // state of `handleDebugValue`, we need know specifically which values were
1591 // invalid, so that we attempt to salvage only those values when processing
1592 // a DIArgList.
1593 const Value *OrigV = V;
1594 DILocalVariable *Var = DDI.getVariable();
1595 DIExpression *Expr = DDI.getExpression();
1596 DebugLoc DL = DDI.getDebugLoc();
1597 unsigned SDOrder = DDI.getSDNodeOrder();
1598
1599 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1600 // that DW_OP_stack_value is desired.
1601 bool StackValue = true;
1602
1603 // handleDebugValue holds out for a register with the address of a global
1604 // that a location list could not name. With no such register forthcoming,
1605 // naming the global still beats dropping the location.
1606 auto HandleGlobalAddress = [&] {
1607 DIExpression *GVExpr = Expr;
1608 const GlobalValue *GV =
1609 getGlobalAddressDbgOperand(V, GVExpr, 0, DAG.getMachineFunction());
1610 if (!GV)
1611 return false;
1612 SDDbgValue *SDV = DAG.getDbgValueList(
1613 Var, GVExpr, SDDbgOperand::fromGlobalAddr(GV), /*Dependencies=*/{},
1614 /*IsIndirect=*/false, DL, SDOrder, /*IsVariadic=*/false);
1615 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1616 return true;
1617 };
1618
1619 // Can this Value can be encoded without any further work?
1620 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false) ||
1621 HandleGlobalAddress())
1622 return;
1623
1624 // Attempt to salvage back through as many instructions as possible. Bail if
1625 // a non-instruction is seen, such as a constant expression or global
1626 // variable. FIXME: Further work could recover those too.
1627 while (isa<Instruction>(V)) {
1628 const Instruction &VAsInst = *cast<const Instruction>(V);
1629 // Temporary "0", awaiting real implementation.
1631 SmallVector<Value *, 4> AdditionalValues;
1632 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1633 Expr->getNumLocationOperands(), Ops,
1634 AdditionalValues);
1635 // If we cannot salvage any further, and haven't yet found a suitable debug
1636 // expression, bail out.
1637 if (!V)
1638 break;
1639
1640 // TODO: If AdditionalValues isn't empty, then the salvage can only be
1641 // represented with a DBG_VALUE_LIST, so we give up. When we have support
1642 // here for variadic dbg_values, remove that condition.
1643 if (!AdditionalValues.empty())
1644 break;
1645
1646 // New value and expr now represent this debuginfo.
1648
1649 // Some kind of simplification occurred: check whether the operand of the
1650 // salvaged debug expression can be encoded in this DAG.
1651 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false) ||
1652 HandleGlobalAddress()) {
1653 LLVM_DEBUG(
1654 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n"
1655 << *OrigV << "\nBy stripping back to:\n " << *V << "\n");
1656 return;
1657 }
1658 }
1659
1660 // This was the final opportunity to salvage this debug information, and it
1661 // couldn't be done. Place a poison DBG_VALUE at this location to terminate
1662 // any earlier variable location.
1663 assert(OrigV && "V shouldn't be null");
1664 auto *Poison = PoisonValue::get(OrigV->getType());
1665 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Poison, DL, SDOrder);
1666 DAG.AddDbgValue(SDV, false);
1667 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n "
1668 << printDDI(OrigV, DDI) << "\n");
1669}
1670
1672 DIExpression *Expr,
1673 DebugLoc DbgLoc,
1674 unsigned Order) {
1675 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1678 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1679 /*IsVariadic*/ false);
1680}
1681
1683 DILocalVariable *Var,
1684 DIExpression *Expr, DebugLoc DbgLoc,
1685 unsigned Order, bool IsVariadic) {
1686 if (Values.empty())
1687 return true;
1688
1689 // Filter EntryValue locations out early.
1690 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1691 return true;
1692
1693 SmallVector<SDDbgOperand> LocationOps;
1694 SmallVector<SDNode *> Dependencies;
1695 for (const auto &[OpIdx, V] : enumerate(Values)) {
1696 // Constant value.
1699 LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1700 continue;
1701 }
1702
1703 // Look through IntToPtr constants.
1704 if (auto *CE = dyn_cast<ConstantExpr>(V))
1705 if (CE->getOpcode() == Instruction::IntToPtr) {
1706 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1707 continue;
1708 }
1709
1710 // The address of a global is a link-time constant, and so is a constant
1711 // displacement from one. A global whose address cannot be described this
1712 // way falls through to be described by whatever materializes it instead.
1713 // So does one that a location list could not name, should the variable
1714 // need one; salvageUnresolvedDbgValue names it if nothing materializes it.
1715 if (CanDescribeGlobalAddressInLocationList)
1717 V, Expr, OpIdx, DAG.getMachineFunction())) {
1719 continue;
1720 }
1721
1722 // If the Value is a frame index, we can create a FrameIndex debug value
1723 // without relying on the DAG at all.
1724 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1725 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1726 if (SI != FuncInfo.StaticAllocaMap.end()) {
1727 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1728 continue;
1729 }
1730 }
1731
1732 // Do not use getValue() in here; we don't want to generate code at
1733 // this point if it hasn't been done yet.
1734 SDValue N = NodeMap[V];
1735 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1736 N = UnusedArgNodeMap[V];
1737
1738 if (N.getNode()) {
1739 // Only emit func arg dbg value for non-variadic dbg.values for now.
1740 if (!IsVariadic &&
1741 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1742 FuncArgumentDbgValueKind::Value, N))
1743 return true;
1744 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1745 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1746 // describe stack slot locations.
1747 //
1748 // Consider "int x = 0; int *px = &x;". There are two kinds of
1749 // interesting debug values here after optimization:
1750 //
1751 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
1752 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1753 //
1754 // Both describe the direct values of their associated variables.
1755 Dependencies.push_back(N.getNode());
1756 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1757 continue;
1758 }
1759 LocationOps.emplace_back(
1760 SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1761 continue;
1762 }
1763
1764 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1765 // Special rules apply for the first dbg.values of parameter variables in a
1766 // function. Identify them by the fact they reference Argument Values, that
1767 // they're parameters, and they are parameters of the current function. We
1768 // need to let them dangle until they get an SDNode.
1769 bool IsParamOfFunc =
1770 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1771 if (IsParamOfFunc)
1772 return false;
1773
1774 // The value is not used in this block yet (or it would have an SDNode).
1775 // We still want the value to appear for the user if possible -- if it has
1776 // an associated VReg, we can refer to that instead.
1777 auto VMI = FuncInfo.ValueMap.find(V);
1778 if (VMI != FuncInfo.ValueMap.end()) {
1779 Register Reg = VMI->second;
1780 // If this is a PHI node, it may be split up into several MI PHI nodes
1781 // (in FunctionLoweringInfo::set).
1782 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1783 V->getType(), std::nullopt);
1784 if (RFV.occupiesMultipleRegs()) {
1785 // FIXME: We could potentially support variadic dbg_values here.
1786 if (IsVariadic)
1787 return false;
1788 unsigned Offset = 0;
1789 unsigned BitsToDescribe = 0;
1790 if (auto VarSize = Var->getSizeInBits())
1791 BitsToDescribe = *VarSize;
1792 if (auto Fragment = Expr->getFragmentInfo())
1793 BitsToDescribe = Fragment->SizeInBits;
1794 for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1795 // Bail out if all bits are described already.
1796 if (Offset >= BitsToDescribe)
1797 break;
1798 // TODO: handle scalable vectors.
1799 unsigned RegisterSize = RegAndSize.second;
1800 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1801 ? BitsToDescribe - Offset
1802 : RegisterSize;
1803 auto FragmentExpr = DIExpression::createFragmentExpression(
1804 Expr, Offset, FragmentSize);
1805 if (!FragmentExpr)
1806 continue;
1807 SDDbgValue *SDV = DAG.getVRegDbgValue(
1808 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1809 DAG.AddDbgValue(SDV, false);
1810 Offset += RegisterSize;
1811 }
1812 return true;
1813 }
1814 // We can use simple vreg locations for variadic dbg_values as well.
1815 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1816 continue;
1817 }
1818 // We failed to create a SDDbgOperand for V.
1819 return false;
1820 }
1821
1822 // We have created a SDDbgOperand for each Value in Values.
1823 assert(!LocationOps.empty());
1824 SDDbgValue *SDV =
1825 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1826 /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1827 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1828 return true;
1829}
1830
1832 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1833 for (auto &Pair : DanglingDebugInfoMap)
1834 for (auto &DDI : Pair.second)
1835 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1837}
1838
1839/// getCopyFromRegs - If there was virtual register allocated for the value V
1840/// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1842 auto It = FuncInfo.ValueMap.find(V);
1843 SDValue Result;
1844
1845 if (It != FuncInfo.ValueMap.end()) {
1846 Register InReg = It->second;
1847
1848 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1849 DAG.getDataLayout(), InReg, Ty,
1850 std::nullopt); // This is not an ABI copy.
1851 SDValue Chain = DAG.getEntryNode();
1852 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1853 V);
1854 resolveDanglingDebugInfo(V, Result);
1855 }
1856
1857 return Result;
1858}
1859
1860/// getValue - Return an SDValue for the given Value.
1862 // If we already have an SDValue for this value, use it. It's important
1863 // to do this first, so that we don't create a CopyFromReg if we already
1864 // have a regular SDValue.
1865 SDValue &N = NodeMap[V];
1866 if (N.getNode()) return N;
1867
1868 // If there's a virtual register allocated and initialized for this
1869 // value, use it.
1870 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1871 return copyFromReg;
1872
1873 // Otherwise create a new SDValue and remember it.
1874 SDValue Val = getValueImpl(V);
1875 NodeMap[V] = Val;
1877 return Val;
1878}
1879
1880void SelectionDAGBuilder::setValueToPoison(const Value *V, const SDLoc &dl) {
1881 if (V->getType()->isVoidTy())
1882 return;
1883
1884 SmallVector<EVT, 4> ValueVTs;
1885 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
1886 V->getType(), ValueVTs);
1887 if (ValueVTs.empty())
1888 return;
1889 setValue(V, DAG.getErrorMergeValues(ValueVTs, SDValue(), dl));
1890}
1891
1892/// getNonRegisterValue - Return an SDValue for the given Value, but
1893/// don't look in FuncInfo.ValueMap for a virtual register.
1895 // If we already have an SDValue for this value, use it.
1896 SDValue &N = NodeMap[V];
1897 if (N.getNode()) {
1898 if (isIntOrFPConstant(N)) {
1899 // Remove the debug location from the node as the node is about to be used
1900 // in a location which may differ from the original debug location. This
1901 // is relevant to Constant and ConstantFP nodes because they can appear
1902 // as constant expressions inside PHI nodes.
1903 N->setDebugLoc(DebugLoc());
1904 }
1905 return N;
1906 }
1907
1908 // Otherwise create a new SDValue and remember it.
1909 SDValue Val = getValueImpl(V);
1910 NodeMap[V] = Val;
1912 return Val;
1913}
1914
1915/// getValueImpl - Helper function for getValue and getNonRegisterValue.
1916/// Create an SDValue for the given value.
1918 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1919
1920 if (const Constant *C = dyn_cast<Constant>(V)) {
1921 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1922
1923 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1924 SDLoc DL = getCurSDLoc();
1925
1926 // DAG.getConstant() may attempt to legalise the vector constant which can
1927 // significantly change the combines applied to the DAG. To reduce the
1928 // divergence when enabling ConstantInt based vectors we try to construct
1929 // the DAG in the same way as shufflevector based splats. TODO: The
1930 // divergence sometimes leads to better optimisations. Ideally we should
1931 // prevent DAG.getConstant() from legalising too early but there are some
1932 // degradations preventing this.
1933 if (VT.isScalableVector())
1934 return DAG.getNode(
1935 ISD::SPLAT_VECTOR, DL, VT,
1936 DAG.getConstant(CI->getValue(), DL, VT.getVectorElementType()));
1937 if (VT.isFixedLengthVector())
1938 return DAG.getSplatBuildVector(
1939 VT, DL,
1940 DAG.getConstant(CI->getValue(), DL, VT.getVectorElementType()));
1941 return DAG.getConstant(*CI, DL, VT);
1942 }
1943
1944 if (const ConstantByte *CB = dyn_cast<ConstantByte>(C))
1945 return DAG.getConstant(CB->getValue(), getCurSDLoc(), VT);
1946
1947 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1948 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1949
1950 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) {
1951 return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT,
1952 getValue(CPA->getPointer()), getValue(CPA->getKey()),
1953 getValue(CPA->getAddrDiscriminator()),
1954 getValue(CPA->getDiscriminator()));
1955 }
1956
1958 return DAG.getConstant(0, getCurSDLoc(), VT);
1959
1960 if (match(C, m_VScale()))
1961 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1962
1963 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1964 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1965
1966 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1967 return isa<PoisonValue>(C) ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
1968
1969 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1970 visit(CE->getOpcode(), *CE);
1971 SDValue N1 = NodeMap[V];
1972 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1973 return N1;
1974 }
1975
1977 SmallVector<SDValue, 4> Constants;
1978 for (const Use &U : C->operands()) {
1979 SDNode *Val = getValue(U).getNode();
1980 // If the operand is an empty aggregate, there are no values.
1981 if (!Val) continue;
1982 // Add each leaf value from the operand to the Constants list
1983 // to form a flattened list of all the values.
1984 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1985 Constants.push_back(SDValue(Val, i));
1986 }
1987
1988 return DAG.getMergeValues(Constants, getCurSDLoc());
1989 }
1990
1991 if (const ConstantDataSequential *CDS =
1994 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i) {
1995 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1996 // Add each leaf value from the operand to the Constants list
1997 // to form a flattened list of all the values.
1998 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1999 Ops.push_back(SDValue(Val, i));
2000 }
2001
2002 if (isa<ArrayType>(CDS->getType()))
2003 return DAG.getMergeValues(Ops, getCurSDLoc());
2004 return DAG.getBuildVector(VT, getCurSDLoc(), Ops);
2005 }
2006
2007 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
2009 "Unknown struct or array constant!");
2010
2011 SmallVector<EVT, 4> ValueVTs;
2012 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
2013 unsigned NumElts = ValueVTs.size();
2014 if (NumElts == 0)
2015 return SDValue(); // empty struct
2016 SmallVector<SDValue, 4> Constants(NumElts);
2017 for (unsigned i = 0; i != NumElts; ++i) {
2018 EVT EltVT = ValueVTs[i];
2019 if (isa<UndefValue>(C))
2020 Constants[i] = DAG.getUNDEF(EltVT);
2021 else if (EltVT.isFloatingPoint())
2022 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
2023 else
2024 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
2025 }
2026
2027 return DAG.getMergeValues(Constants, getCurSDLoc());
2028 }
2029
2030 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
2031 return DAG.getBlockAddress(BA, VT);
2032
2033 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
2034 return getValue(Equiv->getGlobalValue());
2035
2036 if (const auto *NC = dyn_cast<NoCFIValue>(C))
2037 return getValue(NC->getGlobalValue());
2038
2039 if (VT == MVT::aarch64svcount) {
2040 assert(C->isNullValue() && "Can only zero this target type!");
2041 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
2042 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
2043 }
2044
2045 if (VT.isRISCVVectorTuple()) {
2046 assert(C->isNullValue() && "Can only zero this target type!");
2047 return DAG.getNode(
2049 DAG.getNode(
2051 EVT::getVectorVT(*DAG.getContext(), MVT::i8,
2052 VT.getSizeInBits().getKnownMinValue() / 8, true),
2053 DAG.getConstant(0, getCurSDLoc(), MVT::getIntegerVT(8))));
2054 }
2055
2056 if (VT == MVT::externref || VT == MVT::funcref) {
2057 assert(C->isNullValue() && "Can only zero this target type!");
2058 // The zero value of a WebAssembly reference type is the null reference,
2059 // materialized with ref.null.
2060 Intrinsic::ID IID = VT == MVT::externref ? Intrinsic::wasm_ref_null_extern
2061 : Intrinsic::wasm_ref_null_func;
2062 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VT,
2063 DAG.getTargetConstant(IID, getCurSDLoc(), MVT::i32));
2064 }
2065
2066 VectorType *VecTy = cast<VectorType>(V->getType());
2067
2068 // Now that we know the number and type of the elements, get that number of
2069 // elements into the Ops array based on what kind of constant it is.
2070 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
2072 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
2073 for (unsigned i = 0; i != NumElements; ++i)
2074 Ops.push_back(getValue(CV->getOperand(i)));
2075
2076 return DAG.getBuildVector(VT, getCurSDLoc(), Ops);
2077 }
2078
2080 EVT EltVT =
2081 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
2082
2083 SDValue Op;
2084 if (EltVT.isFloatingPoint())
2085 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
2086 else
2087 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
2088
2089 return DAG.getSplat(VT, getCurSDLoc(), Op);
2090 }
2091
2092 llvm_unreachable("Unknown vector constant");
2093 }
2094
2095 // If this is a static alloca, generate it as the frameindex instead of
2096 // computation.
2097 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
2098 auto SI = FuncInfo.StaticAllocaMap.find(AI);
2099 if (SI != FuncInfo.StaticAllocaMap.end())
2100 return DAG.getFrameIndex(
2101 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
2102 }
2103
2104 // If this is an instruction which fast-isel has deferred, select it now.
2105 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
2106 Register InReg = FuncInfo.InitializeRegForValue(Inst);
2107 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
2108 Inst->getType(), std::nullopt);
2109 SDValue Chain = DAG.getEntryNode();
2110 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
2111 }
2112
2113 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
2114 return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
2115
2116 if (const auto *BB = dyn_cast<BasicBlock>(V))
2117 return DAG.getBasicBlock(FuncInfo.getMBB(BB));
2118
2119 llvm_unreachable("Can't get register for value!");
2120}
2121
2122void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
2124 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
2125 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
2126 bool IsSEH = isAsynchronousEHPersonality(Pers);
2127 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
2128 if (IsSEH) {
2129 // For SEH, EHCont Guard needs to know that this catchpad is a target.
2130 CatchPadMBB->setIsEHContTarget(true);
2132 } else
2133 CatchPadMBB->setIsEHScopeEntry();
2134 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
2135 if (IsMSVCCXX || IsCoreCLR)
2136 CatchPadMBB->setIsEHFuncletEntry();
2137}
2138
2139void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
2140 // Update machine-CFG edge.
2141 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor());
2142 FuncInfo.MBB->addSuccessor(TargetMBB);
2143
2144 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2145 bool IsSEH = isAsynchronousEHPersonality(Pers);
2146 if (IsSEH) {
2147 // If this is not a fall-through branch or optimizations are switched off,
2148 // emit the branch.
2149 if (TargetMBB != NextBlock(FuncInfo.MBB) ||
2150 TM.getOptLevel() == CodeGenOptLevel::None)
2151 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2152 getControlRoot(), DAG.getBasicBlock(TargetMBB)));
2153 return;
2154 }
2155
2156 // For non-SEH, EHCont Guard needs to know that this catchret is a target.
2157 TargetMBB->setIsEHContTarget(true);
2158 DAG.getMachineFunction().setHasEHContTarget(true);
2159
2160 // Figure out the funclet membership for the catchret's successor.
2161 // This will be used by the FuncletLayout pass to determine how to order the
2162 // BB's.
2163 // A 'catchret' returns to the outer scope's color.
2164 Value *ParentPad = I.getCatchSwitchParentPad();
2165 const BasicBlock *SuccessorColor;
2166 if (isa<ConstantTokenNone>(ParentPad))
2167 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2168 else
2169 SuccessorColor = cast<Instruction>(ParentPad)->getParent();
2170 assert(SuccessorColor && "No parent funclet for catchret!");
2171 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor);
2172 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2173
2174 // Create the terminator node.
2175 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2176 getControlRoot(), DAG.getBasicBlock(TargetMBB),
2177 DAG.getBasicBlock(SuccessorColorMBB));
2178 DAG.setRoot(Ret);
2179}
2180
2181void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2182 // Don't emit any special code for the cleanuppad instruction. It just marks
2183 // the start of an EH scope/funclet.
2184 FuncInfo.MBB->setIsEHScopeEntry();
2185 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2186 if (Pers != EHPersonality::Wasm_CXX && Pers != EHPersonality::Wasm_D) {
2187 FuncInfo.MBB->setIsEHFuncletEntry();
2188 FuncInfo.MBB->setIsCleanupFuncletEntry();
2189 }
2190}
2191
2192/// When an invoke or a cleanupret unwinds to the next EH pad, there are
2193/// many places it could ultimately go. In the IR, we have a single unwind
2194/// destination, but in the machine CFG, we enumerate all the possible blocks.
2195/// This function skips over imaginary basic blocks that hold catchswitch
2196/// instructions, and finds all the "real" machine
2197/// basic block destinations. As those destinations may not be successors of
2198/// EHPadBB, here we also calculate the edge probability to those destinations.
2199/// The passed-in Prob is the edge probability to EHPadBB.
2201 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2202 BranchProbability Prob,
2203 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2204 &UnwindDests) {
2205 EHPersonality Personality =
2207 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2208 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2209 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2210 bool IsWasmD = Personality == EHPersonality::Wasm_D;
2211 bool IsSEH = isAsynchronousEHPersonality(Personality);
2212
2213 while (EHPadBB) {
2215 BasicBlock *NewEHPadBB = nullptr;
2216 if (isa<LandingPadInst>(Pad)) {
2217 // Stop on landingpads. They are not funclets.
2218 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2219 break;
2220 } else if (isa<CleanupPadInst>(Pad)) {
2221 // Stop on cleanup pads. Cleanups are always funclet entries for all known
2222 // personalities except Wasm. And in Wasm this becomes a catch_all(_ref),
2223 // which always catches an exception.
2224 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2225 UnwindDests.back().first->setIsEHScopeEntry();
2226 // In Wasm, EH scopes are not funclets
2227 if (!IsWasmCXX && !IsWasmD)
2228 UnwindDests.back().first->setIsEHFuncletEntry();
2229 break;
2230 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2231 // Add the catchpad handlers to the possible destinations.
2232 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2233 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2234 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2235 if (IsMSVCCXX || IsCoreCLR)
2236 UnwindDests.back().first->setIsEHFuncletEntry();
2237 if (!IsSEH)
2238 UnwindDests.back().first->setIsEHScopeEntry();
2239 }
2240 NewEHPadBB = CatchSwitch->getUnwindDest();
2241 } else {
2242 continue;
2243 }
2244
2245 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2246 if (BPI && NewEHPadBB)
2247 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2248 EHPadBB = NewEHPadBB;
2249 }
2250}
2251
2252void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2253 // Update successor info.
2255 auto UnwindDest = I.getUnwindDest();
2256 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2257 BranchProbability UnwindDestProb =
2258 (BPI && UnwindDest)
2259 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2261 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2262 for (auto &UnwindDest : UnwindDests) {
2263 UnwindDest.first->setIsEHPad();
2264 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2265 }
2266 FuncInfo.MBB->normalizeSuccProbs();
2267
2268 // Create the terminator node.
2269 MachineBasicBlock *CleanupPadMBB =
2270 FuncInfo.getMBB(I.getCleanupPad()->getParent());
2271 SDValue Ret = DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other,
2272 getControlRoot(), DAG.getBasicBlock(CleanupPadMBB));
2273 DAG.setRoot(Ret);
2274}
2275
2276void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2277 report_fatal_error("visitCatchSwitch not yet implemented!");
2278}
2279
2280void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2281 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2282 auto &DL = DAG.getDataLayout();
2283 SDValue Chain = getControlRoot();
2286
2287 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2288 // lower
2289 //
2290 // %val = call <ty> @llvm.experimental.deoptimize()
2291 // ret <ty> %val
2292 //
2293 // differently.
2294 if (I.getParent()->getTerminatingDeoptimizeCall()) {
2296 return;
2297 }
2298
2299 if (!FuncInfo.CanLowerReturn) {
2300 Register DemoteReg = FuncInfo.DemoteRegister;
2301
2302 // Emit a store of the return value through the virtual register.
2303 // Leave Outs empty so that LowerReturn won't try to load return
2304 // registers the usual way.
2305 MVT PtrValueVT = TLI.getPointerTy(DL, DL.getAllocaAddrSpace());
2306 SDValue RetPtr =
2307 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVT);
2308 Type *RetTy = I.getOperand(0)->getType();
2309 Align BaseAlign = DL.getPrefTypeAlign(RetTy);
2310 RetPtr =
2311 TLI.annotateStackObjectPointer(RetPtr, DAG, getCurSDLoc(), BaseAlign);
2312 SDValue RetOp = getValue(I.getOperand(0));
2313
2314 SmallVector<EVT, 4> ValueVTs, MemVTs;
2315 SmallVector<uint64_t, 4> Offsets;
2316 ComputeValueVTs(TLI, DL, RetTy, ValueVTs, &MemVTs, &Offsets, 0);
2317 unsigned NumValues = ValueVTs.size();
2318
2319 SmallVector<SDValue, 4> Chains(NumValues);
2320 for (unsigned i = 0; i != NumValues; ++i) {
2321 // An aggregate return value cannot wrap around the address space, so
2322 // offsets to its parts don't wrap either.
2323 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2324 TypeSize::getFixed(Offsets[i]));
2325
2326 SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2327 if (MemVTs[i] != ValueVTs[i])
2328 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2329 Chains[i] = DAG.getStore(
2330 Chain, getCurSDLoc(), Val,
2331 // FIXME: better loc info would be nice.
2332 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2333 commonAlignment(BaseAlign, Offsets[i]));
2334 }
2335
2336 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2337 MVT::Other, Chains);
2338 } else if (I.getNumOperands() != 0) {
2340 ComputeValueTypes(DL, I.getOperand(0)->getType(), Types);
2341 unsigned NumValues = Types.size();
2342 if (NumValues) {
2343 SDValue RetOp = getValue(I.getOperand(0));
2344
2345 const Function *F = I.getParent()->getParent();
2346
2348 I.getOperand(0)->getType(), F->getCallingConv(),
2349 /*IsVarArg*/ false, DL);
2350
2352 if (F->getAttributes().hasRetAttr(Attribute::SExt))
2354 else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2356
2357 LLVMContext &Context = F->getContext();
2358 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2359
2360 for (unsigned j = 0; j != NumValues; ++j) {
2361 EVT VT = TLI.getValueType(DL, Types[j]);
2362
2363 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2365
2366 CallingConv::ID CC = F->getCallingConv();
2367
2369 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2372 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2373 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2374
2375 // 'inreg' on function refers to return value
2376 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2377 if (RetInReg)
2378 Flags.setInReg();
2379
2380 if (I.getOperand(0)->getType()->isPointerTy()) {
2381 Flags.setPointer();
2382 Flags.setPointerAddrSpace(
2383 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2384 }
2385
2386 if (NeedsRegBlock) {
2387 Flags.setInConsecutiveRegs();
2388 if (j == NumValues - 1)
2389 Flags.setInConsecutiveRegsLast();
2390 }
2391
2392 // Propagate extension type if any
2394 Flags.setSExt();
2395 else if (ExtendKind == ISD::ZERO_EXTEND)
2396 Flags.setZExt();
2397 else if (F->getAttributes().hasRetAttr(Attribute::NoExt))
2398 Flags.setNoExt();
2399
2400 for (unsigned i = 0; i < NumParts; ++i) {
2401 Outs.push_back(ISD::OutputArg(Flags,
2402 Parts[i].getValueType().getSimpleVT(),
2403 VT, Types[j], 0, 0));
2404 OutVals.push_back(Parts[i]);
2405 }
2406 }
2407 }
2408 }
2409
2410 // Push in swifterror virtual register as the last element of Outs. This makes
2411 // sure swifterror virtual register will be returned in the swifterror
2412 // physical register.
2413 const Function *F = I.getParent()->getParent();
2414 if (TLI.supportSwiftError() &&
2415 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2416 assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2417 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2418 Flags.setSwiftError();
2419 Outs.push_back(ISD::OutputArg(Flags, /*vt=*/TLI.getPointerTy(DL),
2420 /*argvt=*/EVT(TLI.getPointerTy(DL)),
2421 PointerType::getUnqual(*DAG.getContext()),
2422 /*origidx=*/1, /*partOffs=*/0));
2423 // Create SDNode for the swifterror virtual register.
2424 OutVals.push_back(
2425 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2426 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2427 EVT(TLI.getPointerTy(DL))));
2428 }
2429
2430 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2431 CallingConv::ID CallConv =
2432 DAG.getMachineFunction().getFunction().getCallingConv();
2433 Chain = DAG.getTargetLoweringInfo().LowerReturn(
2434 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2435
2436 // Verify that the target's LowerReturn behaved as expected.
2437 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2438 "LowerReturn didn't return a valid chain!");
2439
2440 // Update the DAG with the new chain value resulting from return lowering.
2441 DAG.setRoot(Chain);
2442}
2443
2444/// CopyToExportRegsIfNeeded - If the given value has virtual registers
2445/// created for it, emit nodes to copy the value into the virtual
2446/// registers.
2448 // Skip empty types
2449 if (V->getType()->isEmptyTy())
2450 return;
2451
2452 auto VMI = FuncInfo.ValueMap.find(V);
2453 if (VMI != FuncInfo.ValueMap.end()) {
2454 assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2455 "Unused value assigned virtual registers!");
2456 CopyValueToVirtualRegister(V, VMI->second);
2457 }
2458}
2459
2460/// ExportFromCurrentBlock - If this condition isn't known to be exported from
2461/// the current basic block, add it to ValueMap now so that we'll get a
2462/// CopyTo/FromReg.
2464 // No need to export constants.
2465 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2466
2467 // Already exported?
2468 if (FuncInfo.isExportedInst(V)) return;
2469
2470 Register Reg = FuncInfo.InitializeRegForValue(V);
2472}
2473
2475 const BasicBlock *FromBB) {
2476 // The operands of the setcc have to be in this block. We don't know
2477 // how to export them from some other block.
2478 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2479 // Can export from current BB.
2480 if (VI->getParent() == FromBB)
2481 return true;
2482
2483 // Is already exported, noop.
2484 return FuncInfo.isExportedInst(V);
2485 }
2486
2487 // If this is an argument, we can export it if the BB is the entry block or
2488 // if it is already exported.
2489 if (isa<Argument>(V)) {
2490 if (FromBB->isEntryBlock())
2491 return true;
2492
2493 // Otherwise, can only export this if it is already exported.
2494 return FuncInfo.isExportedInst(V);
2495 }
2496
2497 // Otherwise, constants can always be exported.
2498 return true;
2499}
2500
2501/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2503SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2504 const MachineBasicBlock *Dst) const {
2506 const BasicBlock *SrcBB = Src->getBasicBlock();
2507 const BasicBlock *DstBB = Dst->getBasicBlock();
2508 if (!BPI) {
2509 // If BPI is not available, set the default probability as 1 / N, where N is
2510 // the number of successors.
2511 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2512 return BranchProbability(1, SuccSize);
2513 }
2514 return BPI->getEdgeProbability(SrcBB, DstBB);
2515}
2516
2517void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2518 MachineBasicBlock *Dst,
2519 BranchProbability Prob) {
2520 if (!FuncInfo.BPI)
2521 Src->addSuccessorWithoutProb(Dst);
2522 else {
2523 if (Prob.isUnknown())
2524 Prob = getEdgeProbability(Src, Dst);
2525 Src->addSuccessor(Dst, Prob);
2526 }
2527}
2528
2529static bool InBlock(const Value *V, const BasicBlock *BB) {
2530 if (const Instruction *I = dyn_cast<Instruction>(V))
2531 return I->getParent() == BB;
2532 return true;
2533}
2534
2535/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2536/// This function emits a branch and is used at the leaves of an OR or an
2537/// AND operator tree.
2538void
2541 MachineBasicBlock *FBB,
2542 MachineBasicBlock *CurBB,
2543 MachineBasicBlock *SwitchBB,
2544 BranchProbability TProb,
2545 BranchProbability FProb,
2546 bool InvertCond) {
2547 const BasicBlock *BB = CurBB->getBasicBlock();
2548
2549 // If the leaf of the tree is a comparison, merge the condition into
2550 // the caseblock.
2551 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2552 // The operands of the cmp have to be in this block. We don't know
2553 // how to export them from some other block. If this is the first block
2554 // of the sequence, no exporting is needed.
2555 if (CurBB == SwitchBB ||
2556 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2557 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2558 ISD::CondCode Condition;
2559 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2560 ICmpInst::Predicate Pred =
2561 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2562 Condition = getICmpCondCode(Pred);
2563 } else {
2564 const FCmpInst *FC = cast<FCmpInst>(Cond);
2565 FCmpInst::Predicate Pred =
2566 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2567 Condition = getFCmpCondCode(Pred);
2568 if (FC->hasNoNaNs() ||
2569 (isKnownNeverNaN(FC->getOperand(0),
2570 SimplifyQuery(DAG.getDataLayout(), FC)) &&
2571 isKnownNeverNaN(FC->getOperand(1),
2572 SimplifyQuery(DAG.getDataLayout(), FC))))
2573 Condition = getFCmpCodeWithoutNaN(Condition);
2574 }
2575
2576 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2577 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2578 SL->SwitchCases.push_back(CB);
2579 return;
2580 }
2581 }
2582
2583 // Create a CaseBlock record representing this branch.
2584 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2585 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2586 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2587 SL->SwitchCases.push_back(CB);
2588}
2589
2590// Collect dependencies on V recursively. This is used for the cost analysis in
2591// `shouldKeepJumpConditionsTogether`.
2595 unsigned Depth = 0) {
2596 // Return false if we have an incomplete count.
2598 return false;
2599
2600 auto *I = dyn_cast<Instruction>(V);
2601 if (I == nullptr)
2602 return true;
2603
2604 if (Necessary != nullptr) {
2605 // This instruction is necessary for the other side of the condition so
2606 // don't count it.
2607 if (Necessary->contains(I))
2608 return true;
2609 }
2610
2611 // Already added this dep.
2612 if (!Deps->try_emplace(I, false).second)
2613 return true;
2614
2615 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2616 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2617 Depth + 1))
2618 return false;
2619 return true;
2620}
2621
2624 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2626 if (Params.BaseCost < 0)
2627 return false;
2628
2629 // Baseline cost.
2630 InstructionCost CostThresh = Params.BaseCost;
2631
2632 BranchProbabilityInfo *BPI = nullptr;
2633 if (Params.LikelyBias || Params.UnlikelyBias)
2634 BPI = FuncInfo.BPI;
2635 if (BPI != nullptr) {
2636 // See if we are either likely to get an early out or compute both lhs/rhs
2637 // of the condition.
2638 BasicBlock *IfTrue = I.getSuccessor(0);
2639 BasicBlock *IfFalse = I.getSuccessor(1);
2641 std::swap(IfTrue, IfFalse);
2642
2643 std::optional<bool> Likely;
2644 if (BPI->isEdgeHot(I.getParent(), IfTrue))
2645 Likely = true;
2646 else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2647 Likely = false;
2648
2649 if (Likely) {
2650 if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2651 // Its likely we will have to compute both lhs and rhs of condition
2652 CostThresh += Params.LikelyBias;
2653 else {
2654 if (Params.UnlikelyBias < 0)
2655 return false;
2656 // Its likely we will get an early out.
2657 CostThresh -= Params.UnlikelyBias;
2658 }
2659 }
2660 }
2661
2662 if (CostThresh <= 0)
2663 return false;
2664
2665 // Collect "all" instructions that lhs condition is dependent on.
2666 // Use map for stable iteration (to avoid non-determanism of iteration of
2667 // SmallPtrSet). The `bool` value is just a dummy.
2669 collectInstructionDeps(&LhsDeps, Lhs);
2670 // Collect "all" instructions that rhs condition is dependent on AND are
2671 // dependencies of lhs. This gives us an estimate on which instructions we
2672 // stand to save by splitting the condition.
2673 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2674 return false;
2675 // Add the compare instruction itself unless its a dependency on the LHS.
2676 if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2677 if (!LhsDeps.contains(RhsI))
2678 RhsDeps.try_emplace(RhsI, false);
2679
2680 InstructionCost CostOfIncluding = 0;
2681 // See if this instruction will need to computed independently of whether RHS
2682 // is.
2683 Value *BrCond = I.getCondition();
2684 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2685 for (const auto *U : Ins->users()) {
2686 // If user is independent of RHS calculation we don't need to count it.
2687 if (auto *UIns = dyn_cast<Instruction>(U))
2688 if (UIns != BrCond && !RhsDeps.contains(UIns))
2689 return false;
2690 }
2691 return true;
2692 };
2693
2694 // Prune instructions from RHS Deps that are dependencies of unrelated
2695 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2696 // arbitrary and just meant to cap the how much time we spend in the pruning
2697 // loop. Its highly unlikely to come into affect.
2698 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2699 // Stop after a certain point. No incorrectness from including too many
2700 // instructions.
2701 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2702 const Instruction *ToDrop = nullptr;
2703 for (const auto &InsPair : RhsDeps) {
2704 if (!ShouldCountInsn(InsPair.first)) {
2705 ToDrop = InsPair.first;
2706 break;
2707 }
2708 }
2709 if (ToDrop == nullptr)
2710 break;
2711 RhsDeps.erase(ToDrop);
2712 }
2713
2714 for (const auto &InsPair : RhsDeps) {
2715 // Finally accumulate latency that we can only attribute to computing the
2716 // RHS condition. Use latency because we are essentially trying to calculate
2717 // the cost of the dependency chain.
2718 // Possible TODO: We could try to estimate ILP and make this more precise.
2719 CostOfIncluding += TTI->getInstructionCost(
2720 InsPair.first, TargetTransformInfo::TCK_Latency);
2721
2722 if (CostOfIncluding > CostThresh)
2723 return false;
2724 }
2725 return true;
2726}
2727
2730 MachineBasicBlock *FBB,
2731 MachineBasicBlock *CurBB,
2732 MachineBasicBlock *SwitchBB,
2734 BranchProbability TProb,
2735 BranchProbability FProb,
2736 bool InvertCond) {
2737 // Skip over not part of the tree and remember to invert op and operands at
2738 // next level.
2739 Value *NotCond;
2740 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2741 InBlock(NotCond, CurBB->getBasicBlock())) {
2742 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2743 !InvertCond);
2744 return;
2745 }
2746
2748 const Value *BOpOp0, *BOpOp1;
2749 // Compute the effective opcode for Cond, taking into account whether it needs
2750 // to be inverted, e.g.
2751 // and (not (or A, B)), C
2752 // gets lowered as
2753 // and (and (not A, not B), C)
2755 if (BOp) {
2756 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2757 ? Instruction::And
2758 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2759 ? Instruction::Or
2761 if (InvertCond) {
2762 if (BOpc == Instruction::And)
2763 BOpc = Instruction::Or;
2764 else if (BOpc == Instruction::Or)
2765 BOpc = Instruction::And;
2766 }
2767 }
2768
2769 // If this node is not part of the or/and tree, emit it as a branch.
2770 // Note that all nodes in the tree should have same opcode.
2771 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2772 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2773 !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2774 !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2775 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2776 TProb, FProb, InvertCond);
2777 return;
2778 }
2779
2780 // Create TmpBB after CurBB.
2781 MachineFunction::iterator BBI(CurBB);
2782 MachineFunction &MF = DAG.getMachineFunction();
2784 CurBB->getParent()->insert(++BBI, TmpBB);
2785
2786 if (Opc == Instruction::Or) {
2787 // Codegen X | Y as:
2788 // BB1:
2789 // jmp_if_X TBB
2790 // jmp TmpBB
2791 // TmpBB:
2792 // jmp_if_Y TBB
2793 // jmp FBB
2794 //
2795
2796 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2797 // The requirement is that
2798 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2799 // = TrueProb for original BB.
2800 // Assuming the original probabilities are A and B, one choice is to set
2801 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2802 // A/(1+B) and 2B/(1+B). This choice assumes that
2803 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2804 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2805 // TmpBB, but the math is more complicated.
2806
2807 auto NewTrueProb = TProb / 2;
2808 auto NewFalseProb = TProb / 2 + FProb;
2809 // Emit the LHS condition.
2810 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2811 NewFalseProb, InvertCond);
2812
2813 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2814 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2816 // Emit the RHS condition into TmpBB.
2817 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2818 Probs[1], InvertCond);
2819 } else {
2820 assert(Opc == Instruction::And && "Unknown merge op!");
2821 // Codegen X & Y as:
2822 // BB1:
2823 // jmp_if_X TmpBB
2824 // jmp FBB
2825 // TmpBB:
2826 // jmp_if_Y TBB
2827 // jmp FBB
2828 //
2829 // This requires creation of TmpBB after CurBB.
2830
2831 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2832 // The requirement is that
2833 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2834 // = FalseProb for original BB.
2835 // Assuming the original probabilities are A and B, one choice is to set
2836 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2837 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2838 // TrueProb for BB1 * FalseProb for TmpBB.
2839
2840 auto NewTrueProb = TProb + FProb / 2;
2841 auto NewFalseProb = FProb / 2;
2842 // Emit the LHS condition.
2843 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2844 NewFalseProb, InvertCond);
2845
2846 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2847 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2849 // Emit the RHS condition into TmpBB.
2850 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2851 Probs[1], InvertCond);
2852 }
2853}
2854
2855/// If the set of cases should be emitted as a series of branches, return true.
2856/// If we should emit this as a bunch of and/or'd together conditions, return
2857/// false.
2858bool
2859SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2860 if (Cases.size() != 2) return true;
2861
2862 // If this is two comparisons of the same values or'd or and'd together, they
2863 // will get folded into a single comparison, so don't emit two blocks.
2864 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2865 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2866 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2867 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2868 return false;
2869 }
2870
2871 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2872 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2873 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2874 Cases[0].CC == Cases[1].CC &&
2875 isa<Constant>(Cases[0].CmpRHS) &&
2876 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2877 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2878 return false;
2879 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2880 return false;
2881 }
2882
2883 return true;
2884}
2885
2886void SelectionDAGBuilder::visitUncondBr(const UncondBrInst &I) {
2888
2889 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2890
2891 // Update machine-CFG edges.
2892 BrMBB->addSuccessor(Succ0MBB);
2893
2894 // If this is not a fall-through branch or optimizations are switched off,
2895 // emit the branch.
2896 if (Succ0MBB != NextBlock(BrMBB) ||
2898 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2899 DAG.getBasicBlock(Succ0MBB));
2900 setValue(&I, Br);
2901 DAG.setRoot(Br);
2902 }
2903}
2904
2905void SelectionDAGBuilder::visitCondBr(const CondBrInst &I) {
2906 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2907
2908 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2909
2910 // If this condition is one of the special cases we handle, do special stuff
2911 // now.
2912 const Value *CondVal = I.getCondition();
2913 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1));
2914
2915 // If this is a series of conditions that are or'd or and'd together, emit
2916 // this as a sequence of branches instead of setcc's with and/or operations.
2917 // As long as jumps are not expensive (exceptions for multi-use logic ops,
2918 // unpredictable branches, and vector extracts because those jumps are likely
2919 // expensive for any target), this should improve performance.
2920 // For example, instead of something like:
2921 // cmp A, B
2922 // C = seteq
2923 // cmp D, E
2924 // F = setle
2925 // or C, F
2926 // jnz foo
2927 // Emit:
2928 // cmp A, B
2929 // je foo
2930 // cmp D, E
2931 // jle foo
2932 bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2933 const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2934 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2935 BOp->hasOneUse() && !IsUnpredictable) {
2936 Value *Vec;
2937 const Value *BOp0, *BOp1;
2939 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2940 Opcode = Instruction::And;
2941 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2942 Opcode = Instruction::Or;
2943
2944 if (Opcode &&
2945 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2946 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2948 FuncInfo, I, Opcode, BOp0, BOp1,
2949 DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2950 Opcode, BOp0, BOp1, FuncInfo.Fn))) {
2951 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2952 getEdgeProbability(BrMBB, Succ0MBB),
2953 getEdgeProbability(BrMBB, Succ1MBB),
2954 /*InvertCond=*/false);
2955 // If the compares in later blocks need to use values not currently
2956 // exported from this block, export them now. This block should always
2957 // be the first entry.
2958 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2959
2960 // Allow some cases to be rejected.
2961 if (ShouldEmitAsBranches(SL->SwitchCases)) {
2962 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2963 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2964 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2965 }
2966
2967 // Emit the branch for this block.
2968 visitSwitchCase(SL->SwitchCases[0], BrMBB);
2969 SL->SwitchCases.erase(SL->SwitchCases.begin());
2970 return;
2971 }
2972
2973 // Okay, we decided not to do this, remove any inserted MBB's and clear
2974 // SwitchCases.
2975 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2976 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2977
2978 SL->SwitchCases.clear();
2979 }
2980 }
2981
2982 // Create a CaseBlock record representing this branch.
2983 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2984 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2986 IsUnpredictable);
2987
2988 // Use visitSwitchCase to actually insert the fast branch sequence for this
2989 // cond branch.
2990 visitSwitchCase(CB, BrMBB);
2991}
2992
2993/// visitSwitchCase - Emits the necessary code to represent a single node in
2994/// the binary search tree resulting from lowering a switch instruction.
2996 MachineBasicBlock *SwitchBB) {
2997 SDValue Cond;
2998 SDValue CondLHS = getValue(CB.CmpLHS);
2999 SDLoc dl = CB.DL;
3000
3001 if (CB.CC == ISD::SETTRUE) {
3002 // Branch or fall through to TrueBB.
3003 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
3004 SwitchBB->normalizeSuccProbs();
3005 if (CB.TrueBB != NextBlock(SwitchBB)) {
3006 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
3007 DAG.getBasicBlock(CB.TrueBB)));
3008 }
3009 return;
3010 }
3011
3012 auto &TLI = DAG.getTargetLoweringInfo();
3013 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
3014
3015 // Build the setcc now.
3016 if (!CB.CmpMHS) {
3017 // Fold "(X == true)" to X and "(X == false)" to !X to
3018 // handle common cases produced by branch lowering.
3019 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
3020 CB.CC == ISD::SETEQ)
3021 Cond = CondLHS;
3022 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
3023 CB.CC == ISD::SETEQ) {
3024 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
3025 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
3026 } else {
3027 SDValue CondRHS = getValue(CB.CmpRHS);
3028
3029 // If a pointer's DAG type is larger than its memory type then the DAG
3030 // values are zero-extended. This breaks signed comparisons so truncate
3031 // back to the underlying type before doing the compare.
3032 if (CondLHS.getValueType() != MemVT) {
3033 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
3034 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
3035 }
3036 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
3037 }
3038 } else {
3039 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
3040
3041 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
3042 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
3043
3044 SDValue CmpOp = getValue(CB.CmpMHS);
3045 EVT VT = CmpOp.getValueType();
3046
3047 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
3048 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
3049 ISD::SETLE);
3050 } else {
3051 SDValue SUB = DAG.getNode(ISD::SUB, dl,
3052 VT, CmpOp, DAG.getConstant(Low, dl, VT));
3053 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
3054 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
3055 }
3056 }
3057
3058 // Update successor info
3059 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
3060 // TrueBB and FalseBB are always different unless the incoming IR is
3061 // degenerate. This only happens when running llc on weird IR.
3062 if (CB.TrueBB != CB.FalseBB)
3063 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
3064 SwitchBB->normalizeSuccProbs();
3065
3066 // If the lhs block is the next block, invert the condition so that we can
3067 // fall through to the lhs instead of the rhs block.
3068 if (CB.TrueBB == NextBlock(SwitchBB)) {
3069 std::swap(CB.TrueBB, CB.FalseBB);
3070 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
3071 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
3072 }
3073
3074 SDNodeFlags Flags;
3076 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3077 Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
3078
3079 setValue(CurInst, BrCond);
3080
3081 // Insert the false branch. Do this even if it's a fall through branch,
3082 // this makes it easier to do DAG optimizations which require inverting
3083 // the branch condition.
3084 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3085 DAG.getBasicBlock(CB.FalseBB));
3086
3087 DAG.setRoot(BrCond);
3088}
3089
3090/// visitJumpTable - Emit JumpTable node in the current MBB
3092 // Emit the code for the jump table
3093 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3094 assert(JT.Reg && "Should lower JT Header first!");
3095 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
3096 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
3097 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
3098 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
3099 Index.getValue(1), Table, Index);
3100 DAG.setRoot(BrJumpTable);
3101}
3102
3103/// visitJumpTableHeader - This function emits necessary code to produce index
3104/// in the JumpTable from switch case.
3106 JumpTableHeader &JTH,
3107 MachineBasicBlock *SwitchBB) {
3108 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3109 const SDLoc &dl = *JT.SL;
3110
3111 // Subtract the lowest switch case value from the value being switched on.
3112 SDValue SwitchOp = getValue(JTH.SValue);
3113 EVT VT = SwitchOp.getValueType();
3114 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3115 DAG.getConstant(JTH.First, dl, VT));
3116
3117 // The SDNode we just created, which holds the value being switched on minus
3118 // the smallest case value, needs to be copied to a virtual register so it
3119 // can be used as an index into the jump table in a subsequent basic block.
3120 // This value may be smaller or larger than the target's pointer type, and
3121 // therefore require extension or truncating.
3122 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3123 SwitchOp =
3124 DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3125
3126 Register JumpTableReg =
3127 FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3128 SDValue CopyTo =
3129 DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3130 JT.Reg = JumpTableReg;
3131
3132 if (!JTH.FallthroughUnreachable) {
3133 // Emit the range check for the jump table, and branch to the default block
3134 // for the switch statement if the value being switched on exceeds the
3135 // largest case in the switch.
3136 SDValue CMP = DAG.getSetCC(
3137 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3138 Sub.getValueType()),
3139 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3140
3141 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3142 MVT::Other, CopyTo, CMP,
3143 DAG.getBasicBlock(JT.Default));
3144
3145 // Avoid emitting unnecessary branches to the next block.
3146 if (JT.MBB != NextBlock(SwitchBB))
3147 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3148 DAG.getBasicBlock(JT.MBB));
3149
3150 DAG.setRoot(BrCond);
3151 } else {
3152 // Avoid emitting unnecessary branches to the next block.
3153 if (JT.MBB != NextBlock(SwitchBB))
3154 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3155 DAG.getBasicBlock(JT.MBB)));
3156 else
3157 DAG.setRoot(CopyTo);
3158 }
3159}
3160
3161/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3162/// variable if there exists one.
3164 SDValue &Chain) {
3166 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3167 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3169 Value *Global =
3170 TLI.getSDagStackGuard(*MF.getFunction().getParent(), DAG.getLibcalls());
3172 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3173 if (Global) {
3174 MachinePointerInfo MPInfo(Global);
3178 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
3179 DAG.setNodeMemRefs(Node, {MemRef});
3180 }
3181 if (PtrTy != PtrMemTy)
3182 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3183 return SDValue(Node, 0);
3184}
3185
3186/// Codegen a new tail for a stack protector check ParentMBB which has had its
3187/// tail spliced into a stack protector check success bb.
3188///
3189/// For a high level explanation of how this fits into the stack protector
3190/// generation see the comment on the declaration of class
3191/// StackProtectorDescriptor.
3193 MachineBasicBlock *ParentBB) {
3194
3195 // First create the loads to the guard/stack slot for the comparison.
3196 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3197 auto &DL = DAG.getDataLayout();
3198 EVT PtrTy = TLI.getFrameIndexTy(DL);
3199 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3200
3201 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3202 int FI = MFI.getStackProtectorIndex();
3203
3204 SDValue Guard;
3205 SDLoc dl = getCurSDLoc();
3206 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3207 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3208 Align Align = DL.getPrefTypeAlign(
3209 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3210
3211 // Generate code to load the content of the guard slot.
3212 SDValue GuardVal = DAG.getLoad(
3213 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3214 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3216
3217 // If cookie mixing is enabled, unmix the stored GuardVal to get back the
3218 // original cookie for comparison. The prologue stored (FP - Cookie) or
3219 // (FP XOR Cookie), so we apply the same operation again to unmix:
3220 // FP - (FP - Cookie) = Cookie, or (FP XOR Cookie) XOR FP = Cookie.
3221 if (TLI.useStackGuardMixFP())
3222 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3223
3224 // If we're using function-based instrumentation, call the guard check
3225 // function
3227 // Get the guard check function from the target and verify it exists since
3228 // we're using function-based instrumentation
3229 const Function *GuardCheckFn =
3230 TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3231 assert(GuardCheckFn && "Guard check function is null");
3232
3233 // The target provides a guard check function to validate the guard value.
3234 // Generate a call to that function with the content of the guard slot as
3235 // argument.
3236 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3237 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3238
3240 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3241 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3242 Entry.IsInReg = true;
3243 Args.push_back(Entry);
3244
3247 .setChain(DAG.getEntryNode())
3248 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3249 getValue(GuardCheckFn), std::move(Args));
3250
3251 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3252 DAG.setRoot(Result.second);
3253 return;
3254 }
3255
3256 // Load the fresh guard value for comparison.
3257 // For targets that mix the cookie in LOAD_STACK_GUARD expansion, we need to
3258 // load directly without using LOAD_STACK_GUARD to avoid unwanted mixing.
3259 SDValue Chain = DAG.getEntryNode();
3260 if (TLI.useStackGuardMixFP()) {
3261 // Mixing targets: load cookie directly to avoid mixing in LOAD_STACK_GUARD
3262 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3263 SDValue GuardPtr = getValue(IRGuard);
3264 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3265 MachinePointerInfo(IRGuard, 0), Align,
3267 } else {
3268 LLVMContext &Ctx = *DAG.getContext();
3269 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3270 Guard = DAG.getPOISON(PtrMemTy);
3271 }
3272 } else {
3273 // Non-mixing targets: use LOAD_STACK_GUARD or direct load as usual
3274 if (TLI.useLoadStackGuardNode(M)) {
3275 Guard = getLoadStackGuard(DAG, dl, Chain);
3276 } else {
3277 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3278 SDValue GuardPtr = getValue(IRGuard);
3279 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3280 MachinePointerInfo(IRGuard, 0), Align,
3282 } else {
3283 LLVMContext &Ctx = *DAG.getContext();
3284 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3285 Guard = DAG.getPOISON(PtrMemTy);
3286 }
3287 }
3288 }
3289
3290 // Now both Guard (fresh cookie) and GuardVal (unmixed from stored value)
3291 // contain unmixed cookie values that can be compared directly.
3292
3293 // Perform the comparison via a getsetcc.
3294 SDValue Cmp = DAG.getSetCC(
3295 dl, TLI.getSetCCResultType(DL, *DAG.getContext(), Guard.getValueType()),
3296 Guard, GuardVal, ISD::SETNE);
3297
3298 // If the guard/stackslot do not equal, branch to failure MBB.
3299 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3300 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3301 // Otherwise branch to success MBB.
3302 SDValue Br = DAG.getNode(ISD::BR, dl,
3303 MVT::Other, BrCond,
3304 DAG.getBasicBlock(SPD.getSuccessMBB()));
3305
3306 DAG.setRoot(Br);
3307}
3308
3309/// Codegen the failure basic block for a stack protector check.
3310///
3311/// A failure stack protector machine basic block consists simply of a call to
3312/// __stack_chk_fail().
3313///
3314/// For a high level explanation of how this fits into the stack protector
3315/// generation see the comment on the declaration of class
3316/// StackProtectorDescriptor.
3319
3320 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3321 MachineBasicBlock *ParentBB = SPD.getParentMBB();
3322 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3323 SDValue Chain;
3324
3325 // For -Oz builds with a guard check function, we use function-based
3326 // instrumentation. Otherwise, if we have a guard check function, we call it
3327 // in the failure block.
3328 auto *GuardCheckFn = TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3329 if (GuardCheckFn && !SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3330 // First create the loads to the guard/stack slot for the comparison.
3331 auto &DL = DAG.getDataLayout();
3332 EVT PtrTy = TLI.getFrameIndexTy(DL);
3333 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3334
3335 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3336 int FI = MFI.getStackProtectorIndex();
3337
3338 SDLoc dl = getCurSDLoc();
3339 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3340 Align Align = DL.getPrefTypeAlign(
3341 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3342
3343 // Generate code to load the content of the guard slot.
3344 SDValue GuardVal = DAG.getLoad(
3345 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3346 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3348
3349 if (TLI.useStackGuardMixFP())
3350 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3351
3352 // The target provides a guard check function to validate the guard value.
3353 // Generate a call to that function with the content of the guard slot as
3354 // argument.
3355 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3356 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3357
3359 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3360 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3361 Entry.IsInReg = true;
3362 Args.push_back(Entry);
3363
3366 .setChain(DAG.getEntryNode())
3367 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3368 getValue(GuardCheckFn), std::move(Args));
3369
3370 Chain = TLI.LowerCallTo(CLI).second;
3371 } else {
3373 CallOptions.setDiscardResult(true);
3374 Chain = TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3375 {}, CallOptions, getCurSDLoc())
3376 .second;
3377 }
3378
3379 // Emit a trap instruction if we are required to do so.
3380 const TargetOptions &TargetOpts = DAG.getTarget().Options;
3381 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3382 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3383
3384 DAG.setRoot(Chain);
3385}
3386
3387/// visitBitTestHeader - This function emits necessary code to produce value
3388/// suitable for "bit tests"
3390 MachineBasicBlock *SwitchBB) {
3391 SDLoc dl = getCurSDLoc();
3392
3393 // Subtract the minimum value.
3394 SDValue SwitchOp = getValue(B.SValue);
3395 EVT VT = SwitchOp.getValueType();
3396 SDValue RangeSub =
3397 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3398
3399 // Determine the type of the test operands.
3400 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3401 bool UsePtrType = false;
3402 if (!TLI.isTypeLegal(VT)) {
3403 UsePtrType = true;
3404 } else {
3405 for (const BitTestCase &Case : B.Cases)
3406 if (!isUIntN(VT.getSizeInBits(), Case.Mask)) {
3407 // Switch table case range are encoded into series of masks.
3408 // Just use pointer type, it's guaranteed to fit.
3409 UsePtrType = true;
3410 break;
3411 }
3412 }
3413 SDValue Sub = RangeSub;
3414 if (UsePtrType) {
3415 VT = TLI.getPointerTy(DAG.getDataLayout());
3416 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3417 }
3418
3419 B.RegVT = VT.getSimpleVT();
3420 B.Reg = FuncInfo.CreateReg(B.RegVT);
3421 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3422
3423 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3424
3425 if (!B.FallthroughUnreachable)
3426 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3427 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3428 SwitchBB->normalizeSuccProbs();
3429
3430 SDValue Root = CopyTo;
3431 if (!B.FallthroughUnreachable) {
3432 // Conditional branch to the default block.
3433 SDValue RangeCmp = DAG.getSetCC(dl,
3434 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3435 RangeSub.getValueType()),
3436 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3437 ISD::SETUGT);
3438
3439 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3440 DAG.getBasicBlock(B.Default));
3441 }
3442
3443 // Avoid emitting unnecessary branches to the next block.
3444 if (MBB != NextBlock(SwitchBB))
3445 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3446
3447 DAG.setRoot(Root);
3448}
3449
3450/// visitBitTestCase - this function produces one "bit test"
3452 MachineBasicBlock *NextMBB,
3453 BranchProbability BranchProbToNext,
3454 Register Reg, BitTestCase &B,
3455 MachineBasicBlock *SwitchBB) {
3456 SDLoc dl = getCurSDLoc();
3457 MVT VT = BB.RegVT;
3458 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3459 SDValue Cmp;
3460 unsigned PopCount = llvm::popcount(B.Mask);
3461 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3462 if (PopCount == 1) {
3463 // Testing for a single bit; just compare the shift count with what it
3464 // would need to be to shift a 1 bit in that position.
3465 Cmp = DAG.getSetCC(
3466 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3467 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3468 ISD::SETEQ);
3469 } else if (PopCount == BB.Range) {
3470 // There is only one zero bit in the range, test for it directly.
3471 Cmp = DAG.getSetCC(
3472 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3473 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3474 } else {
3475 // Make desired shift
3476 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3477 DAG.getConstant(1, dl, VT), ShiftOp);
3478
3479 // Emit bit tests and jumps
3480 SDValue AndOp = DAG.getNode(ISD::AND, dl,
3481 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3482 Cmp = DAG.getSetCC(
3483 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3484 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3485 }
3486
3487 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3488 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3489 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3490 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3491 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3492 // one as they are relative probabilities (and thus work more like weights),
3493 // and hence we need to normalize them to let the sum of them become one.
3494 SwitchBB->normalizeSuccProbs();
3495
3496 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3497 MVT::Other, getControlRoot(),
3498 Cmp, DAG.getBasicBlock(B.TargetBB));
3499
3500 // Avoid emitting unnecessary branches to the next block.
3501 if (NextMBB != NextBlock(SwitchBB))
3502 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3503 DAG.getBasicBlock(NextMBB));
3504
3505 DAG.setRoot(BrAnd);
3506}
3507
3508void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3509 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3510
3511 // Retrieve successors. Look through artificial IR level blocks like
3512 // catchswitch for successors.
3513 MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0));
3514 const BasicBlock *EHPadBB = I.getSuccessor(1);
3515 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB);
3516
3517 // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3518 // have to do anything here to lower funclet bundles.
3519 failForInvalidBundles(I, "invokes",
3525
3526 const Value *Callee(I.getCalledOperand());
3527 const Function *Fn = dyn_cast<Function>(Callee);
3528 if (isa<InlineAsm>(Callee))
3529 visitInlineAsm(I, EHPadBB);
3530 else if (Fn && Fn->isIntrinsic()) {
3531 switch (Fn->getIntrinsicID()) {
3532 default:
3533 llvm_unreachable("Cannot invoke this intrinsic");
3534 case Intrinsic::donothing:
3535 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3536 case Intrinsic::seh_try_begin:
3537 case Intrinsic::seh_scope_begin:
3538 case Intrinsic::seh_try_end:
3539 case Intrinsic::seh_scope_end:
3540 if (EHPadMBB)
3541 // a block referenced by EH table
3542 // so dtor-funclet not removed by opts
3543 EHPadMBB->setMachineBlockAddressTaken();
3544 break;
3545 case Intrinsic::experimental_patchpoint_void:
3546 case Intrinsic::experimental_patchpoint:
3547 visitPatchpoint(I, EHPadBB);
3548 break;
3549 case Intrinsic::experimental_gc_statepoint:
3551 break;
3552 // wasm_throw, wasm_rethrow: This is usually done in visitTargetIntrinsic,
3553 // but these intrinsics are special because they can be invoked, so we
3554 // manually lower it to a DAG node here.
3555 case Intrinsic::wasm_throw: {
3557 std::array<SDValue, 4> Ops = {
3558 getControlRoot(), // inchain for the terminator node
3559 DAG.getTargetConstant(Intrinsic::wasm_throw, getCurSDLoc(),
3560 TLI.getPointerTy(DAG.getDataLayout())),
3561 getValue(I.getArgOperand(0)), // tag
3562 getValue(I.getArgOperand(1)) // thrown value
3563 };
3564 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3565 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3566 break;
3567 }
3568 case Intrinsic::wasm_rethrow: {
3569 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3570 std::array<SDValue, 2> Ops = {
3571 getControlRoot(), // inchain for the terminator node
3572 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3573 TLI.getPointerTy(DAG.getDataLayout()))};
3574 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3575 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3576 break;
3577 }
3578 // EH labels mark it as an invoke site, like a call.
3579 case Intrinsic::bpf_unwind_exit: {
3580 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3581 MCSymbol *BeginLabel;
3582 std::array<SDValue, 2> Ops = {
3583 lowerStartEH(getControlRoot(), EHPadBB, BeginLabel),
3584 DAG.getTargetConstant(Intrinsic::bpf_unwind_exit, getCurSDLoc(),
3585 TLI.getPointerTy(DAG.getDataLayout()))};
3586 SDValue Chain =
3587 DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), MVT::Other, Ops);
3588 DAG.setRoot(lowerEndEH(Chain, &I, EHPadBB, BeginLabel));
3589 break;
3590 }
3591 }
3592 } else if (I.hasDeoptState()) {
3593 // Currently we do not lower any intrinsic calls with deopt operand bundles.
3594 // Eventually we will support lowering the @llvm.experimental.deoptimize
3595 // intrinsic, and right now there are no plans to support other intrinsics
3596 // with deopt state.
3597 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3598 } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3600 } else {
3601 LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3602 }
3603
3604 // If the value of the invoke is used outside of its defining block, make it
3605 // available as a virtual register.
3606 // We already took care of the exported value for the statepoint instruction
3607 // during call to the LowerStatepoint.
3608 if (!isa<GCStatepointInst>(I)) {
3610 }
3611
3613 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3614 BranchProbability EHPadBBProb =
3615 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3617 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3618
3619 // Update successor info.
3620 addSuccessorWithProb(InvokeMBB, Return);
3621 for (auto &UnwindDest : UnwindDests) {
3622 UnwindDest.first->setIsEHPad();
3623 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3624 }
3625 InvokeMBB->normalizeSuccProbs();
3626
3627 // Drop into normal successor.
3628 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3629 DAG.getBasicBlock(Return)));
3630}
3631
3632/// The intrinsics currently supported by callbr are implicit control flow
3633/// intrinsics such as amdgcn.kill.
3634/// - they should be called (no "dontcall-" attributes)
3635/// - they do not touch memory on the target (= !TLI.getTgtMemIntrinsic())
3636/// - they do not need custom argument handling (no
3637/// TLI.CollectTargetIntrinsicOperands())
3638void SelectionDAGBuilder::visitCallBrIntrinsic(const CallBrInst &I) {
3639#ifndef NDEBUG
3641 DAG.getTargetLoweringInfo().getTgtMemIntrinsic(
3642 Infos, I, DAG.getMachineFunction(), I.getIntrinsicID());
3643 assert(Infos.empty() && "Intrinsic touches memory");
3644#endif
3645
3646 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
3647
3649 getTargetIntrinsicOperands(I, HasChain, OnlyLoad);
3650 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
3651
3652 // Create the node.
3653 SDValue Result =
3654 getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
3655 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
3656
3657 setValue(&I, Result);
3658}
3659
3660void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3661 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3662
3663 if (I.isInlineAsm()) {
3664 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3665 // have to do anything here to lower funclet bundles.
3666 failForInvalidBundles(I, "callbrs",
3668 visitInlineAsm(I);
3669 } else {
3670 assert(!I.hasOperandBundles() &&
3671 "Can't have operand bundles for intrinsics");
3672 visitCallBrIntrinsic(I);
3673 }
3675
3676 // Retrieve successors.
3677 SmallPtrSet<BasicBlock *, 8> Dests;
3678 Dests.insert(I.getDefaultDest());
3679 MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest());
3680
3681 // Update successor info.
3682 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3683 // TODO: For most of the cases where there is an intrinsic callbr, we're
3684 // having exactly one indirect target, which will be unreachable. As soon as
3685 // this changes, we might need to enhance
3686 // Target->setIsInlineAsmBrIndirectTarget or add something similar for
3687 // intrinsic indirect branches.
3688 if (I.isInlineAsm()) {
3689 for (BasicBlock *Dest : I.getIndirectDests()) {
3690 MachineBasicBlock *Target = FuncInfo.getMBB(Dest);
3691 Target->setIsInlineAsmBrIndirectTarget();
3692 // If we introduce a type of asm goto statement that is permitted to use
3693 // an indirect call instruction to jump to its labels, then we should add
3694 // a call to Target->setMachineBlockAddressTaken() here, to mark the
3695 // target block as requiring a BTI.
3696
3697 Target->setLabelMustBeEmitted();
3698 // Don't add duplicate machine successors.
3699 if (Dests.insert(Dest).second)
3700 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3701 }
3702 }
3703 CallBrMBB->normalizeSuccProbs();
3704
3705 // Drop into default successor.
3706 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3707 MVT::Other, getControlRoot(),
3708 DAG.getBasicBlock(Return)));
3709}
3710
3711void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3712 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3713}
3714
3715void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3716 assert(FuncInfo.MBB->isEHPad() &&
3717 "Call to landingpad not in landing pad!");
3718
3719 // If there aren't registers to copy the values into (e.g., during SjLj
3720 // exceptions), then don't bother to create these DAG nodes.
3721 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3722 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3723 if (TLI.getExceptionPointerRegister(FuncInfo.ExceptionModel, PersonalityFn) ==
3724 0 &&
3726 PersonalityFn) == 0)
3727 return;
3728
3729 // If landingpad's return type is token type, we don't create DAG nodes
3730 // for its exception pointer and selector value. The extraction of exception
3731 // pointer or selector value from token type landingpads is not currently
3732 // supported.
3733 if (LP.getType()->isTokenTy())
3734 return;
3735
3736 // LangRef leaves the result type target-specific, so diagnose types this
3737 // lowering cannot represent instead of asserting.
3738 SDLoc dl = getCurSDLoc();
3740 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
3741 *LP.getFunction(),
3742 "landingpad result type must be a struct of an exception pointer and "
3743 "an integer selector",
3744 dl.getDebugLoc()));
3745 setValueToPoison(&LP, dl);
3746 return;
3747 }
3748
3749 SmallVector<EVT, 2> ValueVTs;
3750 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3751 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3752
3753 // Get the two live-in registers as SDValues. The physregs have already been
3754 // copied into virtual registers.
3755 SDValue Ops[2];
3756 if (FuncInfo.ExceptionPointerVirtReg) {
3757 Ops[0] = DAG.getZExtOrTrunc(
3758 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3759 FuncInfo.ExceptionPointerVirtReg,
3760 TLI.getPointerTy(DAG.getDataLayout())),
3761 dl, ValueVTs[0]);
3762 } else {
3763 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3764 }
3765 Ops[1] = DAG.getZExtOrTrunc(
3766 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3767 FuncInfo.ExceptionSelectorVirtReg,
3768 TLI.getPointerTy(DAG.getDataLayout())),
3769 dl, ValueVTs[1]);
3770
3771 // Merge into one.
3772 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3773 DAG.getVTList(ValueVTs), Ops);
3774 setValue(&LP, Res);
3775}
3776
3779 // Update JTCases.
3780 for (JumpTableBlock &JTB : SL->JTCases)
3781 if (JTB.first.HeaderBB == First)
3782 JTB.first.HeaderBB = Last;
3783
3784 // Update BitTestCases.
3785 for (BitTestBlock &BTB : SL->BitTestCases)
3786 if (BTB.Parent == First)
3787 BTB.Parent = Last;
3788}
3789
3790void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3791 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3792
3793 // Update machine-CFG edges with unique successors.
3795 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3796 BasicBlock *BB = I.getSuccessor(i);
3797 bool Inserted = Done.insert(BB).second;
3798 if (!Inserted)
3799 continue;
3800
3801 MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3802 addSuccessorWithProb(IndirectBrMBB, Succ);
3803 }
3804 IndirectBrMBB->normalizeSuccProbs();
3805
3807 MVT::Other, getControlRoot(),
3808 getValue(I.getAddress())));
3809}
3810
3811void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3812 if (!I.shouldLowerToTrap(DAG.getTarget().Options.TrapUnreachable,
3813 DAG.getTarget().Options.NoTrapAfterNoreturn))
3814 return;
3815
3816 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3817}
3818
3819void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3820 SDNodeFlags Flags;
3821 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3822 Flags.copyFMF(*FPOp);
3823
3824 SDValue Op = getValue(I.getOperand(0));
3825 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3826 Op, Flags);
3827 setValue(&I, UnNodeValue);
3828}
3829
3830void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3831 SDNodeFlags Flags;
3832 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3833 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3834 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3835 }
3836 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3837 Flags.setExact(ExactOp->isExact());
3838 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3839 Flags.setDisjoint(DisjointOp->isDisjoint());
3840 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3841 Flags.copyFMF(*FPOp);
3842
3843 SDValue Op1 = getValue(I.getOperand(0));
3844 SDValue Op2 = getValue(I.getOperand(1));
3845 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3846 Op1, Op2, Flags);
3847 setValue(&I, BinNodeValue);
3848}
3849
3850void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3851 SDValue Op1 = getValue(I.getOperand(0));
3852 SDValue Op2 = getValue(I.getOperand(1));
3853
3854 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3855 Op1.getValueType(), DAG.getDataLayout());
3856
3857 // Coerce the shift amount to the right type if we can. This exposes the
3858 // truncate or zext to optimization early.
3859 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3861 "Unexpected shift type");
3862 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3863 }
3864
3865 bool nuw = false;
3866 bool nsw = false;
3867 bool exact = false;
3868
3869 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3870
3871 if (const OverflowingBinaryOperator *OFBinOp =
3873 nuw = OFBinOp->hasNoUnsignedWrap();
3874 nsw = OFBinOp->hasNoSignedWrap();
3875 }
3876 if (const PossiblyExactOperator *ExactOp =
3878 exact = ExactOp->isExact();
3879 }
3880 SDNodeFlags Flags;
3881 Flags.setExact(exact);
3882 Flags.setNoSignedWrap(nsw);
3883 Flags.setNoUnsignedWrap(nuw);
3884 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3885 Flags);
3886 setValue(&I, Res);
3887}
3888
3889void SelectionDAGBuilder::visitSDiv(const User &I) {
3890 SDValue Op1 = getValue(I.getOperand(0));
3891 SDValue Op2 = getValue(I.getOperand(1));
3892
3893 SDNodeFlags Flags;
3894 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3895 cast<PossiblyExactOperator>(&I)->isExact());
3896 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3897 Op2, Flags));
3898}
3899
3900void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3901 ICmpInst::Predicate predicate = I.getPredicate();
3902 SDValue Op1 = getValue(I.getOperand(0));
3903 SDValue Op2 = getValue(I.getOperand(1));
3904 ISD::CondCode Opcode = getICmpCondCode(predicate);
3905
3906 auto &TLI = DAG.getTargetLoweringInfo();
3907 EVT MemVT =
3908 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3909
3910 // If a pointer's DAG type is larger than its memory type then the DAG values
3911 // are zero-extended. This breaks signed comparisons so truncate back to the
3912 // underlying type before doing the compare.
3913 if (Op1.getValueType() != MemVT) {
3914 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3915 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3916 }
3917
3918 SDNodeFlags Flags;
3919 Flags.setSameSign(I.hasSameSign());
3920
3921 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3922 I.getType());
3923 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode,
3924 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3925}
3926
3927void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3928 FCmpInst::Predicate predicate = I.getPredicate();
3929 SDValue Op1 = getValue(I.getOperand(0));
3930 SDValue Op2 = getValue(I.getOperand(1));
3931
3932 ISD::CondCode Condition = getFCmpCondCode(predicate);
3933 auto *FPMO = cast<FPMathOperator>(&I);
3934 if (FPMO->hasNoNaNs() ||
3935 (DAG.isKnownNeverNaN(Op1) && DAG.isKnownNeverNaN(Op2)))
3936 Condition = getFCmpCodeWithoutNaN(Condition);
3937
3938 SDNodeFlags Flags;
3939 Flags.copyFMF(*FPMO);
3940
3941 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3942 I.getType());
3943 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition,
3944 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3945}
3946
3947// Check if the condition of the select has one use or two users that are both
3948// selects with the same condition.
3949static bool hasOnlySelectUsers(const Value *Cond) {
3950 return llvm::all_of(Cond->users(), [](const Value *V) {
3951 return isa<SelectInst>(V);
3952 });
3953}
3954
3955void SelectionDAGBuilder::visitSelect(const User &I) {
3956 SmallVector<EVT, 4> ValueVTs;
3957 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3958 ValueVTs);
3959 unsigned NumValues = ValueVTs.size();
3960 if (NumValues == 0) return;
3961
3963 SDValue Cond = getValue(I.getOperand(0));
3964 SDValue LHSVal = getValue(I.getOperand(1));
3965 SDValue RHSVal = getValue(I.getOperand(2));
3966 SmallVector<SDValue, 1> BaseOps(1, Cond);
3968 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3969
3970 bool IsUnaryAbs = false;
3971 bool Negate = false;
3972
3973 SDNodeFlags Flags;
3974 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3975 Flags.copyFMF(*FPOp);
3976
3977 Flags.setUnpredictable(
3978 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3979
3980 // Min/max matching is only viable if all output VTs are the same.
3981 if (all_equal(ValueVTs)) {
3982 EVT VT = ValueVTs[0];
3983 LLVMContext &Ctx = *DAG.getContext();
3984 auto &TLI = DAG.getTargetLoweringInfo();
3985
3986 // We care about the legality of the operation after it has been type
3987 // legalized.
3989 VT = TLI.getTypeToTransformTo(Ctx, VT);
3990
3991 // If the vselect is legal, assume we want to leave this as a vector setcc +
3992 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3993 // min/max is legal on the scalar type.
3994 bool UseScalarMinMax = VT.isVector() &&
3996
3997 // ValueTracking's select pattern matching does not account for -0.0,
3998 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3999 // -0.0 is less than +0.0.
4000 const Value *LHS, *RHS;
4001 auto SPR = matchSelectPattern(&I, LHS, RHS);
4003 switch (SPR.Flavor) {
4004 case SPF_UMAX: Opc = ISD::UMAX; break;
4005 case SPF_UMIN: Opc = ISD::UMIN; break;
4006 case SPF_SMAX: Opc = ISD::SMAX; break;
4007 case SPF_SMIN: Opc = ISD::SMIN; break;
4008 case SPF_FMINNUM:
4010 break;
4011
4012 switch (SPR.NaNBehavior) {
4013 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
4014 case SPNB_RETURNS_ANY:
4015 case SPNB_RETURNS_NAN:
4016 break;
4017 case SPNB_RETURNS_OTHER:
4019 Flags.setNoSignedZeros(true);
4020 break;
4021 }
4022 break;
4023 case SPF_FMAXNUM:
4025 break;
4026
4027 switch (SPR.NaNBehavior) {
4028 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
4029 case SPNB_RETURNS_NAN:
4030 case SPNB_RETURNS_ANY:
4031 break;
4032 case SPNB_RETURNS_OTHER:
4034 Flags.setNoSignedZeros(true);
4035 break;
4036 }
4037 break;
4038 case SPF_NABS:
4039 Negate = true;
4040 [[fallthrough]];
4041 case SPF_ABS:
4042 IsUnaryAbs = true;
4043 Opc = ISD::ABS;
4044 break;
4045 default: break;
4046 }
4047
4048 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
4050 (UseScalarMinMax &&
4052 // If the underlying comparison instruction is used by any other
4053 // instruction, the consumed instructions won't be destroyed, so it is
4054 // not profitable to convert to a min/max.
4056 OpCode = Opc;
4057 LHSVal = getValue(LHS);
4058 RHSVal = getValue(RHS);
4059 BaseOps.clear();
4060 }
4061
4062 if (IsUnaryAbs) {
4063 OpCode = Opc;
4064 LHSVal = getValue(LHS);
4065 BaseOps.clear();
4066 }
4067 }
4068
4069 if (IsUnaryAbs) {
4070 for (unsigned i = 0; i != NumValues; ++i) {
4071 SDLoc dl = getCurSDLoc();
4072 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
4073 Values[i] =
4074 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
4075 if (Negate)
4076 Values[i] = DAG.getNegative(Values[i], dl, VT);
4077 }
4078 } else {
4079 for (unsigned i = 0; i != NumValues; ++i) {
4080 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
4081 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
4082 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
4083 Values[i] = DAG.getNode(
4084 OpCode, getCurSDLoc(),
4085 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
4086 }
4087 }
4088
4090 DAG.getVTList(ValueVTs), Values));
4091}
4092
4093void SelectionDAGBuilder::visitTrunc(const User &I) {
4094 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
4095 SDValue N = getValue(I.getOperand(0));
4096 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4097 I.getType());
4098 SDNodeFlags Flags;
4099 if (auto *Trunc = dyn_cast<TruncInst>(&I)) {
4100 Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
4101 Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
4102 }
4103
4104 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N, Flags));
4105}
4106
4107void SelectionDAGBuilder::visitZExt(const User &I) {
4108 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4109 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
4110 SDValue N = getValue(I.getOperand(0));
4111 auto &TLI = DAG.getTargetLoweringInfo();
4112 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4113
4114 SDNodeFlags Flags;
4115 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
4116 Flags.setNonNeg(PNI->hasNonNeg());
4117
4118 // Eagerly use nonneg information to canonicalize towards sign_extend if
4119 // that is the target's preference.
4120 // TODO: Let the target do this later.
4121 if (Flags.hasNonNeg() &&
4122 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
4123 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4124 return;
4125 }
4126
4127 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4128}
4129
4130void SelectionDAGBuilder::visitSExt(const User &I) {
4131 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4132 // SExt also can't be a cast to bool for same reason. So, nothing much to do
4133 SDValue N = getValue(I.getOperand(0));
4134 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4135 I.getType());
4136 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4137}
4138
4139void SelectionDAGBuilder::visitFPTrunc(const User &I) {
4140 // FPTrunc is never a no-op cast, no need to check
4141 SDValue N = getValue(I.getOperand(0));
4142 SDLoc dl = getCurSDLoc();
4143 SDNodeFlags Flags;
4144 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4145 Flags.copyFMF(*FPOp);
4146 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4147 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4148 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
4149 DAG.getTargetConstant(
4150 0, dl, TLI.getPointerTy(DAG.getDataLayout())),
4151 Flags));
4152}
4153
4154void SelectionDAGBuilder::visitFPExt(const User &I) {
4155 // FPExt is never a no-op cast, no need to check
4156 SDValue N = getValue(I.getOperand(0));
4157 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4158 I.getType());
4159 SDNodeFlags Flags;
4160 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4161 Flags.copyFMF(*FPOp);
4162 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4163}
4164
4165void SelectionDAGBuilder::visitFPToUI(const User &I) {
4166 // FPToUI is never a no-op cast, no need to check
4167 SDValue N = getValue(I.getOperand(0));
4168 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4169 I.getType());
4170 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
4171}
4172
4173void SelectionDAGBuilder::visitFPToSI(const User &I) {
4174 // FPToSI is never a no-op cast, no need to check
4175 SDValue N = getValue(I.getOperand(0));
4176 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4177 I.getType());
4178 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
4179}
4180
4181void SelectionDAGBuilder::visitUIToFP(const User &I) {
4182 // UIToFP is never a no-op cast, no need to check
4183 SDValue N = getValue(I.getOperand(0));
4184 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4185 I.getType());
4186 SDNodeFlags Flags;
4187 Flags.setNonNeg(cast<PossiblyNonNegInst>(&I)->hasNonNeg());
4188 Flags.copyFMF(*cast<FPMathOperator>(&I));
4189
4190 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4191}
4192
4193void SelectionDAGBuilder::visitSIToFP(const User &I) {
4194 // SIToFP is never a no-op cast, no need to check
4195 SDValue N = getValue(I.getOperand(0));
4196 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4197 I.getType());
4198 SDNodeFlags Flags;
4199 Flags.copyFMF(*cast<FPMathOperator>(&I));
4200
4201 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4202}
4203
4204void SelectionDAGBuilder::visitPtrToAddr(const User &I) {
4205 SDValue N = getValue(I.getOperand(0));
4206 // By definition the type of the ptrtoaddr must be equal to the address type.
4207 const auto &TLI = DAG.getTargetLoweringInfo();
4208 EVT AddrVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4209 // The address width must be smaller or equal to the pointer representation
4210 // width, so we lower ptrtoaddr as a truncate (possibly folded to a no-op).
4211 N = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), AddrVT, N);
4212 setValue(&I, N);
4213}
4214
4215void SelectionDAGBuilder::visitPtrToInt(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 = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4221 I.getType());
4222 EVT PtrMemVT =
4223 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
4224 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4225 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
4226 setValue(&I, N);
4227}
4228
4229void SelectionDAGBuilder::visitIntToPtr(const User &I) {
4230 // What to do depends on the size of the integer and the size of the pointer.
4231 // We can either truncate, zero extend, or no-op, accordingly.
4232 SDValue N = getValue(I.getOperand(0));
4233 auto &TLI = DAG.getTargetLoweringInfo();
4234 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4235 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4236 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4237 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
4238 setValue(&I, N);
4239}
4240
4241void SelectionDAGBuilder::visitBitCast(const User &I) {
4242 SDValue N = getValue(I.getOperand(0));
4243 SDLoc dl = getCurSDLoc();
4244 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4245 I.getType());
4246
4247 // BitCast assures us that source and destination are the same size so this is
4248 // either a BITCAST or a no-op.
4249 if (DestVT != N.getValueType())
4250 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
4251 DestVT, N)); // convert types.
4252 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
4253 // might fold any kind of constant expression to an integer constant and that
4254 // is not what we are looking for. Only recognize a bitcast of a genuine
4255 // constant integer as an opaque constant.
4256 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
4257 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
4258 /*isOpaque*/true));
4259 else
4260 setValue(&I, N); // noop cast.
4261}
4262
4263void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
4264 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4265 const Value *SV = I.getOperand(0);
4266 SDValue N = getValue(SV);
4267 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4268
4269 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
4270 unsigned DestAS = I.getType()->getPointerAddressSpace();
4271
4272 if (!TM.isNoopAddrSpaceCast(DAG.getDataLayout(), SrcAS, DestAS)) {
4273 SDNodeFlags Flags;
4274 if (const auto *ASC = dyn_cast<AddrSpaceCastInst>(&I))
4275 Flags.setNonNull(ASC->hasNonNull());
4276 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS, Flags);
4277 }
4278
4279 setValue(&I, N);
4280}
4281
4282void SelectionDAGBuilder::visitInsertElement(const User &I) {
4283 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4284 SDValue InVec = getValue(I.getOperand(0));
4285 SDValue InVal = getValue(I.getOperand(1));
4286 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
4287 TLI.getVectorIdxTy(DAG.getDataLayout()));
4289 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4290 InVec, InVal, InIdx));
4291}
4292
4293void SelectionDAGBuilder::visitBitInsert(const User &I) {
4294 SDValue Base = getValue(I.getOperand(0));
4295 SDValue Val = getValue(I.getOperand(1));
4296 SDValue Offset = getValue(I.getOperand(2));
4297 EVT BaseVT = Base.getValueType();
4298 EVT ValVT = Val.getValueType();
4299 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4300 SDLoc dl = getCurSDLoc();
4301
4302 assert(BaseVT.getSizeInBits() >= ValVT.getSizeInBits() &&
4303 "bitinsert val wider than base should be rejected by verifier");
4304
4305 // If Val is a float, cast it to an integer of the same bitwidth
4306 // so DAG.getZExtOrTrunc can process it safely.
4307 if (!ValVT.isInteger()) {
4308 ValVT = ValVT.changeTypeToInteger();
4309 Val = DAG.getBitcast(ValVT, Val);
4310 }
4311
4312 // Legalize shift amount to the target's shift amount type.
4313 EVT ShiftAmtTy = TLI.getShiftAmountTy(BaseVT, DAG.getDataLayout());
4314 SDValue LegalShiftAmount = DAG.getZExtOrTrunc(Offset, dl, ShiftAmtTy);
4315
4316 unsigned BaseBitWidth = BaseVT.getScalarSizeInBits();
4317 unsigned ValBitWidth = ValVT.getScalarSizeInBits();
4318 APInt InsertMask = APInt::getLowBitsSet(BaseBitWidth, ValBitWidth);
4319 SDValue ShiftedMask =
4320 DAG.getNode(ISD::SHL, dl, BaseVT, DAG.getConstant(InsertMask, dl, BaseVT),
4321 LegalShiftAmount);
4322 SDValue ClearMask = DAG.getNOT(dl, ShiftedMask, BaseVT);
4323 SDValue ClearedBase = DAG.getNode(ISD::AND, dl, BaseVT, Base, ClearMask);
4324
4325 SDValue ExtVal = DAG.getZExtOrTrunc(Val, dl, BaseVT);
4326 SDValue ShiftedVal =
4327 DAG.getNode(ISD::SHL, dl, BaseVT, ExtVal, LegalShiftAmount);
4328 SDValue Result = DAG.getNode(ISD::OR, dl, BaseVT, ClearedBase, ShiftedVal);
4329 setValue(&I, Result);
4330}
4331
4332void SelectionDAGBuilder::visitBitExtract(const User &I) {
4333 SDValue Src = getValue(I.getOperand(0));
4334 SDValue Offset = getValue(I.getOperand(1));
4335 EVT SrcVT = Src.getValueType();
4336 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4337 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4338 SDLoc dl = getCurSDLoc();
4339
4340 assert(ResultVT.getSizeInBits() <= SrcVT.getSizeInBits() &&
4341 "bitextract result wider than source should be rejected by verifier");
4342
4343 // Legalize shift amount to the target's shift amount type.
4344 EVT ShiftAmtTy = TLI.getShiftAmountTy(SrcVT, DAG.getDataLayout());
4345 SDValue LegalShiftAmount = DAG.getZExtOrTrunc(Offset, dl, ShiftAmtTy);
4346
4347 // Shift right by Offset - brings target field to bit 0
4348 SDValue Shifted = DAG.getNode(ISD::SRL, dl, SrcVT, Src, LegalShiftAmount);
4349
4351 if (!ResultVT.isInteger()) {
4352 // Drop into the integer domain to safely truncate the shifted bits
4353 EVT IntResultVT = ResultVT.changeTypeToInteger();
4354 Result = DAG.getNode(ISD::TRUNCATE, dl, IntResultVT, Shifted);
4355 Result = DAG.getBitcast(ResultVT, Result);
4356 } else {
4357 // Normal integer path
4358 Result = DAG.getNode(ISD::TRUNCATE, dl, ResultVT, Shifted);
4359 }
4360
4361 setValue(&I, Result);
4362}
4363
4364void SelectionDAGBuilder::visitExtractElement(const User &I) {
4365 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4366 SDValue InVec = getValue(I.getOperand(0));
4367 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
4368 TLI.getVectorIdxTy(DAG.getDataLayout()));
4370 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4371 InVec, InIdx));
4372}
4373
4374void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4375 SDValue Src1 = getValue(I.getOperand(0));
4376 SDValue Src2 = getValue(I.getOperand(1));
4377 ArrayRef<int> Mask;
4378 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4379 Mask = SVI->getShuffleMask();
4380 else
4381 Mask = cast<ConstantExpr>(I).getShuffleMask();
4382 SDLoc DL = getCurSDLoc();
4383 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4384 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4385 EVT SrcVT = Src1.getValueType();
4386
4387 if (all_of(Mask, equal_to(0)) && VT.isScalableVector()) {
4388 // Canonical splat form of first element of first input vector.
4389 SDValue FirstElt =
4390 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4391 DAG.getVectorIdxConstant(0, DL));
4392 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4393 return;
4394 }
4395
4396 // For now, we only handle splats for scalable vectors.
4397 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4398 // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4399 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4400
4401 unsigned SrcNumElts = SrcVT.getVectorNumElements();
4402 unsigned MaskNumElts = Mask.size();
4403
4404 if (SrcNumElts == MaskNumElts) {
4405 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4406 return;
4407 }
4408
4409 // Normalize the shuffle vector since mask and vector length don't match.
4410 if (SrcNumElts < MaskNumElts) {
4411 // Mask is longer than the source vectors. We can use concatenate vector to
4412 // make the mask and vectors lengths match.
4413
4414 if (MaskNumElts % SrcNumElts == 0) {
4415 // Mask length is a multiple of the source vector length.
4416 // Check if the shuffle is some kind of concatenation of the input
4417 // vectors.
4418 unsigned NumConcat = MaskNumElts / SrcNumElts;
4419 bool IsConcat = true;
4420 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4421 for (unsigned i = 0; i != MaskNumElts; ++i) {
4422 int Idx = Mask[i];
4423 if (Idx < 0)
4424 continue;
4425 // Ensure the indices in each SrcVT sized piece are sequential and that
4426 // the same source is used for the whole piece.
4427 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4428 (ConcatSrcs[i / SrcNumElts] >= 0 &&
4429 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4430 IsConcat = false;
4431 break;
4432 }
4433 // Remember which source this index came from.
4434 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4435 }
4436
4437 // The shuffle is concatenating multiple vectors together. Just emit
4438 // a CONCAT_VECTORS operation.
4439 if (IsConcat) {
4440 SmallVector<SDValue, 8> ConcatOps;
4441 for (auto Src : ConcatSrcs) {
4442 if (Src < 0)
4443 ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4444 else if (Src == 0)
4445 ConcatOps.push_back(Src1);
4446 else
4447 ConcatOps.push_back(Src2);
4448 }
4449 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4450 return;
4451 }
4452 }
4453
4454 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4455 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4456 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4457 PaddedMaskNumElts);
4458
4459 // Pad both vectors with undefs to make them the same length as the mask.
4460 SDValue UndefVal = DAG.getUNDEF(SrcVT);
4461
4462 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4463 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4464 MOps1[0] = Src1;
4465 MOps2[0] = Src2;
4466
4467 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4468 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4469
4470 // Readjust mask for new input vector length.
4471 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4472 for (unsigned i = 0; i != MaskNumElts; ++i) {
4473 int Idx = Mask[i];
4474 if (Idx >= (int)SrcNumElts)
4475 Idx -= SrcNumElts - PaddedMaskNumElts;
4476 MappedOps[i] = Idx;
4477 }
4478
4479 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4480
4481 // If the concatenated vector was padded, extract a subvector with the
4482 // correct number of elements.
4483 if (MaskNumElts != PaddedMaskNumElts)
4484 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4485 DAG.getVectorIdxConstant(0, DL));
4486
4487 setValue(&I, Result);
4488 return;
4489 }
4490
4491 assert(SrcNumElts > MaskNumElts);
4492
4493 // Analyze the access pattern of the vector to see if we can extract
4494 // two subvectors and do the shuffle.
4495 int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4496 bool CanExtract = true;
4497 for (int Idx : Mask) {
4498 unsigned Input = 0;
4499 if (Idx < 0)
4500 continue;
4501
4502 if (Idx >= (int)SrcNumElts) {
4503 Input = 1;
4504 Idx -= SrcNumElts;
4505 }
4506
4507 // If all the indices come from the same MaskNumElts sized portion of
4508 // the sources we can use extract. Also make sure the extract wouldn't
4509 // extract past the end of the source.
4510 int NewStartIdx = alignDown(Idx, MaskNumElts);
4511 if (NewStartIdx + MaskNumElts > SrcNumElts ||
4512 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4513 CanExtract = false;
4514 // Make sure we always update StartIdx as we use it to track if all
4515 // elements are undef.
4516 StartIdx[Input] = NewStartIdx;
4517 }
4518
4519 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4520 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4521 return;
4522 }
4523 if (CanExtract) {
4524 // Extract appropriate subvector and generate a vector shuffle
4525 for (unsigned Input = 0; Input < 2; ++Input) {
4526 SDValue &Src = Input == 0 ? Src1 : Src2;
4527 if (StartIdx[Input] < 0)
4528 Src = DAG.getUNDEF(VT);
4529 else {
4530 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4531 DAG.getVectorIdxConstant(StartIdx[Input], DL));
4532 }
4533 }
4534
4535 // Calculate new mask.
4536 SmallVector<int, 8> MappedOps(Mask);
4537 for (int &Idx : MappedOps) {
4538 if (Idx >= (int)SrcNumElts)
4539 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4540 else if (Idx >= 0)
4541 Idx -= StartIdx[0];
4542 }
4543
4544 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4545 return;
4546 }
4547
4548 // We can't use either concat vectors or extract subvectors so fall back to
4549 // replacing the shuffle with extract and build vector.
4550 // to insert and build vector.
4551 EVT EltVT = VT.getVectorElementType();
4553 for (int Idx : Mask) {
4554 SDValue Res;
4555
4556 if (Idx < 0) {
4557 Res = DAG.getUNDEF(EltVT);
4558 } else {
4559 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4560 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4561
4562 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4563 DAG.getVectorIdxConstant(Idx, DL));
4564 }
4565
4566 Ops.push_back(Res);
4567 }
4568
4569 setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4570}
4571
4572void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4573 ArrayRef<unsigned> Indices = I.getIndices();
4574 const Value *Op0 = I.getOperand(0);
4575 const Value *Op1 = I.getOperand(1);
4576 Type *AggTy = I.getType();
4577 Type *ValTy = Op1->getType();
4578 bool IntoUndef = isa<UndefValue>(Op0);
4579 bool FromUndef = isa<UndefValue>(Op1);
4580
4581 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4582
4583 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4584 SmallVector<EVT, 4> AggValueVTs;
4585 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4586 SmallVector<EVT, 4> ValValueVTs;
4587 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4588
4589 unsigned NumAggValues = AggValueVTs.size();
4590 unsigned NumValValues = ValValueVTs.size();
4591 SmallVector<SDValue, 4> Values(NumAggValues);
4592
4593 // Ignore an insertvalue that produces an empty object
4594 if (!NumAggValues) {
4595 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4596 return;
4597 }
4598
4599 SDValue Agg = getValue(Op0);
4600 unsigned i = 0;
4601 // Copy the beginning value(s) from the original aggregate.
4602 for (; i != LinearIndex; ++i)
4603 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4604 SDValue(Agg.getNode(), Agg.getResNo() + i);
4605 // Copy values from the inserted value(s).
4606 if (NumValValues) {
4607 SDValue Val = getValue(Op1);
4608 for (; i != LinearIndex + NumValValues; ++i)
4609 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4610 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4611 }
4612 // Copy remaining value(s) from the original aggregate.
4613 for (; i != NumAggValues; ++i)
4614 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4615 SDValue(Agg.getNode(), Agg.getResNo() + i);
4616
4618 DAG.getVTList(AggValueVTs), Values));
4619}
4620
4621void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4622 ArrayRef<unsigned> Indices = I.getIndices();
4623 const Value *Op0 = I.getOperand(0);
4624 Type *AggTy = Op0->getType();
4625 Type *ValTy = I.getType();
4626 bool OutOfUndef = isa<UndefValue>(Op0);
4627
4628 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4629
4630 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4631 SmallVector<EVT, 4> ValValueVTs;
4632 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4633
4634 unsigned NumValValues = ValValueVTs.size();
4635
4636 // Ignore a extractvalue that produces an empty object
4637 if (!NumValValues) {
4638 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4639 return;
4640 }
4641
4642 SmallVector<SDValue, 4> Values(NumValValues);
4643
4644 SDValue Agg = getValue(Op0);
4645 // Copy out the selected value(s).
4646 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4647 Values[i - LinearIndex] =
4648 OutOfUndef ?
4649 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4650 SDValue(Agg.getNode(), Agg.getResNo() + i);
4651
4653 DAG.getVTList(ValValueVTs), Values));
4654}
4655
4656void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4657 Value *Op0 = I.getOperand(0);
4658 // Note that the pointer operand may be a vector of pointers. Take the scalar
4659 // element which holds a pointer.
4660 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4661 SDValue N = getValue(Op0);
4662 SDLoc dl = getCurSDLoc();
4663 auto &TLI = DAG.getTargetLoweringInfo();
4664 GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4665
4666 // For a vector GEP, keep the prefix scalar as long as possible, then
4667 // convert any scalars encountered after the first vector operand to vectors.
4668 bool IsVectorGEP = I.getType()->isVectorTy();
4669 ElementCount VectorElementCount =
4670 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4672
4674 GTI != E; ++GTI) {
4675 const Value *Idx = GTI.getOperand();
4676 if (StructType *StTy = GTI.getStructTypeOrNull()) {
4677 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4678 if (Field) {
4679 // N = N + Offset
4681 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4682
4683 // In an inbounds GEP with an offset that is nonnegative even when
4684 // interpreted as signed, assume there is no unsigned overflow.
4685 SDNodeFlags Flags;
4686 if (NW.hasNoUnsignedWrap() ||
4687 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4689 Flags.setInBounds(NW.isInBounds());
4690
4691 N = DAG.getMemBasePlusOffset(
4692 N, DAG.getConstant(Offset, dl, N.getValueType()), dl, Flags);
4693 }
4694 } else {
4695 // IdxSize is the width of the arithmetic according to IR semantics.
4696 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4697 // (and fix up the result later).
4698 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4699 MVT IdxTy = MVT::getIntegerVT(IdxSize);
4700 TypeSize ElementSize =
4701 GTI.getSequentialElementStride(DAG.getDataLayout());
4702 // We intentionally mask away the high bits here; ElementSize may not
4703 // fit in IdxTy.
4704 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4705 /*isSigned=*/false, /*implicitTrunc=*/true);
4706 bool ElementScalable = ElementSize.isScalable();
4707
4708 // If this is a scalar constant or a splat vector of constants,
4709 // handle it quickly.
4710 const auto *C = dyn_cast<Constant>(Idx);
4711 if (C && isa<VectorType>(C->getType()))
4712 C = C->getSplatValue();
4713
4714 const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4715 if (CI && CI->isZero())
4716 continue;
4717 if (CI && !ElementScalable) {
4718 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4719 LLVMContext &Context = *DAG.getContext();
4720 SDValue OffsVal;
4721 if (N.getValueType().isVector())
4722 OffsVal = DAG.getConstant(
4723 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4724 else
4725 OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4726
4727 // In an inbounds GEP with an offset that is nonnegative even when
4728 // interpreted as signed, assume there is no unsigned overflow.
4729 SDNodeFlags Flags;
4730 if (NW.hasNoUnsignedWrap() ||
4731 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4732 Flags.setNoUnsignedWrap(true);
4733 Flags.setInBounds(NW.isInBounds());
4734
4735 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4736
4737 N = DAG.getMemBasePlusOffset(N, OffsVal, dl, Flags);
4738 continue;
4739 }
4740
4741 // N = N + Idx * ElementMul;
4742 SDValue IdxN = getValue(Idx);
4743
4744 if (IdxN.getValueType().isVector() != N.getValueType().isVector()) {
4745 if (N.getValueType().isVector()) {
4746 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4747 VectorElementCount);
4748 IdxN = DAG.getSplat(VT, dl, IdxN);
4749 } else {
4750 EVT VT =
4751 EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4752 N = DAG.getSplat(VT, dl, N);
4753 }
4754 }
4755
4756 // If the index is smaller or larger than intptr_t, truncate or extend
4757 // it.
4758 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4759
4760 SDNodeFlags ScaleFlags;
4761 // The multiplication of an index by the type size does not wrap the
4762 // pointer index type in a signed sense (mul nsw).
4764
4765 // The multiplication of an index by the type size does not wrap the
4766 // pointer index type in an unsigned sense (mul nuw).
4767 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4768
4769 if (ElementScalable) {
4770 EVT VScaleTy = N.getValueType().getScalarType();
4771 SDValue VScale = DAG.getNode(
4772 ISD::VSCALE, dl, VScaleTy,
4773 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4774 if (N.getValueType().isVector())
4775 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4776 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale,
4777 ScaleFlags);
4778 } else {
4779 // If this is a multiply by a power of two, turn it into a shl
4780 // immediately. This is a very common case.
4781 if (ElementMul != 1) {
4782 if (ElementMul.isPowerOf2()) {
4783 unsigned Amt = ElementMul.logBase2();
4784 IdxN = DAG.getNode(
4785 ISD::SHL, dl, N.getValueType(), IdxN,
4786 DAG.getShiftAmountConstant(Amt, N.getValueType(), dl),
4787 ScaleFlags);
4788 } else {
4789 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4790 IdxN.getValueType());
4791 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, Scale,
4792 ScaleFlags);
4793 }
4794 }
4795 }
4796
4797 // The successive addition of the current address, truncated to the
4798 // pointer index type and interpreted as an unsigned number, and each
4799 // offset, also interpreted as an unsigned number, does not wrap the
4800 // pointer index type (add nuw).
4801 SDNodeFlags AddFlags;
4802 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4803 AddFlags.setInBounds(NW.isInBounds());
4804
4805 N = DAG.getMemBasePlusOffset(N, IdxN, dl, AddFlags);
4806 }
4807 }
4808
4809 if (IsVectorGEP && !N.getValueType().isVector()) {
4810 EVT VT = EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4811 N = DAG.getSplat(VT, dl, N);
4812 }
4813
4814 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4815 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4816 if (IsVectorGEP) {
4817 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4818 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4819 }
4820
4821 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4822 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4823
4824 setValue(&I, N);
4825}
4826
4827void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4828 // If this is a fixed sized alloca in the entry block of the function,
4829 // allocate it statically on the stack.
4830 if (FuncInfo.StaticAllocaMap.count(&I))
4831 return; // getValue will auto-populate this.
4832
4833 SDLoc dl = getCurSDLoc();
4834 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4835 auto &DL = DAG.getDataLayout();
4836 TypeSize TySize = I.getAllocationBaseSize(DL);
4837 MaybeAlign Alignment = I.getAlign();
4838
4839 SDValue AllocSize = getValue(I.getArraySize());
4840
4841 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4842 if (AllocSize.getValueType() != IntPtr)
4843 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4844
4845 AllocSize = DAG.getNode(
4846 ISD::MUL, dl, IntPtr, AllocSize,
4847 DAG.getZExtOrTrunc(DAG.getTypeSize(dl, MVT::i64, TySize), dl, IntPtr));
4848
4849 // Handle alignment. If the requested alignment is less than or equal to
4850 // the stack alignment, ignore it. If the size is greater than or equal to
4851 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4852 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4853 if (*Alignment <= StackAlign)
4854 Alignment = std::nullopt;
4855
4856 const uint64_t StackAlignMask = StackAlign.value() - 1U;
4857 // Round the size of the allocation up to the stack alignment size
4858 // by add SA-1 to the size. This doesn't overflow because we're computing
4859 // an address inside an alloca.
4860 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4861 DAG.getConstant(StackAlignMask, dl, IntPtr),
4863
4864 // Mask out the low bits for alignment purposes.
4865 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4866 DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4867
4868 SDValue Ops[] = {
4869 getRoot(), AllocSize,
4870 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4871 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4872 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4873 setValue(&I, DSA);
4874 DAG.setRoot(DSA.getValue(1));
4875
4876 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4877}
4878
4879static const MDNode *getRangeMetadata(const Instruction &I) {
4880 return I.getMetadata(LLVMContext::MD_range);
4881}
4882
4883static std::optional<ConstantRange> getRange(const Instruction &I) {
4884 if (const auto *CB = dyn_cast<CallBase>(&I))
4885 if (std::optional<ConstantRange> CR = CB->getRange())
4886 return CR;
4887 if (const MDNode *Range = getRangeMetadata(I))
4889 return std::nullopt;
4890}
4891
4893 if (const auto *CB = dyn_cast<CallBase>(&I))
4894 return CB->getRetNoFPClass();
4895 return fcNone;
4896}
4897
4898void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4899 if (I.isAtomic())
4900 return visitAtomicLoad(I);
4901
4902 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4903 const Value *SV = I.getOperand(0);
4904 if (TLI.supportSwiftError()) {
4905 // Swifterror values can come from either a function parameter with
4906 // swifterror attribute or an alloca with swifterror attribute.
4907 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4908 if (Arg->hasSwiftErrorAttr())
4909 return visitLoadFromSwiftError(I);
4910 }
4911
4912 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4913 if (Alloca->isSwiftError())
4914 return visitLoadFromSwiftError(I);
4915 }
4916 }
4917
4918 SDValue Ptr = getValue(SV);
4919
4920 Type *Ty = I.getType();
4921 SmallVector<EVT, 4> ValueVTs, MemVTs;
4923 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4924 unsigned NumValues = ValueVTs.size();
4925 if (NumValues == 0)
4926 return;
4927
4928 Align Alignment = I.getAlign();
4929 AAMDNodes AAInfo = I.getAAMetadata();
4930 const MDNode *Ranges = getRangeMetadata(I);
4931 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
4932 bool isVolatile = I.isVolatile();
4933 MachineMemOperand::Flags MMOFlags =
4934 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4935
4936 SDValue Root;
4937 bool ConstantMemory = false;
4938 if (isVolatile)
4939 // Serialize volatile loads with other side effects.
4940 Root = getRoot();
4941 else if (NumValues > MaxParallelChains)
4942 Root = getMemoryRoot();
4943 else if (BatchAA &&
4944 BatchAA->pointsToConstantMemory(MemoryLocation(
4945 SV,
4946 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4947 AAInfo))) {
4948 // Do not serialize (non-volatile) loads of constant memory with anything.
4949 Root = DAG.getEntryNode();
4950 ConstantMemory = true;
4952 } else {
4953 // Do not serialize non-volatile loads against each other.
4954 Root = DAG.getRoot();
4955 }
4956
4957 SDLoc dl = getCurSDLoc();
4958
4959 if (isVolatile)
4960 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4961
4963 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4964
4965 unsigned ChainI = 0;
4966 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4967 // Serializing loads here may result in excessive register pressure, and
4968 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4969 // could recover a bit by hoisting nodes upward in the chain by recognizing
4970 // they are side-effect free or do not alias. The optimizer should really
4971 // avoid this case by converting large object/array copies to llvm.memcpy
4972 // (MaxParallelChains should always remain as failsafe).
4973 if (ChainI == MaxParallelChains) {
4974 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4975 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4976 ArrayRef(Chains.data(), ChainI));
4977 Root = Chain;
4978 ChainI = 0;
4979 }
4980
4981 // TODO: MachinePointerInfo only supports a fixed length offset.
4982 MachinePointerInfo PtrInfo =
4983 !Offsets[i].isScalable() || Offsets[i].isZero()
4984 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4985 : MachinePointerInfo();
4986
4987 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4988 SDValue L =
4989 DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, MMOFlags,
4990 MMOMetadata(AAInfo, Ranges, MemCacheHint));
4991 Chains[ChainI] = L.getValue(1);
4992
4993 if (MemVTs[i] != ValueVTs[i])
4994 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4995
4996 if (MDNode *NoFPClassMD = I.getMetadata(LLVMContext::MD_nofpclass)) {
4997 uint64_t FPTestInt =
4998 cast<ConstantInt>(
4999 cast<ConstantAsMetadata>(NoFPClassMD->getOperand(0))->getValue())
5000 ->getZExtValue();
5001 if (FPTestInt != fcNone) {
5002 SDValue FPTestConst =
5003 DAG.getTargetConstant(FPTestInt, SDLoc(), MVT::i32);
5004 L = DAG.getNode(ISD::AssertNoFPClass, dl, L.getValueType(), L,
5005 FPTestConst);
5006 }
5007 }
5008 Values[i] = L;
5009 }
5010
5011 if (!ConstantMemory) {
5012 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5013 ArrayRef(Chains.data(), ChainI));
5014 if (isVolatile)
5015 DAG.setRoot(Chain);
5016 else
5017 PendingLoads.push_back(Chain);
5018 }
5019
5020 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
5021 DAG.getVTList(ValueVTs), Values));
5022}
5023
5024void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
5025 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
5026 "call visitStoreToSwiftError when backend supports swifterror");
5027
5028 SmallVector<EVT, 4> ValueVTs;
5029 SmallVector<uint64_t, 4> Offsets;
5030 const Value *SrcV = I.getOperand(0);
5031 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
5032 SrcV->getType(), ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
5033 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
5034 "expect a single EVT for swifterror");
5035
5036 SDValue Src = getValue(SrcV);
5037 // Create a virtual register, then update the virtual register.
5038 Register VReg =
5039 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
5040 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
5041 // Chain can be getRoot or getControlRoot.
5042 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
5043 SDValue(Src.getNode(), Src.getResNo()));
5044 DAG.setRoot(CopyNode);
5045}
5046
5047void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
5048 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
5049 "call visitLoadFromSwiftError when backend supports swifterror");
5050
5051 assert(!I.isVolatile() &&
5052 !I.hasMetadata(LLVMContext::MD_nontemporal) &&
5053 !I.hasMetadata(LLVMContext::MD_invariant_load) &&
5054 "Support volatile, non temporal, invariant for load_from_swift_error");
5055
5056 const Value *SV = I.getOperand(0);
5057 Type *Ty = I.getType();
5058 assert(
5059 (!BatchAA ||
5060 !BatchAA->pointsToConstantMemory(MemoryLocation(
5061 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
5062 I.getAAMetadata()))) &&
5063 "load_from_swift_error should not be constant memory");
5064
5065 SmallVector<EVT, 4> ValueVTs;
5066 SmallVector<uint64_t, 4> Offsets;
5067 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
5068 ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
5069 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
5070 "expect a single EVT for swifterror");
5071
5072 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
5073 SDValue L = DAG.getCopyFromReg(
5074 getRoot(), getCurSDLoc(),
5075 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
5076
5077 setValue(&I, L);
5078}
5079
5080void SelectionDAGBuilder::visitStore(const StoreInst &I) {
5081 if (I.isAtomic())
5082 return visitAtomicStore(I);
5083
5084 const Value *SrcV = I.getOperand(0);
5085 const Value *PtrV = I.getOperand(1);
5086
5087 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5088 if (TLI.supportSwiftError()) {
5089 // Swifterror values can come from either a function parameter with
5090 // swifterror attribute or an alloca with swifterror attribute.
5091 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
5092 if (Arg->hasSwiftErrorAttr())
5093 return visitStoreToSwiftError(I);
5094 }
5095
5096 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
5097 if (Alloca->isSwiftError())
5098 return visitStoreToSwiftError(I);
5099 }
5100 }
5101
5102 SmallVector<EVT, 4> ValueVTs, MemVTs;
5104 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
5105 SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
5106 unsigned NumValues = ValueVTs.size();
5107 if (NumValues == 0)
5108 return;
5109
5110 // Get the lowered operands. Note that we do this after
5111 // checking if NumResults is zero, because with zero results
5112 // the operands won't have values in the map.
5113 SDValue Src = getValue(SrcV);
5114 SDValue Ptr = getValue(PtrV);
5115
5116 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
5117 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
5118 SDLoc dl = getCurSDLoc();
5119 Align Alignment = I.getAlign();
5120 AAMDNodes AAInfo = I.getAAMetadata();
5121 const MDNode *MemCacheHint =
5122 getMemCacheHintMetadata(I, I.getPointerOperandIndex());
5123
5124 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5125
5126 unsigned ChainI = 0;
5127 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
5128 // See visitLoad comments.
5129 if (ChainI == MaxParallelChains) {
5130 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5131 ArrayRef(Chains.data(), ChainI));
5132 Root = Chain;
5133 ChainI = 0;
5134 }
5135
5136 // TODO: MachinePointerInfo only supports a fixed length offset.
5137 MachinePointerInfo PtrInfo =
5138 !Offsets[i].isScalable() || Offsets[i].isZero()
5139 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
5140 : MachinePointerInfo();
5141
5142 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
5143 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
5144 if (MemVTs[i] != ValueVTs[i])
5145 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
5146 SDValue St =
5147 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags,
5148 MMOMetadata(AAInfo, /*Ranges=*/nullptr, MemCacheHint));
5149 Chains[ChainI] = St;
5150 }
5151
5152 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5153 ArrayRef(Chains.data(), ChainI));
5154 setValue(&I, StoreNode);
5155 DAG.setRoot(StoreNode);
5156}
5157
5158void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
5159 bool IsCompressing) {
5160 SDLoc sdl = getCurSDLoc();
5161
5162 Value *Src0Operand = I.getArgOperand(0);
5163 Value *PtrOperand = I.getArgOperand(1);
5164 Value *MaskOperand = I.getArgOperand(2);
5165 Align Alignment = I.getParamAlign(1).valueOrOne();
5166
5167 SDValue Ptr = getValue(PtrOperand);
5168 SDValue Src0 = getValue(Src0Operand);
5169 SDValue Mask = getValue(MaskOperand);
5170 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5171
5172 EVT VT = Src0.getValueType();
5173
5174 const auto &TLI = DAG.getTargetLoweringInfo();
5175
5176 auto MMOFlags = MachineMemOperand::MOStore;
5177 MMOFlags |= TLI.getTargetMMOFlags(I);
5178 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5180
5181 const MDNode *MemCacheHint = getMemCacheHintMetadata(I, /*OperandNo=*/1);
5182
5183 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5184 MachinePointerInfo(PtrOperand), MMOFlags,
5185 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5186 MMOMetadata(I.getAAMetadata(), /*Ranges=*/nullptr, MemCacheHint));
5187
5188 SDValue StoreNode =
5189 !IsCompressing && TTI->hasConditionalLoadStoreForType(
5190 I.getArgOperand(0)->getType(), /*IsStore=*/true)
5191 ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
5192 Mask)
5193 : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
5194 VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
5195 IsCompressing);
5196 DAG.setRoot(StoreNode);
5197 setValue(&I, StoreNode);
5198}
5199
5200// Get a uniform base for the Gather/Scatter intrinsic.
5201// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
5202// We try to represent it as a base pointer + vector of indices.
5203// Usually, the vector of pointers comes from a 'getelementptr' instruction.
5204// The first operand of the GEP may be a single pointer or a vector of pointers
5205// Example:
5206// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
5207// or
5208// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
5209// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
5210//
5211// When the first GEP operand is a single pointer - it is the uniform base we
5212// are looking for. If first operand of the GEP is a splat vector - we
5213// extract the splat value and use it as a uniform base.
5214// In all other cases the function returns 'false'.
5215static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
5216 SDValue &Scale, SelectionDAGBuilder *SDB,
5217 const BasicBlock *CurBB, uint64_t ElemSize) {
5218 SelectionDAG& DAG = SDB->DAG;
5220 const DataLayout &DL = DAG.getDataLayout();
5221
5222 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
5223
5224 // Handle splat constant pointer.
5225 if (auto *C = dyn_cast<Constant>(Ptr)) {
5226 C = C->getSplatValue();
5227 if (!C)
5228 return false;
5229
5230 Base = SDB->getValue(C);
5231
5232 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
5233 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
5234 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
5235 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5236 return true;
5237 }
5238
5240 if (!GEP || GEP->getParent() != CurBB)
5241 return false;
5242
5243 if (GEP->getNumOperands() != 2)
5244 return false;
5245
5246 const Value *BasePtr = GEP->getPointerOperand();
5247 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
5248
5249 // Make sure the base is scalar and the index is a vector.
5250 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
5251 return false;
5252
5253 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
5254 if (ScaleVal.isScalable())
5255 return false;
5256
5257 // Target may not support the required addressing mode.
5258 if (ScaleVal != 1 &&
5259 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
5260 return false;
5261
5262 Base = SDB->getValue(BasePtr);
5263 Index = SDB->getValue(IndexVal);
5264
5265 Scale =
5266 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5267 return true;
5268}
5269
5270void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
5271 SDLoc sdl = getCurSDLoc();
5272
5273 // llvm.masked.scatter.*(Src0, Ptrs, Mask)
5274 const Value *Ptr = I.getArgOperand(1);
5275 SDValue Src0 = getValue(I.getArgOperand(0));
5276 SDValue Mask = getValue(I.getArgOperand(2));
5277 EVT VT = Src0.getValueType();
5278 Align Alignment = I.getParamAlign(1).valueOrOne();
5279 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5280
5281 SDValue Base;
5282 SDValue Index;
5283 SDValue Scale;
5284 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5285 I.getParent(), VT.getScalarStoreSize());
5286
5287 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5288 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5289 MachinePointerInfo(AS), MachineMemOperand::MOStore,
5290 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
5291 if (!UniformBase) {
5292 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5293 Index = getValue(Ptr);
5294 Scale =
5295 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5296 }
5297
5298 EVT IdxVT = Index.getValueType();
5299 EVT EltTy = IdxVT.getVectorElementType();
5300 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5301 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5302 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5303 }
5304
5305 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
5306 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
5307 Ops, MMO, ISD::SIGNED_SCALED, false);
5308 DAG.setRoot(Scatter);
5309 setValue(&I, Scatter);
5310}
5311
5312void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
5313 SDLoc sdl = getCurSDLoc();
5314
5315 Value *PtrOperand = I.getArgOperand(0);
5316 Value *MaskOperand = I.getArgOperand(1);
5317 Value *Src0Operand = I.getArgOperand(2);
5318 Align Alignment = I.getParamAlign(0).valueOrOne();
5319
5320 SDValue Ptr = getValue(PtrOperand);
5321 SDValue Src0 = getValue(Src0Operand);
5322 SDValue Mask = getValue(MaskOperand);
5323 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5324
5325 EVT VT = Src0.getValueType();
5326 AAMDNodes AAInfo = I.getAAMetadata();
5327 const MDNode *Ranges = getRangeMetadata(I);
5328 const MDNode *MemCacheHint = getMemCacheHintMetadata(I, /*OperandNo=*/0);
5329
5330 // Do not serialize masked loads of constant memory with anything.
5331 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
5332 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
5333
5334 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
5335
5336 const auto &TLI = DAG.getTargetLoweringInfo();
5337
5338 auto MMOFlags = MachineMemOperand::MOLoad;
5339 MMOFlags |= TLI.getTargetMMOFlags(I);
5340 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5342 if (I.hasMetadata(LLVMContext::MD_invariant_load))
5344
5345 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5346 MachinePointerInfo(PtrOperand), MMOFlags,
5347 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5348 MMOMetadata(AAInfo, Ranges, MemCacheHint));
5349
5350 // The Load/Res may point to different values and both of them are output
5351 // variables.
5352 SDValue Load;
5353 SDValue Res;
5354 if (!IsExpanding &&
5355 TTI->hasConditionalLoadStoreForType(Src0Operand->getType(),
5356 /*IsStore=*/false))
5357 Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
5358 else
5359 Res = Load =
5360 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
5361 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5362 if (AddToChain)
5363 PendingLoads.push_back(Load.getValue(1));
5364 setValue(&I, Res);
5365}
5366
5367void SelectionDAGBuilder::visitSpeculativeLoad(const CallInst &I) {
5368 SDLoc sdl = getCurSDLoc();
5369 Value *PtrOperand = I.getArgOperand(0);
5370 // The remaining arguments (num_accessible_bytes or oracle function + args)
5371 // are IR-level semantics only; they are not needed at codegen.
5372 SDValue Ptr = getValue(PtrOperand);
5373
5374 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5375 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5376 Align Alignment = I.getParamAlign(0).valueOrOne();
5377 AAMDNodes AAInfo = I.getAAMetadata();
5378
5379 SDValue InChain = DAG.getRoot();
5380
5381 // Use MOLoad but NOT MODereferenceable - the memory may not be
5382 // fully dereferenceable.
5383 auto MMOFlags = MachineMemOperand::MOLoad;
5384 MMOFlags |= TLI.getTargetMMOFlags(I);
5385 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5387 if (I.hasMetadata(LLVMContext::MD_invariant_load))
5389
5390 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5391 MachinePointerInfo(PtrOperand), MMOFlags,
5392 LocationSize::precise(VT.getStoreSize()), Alignment, AAInfo);
5393
5394 SDValue Load = DAG.getLoad(VT, sdl, InChain, Ptr, MMO);
5395 PendingLoads.push_back(Load.getValue(1));
5396 setValue(&I, Load);
5397}
5398
5399void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5400 SDLoc sdl = getCurSDLoc();
5401
5402 // @llvm.masked.gather.*(Ptrs, Mask, Src0)
5403 const Value *Ptr = I.getArgOperand(0);
5404 SDValue Src0 = getValue(I.getArgOperand(2));
5405 SDValue Mask = getValue(I.getArgOperand(1));
5406
5407 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5408 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5409 Align Alignment = I.getParamAlign(0).valueOrOne();
5410
5411 const MDNode *Ranges = getRangeMetadata(I);
5412
5413 SDValue Root = DAG.getRoot();
5414 SDValue Base;
5415 SDValue Index;
5416 SDValue Scale;
5417 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5418 I.getParent(), VT.getScalarStoreSize());
5419 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5420 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5421 MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5423 MMOMetadata(I.getAAMetadata(), Ranges));
5424
5425 if (!UniformBase) {
5426 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5427 Index = getValue(Ptr);
5428 Scale =
5429 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5430 }
5431
5432 EVT IdxVT = Index.getValueType();
5433 EVT EltTy = IdxVT.getVectorElementType();
5434 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5435 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5436 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5437 }
5438
5439 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5440 SDValue Gather =
5441 DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, Ops, MMO,
5443
5444 PendingLoads.push_back(Gather.getValue(1));
5445 setValue(&I, Gather);
5446}
5447
5448void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5449 SDLoc dl = getCurSDLoc();
5450 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5451 AtomicOrdering FailureOrdering = I.getFailureOrdering();
5452 SyncScope::ID SSID = I.getSyncScopeID();
5453
5454 SDValue InChain = getRoot();
5455
5456 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5457 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5458
5459 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5460 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5461
5462 MachineFunction &MF = DAG.getMachineFunction();
5463 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5464 MachineMemOperand *MMO = MF.getMachineMemOperand(
5465 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5466 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5467 SSID, SuccessOrdering, FailureOrdering);
5468
5470 dl, MemVT, VTs, InChain,
5471 getValue(I.getPointerOperand()),
5472 getValue(I.getCompareOperand()),
5473 getValue(I.getNewValOperand()), MMO);
5474
5475 SDValue OutChain = L.getValue(2);
5476
5477 setValue(&I, L);
5478 DAG.setRoot(OutChain);
5479}
5480
5481void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5482 SDLoc dl = getCurSDLoc();
5484 switch (I.getOperation()) {
5485 default: llvm_unreachable("Unknown atomicrmw operation");
5503 break;
5506 break;
5509 break;
5512 break;
5515 break;
5518 break;
5521 break;
5524 break;
5525 }
5526 AtomicOrdering Ordering = I.getOrdering();
5527 SyncScope::ID SSID = I.getSyncScopeID();
5528
5529 SDValue InChain = getRoot();
5530
5531 auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5532 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5533 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5534
5535 MachineFunction &MF = DAG.getMachineFunction();
5536 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5537 MachineMemOperand *MMO = MF.getMachineMemOperand(
5538 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5539 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5540 SSID, Ordering);
5541
5542 SDValue L =
5543 DAG.getAtomic(NT, dl, MemVT, InChain,
5544 getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5545 MMO);
5546
5547 SDValue OutChain = L.getValue(1);
5548
5549 setValue(&I, L);
5550 DAG.setRoot(OutChain);
5551}
5552
5553void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5554 SDLoc dl = getCurSDLoc();
5555 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5556 SDValue Ops[3];
5557 Ops[0] = getRoot();
5558 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5559 TLI.getFenceOperandTy(DAG.getDataLayout()));
5560 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5561 TLI.getFenceOperandTy(DAG.getDataLayout()));
5562 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5563 setValue(&I, N);
5564 DAG.setRoot(N);
5565}
5566
5567void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5568 SDLoc dl = getCurSDLoc();
5569 AtomicOrdering Order = I.getOrdering();
5570 SyncScope::ID SSID = I.getSyncScopeID();
5571
5572 SDValue InChain = getRoot();
5573
5574 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5575 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5576 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5577
5578 if (!TLI.isAtomicAlignmentSupported(I.getAlign(), MemVT.getSizeInBits() / 8))
5579 report_fatal_error("Cannot generate unaligned atomic load");
5580
5581 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5582
5583 const MDNode *Ranges = getRangeMetadata(I);
5584 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5585 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5586 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5587 I.getAlign(), MMOMetadata(AAMDNodes(), Ranges, MemCacheHint), SSID,
5588 Order);
5589
5590 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5591
5592 SDValue Ptr = getValue(I.getPointerOperand());
5593 SDValue L =
5594 DAG.getAtomicLoad(ISD::NON_EXTLOAD, dl, MemVT, MemVT, InChain, Ptr, MMO);
5595
5596 SDValue OutChain = L.getValue(1);
5597 if (MemVT != VT)
5598 L = DAG.getPtrExtOrTrunc(L, dl, VT);
5599
5600 setValue(&I, L);
5601 DAG.setRoot(OutChain);
5602}
5603
5604void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5605 SDLoc dl = getCurSDLoc();
5606
5607 AtomicOrdering Ordering = I.getOrdering();
5608 SyncScope::ID SSID = I.getSyncScopeID();
5609
5610 SDValue InChain = getRoot();
5611
5612 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5613 EVT MemVT =
5614 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5615
5616 if (!TLI.isAtomicAlignmentSupported(I.getAlign(), MemVT.getSizeInBits() / 8))
5617 report_fatal_error("Cannot generate unaligned atomic store");
5618
5619 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5620
5621 MachineFunction &MF = DAG.getMachineFunction();
5622 const MDNode *MemCacheHint =
5623 getMemCacheHintMetadata(I, I.getPointerOperandIndex());
5624 MachineMemOperand *MMO = MF.getMachineMemOperand(
5625 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5626 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5627 SSID, Ordering);
5628
5629 SDValue Val = getValue(I.getValueOperand());
5630 if (Val.getValueType() != MemVT)
5631 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5632 SDValue Ptr = getValue(I.getPointerOperand());
5633
5634 SDValue OutChain =
5635 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5636
5637 setValue(&I, OutChain);
5638 DAG.setRoot(OutChain);
5639}
5640
5641/// Check if this intrinsic call depends on the chain (1st return value)
5642/// and if it only *loads* memory.
5643/// Ignore the callsite's attributes. A specific call site may be marked with
5644/// readnone, but the lowering code will expect the chain based on the
5645/// definition.
5646std::pair<bool, bool>
5647SelectionDAGBuilder::getTargetIntrinsicCallProperties(const CallBase &I) {
5648 const Function *F = I.getCalledFunction();
5649 bool HasChain = !F->doesNotAccessMemory();
5650 bool OnlyLoad =
5651 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5652
5653 return {HasChain, OnlyLoad};
5654}
5655
5656SmallVector<SDValue, 8> SelectionDAGBuilder::getTargetIntrinsicOperands(
5657 const CallBase &I, bool HasChain, bool OnlyLoad,
5658 TargetLowering::IntrinsicInfo *TgtMemIntrinsicInfo) {
5659 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5660
5661 // Build the operand list.
5663 if (HasChain) { // If this intrinsic has side-effects, chainify it.
5664 if (OnlyLoad) {
5665 // We don't need to serialize loads against other loads.
5666 Ops.push_back(DAG.getRoot());
5667 } else {
5668 Ops.push_back(getRoot());
5669 }
5670 }
5671
5672 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5673 if (!TgtMemIntrinsicInfo || TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_VOID ||
5674 TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_W_CHAIN)
5675 Ops.push_back(DAG.getTargetConstant(I.getIntrinsicID(), getCurSDLoc(),
5676 TLI.getPointerTy(DAG.getDataLayout())));
5677
5678 // Add all operands of the call to the operand list.
5679 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5680 const Value *Arg = I.getArgOperand(i);
5681 if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5682 Ops.push_back(getValue(Arg));
5683 continue;
5684 }
5685
5686 // Use TargetConstant instead of a regular constant for immarg.
5687 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5688 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5689 assert(CI->getBitWidth() <= 64 &&
5690 "large intrinsic immediates not handled");
5691 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5692 } else {
5693 Ops.push_back(
5694 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5695 }
5696 }
5697
5698 if (std::optional<OperandBundleUse> Bundle =
5699 I.getOperandBundle(LLVMContext::OB_deactivation_symbol)) {
5700 auto *Sym = Bundle->Inputs[0].get();
5701 SDValue SDSym = getValue(Sym);
5702 SDSym = DAG.getDeactivationSymbol(cast<GlobalValue>(Sym));
5703 Ops.push_back(SDSym);
5704 }
5705
5706 if (std::optional<OperandBundleUse> Bundle =
5707 I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5708 Value *Token = Bundle->Inputs[0].get();
5709 SDValue ConvControlToken = getValue(Token);
5710 assert(Ops.back().getValueType() != MVT::Glue &&
5711 "Did not expect another glue node here.");
5712 ConvControlToken =
5713 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5714 Ops.push_back(ConvControlToken);
5715 }
5716
5717 return Ops;
5718}
5719
5720SDVTList SelectionDAGBuilder::getTargetIntrinsicVTList(const CallBase &I,
5721 bool HasChain) {
5722 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5723
5724 SmallVector<EVT, 4> ValueVTs;
5725 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5726
5727 if (HasChain)
5728 ValueVTs.push_back(MVT::Other);
5729
5730 return DAG.getVTList(ValueVTs);
5731}
5732
5733/// Get an INTRINSIC node for a target intrinsic which does not touch memory.
5734SDValue SelectionDAGBuilder::getTargetNonMemIntrinsicNode(
5735 const Type &IntrinsicVT, bool HasChain, ArrayRef<SDValue> Ops,
5736 const SDVTList &VTs) {
5737 if (!HasChain)
5738 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5739 if (!IntrinsicVT.isVoidTy())
5740 return DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5741 return DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5742}
5743
5744/// Set root, convert return type if necessary and check alignment.
5745SDValue SelectionDAGBuilder::handleTargetIntrinsicRet(const CallBase &I,
5746 bool HasChain,
5747 bool OnlyLoad,
5748 SDValue Result) {
5749 if (HasChain) {
5750 SDValue Chain = Result.getValue(Result.getNode()->getNumValues() - 1);
5751 if (OnlyLoad)
5752 PendingLoads.push_back(Chain);
5753 else
5754 DAG.setRoot(Chain);
5755 }
5756
5757 if (I.getType()->isVoidTy())
5758 return Result;
5759
5760 if (MaybeAlign Alignment = I.getRetAlign(); InsertAssertAlign && Alignment) {
5761 // Insert `assertalign` node if there's an alignment.
5762 Result = DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5763 } else if (!isa<VectorType>(I.getType())) {
5764 Result = lowerRangeToAssertZExt(DAG, I, Result);
5765 }
5766
5767 return Result;
5768}
5769
5770/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5771/// node.
5772void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5773 unsigned Intrinsic) {
5774 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
5775 Intrinsic::ID IntrinsicID = static_cast<Intrinsic::ID>(Intrinsic);
5776
5777 if (!DAG.getMachineFunction().getSubtarget().isIntrinsicSupported(
5778 Intrinsic)) {
5779 SDLoc DL = getCurSDLoc();
5780 DAG.getContext()->diagnose(DiagnosticInfoUnsupportedTargetIntrinsic(
5781 *I.getFunction(), IntrinsicID, DL.getDebugLoc()));
5782
5783 // The intrinsic is not available on this subtarget. Preserve the chain for
5784 // side-effecting intrinsics and lower any result to poison so that
5785 // compilation can continue and collect further diagnostics.
5786 if (HasChain && !OnlyLoad)
5787 DAG.setRoot(getRoot());
5788
5790 return;
5791 }
5792
5793 // Infos is set by getTgtMemIntrinsic.
5795 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5796 TLI.getTgtMemIntrinsic(Infos, I, DAG.getMachineFunction(), Intrinsic);
5797 // Use the first (primary) info determines the node opcode.
5798 TargetLowering::IntrinsicInfo *Info = !Infos.empty() ? &Infos[0] : nullptr;
5799
5801 getTargetIntrinsicOperands(I, HasChain, OnlyLoad, Info);
5802 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
5803
5804 // Propagate fast-math-flags from IR to node(s).
5805 SDNodeFlags Flags;
5806 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5807 Flags.copyFMF(*FPMO);
5808 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5809
5810 // Create the node.
5812
5813 // In some cases, custom collection of operands from CallInst I may be needed.
5815 if (!Infos.empty()) {
5816 // This is target intrinsic that touches memory
5817 // Create MachineMemOperands for each memory access described by the target.
5818 MachineFunction &MF = DAG.getMachineFunction();
5820 for (const auto &Info : Infos) {
5821 // TODO: We currently just fallback to address space 0 if
5822 // getTgtMemIntrinsic didn't yield anything useful.
5823 MachinePointerInfo MPI;
5824 if (Info.ptrVal)
5825 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5826 else if (Info.fallbackAddressSpace)
5827 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5828 EVT MemVT = Info.memVT;
5829 LocationSize Size = LocationSize::precise(Info.size);
5830 if (Size.hasValue() && !Size.getValue())
5832 Align Alignment = Info.align.value_or(DAG.getEVTAlign(MemVT));
5833 MachineMemOperand *MMO = MF.getMachineMemOperand(
5834 MPI, Info.flags, Size, Alignment, I.getAAMetadata(), Info.ssid,
5835 Info.order, Info.failureOrder);
5836 MMOs.push_back(MMO);
5837 }
5838
5839 Result = DAG.getMemIntrinsicNode(Info->opc, getCurSDLoc(), VTs, Ops,
5840 Info->memVT, MMOs);
5841 } else {
5842 Result = getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
5843 }
5844
5845 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
5846
5847 setValue(&I, Result);
5848}
5849
5850/// GetSignificand - Get the significand and build it into a floating-point
5851/// number with exponent of 1:
5852///
5853/// Op = (Op & 0x007fffff) | 0x3f800000;
5854///
5855/// where Op is the hexadecimal representation of floating point value.
5857 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5858 DAG.getConstant(0x007fffff, dl, MVT::i32));
5859 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5860 DAG.getConstant(0x3f800000, dl, MVT::i32));
5861 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5862}
5863
5864/// GetExponent - Get the exponent:
5865///
5866/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5867///
5868/// where Op is the hexadecimal representation of floating point value.
5870 const TargetLowering &TLI, const SDLoc &dl) {
5871 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5872 DAG.getConstant(0x7f800000, dl, MVT::i32));
5873 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
5874 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5875 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5876 DAG.getConstant(127, dl, MVT::i32));
5877 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5878}
5879
5880/// getF32Constant - Get 32-bit floating point constant.
5881static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5882 const SDLoc &dl) {
5883 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5884 MVT::f32);
5885}
5886
5888 SelectionDAG &DAG) {
5889 // TODO: What fast-math-flags should be set on the floating-point nodes?
5890
5891 // IntegerPartOfX = ((int32_t)(t0);
5892 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5893
5894 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
5895 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5896 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5897
5898 // IntegerPartOfX <<= 23;
5899 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5900 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5901
5902 SDValue TwoToFractionalPartOfX;
5903 if (LimitFloatPrecision <= 6) {
5904 // For floating-point precision of 6:
5905 //
5906 // TwoToFractionalPartOfX =
5907 // 0.997535578f +
5908 // (0.735607626f + 0.252464424f * x) * x;
5909 //
5910 // error 0.0144103317, which is 6 bits
5911 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5912 getF32Constant(DAG, 0x3e814304, dl));
5913 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5914 getF32Constant(DAG, 0x3f3c50c8, dl));
5915 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5916 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5917 getF32Constant(DAG, 0x3f7f5e7e, dl));
5918 } else if (LimitFloatPrecision <= 12) {
5919 // For floating-point precision of 12:
5920 //
5921 // TwoToFractionalPartOfX =
5922 // 0.999892986f +
5923 // (0.696457318f +
5924 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
5925 //
5926 // error 0.000107046256, which is 13 to 14 bits
5927 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5928 getF32Constant(DAG, 0x3da235e3, dl));
5929 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5930 getF32Constant(DAG, 0x3e65b8f3, dl));
5931 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5932 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5933 getF32Constant(DAG, 0x3f324b07, dl));
5934 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5935 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5936 getF32Constant(DAG, 0x3f7ff8fd, dl));
5937 } else { // LimitFloatPrecision <= 18
5938 // For floating-point precision of 18:
5939 //
5940 // TwoToFractionalPartOfX =
5941 // 0.999999982f +
5942 // (0.693148872f +
5943 // (0.240227044f +
5944 // (0.554906021e-1f +
5945 // (0.961591928e-2f +
5946 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5947 // error 2.47208000*10^(-7), which is better than 18 bits
5948 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5949 getF32Constant(DAG, 0x3924b03e, dl));
5950 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5951 getF32Constant(DAG, 0x3ab24b87, dl));
5952 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5953 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5954 getF32Constant(DAG, 0x3c1d8c17, dl));
5955 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5956 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5957 getF32Constant(DAG, 0x3d634a1d, dl));
5958 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5959 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5960 getF32Constant(DAG, 0x3e75fe14, dl));
5961 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5962 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5963 getF32Constant(DAG, 0x3f317234, dl));
5964 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5965 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5966 getF32Constant(DAG, 0x3f800000, dl));
5967 }
5968
5969 // Add the exponent into the result in integer domain.
5970 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5971 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5972 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5973}
5974
5975/// expandExp - Lower an exp intrinsic. Handles the special sequences for
5976/// limited-precision mode.
5978 const TargetLowering &TLI, SDNodeFlags Flags) {
5979 if (Op.getValueType() == MVT::f32 &&
5981
5982 // Put the exponent in the right bit position for later addition to the
5983 // final result:
5984 //
5985 // t0 = Op * log2(e)
5986
5987 // TODO: What fast-math-flags should be set here?
5988 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5989 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5990 return getLimitedPrecisionExp2(t0, dl, DAG);
5991 }
5992
5993 // No special expansion.
5994 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5995}
5996
5997/// expandLog - Lower a log intrinsic. Handles the special sequences for
5998/// limited-precision mode.
6000 const TargetLowering &TLI, SDNodeFlags Flags) {
6001 // TODO: What fast-math-flags should be set on the floating-point nodes?
6002
6003 if (Op.getValueType() == MVT::f32 &&
6005 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6006
6007 // Scale the exponent by log(2).
6008 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
6009 SDValue LogOfExponent =
6010 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
6011 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
6012
6013 // Get the significand and build it into a floating-point number with
6014 // exponent of 1.
6015 SDValue X = GetSignificand(DAG, Op1, dl);
6016
6017 SDValue LogOfMantissa;
6018 if (LimitFloatPrecision <= 6) {
6019 // For floating-point precision of 6:
6020 //
6021 // LogofMantissa =
6022 // -1.1609546f +
6023 // (1.4034025f - 0.23903021f * x) * x;
6024 //
6025 // error 0.0034276066, which is better than 8 bits
6026 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6027 getF32Constant(DAG, 0xbe74c456, dl));
6028 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6029 getF32Constant(DAG, 0x3fb3a2b1, dl));
6030 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6031 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6032 getF32Constant(DAG, 0x3f949a29, dl));
6033 } else if (LimitFloatPrecision <= 12) {
6034 // For floating-point precision of 12:
6035 //
6036 // LogOfMantissa =
6037 // -1.7417939f +
6038 // (2.8212026f +
6039 // (-1.4699568f +
6040 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
6041 //
6042 // error 0.000061011436, which is 14 bits
6043 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6044 getF32Constant(DAG, 0xbd67b6d6, dl));
6045 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6046 getF32Constant(DAG, 0x3ee4f4b8, dl));
6047 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6048 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6049 getF32Constant(DAG, 0x3fbc278b, dl));
6050 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6051 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6052 getF32Constant(DAG, 0x40348e95, dl));
6053 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6054 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6055 getF32Constant(DAG, 0x3fdef31a, dl));
6056 } else { // LimitFloatPrecision <= 18
6057 // For floating-point precision of 18:
6058 //
6059 // LogOfMantissa =
6060 // -2.1072184f +
6061 // (4.2372794f +
6062 // (-3.7029485f +
6063 // (2.2781945f +
6064 // (-0.87823314f +
6065 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
6066 //
6067 // error 0.0000023660568, which is better than 18 bits
6068 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6069 getF32Constant(DAG, 0xbc91e5ac, dl));
6070 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6071 getF32Constant(DAG, 0x3e4350aa, dl));
6072 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6073 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6074 getF32Constant(DAG, 0x3f60d3e3, dl));
6075 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6076 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6077 getF32Constant(DAG, 0x4011cdf0, dl));
6078 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6079 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6080 getF32Constant(DAG, 0x406cfd1c, dl));
6081 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6082 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
6083 getF32Constant(DAG, 0x408797cb, dl));
6084 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
6085 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
6086 getF32Constant(DAG, 0x4006dcab, dl));
6087 }
6088
6089 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
6090 }
6091
6092 // No special expansion.
6093 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
6094}
6095
6096/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
6097/// limited-precision mode.
6099 const TargetLowering &TLI, SDNodeFlags Flags) {
6100 // TODO: What fast-math-flags should be set on the floating-point nodes?
6101
6102 if (Op.getValueType() == MVT::f32 &&
6104 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6105
6106 // Get the exponent.
6107 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
6108
6109 // Get the significand and build it into a floating-point number with
6110 // exponent of 1.
6111 SDValue X = GetSignificand(DAG, Op1, dl);
6112
6113 // Different possible minimax approximations of significand in
6114 // floating-point for various degrees of accuracy over [1,2].
6115 SDValue Log2ofMantissa;
6116 if (LimitFloatPrecision <= 6) {
6117 // For floating-point precision of 6:
6118 //
6119 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
6120 //
6121 // error 0.0049451742, which is more than 7 bits
6122 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6123 getF32Constant(DAG, 0xbeb08fe0, dl));
6124 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6125 getF32Constant(DAG, 0x40019463, dl));
6126 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6127 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6128 getF32Constant(DAG, 0x3fd6633d, dl));
6129 } else if (LimitFloatPrecision <= 12) {
6130 // For floating-point precision of 12:
6131 //
6132 // Log2ofMantissa =
6133 // -2.51285454f +
6134 // (4.07009056f +
6135 // (-2.12067489f +
6136 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
6137 //
6138 // error 0.0000876136000, which is better than 13 bits
6139 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6140 getF32Constant(DAG, 0xbda7262e, dl));
6141 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6142 getF32Constant(DAG, 0x3f25280b, dl));
6143 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6144 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6145 getF32Constant(DAG, 0x4007b923, dl));
6146 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6147 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6148 getF32Constant(DAG, 0x40823e2f, dl));
6149 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6150 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6151 getF32Constant(DAG, 0x4020d29c, dl));
6152 } else { // LimitFloatPrecision <= 18
6153 // For floating-point precision of 18:
6154 //
6155 // Log2ofMantissa =
6156 // -3.0400495f +
6157 // (6.1129976f +
6158 // (-5.3420409f +
6159 // (3.2865683f +
6160 // (-1.2669343f +
6161 // (0.27515199f -
6162 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
6163 //
6164 // error 0.0000018516, which is better than 18 bits
6165 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6166 getF32Constant(DAG, 0xbcd2769e, dl));
6167 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6168 getF32Constant(DAG, 0x3e8ce0b9, dl));
6169 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6170 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6171 getF32Constant(DAG, 0x3fa22ae7, dl));
6172 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6173 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6174 getF32Constant(DAG, 0x40525723, dl));
6175 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6176 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6177 getF32Constant(DAG, 0x40aaf200, dl));
6178 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6179 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
6180 getF32Constant(DAG, 0x40c39dad, dl));
6181 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
6182 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
6183 getF32Constant(DAG, 0x4042902c, dl));
6184 }
6185
6186 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
6187 }
6188
6189 // No special expansion.
6190 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
6191}
6192
6193/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
6194/// limited-precision mode.
6196 const TargetLowering &TLI, SDNodeFlags Flags) {
6197 // TODO: What fast-math-flags should be set on the floating-point nodes?
6198
6199 if (Op.getValueType() == MVT::f32 &&
6201 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6202
6203 // Scale the exponent by log10(2) [0.30102999f].
6204 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
6205 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
6206 getF32Constant(DAG, 0x3e9a209a, dl));
6207
6208 // Get the significand and build it into a floating-point number with
6209 // exponent of 1.
6210 SDValue X = GetSignificand(DAG, Op1, dl);
6211
6212 SDValue Log10ofMantissa;
6213 if (LimitFloatPrecision <= 6) {
6214 // For floating-point precision of 6:
6215 //
6216 // Log10ofMantissa =
6217 // -0.50419619f +
6218 // (0.60948995f - 0.10380950f * x) * x;
6219 //
6220 // error 0.0014886165, which is 6 bits
6221 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6222 getF32Constant(DAG, 0xbdd49a13, dl));
6223 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6224 getF32Constant(DAG, 0x3f1c0789, dl));
6225 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6226 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6227 getF32Constant(DAG, 0x3f011300, dl));
6228 } else if (LimitFloatPrecision <= 12) {
6229 // For floating-point precision of 12:
6230 //
6231 // Log10ofMantissa =
6232 // -0.64831180f +
6233 // (0.91751397f +
6234 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
6235 //
6236 // error 0.00019228036, which is better than 12 bits
6237 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6238 getF32Constant(DAG, 0x3d431f31, dl));
6239 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6240 getF32Constant(DAG, 0x3ea21fb2, dl));
6241 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6242 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6243 getF32Constant(DAG, 0x3f6ae232, dl));
6244 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6245 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6246 getF32Constant(DAG, 0x3f25f7c3, dl));
6247 } else { // LimitFloatPrecision <= 18
6248 // For floating-point precision of 18:
6249 //
6250 // Log10ofMantissa =
6251 // -0.84299375f +
6252 // (1.5327582f +
6253 // (-1.0688956f +
6254 // (0.49102474f +
6255 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
6256 //
6257 // error 0.0000037995730, which is better than 18 bits
6258 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6259 getF32Constant(DAG, 0x3c5d51ce, dl));
6260 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6261 getF32Constant(DAG, 0x3e00685a, dl));
6262 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6263 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6264 getF32Constant(DAG, 0x3efb6798, dl));
6265 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6266 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6267 getF32Constant(DAG, 0x3f88d192, dl));
6268 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6269 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
6270 getF32Constant(DAG, 0x3fc4316c, dl));
6271 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6272 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
6273 getF32Constant(DAG, 0x3f57ce70, dl));
6274 }
6275
6276 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
6277 }
6278
6279 // No special expansion.
6280 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
6281}
6282
6283/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
6284/// limited-precision mode.
6286 const TargetLowering &TLI, SDNodeFlags Flags) {
6287 if (Op.getValueType() == MVT::f32 &&
6289 return getLimitedPrecisionExp2(Op, dl, DAG);
6290
6291 // No special expansion.
6292 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
6293}
6294
6295/// visitPow - Lower a pow intrinsic. Handles the special sequences for
6296/// limited-precision mode with x == 10.0f.
6298 SelectionDAG &DAG, const TargetLowering &TLI,
6299 SDNodeFlags Flags) {
6300 bool IsExp10 = false;
6301 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
6304 APFloat Ten(10.0f);
6305 IsExp10 = LHSC->isExactlyValue(Ten);
6306 }
6307 }
6308
6309 // TODO: What fast-math-flags should be set on the FMUL node?
6310 if (IsExp10) {
6311 // Put the exponent in the right bit position for later addition to the
6312 // final result:
6313 //
6314 // #define LOG2OF10 3.3219281f
6315 // t0 = Op * LOG2OF10;
6316 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
6317 getF32Constant(DAG, 0x40549a78, dl));
6318 return getLimitedPrecisionExp2(t0, dl, DAG);
6319 }
6320
6321 // No special expansion.
6322 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
6323}
6324
6325/// ExpandPowI - Expand a llvm.powi intrinsic.
6327 SelectionDAG &DAG) {
6328 // If RHS is a constant, we can expand this out to a multiplication tree if
6329 // it's beneficial on the target, otherwise we end up lowering to a call to
6330 // __powidf2 (for example).
6332 unsigned Val = RHSC->getSExtValue();
6333
6334 // powi(x, 0) -> 1.0
6335 if (Val == 0)
6336 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
6337
6339 Val, DAG.shouldOptForSize())) {
6340 // Get the exponent as a positive value.
6341 if ((int)Val < 0)
6342 Val = -Val;
6343 // We use the simple binary decomposition method to generate the multiply
6344 // sequence. There are more optimal ways to do this (for example,
6345 // powi(x,15) generates one more multiply than it should), but this has
6346 // the benefit of being both really simple and much better than a libcall.
6347 SDValue Res; // Logically starts equal to 1.0
6348 SDValue CurSquare = LHS;
6349 // TODO: Intrinsics should have fast-math-flags that propagate to these
6350 // nodes.
6351 while (Val) {
6352 if (Val & 1) {
6353 if (Res.getNode())
6354 Res =
6355 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
6356 else
6357 Res = CurSquare; // 1.0*CurSquare.
6358 }
6359
6360 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
6361 CurSquare, CurSquare);
6362 Val >>= 1;
6363 }
6364
6365 // If the original was negative, invert the result, producing 1/(x*x*x).
6366 if (RHSC->getSExtValue() < 0)
6367 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
6368 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
6369 return Res;
6370 }
6371 }
6372
6373 // Otherwise, expand to a libcall.
6374 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
6375}
6376
6377static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
6378 SDValue LHS, SDValue RHS, SDValue Scale,
6379 SelectionDAG &DAG, const TargetLowering &TLI) {
6380 EVT VT = LHS.getValueType();
6381 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
6382 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
6383 LLVMContext &Ctx = *DAG.getContext();
6384
6385 // If the type is legal but the operation isn't, this node might survive all
6386 // the way to operation legalization. If we end up there and we do not have
6387 // the ability to widen the type (if VT*2 is not legal), we cannot expand the
6388 // node.
6389
6390 // Coax the legalizer into expanding the node during type legalization instead
6391 // by bumping the size by one bit. This will force it to Promote, enabling the
6392 // early expansion and avoiding the need to expand later.
6393
6394 // We don't have to do this if Scale is 0; that can always be expanded, unless
6395 // it's a saturating signed operation. Those can experience true integer
6396 // division overflow, a case which we must avoid.
6397
6398 // FIXME: We wouldn't have to do this (or any of the early
6399 // expansion/promotion) if it was possible to expand a libcall of an
6400 // illegal type during operation legalization. But it's not, so things
6401 // get a bit hacky.
6402 unsigned ScaleInt = Scale->getAsZExtVal();
6403 if ((ScaleInt > 0 || (Saturating && Signed)) &&
6404 (TLI.isTypeLegal(VT) ||
6405 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
6406 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
6407 Opcode, VT, ScaleInt);
6408 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
6409 EVT PromVT;
6410 if (VT.isScalarInteger())
6411 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
6412 else if (VT.isVector()) {
6413 PromVT = VT.getVectorElementType();
6414 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
6415 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
6416 } else
6417 llvm_unreachable("Wrong VT for DIVFIX?");
6418 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
6419 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
6420 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
6421 // For saturating operations, we need to shift up the LHS to get the
6422 // proper saturation width, and then shift down again afterwards.
6423 if (Saturating)
6424 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
6425 DAG.getConstant(1, DL, ShiftTy));
6426 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
6427 if (Saturating)
6428 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
6429 DAG.getConstant(1, DL, ShiftTy));
6430 return DAG.getZExtOrTrunc(Res, DL, VT);
6431 }
6432 }
6433
6434 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
6435}
6436
6437// getUnderlyingArgRegs - Find underlying registers used for a truncated,
6438// bitcasted, or split argument. Returns a list of <Register, size in bits>
6439static void
6440getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
6441 const SDValue &N) {
6442 switch (N.getOpcode()) {
6443 case ISD::CopyFromReg: {
6444 SDValue Op = N.getOperand(1);
6445 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
6446 Op.getValueType().getSizeInBits());
6447 return;
6448 }
6449 case ISD::BITCAST:
6450 case ISD::AssertZext:
6451 case ISD::AssertSext:
6452 case ISD::TRUNCATE:
6453 getUnderlyingArgRegs(Regs, N.getOperand(0));
6454 return;
6455 case ISD::BUILD_PAIR:
6456 case ISD::BUILD_VECTOR:
6458 for (SDValue Op : N->op_values())
6459 getUnderlyingArgRegs(Regs, Op);
6460 return;
6461 default:
6462 return;
6463 }
6464}
6465
6466/// If the DbgValueInst is a dbg_value of a function argument, create the
6467/// corresponding DBG_VALUE machine instruction for it now. At the end of
6468/// instruction selection, they will be inserted to the entry BB.
6469/// We don't currently support this for variadic dbg_values, as they shouldn't
6470/// appear for function arguments or in the prologue.
6471bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6472 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6473 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6474 const Argument *Arg = dyn_cast<Argument>(V);
6475 if (!Arg)
6476 return false;
6477
6478 MachineFunction &MF = DAG.getMachineFunction();
6479 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6480
6481 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6482 // we've been asked to pursue.
6483 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6484 bool Indirect) {
6485 if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6486 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6487 // pointing at the VReg, which will be patched up later.
6488 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6490 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6491 /* isKill */ false, /* isDead */ false,
6492 /* isUndef */ false, /* isEarlyClobber */ false,
6493 /* SubReg */ 0, /* isDebug */ true)});
6494
6495 auto *NewDIExpr = FragExpr;
6496 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6497 // the DIExpression.
6498 if (Indirect)
6499 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6501 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6502 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6503 } else {
6504 // Create a completely standard DBG_VALUE.
6505 auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6506 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6507 }
6508 };
6509
6510 if (Kind == FuncArgumentDbgValueKind::Value) {
6511 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6512 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6513 // the entry block.
6514 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6515 if (!IsInEntryBlock)
6516 return false;
6517
6518 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6519 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6520 // variable that also is a param.
6521 //
6522 // Although, if we are at the top of the entry block already, we can still
6523 // emit using ArgDbgValue. This might catch some situations when the
6524 // dbg.value refers to an argument that isn't used in the entry block, so
6525 // any CopyToReg node would be optimized out and the only way to express
6526 // this DBG_VALUE is by using the physical reg (or FI) as done in this
6527 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
6528 // we should only emit as ArgDbgValue if the Variable is an argument to the
6529 // current function, and the dbg.value intrinsic is found in the entry
6530 // block.
6531 bool VariableIsFunctionInputArg = Variable->isParameter() &&
6532 !DL->getInlinedAt();
6533 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6534 if (!IsInPrologue && !VariableIsFunctionInputArg)
6535 return false;
6536
6537 // Here we assume that a function argument on IR level only can be used to
6538 // describe one input parameter on source level. If we for example have
6539 // source code like this
6540 //
6541 // struct A { long x, y; };
6542 // void foo(struct A a, long b) {
6543 // ...
6544 // b = a.x;
6545 // ...
6546 // }
6547 //
6548 // and IR like this
6549 //
6550 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
6551 // entry:
6552 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6553 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6554 // call void @llvm.dbg.value(metadata i32 %b, "b",
6555 // ...
6556 // call void @llvm.dbg.value(metadata i32 %a1, "b"
6557 // ...
6558 //
6559 // then the last dbg.value is describing a parameter "b" using a value that
6560 // is an argument. But since we already has used %a1 to describe a parameter
6561 // we should not handle that last dbg.value here (that would result in an
6562 // incorrect hoisting of the DBG_VALUE to the function entry).
6563 // Notice that we allow one dbg.value per IR level argument, to accommodate
6564 // for the situation with fragments above.
6565 // If there is no node for the value being handled, we return true to skip
6566 // the normal generation of debug info, as it would kill existing debug
6567 // info for the parameter in case of duplicates.
6568 if (VariableIsFunctionInputArg) {
6569 unsigned ArgNo = Arg->getArgNo();
6570 if (ArgNo >= FuncInfo.DescribedArgs.size())
6571 FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6572 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6573 return !NodeMap[V].getNode();
6574 FuncInfo.DescribedArgs.set(ArgNo);
6575 }
6576 }
6577
6578 bool IsIndirect = false;
6579 std::optional<MachineOperand> Op;
6580 // Some arguments' frame index is recorded during argument lowering.
6581 int FI = FuncInfo.getArgumentFrameIndex(Arg);
6582 if (FI != std::numeric_limits<int>::max())
6584
6586 if (!Op && N.getNode()) {
6587 getUnderlyingArgRegs(ArgRegsAndSizes, N);
6588 Register Reg;
6589 if (ArgRegsAndSizes.size() == 1)
6590 Reg = ArgRegsAndSizes.front().first;
6591
6592 if (Reg && Reg.isVirtual()) {
6593 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6594 Register PR = RegInfo.getLiveInPhysReg(Reg);
6595 if (PR)
6596 Reg = PR;
6597 }
6598 if (Reg) {
6600 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6601 }
6602 }
6603
6604 if (!Op && N.getNode()) {
6605 // Check if frame index is available.
6606 SDValue LCandidate = peekThroughBitcasts(N);
6607 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6608 if (FrameIndexSDNode *FINode =
6609 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6610 Op = MachineOperand::CreateFI(FINode->getIndex());
6611 }
6612
6613 if (!Op) {
6614 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6615 auto splitMultiRegDbgValue =
6616 [&](ArrayRef<std::pair<Register, TypeSize>> SplitRegs) -> bool {
6617 unsigned Offset = 0;
6618 for (const auto &[Reg, RegSizeInBits] : SplitRegs) {
6619 // FIXME: Scalable sizes are not supported in fragment expressions.
6620 if (RegSizeInBits.isScalable())
6621 return false;
6622
6623 // If the expression is already a fragment, the current register
6624 // offset+size might extend beyond the fragment. In this case, only
6625 // the register bits that are inside the fragment are relevant.
6626 int RegFragmentSizeInBits = RegSizeInBits.getFixedValue();
6627 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6628 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6629 // The register is entirely outside the expression fragment,
6630 // so is irrelevant for debug info.
6631 if (Offset >= ExprFragmentSizeInBits)
6632 break;
6633 // The register is partially outside the expression fragment, only
6634 // the low bits within the fragment are relevant for debug info.
6635 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6636 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6637 }
6638 }
6639
6640 auto FragmentExpr = DIExpression::createFragmentExpression(
6641 Expr, Offset, RegFragmentSizeInBits);
6642 Offset += RegSizeInBits.getFixedValue();
6643 // If a valid fragment expression cannot be created, the variable's
6644 // correct value cannot be determined and so it is set as poison.
6645 if (!FragmentExpr) {
6646 SDDbgValue *SDV = DAG.getConstantDbgValue(
6647 Variable, Expr, PoisonValue::get(V->getType()), DL, SDNodeOrder);
6648 DAG.AddDbgValue(SDV, false);
6649 continue;
6650 }
6651 MachineInstr *NewMI = MakeVRegDbgValue(
6652 Reg, *FragmentExpr, Kind != FuncArgumentDbgValueKind::Value);
6653 FuncInfo.ArgDbgValues.push_back(NewMI);
6654 }
6655
6656 return true;
6657 };
6658
6659 // Check if ValueMap has reg number.
6661 VMI = FuncInfo.ValueMap.find(V);
6662 if (VMI != FuncInfo.ValueMap.end()) {
6663 const auto &TLI = DAG.getTargetLoweringInfo();
6664 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6665 V->getType(), std::nullopt);
6666 if (RFV.occupiesMultipleRegs())
6667 return splitMultiRegDbgValue(RFV.getRegsAndSizes());
6668
6669 Op = MachineOperand::CreateReg(VMI->second, false);
6670 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6671 } else if (ArgRegsAndSizes.size() > 1) {
6672 // This was split due to the calling convention, and no virtual register
6673 // mapping exists for the value.
6674 return splitMultiRegDbgValue(ArgRegsAndSizes);
6675 }
6676 }
6677
6678 if (!Op)
6679 return false;
6680
6681 assert(Variable->isValidLocationForIntrinsic(DL) &&
6682 "Expected inlined-at fields to agree");
6683 MachineInstr *NewMI = nullptr;
6684
6685 if (Op->isReg())
6686 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6687 else
6688 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6689 Variable, Expr);
6690
6691 // Otherwise, use ArgDbgValues.
6692 FuncInfo.ArgDbgValues.push_back(NewMI);
6693 return true;
6694}
6695
6696/// Return the appropriate SDDbgValue based on N.
6697SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6698 DILocalVariable *Variable,
6699 DIExpression *Expr,
6700 const DebugLoc &dl,
6701 unsigned DbgSDNodeOrder) {
6702 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6703 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6704 // stack slot locations.
6705 //
6706 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6707 // debug values here after optimization:
6708 //
6709 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
6710 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6711 //
6712 // Both describe the direct values of their associated variables.
6713 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6714 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6715 }
6716 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6717 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6718}
6719
6720static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6721 switch (Intrinsic) {
6722 case Intrinsic::smul_fix:
6723 return ISD::SMULFIX;
6724 case Intrinsic::umul_fix:
6725 return ISD::UMULFIX;
6726 case Intrinsic::smul_fix_sat:
6727 return ISD::SMULFIXSAT;
6728 case Intrinsic::umul_fix_sat:
6729 return ISD::UMULFIXSAT;
6730 case Intrinsic::sdiv_fix:
6731 return ISD::SDIVFIX;
6732 case Intrinsic::udiv_fix:
6733 return ISD::UDIVFIX;
6734 case Intrinsic::sdiv_fix_sat:
6735 return ISD::SDIVFIXSAT;
6736 case Intrinsic::udiv_fix_sat:
6737 return ISD::UDIVFIXSAT;
6738 default:
6739 llvm_unreachable("Unhandled fixed point intrinsic");
6740 }
6741}
6742
6743/// Given a @llvm.call.preallocated.setup, return the corresponding
6744/// preallocated call.
6745static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6746 assert(cast<CallBase>(PreallocatedSetup)
6748 ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6749 "expected call_preallocated_setup Value");
6750 for (const auto *U : PreallocatedSetup->users()) {
6751 auto *UseCall = cast<CallBase>(U);
6752 const Function *Fn = UseCall->getCalledFunction();
6753 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6754 return UseCall;
6755 }
6756 }
6757 llvm_unreachable("expected corresponding call to preallocated setup/arg");
6758}
6759
6760/// If DI is a debug value with an EntryValue expression, lower it using the
6761/// corresponding physical register of the associated Argument value
6762/// (guaranteed to exist by the verifier).
6763bool SelectionDAGBuilder::visitEntryValueDbgValue(
6765 DIExpression *Expr, DebugLoc DbgLoc) {
6766 if (!Expr->isEntryValue() || !hasSingleElement(Values))
6767 return false;
6768
6769 // These properties are guaranteed by the verifier.
6770 const Argument *Arg = cast<Argument>(Values[0]);
6771 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6772
6773 auto ArgIt = FuncInfo.ValueMap.find(Arg);
6774 if (ArgIt == FuncInfo.ValueMap.end()) {
6775 LLVM_DEBUG(
6776 dbgs() << "Dropping dbg.value: expression is entry_value but "
6777 "couldn't find an associated register for the Argument\n");
6778 return true;
6779 }
6780 Register ArgVReg = ArgIt->getSecond();
6781
6782 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6783 if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6784 SDDbgValue *SDV = DAG.getVRegDbgValue(
6785 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6786 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6787 return true;
6788 }
6789 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6790 "couldn't find a physical register\n");
6791 return true;
6792}
6793
6794/// Lower the call to the specified intrinsic function.
6795void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6796 unsigned Intrinsic) {
6797 SDLoc sdl = getCurSDLoc();
6798 switch (Intrinsic) {
6799 case Intrinsic::experimental_convergence_anchor:
6800 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6801 break;
6802 case Intrinsic::experimental_convergence_entry:
6803 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6804 break;
6805 case Intrinsic::experimental_convergence_loop: {
6806 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6807 auto *Token = Bundle->Inputs[0].get();
6808 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6809 getValue(Token)));
6810 break;
6811 }
6812 }
6813}
6814
6815void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6816 unsigned IntrinsicID) {
6817 // For now, we're only lowering an 'add' histogram.
6818 // We can add others later, e.g. saturating adds, min/max.
6819 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6820 "Tried to lower unsupported histogram type");
6821 SDLoc sdl = getCurSDLoc();
6822 Value *Ptr = I.getOperand(0);
6823 SDValue Inc = getValue(I.getOperand(1));
6824 SDValue Mask = getValue(I.getOperand(2));
6825
6826 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6827 EVT VT = Inc.getValueType();
6828 Align Alignment = DAG.getEVTAlign(VT);
6829
6830 const MDNode *Ranges = getRangeMetadata(I);
6831
6832 SDValue Root = DAG.getRoot();
6833 SDValue Base;
6834 SDValue Index;
6835 SDValue Scale;
6836 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
6837 I.getParent(), VT.getScalarStoreSize());
6838
6839 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6840
6841 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6842 MachinePointerInfo(AS),
6844 MemoryLocation::UnknownSize, Alignment,
6845 MMOMetadata(I.getAAMetadata(), Ranges));
6846
6847 if (!UniformBase) {
6848 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6849 Index = getValue(Ptr);
6850 Scale =
6851 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6852 }
6853
6854 EVT IdxVT = Index.getValueType();
6855
6856 // Avoid using e.g. i32 as index type when the increment must be performed
6857 // on i64's.
6858 bool MustExtendIndex = VT.getScalarSizeInBits() > IdxVT.getScalarSizeInBits();
6859 EVT EltTy = MustExtendIndex ? VT : IdxVT.getVectorElementType();
6860 if (MustExtendIndex || TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6861 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
6862 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6863 }
6864
6865 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6866
6867 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6868 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6869 Ops, MMO, ISD::SIGNED_SCALED);
6870
6871 setValue(&I, Histogram);
6872 DAG.setRoot(Histogram);
6873}
6874
6875void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6876 unsigned Intrinsic) {
6877 assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6878 "Tried lowering invalid vector extract last");
6879 SDLoc sdl = getCurSDLoc();
6880 const DataLayout &Layout = DAG.getDataLayout();
6881 SDValue Data = getValue(I.getOperand(0));
6882 SDValue Mask = getValue(I.getOperand(1));
6883
6884 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6885 EVT ResVT = TLI.getValueType(Layout, I.getType());
6886
6887 EVT ExtVT = TLI.getVectorIdxTy(Layout);
6888 SDValue Idx = DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, sdl, ExtVT, Mask);
6889 SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl, ResVT, Data, Idx);
6890
6891 Value *Default = I.getOperand(2);
6893 SDValue PassThru = getValue(Default);
6894 EVT BoolVT = Mask.getValueType().getScalarType();
6895 SDValue AnyActive = DAG.getNode(ISD::VECREDUCE_OR, sdl, BoolVT, Mask);
6896 Result = DAG.getSelect(sdl, ResVT, AnyActive, Result, PassThru);
6897 }
6898
6899 setValue(&I, Result);
6900}
6901
6902/// Lower the call to the specified intrinsic function.
6903void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6904 unsigned Intrinsic) {
6905 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6906 SDLoc sdl = getCurSDLoc();
6907 DebugLoc dl = getCurDebugLoc();
6908 SDValue Res;
6909
6910 SDNodeFlags Flags;
6911 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6912 Flags.copyFMF(*FPOp);
6913
6914 switch (Intrinsic) {
6915 default:
6916 // By default, turn this into a target intrinsic node.
6917 visitTargetIntrinsic(I, Intrinsic);
6918 return;
6919 case Intrinsic::vscale: {
6920 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6921 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6922 return;
6923 }
6924 case Intrinsic::vastart: visitVAStart(I); return;
6925 case Intrinsic::vaend: visitVAEnd(I); return;
6926 case Intrinsic::vacopy: visitVACopy(I); return;
6927 case Intrinsic::returnaddress:
6928 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6929 TLI.getValueType(DAG.getDataLayout(), I.getType()),
6930 getValue(I.getArgOperand(0))));
6931 return;
6932 case Intrinsic::addressofreturnaddress:
6933 setValue(&I,
6934 DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6935 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6936 return;
6937 case Intrinsic::sponentry:
6938 setValue(&I,
6939 DAG.getNode(ISD::SPONENTRY, sdl,
6940 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6941 return;
6942 case Intrinsic::frameaddress:
6943 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6944 TLI.getFrameIndexTy(DAG.getDataLayout()),
6945 getValue(I.getArgOperand(0))));
6946 return;
6947 case Intrinsic::read_volatile_register:
6948 case Intrinsic::read_register: {
6949 Value *Reg = I.getArgOperand(0);
6950 SDValue Chain = getRoot();
6952 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6953 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6954 Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6955 DAG.getVTList(VT, MVT::Other), Chain, RegName);
6956 setValue(&I, Res);
6957 DAG.setRoot(Res.getValue(1));
6958 return;
6959 }
6960 case Intrinsic::write_register: {
6961 Value *Reg = I.getArgOperand(0);
6962 Value *RegValue = I.getArgOperand(1);
6963 SDValue Chain = getRoot();
6965 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6966 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6967 RegName, getValue(RegValue)));
6968 return;
6969 }
6970 case Intrinsic::write_volatile_register: {
6971 Value *Reg = I.getArgOperand(0);
6972 Value *RegValue = I.getArgOperand(1);
6973 SDValue Chain = getRoot();
6974 const MDNode *MD = cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata());
6975 SDValue RegName = DAG.getMDNode(MD);
6976 EVT VT = TLI.getValueType(DAG.getDataLayout(), RegValue->getType());
6977 SDValue WriteChain = DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other,
6978 Chain, RegName, getValue(RegValue));
6979 // FAKE_USE of the physical register marks it live after the WRITE_REGISTER,
6980 // preventing the backend from dead-eliminating the write. This is
6981 // preferred over READ_REGISTER, which would emit extra register copies
6982 // (e.g. fmov xN, dN for FP/SIMD registers).
6983 const MDString *RegStr = cast<MDString>(MD->getOperand(0));
6984 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
6985 const MachineFunction &MF = DAG.getMachineFunction();
6986 Register PhysReg =
6987 TLI.getRegisterByName(RegStr->getString().data(), Ty, MF);
6988 if (PhysReg.isValid()) {
6989 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6990 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysReg);
6991 MVT RegVT = *TRI->legalclasstypes_begin(*RC);
6992 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other,
6993 {WriteChain, DAG.getRegister(PhysReg, RegVT)}));
6994 } else {
6995 DAG.setRoot(WriteChain);
6996 }
6997 return;
6998 }
6999 case Intrinsic::memcpy:
7000 case Intrinsic::memcpy_inline: {
7001 const auto &MCI = cast<MemCpyInst>(I);
7002 SDValue Dst = getValue(I.getArgOperand(0));
7003 SDValue Src = getValue(I.getArgOperand(1));
7004 SDValue Size = getValue(I.getArgOperand(2));
7005 assert((!MCI.isForceInlined() || isa<ConstantSDNode>(Size)) &&
7006 "memcpy_inline needs constant size");
7007 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
7008 Align DstAlign = MCI.getDestAlign().valueOrOne();
7009 Align SrcAlign = MCI.getSourceAlign().valueOrOne();
7010 bool isVol = MCI.isVolatile();
7011 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7012 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, DstAlign, SrcAlign,
7013 isVol, MCI.isForceInlined(), &I, std::nullopt,
7014 MachinePointerInfo(I.getArgOperand(0)),
7015 MachinePointerInfo(I.getArgOperand(1)),
7016 I.getAAMetadata(), BatchAA);
7017 updateDAGForMaybeTailCall(MC);
7018 return;
7019 }
7020 case Intrinsic::memset:
7021 case Intrinsic::memset_inline: {
7022 const auto &MSII = cast<MemSetInst>(I);
7023 SDValue Dst = getValue(I.getArgOperand(0));
7024 SDValue Value = getValue(I.getArgOperand(1));
7025 SDValue Size = getValue(I.getArgOperand(2));
7026 assert((!MSII.isForceInlined() || isa<ConstantSDNode>(Size)) &&
7027 "memset_inline needs constant size");
7028 // @llvm.memset defines 0 and 1 to both mean no alignment.
7029 Align DstAlign = MSII.getDestAlign().valueOrOne();
7030 bool isVol = MSII.isVolatile();
7031 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7032 SDValue MC = DAG.getMemset(
7033 Root, sdl, Dst, Value, Size, DstAlign, isVol, MSII.isForceInlined(),
7034 &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
7035 updateDAGForMaybeTailCall(MC);
7036 return;
7037 }
7038 case Intrinsic::memmove: {
7039 const auto &MMI = cast<MemMoveInst>(I);
7040 SDValue Op1 = getValue(I.getArgOperand(0));
7041 SDValue Op2 = getValue(I.getArgOperand(1));
7042 SDValue Op3 = getValue(I.getArgOperand(2));
7043 // @llvm.memmove defines 0 and 1 to both mean no alignment.
7044 Align DstAlign = MMI.getDestAlign().valueOrOne();
7045 Align SrcAlign = MMI.getSourceAlign().valueOrOne();
7046 bool isVol = MMI.isVolatile();
7047 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7048 SDValue MM = DAG.getMemmove(
7049 Root, sdl, Op1, Op2, Op3, DstAlign, SrcAlign, isVol, &I,
7050 /* OverrideTailCall */ std::nullopt,
7051 MachinePointerInfo(I.getArgOperand(0)),
7052 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), BatchAA);
7053 updateDAGForMaybeTailCall(MM);
7054 return;
7055 }
7056 case Intrinsic::memcpy_element_unordered_atomic: {
7057 auto &MI = cast<AnyMemCpyInst>(I);
7058 SDValue Dst = getValue(MI.getRawDest());
7059 SDValue Src = getValue(MI.getRawSource());
7060 SDValue Length = getValue(MI.getLength());
7061
7062 Type *LengthTy = MI.getLength()->getType();
7063 unsigned ElemSz = MI.getElementSizeInBytes();
7064 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7065 SDValue MC =
7066 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
7067 isTC, MachinePointerInfo(MI.getRawDest()),
7068 MachinePointerInfo(MI.getRawSource()));
7069 updateDAGForMaybeTailCall(MC);
7070 return;
7071 }
7072 case Intrinsic::memmove_element_unordered_atomic: {
7073 auto &MI = cast<AnyMemMoveInst>(I);
7074 SDValue Dst = getValue(MI.getRawDest());
7075 SDValue Src = getValue(MI.getRawSource());
7076 SDValue Length = getValue(MI.getLength());
7077
7078 Type *LengthTy = MI.getLength()->getType();
7079 unsigned ElemSz = MI.getElementSizeInBytes();
7080 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7081 SDValue MC =
7082 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
7083 isTC, MachinePointerInfo(MI.getRawDest()),
7084 MachinePointerInfo(MI.getRawSource()));
7085 updateDAGForMaybeTailCall(MC);
7086 return;
7087 }
7088 case Intrinsic::memset_element_unordered_atomic: {
7089 auto &MI = cast<AnyMemSetInst>(I);
7090 SDValue Dst = getValue(MI.getRawDest());
7091 SDValue Val = getValue(MI.getValue());
7092 SDValue Length = getValue(MI.getLength());
7093
7094 Type *LengthTy = MI.getLength()->getType();
7095 unsigned ElemSz = MI.getElementSizeInBytes();
7096 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7097 SDValue MC =
7098 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
7099 isTC, MachinePointerInfo(MI.getRawDest()));
7100 updateDAGForMaybeTailCall(MC);
7101 return;
7102 }
7103 case Intrinsic::call_preallocated_setup: {
7104 const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
7105 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
7106 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
7107 getRoot(), SrcValue);
7108 setValue(&I, Res);
7109 DAG.setRoot(Res);
7110 return;
7111 }
7112 case Intrinsic::call_preallocated_arg: {
7113 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
7114 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
7115 SDValue Ops[3];
7116 Ops[0] = getRoot();
7117 Ops[1] = SrcValue;
7118 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7119 MVT::i32); // arg index
7120 SDValue Res = DAG.getNode(
7122 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
7123 setValue(&I, Res);
7124 DAG.setRoot(Res.getValue(1));
7125 return;
7126 }
7127
7128 case Intrinsic::eh_typeid_for: {
7129 // Find the type id for the given typeinfo.
7130 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
7131 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
7132 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
7133 setValue(&I, Res);
7134 return;
7135 }
7136
7137 case Intrinsic::eh_return_i32:
7138 case Intrinsic::eh_return_i64:
7139 DAG.getMachineFunction().setCallsEHReturn(true);
7140 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
7141 MVT::Other,
7143 getValue(I.getArgOperand(0)),
7144 getValue(I.getArgOperand(1))));
7145 return;
7146 case Intrinsic::eh_unwind_init:
7147 DAG.getMachineFunction().setCallsUnwindInit(true);
7148 return;
7149 case Intrinsic::eh_dwarf_cfa:
7150 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
7151 TLI.getPointerTy(DAG.getDataLayout()),
7152 getValue(I.getArgOperand(0))));
7153 return;
7154 case Intrinsic::eh_sjlj_callsite: {
7155 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
7156 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
7157
7158 FuncInfo.setCurrentCallSite(CI->getZExtValue());
7159 return;
7160 }
7161 case Intrinsic::eh_sjlj_functioncontext: {
7162 // Get and store the index of the function context.
7163 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7164 AllocaInst *FnCtx =
7165 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
7166 int FI = FuncInfo.StaticAllocaMap[FnCtx];
7168 return;
7169 }
7170 case Intrinsic::eh_sjlj_setjmp: {
7171 SDValue Ops[2];
7172 Ops[0] = getRoot();
7173 Ops[1] = getValue(I.getArgOperand(0));
7174 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
7175 DAG.getVTList(MVT::i32, MVT::Other), Ops);
7176 setValue(&I, Op.getValue(0));
7177 DAG.setRoot(Op.getValue(1));
7178 return;
7179 }
7180 case Intrinsic::eh_sjlj_longjmp:
7181 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
7182 getRoot(), getValue(I.getArgOperand(0))));
7183 return;
7184 case Intrinsic::eh_sjlj_setup_dispatch:
7185 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
7186 getRoot()));
7187 return;
7188 case Intrinsic::masked_gather:
7189 visitMaskedGather(I);
7190 return;
7191 case Intrinsic::masked_load:
7192 visitMaskedLoad(I);
7193 return;
7194 case Intrinsic::masked_scatter:
7195 visitMaskedScatter(I);
7196 return;
7197 case Intrinsic::masked_store:
7198 visitMaskedStore(I);
7199 return;
7200 case Intrinsic::masked_expandload:
7201 visitMaskedLoad(I, true /* IsExpanding */);
7202 return;
7203 case Intrinsic::masked_compressstore:
7204 visitMaskedStore(I, true /* IsCompressing */);
7205 return;
7206 case Intrinsic::speculative_load:
7207 visitSpeculativeLoad(I);
7208 return;
7209 case Intrinsic::powi:
7210 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
7211 getValue(I.getArgOperand(1)), DAG));
7212 return;
7213 case Intrinsic::log:
7214 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7215 return;
7216 case Intrinsic::log2:
7217 setValue(&I,
7218 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7219 return;
7220 case Intrinsic::log10:
7221 setValue(&I,
7222 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7223 return;
7224 case Intrinsic::exp:
7225 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7226 return;
7227 case Intrinsic::exp2:
7228 setValue(&I,
7229 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7230 return;
7231 case Intrinsic::pow:
7232 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
7233 getValue(I.getArgOperand(1)), DAG, TLI, Flags));
7234 return;
7235 case Intrinsic::sqrt:
7236 case Intrinsic::fabs:
7237 case Intrinsic::sin:
7238 case Intrinsic::cos:
7239 case Intrinsic::tan:
7240 case Intrinsic::asin:
7241 case Intrinsic::acos:
7242 case Intrinsic::atan:
7243 case Intrinsic::sinh:
7244 case Intrinsic::cosh:
7245 case Intrinsic::tanh:
7246 case Intrinsic::exp10:
7247 case Intrinsic::floor:
7248 case Intrinsic::ceil:
7249 case Intrinsic::trunc:
7250 case Intrinsic::rint:
7251 case Intrinsic::nearbyint:
7252 case Intrinsic::round:
7253 case Intrinsic::roundeven:
7254 case Intrinsic::canonicalize: {
7255 unsigned Opcode;
7256 // clang-format off
7257 switch (Intrinsic) {
7258 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7259 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
7260 case Intrinsic::fabs: Opcode = ISD::FABS; break;
7261 case Intrinsic::sin: Opcode = ISD::FSIN; break;
7262 case Intrinsic::cos: Opcode = ISD::FCOS; break;
7263 case Intrinsic::tan: Opcode = ISD::FTAN; break;
7264 case Intrinsic::asin: Opcode = ISD::FASIN; break;
7265 case Intrinsic::acos: Opcode = ISD::FACOS; break;
7266 case Intrinsic::atan: Opcode = ISD::FATAN; break;
7267 case Intrinsic::sinh: Opcode = ISD::FSINH; break;
7268 case Intrinsic::cosh: Opcode = ISD::FCOSH; break;
7269 case Intrinsic::tanh: Opcode = ISD::FTANH; break;
7270 case Intrinsic::exp10: Opcode = ISD::FEXP10; break;
7271 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
7272 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
7273 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
7274 case Intrinsic::rint: Opcode = ISD::FRINT; break;
7275 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
7276 case Intrinsic::round: Opcode = ISD::FROUND; break;
7277 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
7278 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
7279 }
7280 // clang-format on
7281
7282 setValue(&I, DAG.getNode(Opcode, sdl,
7283 getValue(I.getArgOperand(0)).getValueType(),
7284 getValue(I.getArgOperand(0)), Flags));
7285 return;
7286 }
7287 case Intrinsic::atan2:
7288 setValue(&I, DAG.getNode(ISD::FATAN2, sdl,
7289 getValue(I.getArgOperand(0)).getValueType(),
7290 getValue(I.getArgOperand(0)),
7291 getValue(I.getArgOperand(1)), Flags));
7292 return;
7293 case Intrinsic::lround:
7294 case Intrinsic::llround:
7295 case Intrinsic::lrint:
7296 case Intrinsic::llrint: {
7297 unsigned Opcode;
7298 // clang-format off
7299 switch (Intrinsic) {
7300 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7301 case Intrinsic::lround: Opcode = ISD::LROUND; break;
7302 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
7303 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
7304 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
7305 }
7306 // clang-format on
7307
7308 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7309 setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
7310 getValue(I.getArgOperand(0))));
7311 return;
7312 }
7313 case Intrinsic::minnum:
7314 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
7315 getValue(I.getArgOperand(0)).getValueType(),
7316 getValue(I.getArgOperand(0)),
7317 getValue(I.getArgOperand(1)), Flags));
7318 return;
7319 case Intrinsic::maxnum:
7320 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
7321 getValue(I.getArgOperand(0)).getValueType(),
7322 getValue(I.getArgOperand(0)),
7323 getValue(I.getArgOperand(1)), Flags));
7324 return;
7325 case Intrinsic::minimum:
7326 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
7327 getValue(I.getArgOperand(0)).getValueType(),
7328 getValue(I.getArgOperand(0)),
7329 getValue(I.getArgOperand(1)), Flags));
7330 return;
7331 case Intrinsic::maximum:
7332 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
7333 getValue(I.getArgOperand(0)).getValueType(),
7334 getValue(I.getArgOperand(0)),
7335 getValue(I.getArgOperand(1)), Flags));
7336 return;
7337 case Intrinsic::minimumnum:
7338 setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
7339 getValue(I.getArgOperand(0)).getValueType(),
7340 getValue(I.getArgOperand(0)),
7341 getValue(I.getArgOperand(1)), Flags));
7342 return;
7343 case Intrinsic::maximumnum:
7344 setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
7345 getValue(I.getArgOperand(0)).getValueType(),
7346 getValue(I.getArgOperand(0)),
7347 getValue(I.getArgOperand(1)), Flags));
7348 return;
7349 case Intrinsic::copysign:
7350 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
7351 getValue(I.getArgOperand(0)).getValueType(),
7352 getValue(I.getArgOperand(0)),
7353 getValue(I.getArgOperand(1)), Flags));
7354 return;
7355 case Intrinsic::ldexp:
7356 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
7357 getValue(I.getArgOperand(0)).getValueType(),
7358 getValue(I.getArgOperand(0)),
7359 getValue(I.getArgOperand(1)), Flags));
7360 return;
7361 case Intrinsic::modf:
7362 case Intrinsic::sincos:
7363 case Intrinsic::sincospi:
7364 case Intrinsic::frexp: {
7365 unsigned Opcode;
7366 switch (Intrinsic) {
7367 default:
7368 llvm_unreachable("unexpected intrinsic");
7369 case Intrinsic::sincos:
7370 Opcode = ISD::FSINCOS;
7371 break;
7372 case Intrinsic::sincospi:
7373 Opcode = ISD::FSINCOSPI;
7374 break;
7375 case Intrinsic::modf:
7376 Opcode = ISD::FMODF;
7377 break;
7378 case Intrinsic::frexp:
7379 Opcode = ISD::FFREXP;
7380 break;
7381 }
7382 SmallVector<EVT, 2> ValueVTs;
7383 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
7384 SDVTList VTs = DAG.getVTList(ValueVTs);
7385 setValue(
7386 &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags));
7387 return;
7388 }
7389 case Intrinsic::arithmetic_fence: {
7390 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
7391 getValue(I.getArgOperand(0)).getValueType(),
7392 getValue(I.getArgOperand(0)), Flags));
7393 return;
7394 }
7395 case Intrinsic::fma:
7396 setValue(&I, DAG.getNode(
7397 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
7398 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
7399 getValue(I.getArgOperand(2)), Flags));
7400 return;
7401#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
7402 case Intrinsic::INTRINSIC:
7403#include "llvm/IR/ConstrainedOps.def"
7404 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
7405 return;
7406#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7407#include "llvm/IR/VPIntrinsics.def"
7408 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
7409 return;
7410 case Intrinsic::fptrunc_round: {
7411 // Get the last argument, the metadata and convert it to an integer in the
7412 // call
7413 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7414 std::optional<RoundingMode> RoundMode =
7415 convertStrToRoundingMode(cast<MDString>(MD)->getString());
7416
7417 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7418
7419 // Propagate fast-math-flags from IR to node(s).
7420 SDNodeFlags Flags;
7421 Flags.copyFMF(*cast<FPMathOperator>(&I));
7422 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7423
7425 Result = DAG.getNode(
7426 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
7427 DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
7428 setValue(&I, Result);
7429
7430 return;
7431 }
7432 case Intrinsic::fmuladd: {
7433 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7434 if (TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7435 setValue(&I, DAG.getNode(ISD::FMA, sdl,
7436 getValue(I.getArgOperand(0)).getValueType(),
7437 getValue(I.getArgOperand(0)),
7438 getValue(I.getArgOperand(1)),
7439 getValue(I.getArgOperand(2)), Flags));
7440 } else if (TLI.isOperationLegalOrCustom(ISD::FMULADD, VT)) {
7441 // TODO: Support splitting the vector.
7442 setValue(&I, DAG.getNode(ISD::FMULADD, sdl,
7443 getValue(I.getArgOperand(0)).getValueType(),
7444 getValue(I.getArgOperand(0)),
7445 getValue(I.getArgOperand(1)),
7446 getValue(I.getArgOperand(2)), Flags));
7447 } else {
7448 // TODO: Intrinsic calls should have fast-math-flags.
7449 SDValue Mul = DAG.getNode(
7450 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
7451 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
7452 SDValue Add = DAG.getNode(ISD::FADD, sdl,
7453 getValue(I.getArgOperand(0)).getValueType(),
7454 Mul, getValue(I.getArgOperand(2)), Flags);
7455 setValue(&I, Add);
7456 }
7457 return;
7458 }
7459 case Intrinsic::fptosi_sat: {
7460 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7461 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7462 getValue(I.getArgOperand(0)),
7463 DAG.getValueType(VT.getScalarType())));
7464 return;
7465 }
7466 case Intrinsic::fptoui_sat: {
7467 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7468 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7469 getValue(I.getArgOperand(0)),
7470 DAG.getValueType(VT.getScalarType())));
7471 return;
7472 }
7473 case Intrinsic::convert_from_arbitrary_fp: {
7474 // Extract format metadata and convert to semantics enum.
7475 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7476 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7477 StringRef FormatStr = cast<MDString>(MD)->getString();
7478 const fltSemantics *SrcSem =
7480 if (!SrcSem) {
7481 DAG.getContext()->emitError(
7482 "convert_from_arbitrary_fp: not implemented format '" + FormatStr +
7483 "'");
7484 setValue(&I, DAG.getPOISON(DstVT));
7485 return;
7486 }
7488
7489 SDValue IntVal = getValue(I.getArgOperand(0));
7490
7491 // Emit ISD::CONVERT_FROM_ARBITRARY_FP node.
7492 SDValue SemConst =
7493 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7494 setValue(&I, DAG.getNode(ISD::CONVERT_FROM_ARBITRARY_FP, sdl, DstVT, IntVal,
7495 SemConst));
7496 return;
7497 }
7498 case Intrinsic::convert_to_arbitrary_fp: {
7499 // Extract format metadata and convert to semantics enum.
7500 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7501 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7502 StringRef FormatStr = cast<MDString>(MD)->getString();
7503 const fltSemantics *DstSem =
7505 if (!DstSem) {
7506 DAG.getContext()->emitError(
7507 "convert_to_arbitrary_fp: not implemented format '" + FormatStr +
7508 "'");
7509 setValue(&I, DAG.getPOISON(DstVT));
7510 return;
7511 }
7513
7514 Metadata *RoundMD =
7515 cast<MetadataAsValue>(I.getArgOperand(2))->getMetadata();
7516 StringRef RoundStr = cast<MDString>(RoundMD)->getString();
7517 std::optional<RoundingMode> RoundMode = convertStrToRoundingMode(RoundStr);
7518 assert(RoundMode && *RoundMode != RoundingMode::Dynamic &&
7519 "Dynamic rounding mode should have been rejected by the verifier");
7520
7521 uint64_t Saturate =
7522 cast<ConstantInt>(I.getArgOperand(3))->getZExtValue() ? 1 : 0;
7523
7524 SDValue FloatVal = getValue(I.getArgOperand(0));
7525
7526 SDValue SemConst =
7527 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7528 SDValue RoundConst =
7529 DAG.getTargetConstant(static_cast<int>(*RoundMode), sdl, MVT::i32);
7530 SDValue SatConst = DAG.getTargetConstant(Saturate, sdl, MVT::i32);
7531 setValue(&I, DAG.getNode(ISD::CONVERT_TO_ARBITRARY_FP, sdl, DstVT, FloatVal,
7532 SemConst, RoundConst, SatConst));
7533 return;
7534 }
7535 case Intrinsic::set_rounding:
7536 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7537 {getRoot(), getValue(I.getArgOperand(0))});
7538 setValue(&I, Res);
7539 DAG.setRoot(Res.getValue(0));
7540 return;
7541 case Intrinsic::is_fpclass: {
7542 const DataLayout DLayout = DAG.getDataLayout();
7543 EVT DestVT = TLI.getValueType(DLayout, I.getType());
7544 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7545 FPClassTest Test = static_cast<FPClassTest>(
7546 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7547 MachineFunction &MF = DAG.getMachineFunction();
7548 const Function &F = MF.getFunction();
7549 SDValue Op = getValue(I.getArgOperand(0));
7550 SDNodeFlags Flags;
7551 Flags.setNoFPExcept(
7552 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7553 // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7554 // expansion can use illegal types. Making expansion early allows
7555 // legalizing these types prior to selection.
7556 if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7558 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7559 setValue(&I, Result);
7560 return;
7561 }
7562
7563 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7564 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7565 setValue(&I, V);
7566 return;
7567 }
7568 case Intrinsic::get_fpenv: {
7569 const DataLayout DLayout = DAG.getDataLayout();
7570 EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7571 Align TempAlign = DAG.getEVTAlign(EnvVT);
7572 SDValue Chain = getRoot();
7573 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7574 // and temporary storage in stack.
7576 Res = DAG.getNode(
7577 ISD::GET_FPENV, sdl,
7578 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7579 MVT::Other),
7580 Chain);
7581 } else {
7582 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7583 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7584 auto MPI =
7585 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7586 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7588 TempAlign);
7589 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7590 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7591 }
7592 setValue(&I, Res);
7593 DAG.setRoot(Res.getValue(1));
7594 return;
7595 }
7596 case Intrinsic::set_fpenv: {
7597 SDValue Env = getValue(I.getArgOperand(0));
7598 EVT EnvVT = Env.getValueType();
7599 Align TempAlign = DAG.getEVTAlign(EnvVT);
7600 SDValue Chain = getRoot();
7601 // If SET_FPENV is custom or legal, use it. Otherwise use loading
7602 // environment from memory.
7604 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7605 } else {
7606 // Allocate space in stack, copy environment bits into it and use this
7607 // memory in SET_FPENV_MEM.
7608 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7609 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7610 auto MPI =
7611 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7612 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7614 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7616 TempAlign);
7617 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7618 }
7619 DAG.setRoot(Chain);
7620 return;
7621 }
7622 case Intrinsic::reset_fpenv:
7623 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7624 return;
7625 case Intrinsic::get_fpmode:
7626 Res = DAG.getNode(
7627 ISD::GET_FPMODE, sdl,
7628 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7629 MVT::Other),
7630 DAG.getRoot());
7631 setValue(&I, Res);
7632 DAG.setRoot(Res.getValue(1));
7633 return;
7634 case Intrinsic::set_fpmode:
7635 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7636 getValue(I.getArgOperand(0)));
7637 DAG.setRoot(Res);
7638 return;
7639 case Intrinsic::reset_fpmode: {
7640 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7641 DAG.setRoot(Res);
7642 return;
7643 }
7644 case Intrinsic::pcmarker: {
7645 SDValue Tmp = getValue(I.getArgOperand(0));
7646 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7647 return;
7648 }
7649 case Intrinsic::readcyclecounter: {
7650 SDValue Op = getRoot();
7651 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7652 DAG.getVTList(MVT::i64, MVT::Other), Op);
7653 setValue(&I, Res);
7654 DAG.setRoot(Res.getValue(1));
7655 return;
7656 }
7657 case Intrinsic::readsteadycounter: {
7658 SDValue Op = getRoot();
7659 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7660 DAG.getVTList(MVT::i64, MVT::Other), Op);
7661 setValue(&I, Res);
7662 DAG.setRoot(Res.getValue(1));
7663 return;
7664 }
7665 case Intrinsic::bitreverse:
7666 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7667 getValue(I.getArgOperand(0)).getValueType(),
7668 getValue(I.getArgOperand(0))));
7669 return;
7670 case Intrinsic::bswap:
7671 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7672 getValue(I.getArgOperand(0)).getValueType(),
7673 getValue(I.getArgOperand(0))));
7674 return;
7675 case Intrinsic::cttz: {
7676 SDValue Arg = getValue(I.getArgOperand(0));
7677 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7678 EVT Ty = Arg.getValueType();
7679 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_POISON,
7680 sdl, Ty, Arg));
7681 return;
7682 }
7683 case Intrinsic::ctlz: {
7684 SDValue Arg = getValue(I.getArgOperand(0));
7685 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7686 EVT Ty = Arg.getValueType();
7687 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_POISON,
7688 sdl, Ty, Arg));
7689 return;
7690 }
7691 case Intrinsic::ctpop: {
7692 SDValue Arg = getValue(I.getArgOperand(0));
7693 EVT Ty = Arg.getValueType();
7694 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7695 return;
7696 }
7697 case Intrinsic::fshl:
7698 case Intrinsic::fshr: {
7699 bool IsFSHL = Intrinsic == Intrinsic::fshl;
7700 SDValue X = getValue(I.getArgOperand(0));
7701 SDValue Y = getValue(I.getArgOperand(1));
7702 SDValue Z = getValue(I.getArgOperand(2));
7703 EVT VT = X.getValueType();
7704
7705 if (X == Y) {
7706 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7707 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7708 } else {
7709 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7710 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7711 }
7712 return;
7713 }
7714 case Intrinsic::clmul: {
7715 SDValue X = getValue(I.getArgOperand(0));
7716 SDValue Y = getValue(I.getArgOperand(1));
7717 setValue(&I, DAG.getNode(ISD::CLMUL, sdl, X.getValueType(), X, Y));
7718 return;
7719 }
7720 case Intrinsic::pext: {
7721 SDValue X = getValue(I.getArgOperand(0));
7722 SDValue Y = getValue(I.getArgOperand(1));
7723 setValue(&I, DAG.getNode(ISD::PEXT, sdl, X.getValueType(), X, Y));
7724 return;
7725 }
7726 case Intrinsic::pdep: {
7727 SDValue X = getValue(I.getArgOperand(0));
7728 SDValue Y = getValue(I.getArgOperand(1));
7729 setValue(&I, DAG.getNode(ISD::PDEP, sdl, X.getValueType(), X, Y));
7730 return;
7731 }
7732 case Intrinsic::smulh:
7733 case Intrinsic::umulh: {
7734 auto Opc = Intrinsic == Intrinsic::smulh ? ISD::MULHS : ISD::MULHU;
7735 SDValue X = getValue(I.getArgOperand(0));
7736 SDValue Y = getValue(I.getArgOperand(1));
7737 setValue(&I, DAG.getNode(Opc, sdl, X.getValueType(), X, Y));
7738 return;
7739 }
7740 case Intrinsic::sadd_sat: {
7741 SDValue Op1 = getValue(I.getArgOperand(0));
7742 SDValue Op2 = getValue(I.getArgOperand(1));
7743 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7744 return;
7745 }
7746 case Intrinsic::uadd_sat: {
7747 SDValue Op1 = getValue(I.getArgOperand(0));
7748 SDValue Op2 = getValue(I.getArgOperand(1));
7749 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7750 return;
7751 }
7752 case Intrinsic::ssub_sat: {
7753 SDValue Op1 = getValue(I.getArgOperand(0));
7754 SDValue Op2 = getValue(I.getArgOperand(1));
7755 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7756 return;
7757 }
7758 case Intrinsic::usub_sat: {
7759 SDValue Op1 = getValue(I.getArgOperand(0));
7760 SDValue Op2 = getValue(I.getArgOperand(1));
7761 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7762 return;
7763 }
7764 case Intrinsic::sshl_sat:
7765 case Intrinsic::ushl_sat: {
7766 SDValue Op1 = getValue(I.getArgOperand(0));
7767 SDValue Op2 = getValue(I.getArgOperand(1));
7768
7769 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
7770 Op1.getValueType(), DAG.getDataLayout());
7771
7772 // Coerce the shift amount to the right type if we can. This exposes the
7773 // truncate or zext to optimization early.
7774 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
7775 assert(ShiftTy.getSizeInBits() >=
7777 "Unexpected shift type");
7778 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
7779 }
7780
7781 unsigned Opc =
7782 Intrinsic == Intrinsic::sshl_sat ? ISD::SSHLSAT : ISD::USHLSAT;
7783 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1, Op2));
7784 return;
7785 }
7786 case Intrinsic::smul_fix:
7787 case Intrinsic::umul_fix:
7788 case Intrinsic::smul_fix_sat:
7789 case Intrinsic::umul_fix_sat: {
7790 SDValue Op1 = getValue(I.getArgOperand(0));
7791 SDValue Op2 = getValue(I.getArgOperand(1));
7792 SDValue Op3 = getValue(I.getArgOperand(2));
7793 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7794 Op1.getValueType(), Op1, Op2, Op3));
7795 return;
7796 }
7797 case Intrinsic::sdiv_fix:
7798 case Intrinsic::udiv_fix:
7799 case Intrinsic::sdiv_fix_sat:
7800 case Intrinsic::udiv_fix_sat: {
7801 SDValue Op1 = getValue(I.getArgOperand(0));
7802 SDValue Op2 = getValue(I.getArgOperand(1));
7803 SDValue Op3 = getValue(I.getArgOperand(2));
7805 Op1, Op2, Op3, DAG, TLI));
7806 return;
7807 }
7808 case Intrinsic::smax: {
7809 SDValue Op1 = getValue(I.getArgOperand(0));
7810 SDValue Op2 = getValue(I.getArgOperand(1));
7811 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7812 return;
7813 }
7814 case Intrinsic::smin: {
7815 SDValue Op1 = getValue(I.getArgOperand(0));
7816 SDValue Op2 = getValue(I.getArgOperand(1));
7817 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7818 return;
7819 }
7820 case Intrinsic::umax: {
7821 SDValue Op1 = getValue(I.getArgOperand(0));
7822 SDValue Op2 = getValue(I.getArgOperand(1));
7823 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7824 return;
7825 }
7826 case Intrinsic::umin: {
7827 SDValue Op1 = getValue(I.getArgOperand(0));
7828 SDValue Op2 = getValue(I.getArgOperand(1));
7829 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7830 return;
7831 }
7832 case Intrinsic::abs: {
7833 SDValue Op1 = getValue(I.getArgOperand(0));
7834 bool IntMinIsPoison = cast<ConstantInt>(I.getArgOperand(1))->isOne();
7835 unsigned Opc = IntMinIsPoison ? ISD::ABS_MIN_POISON : ISD::ABS;
7836 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1));
7837 return;
7838 }
7839 case Intrinsic::scmp: {
7840 SDValue Op1 = getValue(I.getArgOperand(0));
7841 SDValue Op2 = getValue(I.getArgOperand(1));
7842 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7843 setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7844 break;
7845 }
7846 case Intrinsic::ucmp: {
7847 SDValue Op1 = getValue(I.getArgOperand(0));
7848 SDValue Op2 = getValue(I.getArgOperand(1));
7849 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7850 setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7851 break;
7852 }
7853 case Intrinsic::stackaddress:
7854 case Intrinsic::stacksave: {
7855 unsigned SDOpcode = Intrinsic == Intrinsic::stackaddress ? ISD::STACKADDRESS
7857 SDValue Op = getRoot();
7858 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7859 Res = DAG.getNode(SDOpcode, sdl, DAG.getVTList(VT, MVT::Other), Op);
7860 setValue(&I, Res);
7861 DAG.setRoot(Res.getValue(1));
7862 return;
7863 }
7864 case Intrinsic::stackrestore:
7865 Res = getValue(I.getArgOperand(0));
7866 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7867 return;
7868 case Intrinsic::get_dynamic_area_offset: {
7869 SDValue Op = getRoot();
7870 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7871 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7872 Op);
7873 DAG.setRoot(Op);
7874 setValue(&I, Res);
7875 return;
7876 }
7877 case Intrinsic::stackguard: {
7878 MachineFunction &MF = DAG.getMachineFunction();
7879 const Module &M = *MF.getFunction().getParent();
7880 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7881 SDValue Chain = getRoot();
7882 if (TLI.useLoadStackGuardNode(M)) {
7883 Res = getLoadStackGuard(DAG, sdl, Chain);
7884 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7885 } else {
7886 const Value *Global = TLI.getSDagStackGuard(M, DAG.getLibcalls());
7887 if (!Global) {
7888 LLVMContext &Ctx = *DAG.getContext();
7889 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
7890 setValue(&I, DAG.getPOISON(PtrTy));
7891 return;
7892 }
7893
7894 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7895 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7896 MachinePointerInfo(Global, 0), Align,
7898 }
7899 // Mix the cookie with FP if enabled. Skip if using LOAD_STACK_GUARD
7900 // with post-RA mixing (AArch64 MSVCRT), as the mixing will be done during
7901 // post-RA expansion of LOAD_STACK_GUARD.
7903 Res = TLI.emitStackGuardMixFP(DAG, Res, sdl);
7904 DAG.setRoot(Chain);
7905 setValue(&I, Res);
7906 return;
7907 }
7908 case Intrinsic::stackprotector: {
7909 // Emit code into the DAG to store the stack guard onto the stack.
7910 MachineFunction &MF = DAG.getMachineFunction();
7911 MachineFrameInfo &MFI = MF.getFrameInfo();
7912 const Module &M = *MF.getFunction().getParent();
7913 SDValue Src, Chain = getRoot();
7914
7916 Src = getLoadStackGuard(DAG, sdl, Chain);
7917 else
7918 Src = getValue(I.getArgOperand(0)); // The guard's value.
7919
7920 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7921
7922 int FI = FuncInfo.StaticAllocaMap[Slot];
7923 MFI.setStackProtectorIndex(FI);
7924 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7925
7926 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7927
7928 // Store the stack protector onto the stack.
7929 Res = DAG.getStore(
7930 Chain, sdl, Src, FIN,
7931 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7932 MaybeAlign(), MachineMemOperand::MOVolatile);
7933 setValue(&I, Res);
7934 DAG.setRoot(Res);
7935 return;
7936 }
7937 case Intrinsic::objectsize:
7938 llvm_unreachable("llvm.objectsize.* should have been lowered already");
7939
7940 case Intrinsic::is_constant:
7941 llvm_unreachable("llvm.is.constant.* should have been lowered already");
7942
7943 case Intrinsic::annotation:
7944 case Intrinsic::ptr_annotation:
7945 case Intrinsic::launder_invariant_group:
7946 // Drop the intrinsic, but forward the value
7947 setValue(&I, getValue(I.getOperand(0)));
7948 return;
7949
7950 case Intrinsic::type_test:
7951 case Intrinsic::public_type_test:
7952 case Intrinsic::type_checked_load:
7953 case Intrinsic::type_checked_load_relative: {
7954 // These intrinsics are expected to be lowered by the LowerTypeTests pass
7955 // before code generation. Surviving until here usually indicates a
7956 // misconfiguration, for instance when devirtualization is enabled but LTO
7957 // does not actually run.
7958 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
7959 *I.getFunction(),
7960 Intrinsic::getBaseName(Intrinsic) +
7961 " intrinsic must be lowered by the LowerTypeTests pass "
7962 "before code generation",
7963 sdl.getDebugLoc()));
7964
7965 // Lower the result to poison so that compilation can continue and collect
7966 // any further diagnostics.
7967 setValueToPoison(&I, sdl);
7968 return;
7969 }
7970
7971 case Intrinsic::assume:
7972 case Intrinsic::experimental_noalias_scope_decl:
7973 case Intrinsic::var_annotation:
7974 case Intrinsic::sideeffect:
7975 // Discard annotate attributes, noalias scope declarations, assumptions, and
7976 // artificial side-effects.
7977 return;
7978
7979 case Intrinsic::codeview_annotation: {
7980 // Emit a label associated with this metadata.
7981 MachineFunction &MF = DAG.getMachineFunction();
7982 MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7983 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7984 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7985 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7986 DAG.setRoot(Res);
7987 return;
7988 }
7989
7990 case Intrinsic::init_trampoline: {
7991 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7992
7993 SDValue Ops[6];
7994 Ops[0] = getRoot();
7995 Ops[1] = getValue(I.getArgOperand(0));
7996 Ops[2] = getValue(I.getArgOperand(1));
7997 Ops[3] = getValue(I.getArgOperand(2));
7998 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7999 Ops[5] = DAG.getSrcValue(F);
8000
8001 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
8002
8003 DAG.setRoot(Res);
8004 return;
8005 }
8006 case Intrinsic::adjust_trampoline:
8007 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
8008 TLI.getPointerTy(DAG.getDataLayout()),
8009 getValue(I.getArgOperand(0))));
8010 return;
8011 case Intrinsic::gcroot: {
8012 assert(DAG.getMachineFunction().getFunction().hasGC() &&
8013 "only valid in functions with gc specified, enforced by Verifier");
8014 assert(GFI && "implied by previous");
8015 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
8016 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
8017
8018 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
8019 GFI->addStackRoot(FI->getIndex(), TypeMap);
8020 return;
8021 }
8022 case Intrinsic::gcread:
8023 case Intrinsic::gcwrite:
8024 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
8025 case Intrinsic::get_rounding:
8026 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
8027 setValue(&I, Res);
8028 DAG.setRoot(Res.getValue(1));
8029 return;
8030
8031 case Intrinsic::expect:
8032 case Intrinsic::expect_with_probability:
8033 // Just replace __builtin_expect(exp, c) and
8034 // __builtin_expect_with_probability(exp, c, p) with EXP.
8035 setValue(&I, getValue(I.getArgOperand(0)));
8036 return;
8037
8038 case Intrinsic::ubsantrap:
8039 case Intrinsic::debugtrap:
8040 case Intrinsic::trap: {
8041 StringRef TrapFuncName =
8042 I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
8043 if (TrapFuncName.empty()) {
8044 switch (Intrinsic) {
8045 case Intrinsic::trap:
8046 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
8047 break;
8048 case Intrinsic::debugtrap:
8049 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
8050 break;
8051 case Intrinsic::ubsantrap:
8052 DAG.setRoot(DAG.getNode(
8053 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
8054 DAG.getTargetConstant(
8055 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
8056 MVT::i32)));
8057 break;
8058 default: llvm_unreachable("unknown trap intrinsic");
8059 }
8060 DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
8061 I.hasFnAttr(Attribute::NoMerge));
8062 return;
8063 }
8065 if (Intrinsic == Intrinsic::ubsantrap) {
8066 Value *Arg = I.getArgOperand(0);
8067 Args.emplace_back(Arg, getValue(Arg),
8068 LibInfo->getExtAttrForI8Param(/*Signed=*/false));
8069 }
8070
8071 TargetLowering::CallLoweringInfo CLI(DAG);
8072 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
8073 CallingConv::C, I.getType(),
8074 DAG.getExternalSymbol(TrapFuncName.data(),
8075 TLI.getPointerTy(DAG.getDataLayout())),
8076 std::move(Args));
8077 CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
8078 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8079 DAG.setRoot(Result.second);
8080 return;
8081 }
8082
8083 case Intrinsic::allow_runtime_check:
8084 case Intrinsic::allow_ubsan_check:
8085 setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
8086 return;
8087
8088 case Intrinsic::uadd_with_overflow:
8089 case Intrinsic::sadd_with_overflow:
8090 case Intrinsic::usub_with_overflow:
8091 case Intrinsic::ssub_with_overflow:
8092 case Intrinsic::umul_with_overflow:
8093 case Intrinsic::smul_with_overflow: {
8095 switch (Intrinsic) {
8096 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8097 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
8098 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
8099 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
8100 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
8101 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
8102 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
8103 }
8104 SDValue Op1 = getValue(I.getArgOperand(0));
8105 SDValue Op2 = getValue(I.getArgOperand(1));
8106
8107 EVT ResultVT = Op1.getValueType();
8108 EVT OverflowVT = ResultVT.changeElementType(*Context, MVT::i1);
8109
8110 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
8111 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
8112 return;
8113 }
8114 case Intrinsic::prefetch: {
8115 SDValue Ops[5];
8116 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
8118 Ops[0] = DAG.getRoot();
8119 Ops[1] = getValue(I.getArgOperand(0));
8120 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
8121 MVT::i32);
8122 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
8123 MVT::i32);
8124 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
8125 MVT::i32);
8126 SDValue Result = DAG.getMemIntrinsicNode(
8127 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
8128 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
8129 /* align */ std::nullopt, Flags);
8130
8131 // Chain the prefetch in parallel with any pending loads, to stay out of
8132 // the way of later optimizations.
8133 PendingLoads.push_back(Result);
8134 Result = getRoot();
8135 DAG.setRoot(Result);
8136 return;
8137 }
8138 case Intrinsic::lifetime_start:
8139 case Intrinsic::lifetime_end: {
8140 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
8141 // Stack coloring is not enabled in O0, discard region information.
8142 if (TM.getOptLevel() == CodeGenOptLevel::None)
8143 return;
8144
8145 const AllocaInst *LifetimeObject = dyn_cast<AllocaInst>(I.getArgOperand(0));
8146 if (!LifetimeObject)
8147 return;
8148
8149 // First check that the Alloca is static, otherwise it won't have a
8150 // valid frame index.
8151 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
8152 if (SI == FuncInfo.StaticAllocaMap.end())
8153 return;
8154
8155 const int FrameIndex = SI->second;
8156 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex);
8157 DAG.setRoot(Res);
8158 return;
8159 }
8160 case Intrinsic::pseudoprobe: {
8161 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
8162 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
8163 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
8164 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
8165 DAG.setRoot(Res);
8166 return;
8167 }
8168 case Intrinsic::invariant_start:
8169 // Discard region information.
8170 setValue(&I,
8171 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
8172 return;
8173 case Intrinsic::invariant_end:
8174 // Discard region information.
8175 return;
8176 case Intrinsic::clear_cache: {
8177 SDValue InputChain = DAG.getRoot();
8178 SDValue StartVal = getValue(I.getArgOperand(0));
8179 SDValue EndVal = getValue(I.getArgOperand(1));
8180 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
8181 {InputChain, StartVal, EndVal});
8182 setValue(&I, Res);
8183 DAG.setRoot(Res);
8184 return;
8185 }
8186 case Intrinsic::donothing:
8187 case Intrinsic::seh_try_begin:
8188 case Intrinsic::seh_scope_begin:
8189 case Intrinsic::seh_try_end:
8190 case Intrinsic::seh_scope_end:
8191 // ignore
8192 return;
8193 case Intrinsic::experimental_stackmap:
8194 visitStackmap(I);
8195 return;
8196 case Intrinsic::experimental_patchpoint_void:
8197 case Intrinsic::experimental_patchpoint:
8198 visitPatchpoint(I);
8199 return;
8200 case Intrinsic::experimental_gc_statepoint:
8202 return;
8203 case Intrinsic::experimental_gc_result:
8204 visitGCResult(cast<GCResultInst>(I));
8205 return;
8206 case Intrinsic::experimental_gc_relocate:
8207 visitGCRelocate(cast<GCRelocateInst>(I));
8208 return;
8209 case Intrinsic::instrprof_cover:
8210 llvm_unreachable("instrprof failed to lower a cover");
8211 case Intrinsic::instrprof_increment:
8212 llvm_unreachable("instrprof failed to lower an increment");
8213 case Intrinsic::instrprof_timestamp:
8214 llvm_unreachable("instrprof failed to lower a timestamp");
8215 case Intrinsic::instrprof_value_profile:
8216 llvm_unreachable("instrprof failed to lower a value profiling call");
8217 case Intrinsic::instrprof_mcdc_parameters:
8218 llvm_unreachable("instrprof failed to lower mcdc parameters");
8219 case Intrinsic::instrprof_mcdc_tvbitmap_update:
8220 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
8221 case Intrinsic::localescape: {
8222 MachineFunction &MF = DAG.getMachineFunction();
8223 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
8224
8225 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
8226 // is the same on all targets.
8227 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
8228 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
8229 if (isa<ConstantPointerNull>(Arg))
8230 continue; // Skip null pointers. They represent a hole in index space.
8231 AllocaInst *Slot = cast<AllocaInst>(Arg);
8232 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
8233 "can only escape static allocas");
8234 int FI = FuncInfo.StaticAllocaMap[Slot];
8235 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8237 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
8238 TII->get(TargetOpcode::LOCAL_ESCAPE))
8239 .addSym(FrameAllocSym)
8240 .addFrameIndex(FI);
8241 }
8242
8243 return;
8244 }
8245
8246 case Intrinsic::localrecover: {
8247 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
8248 MachineFunction &MF = DAG.getMachineFunction();
8249
8250 // Get the symbol that defines the frame offset.
8251 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
8252 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
8253 unsigned IdxVal =
8254 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
8255 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8257
8258 Value *FP = I.getArgOperand(1);
8259 SDValue FPVal = getValue(FP);
8260 EVT PtrVT = FPVal.getValueType();
8261
8262 // Create a MCSymbol for the label to avoid any target lowering
8263 // that would make this PC relative.
8264 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
8265 SDValue OffsetVal =
8266 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
8267
8268 // Add the offset to the FP.
8269 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
8270 setValue(&I, Add);
8271
8272 return;
8273 }
8274
8275 case Intrinsic::fake_use: {
8276 Value *V = I.getArgOperand(0);
8277 SDValue Ops[2];
8278 // For Values not declared or previously used in this basic block, the
8279 // NodeMap will not have an entry, and `getValue` will assert if V has no
8280 // valid register value.
8281 auto FakeUseValue = [&]() -> SDValue {
8282 SDValue &N = NodeMap[V];
8283 if (N.getNode())
8284 return N;
8285
8286 // If there's a virtual register allocated and initialized for this
8287 // value, use it.
8288 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
8289 return copyFromReg;
8290 // FIXME: Do we want to preserve constants? It seems pointless.
8291 if (isa<Constant>(V))
8292 return getValue(V);
8293 return SDValue();
8294 }();
8295 if (!FakeUseValue || FakeUseValue.isUndef())
8296 return;
8297 Ops[0] = getRoot();
8298 Ops[1] = FakeUseValue;
8299 // Also, do not translate a fake use with an undef operand, or any other
8300 // empty SDValues.
8301 if (!Ops[1] || Ops[1].isUndef())
8302 return;
8303 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
8304 return;
8305 }
8306
8307 case Intrinsic::reloc_none: {
8308 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
8309 StringRef SymbolName = cast<MDString>(MD)->getString();
8310 SDValue Ops[2] = {
8311 getRoot(),
8312 DAG.getTargetExternalSymbol(
8313 SymbolName.data(), TLI.getProgramPointerTy(DAG.getDataLayout()))};
8314 DAG.setRoot(DAG.getNode(ISD::RELOC_NONE, sdl, MVT::Other, Ops));
8315 return;
8316 }
8317
8318 case Intrinsic::cond_loop: {
8319 SDValue InputChain = DAG.getRoot();
8320 SDValue P = getValue(I.getArgOperand(0));
8321 Res = DAG.getNode(ISD::COND_LOOP, sdl, DAG.getVTList(MVT::Other),
8322 {InputChain, P});
8323 setValue(&I, Res);
8324 DAG.setRoot(Res);
8325 return;
8326 }
8327
8328 case Intrinsic::eh_exceptionpointer:
8329 case Intrinsic::eh_exceptioncode: {
8330 // Get the exception pointer vreg, copy from it, and resize it to fit.
8331 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
8332 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
8333 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
8334 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
8335 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
8336 if (Intrinsic == Intrinsic::eh_exceptioncode)
8337 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
8338 setValue(&I, N);
8339 return;
8340 }
8341 case Intrinsic::xray_customevent: {
8342 // Here we want to make sure that the intrinsic behaves as if it has a
8343 // specific calling convention.
8344 const auto &Triple = DAG.getTarget().getTargetTriple();
8345 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8346 Triple.getArch() != Triple::hexagon)
8347 return;
8348
8350
8351 // We want to say that we always want the arguments in registers.
8352 SDValue LogEntryVal = getValue(I.getArgOperand(0));
8353 SDValue StrSizeVal = getValue(I.getArgOperand(1));
8354 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8355 SDValue Chain = getRoot();
8356 Ops.push_back(LogEntryVal);
8357 Ops.push_back(StrSizeVal);
8358 Ops.push_back(Chain);
8359
8360 // We need to enforce the calling convention for the callsite, so that
8361 // argument ordering is enforced correctly, and that register allocation can
8362 // see that some registers may be assumed clobbered and have to preserve
8363 // them across calls to the intrinsic.
8364 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
8365 sdl, NodeTys, Ops);
8366 SDValue patchableNode = SDValue(MN, 0);
8367 DAG.setRoot(patchableNode);
8368 setValue(&I, patchableNode);
8369 return;
8370 }
8371 case Intrinsic::xray_typedevent: {
8372 // Here we want to make sure that the intrinsic behaves as if it has a
8373 // specific calling convention.
8374 const auto &Triple = DAG.getTarget().getTargetTriple();
8375 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8376 Triple.getArch() != Triple::hexagon)
8377 return;
8378
8380
8381 // We want to say that we always want the arguments in registers.
8382 // It's unclear to me how manipulating the selection DAG here forces callers
8383 // to provide arguments in registers instead of on the stack.
8384 SDValue LogTypeId = getValue(I.getArgOperand(0));
8385 SDValue LogEntryVal = getValue(I.getArgOperand(1));
8386 SDValue StrSizeVal = getValue(I.getArgOperand(2));
8387 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8388 SDValue Chain = getRoot();
8389 Ops.push_back(LogTypeId);
8390 Ops.push_back(LogEntryVal);
8391 Ops.push_back(StrSizeVal);
8392 Ops.push_back(Chain);
8393
8394 // We need to enforce the calling convention for the callsite, so that
8395 // argument ordering is enforced correctly, and that register allocation can
8396 // see that some registers may be assumed clobbered and have to preserve
8397 // them across calls to the intrinsic.
8398 MachineSDNode *MN = DAG.getMachineNode(
8399 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
8400 SDValue patchableNode = SDValue(MN, 0);
8401 DAG.setRoot(patchableNode);
8402 setValue(&I, patchableNode);
8403 return;
8404 }
8405 case Intrinsic::experimental_deoptimize:
8407 return;
8408 case Intrinsic::stepvector:
8409 visitStepVector(I);
8410 return;
8411 case Intrinsic::vector_reduce_fadd:
8412 case Intrinsic::vector_reduce_fmul:
8413 case Intrinsic::vector_reduce_add:
8414 case Intrinsic::vector_reduce_mul:
8415 case Intrinsic::vector_reduce_and:
8416 case Intrinsic::vector_reduce_or:
8417 case Intrinsic::vector_reduce_xor:
8418 case Intrinsic::vector_reduce_smax:
8419 case Intrinsic::vector_reduce_smin:
8420 case Intrinsic::vector_reduce_umax:
8421 case Intrinsic::vector_reduce_umin:
8422 case Intrinsic::vector_reduce_fmax:
8423 case Intrinsic::vector_reduce_fmin:
8424 case Intrinsic::vector_reduce_fmaximum:
8425 case Intrinsic::vector_reduce_fminimum:
8426 case Intrinsic::vector_reduce_fmaximumnum:
8427 case Intrinsic::vector_reduce_fminimumnum:
8428 visitVectorReduce(I, Intrinsic);
8429 return;
8430
8431 case Intrinsic::icall_branch_funnel: {
8433 Ops.push_back(getValue(I.getArgOperand(0)));
8434
8435 int64_t Offset;
8437 I.getArgOperand(1), Offset, DAG.getDataLayout()));
8438 if (!Base)
8440 "llvm.icall.branch.funnel operand must be a GlobalValue");
8441 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
8442
8443 struct BranchFunnelTarget {
8444 int64_t Offset;
8446 };
8448
8449 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
8451 I.getArgOperand(Op), Offset, DAG.getDataLayout()));
8452 if (ElemBase != Base)
8453 report_fatal_error("all llvm.icall.branch.funnel operands must refer "
8454 "to the same GlobalValue");
8455
8456 SDValue Val = getValue(I.getArgOperand(Op + 1));
8457 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
8458 if (!GA)
8460 "llvm.icall.branch.funnel operand must be a GlobalValue");
8461 Targets.push_back({Offset, DAG.getTargetGlobalAddress(
8462 GA->getGlobal(), sdl, Val.getValueType(),
8463 GA->getOffset())});
8464 }
8465 llvm::sort(Targets,
8466 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
8467 return T1.Offset < T2.Offset;
8468 });
8469
8470 for (auto &T : Targets) {
8471 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
8472 Ops.push_back(T.Target);
8473 }
8474
8475 Ops.push_back(DAG.getRoot()); // Chain
8476 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
8477 MVT::Other, Ops),
8478 0);
8479 DAG.setRoot(N);
8480 setValue(&I, N);
8481 HasTailCall = true;
8482 return;
8483 }
8484
8485 case Intrinsic::wasm_landingpad_index:
8486 // Information this intrinsic contained has been transferred to
8487 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
8488 // delete it now.
8489 return;
8490
8491 case Intrinsic::aarch64_settag:
8492 case Intrinsic::aarch64_settag_zero: {
8493 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8494 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
8496 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
8497 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
8498 ZeroMemory);
8499 DAG.setRoot(Val);
8500 setValue(&I, Val);
8501 return;
8502 }
8503 case Intrinsic::amdgcn_cs_chain: {
8504 // At this point we don't care if it's amdgpu_cs_chain or
8505 // amdgpu_cs_chain_preserve.
8507
8508 Type *RetTy = I.getType();
8509 assert(RetTy->isVoidTy() && "Should not return");
8510
8511 SDValue Callee = getValue(I.getOperand(0));
8512
8513 // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8514 // We'll also tack the value of the EXEC mask at the end.
8516 Args.reserve(3);
8517
8518 for (unsigned Idx : {2, 3, 1}) {
8519 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8520 I.getOperand(Idx)->getType());
8521 Arg.setAttributes(&I, Idx);
8522 Args.push_back(Arg);
8523 }
8524
8525 assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8526 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8527 Args[2].IsInReg = true; // EXEC should be inreg
8528
8529 // Forward the flags and any additional arguments.
8530 for (unsigned Idx = 4; Idx < I.arg_size(); ++Idx) {
8531 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8532 I.getOperand(Idx)->getType());
8533 Arg.setAttributes(&I, Idx);
8534 Args.push_back(Arg);
8535 }
8536
8537 TargetLowering::CallLoweringInfo CLI(DAG);
8538 CLI.setDebugLoc(getCurSDLoc())
8539 .setChain(getRoot())
8540 .setCallee(CC, RetTy, Callee, std::move(Args))
8541 .setNoReturn(true)
8542 .setTailCall(true)
8543 .setConvergent(I.isConvergent());
8544 CLI.CB = &I;
8545 std::pair<SDValue, SDValue> Result =
8546 lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8547 (void)Result;
8548 assert(!Result.first.getNode() && !Result.second.getNode() &&
8549 "Should've lowered as tail call");
8550
8551 HasTailCall = true;
8552 return;
8553 }
8554 case Intrinsic::amdgcn_call_whole_wave: {
8556 bool isTailCall = I.isTailCall();
8557
8558 // The first argument is the callee. Skip it when assembling the call args.
8559 for (unsigned Idx = 1; Idx < I.arg_size(); ++Idx) {
8560 TargetLowering::ArgListEntry Arg(getValue(I.getArgOperand(Idx)),
8561 I.getArgOperand(Idx)->getType());
8562 Arg.setAttributes(&I, Idx);
8563
8564 // If we have an explicit sret argument that is an Instruction, (i.e., it
8565 // might point to function-local memory), we can't meaningfully tail-call.
8566 if (Arg.IsSRet && isa<Instruction>(I.getArgOperand(Idx)))
8567 isTailCall = false;
8568
8569 Args.push_back(Arg);
8570 }
8571
8572 SDValue ConvControlToken;
8573 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8574 auto *Token = Bundle->Inputs[0].get();
8575 ConvControlToken = getValue(Token);
8576 }
8577
8578 TargetLowering::CallLoweringInfo CLI(DAG);
8579 CLI.setDebugLoc(getCurSDLoc())
8580 .setChain(getRoot())
8581 .setCallee(CallingConv::AMDGPU_Gfx_WholeWave, I.getType(),
8582 getValue(I.getArgOperand(0)), std::move(Args))
8583 .setTailCall(isTailCall && canTailCall(I))
8584 .setIsPreallocated(
8585 I.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8586 .setConvergent(I.isConvergent())
8587 .setConvergenceControlToken(ConvControlToken);
8588 CLI.CB = &I;
8589
8590 std::pair<SDValue, SDValue> Result =
8591 lowerInvokable(CLI, /*EHPadBB=*/nullptr);
8592
8593 if (Result.first.getNode())
8594 setValue(&I, Result.first);
8595 return;
8596 }
8597 case Intrinsic::ptrmask: {
8598 SDValue Ptr = getValue(I.getOperand(0));
8599 SDValue Mask = getValue(I.getOperand(1));
8600
8601 // On arm64_32, pointers are 32 bits when stored in memory, but
8602 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to
8603 // match the index type, but the pointer is 64 bits, so the mask must be
8604 // zero-extended up to 64 bits to match the pointer.
8605 EVT PtrVT =
8606 TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8607 EVT MemVT =
8608 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8609 assert(PtrVT == Ptr.getValueType());
8610 if (Mask.getValueType().getFixedSizeInBits() < MemVT.getFixedSizeInBits()) {
8611 // For AMDGPU buffer descriptors the mask is 48 bits, but the pointer is
8612 // 128-bit, so we have to pad the mask with ones for unused bits.
8613 auto HighOnes = DAG.getNode(
8614 ISD::SHL, sdl, PtrVT, DAG.getAllOnesConstant(sdl, PtrVT),
8615 DAG.getShiftAmountConstant(Mask.getValueType().getFixedSizeInBits(),
8616 PtrVT, sdl));
8617 Mask = DAG.getNode(ISD::OR, sdl, PtrVT,
8618 DAG.getZExtOrTrunc(Mask, sdl, PtrVT), HighOnes);
8619 } else if (Mask.getValueType() != PtrVT)
8620 Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
8621
8622 assert(Mask.getValueType() == PtrVT);
8623 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
8624 return;
8625 }
8626 case Intrinsic::threadlocal_address: {
8627 setValue(&I, getValue(I.getOperand(0)));
8628 return;
8629 }
8630 case Intrinsic::get_active_lane_mask: {
8631 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8632 SDValue Index = getValue(I.getOperand(0));
8633 SDValue TripCount = getValue(I.getOperand(1));
8634 EVT ElementVT = Index.getValueType();
8635
8636 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
8637 setValue(&I, DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, sdl, CCVT, Index,
8638 TripCount));
8639 return;
8640 }
8641
8642 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
8643 CCVT.getVectorElementCount());
8644
8645 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
8646 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
8647 SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
8648 SDValue VectorInduction = DAG.getNode(
8649 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
8650 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
8651 VectorTripCount, ISD::CondCode::SETULT);
8652 setValue(&I, SetCC);
8653 return;
8654 }
8655 case Intrinsic::mask_beforefirst: {
8656 SDValue Op = getValue(I.getOperand(0));
8657 setValue(&I,
8658 DAG.getNode(ISD::MASK_BEFOREFIRST, sdl, Op.getValueType(), Op));
8659 return;
8660 }
8661 case Intrinsic::experimental_get_vector_length: {
8662 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8663 "Expected positive VF");
8664 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
8665 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
8666
8667 SDValue Count = getValue(I.getOperand(0));
8668 EVT CountVT = Count.getValueType();
8669
8670 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8671 visitTargetIntrinsic(I, Intrinsic);
8672 return;
8673 }
8674
8675 // Expand to a umin between the trip count and the maximum elements the type
8676 // can hold.
8677 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8678
8679 // Extend the trip count to at least the result VT.
8680 if (CountVT.bitsLT(VT)) {
8681 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
8682 CountVT = VT;
8683 }
8684
8685 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
8687
8688 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8689 // Clip to the result type if needed.
8690 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8691
8692 setValue(&I, Trunc);
8693 return;
8694 }
8695 case Intrinsic::vector_partial_reduce_add: {
8696 SDValue Acc = getValue(I.getOperand(0));
8697 SDValue Input = getValue(I.getOperand(1));
8698 setValue(&I,
8699 DAG.getNode(ISD::PARTIAL_REDUCE_UMLA, sdl, Acc.getValueType(), Acc,
8700 Input, DAG.getConstant(1, sdl, Input.getValueType())));
8701 return;
8702 }
8703 case Intrinsic::vector_partial_reduce_fadd: {
8704 SDNodeFlags Flags;
8705 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
8706 Flags.copyFMF(*FPOp);
8707 SDValue Acc = getValue(I.getOperand(0));
8708 SDValue Input = getValue(I.getOperand(1));
8709 setValue(&I, DAG.getNode(ISD::PARTIAL_REDUCE_FMLA, sdl, Acc.getValueType(),
8710 Acc, Input,
8711 DAG.getConstantFP(1.0, sdl, Input.getValueType()),
8712 Flags));
8713 return;
8714 }
8715 case Intrinsic::experimental_cttz_elts: {
8716 SDValue Op = getValue(I.getOperand(0));
8717 EVT OpVT = Op.getValueType();
8718 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8719 bool ZeroIsPoison =
8720 !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8721 if (OpVT.getVectorElementType() != MVT::i1) {
8722 // Compare the input vector elements to zero & use to count trailing
8723 // zeros.
8724 SDValue AllZero = DAG.getConstant(0, sdl, OpVT);
8725 EVT I1OpVT = OpVT.changeVectorElementType(*DAG.getContext(), MVT::i1);
8726 Op = DAG.getSetCC(sdl, I1OpVT, Op, AllZero, ISD::SETNE);
8727 }
8728 setValue(&I, DAG.getNode(ZeroIsPoison ? ISD::CTTZ_ELTS_ZERO_POISON
8730 sdl, RetTy, Op));
8731 return;
8732 }
8733 case Intrinsic::vector_insert: {
8734 SDValue Vec = getValue(I.getOperand(0));
8735 SDValue SubVec = getValue(I.getOperand(1));
8736 SDValue Index = getValue(I.getOperand(2));
8737
8738 // The intrinsic's index type is i64, but the SDNode requires an index type
8739 // suitable for the target. Convert the index as required.
8740 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8741 if (Index.getValueType() != VectorIdxTy)
8742 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8743
8744 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8745 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8746 Index));
8747 return;
8748 }
8749 case Intrinsic::vector_extract: {
8750 SDValue Vec = getValue(I.getOperand(0));
8751 SDValue Index = getValue(I.getOperand(1));
8752 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8753
8754 // The intrinsic's index type is i64, but the SDNode requires an index type
8755 // suitable for the target. Convert the index as required.
8756 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8757 if (Index.getValueType() != VectorIdxTy)
8758 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8759
8760 setValue(&I,
8761 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8762 return;
8763 }
8764 case Intrinsic::experimental_vector_match: {
8765 SDValue Op1 = getValue(I.getOperand(0));
8766 SDValue Op2 = getValue(I.getOperand(1));
8767 SDValue Mask = getValue(I.getOperand(2));
8768 EVT ResVT = Mask.getValueType();
8769 setValue(&I, DAG.getNode(ISD::VECTOR_MATCH, sdl, ResVT, Op1, Op2, Mask));
8770 return;
8771 }
8772 case Intrinsic::vector_reverse:
8773 visitVectorReverse(I);
8774 return;
8775 case Intrinsic::vector_splice_left:
8776 case Intrinsic::vector_splice_right:
8777 visitVectorSplice(I);
8778 return;
8779 case Intrinsic::callbr_landingpad:
8780 visitCallBrLandingPad(I);
8781 return;
8782 case Intrinsic::vector_interleave2:
8783 visitVectorInterleave(I, 2);
8784 return;
8785 case Intrinsic::vector_interleave3:
8786 visitVectorInterleave(I, 3);
8787 return;
8788 case Intrinsic::vector_interleave4:
8789 visitVectorInterleave(I, 4);
8790 return;
8791 case Intrinsic::vector_interleave5:
8792 visitVectorInterleave(I, 5);
8793 return;
8794 case Intrinsic::vector_interleave6:
8795 visitVectorInterleave(I, 6);
8796 return;
8797 case Intrinsic::vector_interleave7:
8798 visitVectorInterleave(I, 7);
8799 return;
8800 case Intrinsic::vector_interleave8:
8801 visitVectorInterleave(I, 8);
8802 return;
8803 case Intrinsic::vector_deinterleave2:
8804 visitVectorDeinterleave(I, 2);
8805 return;
8806 case Intrinsic::vector_deinterleave3:
8807 visitVectorDeinterleave(I, 3);
8808 return;
8809 case Intrinsic::vector_deinterleave4:
8810 visitVectorDeinterleave(I, 4);
8811 return;
8812 case Intrinsic::vector_deinterleave5:
8813 visitVectorDeinterleave(I, 5);
8814 return;
8815 case Intrinsic::vector_deinterleave6:
8816 visitVectorDeinterleave(I, 6);
8817 return;
8818 case Intrinsic::vector_deinterleave7:
8819 visitVectorDeinterleave(I, 7);
8820 return;
8821 case Intrinsic::vector_deinterleave8:
8822 visitVectorDeinterleave(I, 8);
8823 return;
8824 case Intrinsic::vector_repeat: {
8825 SDValue Vec = getValue(I.getOperand(0));
8826 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8827 setValue(&I, DAG.getNode(ISD::VECTOR_REPEAT, sdl, ResultVT, Vec));
8828 return;
8829 }
8830 case Intrinsic::experimental_vector_compress:
8831 setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8832 getValue(I.getArgOperand(0)).getValueType(),
8833 getValue(I.getArgOperand(0)),
8834 getValue(I.getArgOperand(1)),
8835 getValue(I.getArgOperand(2)), Flags));
8836 return;
8837 case Intrinsic::experimental_convergence_anchor:
8838 case Intrinsic::experimental_convergence_entry:
8839 case Intrinsic::experimental_convergence_loop:
8840 visitConvergenceControl(I, Intrinsic);
8841 return;
8842 case Intrinsic::experimental_vector_histogram_add: {
8843 visitVectorHistogram(I, Intrinsic);
8844 return;
8845 }
8846 case Intrinsic::experimental_vector_extract_last_active: {
8847 visitVectorExtractLastActive(I, Intrinsic);
8848 return;
8849 }
8850 case Intrinsic::loop_dependence_war_mask:
8851 setValue(&I,
8853 EVT::getEVT(I.getType()), getValue(I.getOperand(0)),
8854 getValue(I.getOperand(1)), getValue(I.getOperand(2)),
8855 DAG.getConstant(0, sdl, MVT::i64)));
8856 return;
8857 case Intrinsic::loop_dependence_raw_mask:
8858 setValue(&I,
8860 EVT::getEVT(I.getType()), getValue(I.getOperand(0)),
8861 getValue(I.getOperand(1)), getValue(I.getOperand(2)),
8862 DAG.getConstant(0, sdl, MVT::i64)));
8863 return;
8864 case Intrinsic::masked_udiv:
8865 setValue(&I,
8866 DAG.getNode(ISD::MASKED_UDIV, sdl, EVT::getEVT(I.getType()),
8867 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8868 getValue(I.getOperand(2))));
8869 return;
8870 case Intrinsic::masked_sdiv:
8871 setValue(&I,
8872 DAG.getNode(ISD::MASKED_SDIV, sdl, EVT::getEVT(I.getType()),
8873 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8874 getValue(I.getOperand(2))));
8875 return;
8876 case Intrinsic::masked_urem:
8877 setValue(&I,
8878 DAG.getNode(ISD::MASKED_UREM, sdl, EVT::getEVT(I.getType()),
8879 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8880 getValue(I.getOperand(2))));
8881 return;
8882 case Intrinsic::masked_srem:
8883 setValue(&I,
8884 DAG.getNode(ISD::MASKED_SREM, sdl, EVT::getEVT(I.getType()),
8885 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8886 getValue(I.getOperand(2))));
8887 return;
8888 }
8889}
8890
8891void SelectionDAGBuilder::pushFPOpOutChain(SDValue Result,
8893 assert(Result.getNode()->getNumValues() == 2);
8894 SDValue OutChain = Result.getValue(1);
8895 assert(OutChain.getValueType() == MVT::Other);
8896
8897 // Instead of updating the root immediately, push the produced chain to the
8898 // appropriate list, deferring the update until the root is requested. In this
8899 // case, the nodes from the lists are chained using TokenFactor, indicating
8900 // that the operations are independent.
8901 //
8902 // In particular, the root is updated before any call that might access the
8903 // floating-point environment, except for constrained intrinsics.
8904 switch (EB) {
8907 PendingConstrainedFP.push_back(OutChain);
8908 break;
8910 PendingConstrainedFPStrict.push_back(OutChain);
8911 break;
8912 }
8913}
8914
8915void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8916 const ConstrainedFPIntrinsic &FPI) {
8917 SDLoc sdl = getCurSDLoc();
8918
8919 // We do not need to serialize constrained FP intrinsics against
8920 // each other or against (nonvolatile) loads, so they can be
8921 // chained like loads.
8923 SDValue Chain = getFPOperationRoot(EB);
8925 Opers.push_back(Chain);
8926 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8927 Opers.push_back(getValue(FPI.getArgOperand(I)));
8928
8929 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8930 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8931 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8932
8933 SDNodeFlags Flags;
8935 Flags.setNoFPExcept(true);
8936
8937 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8938 Flags.copyFMF(*FPOp);
8939
8940 unsigned Opcode;
8941 switch (FPI.getIntrinsicID()) {
8942 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8943#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8944 case Intrinsic::INTRINSIC: \
8945 Opcode = ISD::STRICT_##DAGN; \
8946 break;
8947#include "llvm/IR/ConstrainedOps.def"
8948 case Intrinsic::experimental_constrained_fmuladd: {
8949 Opcode = ISD::STRICT_FMA;
8950 // Break fmuladd into fmul and fadd.
8951 if (!TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8952 Opers.pop_back();
8953 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8954 pushFPOpOutChain(Mul, EB);
8955 Opcode = ISD::STRICT_FADD;
8956 Opers.clear();
8957 Opers.push_back(Mul.getValue(1));
8958 Opers.push_back(Mul.getValue(0));
8959 Opers.push_back(getValue(FPI.getArgOperand(2)));
8960 }
8961 break;
8962 }
8963 }
8964
8965 // A few strict DAG nodes carry additional operands that are not
8966 // set up by the default code above.
8967 switch (Opcode) {
8968 default: break;
8970 Opers.push_back(
8971 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8972 break;
8973 case ISD::STRICT_FSETCC:
8974 case ISD::STRICT_FSETCCS: {
8975 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8976 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8977 if (DAG.isKnownNeverNaN(Opers[1]) && DAG.isKnownNeverNaN(Opers[2]))
8978 Condition = getFCmpCodeWithoutNaN(Condition);
8979 Opers.push_back(DAG.getCondCode(Condition));
8980 break;
8981 }
8982 }
8983
8984 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8985 pushFPOpOutChain(Result, EB);
8986
8987 SDValue FPResult = Result.getValue(0);
8988 setValue(&FPI, FPResult);
8989}
8990
8991static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8992 std::optional<unsigned> ResOPC;
8993 switch (VPIntrin.getIntrinsicID()) {
8994 case Intrinsic::vp_cttz_elts: {
8995 bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8996 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_POISON : ISD::VP_CTTZ_ELTS;
8997 break;
8998 }
8999#define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \
9000 case Intrinsic::VPID: \
9001 ResOPC = ISD::VPSD; \
9002 break;
9003#include "llvm/IR/VPIntrinsics.def"
9004 }
9005
9006 if (!ResOPC)
9008 "Inconsistency: no SDNode available for this VPIntrinsic!");
9009
9010 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
9011 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
9012 if (VPIntrin.getFastMathFlags().allowReassoc())
9013 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
9014 : ISD::VP_REDUCE_FMUL;
9015 }
9016
9017 return *ResOPC;
9018}
9019
9020void SelectionDAGBuilder::visitVPLoad(
9021 const VPIntrinsic &VPIntrin, EVT VT,
9022 const SmallVectorImpl<SDValue> &OpValues) {
9023 SDLoc DL = getCurSDLoc();
9024 Value *PtrOperand = VPIntrin.getArgOperand(0);
9025 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9026 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9027 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9028 SDValue LD;
9029 // Do not serialize variable-length loads of constant memory with
9030 // anything.
9031 if (!Alignment)
9032 Alignment = DAG.getEVTAlign(VT);
9033 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9034 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9035 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9036 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9037 MachineMemOperand::Flags MMOFlags =
9039 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9040 MachinePointerInfo(PtrOperand), MMOFlags,
9042 MMOMetadata(AAInfo, Ranges));
9043 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
9044 MMO, false /*IsExpanding */);
9045 if (AddToChain)
9046 PendingLoads.push_back(LD.getValue(1));
9047 setValue(&VPIntrin, LD);
9048}
9049
9050void SelectionDAGBuilder::visitVPLoadFF(
9051 const VPIntrinsic &VPIntrin, EVT VT, EVT EVLVT,
9052 const SmallVectorImpl<SDValue> &OpValues) {
9053 assert(OpValues.size() == 3 && "Unexpected number of operands");
9054 SDLoc DL = getCurSDLoc();
9055 Value *PtrOperand = VPIntrin.getArgOperand(0);
9056 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9057 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9058 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
9059 SDValue LD;
9060 // Do not serialize variable-length loads of constant memory with
9061 // anything.
9062 if (!Alignment)
9063 Alignment = DAG.getEVTAlign(VT);
9064 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9065 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9066 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9067 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9068 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
9070 MMOMetadata(AAInfo, Ranges));
9071 LD = DAG.getLoadFFVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
9072 MMO);
9073 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, EVLVT, LD.getValue(1));
9074 if (AddToChain)
9075 PendingLoads.push_back(LD.getValue(2));
9076 setValue(&VPIntrin, DAG.getMergeValues({LD.getValue(0), Trunc}, DL));
9077}
9078
9079void SelectionDAGBuilder::visitVPGather(
9080 const VPIntrinsic &VPIntrin, EVT VT,
9081 const SmallVectorImpl<SDValue> &OpValues) {
9082 SDLoc DL = getCurSDLoc();
9083 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9084 Value *PtrOperand = VPIntrin.getArgOperand(0);
9085 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9086 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9087 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9088 SDValue LD;
9089 if (!Alignment)
9090 Alignment = DAG.getEVTAlign(VT.getScalarType());
9091 unsigned AS =
9092 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
9093 MachineMemOperand::Flags MMOFlags =
9095 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9096 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9097 *Alignment, MMOMetadata(AAInfo, Ranges));
9098 SDValue Base, Index, Scale;
9099 bool UniformBase =
9100 getUniformBase(PtrOperand, Base, Index, Scale, this, VPIntrin.getParent(),
9101 VT.getScalarStoreSize());
9102 if (!UniformBase) {
9103 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
9104 Index = getValue(PtrOperand);
9105 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
9106 }
9107 EVT IdxVT = Index.getValueType();
9108 EVT EltTy = IdxVT.getVectorElementType();
9109 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
9110 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
9111 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
9112 }
9113 LD = DAG.getGatherVP(
9114 DAG.getVTList(VT, MVT::Other), VT, DL,
9115 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
9117 PendingLoads.push_back(LD.getValue(1));
9118 setValue(&VPIntrin, LD);
9119}
9120
9121void SelectionDAGBuilder::visitVPStore(
9122 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9123 SDLoc DL = getCurSDLoc();
9124 Value *PtrOperand = VPIntrin.getArgOperand(1);
9125 EVT VT = OpValues[0].getValueType();
9126 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9127 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9128 SDValue ST;
9129 if (!Alignment)
9130 Alignment = DAG.getEVTAlign(VT);
9131 SDValue Ptr = OpValues[1];
9132 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
9133 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9134 MachineMemOperand::Flags MMOFlags =
9136 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9137 MachinePointerInfo(PtrOperand), MMOFlags,
9138 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
9139 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
9140 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
9141 /* IsTruncating */ false, /*IsCompressing*/ false);
9142 DAG.setRoot(ST);
9143 setValue(&VPIntrin, ST);
9144}
9145
9146void SelectionDAGBuilder::visitVPScatter(
9147 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9148 SDLoc DL = getCurSDLoc();
9149 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9150 Value *PtrOperand = VPIntrin.getArgOperand(1);
9151 EVT VT = OpValues[0].getValueType();
9152 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9153 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9154 SDValue ST;
9155 if (!Alignment)
9156 Alignment = DAG.getEVTAlign(VT.getScalarType());
9157 unsigned AS =
9158 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
9159 MachineMemOperand::Flags MMOFlags =
9161 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9162 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9163 *Alignment, AAInfo);
9164 SDValue Base, Index, Scale;
9165 bool UniformBase =
9166 getUniformBase(PtrOperand, Base, Index, Scale, this, VPIntrin.getParent(),
9167 VT.getScalarStoreSize());
9168 if (!UniformBase) {
9169 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
9170 Index = getValue(PtrOperand);
9171 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
9172 }
9173 EVT IdxVT = Index.getValueType();
9174 EVT EltTy = IdxVT.getVectorElementType();
9175 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
9176 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
9177 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
9178 }
9179 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
9180 {getMemoryRoot(), OpValues[0], Base, Index, Scale,
9181 OpValues[2], OpValues[3]},
9182 MMO, ISD::SIGNED_SCALED);
9183 DAG.setRoot(ST);
9184 setValue(&VPIntrin, ST);
9185}
9186
9187void SelectionDAGBuilder::visitVPStridedLoad(
9188 const VPIntrinsic &VPIntrin, EVT VT,
9189 const SmallVectorImpl<SDValue> &OpValues) {
9190 SDLoc DL = getCurSDLoc();
9191 Value *PtrOperand = VPIntrin.getArgOperand(0);
9192 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9193 if (!Alignment)
9194 Alignment = DAG.getEVTAlign(VT.getScalarType());
9195 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9196 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9197 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9198 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9199 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9200 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9201 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9202 MachineMemOperand::Flags MMOFlags =
9204 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9205 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9206 *Alignment, MMOMetadata(AAInfo, Ranges));
9207
9208 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
9209 OpValues[2], OpValues[3], MMO,
9210 false /*IsExpanding*/);
9211
9212 if (AddToChain)
9213 PendingLoads.push_back(LD.getValue(1));
9214 setValue(&VPIntrin, LD);
9215}
9216
9217void SelectionDAGBuilder::visitVPStridedStore(
9218 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9219 SDLoc DL = getCurSDLoc();
9220 Value *PtrOperand = VPIntrin.getArgOperand(1);
9221 EVT VT = OpValues[0].getValueType();
9222 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9223 if (!Alignment)
9224 Alignment = DAG.getEVTAlign(VT.getScalarType());
9225 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9226 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9227 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9228 MachineMemOperand::Flags MMOFlags =
9230 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9231 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9232 *Alignment, AAInfo);
9233
9234 SDValue ST = DAG.getStridedStoreVP(
9235 getMemoryRoot(), DL, OpValues[0], OpValues[1],
9236 DAG.getPOISON(OpValues[1].getValueType()), OpValues[2], OpValues[3],
9237 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
9238 /*IsCompressing*/ false);
9239
9240 DAG.setRoot(ST);
9241 setValue(&VPIntrin, ST);
9242}
9243
9244void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
9245 const VPIntrinsic &VPIntrin) {
9246 SDLoc DL = getCurSDLoc();
9247 unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
9248
9249 auto IID = VPIntrin.getIntrinsicID();
9250
9251 SmallVector<EVT, 4> ValueVTs;
9252 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9253 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
9254 SDVTList VTs = DAG.getVTList(ValueVTs);
9255
9256 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
9257
9258 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
9259 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
9260 "Unexpected target EVL type");
9261
9262 // Request operands.
9263 SmallVector<SDValue, 7> OpValues;
9264 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
9265 auto Op = getValue(VPIntrin.getArgOperand(I));
9266 if (I == EVLParamPos)
9267 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
9268 OpValues.push_back(Op);
9269 }
9270
9271 switch (Opcode) {
9272 default: {
9273 SDNodeFlags SDFlags;
9274 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
9275 SDFlags.copyFMF(*FPMO);
9276 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
9277 setValue(&VPIntrin, Result);
9278 break;
9279 }
9280 case ISD::VP_LOAD:
9281 visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
9282 break;
9283 case ISD::VP_LOAD_FF:
9284 visitVPLoadFF(VPIntrin, ValueVTs[0], ValueVTs[1], OpValues);
9285 break;
9286 case ISD::VP_GATHER:
9287 visitVPGather(VPIntrin, ValueVTs[0], OpValues);
9288 break;
9289 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
9290 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
9291 break;
9292 case ISD::VP_STORE:
9293 visitVPStore(VPIntrin, OpValues);
9294 break;
9295 case ISD::VP_SCATTER:
9296 visitVPScatter(VPIntrin, OpValues);
9297 break;
9298 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
9299 visitVPStridedStore(VPIntrin, OpValues);
9300 break;
9301 case ISD::VP_CTTZ_ELTS_ZERO_POISON:
9302 case ISD::VP_CTTZ_ELTS: {
9303 SDValue Result =
9304 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
9305 setValue(&VPIntrin, Result);
9306 break;
9307 }
9308 }
9309}
9310
9312 const BasicBlock *EHPadBB,
9313 MCSymbol *&BeginLabel) {
9314 MachineFunction &MF = DAG.getMachineFunction();
9315
9316 // Skip emitting EH_LABEL on targets whose exception tables don't reference
9317 // them (32-bit x86 SEH, Wasm).
9319 FuncInfo.ExceptionModel)) {
9320 BeginLabel = nullptr;
9321 return Chain;
9322 }
9323
9324 // Insert a label before the invoke call to mark the try range. This can be
9325 // used to detect deletion of the invoke via the MachineModuleInfo.
9326 BeginLabel = MF.getContext().createTempSymbol();
9327
9328 // For SjLj, keep track of which landing pads go with which invokes
9329 // so as to maintain the ordering of pads in the LSDA.
9330 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
9331 if (CallSiteIndex) {
9332 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
9333 LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
9334
9335 // Now that the call site is handled, stop tracking it.
9336 FuncInfo.setCurrentCallSite(0);
9337 }
9338
9339 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
9340}
9341
9342SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
9343 const BasicBlock *EHPadBB,
9344 MCSymbol *BeginLabel) {
9345 // No labels were emitted.
9346 if (!BeginLabel)
9347 return Chain;
9348
9350
9351 // Insert a label at the end of the invoke call to mark the try range. This
9352 // can be used to detect deletion of the invoke via the MachineModuleInfo.
9353 MCSymbol *EndLabel = MF.getContext().createTempSymbol();
9354 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
9355
9356 // Inform MachineModuleInfo of range.
9358 // There is a platform (e.g. wasm) that uses funclet style IR but does not
9359 // actually use outlined funclets and their LSDA info style.
9360 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
9361 assert(II && "II should've been set");
9362 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
9363 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
9364 } else if (!isScopedEHPersonality(Pers)) {
9365 assert(EHPadBB);
9366 MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
9367 }
9368
9369 return Chain;
9370}
9371
9372std::pair<SDValue, SDValue>
9374 const BasicBlock *EHPadBB) {
9375 MCSymbol *BeginLabel = nullptr;
9376
9377 if (EHPadBB) {
9378 // Both PendingLoads and PendingExports must be flushed here;
9379 // this call might not return.
9380 (void)getRoot();
9381 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
9382 CLI.setChain(getRoot());
9383 }
9384
9385 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9386 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
9387
9388 assert((CLI.IsTailCall || Result.second.getNode()) &&
9389 "Non-null chain expected with non-tail call!");
9390 assert((Result.second.getNode() || !Result.first.getNode()) &&
9391 "Null value expected with tail call!");
9392
9393 if (!Result.second.getNode()) {
9394 // As a special case, a null chain means that a tail call has been emitted
9395 // and the DAG root is already updated.
9396 HasTailCall = true;
9397
9398 // Since there's no actual continuation from this block, nothing can be
9399 // relying on us setting vregs for them.
9400 PendingExports.clear();
9401 } else {
9402 DAG.setRoot(Result.second);
9403 }
9404
9405 if (EHPadBB) {
9406 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
9407 BeginLabel));
9408 Result.second = getRoot();
9409 }
9410
9411 return Result;
9412}
9413
9415 bool isMustTailCall = CB.isMustTailCall();
9416
9417 // Avoid emitting tail calls in functions with the disable-tail-calls
9418 // attribute.
9419 const Function *Caller = CB.getParent()->getParent();
9420 if (!isMustTailCall &&
9421 Caller->getFnAttribute("disable-tail-calls").getValueAsBool())
9422 return false;
9423
9424 // We can't tail call inside a function with a swifterror argument. Lowering
9425 // does not support this yet. It would have to move into the swifterror
9426 // register before the call.
9427 if (DAG.hasSwiftErrorArg())
9428 return false;
9429
9430 // Check if target-independent constraints permit a tail call here.
9431 // Target-dependent constraints are checked within TLI->LowerCallTo.
9432 return isInTailCallPosition(CB, DAG.getTarget());
9433}
9434
9436 bool isTailCall, bool isMustTailCall,
9437 const BasicBlock *EHPadBB,
9438 const TargetLowering::PtrAuthInfo *PAI) {
9439 auto &DL = DAG.getDataLayout();
9440 FunctionType *FTy = CB.getFunctionType();
9441 Type *RetTy = CB.getType();
9442
9444 Args.reserve(CB.arg_size());
9445
9446 const Value *SwiftErrorVal = nullptr;
9447 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9448
9449 if (isTailCall)
9450 isTailCall = canTailCall(CB);
9451
9452 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
9453 const Value *V = *I;
9454
9455 // Skip empty types
9456 if (V->getType()->isEmptyTy())
9457 continue;
9458
9459 SDValue ArgNode = getValue(V);
9460 TargetLowering::ArgListEntry Entry(ArgNode, V->getType());
9461 Entry.setAttributes(&CB, I - CB.arg_begin());
9462
9463 // Use swifterror virtual register as input to the call.
9464 if (Entry.IsSwiftError && TLI.supportSwiftError()) {
9465 SwiftErrorVal = V;
9466 // We find the virtual register for the actual swifterror argument.
9467 // Instead of using the Value, we use the virtual register instead.
9468 Entry.Node =
9469 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
9470 EVT(TLI.getPointerTy(DL)));
9471 }
9472
9473 Args.push_back(Entry);
9474
9475 // If we have an explicit sret argument that is an Instruction, (i.e., it
9476 // might point to function-local memory), we can't meaningfully tail-call.
9477 if (Entry.IsSRet && isa<Instruction>(V))
9478 isTailCall = false;
9479 }
9480
9481 // If call site has a cfguardtarget operand bundle, create and add an
9482 // additional ArgListEntry.
9483 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
9484 Value *V = Bundle->Inputs[0];
9486 Entry.IsCFGuardTarget = true;
9487 Args.push_back(Entry);
9488 }
9489
9490 // Disable tail calls if there is an swifterror argument. Targets have not
9491 // been updated to support tail calls.
9492 if (TLI.supportSwiftError() && SwiftErrorVal)
9493 isTailCall = false;
9494
9495 ConstantInt *CFIType = nullptr;
9496 if (CB.isIndirectCall()) {
9497 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
9498 if (!TLI.supportKCFIBundles())
9500 "Target doesn't support calls with kcfi operand bundles.");
9501 CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
9502 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
9503 }
9504 }
9505
9506 SDValue ConvControlToken;
9507 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
9508 auto *Token = Bundle->Inputs[0].get();
9509 ConvControlToken = getValue(Token);
9510 }
9511
9512 GlobalValue *DeactivationSymbol = nullptr;
9514 DeactivationSymbol = cast<GlobalValue>(Bundle->Inputs[0].get());
9515 }
9516
9519 .setChain(getRoot())
9520 .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
9521 .setTailCall(isTailCall)
9525 .setCFIType(CFIType)
9526 .setConvergenceControlToken(ConvControlToken)
9527 .setDeactivationSymbol(DeactivationSymbol);
9528
9529 // Set the pointer authentication info if we have it.
9530 if (PAI) {
9531 if (!TLI.supportPtrAuthBundles())
9533 "This target doesn't support calls with ptrauth operand bundles.");
9534 CLI.setPtrAuth(*PAI);
9535 }
9536
9537 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9538
9539 if (Result.first.getNode()) {
9540 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
9541 Result.first = lowerNoFPClassToAssertNoFPClass(DAG, CB, Result.first);
9542 setValue(&CB, Result.first);
9543 }
9544
9545 // The last element of CLI.InVals has the SDValue for swifterror return.
9546 // Here we copy it to a virtual register and update SwiftErrorMap for
9547 // book-keeping.
9548 if (SwiftErrorVal && TLI.supportSwiftError()) {
9549 // Get the last element of InVals.
9550 SDValue Src = CLI.InVals.back();
9551 Register VReg =
9552 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
9553 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
9554 DAG.setRoot(CopyNode);
9555 }
9556}
9557
9558static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
9559 SelectionDAGBuilder &Builder) {
9560 // Check to see if this load can be trivially constant folded, e.g. if the
9561 // input is from a string literal.
9562 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
9563 // Cast pointer to the type we really want to load.
9564 Type *LoadTy =
9565 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
9566 if (LoadVT.isVector())
9567 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
9568 if (const Constant *LoadCst =
9569 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
9570 LoadTy, Builder.DAG.getDataLayout()))
9571 return Builder.getValue(LoadCst);
9572 }
9573
9574 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
9575 // still constant memory, the input chain can be the entry node.
9576 SDValue Root;
9577 bool ConstantMemory = false;
9578
9579 // Do not serialize (non-volatile) loads of constant memory with anything.
9580 if (Builder.BatchAA && Builder.BatchAA->pointsToConstantMemory(PtrVal)) {
9581 Root = Builder.DAG.getEntryNode();
9582 ConstantMemory = true;
9583 } else {
9584 // Do not serialize non-volatile loads against each other.
9585 Root = Builder.DAG.getRoot();
9586 }
9587
9588 SDValue Ptr = Builder.getValue(PtrVal);
9589 SDValue LoadVal =
9590 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
9591 MachinePointerInfo(PtrVal), Align(1));
9592
9593 if (!ConstantMemory)
9594 Builder.PendingLoads.push_back(LoadVal.getValue(1));
9595 return LoadVal;
9596}
9597
9598/// Record the value for an instruction that produces an integer result,
9599/// converting the type where necessary.
9600void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
9601 SDValue Value,
9602 bool IsSigned) {
9603 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9604 I.getType(), true);
9605 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
9606 setValue(&I, Value);
9607}
9608
9609/// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
9610/// true and lower it. Otherwise return false, and it will be lowered like a
9611/// normal call.
9612/// The caller already checked that \p I calls the appropriate LibFunc with a
9613/// correct prototype.
9614bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
9615 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
9616 const Value *Size = I.getArgOperand(2);
9617 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
9618 if (CSize && CSize->getZExtValue() == 0) {
9619 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9620 I.getType(), true);
9621 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
9622 return true;
9623 }
9624
9625 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9626 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9627 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
9628 getValue(Size), &I);
9629 if (Res.first.getNode()) {
9630 processIntegerCallValue(I, Res.first, true);
9631 PendingLoads.push_back(Res.second);
9632 return true;
9633 }
9634
9635 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
9636 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
9637 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
9638 return false;
9639
9640 // If the target has a fast compare for the given size, it will return a
9641 // preferred load type for that size. Require that the load VT is legal and
9642 // that the target supports unaligned loads of that type. Otherwise, return
9643 // INVALID.
9644 auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9645 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9646 MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9647 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9648 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9649 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9650 // TODO: Check alignment of src and dest ptrs.
9651 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9652 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9653 if (!TLI.isTypeLegal(LVT) ||
9654 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
9657 }
9658
9659 return LVT;
9660 };
9661
9662 // This turns into unaligned loads. We only do this if the target natively
9663 // supports the MVT we'll be loading or if it is small enough (<= 4) that
9664 // we'll only produce a small number of byte loads.
9665 MVT LoadVT;
9666 unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9667 switch (NumBitsToCompare) {
9668 default:
9669 return false;
9670 case 16:
9671 LoadVT = MVT::i16;
9672 break;
9673 case 32:
9674 LoadVT = MVT::i32;
9675 break;
9676 case 64:
9677 case 128:
9678 case 256:
9679 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9680 break;
9681 }
9682
9683 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9684 return false;
9685
9686 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9687 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9688
9689 // Bitcast to a wide integer type if the loads are vectors.
9690 if (LoadVT.isVector()) {
9691 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9692 LoadL = DAG.getBitcast(CmpVT, LoadL);
9693 LoadR = DAG.getBitcast(CmpVT, LoadR);
9694 }
9695
9696 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9697 processIntegerCallValue(I, Cmp, false);
9698 return true;
9699}
9700
9701/// See if we can lower a memchr call into an optimized form. If so, return
9702/// true and lower it. Otherwise return false, and it will be lowered like a
9703/// normal call.
9704/// The caller already checked that \p I calls the appropriate LibFunc with a
9705/// correct prototype.
9706bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9707 const Value *Src = I.getArgOperand(0);
9708 const Value *Char = I.getArgOperand(1);
9709 const Value *Length = I.getArgOperand(2);
9710
9711 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9712 std::pair<SDValue, SDValue> Res =
9713 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9714 getValue(Src), getValue(Char), getValue(Length),
9715 MachinePointerInfo(Src));
9716 if (Res.first.getNode()) {
9717 setValue(&I, Res.first);
9718 PendingLoads.push_back(Res.second);
9719 return true;
9720 }
9721
9722 return false;
9723}
9724
9725/// See if we can lower a memccpy call into an optimized form. If so, return
9726/// true and lower it, otherwise return false and it will be lowered like a
9727/// normal call.
9728/// The caller already checked that \p I calls the appropriate LibFunc with a
9729/// correct prototype.
9730bool SelectionDAGBuilder::visitMemCCpyCall(const CallInst &I) {
9731 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9732 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemccpy(
9733 DAG, getCurSDLoc(), DAG.getRoot(), getValue(I.getArgOperand(0)),
9734 getValue(I.getArgOperand(1)), getValue(I.getArgOperand(2)),
9735 getValue(I.getArgOperand(3)), &I);
9736
9737 if (Res.first) {
9738 processIntegerCallValue(I, Res.first, true);
9739 PendingLoads.push_back(Res.second);
9740 return true;
9741 }
9742 return false;
9743}
9744
9745/// See if we can lower a mempcpy call into an optimized form. If so, return
9746/// true and lower it. Otherwise return false, and it will be lowered like a
9747/// normal call.
9748/// The caller already checked that \p I calls the appropriate LibFunc with a
9749/// correct prototype.
9750bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9751 SDValue Dst = getValue(I.getArgOperand(0));
9752 SDValue Src = getValue(I.getArgOperand(1));
9753 SDValue Size = getValue(I.getArgOperand(2));
9754
9755 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9756 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9757
9758 SDLoc sdl = getCurSDLoc();
9759
9760 // In the mempcpy context we need to pass in a false value for isTailCall
9761 // because the return pointer needs to be adjusted by the size of
9762 // the copied memory.
9763 SDValue Root = getMemoryRoot();
9764 SDValue MC = DAG.getMemcpy(
9765 Root, sdl, Dst, Src, Size, DstAlign, SrcAlign, false, false,
9766 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9767 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9768 assert(MC.getNode() != nullptr &&
9769 "** memcpy should not be lowered as TailCall in mempcpy context **");
9770 DAG.setRoot(MC);
9771
9772 // Check if Size needs to be truncated or extended.
9773 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9774
9775 // Adjust return pointer to point just past the last dst byte.
9776 SDValue DstPlusSize = DAG.getMemBasePlusOffset(Dst, Size, sdl);
9777 setValue(&I, DstPlusSize);
9778 return true;
9779}
9780
9781/// See if we can lower a strcpy call into an optimized form. If so, return
9782/// true and lower it, otherwise return false and it will be lowered like a
9783/// normal call.
9784/// The caller already checked that \p I calls the appropriate LibFunc with a
9785/// correct prototype.
9786bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9787 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9788
9789 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9790 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcpy(
9791 DAG, getCurSDLoc(), getRoot(), getValue(Arg0), getValue(Arg1),
9792 MachinePointerInfo(Arg0), MachinePointerInfo(Arg1), isStpcpy, &I);
9793 if (Res.first.getNode()) {
9794 setValue(&I, Res.first);
9795 DAG.setRoot(Res.second);
9796 return true;
9797 }
9798
9799 return false;
9800}
9801
9802/// See if we can lower a strcmp call into an optimized form. If so, return
9803/// true and lower it, otherwise return false and it will be lowered like a
9804/// normal call.
9805/// The caller already checked that \p I calls the appropriate LibFunc with a
9806/// correct prototype.
9807bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9808 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9809
9810 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9811 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcmp(
9812 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), getValue(Arg1),
9813 MachinePointerInfo(Arg0), MachinePointerInfo(Arg1), &I);
9814 if (Res.first.getNode()) {
9815 processIntegerCallValue(I, Res.first, true);
9816 PendingLoads.push_back(Res.second);
9817 return true;
9818 }
9819
9820 return false;
9821}
9822
9823/// See if we can lower a strlen call into an optimized form. If so, return
9824/// true and lower it, otherwise return false and it will be lowered like a
9825/// normal call.
9826/// The caller already checked that \p I calls the appropriate LibFunc with a
9827/// correct prototype.
9828bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9829 const Value *Arg0 = I.getArgOperand(0);
9830
9831 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9832 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrlen(
9833 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), &I);
9834 if (Res.first.getNode()) {
9835 processIntegerCallValue(I, Res.first, false);
9836 PendingLoads.push_back(Res.second);
9837 return true;
9838 }
9839
9840 return false;
9841}
9842
9843/// See if we can lower a strnlen call into an optimized form. If so, return
9844/// true and lower it, otherwise return false and it will be lowered like a
9845/// normal call.
9846/// The caller already checked that \p I calls the appropriate LibFunc with a
9847/// correct prototype.
9848bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9849 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9850
9851 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9852 std::pair<SDValue, SDValue> Res =
9853 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9854 getValue(Arg0), getValue(Arg1),
9855 MachinePointerInfo(Arg0));
9856 if (Res.first.getNode()) {
9857 processIntegerCallValue(I, Res.first, false);
9858 PendingLoads.push_back(Res.second);
9859 return true;
9860 }
9861
9862 return false;
9863}
9864
9865/// See if we can lower a Strstr call into an optimized form. If so, return
9866/// true and lower it, otherwise return false and it will be lowered like a
9867/// normal call.
9868/// The caller already checked that \p I calls the appropriate LibFunc with a
9869/// correct prototype.
9870bool SelectionDAGBuilder::visitStrstrCall(const CallInst &I) {
9871 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9872 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9873 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrstr(
9874 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), getValue(Arg1), &I);
9875 if (Res.first) {
9876 processIntegerCallValue(I, Res.first, false);
9877 PendingLoads.push_back(Res.second);
9878 return true;
9879 }
9880 return false;
9881}
9882
9883/// See if we can lower a unary floating-point operation into an SDNode with
9884/// the specified Opcode. If so, return true and lower it, otherwise return
9885/// false and it will be lowered like a normal call.
9886/// The caller already checked that \p I calls the appropriate LibFunc with a
9887/// correct prototype.
9888bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9889 unsigned Opcode) {
9890 // We already checked this call's prototype; verify it doesn't modify errno.
9891 // Do not perform optimizations for call sites that require strict
9892 // floating-point semantics.
9893 if (!I.onlyReadsMemory() || I.isStrictFP())
9894 return false;
9895
9896 SDNodeFlags Flags;
9897 Flags.copyFMF(cast<FPMathOperator>(I));
9898
9899 SDValue Tmp = getValue(I.getArgOperand(0));
9900 setValue(&I,
9901 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9902 return true;
9903}
9904
9905/// See if we can lower a binary floating-point operation into an SDNode with
9906/// the specified Opcode. If so, return true and lower it. Otherwise return
9907/// false, and it will be lowered like a normal call.
9908/// The caller already checked that \p I calls the appropriate LibFunc with a
9909/// correct prototype.
9910bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9911 unsigned Opcode) {
9912 // We already checked this call's prototype; verify it doesn't modify errno.
9913 // Do not perform optimizations for call sites that require strict
9914 // floating-point semantics.
9915 if (!I.onlyReadsMemory() || I.isStrictFP())
9916 return false;
9917
9918 SDNodeFlags Flags;
9919 Flags.copyFMF(cast<FPMathOperator>(I));
9920
9921 SDValue Tmp0 = getValue(I.getArgOperand(0));
9922 SDValue Tmp1 = getValue(I.getArgOperand(1));
9923 EVT VT = Tmp0.getValueType();
9924 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9925 return true;
9926}
9927
9928void SelectionDAGBuilder::visitCall(const CallInst &I) {
9929 // Handle inline assembly differently.
9930 if (I.isInlineAsm()) {
9931 visitInlineAsm(I);
9932 return;
9933 }
9934
9936
9937 if (Function *F = I.getCalledFunction()) {
9938 if (F->isDeclaration()) {
9939 // Is this an LLVM intrinsic?
9940 if (unsigned IID = F->getIntrinsicID()) {
9941 visitIntrinsicCall(I, IID);
9942 return;
9943 }
9944 }
9945
9946 // Check for well-known libc/libm calls. If the function is internal, it
9947 // can't be a library call. Don't do the check if marked as nobuiltin for
9948 // some reason.
9949 // This code should not handle libcalls that are already canonicalized to
9950 // intrinsics by the middle-end.
9951 LibFunc Func = !I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName()
9952 ? LibInfo->getLibFunc(*F)
9953 : NotLibFunc;
9954 if (LibInfo->hasOptimizedCodeGen(Func)) {
9955 switch (Func) {
9956 default: break;
9957 case LibFunc_bcmp:
9958 if (visitMemCmpBCmpCall(I))
9959 return;
9960 break;
9961 case LibFunc_copysign:
9962 case LibFunc_copysignf:
9963 case LibFunc_copysignl:
9964 // We already checked this call's prototype; verify it doesn't modify
9965 // errno.
9966 if (I.onlyReadsMemory()) {
9967 SDValue LHS = getValue(I.getArgOperand(0));
9968 SDValue RHS = getValue(I.getArgOperand(1));
9970 LHS.getValueType(), LHS, RHS));
9971 return;
9972 }
9973 break;
9974 case LibFunc_sin:
9975 case LibFunc_sinf:
9976 case LibFunc_sinl:
9977 if (visitUnaryFloatCall(I, ISD::FSIN))
9978 return;
9979 break;
9980 case LibFunc_cos:
9981 case LibFunc_cosf:
9982 case LibFunc_cosl:
9983 if (visitUnaryFloatCall(I, ISD::FCOS))
9984 return;
9985 break;
9986 case LibFunc_tan:
9987 case LibFunc_tanf:
9988 case LibFunc_tanl:
9989 if (visitUnaryFloatCall(I, ISD::FTAN))
9990 return;
9991 break;
9992 case LibFunc_asin:
9993 case LibFunc_asinf:
9994 case LibFunc_asinl:
9995 if (visitUnaryFloatCall(I, ISD::FASIN))
9996 return;
9997 break;
9998 case LibFunc_acos:
9999 case LibFunc_acosf:
10000 case LibFunc_acosl:
10001 if (visitUnaryFloatCall(I, ISD::FACOS))
10002 return;
10003 break;
10004 case LibFunc_atan:
10005 case LibFunc_atanf:
10006 case LibFunc_atanl:
10007 if (visitUnaryFloatCall(I, ISD::FATAN))
10008 return;
10009 break;
10010 case LibFunc_atan2:
10011 case LibFunc_atan2f:
10012 case LibFunc_atan2l:
10013 if (visitBinaryFloatCall(I, ISD::FATAN2))
10014 return;
10015 break;
10016 case LibFunc_sinh:
10017 case LibFunc_sinhf:
10018 case LibFunc_sinhl:
10019 if (visitUnaryFloatCall(I, ISD::FSINH))
10020 return;
10021 break;
10022 case LibFunc_cosh:
10023 case LibFunc_coshf:
10024 case LibFunc_coshl:
10025 if (visitUnaryFloatCall(I, ISD::FCOSH))
10026 return;
10027 break;
10028 case LibFunc_tanh:
10029 case LibFunc_tanhf:
10030 case LibFunc_tanhl:
10031 if (visitUnaryFloatCall(I, ISD::FTANH))
10032 return;
10033 break;
10034 case LibFunc_sqrt:
10035 case LibFunc_sqrtf:
10036 case LibFunc_sqrtl:
10037 case LibFunc_sqrt_finite:
10038 case LibFunc_sqrtf_finite:
10039 case LibFunc_sqrtl_finite:
10040 if (visitUnaryFloatCall(I, ISD::FSQRT))
10041 return;
10042 break;
10043 case LibFunc_log2:
10044 case LibFunc_log2f:
10045 case LibFunc_log2l:
10046 if (visitUnaryFloatCall(I, ISD::FLOG2))
10047 return;
10048 break;
10049 case LibFunc_exp2:
10050 case LibFunc_exp2f:
10051 case LibFunc_exp2l:
10052 if (visitUnaryFloatCall(I, ISD::FEXP2))
10053 return;
10054 break;
10055 case LibFunc_exp10:
10056 case LibFunc_exp10f:
10057 case LibFunc_exp10l:
10058 if (visitUnaryFloatCall(I, ISD::FEXP10))
10059 return;
10060 break;
10061 case LibFunc_ldexp:
10062 case LibFunc_ldexpf:
10063 case LibFunc_ldexpl:
10064 if (visitBinaryFloatCall(I, ISD::FLDEXP))
10065 return;
10066 break;
10067 case LibFunc_strstr:
10068 if (visitStrstrCall(I))
10069 return;
10070 break;
10071 case LibFunc_memcmp:
10072 if (visitMemCmpBCmpCall(I))
10073 return;
10074 break;
10075 case LibFunc_memccpy:
10076 if (visitMemCCpyCall(I))
10077 return;
10078 break;
10079 case LibFunc_mempcpy:
10080 if (visitMemPCpyCall(I))
10081 return;
10082 break;
10083 case LibFunc_memchr:
10084 if (visitMemChrCall(I))
10085 return;
10086 break;
10087 case LibFunc_strcpy:
10088 if (visitStrCpyCall(I, false))
10089 return;
10090 break;
10091 case LibFunc_stpcpy:
10092 if (visitStrCpyCall(I, true))
10093 return;
10094 break;
10095 case LibFunc_strcmp:
10096 if (visitStrCmpCall(I))
10097 return;
10098 break;
10099 case LibFunc_strlen:
10100 if (visitStrLenCall(I))
10101 return;
10102 break;
10103 case LibFunc_strnlen:
10104 if (visitStrNLenCall(I))
10105 return;
10106 break;
10107 }
10108 }
10109 }
10110
10111 if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
10112 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
10113 return;
10114 }
10115
10116 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
10117 // have to do anything here to lower funclet bundles.
10118 // CFGuardTarget bundles are lowered in LowerCallTo.
10120 I, "calls",
10125
10126 SDValue Callee = getValue(I.getCalledOperand());
10127
10128 if (I.hasDeoptState())
10129 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
10130 else
10131 // Check if we can potentially perform a tail call. More detailed checking
10132 // is be done within LowerCallTo, after more information about the call is
10133 // known.
10134 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
10135}
10136
10138 const CallBase &CB, const BasicBlock *EHPadBB) {
10139 auto PAB = CB.getOperandBundle("ptrauth");
10140 const Value *CalleeV = CB.getCalledOperand();
10141
10142 // Gather the call ptrauth data from the operand bundle:
10143 // [ i32 <key>, i64 <discriminator> ]
10144 const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
10145 const Value *Discriminator = PAB->Inputs[1];
10146
10147 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
10148 assert(Discriminator->getType()->isIntegerTy(64) &&
10149 "Invalid ptrauth discriminator");
10150
10151 // Look through ptrauth constants to find the raw callee.
10152 // Do a direct unauthenticated call if we found it and everything matches.
10153 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
10154 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
10155 DAG.getDataLayout()))
10156 return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
10157 CB.isMustTailCall(), EHPadBB);
10158
10159 // Functions should never be ptrauth-called directly.
10160 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
10161
10162 // Otherwise, do an authenticated indirect call.
10163 TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
10164 getValue(Discriminator)};
10165
10166 LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
10167 EHPadBB, &PAI);
10168}
10169
10170namespace {
10171
10172/// AsmOperandInfo - This contains information for each constraint that we are
10173/// lowering.
10174class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
10175public:
10176 /// CallOperand - If this is the result output operand or a clobber
10177 /// this is null, otherwise it is the incoming operand to the CallInst.
10178 /// This gets modified as the asm is processed.
10179 SDValue CallOperand;
10180
10181 /// AssignedRegs - If this is a register or register class operand, this
10182 /// contains the set of register corresponding to the operand.
10183 RegsForValue AssignedRegs;
10184
10185 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
10186 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
10187 }
10188
10189 /// Whether or not this operand accesses memory
10190 bool hasMemory(const TargetLowering &TLI) const {
10191 // Indirect operand accesses access memory.
10192 if (isIndirect)
10193 return true;
10194
10195 for (const auto &Code : Codes)
10196 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
10197 return true;
10198
10199 return false;
10200 }
10201};
10202
10203
10204} // end anonymous namespace
10205
10206/// Make sure that the output operand \p OpInfo and its corresponding input
10207/// operand \p MatchingOpInfo have compatible constraint types (otherwise error
10208/// out).
10209static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
10210 SDISelAsmOperandInfo &MatchingOpInfo,
10211 SelectionDAG &DAG) {
10212 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
10213 return;
10214
10216 const auto &TLI = DAG.getTargetLoweringInfo();
10217
10218 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
10219 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
10220 OpInfo.ConstraintVT);
10221 std::pair<unsigned, const TargetRegisterClass *> InputRC =
10222 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
10223 MatchingOpInfo.ConstraintVT);
10224 const bool OutOpIsIntOrFP =
10225 OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
10226 const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
10227 MatchingOpInfo.ConstraintVT.isFloatingPoint();
10228 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
10229 // FIXME: error out in a more elegant fashion
10230 report_fatal_error("Unsupported asm: input constraint"
10231 " with a matching output constraint of"
10232 " incompatible type!");
10233 }
10234 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
10235}
10236
10237/// Get a direct memory input to behave well as an indirect operand.
10238/// This may introduce stores, hence the need for a \p Chain.
10239/// \return The (possibly updated) chain.
10240static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
10241 SDISelAsmOperandInfo &OpInfo,
10242 SelectionDAG &DAG) {
10244
10245 // If we don't have an indirect input, put it in the constpool if we can,
10246 // otherwise spill it to a stack slot.
10247 // TODO: This isn't quite right. We need to handle these according to
10248 // the addressing mode that the constraint wants. Also, this may take
10249 // an additional register for the computation and we don't want that
10250 // either.
10251
10252 // If the operand is a float, integer, or vector constant, spill to a
10253 // constant pool entry to get its address.
10254 const Value *OpVal = OpInfo.CallOperandVal;
10255 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
10257 OpInfo.CallOperand = DAG.getConstantPool(
10258 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
10259 return Chain;
10260 }
10261
10262 // Otherwise, create a stack slot and emit a store to it before the asm.
10263 Type *Ty = OpVal->getType();
10264 auto &DL = DAG.getDataLayout();
10265 TypeSize TySize = DL.getTypeAllocSize(Ty);
10268 int StackID = 0;
10269 if (TySize.isScalable())
10270 StackID = TFI->getStackIDForScalableVectors();
10271 int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
10272 DL.getPrefTypeAlign(Ty), false,
10273 nullptr, StackID);
10274 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
10275 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
10277 TLI.getMemValueType(DL, Ty));
10278 OpInfo.CallOperand = StackSlot;
10279
10280 return Chain;
10281}
10282
10283/// GetRegistersForValue - Assign registers (virtual or physical) for the
10284/// specified operand. We prefer to assign virtual registers, to allow the
10285/// register allocator to handle the assignment process. However, if the asm
10286/// uses features that we can't model on machineinstrs, we have SDISel do the
10287/// allocation. This produces generally horrible, but correct, code.
10288///
10289/// OpInfo describes the operand
10290/// RefOpInfo describes the matching operand if any, the operand otherwise
10291static std::optional<unsigned>
10293 SDISelAsmOperandInfo &OpInfo,
10294 SDISelAsmOperandInfo &RefOpInfo) {
10295 LLVMContext &Context = *DAG.getContext();
10297
10301
10302 // No work to do for memory/address operands.
10303 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
10304 OpInfo.ConstraintType == TargetLowering::C_Address)
10305 return std::nullopt;
10306
10307 // If this is a constraint for a single physreg, or a constraint for a
10308 // register class, find it.
10309 unsigned AssignedReg;
10310 const TargetRegisterClass *RC;
10311 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
10312 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
10313 // RC is unset only on failure. Return immediately.
10314 if (!RC)
10315 return std::nullopt;
10316
10317 // Get the actual register value type. This is important, because the user
10318 // may have asked for (e.g.) the AX register in i32 type. We need to
10319 // remember that AX is actually i16 to get the right extension.
10320 const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
10321
10322 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
10323 // If this is an FP operand in an integer register (or visa versa), or more
10324 // generally if the operand value disagrees with the register class we plan
10325 // to stick it in, fix the operand type.
10326 //
10327 // If this is an input value, the bitcast to the new type is done now.
10328 // Bitcast for output value is done at the end of visitInlineAsm().
10329 if ((OpInfo.Type == InlineAsm::isOutput ||
10330 OpInfo.Type == InlineAsm::isInput) &&
10331 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
10332 // Try to convert to the first EVT that the reg class contains. If the
10333 // types are identical size, use a bitcast to convert (e.g. two differing
10334 // vector types). Note: output bitcast is done at the end of
10335 // visitInlineAsm().
10336 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
10337 // Exclude indirect inputs while they are unsupported because the code
10338 // to perform the load is missing and thus OpInfo.CallOperand still
10339 // refers to the input address rather than the pointed-to value.
10340 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
10341 OpInfo.CallOperand =
10342 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
10343 OpInfo.ConstraintVT = RegVT;
10344 // If the operand is an FP value and we want it in integer registers,
10345 // use the corresponding integer type. This turns an f64 value into
10346 // i64, which can be passed with two i32 values on a 32-bit machine.
10347 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
10348 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
10349 // No integer type of that size to bitcast to (e.g. f80).
10350 if (!VT.isValid())
10351 return std::nullopt;
10352 if (OpInfo.Type == InlineAsm::isInput)
10353 OpInfo.CallOperand =
10354 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
10355 OpInfo.ConstraintVT = VT;
10356 }
10357 }
10358 }
10359
10360 // No need to allocate a matching input constraint since the constraint it's
10361 // matching to has already been allocated.
10362 if (OpInfo.isMatchingInputConstraint())
10363 return std::nullopt;
10364
10365 EVT ValueVT = OpInfo.ConstraintVT;
10366 if (OpInfo.ConstraintVT == MVT::Other)
10367 ValueVT = RegVT;
10368
10369 // Initialize NumRegs.
10370 unsigned NumRegs = 1;
10371 if (OpInfo.ConstraintVT != MVT::Other)
10372 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
10373
10374 // If this is a constraint for a specific physical register, like {r17},
10375 // assign it now.
10376
10377 // If this associated to a specific register, initialize iterator to correct
10378 // place. If virtual, make sure we have enough registers
10379
10380 // Initialize iterator if necessary
10383
10384 // Do not check for single registers.
10385 if (AssignedReg) {
10386 I = std::find(I, RC->end(), AssignedReg);
10387 if (I == RC->end()) {
10388 // RC does not contain the selected register, which indicates a
10389 // mismatch between the register and the required type/bitwidth.
10390 return {AssignedReg};
10391 }
10392 }
10393
10394 for (; NumRegs; --NumRegs, ++I) {
10395 assert(I != RC->end() && "Ran out of registers to allocate!");
10396 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
10397 Regs.push_back(R);
10398 }
10399
10400 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
10401 return std::nullopt;
10402}
10403
10404static unsigned
10406 const std::vector<SDValue> &AsmNodeOperands) {
10407 // Scan until we find the definition we already emitted of this operand.
10408 unsigned CurOp = InlineAsm::Op_FirstOperand;
10409 for (; OperandNo; --OperandNo) {
10410 // Advance to the next operand.
10411 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
10412 const InlineAsm::Flag F(OpFlag);
10413 assert(
10414 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
10415 "Skipped past definitions?");
10416 CurOp += F.getNumOperandRegisters() + 1;
10417 }
10418 return CurOp;
10419}
10420
10421namespace {
10422
10423class ExtraFlags {
10424 unsigned Flags = 0;
10425
10426public:
10427 explicit ExtraFlags(const CallBase &Call) {
10428 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
10429 if (IA->hasSideEffects())
10431 if (IA->isAlignStack())
10433 if (IA->canThrow())
10435 if (Call.isConvergent())
10437 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
10438 }
10439
10440 void update(const TargetLowering::AsmOperandInfo &OpInfo) {
10441 // Ideally, we would only check against memory constraints. However, the
10442 // meaning of an Other constraint can be target-specific and we can't easily
10443 // reason about it. Therefore, be conservative and set MayLoad/MayStore
10444 // for Other constraints as well.
10447 if (OpInfo.Type == InlineAsm::isInput)
10449 else if (OpInfo.Type == InlineAsm::isOutput)
10451 else if (OpInfo.Type == InlineAsm::isClobber)
10453 }
10454 }
10455
10456 unsigned get() const { return Flags; }
10457};
10458
10459} // end anonymous namespace
10460
10461static bool isFunction(SDValue Op) {
10462 if (Op && Op.getOpcode() == ISD::GlobalAddress) {
10463 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10464 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
10465
10466 // In normal "call dllimport func" instruction (non-inlineasm) it force
10467 // indirect access by specifing call opcode. And usually specially print
10468 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
10469 // not do in this way now. (In fact, this is similar with "Data Access"
10470 // action). So here we ignore dllimport function.
10471 if (Fn && !Fn->hasDLLImportStorageClass())
10472 return true;
10473 }
10474 }
10475 return false;
10476}
10477
10478namespace {
10479
10480struct ConstraintDecisionInfo {
10481 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
10482 std::vector<SDValue> AsmNodeOperands;
10483 SDValue Glue, Chain;
10484 bool HasSideEffect = false;
10485 MCSymbol *BeginLabel = nullptr;
10486
10487 SmallVector<char> Buffer;
10488 raw_svector_ostream ErrorMsg;
10489
10490 ConstraintDecisionInfo() : ErrorMsg(Buffer) {}
10491};
10492
10493} // end anonymous namespace
10494
10495/// Construct operand info objects.
10496static bool
10497constructOperandInfo(ConstraintDecisionInfo &Info,
10498 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10499 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10500 ExtraFlags &ExtraInfo) {
10501 for (auto &T : TargetConstraints) {
10502 Info.ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
10503 SDISelAsmOperandInfo &OpInfo = Info.ConstraintOperands.back();
10504
10505 if (OpInfo.CallOperandVal)
10506 OpInfo.CallOperand = Builder.getValue(OpInfo.CallOperandVal);
10507
10508 if (!Info.HasSideEffect)
10509 Info.HasSideEffect = OpInfo.hasMemory(TLI);
10510
10511 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
10512 // FIXME: Could we compute this on OpInfo rather than T?
10513
10514 // Compute the constraint code and ConstraintType to use.
10515 TLI.ComputeConstraintToUse(T, SDValue());
10516
10517 if (T.ConstraintType == TargetLowering::C_Immediate && OpInfo.CallOperand &&
10518 !isa<ConstantSDNode>(OpInfo.CallOperand)) {
10519 // We've delayed emitting a diagnostic like the "n" constraint because
10520 // inlining could cause an integer showing up.
10521 Info.ErrorMsg << "constraint '" << T.ConstraintCode
10522 << "' expects an integer constant expression";
10523 return true;
10524 }
10525
10526 ExtraInfo.update(T);
10527 }
10528
10529 return false;
10530}
10531
10532/// Compute which constraint option to use for each operand.
10533static void
10534computeConstraintToUse(ConstraintDecisionInfo &Info, const CallBase &Call,
10535 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10536 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10537 const TargetMachine &TM, SelectionDAG &DAG) {
10538 const auto *IA = cast<InlineAsm>(Call.getCalledOperand());
10540 IA->collectAsmStrs(AsmStrs);
10541
10542 int OpNo = -1;
10543 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10544 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
10545 OpNo++;
10546
10547 // If this is an output operand with a matching input operand, look up the
10548 // matching input. If their types mismatch, e.g. one is an integer, the
10549 // other is floating point, or their sizes are different, flag it as an
10550 // error.
10551 if (OpInfo.hasMatchingInput()) {
10552 SDISelAsmOperandInfo &Input =
10553 Info.ConstraintOperands[OpInfo.MatchingInput];
10554 patchMatchingInput(OpInfo, Input, DAG);
10555 }
10556
10557 // Compute the constraint code and ConstraintType to use.
10558 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
10559
10560 if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
10561 OpInfo.Type == InlineAsm::isClobber) ||
10562 OpInfo.ConstraintType == TargetLowering::C_Address)
10563 continue;
10564
10565 // In Linux PIC model, there are 4 cases about value/label addressing:
10566 //
10567 // 1: Function call or Label jmp inside the module.
10568 // 2: Data access (such as global variable, static variable) inside module.
10569 // 3: Function call or Label jmp outside the module.
10570 // 4: Data access (such as global variable) outside the module.
10571 //
10572 // Due to current llvm inline asm architecture designed to not "recognize"
10573 // the asm code, there are quite troubles for us to treat mem addressing
10574 // differently for same value/adress used in different instructions.
10575 // For example, in pic model, call a func may in plt way or direclty
10576 // pc-related, but lea/mov a function adress may use got.
10577 //
10578 // Here we try to "recognize" function call for the case 1 and case 3 in
10579 // inline asm. And try to adjust the constraint for them.
10580 //
10581 // TODO: Due to current inline asm didn't encourage to jmp to the outsider
10582 // label, so here we don't handle jmp function label now, but we need to
10583 // enhance it (especilly in PIC model) if we meet meaningful requirements.
10584 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
10585 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
10587 OpInfo.isIndirect = false;
10588 OpInfo.ConstraintType = TargetLowering::C_Address;
10589 }
10590
10591 // If this is a memory input, and if the operand is not indirect, do what we
10592 // need to provide an address for the memory input.
10593 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
10594 !OpInfo.isIndirect) {
10595 assert((OpInfo.isMultipleAlternative ||
10596 (OpInfo.Type == InlineAsm::isInput)) &&
10597 "Can only indirectify direct input operands!");
10598
10599 // Memory operands really want the address of the value.
10600 Info.Chain = getAddressForMemoryInput(Info.Chain, Builder.getCurSDLoc(),
10601 OpInfo, DAG);
10602
10603 // There is no longer a Value* corresponding to this operand.
10604 OpInfo.CallOperandVal = nullptr;
10605
10606 // It is now an indirect operand.
10607 OpInfo.isIndirect = true;
10608 }
10609 }
10610}
10611
10612/// Prepare DAG-level operands. As part of this, assign virtual and physical
10613/// registers for inputs and output.
10614static bool prepareDAGLevelOperands(ConstraintDecisionInfo &Info,
10615 const CallBase &Call,
10616 SelectionDAGBuilder &Builder,
10617 const TargetLowering &TLI,
10618 SelectionDAG &DAG) {
10619 SDLoc DL = Builder.getCurSDLoc();
10620 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10621 // Assign Registers.
10622 SDISelAsmOperandInfo &RefOpInfo =
10623 OpInfo.isMatchingInputConstraint()
10624 ? Info.ConstraintOperands[OpInfo.getMatchedOperand()]
10625 : OpInfo;
10626 const auto RegError = getRegistersForValue(DAG, DL, OpInfo, RefOpInfo);
10627 if (RegError) {
10628 const MachineFunction &MF = DAG.getMachineFunction();
10630 const char *RegName = TRI.getName(*RegError);
10631 Info.ErrorMsg << "register '" << RegName << "' allocated for constraint '"
10632 << OpInfo.ConstraintCode
10633 << "' does not match required type";
10634 return true;
10635 }
10636
10637 auto DetectWriteToReservedRegister = [&]() {
10638 const MachineFunction &MF = DAG.getMachineFunction();
10640
10641 for (Register Reg : OpInfo.AssignedRegs.Regs) {
10642 if (Reg.isPhysical() && TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
10643 Info.ErrorMsg << "write to reserved register '"
10644 << TRI.getRegAsmName(Reg) << "'";
10645 return true;
10646 }
10647 }
10648
10649 return false;
10650 };
10651 assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10652 (OpInfo.Type == InlineAsm::isInput &&
10653 !OpInfo.isMatchingInputConstraint())) &&
10654 "Only address as input operand is allowed.");
10655
10656 switch (OpInfo.Type) {
10658 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10659 const InlineAsm::ConstraintCode ConstraintID =
10660 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10662 "Failed to convert memory constraint code to constraint id.");
10663
10664 // Add information to the INLINEASM node to know about this output.
10666 OpFlags.setMemConstraint(ConstraintID);
10667 Info.AsmNodeOperands.push_back(
10668 DAG.getTargetConstant(OpFlags, DL, MVT::i32));
10669 Info.AsmNodeOperands.push_back(OpInfo.CallOperand);
10670 } else {
10671 // Otherwise, this outputs to a register (directly for C_Register /
10672 // C_RegisterClass, and a target-defined fashion for
10673 // C_Immediate/C_Other). Find a register that we can use.
10674 if (OpInfo.AssignedRegs.Regs.empty()) {
10675 Info.ErrorMsg << "could not allocate output register for "
10676 << "constraint '" << OpInfo.ConstraintCode << "'";
10677 return true;
10678 }
10679
10680 if (DetectWriteToReservedRegister())
10681 return true;
10682
10683 // Add information to the INLINEASM node to know that this register is
10684 // set.
10685 OpInfo.AssignedRegs.AddInlineAsmOperands(
10686 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10688 false, 0, DL, DAG, Info.AsmNodeOperands);
10689 }
10690 break;
10691
10692 case InlineAsm::isInput:
10693 case InlineAsm::isLabel: {
10694 SDValue InOperandVal = OpInfo.CallOperand;
10695
10696 if (OpInfo.isMatchingInputConstraint()) {
10697 // If this is required to match an output register we have already set,
10698 // just use its register.
10699 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10700 Info.AsmNodeOperands);
10701 InlineAsm::Flag Flag(Info.AsmNodeOperands[CurOp]->getAsZExtVal());
10702 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10703 if (OpInfo.isIndirect) {
10704 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10705 Info.ErrorMsg << "inline asm not supported yet: cannot handle "
10706 << "tied indirect register inputs";
10707 return true;
10708 }
10709
10714 auto *R = cast<RegisterSDNode>(Info.AsmNodeOperands[CurOp + 1]);
10715 Register TiedReg = R->getReg();
10716 MVT RegVT = R->getSimpleValueType(0);
10717 const TargetRegisterClass *RC =
10718 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg)
10719 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10720 : TRI.getMinimalPhysRegClass(TiedReg);
10721 for (unsigned I = 0, E = Flag.getNumOperandRegisters(); I != E; ++I)
10722 Regs.push_back(MRI.createVirtualRegister(RC));
10723
10724 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10725
10726 // Use the produced MatchedRegs object to
10727 MatchedRegs.getCopyToRegs(InOperandVal, DAG, DL, Info.Chain,
10728 &Info.Glue, &Call);
10730 OpInfo.getMatchedOperand(), DL, DAG,
10731 Info.AsmNodeOperands);
10732 break;
10733 }
10734
10735 assert(Flag.isMemKind() && "Unknown matching constraint!");
10736 assert(Flag.getNumOperandRegisters() == 1 &&
10737 "Unexpected number of operands");
10738
10739 // Add information to the INLINEASM node to know about this input.
10740 // See InlineAsm.h isUseOperandTiedToDef.
10741 Flag.clearMemConstraint();
10742 Flag.setMatchingOp(OpInfo.getMatchedOperand());
10743 Info.AsmNodeOperands.push_back(DAG.getTargetConstant(
10744 Flag, DL, TLI.getPointerTy(DAG.getDataLayout())));
10745 Info.AsmNodeOperands.push_back(Info.AsmNodeOperands[CurOp + 1]);
10746 break;
10747 }
10748
10749 // Treat indirect 'X' constraint as memory.
10750 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10751 OpInfo.isIndirect)
10752 OpInfo.ConstraintType = TargetLowering::C_Memory;
10753
10754 if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10755 OpInfo.ConstraintType == TargetLowering::C_Other) {
10756 std::vector<SDValue> Ops;
10757 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10758 Ops, DAG);
10759 if (Ops.empty()) {
10760 if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10761 if (isa<ConstantSDNode>(InOperandVal)) {
10762 Info.ErrorMsg << "value out of range for constraint '"
10763 << OpInfo.ConstraintCode << "'";
10764 return true;
10765 }
10766
10767 Info.ErrorMsg << "invalid operand for inline asm constraint '"
10768 << OpInfo.ConstraintCode << "'";
10769 return true;
10770 }
10771
10772 // Add information to the INLINEASM node to know about this input.
10773 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10774 Info.AsmNodeOperands.push_back(DAG.getTargetConstant(
10775 ResOpType, DL, TLI.getPointerTy(DAG.getDataLayout())));
10776 llvm::append_range(Info.AsmNodeOperands, Ops);
10777 break;
10778 }
10779
10780 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10781 assert((OpInfo.isIndirect ||
10782 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10783 "Operand must be indirect to be a mem!");
10784 assert(InOperandVal.getValueType() ==
10785 TLI.getPointerTy(DAG.getDataLayout()) &&
10786 "Memory operands expect pointer values");
10787
10788 const InlineAsm::ConstraintCode ConstraintID =
10789 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10791 "Failed to convert memory constraint code to constraint id.");
10792
10793 // Add information to the INLINEASM node to know about this input.
10795 ResOpType.setMemConstraint(ConstraintID);
10796 Info.AsmNodeOperands.push_back(
10797 DAG.getTargetConstant(ResOpType, DL, MVT::i32));
10798 Info.AsmNodeOperands.push_back(InOperandVal);
10799 break;
10800 }
10801
10802 if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10803 const InlineAsm::ConstraintCode ConstraintID =
10804 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10806 "Failed to convert memory constraint code to constraint id.");
10807
10809
10810 SDValue AsmOp = InOperandVal;
10811 if (TLI.supportsInlineAsmFuncOperands() && isFunction(InOperandVal)) {
10812 auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10813 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10814 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10815 InOperandVal.getValueType(),
10816 GA->getOffset());
10817 }
10818
10819 // Add information to the INLINEASM node to know about this input.
10820 ResOpType.setMemConstraint(ConstraintID);
10821
10822 Info.AsmNodeOperands.push_back(
10823 DAG.getTargetConstant(ResOpType, DL, MVT::i32));
10824 Info.AsmNodeOperands.push_back(AsmOp);
10825 break;
10826 }
10827
10828 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10829 OpInfo.ConstraintType != TargetLowering::C_Register) {
10830 Info.ErrorMsg << "unknown asm constraint '" << OpInfo.ConstraintCode
10831 << "'";
10832 return true;
10833 }
10834
10835 // TODO: Support this.
10836 if (OpInfo.isIndirect) {
10837 Info.ErrorMsg << "cannot handle indirect register inputs yet for "
10838 << "constraint '" << OpInfo.ConstraintCode << "'";
10839 return true;
10840 }
10841
10842 // Copy the input into the appropriate registers.
10843 if (OpInfo.AssignedRegs.Regs.empty()) {
10844 Info.ErrorMsg << "could not allocate input reg for constraint '"
10845 << OpInfo.ConstraintCode << "'";
10846 return true;
10847 }
10848
10849 if (DetectWriteToReservedRegister())
10850 return true;
10851
10852 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, DL, Info.Chain,
10853 &Info.Glue, &Call);
10854 OpInfo.AssignedRegs.AddInlineAsmOperands(
10855 InlineAsm::Kind::RegUse, false, 0, DL, DAG, Info.AsmNodeOperands);
10856 break;
10857 }
10858
10860 // Add the clobbered value to the operand list, so that the register
10861 // allocator is aware that the physreg got clobbered.
10862 if (!OpInfo.AssignedRegs.Regs.empty())
10863 OpInfo.AssignedRegs.AddInlineAsmOperands(
10864 InlineAsm::Kind::Clobber, false, 0, DL, DAG, Info.AsmNodeOperands);
10865 break;
10866 }
10867 }
10868
10869 return false;
10870}
10871
10872/// DetermineConstraints - Find the constraints to use for inline asm operands.
10873static bool
10874determineConstraints(ConstraintDecisionInfo &Info,
10875 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10876 const CallBase &Call, SelectionDAGBuilder &Builder,
10877 const TargetLowering &TLI, const TargetMachine &TM,
10878 SelectionDAG &DAG, const BasicBlock *EHPadBB) {
10879 const auto *IA = cast<InlineAsm>(Call.getCalledOperand());
10880 ExtraFlags ExtraInfo(Call);
10881
10882 // First pass: Construct operand info objects.
10883 Info.HasSideEffect = IA->hasSideEffects();
10884 if (constructOperandInfo(Info, TargetConstraints, Builder, TLI, ExtraInfo))
10885 return true;
10886
10887 // We won't need to flush pending loads if this asm doesn't touch
10888 // memory and is nonvolatile.
10889 Info.Chain = Info.HasSideEffect ? Builder.getRoot() : DAG.getRoot();
10890
10891 bool IsCallBr = isa<CallBrInst>(Call);
10892 bool EmitEHLabels = isa<InvokeInst>(Call);
10893 if (IsCallBr || EmitEHLabels)
10894 // If this is a callbr or invoke we need to flush pending exports since
10895 // inlineasm_br and invoke are terminators.
10896 // We need to do this before nodes are glued to the inlineasm_br node.
10897 Info.Chain = Builder.getControlRoot();
10898
10899 if (EmitEHLabels)
10900 Info.Chain = Builder.lowerStartEH(Info.Chain, EHPadBB, Info.BeginLabel);
10901
10902 // Second pass: Compute which constraint option to use.
10903 computeConstraintToUse(Info, Call, TargetConstraints, Builder, TLI, TM, DAG);
10904
10905 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10906 Info.AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
10907 Info.AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
10908 IA->getAsmString().data(), TLI.getProgramPointerTy(DAG.getDataLayout())));
10909
10910 // If we have a !srcloc metadata node associated with it, we want to attach
10911 // this to the ultimately generated inline asm machineinstr. To do this, we
10912 // pass in the third operand as this (potentially null) inline asm MDNode.
10913 const MDNode *SrcLoc = Call.getMetadata("srcloc");
10914 Info.AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
10915
10916 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10917 // bits as operand 3.
10918 Info.AsmNodeOperands.push_back(
10919 DAG.getTargetConstant(ExtraInfo.get(), Builder.getCurSDLoc(),
10920 TLI.getPointerTy(DAG.getDataLayout())));
10921
10922 // Third pass: Prepare DAG-level operands
10923 return prepareDAGLevelOperands(Info, Call, Builder, TLI, DAG);
10924}
10925
10926/// visitInlineAsm - Handle a call to an InlineAsm object.
10927void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
10928 const BasicBlock *EHPadBB) {
10929 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10931 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
10932
10933 assert((!isa<InvokeInst>(Call) || EHPadBB) &&
10934 "InvokeInst must have an EHPadBB");
10935
10936 ConstraintDecisionInfo Info;
10937 if (determineConstraints(Info, TargetConstraints, Call, *this, TLI, TM, DAG,
10938 EHPadBB))
10939 return emitInlineAsmError(Call, Info.ErrorMsg.str());
10940
10941 SDValue Glue = Info.Glue;
10942 SDValue Chain = Info.Chain;
10943
10944 // Finish up input operands. Set the input chain and add the flag last.
10945 Info.AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10946 if (Glue.getNode())
10947 Info.AsmNodeOperands.push_back(Glue);
10948
10949 bool IsCallBr = isa<CallBrInst>(Call);
10950 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10951 Chain =
10952 DAG.getNode(ISDOpc, getCurSDLoc(), DAG.getVTList(MVT::Other, MVT::Glue),
10953 Info.AsmNodeOperands);
10954 Glue = Chain.getValue(1);
10955
10956 // Do additional work to generate outputs.
10957
10958 SmallVector<EVT, 1> ResultVTs;
10959 SmallVector<SDValue, 1> ResultValues;
10960 SmallVector<SDValue, 8> OutChains;
10961
10962 llvm::Type *CallResultType = Call.getType();
10963 ArrayRef<Type *> ResultTypes;
10964 if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10965 ResultTypes = StructResult->elements();
10966 else if (!CallResultType->isVoidTy())
10967 ResultTypes = ArrayRef(CallResultType);
10968
10969 auto CurResultType = ResultTypes.begin();
10970 auto handleRegAssign = [&](SDValue V) {
10971 assert(CurResultType != ResultTypes.end() && "Unexpected value");
10972 assert((*CurResultType)->isSized() && "Unexpected unsized type");
10973 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10974 ++CurResultType;
10975 // If the type of the inline asm call site return value is different but has
10976 // same size as the type of the asm output bitcast it. One example of this
10977 // is for vectors with different width / number of elements. This can
10978 // happen for register classes that can contain multiple different value
10979 // types. The preg or vreg allocated may not have the same VT as was
10980 // expected.
10981 //
10982 // This can also happen for a return value that disagrees with the register
10983 // class it is put in, eg. a double in a general-purpose register on a
10984 // 32-bit machine.
10985 if (ResultVT != V.getValueType() &&
10986 ResultVT.getSizeInBits() == V.getValueSizeInBits())
10987 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10988 else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10989 V.getValueType().isInteger()) {
10990 // If a result value was tied to an input value, the computed result
10991 // may have a wider width than the expected result. Extract the
10992 // relevant portion.
10993 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10994 }
10995 assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10996 ResultVTs.push_back(ResultVT);
10997 ResultValues.push_back(V);
10998 };
10999
11000 // Deal with output operands.
11001 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
11002 if (OpInfo.Type == InlineAsm::isOutput) {
11003 SDValue Val;
11004 // Skip trivial output operands.
11005 if (OpInfo.AssignedRegs.Regs.empty())
11006 continue;
11007
11008 switch (OpInfo.ConstraintType) {
11011 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
11012 Chain, &Glue, &Call);
11013 break;
11016 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
11017 OpInfo, DAG);
11018 break;
11020 break; // Already handled.
11022 break; // Silence warning.
11024 assert(false && "Unexpected unknown constraint");
11025 }
11026
11027 // Indirect output manifest as stores. Record output chains.
11028 if (OpInfo.isIndirect) {
11029 const Value *Ptr = OpInfo.CallOperandVal;
11030 assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
11031 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
11032 MachinePointerInfo(Ptr));
11033 OutChains.push_back(Store);
11034 } else {
11035 // generate CopyFromRegs to associated registers.
11036 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
11037 if (Val.getOpcode() == ISD::MERGE_VALUES) {
11038 for (const SDValue &V : Val->op_values())
11039 handleRegAssign(V);
11040 } else
11041 handleRegAssign(Val);
11042 }
11043 }
11044 }
11045
11046 // Set results.
11047 if (!ResultValues.empty()) {
11048 assert(CurResultType == ResultTypes.end() &&
11049 "Mismatch in number of ResultTypes");
11050 assert(ResultValues.size() == ResultTypes.size() &&
11051 "Mismatch in number of output operands in asm result");
11052
11054 DAG.getVTList(ResultVTs), ResultValues);
11055 setValue(&Call, V);
11056 }
11057
11058 // Collect store chains.
11059 if (!OutChains.empty())
11060 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
11061
11062 if (const auto *II = dyn_cast<InvokeInst>(&Call))
11063 Chain = lowerEndEH(Chain, II, EHPadBB, Info.BeginLabel);
11064
11065 // Only Update Root if inline assembly has a memory effect.
11066 if (ResultValues.empty() || Info.HasSideEffect || !OutChains.empty() ||
11067 IsCallBr || isa<InvokeInst>(Call))
11068 DAG.setRoot(Chain);
11069}
11070
11071void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
11072 const Twine &Message) {
11073 LLVMContext &Ctx = *DAG.getContext();
11074 Ctx.diagnose(DiagnosticInfoInlineAsm(Call, Message));
11075
11076 // Make sure we leave the DAG in a valid state
11077 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11078 SmallVector<EVT, 1> ValueVTs;
11079 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
11080
11081 if (ValueVTs.empty())
11082 return;
11083
11085 for (const EVT &VT : ValueVTs)
11086 Ops.push_back(DAG.getUNDEF(VT));
11087
11088 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
11089}
11090
11091void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
11092 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
11093 MVT::Other, getRoot(),
11094 getValue(I.getArgOperand(0)),
11095 DAG.getSrcValue(I.getArgOperand(0))));
11096}
11097
11098void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
11099 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11100 const DataLayout &DL = DAG.getDataLayout();
11101 SDValue V = DAG.getVAArg(
11102 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
11103 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
11104 DL.getABITypeAlign(I.getType()).value());
11105 DAG.setRoot(V.getValue(1));
11106
11107 if (I.getType()->isPointerTy())
11108 V = DAG.getPtrExtOrTrunc(
11109 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
11110 setValue(&I, V);
11111}
11112
11113void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
11114 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
11115 MVT::Other, getRoot(),
11116 getValue(I.getArgOperand(0)),
11117 DAG.getSrcValue(I.getArgOperand(0))));
11118}
11119
11120void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
11121 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
11122 MVT::Other, getRoot(),
11123 getValue(I.getArgOperand(0)),
11124 getValue(I.getArgOperand(1)),
11125 DAG.getSrcValue(I.getArgOperand(0)),
11126 DAG.getSrcValue(I.getArgOperand(1))));
11127}
11128
11130 const Instruction &I,
11131 SDValue Op) {
11132 std::optional<ConstantRange> CR = getRange(I);
11133
11134 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
11135 return Op;
11136
11137 APInt Hi = CR->getUnsignedMax();
11138 unsigned Bits = std::max(Hi.getActiveBits(),
11139 static_cast<unsigned>(IntegerType::MIN_INT_BITS));
11140
11141 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
11142
11143 SDLoc SL = getCurSDLoc();
11144
11145 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
11146 DAG.getValueType(SmallVT));
11147 unsigned NumVals = Op.getNode()->getNumValues();
11148 if (NumVals == 1)
11149 return ZExt;
11150
11152
11153 Ops.push_back(ZExt);
11154 for (unsigned I = 1; I != NumVals; ++I)
11155 Ops.push_back(Op.getValue(I));
11156
11157 return DAG.getMergeValues(Ops, SL);
11158}
11159
11161 SelectionDAG &DAG, const Instruction &I, SDValue Op) {
11162 FPClassTest Classes = getNoFPClass(I);
11163 if (Classes == fcNone)
11164 return Op;
11165
11166 SDLoc SL = getCurSDLoc();
11167 SDValue TestConst = DAG.getTargetConstant(Classes, SDLoc(), MVT::i32);
11168
11169 if (Op.getOpcode() != ISD::MERGE_VALUES) {
11170 return DAG.getNode(ISD::AssertNoFPClass, SL, Op.getValueType(), Op,
11171 TestConst);
11172 }
11173
11174 SmallVector<SDValue, 8> Ops(Op.getNumOperands());
11175 for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
11176 SDValue MergeOp = Op.getOperand(I);
11177 Ops[I] = DAG.getNode(ISD::AssertNoFPClass, SL, MergeOp.getValueType(),
11178 MergeOp, TestConst);
11179 }
11180
11181 return DAG.getMergeValues(Ops, SL);
11182}
11183
11184/// Populate a CallLowerinInfo (into \p CLI) based on the properties of
11185/// the call being lowered.
11186///
11187/// This is a helper for lowering intrinsics that follow a target calling
11188/// convention or require stack pointer adjustment. Only a subset of the
11189/// intrinsic's operands need to participate in the calling convention.
11192 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
11193 AttributeSet RetAttrs, bool IsPatchPoint) {
11195 Args.reserve(NumArgs);
11196
11197 // Populate the argument list.
11198 // Attributes for args start at offset 1, after the return attribute.
11199 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
11200 ArgI != ArgE; ++ArgI) {
11201 const Value *V = Call->getOperand(ArgI);
11202
11203 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
11204
11205 TargetLowering::ArgListEntry Entry(getValue(V), V->getType());
11206 Entry.setAttributes(Call, ArgI);
11207 Args.push_back(Entry);
11208 }
11209
11211 .setChain(getRoot())
11212 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
11213 RetAttrs)
11214 .setDiscardResult(Call->use_empty())
11215 .setIsPatchPoint(IsPatchPoint)
11217 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
11218}
11219
11220/// Add a stack map intrinsic call's live variable operands to a stackmap
11221/// or patchpoint target node's operand list.
11222///
11223/// Constants are converted to TargetConstants purely as an optimization to
11224/// avoid constant materialization and register allocation.
11225///
11226/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
11227/// generate addess computation nodes, and so FinalizeISel can convert the
11228/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
11229/// address materialization and register allocation, but may also be required
11230/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
11231/// alloca in the entry block, then the runtime may assume that the alloca's
11232/// StackMap location can be read immediately after compilation and that the
11233/// location is valid at any point during execution (this is similar to the
11234/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
11235/// only available in a register, then the runtime would need to trap when
11236/// execution reaches the StackMap in order to read the alloca's location.
11237static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
11239 SelectionDAGBuilder &Builder) {
11240 SelectionDAG &DAG = Builder.DAG;
11241 for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
11242 SDValue Op = Builder.getValue(Call.getArgOperand(I));
11243
11244 // Things on the stack are pointer-typed, meaning that they are already
11245 // legal and can be emitted directly to target nodes.
11247 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
11248 } else {
11249 // Otherwise emit a target independent node to be legalised.
11250 Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
11251 }
11252 }
11253}
11254
11255/// Lower llvm.experimental.stackmap.
11256void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
11257 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
11258 // [live variables...])
11259
11260 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
11261
11262 SDValue Chain, InGlue, Callee;
11264
11265 SDLoc DL = getCurSDLoc();
11267
11268 // The stackmap intrinsic only records the live variables (the arguments
11269 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
11270 // intrinsic, this won't be lowered to a function call. This means we don't
11271 // have to worry about calling conventions and target specific lowering code.
11272 // Instead we perform the call lowering right here.
11273 //
11274 // chain, flag = CALLSEQ_START(chain, 0, 0)
11275 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
11276 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
11277 //
11278 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
11279 InGlue = Chain.getValue(1);
11280
11281 // Add the STACKMAP operands, starting with DAG house-keeping.
11282 Ops.push_back(Chain);
11283 Ops.push_back(InGlue);
11284
11285 // Add the <id>, <numShadowBytes> operands.
11286 //
11287 // These do not require legalisation, and can be emitted directly to target
11288 // constant nodes.
11290 assert(ID.getValueType() == MVT::i64);
11291 SDValue IDConst =
11292 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
11293 Ops.push_back(IDConst);
11294
11295 SDValue Shad = getValue(CI.getArgOperand(1));
11296 assert(Shad.getValueType() == MVT::i32);
11297 SDValue ShadConst =
11298 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
11299 Ops.push_back(ShadConst);
11300
11301 // Add the live variables.
11302 addStackMapLiveVars(CI, 2, DL, Ops, *this);
11303
11304 // Create the STACKMAP node.
11305 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11306 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
11307 InGlue = Chain.getValue(1);
11308
11309 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
11310
11311 // Stackmaps don't generate values, so nothing goes into the NodeMap.
11312
11313 // Set the root to the target-lowered call chain.
11314 DAG.setRoot(Chain);
11315
11316 // Inform the Frame Information that we have a stackmap in this function.
11317 FuncInfo.MF->getFrameInfo().setHasStackMap();
11318}
11319
11320/// Lower llvm.experimental.patchpoint directly to its target opcode.
11321void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
11322 const BasicBlock *EHPadBB) {
11323 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
11324 // i32 <numBytes>,
11325 // i8* <target>,
11326 // i32 <numArgs>,
11327 // [Args...],
11328 // [live variables...])
11329
11331 bool IsAnyRegCC = CC == CallingConv::AnyReg;
11332 bool HasDef = !CB.getType()->isVoidTy();
11333 SDLoc dl = getCurSDLoc();
11335
11336 // Handle immediate and symbolic callees.
11337 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
11338 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
11339 /*isTarget=*/true);
11340 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
11341 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
11342 SDLoc(SymbolicCallee),
11343 SymbolicCallee->getValueType(0));
11344
11345 // Get the real number of arguments participating in the call <numArgs>
11347 unsigned NumArgs = NArgVal->getAsZExtVal();
11348
11349 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
11350 // Intrinsics include all meta-operands up to but not including CC.
11351 unsigned NumMetaOpers = PatchPointOpers::CCPos;
11352 assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
11353 "Not enough arguments provided to the patchpoint intrinsic");
11354
11355 // For AnyRegCC the arguments are lowered later on manually.
11356 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
11357 Type *ReturnTy =
11358 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
11359
11360 TargetLowering::CallLoweringInfo CLI(DAG);
11361 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
11362 ReturnTy, CB.getAttributes().getRetAttrs(), true);
11363 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
11364
11365 SDNode *CallEnd = Result.second.getNode();
11366 if (CallEnd->getOpcode() == ISD::EH_LABEL)
11367 CallEnd = CallEnd->getOperand(0).getNode();
11368 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
11369 CallEnd = CallEnd->getOperand(0).getNode();
11370
11371 /// Get a call instruction from the call sequence chain.
11372 /// Tail calls are not allowed.
11373 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
11374 "Expected a callseq node.");
11375 SDNode *Call = CallEnd->getOperand(0).getNode();
11376 bool HasGlue = Call->getGluedNode();
11377
11378 // Replace the target specific call node with the patchable intrinsic.
11380
11381 // Push the chain.
11382 Ops.push_back(*(Call->op_begin()));
11383
11384 // Optionally, push the glue (if any).
11385 if (HasGlue)
11386 Ops.push_back(*(Call->op_end() - 1));
11387
11388 // Push the register mask info.
11389 if (HasGlue)
11390 Ops.push_back(*(Call->op_end() - 2));
11391 else
11392 Ops.push_back(*(Call->op_end() - 1));
11393
11394 // Add the <id> and <numBytes> constants.
11396 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
11398 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
11399
11400 // Add the callee.
11401 Ops.push_back(Callee);
11402
11403 // Adjust <numArgs> to account for any arguments that have been passed on the
11404 // stack instead.
11405 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
11406 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
11407 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
11408 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
11409
11410 // Add the calling convention
11411 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
11412
11413 // Add the arguments we omitted previously. The register allocator should
11414 // place these in any free register.
11415 if (IsAnyRegCC)
11416 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
11417 Ops.push_back(getValue(CB.getArgOperand(i)));
11418
11419 // Push the arguments from the call instruction.
11420 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
11421 Ops.append(Call->op_begin() + 2, e);
11422
11423 // Push live variables for the stack map.
11424 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
11425
11426 SDVTList NodeTys;
11427 if (IsAnyRegCC && HasDef) {
11428 // Create the return types based on the intrinsic definition
11429 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11430 SmallVector<EVT, 3> ValueVTs;
11431 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
11432 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
11433
11434 // There is always a chain and a glue type at the end
11435 ValueVTs.push_back(MVT::Other);
11436 ValueVTs.push_back(MVT::Glue);
11437 NodeTys = DAG.getVTList(ValueVTs);
11438 } else
11439 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11440
11441 // Replace the target specific call node with a PATCHPOINT node.
11442 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
11443
11444 // Update the NodeMap.
11445 if (HasDef) {
11446 if (IsAnyRegCC)
11447 setValue(&CB, SDValue(PPV.getNode(), 0));
11448 else
11449 setValue(&CB, Result.first);
11450 }
11451
11452 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
11453 // call sequence. Furthermore the location of the chain and glue can change
11454 // when the AnyReg calling convention is used and the intrinsic returns a
11455 // value.
11456 if (IsAnyRegCC && HasDef) {
11457 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
11458 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
11459 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11460 } else
11461 DAG.ReplaceAllUsesWith(Call, PPV.getNode());
11462 DAG.DeleteNode(Call);
11463
11464 // Inform the Frame Information that we have a patchpoint in this function.
11465 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
11466}
11467
11468void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
11469 unsigned Intrinsic) {
11470 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11471 SDValue Op1 = getValue(I.getArgOperand(0));
11472 SDValue Op2;
11473 if (I.arg_size() > 1)
11474 Op2 = getValue(I.getArgOperand(1));
11475 SDLoc dl = getCurSDLoc();
11476 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11477 SDValue Res;
11478 SDNodeFlags SDFlags;
11479 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
11480 SDFlags.copyFMF(*FPMO);
11481
11482 switch (Intrinsic) {
11483 case Intrinsic::vector_reduce_fadd:
11484 if (SDFlags.hasAllowReassociation())
11485 Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
11486 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
11487 SDFlags);
11488 else
11489 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
11490 break;
11491 case Intrinsic::vector_reduce_fmul:
11492 if (SDFlags.hasAllowReassociation())
11493 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
11494 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
11495 SDFlags);
11496 else
11497 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
11498 break;
11499 case Intrinsic::vector_reduce_add:
11500 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
11501 break;
11502 case Intrinsic::vector_reduce_mul:
11503 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
11504 break;
11505 case Intrinsic::vector_reduce_and:
11506 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
11507 break;
11508 case Intrinsic::vector_reduce_or:
11509 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
11510 break;
11511 case Intrinsic::vector_reduce_xor:
11512 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
11513 break;
11514 case Intrinsic::vector_reduce_smax:
11515 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
11516 break;
11517 case Intrinsic::vector_reduce_smin:
11518 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
11519 break;
11520 case Intrinsic::vector_reduce_umax:
11521 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
11522 break;
11523 case Intrinsic::vector_reduce_umin:
11524 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
11525 break;
11526 case Intrinsic::vector_reduce_fmax:
11527 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
11528 break;
11529 case Intrinsic::vector_reduce_fmin:
11530 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
11531 break;
11532 case Intrinsic::vector_reduce_fmaximum:
11533 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
11534 break;
11535 case Intrinsic::vector_reduce_fminimum:
11536 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
11537 break;
11538 case Intrinsic::vector_reduce_fmaximumnum:
11539 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUMNUM, dl, VT, Op1, SDFlags);
11540 break;
11541 case Intrinsic::vector_reduce_fminimumnum:
11542 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUMNUM, dl, VT, Op1, SDFlags);
11543 break;
11544 default:
11545 llvm_unreachable("Unhandled vector reduce intrinsic");
11546 }
11547 setValue(&I, Res);
11548}
11549
11550/// Returns an AttributeList representing the attributes applied to the return
11551/// value of the given call.
11554 if (CLI.RetSExt)
11555 Attrs.push_back(Attribute::SExt);
11556 if (CLI.RetZExt)
11557 Attrs.push_back(Attribute::ZExt);
11558 if (CLI.IsInReg)
11559 Attrs.push_back(Attribute::InReg);
11560
11561 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
11562 Attrs);
11563}
11564
11565/// TargetLowering::LowerCallTo - This is the default LowerCallTo
11566/// implementation, which just calls LowerCall.
11567/// FIXME: When all targets are
11568/// migrated to using LowerCall, this hook should be integrated into SDISel.
11569std::pair<SDValue, SDValue>
11571 LLVMContext &Context = CLI.RetTy->getContext();
11572
11573 // Handle the incoming return values from the call.
11574 CLI.Ins.clear();
11575 SmallVector<Type *, 4> RetOrigTys;
11577 auto &DL = CLI.DAG.getDataLayout();
11578 ComputeValueTypes(DL, CLI.OrigRetTy, RetOrigTys, &Offsets);
11579
11580 SmallVector<EVT, 4> RetVTs;
11581 if (CLI.RetTy != CLI.OrigRetTy) {
11582 assert(RetOrigTys.size() == 1 &&
11583 "Only supported for non-aggregate returns");
11584 RetVTs.push_back(getValueType(DL, CLI.RetTy));
11585 } else {
11586 for (Type *Ty : RetOrigTys)
11587 RetVTs.push_back(getValueType(DL, Ty));
11588 }
11589
11590 if (CLI.IsPostTypeLegalization) {
11591 // If we are lowering a libcall after legalization, split the return type.
11592 SmallVector<Type *, 4> OldRetOrigTys;
11593 SmallVector<EVT, 4> OldRetVTs;
11594 SmallVector<TypeSize, 4> OldOffsets;
11595 RetOrigTys.swap(OldRetOrigTys);
11596 RetVTs.swap(OldRetVTs);
11597 Offsets.swap(OldOffsets);
11598
11599 for (size_t i = 0, e = OldRetVTs.size(); i != e; ++i) {
11600 EVT RetVT = OldRetVTs[i];
11601 uint64_t Offset = OldOffsets[i];
11602 MVT RegisterVT = getRegisterType(Context, RetVT);
11603 unsigned NumRegs = getNumRegisters(Context, RetVT);
11604 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
11605 RetOrigTys.append(NumRegs, OldRetOrigTys[i]);
11606 RetVTs.append(NumRegs, RegisterVT);
11607 for (unsigned j = 0; j != NumRegs; ++j)
11608 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
11609 }
11610 }
11611
11613 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
11614
11615 bool CanLowerReturn =
11617 CLI.IsVarArg, Outs, Context, CLI.RetTy);
11618
11619 SDValue DemoteStackSlot;
11620 int DemoteStackIdx = -100;
11621 if (!CanLowerReturn) {
11622 // FIXME: equivalent assert?
11623 // assert(!CS.hasInAllocaArgument() &&
11624 // "sret demotion is incompatible with inalloca");
11625 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
11626 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
11628 DemoteStackIdx =
11629 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
11630 Type *StackSlotPtrType = PointerType::get(Context, DL.getAllocaAddrSpace());
11631
11632 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
11633 ArgListEntry Entry(DemoteStackSlot, StackSlotPtrType);
11634 Entry.IsSRet = true;
11635 Entry.Alignment = Alignment;
11636 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
11637 CLI.NumFixedArgs += 1;
11638 CLI.getArgs()[0].IndirectType = CLI.RetTy;
11639 CLI.RetTy = CLI.OrigRetTy = Type::getVoidTy(Context);
11640
11641 // sret demotion isn't compatible with tail-calls, since the sret argument
11642 // points into the callers stack frame.
11643 CLI.IsTailCall = false;
11644 } else {
11645 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11646 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
11647 for (unsigned I = 0, E = RetVTs.size(); I != E; ++I) {
11648 ISD::ArgFlagsTy Flags;
11649 if (NeedsRegBlock) {
11650 Flags.setInConsecutiveRegs();
11651 if (I == RetVTs.size() - 1)
11652 Flags.setInConsecutiveRegsLast();
11653 }
11654 EVT VT = RetVTs[I];
11655 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11656 unsigned NumRegs =
11657 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11658 for (unsigned i = 0; i != NumRegs; ++i) {
11659 ISD::InputArg Ret(Flags, RegisterVT, VT, RetOrigTys[I],
11661 if (CLI.RetTy->isPointerTy()) {
11662 Ret.Flags.setPointer();
11664 cast<PointerType>(CLI.RetTy)->getAddressSpace());
11665 }
11666 if (CLI.RetSExt)
11667 Ret.Flags.setSExt();
11668 if (CLI.RetZExt)
11669 Ret.Flags.setZExt();
11670 if (CLI.IsInReg)
11671 Ret.Flags.setInReg();
11672 CLI.Ins.push_back(Ret);
11673 }
11674 }
11675 }
11676
11677 // We push in swifterror return as the last element of CLI.Ins.
11678 ArgListTy &Args = CLI.getArgs();
11679 if (supportSwiftError()) {
11680 for (const ArgListEntry &Arg : Args) {
11681 if (Arg.IsSwiftError) {
11682 ISD::ArgFlagsTy Flags;
11683 Flags.setSwiftError();
11685 PointerType::getUnqual(Context),
11686 /*Used=*/true, ISD::InputArg::NoArgIndex, 0);
11687 CLI.Ins.push_back(Ret);
11688 }
11689 }
11690 }
11691
11692 // Handle all of the outgoing arguments.
11693 CLI.Outs.clear();
11694 CLI.OutVals.clear();
11695 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11696 SmallVector<Type *, 4> OrigArgTys;
11697 ComputeValueTypes(DL, Args[i].OrigTy, OrigArgTys);
11698 // FIXME: Split arguments if CLI.IsPostTypeLegalization
11699 Type *FinalType = Args[i].Ty;
11700 if (Args[i].IsByVal)
11701 FinalType = Args[i].IndirectType;
11702 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11703 FinalType, CLI.CallConv, CLI.IsVarArg, DL);
11704 for (unsigned Value = 0, NumValues = OrigArgTys.size(); Value != NumValues;
11705 ++Value) {
11706 Type *OrigArgTy = OrigArgTys[Value];
11707 Type *ArgTy = OrigArgTy;
11708 if (Args[i].Ty != Args[i].OrigTy) {
11709 assert(Value == 0 && "Only supported for non-aggregate arguments");
11710 ArgTy = Args[i].Ty;
11711 }
11712
11713 EVT VT = getValueType(DL, ArgTy);
11714 SDValue Op = SDValue(Args[i].Node.getNode(),
11715 Args[i].Node.getResNo() + Value);
11716 ISD::ArgFlagsTy Flags;
11717
11718 // Certain targets (such as MIPS), may have a different ABI alignment
11719 // for a type depending on the context. Give the target a chance to
11720 // specify the alignment it wants.
11721 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11722 Flags.setOrigAlign(OriginalAlignment);
11723
11724 if (i >= CLI.NumFixedArgs)
11725 Flags.setVarArg();
11726 if (ArgTy->isPointerTy()) {
11727 Flags.setPointer();
11728 Flags.setPointerAddrSpace(cast<PointerType>(ArgTy)->getAddressSpace());
11729 }
11730 if (Args[i].IsZExt)
11731 Flags.setZExt();
11732 if (Args[i].IsSExt)
11733 Flags.setSExt();
11734 if (Args[i].IsNoExt)
11735 Flags.setNoExt();
11736 if (Args[i].IsInReg) {
11737 // If we are using vectorcall calling convention, a structure that is
11738 // passed InReg - is surely an HVA
11740 isa<StructType>(FinalType)) {
11741 // The first value of a structure is marked
11742 if (0 == Value)
11743 Flags.setHvaStart();
11744 Flags.setHva();
11745 }
11746 // Set InReg Flag
11747 Flags.setInReg();
11748 }
11749 if (Args[i].IsSRet)
11750 Flags.setSRet();
11751 if (Args[i].IsSwiftSelf)
11752 Flags.setSwiftSelf();
11753 if (Args[i].IsSwiftAsync)
11754 Flags.setSwiftAsync();
11755 if (Args[i].IsSwiftError)
11756 Flags.setSwiftError();
11757 if (Args[i].IsCFGuardTarget)
11758 Flags.setCFGuardTarget();
11759 if (Args[i].IsByVal)
11760 Flags.setByVal();
11761 if (Args[i].IsByRef)
11762 Flags.setByRef();
11763 if (Args[i].IsPreallocated) {
11764 Flags.setPreallocated();
11765 // Set the byval flag for CCAssignFn callbacks that don't know about
11766 // preallocated. This way we can know how many bytes we should've
11767 // allocated and how many bytes a callee cleanup function will pop. If
11768 // we port preallocated to more targets, we'll have to add custom
11769 // preallocated handling in the various CC lowering callbacks.
11770 Flags.setByVal();
11771 }
11772 if (Args[i].IsInAlloca) {
11773 Flags.setInAlloca();
11774 // Set the byval flag for CCAssignFn callbacks that don't know about
11775 // inalloca. This way we can know how many bytes we should've allocated
11776 // and how many bytes a callee cleanup function will pop. If we port
11777 // inalloca to more targets, we'll have to add custom inalloca handling
11778 // in the various CC lowering callbacks.
11779 Flags.setByVal();
11780 }
11781 Align MemAlign;
11782 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11783 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11784 Flags.setByValSize(FrameSize);
11785
11786 // info is not there but there are cases it cannot get right.
11787 if (auto MA = Args[i].Alignment)
11788 MemAlign = *MA;
11789 else
11790 MemAlign = getByValTypeAlignment(Args[i].IndirectType, DL);
11791 } else if (auto MA = Args[i].Alignment) {
11792 MemAlign = *MA;
11793 } else {
11794 MemAlign = OriginalAlignment;
11795 }
11796 Flags.setMemAlign(MemAlign);
11797 if (Args[i].IsNest)
11798 Flags.setNest();
11799 if (NeedsRegBlock)
11800 Flags.setInConsecutiveRegs();
11801
11802 MVT PartVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11803 unsigned NumParts =
11804 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11807
11808 if (Args[i].IsSExt)
11810 else if (Args[i].IsZExt)
11812
11813 // Conservatively only handle 'returned' on non-vectors that can be lowered,
11814 // for now.
11815 if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11817 assert((CLI.RetTy == Args[i].Ty ||
11818 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11820 Args[i].Ty->getPointerAddressSpace())) &&
11821 RetVTs.size() == NumValues && "unexpected use of 'returned'");
11822 // Before passing 'returned' to the target lowering code, ensure that
11823 // either the register MVT and the actual EVT are the same size or that
11824 // the return value and argument are extended in the same way; in these
11825 // cases it's safe to pass the argument register value unchanged as the
11826 // return register value (although it's at the target's option whether
11827 // to do so)
11828 // TODO: allow code generation to take advantage of partially preserved
11829 // registers rather than clobbering the entire register when the
11830 // parameter extension method is not compatible with the return
11831 // extension method
11832 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11833 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11834 CLI.RetZExt == Args[i].IsZExt))
11835 Flags.setReturned();
11836 }
11837
11838 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11839 CLI.CallConv, ExtendKind);
11840
11841 for (unsigned j = 0; j != NumParts; ++j) {
11842 // if it isn't first piece, alignment must be 1
11843 // For scalable vectors the scalable part is currently handled
11844 // by individual targets, so we just use the known minimum size here.
11845 ISD::OutputArg MyFlags(
11846 Flags, Parts[j].getValueType().getSimpleVT(), VT, OrigArgTy, i,
11847 j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11848 if (NumParts > 1 && j == 0)
11849 MyFlags.Flags.setSplit();
11850 else if (j != 0) {
11851 MyFlags.Flags.setOrigAlign(Align(1));
11852 if (j == NumParts - 1)
11853 MyFlags.Flags.setSplitEnd();
11854 }
11855
11856 CLI.Outs.push_back(MyFlags);
11857 CLI.OutVals.push_back(Parts[j]);
11858 }
11859
11860 if (NeedsRegBlock && Value == NumValues - 1)
11861 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11862 }
11863 }
11864
11866 CLI.Chain = LowerCall(CLI, InVals);
11867
11868 // Update CLI.InVals to use outside of this function.
11869 CLI.InVals = InVals;
11870
11871 // Verify that the target's LowerCall behaved as expected.
11872 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11873 "LowerCall didn't return a valid chain!");
11874 assert((!CLI.IsTailCall || InVals.empty()) &&
11875 "LowerCall emitted a return value for a tail call!");
11876 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11877 "LowerCall didn't emit the correct number of values!");
11878
11879 // For a tail call, the return value is merely live-out and there aren't
11880 // any nodes in the DAG representing it. Return a special value to
11881 // indicate that a tail call has been emitted and no more Instructions
11882 // should be processed in the current block.
11883 if (CLI.IsTailCall) {
11884 CLI.DAG.setRoot(CLI.Chain);
11885 return std::make_pair(SDValue(), SDValue());
11886 }
11887
11888#ifndef NDEBUG
11889 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11890 assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11891 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11892 "LowerCall emitted a value with the wrong type!");
11893 }
11894#endif
11895
11896 SmallVector<SDValue, 4> ReturnValues;
11897 if (!CanLowerReturn) {
11898 // The instruction result is the result of loading from the
11899 // hidden sret parameter.
11900 MVT PtrVT = getPointerTy(DL, DL.getAllocaAddrSpace());
11901
11902 unsigned NumValues = RetVTs.size();
11903 ReturnValues.resize(NumValues);
11904 SmallVector<SDValue, 4> Chains(NumValues);
11905
11906 // An aggregate return value cannot wrap around the address space, so
11907 // offsets to its parts don't wrap either.
11909 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11910 for (unsigned i = 0; i < NumValues; ++i) {
11912 DemoteStackSlot, CLI.DAG.getConstant(Offsets[i], CLI.DL, PtrVT),
11914 SDValue L = CLI.DAG.getLoad(
11915 RetVTs[i], CLI.DL, CLI.Chain, Add,
11917 DemoteStackIdx, Offsets[i]),
11918 HiddenSRetAlign);
11919 ReturnValues[i] = L;
11920 Chains[i] = L.getValue(1);
11921 }
11922
11923 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11924 } else {
11925 // Collect the legal value parts into potentially illegal values
11926 // that correspond to the original function's return values.
11927 std::optional<ISD::NodeType> AssertOp;
11928 if (CLI.RetSExt)
11929 AssertOp = ISD::AssertSext;
11930 else if (CLI.RetZExt)
11931 AssertOp = ISD::AssertZext;
11932 unsigned CurReg = 0;
11933 for (EVT VT : RetVTs) {
11934 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11935 unsigned NumRegs =
11936 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11937
11938 ReturnValues.push_back(getCopyFromParts(
11939 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11940 CLI.Chain, CLI.CallConv, AssertOp));
11941 CurReg += NumRegs;
11942 }
11943
11944 // For a function returning void, there is no return value. We can't create
11945 // such a node, so we just return a null return value in that case. In
11946 // that case, nothing will actually look at the value.
11947 if (ReturnValues.empty())
11948 return std::make_pair(SDValue(), CLI.Chain);
11949 }
11950
11951 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11952 CLI.DAG.getVTList(RetVTs), ReturnValues);
11953 return std::make_pair(Res, CLI.Chain);
11954}
11955
11956/// Places new result values for the node in Results (their number
11957/// and types must exactly match those of the original return values of
11958/// the node), or leaves Results empty, which indicates that the node is not
11959/// to be custom lowered after all.
11962 SelectionDAG &DAG) const {
11963 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11964
11965 if (!Res.getNode())
11966 return;
11967
11968 // If the original node has one result, take the return value from
11969 // LowerOperation as is. It might not be result number 0.
11970 if (N->getNumValues() == 1) {
11971 Results.push_back(Res);
11972 return;
11973 }
11974
11975 // If the original node has multiple results, then the return node should
11976 // have the same number of results.
11977 assert((N->getNumValues() == Res->getNumValues()) &&
11978 "Lowering returned the wrong number of results!");
11979
11980 // Places new result values base on N result number.
11981 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11982 Results.push_back(Res.getValue(I));
11983}
11984
11986 llvm_unreachable("LowerOperation not implemented for this target!");
11987}
11988
11990 Register Reg,
11991 ISD::NodeType ExtendType) {
11993 assert((Op.getOpcode() != ISD::CopyFromReg ||
11994 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11995 "Copy from a reg to the same reg!");
11996 assert(!Reg.isPhysical() && "Is a physreg");
11997
11998 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11999 // If this is an InlineAsm we have to match the registers required, not the
12000 // notional registers required by the type.
12001
12002 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
12003 std::nullopt); // This is not an ABI copy.
12004 SDValue Chain = DAG.getEntryNode();
12005
12006 if (ExtendType == ISD::ANY_EXTEND) {
12007 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
12008 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
12009 ExtendType = PreferredExtendIt->second;
12010 }
12011 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
12012 PendingExports.push_back(Chain);
12013}
12014
12016
12017/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
12018/// entry block, return true. This includes arguments used by switches, since
12019/// the switch may expand into multiple basic blocks.
12020static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
12021 // With FastISel active, we may be splitting blocks, so force creation
12022 // of virtual registers for all non-dead arguments.
12023 if (FastISel)
12024 return A->use_empty();
12025
12026 const BasicBlock &Entry = A->getParent()->front();
12027 for (const User *U : A->users())
12028 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
12029 return false; // Use not in entry block.
12030
12031 return true;
12032}
12033
12035 DenseMap<const Argument *,
12036 std::pair<const AllocaInst *, const StoreInst *>>;
12037
12038/// Scan the entry block of the function in FuncInfo for arguments that look
12039/// like copies into a local alloca. Record any copied arguments in
12040/// ArgCopyElisionCandidates.
12041static void
12043 FunctionLoweringInfo *FuncInfo,
12044 ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
12045 // Record the state of every static alloca used in the entry block. Argument
12046 // allocas are all used in the entry block, so we need approximately as many
12047 // entries as we have arguments.
12048 enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
12050 unsigned NumArgs = FuncInfo->Fn->arg_size();
12051 StaticAllocas.reserve(NumArgs * 2);
12052
12053 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
12054 if (!V)
12055 return nullptr;
12056 V = V->stripPointerCasts();
12057 const auto *AI = dyn_cast<AllocaInst>(V);
12058 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
12059 return nullptr;
12060 auto Iter = StaticAllocas.insert({AI, Unknown});
12061 return &Iter.first->second;
12062 };
12063
12064 // Look for stores of arguments to static allocas. Look through bitcasts and
12065 // GEPs to handle type coercions, as long as the alloca is fully initialized
12066 // by the store. Any non-store use of an alloca escapes it and any subsequent
12067 // unanalyzed store might write it.
12068 // FIXME: Handle structs initialized with multiple stores.
12069 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
12070 // Look for stores, and handle non-store uses conservatively.
12071 const auto *SI = dyn_cast<StoreInst>(&I);
12072 if (!SI) {
12073 // We will look through cast uses, so ignore them completely.
12074 if (I.isCast())
12075 continue;
12076 // Ignore pseudo op intrinsics, they don't escape or store to allocas.
12078 continue;
12079 // This is an unknown instruction. Assume it escapes or writes to all
12080 // static alloca operands.
12081 for (const Use &U : I.operands()) {
12082 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
12083 *Info = StaticAllocaInfo::Clobbered;
12084 }
12085 continue;
12086 }
12087
12088 // If the stored value is a static alloca, mark it as escaped.
12089 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
12090 *Info = StaticAllocaInfo::Clobbered;
12091
12092 // Check if the destination is a static alloca.
12093 const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
12094 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
12095 if (!Info)
12096 continue;
12097 const AllocaInst *AI = cast<AllocaInst>(Dst);
12098
12099 // Skip allocas that have been initialized or clobbered.
12100 if (*Info != StaticAllocaInfo::Unknown)
12101 continue;
12102
12103 // Check if the stored value is an argument, and that this store fully
12104 // initializes the alloca.
12105 // If the argument type has padding bits we can't directly forward a pointer
12106 // as the upper bits may contain garbage.
12107 // Don't elide copies from the same argument twice.
12108 const Value *Val = SI->getValueOperand()->stripPointerCasts();
12109 const auto *Arg = dyn_cast<Argument>(Val);
12110 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL);
12111 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
12112 Arg->getType()->isEmptyTy() || !AllocaSize ||
12113 DL.getTypeStoreSize(Arg->getType()) != *AllocaSize ||
12114 !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
12115 ArgCopyElisionCandidates.count(Arg)) {
12116 *Info = StaticAllocaInfo::Clobbered;
12117 continue;
12118 }
12119
12120 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
12121 << '\n');
12122
12123 // Mark this alloca and store for argument copy elision.
12124 *Info = StaticAllocaInfo::Elidable;
12125 ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
12126
12127 // Stop scanning if we've seen all arguments. This will happen early in -O0
12128 // builds, which is useful, because -O0 builds have large entry blocks and
12129 // many allocas.
12130 if (ArgCopyElisionCandidates.size() == NumArgs)
12131 break;
12132 }
12133}
12134
12135/// Try to elide argument copies from memory into a local alloca. Succeeds if
12136/// ArgVal is a load from a suitable fixed stack object.
12139 DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
12140 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
12141 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
12142 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
12143 // Check if this is a load from a fixed stack object.
12144 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
12145 if (!LNode)
12146 return;
12147 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
12148 if (!FINode)
12149 return;
12150
12151 // Check that the fixed stack object is the right size and alignment.
12152 // Look at the alignment that the user wrote on the alloca instead of looking
12153 // at the stack object.
12154 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
12155 assert(ArgCopyIter != ArgCopyElisionCandidates.end());
12156 const AllocaInst *AI = ArgCopyIter->second.first;
12157 int FixedIndex = FINode->getIndex();
12158 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
12159 int OldIndex = AllocaIndex;
12160 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
12161 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
12162 LLVM_DEBUG(
12163 dbgs() << " argument copy elision failed due to bad fixed stack "
12164 "object size\n");
12165 return;
12166 }
12167 Align RequiredAlignment = AI->getAlign();
12168 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
12169 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
12170 "greater than stack argument alignment ("
12171 << DebugStr(RequiredAlignment) << " vs "
12172 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
12173 return;
12174 }
12175
12176 // Perform the elision. Delete the old stack object and replace its only use
12177 // in the variable info map. Mark the stack object as mutable and aliased.
12178 LLVM_DEBUG({
12179 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
12180 << " Replacing frame index " << OldIndex << " with " << FixedIndex
12181 << '\n';
12182 });
12183 MFI.RemoveStackObject(OldIndex);
12184 MFI.setIsImmutableObjectIndex(FixedIndex, false);
12185 MFI.setIsAliasedObjectIndex(FixedIndex, true);
12186 AllocaIndex = FixedIndex;
12187 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
12188 for (SDValue ArgVal : ArgVals)
12189 Chains.push_back(ArgVal.getValue(1));
12190
12191 // Avoid emitting code for the store implementing the copy.
12192 const StoreInst *SI = ArgCopyIter->second.second;
12193 ElidedArgCopyInstrs.insert(SI);
12194
12195 // Check for uses of the argument again so that we can avoid exporting ArgVal
12196 // if it is't used by anything other than the store.
12197 for (const Value *U : Arg.users()) {
12198 if (U != SI) {
12199 ArgHasUses = true;
12200 break;
12201 }
12202 }
12203}
12204
12205void SelectionDAGISel::LowerArguments(const Function &F, bool FastISel) {
12206 SelectionDAG &DAG = SDB->DAG;
12207 SDLoc dl = SDB->getCurSDLoc();
12208 const DataLayout &DL = DAG.getDataLayout();
12210
12211 // In Naked functions we aren't going to save any registers.
12212 if (F.hasFnAttribute(Attribute::Naked))
12213 return;
12214
12215 if (!FuncInfo->CanLowerReturn) {
12216 // Put in an sret pointer parameter before all the other parameters.
12217 MVT ValueVT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
12218
12219 ISD::ArgFlagsTy Flags;
12220 Flags.setSRet();
12221 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVT);
12222 ISD::InputArg RetArg(Flags, RegisterVT, ValueVT, F.getReturnType(), true,
12224 Ins.push_back(RetArg);
12225 }
12226
12227 // Look for stores of arguments to static allocas. Mark such arguments with a
12228 // flag to ask the target to give us the memory location of that argument if
12229 // available.
12230 ArgCopyElisionMapTy ArgCopyElisionCandidates;
12232 ArgCopyElisionCandidates);
12233
12234 // Set up the incoming argument description vector.
12235 for (const Argument &Arg : F.args()) {
12236 unsigned ArgNo = Arg.getArgNo();
12238 ComputeValueTypes(DAG.getDataLayout(), Arg.getType(), Types);
12239 bool isArgValueUsed = !Arg.use_empty();
12240 Type *FinalType = Arg.getType();
12241 if (Arg.hasAttribute(Attribute::ByVal))
12242 FinalType = Arg.getParamByValType();
12243 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
12244 FinalType, F.getCallingConv(), F.isVarArg(), DL);
12245 for (unsigned Value = 0, NumValues = Types.size(); Value != NumValues;
12246 ++Value) {
12247 Type *ArgTy = Types[Value];
12248 EVT VT = TLI->getValueType(DL, ArgTy);
12249 ISD::ArgFlagsTy Flags;
12250
12251 if (ArgTy->isPointerTy()) {
12252 Flags.setPointer();
12253 Flags.setPointerAddrSpace(cast<PointerType>(ArgTy)->getAddressSpace());
12254 }
12255 if (Arg.hasAttribute(Attribute::ZExt))
12256 Flags.setZExt();
12257 if (Arg.hasAttribute(Attribute::SExt))
12258 Flags.setSExt();
12259 if (Arg.hasAttribute(Attribute::InReg)) {
12260 // If we are using vectorcall calling convention, a structure that is
12261 // passed InReg - is surely an HVA
12262 if (F.getCallingConv() == CallingConv::X86_VectorCall &&
12263 isa<StructType>(Arg.getType())) {
12264 // The first value of a structure is marked
12265 if (0 == Value)
12266 Flags.setHvaStart();
12267 Flags.setHva();
12268 }
12269 // Set InReg Flag
12270 Flags.setInReg();
12271 }
12272 if (Arg.hasAttribute(Attribute::StructRet))
12273 Flags.setSRet();
12274 if (Arg.hasAttribute(Attribute::SwiftSelf))
12275 Flags.setSwiftSelf();
12276 if (Arg.hasAttribute(Attribute::SwiftAsync))
12277 Flags.setSwiftAsync();
12278 if (Arg.hasAttribute(Attribute::SwiftError))
12279 Flags.setSwiftError();
12280 if (Arg.hasAttribute(Attribute::ByVal))
12281 Flags.setByVal();
12282 if (Arg.hasAttribute(Attribute::ByRef))
12283 Flags.setByRef();
12284 if (Arg.hasAttribute(Attribute::InAlloca)) {
12285 Flags.setInAlloca();
12286 // Set the byval flag for CCAssignFn callbacks that don't know about
12287 // inalloca. This way we can know how many bytes we should've allocated
12288 // and how many bytes a callee cleanup function will pop. If we port
12289 // inalloca to more targets, we'll have to add custom inalloca handling
12290 // in the various CC lowering callbacks.
12291 Flags.setByVal();
12292 }
12293 if (Arg.hasAttribute(Attribute::Preallocated)) {
12294 Flags.setPreallocated();
12295 // Set the byval flag for CCAssignFn callbacks that don't know about
12296 // preallocated. This way we can know how many bytes we should've
12297 // allocated and how many bytes a callee cleanup function will pop. If
12298 // we port preallocated to more targets, we'll have to add custom
12299 // preallocated handling in the various CC lowering callbacks.
12300 Flags.setByVal();
12301 }
12302
12303 // Certain targets (such as MIPS), may have a different ABI alignment
12304 // for a type depending on the context. Give the target a chance to
12305 // specify the alignment it wants.
12306 const Align OriginalAlignment(
12307 TLI->getABIAlignmentForCallingConv(ArgTy, DL));
12308 Flags.setOrigAlign(OriginalAlignment);
12309
12310 Align MemAlign;
12311 Type *ArgMemTy = nullptr;
12312 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
12313 Flags.isByRef()) {
12314 if (!ArgMemTy)
12315 ArgMemTy = Arg.getPointeeInMemoryValueType();
12316
12317 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
12318
12319 // For in-memory arguments, size and alignment should be passed from FE.
12320 // BE will guess if this info is not there but there are cases it cannot
12321 // get right.
12322 if (auto ParamAlign = Arg.getParamStackAlign())
12323 MemAlign = *ParamAlign;
12324 else if ((ParamAlign = Arg.getParamAlign()))
12325 MemAlign = *ParamAlign;
12326 else
12327 MemAlign = TLI->getByValTypeAlignment(ArgMemTy, DL);
12328 if (Flags.isByRef())
12329 Flags.setByRefSize(MemSize);
12330 else
12331 Flags.setByValSize(MemSize);
12332 } else if (auto ParamAlign = Arg.getParamStackAlign()) {
12333 MemAlign = *ParamAlign;
12334 } else {
12335 MemAlign = OriginalAlignment;
12336 }
12337 Flags.setMemAlign(MemAlign);
12338
12339 if (Arg.hasAttribute(Attribute::Nest))
12340 Flags.setNest();
12341 if (NeedsRegBlock)
12342 Flags.setInConsecutiveRegs();
12343 if (ArgCopyElisionCandidates.count(&Arg))
12344 Flags.setCopyElisionCandidate();
12345 if (Arg.hasAttribute(Attribute::Returned))
12346 Flags.setReturned();
12347
12348 MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
12349 *CurDAG->getContext(), F.getCallingConv(), VT);
12350 unsigned NumRegs = TLI->getNumRegistersForCallingConv(
12351 *CurDAG->getContext(), F.getCallingConv(), VT);
12352 for (unsigned i = 0; i != NumRegs; ++i) {
12353 // For scalable vectors, use the minimum size; individual targets
12354 // are responsible for handling scalable vector arguments and
12355 // return values.
12356 ISD::InputArg MyFlags(
12357 Flags, RegisterVT, VT, ArgTy, isArgValueUsed, ArgNo,
12358 i * RegisterVT.getStoreSize().getKnownMinValue());
12359 if (NumRegs > 1 && i == 0)
12360 MyFlags.Flags.setSplit();
12361 // if it isn't first piece, alignment must be 1
12362 else if (i > 0) {
12363 MyFlags.Flags.setOrigAlign(Align(1));
12364 if (i == NumRegs - 1)
12365 MyFlags.Flags.setSplitEnd();
12366 }
12367 Ins.push_back(MyFlags);
12368 }
12369 if (NeedsRegBlock && Value == NumValues - 1)
12370 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
12371 }
12372 }
12373
12374 // Call the target to set up the argument values.
12376 SDValue NewRoot = TLI->LowerFormalArguments(
12377 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
12378
12379 // Verify that the target's LowerFormalArguments behaved as expected.
12380 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
12381 "LowerFormalArguments didn't return a valid chain!");
12382 assert(InVals.size() == Ins.size() &&
12383 "LowerFormalArguments didn't emit the correct number of values!");
12384 assert(all_of(InVals, [](SDValue InVal) { return InVal.getNode(); }) &&
12385 "LowerFormalArguments emitted a null value!");
12386
12387 // Update the DAG with the new chain value resulting from argument lowering.
12388 DAG.setRoot(NewRoot);
12389
12390 // Set up the argument values.
12391 unsigned i = 0;
12392 if (!FuncInfo->CanLowerReturn) {
12393 // Create a virtual register for the sret pointer, and put in a copy
12394 // from the sret argument into it.
12395 MVT VT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
12396 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
12397 std::optional<ISD::NodeType> AssertOp;
12398 SDValue ArgValue =
12399 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
12400 F.getCallingConv(), AssertOp);
12401
12402 MachineFunction& MF = SDB->DAG.getMachineFunction();
12403 MachineRegisterInfo& RegInfo = MF.getRegInfo();
12404 Register SRetReg =
12405 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
12406 FuncInfo->DemoteRegister = SRetReg;
12407 NewRoot =
12408 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
12409 DAG.setRoot(NewRoot);
12410
12411 // i indexes lowered arguments. Bump it past the hidden sret argument.
12412 ++i;
12413 }
12414
12416 DenseMap<int, int> ArgCopyElisionFrameIndexMap;
12417 for (const Argument &Arg : F.args()) {
12418 SmallVector<SDValue, 4> ArgValues;
12419 SmallVector<EVT, 4> ValueVTs;
12420 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
12421 unsigned NumValues = ValueVTs.size();
12422 if (NumValues == 0)
12423 continue;
12424
12425 bool ArgHasUses = !Arg.use_empty();
12426
12427 // Elide the copying store if the target loaded this argument from a
12428 // suitable fixed stack object.
12429 if (Ins[i].Flags.isCopyElisionCandidate()) {
12430 unsigned NumParts = 0;
12431 for (EVT VT : ValueVTs)
12432 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
12433 F.getCallingConv(), VT);
12434
12435 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
12436 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
12437 ArrayRef(&InVals[i], NumParts), ArgHasUses);
12438 }
12439
12440 // If this argument is unused then remember its value. It is used to generate
12441 // debugging information.
12442 bool isSwiftErrorArg =
12443 TLI->supportSwiftError() &&
12444 Arg.hasAttribute(Attribute::SwiftError);
12445 if (!ArgHasUses && !isSwiftErrorArg) {
12446 SDB->setUnusedArgValue(&Arg, InVals[i]);
12447
12448 // Also remember any frame index for use in FastISel.
12449 if (FrameIndexSDNode *FI =
12451 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12452 }
12453
12454 for (unsigned Val = 0; Val != NumValues; ++Val) {
12455 EVT VT = ValueVTs[Val];
12456 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
12457 F.getCallingConv(), VT);
12458 unsigned NumParts = TLI->getNumRegistersForCallingConv(
12459 *CurDAG->getContext(), F.getCallingConv(), VT);
12460
12461 // Even an apparent 'unused' swifterror argument needs to be returned. So
12462 // we do generate a copy for it that can be used on return from the
12463 // function.
12464 if (ArgHasUses || isSwiftErrorArg) {
12465 std::optional<ISD::NodeType> AssertOp;
12466 if (Arg.hasAttribute(Attribute::SExt))
12467 AssertOp = ISD::AssertSext;
12468 else if (Arg.hasAttribute(Attribute::ZExt))
12469 AssertOp = ISD::AssertZext;
12470
12471 SDValue OutVal =
12472 getCopyFromParts(DAG, dl, &InVals[i], NumParts, PartVT, VT, nullptr,
12473 NewRoot, F.getCallingConv(), AssertOp);
12474
12475 FPClassTest NoFPClass = Arg.getNoFPClass();
12476 if (NoFPClass != fcNone) {
12477 SDValue SDNoFPClass = DAG.getTargetConstant(
12478 static_cast<uint64_t>(NoFPClass), dl, MVT::i32);
12479 OutVal = DAG.getNode(ISD::AssertNoFPClass, dl, OutVal.getValueType(),
12480 OutVal, SDNoFPClass);
12481 }
12482 ArgValues.push_back(OutVal);
12483 }
12484
12485 i += NumParts;
12486 }
12487
12488 // We don't need to do anything else for unused arguments.
12489 if (ArgValues.empty())
12490 continue;
12491
12492 // Note down frame index.
12493 if (FrameIndexSDNode *FI =
12494 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
12495 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12496
12497 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
12498 SDB->getCurSDLoc());
12499
12500 SDB->setValue(&Arg, Res);
12501 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
12502 // We want to associate the argument with the frame index, among
12503 // involved operands, that correspond to the lowest address. The
12504 // getCopyFromParts function, called earlier, is swapping the order of
12505 // the operands to BUILD_PAIR depending on endianness. The result of
12506 // that swapping is that the least significant bits of the argument will
12507 // be in the first operand of the BUILD_PAIR node, and the most
12508 // significant bits will be in the second operand.
12509 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
12510 if (LoadSDNode *LNode =
12511 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
12512 if (FrameIndexSDNode *FI =
12513 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
12514 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12515 }
12516
12517 // Analyses past this point are naive and don't expect an assertion.
12518 if (Res.getOpcode() == ISD::AssertZext)
12519 Res = Res.getOperand(0);
12520
12521 // Update the SwiftErrorVRegDefMap.
12522 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
12523 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
12524 if (Reg.isVirtual())
12525 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
12526 Reg);
12527 }
12528
12529 // If this argument is live outside of the entry block, insert a copy from
12530 // wherever we got it to the vreg that other BB's will reference it as.
12531 if (Res.getOpcode() == ISD::CopyFromReg) {
12532 // If we can, though, try to skip creating an unnecessary vreg.
12533 // FIXME: This isn't very clean... it would be nice to make this more
12534 // general.
12535 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
12536 if (Reg.isVirtual()) {
12537 FuncInfo->ValueMap[&Arg] = Reg;
12538 continue;
12539 }
12540 }
12541 if (!isOnlyUsedInEntryBlock(&Arg, FastISel)) {
12542 FuncInfo->InitializeRegForValue(&Arg);
12543 SDB->CopyToExportRegsIfNeeded(&Arg);
12544 }
12545 }
12546
12547 if (!Chains.empty()) {
12548 Chains.push_back(NewRoot);
12549 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
12550 }
12551
12552 DAG.setRoot(NewRoot);
12553
12554 assert(i == InVals.size() && "Argument register count mismatch!");
12555
12556 // If any argument copy elisions occurred and we have debug info, update the
12557 // stale frame indices used in the dbg.declare variable info table.
12558 if (!ArgCopyElisionFrameIndexMap.empty()) {
12559 for (MachineFunction::VariableDbgInfo &VI :
12560 MF->getInStackSlotVariableDbgInfo()) {
12561 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
12562 if (I != ArgCopyElisionFrameIndexMap.end())
12563 VI.updateStackSlot(I->second);
12564 }
12565 }
12566
12567 // Finally, if the target has anything special to do, allow it to do so.
12569}
12570
12571/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
12572/// ensure constants are generated when needed. Remember the virtual registers
12573/// that need to be added to the Machine PHI nodes as input. We cannot just
12574/// directly add them, because expansion might result in multiple MBB's for one
12575/// BB. As such, the start of the BB might correspond to a different MBB than
12576/// the end.
12577void
12578SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
12579 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12580
12581 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
12582
12583 // Check PHI nodes in successors that expect a value to be available from this
12584 // block.
12585 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
12586 if (!isa<PHINode>(SuccBB->begin())) continue;
12587 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
12588
12589 // If this terminator has multiple identical successors (common for
12590 // switches), only handle each succ once.
12591 if (!SuccsHandled.insert(SuccMBB).second)
12592 continue;
12593
12595
12596 // At this point we know that there is a 1-1 correspondence between LLVM PHI
12597 // nodes and Machine PHI nodes, but the incoming operands have not been
12598 // emitted yet.
12599 for (const PHINode &PN : SuccBB->phis()) {
12600 // Ignore dead phi's.
12601 if (PN.use_empty())
12602 continue;
12603
12604 // Skip empty types
12605 if (PN.getType()->isEmptyTy())
12606 continue;
12607
12608 Register Reg;
12609 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
12610
12611 if (const auto *C = dyn_cast<Constant>(PHIOp)) {
12612 Register &RegOut = ConstantsOut[C];
12613 if (!RegOut) {
12614 RegOut = FuncInfo.CreateRegs(PHIOp);
12615 // We need to zero/sign extend ConstantInt phi operands to match
12616 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
12617 ISD::NodeType ExtendType = ISD::ANY_EXTEND;
12618 if (auto *CI = dyn_cast<ConstantInt>(C))
12619 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
12621 CopyValueToVirtualRegister(C, RegOut, ExtendType);
12622 }
12623 Reg = RegOut;
12624 } else {
12625 auto I = FuncInfo.ValueMap.find(PHIOp);
12626 if (I != FuncInfo.ValueMap.end())
12627 Reg = I->second;
12628 else {
12629 assert(isa<AllocaInst>(PHIOp) &&
12630 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
12631 "Didn't codegen value into a register!??");
12632 Reg = FuncInfo.CreateRegs(PHIOp);
12634 }
12635 }
12636
12637 // Remember that this register needs to added to the machine PHI node as
12638 // the input for this MBB.
12639 SmallVector<EVT, 4> ValueVTs;
12640 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
12641 for (EVT VT : ValueVTs) {
12642 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
12643 for (unsigned i = 0; i != NumRegisters; ++i)
12644 FuncInfo.PHINodesToUpdate.emplace_back(&*MBBI++, Reg + i);
12645 Reg += NumRegisters;
12646 }
12647 }
12648 }
12649
12650 ConstantsOut.clear();
12651}
12652
12653MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
12655 if (++I == FuncInfo.MF->end())
12656 return nullptr;
12657 return &*I;
12658}
12659
12660/// During lowering new call nodes can be created (such as memset, etc.).
12661/// Those will become new roots of the current DAG, but complications arise
12662/// when they are tail calls. In such cases, the call lowering will update
12663/// the root, but the builder still needs to know that a tail call has been
12664/// lowered in order to avoid generating an additional return.
12665void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12666 // If the node is null, we do have a tail call.
12667 if (MaybeTC.getNode() != nullptr)
12668 DAG.setRoot(MaybeTC);
12669 else
12670 HasTailCall = true;
12671}
12672
12673void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12674 MachineBasicBlock *SwitchMBB,
12675 MachineBasicBlock *DefaultMBB) {
12676 MachineFunction *CurMF = FuncInfo.MF;
12677 MachineBasicBlock *NextMBB = nullptr;
12679 if (++BBI != FuncInfo.MF->end())
12680 NextMBB = &*BBI;
12681
12682 unsigned Size = W.LastCluster - W.FirstCluster + 1;
12683
12684 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12685
12686 if (Size == 2 && W.MBB == SwitchMBB) {
12687 // If any two of the cases has the same destination, and if one value
12688 // is the same as the other, but has one bit unset that the other has set,
12689 // use bit manipulation to do two compares at once. For example:
12690 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12691 // TODO: This could be extended to merge any 2 cases in switches with 3
12692 // cases.
12693 // TODO: Handle cases where W.CaseBB != SwitchBB.
12694 CaseCluster &Small = *W.FirstCluster;
12695 CaseCluster &Big = *W.LastCluster;
12696
12697 if (Small.Low == Small.High && Big.Low == Big.High &&
12698 Small.MBB == Big.MBB) {
12699 const APInt &SmallValue = Small.Low->getValue();
12700 const APInt &BigValue = Big.Low->getValue();
12701
12702 // Check that there is only one bit different.
12703 APInt CommonBit = BigValue ^ SmallValue;
12704 if (CommonBit.isPowerOf2()) {
12705 SDValue CondLHS = getValue(Cond);
12706 EVT VT = CondLHS.getValueType();
12707 SDLoc DL = getCurSDLoc();
12708
12709 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
12710 DAG.getConstant(CommonBit, DL, VT));
12711 SDValue Cond = DAG.getSetCC(
12712 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
12713 ISD::SETEQ);
12714
12715 // Update successor info.
12716 // Both Small and Big will jump to Small.BB, so we sum up the
12717 // probabilities.
12718 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
12719 if (BPI)
12720 addSuccessorWithProb(
12721 SwitchMBB, DefaultMBB,
12722 // The default destination is the first successor in IR.
12723 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12724 else
12725 addSuccessorWithProb(SwitchMBB, DefaultMBB);
12726
12727 // Insert the true branch.
12728 SDValue BrCond =
12729 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12730 DAG.getBasicBlock(Small.MBB));
12731 // Insert the false branch.
12732 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12733 DAG.getBasicBlock(DefaultMBB));
12734
12735 DAG.setRoot(BrCond);
12736 return;
12737 }
12738 }
12739 }
12740
12741 if (TM.getOptLevel() != CodeGenOptLevel::None) {
12742 // Here, we order cases by probability so the most likely case will be
12743 // checked first. However, two clusters can have the same probability in
12744 // which case their relative ordering is non-deterministic. So we use Low
12745 // as a tie-breaker as clusters are guaranteed to never overlap.
12746 llvm::sort(W.FirstCluster, W.LastCluster + 1,
12747 [](const CaseCluster &a, const CaseCluster &b) {
12748 return a.Prob != b.Prob ?
12749 a.Prob > b.Prob :
12750 a.Low->getValue().slt(b.Low->getValue());
12751 });
12752
12753 // Rearrange the case blocks so that the last one falls through if possible
12754 // without changing the order of probabilities.
12755 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12756 --I;
12757 if (I->Prob > W.LastCluster->Prob)
12758 break;
12759 if (I->Kind == CC_Range && I->MBB == NextMBB) {
12760 std::swap(*I, *W.LastCluster);
12761 break;
12762 }
12763 }
12764 }
12765
12766 // Compute total probability.
12767 BranchProbability DefaultProb = W.DefaultProb;
12768 BranchProbability UnhandledProbs = DefaultProb;
12769 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12770 UnhandledProbs += I->Prob;
12771
12772 MachineBasicBlock *CurMBB = W.MBB;
12773 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12774 bool FallthroughUnreachable = false;
12775 MachineBasicBlock *Fallthrough;
12776 if (I == W.LastCluster) {
12777 // For the last cluster, fall through to the default destination.
12778 Fallthrough = DefaultMBB;
12779 FallthroughUnreachable =
12781 } else {
12782 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12783 CurMF->insert(BBI, Fallthrough);
12784 // Put Cond in a virtual register to make it available from the new blocks.
12786 }
12787 UnhandledProbs -= I->Prob;
12788
12789 switch (I->Kind) {
12790 case CC_JumpTable: {
12791 // FIXME: Optimize away range check based on pivot comparisons.
12792 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12793 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12794
12795 // The jump block hasn't been inserted yet; insert it here.
12796 MachineBasicBlock *JumpMBB = JT->MBB;
12797 CurMF->insert(BBI, JumpMBB);
12798
12799 auto JumpProb = I->Prob;
12800 auto FallthroughProb = UnhandledProbs;
12801
12802 // If the default statement is a target of the jump table, we evenly
12803 // distribute the default probability to successors of CurMBB. Also
12804 // update the probability on the edge from JumpMBB to Fallthrough.
12805 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12806 SE = JumpMBB->succ_end();
12807 SI != SE; ++SI) {
12808 if (*SI == DefaultMBB) {
12809 JumpProb += DefaultProb / 2;
12810 FallthroughProb -= DefaultProb / 2;
12811 JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12812 JumpMBB->normalizeSuccProbs();
12813 break;
12814 }
12815 }
12816
12817 // If the default clause is unreachable, propagate that knowledge into
12818 // JTH->FallthroughUnreachable which will use it to suppress the range
12819 // check.
12820 //
12821 // However, don't do this if we're doing branch target enforcement
12822 // (e.g. Arm BTI, or the cf-protection-branch module flag used by
12823 // RISC-V Zicfilp and X86 IBT), because a table branch _without_ a
12824 // range check can be a tempting JOP gadget - out-of-bounds inputs
12825 // that are impossible in correct execution become possible again if
12826 // an attacker can influence the control flow. So if an attacker
12827 // doesn't already have a branch target enforcement bypass available,
12828 // we don't want them to be able to get one out of this table branch.
12829 if (FallthroughUnreachable) {
12830 Function &CurFunc = CurMF->getFunction();
12831 bool HasCFBranch = false;
12832 if (auto *CFBranch = mdconst::extract_or_null<ConstantInt>(
12833 CurFunc.getParent()->getModuleFlag("cf-protection-branch")))
12834 HasCFBranch = !CFBranch->isZero();
12835 if (!HasCFBranch &&
12836 !CurFunc.hasFnAttribute("branch-target-enforcement"))
12837 JTH->FallthroughUnreachable = true;
12838 }
12839
12840 if (!JTH->FallthroughUnreachable)
12841 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12842 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12843 CurMBB->normalizeSuccProbs();
12844
12845 // The jump table header will be inserted in our current block, do the
12846 // range check, and fall through to our fallthrough block.
12847 JTH->HeaderBB = CurMBB;
12848 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12849
12850 // If we're in the right place, emit the jump table header right now.
12851 if (CurMBB == SwitchMBB) {
12852 visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12853 JTH->Emitted = true;
12854 }
12855 break;
12856 }
12857 case CC_BitTests: {
12858 // FIXME: Optimize away range check based on pivot comparisons.
12859 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12860
12861 // The bit test blocks haven't been inserted yet; insert them here.
12862 for (BitTestCase &BTC : BTB->Cases)
12863 CurMF->insert(BBI, BTC.ThisBB);
12864
12865 // Fill in fields of the BitTestBlock.
12866 BTB->Parent = CurMBB;
12867 BTB->Default = Fallthrough;
12868
12869 BTB->DefaultProb = UnhandledProbs;
12870 // If the cases in bit test don't form a contiguous range, we evenly
12871 // distribute the probability on the edge to Fallthrough to two
12872 // successors of CurMBB.
12873 if (!BTB->ContiguousRange) {
12874 BTB->Prob += DefaultProb / 2;
12875 BTB->DefaultProb -= DefaultProb / 2;
12876 }
12877
12878 if (FallthroughUnreachable)
12879 BTB->FallthroughUnreachable = true;
12880
12881 // If we're in the right place, emit the bit test header right now.
12882 if (CurMBB == SwitchMBB) {
12883 visitBitTestHeader(*BTB, SwitchMBB);
12884 BTB->Emitted = true;
12885 }
12886 break;
12887 }
12888 case CC_Range: {
12889 const Value *RHS, *LHS, *MHS;
12891 if (I->Low == I->High) {
12892 // Check Cond == I->Low.
12893 CC = ISD::SETEQ;
12894 LHS = Cond;
12895 RHS=I->Low;
12896 MHS = nullptr;
12897 } else {
12898 // Check I->Low <= Cond <= I->High.
12899 CC = ISD::SETLE;
12900 LHS = I->Low;
12901 MHS = Cond;
12902 RHS = I->High;
12903 }
12904
12905 // If Fallthrough is unreachable, fold away the comparison.
12906 if (FallthroughUnreachable)
12907 CC = ISD::SETTRUE;
12908
12909 // The false probability is the sum of all unhandled cases.
12910 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12911 getCurSDLoc(), I->Prob, UnhandledProbs);
12912
12913 if (CurMBB == SwitchMBB)
12914 visitSwitchCase(CB, SwitchMBB);
12915 else
12916 SL->SwitchCases.push_back(CB);
12917
12918 break;
12919 }
12920 }
12921 CurMBB = Fallthrough;
12922 }
12923}
12924
12925void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12926 const SwitchWorkListItem &W,
12927 Value *Cond,
12928 MachineBasicBlock *SwitchMBB) {
12929 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12930 "Clusters not sorted?");
12931 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12932
12933 auto [LastLeft, FirstRight, LeftProb, RightProb] =
12934 SL->computeSplitWorkItemInfo(W);
12935
12936 // Use the first element on the right as pivot since we will make less-than
12937 // comparisons against it.
12938 CaseClusterIt PivotCluster = FirstRight;
12939 assert(PivotCluster > W.FirstCluster);
12940 assert(PivotCluster <= W.LastCluster);
12941
12942 CaseClusterIt FirstLeft = W.FirstCluster;
12943 CaseClusterIt LastRight = W.LastCluster;
12944
12945 const ConstantInt *Pivot = PivotCluster->Low;
12946
12947 // New blocks will be inserted immediately after the current one.
12949 ++BBI;
12950
12951 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12952 // we can branch to its destination directly if it's squeezed exactly in
12953 // between the known lower bound and Pivot - 1.
12954 MachineBasicBlock *LeftMBB;
12955 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12956 FirstLeft->Low == W.GE &&
12957 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12958 LeftMBB = FirstLeft->MBB;
12959 } else {
12960 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12961 FuncInfo.MF->insert(BBI, LeftMBB);
12962 WorkList.push_back(
12963 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12964 // Put Cond in a virtual register to make it available from the new blocks.
12966 }
12967
12968 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12969 // single cluster, RHS.Low == Pivot, and we can branch to its destination
12970 // directly if RHS.High equals the current upper bound.
12971 MachineBasicBlock *RightMBB;
12972 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12973 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12974 RightMBB = FirstRight->MBB;
12975 } else {
12976 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12977 FuncInfo.MF->insert(BBI, RightMBB);
12978 WorkList.push_back(
12979 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12980 // Put Cond in a virtual register to make it available from the new blocks.
12982 }
12983
12984 // Create the CaseBlock record that will be used to lower the branch.
12985 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12986 getCurSDLoc(), LeftProb, RightProb);
12987
12988 if (W.MBB == SwitchMBB)
12989 visitSwitchCase(CB, SwitchMBB);
12990 else
12991 SL->SwitchCases.push_back(CB);
12992}
12993
12994// Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12995// from the swith statement.
12997 BranchProbability PeeledCaseProb) {
12998 if (PeeledCaseProb == BranchProbability::getOne())
13000 BranchProbability SwitchProb = PeeledCaseProb.getCompl();
13001
13002 uint32_t Numerator = CaseProb.getNumerator();
13003 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
13004 return BranchProbability(Numerator, std::max(Numerator, Denominator));
13005}
13006
13007// Try to peel the top probability case if it exceeds the threshold.
13008// Return current MachineBasicBlock for the switch statement if the peeling
13009// does not occur.
13010// If the peeling is performed, return the newly created MachineBasicBlock
13011// for the peeled switch statement. Also update Clusters to remove the peeled
13012// case. PeeledCaseProb is the BranchProbability for the peeled case.
13013MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
13014 const SwitchInst &SI, CaseClusterVector &Clusters,
13015 BranchProbability &PeeledCaseProb) {
13016 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
13017 // Don't perform if there is only one cluster or optimizing for size.
13018 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
13019 TM.getOptLevel() == CodeGenOptLevel::None ||
13020 SwitchMBB->getParent()->getFunction().hasMinSize())
13021 return SwitchMBB;
13022
13023 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
13024 unsigned PeeledCaseIndex = 0;
13025 bool SwitchPeeled = false;
13026 for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
13027 CaseCluster &CC = Clusters[Index];
13028 if (CC.Prob < TopCaseProb)
13029 continue;
13030 TopCaseProb = CC.Prob;
13031 PeeledCaseIndex = Index;
13032 SwitchPeeled = true;
13033 }
13034 if (!SwitchPeeled)
13035 return SwitchMBB;
13036
13037 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
13038 << TopCaseProb << "\n");
13039
13040 // Record the MBB for the peeled switch statement.
13041 MachineFunction::iterator BBI(SwitchMBB);
13042 ++BBI;
13043 MachineBasicBlock *PeeledSwitchMBB =
13044 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
13045 FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
13046
13047 ExportFromCurrentBlock(SI.getCondition());
13048 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
13049 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
13050 nullptr, nullptr, TopCaseProb.getCompl()};
13051 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
13052
13053 Clusters.erase(PeeledCaseIt);
13054 for (CaseCluster &CC : Clusters) {
13055 LLVM_DEBUG(
13056 dbgs() << "Scale the probablity for one cluster, before scaling: "
13057 << CC.Prob << "\n");
13058 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
13059 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
13060 }
13061 PeeledCaseProb = TopCaseProb;
13062 return PeeledSwitchMBB;
13063}
13064
13065void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
13066 // Extract cases from the switch.
13067 BranchProbabilityInfo *BPI = FuncInfo.BPI;
13068 CaseClusterVector Clusters;
13069 Clusters.reserve(SI.getNumCases());
13070 for (auto I : SI.cases()) {
13071 MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
13072 const ConstantInt *CaseVal = I.getCaseValue();
13073 BranchProbability Prob =
13074 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
13075 : BranchProbability(1, SI.getNumCases() + 1);
13076 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
13077 }
13078
13079 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
13080
13081 // Cluster adjacent cases with the same destination. We do this at all
13082 // optimization levels because it's cheap to do and will make codegen faster
13083 // if there are many clusters.
13084 sortAndRangeify(Clusters);
13085
13086 // The branch probablity of the peeled case.
13087 BranchProbability PeeledCaseProb = BranchProbability::getZero();
13088 MachineBasicBlock *PeeledSwitchMBB =
13089 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
13090
13091 // If there is only the default destination, jump there directly.
13092 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
13093 if (Clusters.empty()) {
13094 assert(PeeledSwitchMBB == SwitchMBB);
13095 SwitchMBB->addSuccessor(DefaultMBB);
13096 if (DefaultMBB != NextBlock(SwitchMBB)) {
13097 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
13098 getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
13099 }
13100 return;
13101 }
13102
13103 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
13104 DAG.getBFI());
13105 SL->findBitTestClusters(Clusters, &SI);
13106
13107 LLVM_DEBUG({
13108 dbgs() << "Case clusters: ";
13109 for (const CaseCluster &C : Clusters) {
13110 if (C.Kind == CC_JumpTable)
13111 dbgs() << "JT:";
13112 if (C.Kind == CC_BitTests)
13113 dbgs() << "BT:";
13114
13115 C.Low->getValue().print(dbgs(), true);
13116 if (C.Low != C.High) {
13117 dbgs() << '-';
13118 C.High->getValue().print(dbgs(), true);
13119 }
13120 dbgs() << ' ';
13121 }
13122 dbgs() << '\n';
13123 });
13124
13125 assert(!Clusters.empty());
13126 SwitchWorkList WorkList;
13127 CaseClusterIt First = Clusters.begin();
13128 CaseClusterIt Last = Clusters.end() - 1;
13129 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
13130 // Scale the branchprobability for DefaultMBB if the peel occurs and
13131 // DefaultMBB is not replaced.
13132 if (PeeledCaseProb != BranchProbability::getZero() &&
13133 DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
13134 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
13135 WorkList.push_back(
13136 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
13137
13138 while (!WorkList.empty()) {
13139 SwitchWorkListItem W = WorkList.pop_back_val();
13140 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
13141
13142 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
13143 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
13144 // For optimized builds, lower large range as a balanced binary tree.
13145 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
13146 continue;
13147 }
13148
13149 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
13150 }
13151}
13152
13153void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
13154 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13155 auto DL = getCurSDLoc();
13156 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13157 setValue(&I, DAG.getStepVector(DL, ResultVT));
13158}
13159
13160void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
13161 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13162 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13163
13164 SDLoc DL = getCurSDLoc();
13165 SDValue V = getValue(I.getOperand(0));
13166 assert(VT == V.getValueType() && "Malformed vector.reverse!");
13167
13168 if (VT.isScalableVector()) {
13169 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
13170 return;
13171 }
13172
13173 // Use VECTOR_SHUFFLE for the fixed-length vector
13174 // to maintain existing behavior.
13175 SmallVector<int, 8> Mask;
13176 unsigned NumElts = VT.getVectorMinNumElements();
13177 for (unsigned i = 0; i != NumElts; ++i)
13178 Mask.push_back(NumElts - 1 - i);
13179
13180 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
13181}
13182
13183void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I,
13184 unsigned Factor) {
13185 auto DL = getCurSDLoc();
13186 SDValue InVec = getValue(I.getOperand(0));
13187
13188 SmallVector<EVT, 4> ValueVTs;
13189 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
13190 ValueVTs);
13191
13192 EVT OutVT = ValueVTs[0];
13193 unsigned OutNumElts = OutVT.getVectorMinNumElements();
13194
13195 SmallVector<SDValue, 4> SubVecs(Factor);
13196 for (unsigned i = 0; i != Factor; ++i) {
13197 assert(ValueVTs[i] == OutVT && "Expected VTs to be the same");
13198 SubVecs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
13199 DAG.getVectorIdxConstant(OutNumElts * i, DL));
13200 }
13201
13202 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
13203 DAG.getVTList(ValueVTs), SubVecs);
13204 setValue(&I, Res);
13205}
13206
13207void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I,
13208 unsigned Factor) {
13209 auto DL = getCurSDLoc();
13210 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13211 EVT InVT = getValue(I.getOperand(0)).getValueType();
13212 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13213
13214 SmallVector<SDValue, 8> InVecs(Factor);
13215 for (unsigned i = 0; i < Factor; ++i) {
13216 InVecs[i] = getValue(I.getOperand(i));
13217 assert(InVecs[i].getValueType() == InVecs[0].getValueType() &&
13218 "Expected VTs to be the same");
13219 }
13220
13221 SmallVector<EVT, 8> ValueVTs(Factor, InVT);
13222 SDValue Res =
13223 DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, DAG.getVTList(ValueVTs), InVecs);
13224
13226 for (unsigned i = 0; i < Factor; ++i)
13227 Results[i] = Res.getValue(i);
13228
13229 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Results);
13230 setValue(&I, Res);
13231}
13232
13233void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
13234 SmallVector<EVT, 4> ValueVTs;
13235 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
13236 ValueVTs);
13237 unsigned NumValues = ValueVTs.size();
13238 if (NumValues == 0) return;
13239
13241 SDValue Op = getValue(I.getOperand(0));
13242
13243 for (unsigned i = 0; i != NumValues; ++i)
13244 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
13245 SDValue(Op.getNode(), Op.getResNo() + i));
13246
13248 DAG.getVTList(ValueVTs), Values));
13249}
13250
13251void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
13252 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13253 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13254
13255 SDLoc DL = getCurSDLoc();
13256 SDValue V1 = getValue(I.getOperand(0));
13257 SDValue V2 = getValue(I.getOperand(1));
13258 const bool IsLeft = I.getIntrinsicID() == Intrinsic::vector_splice_left;
13259
13260 // VECTOR_SHUFFLE doesn't support a scalable or non-constant mask.
13261 if (VT.isScalableVector() || !isa<ConstantInt>(I.getOperand(2))) {
13262 SDValue Offset = DAG.getZExtOrTrunc(
13263 getValue(I.getOperand(2)), DL, TLI.getVectorIdxTy(DAG.getDataLayout()));
13264 setValue(&I, DAG.getNode(IsLeft ? ISD::VECTOR_SPLICE_LEFT
13266 DL, VT, V1, V2, Offset));
13267 return;
13268 }
13269 uint64_t Imm = cast<ConstantInt>(I.getOperand(2))->getZExtValue();
13270
13271 unsigned NumElts = VT.getVectorNumElements();
13272
13273 uint64_t Idx = IsLeft ? Imm : NumElts - Imm;
13274
13275 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
13276 SmallVector<int, 8> Mask;
13277 for (unsigned i = 0; i < NumElts; ++i)
13278 Mask.push_back(Idx + i);
13279 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
13280}
13281
13282// Consider the following MIR after SelectionDAG, which produces output in
13283// phyregs in the first case or virtregs in the second case.
13284//
13285// INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
13286// %5:gr32 = COPY $ebx
13287// %6:gr32 = COPY $edx
13288// %1:gr32 = COPY %6:gr32
13289// %0:gr32 = COPY %5:gr32
13290//
13291// INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
13292// %1:gr32 = COPY %6:gr32
13293// %0:gr32 = COPY %5:gr32
13294//
13295// Given %0, we'd like to return $ebx in the first case and %5 in the second.
13296// Given %1, we'd like to return $edx in the first case and %6 in the second.
13297//
13298// If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
13299// to a single virtreg (such as %0). The remaining outputs monotonically
13300// increase in virtreg number from there. If a callbr has no outputs, then it
13301// should not have a corresponding callbr landingpad; in fact, the callbr
13302// landingpad would not even be able to refer to such a callbr.
13304 MachineInstr *MI = MRI.def_begin(Reg)->getParent();
13305 // There is definitely at least one copy.
13306 assert(MI->getOpcode() == TargetOpcode::COPY &&
13307 "start of copy chain MUST be COPY");
13308 Reg = MI->getOperand(1).getReg();
13309
13310 // If the copied register in the first copy must be virtual.
13311 assert(Reg.isVirtual() && "expected COPY of virtual register");
13312 MI = MRI.def_begin(Reg)->getParent();
13313
13314 // There may be an optional second copy.
13315 if (MI->getOpcode() == TargetOpcode::COPY) {
13316 assert(Reg.isVirtual() && "expected COPY of virtual register");
13317 Reg = MI->getOperand(1).getReg();
13318 assert(Reg.isPhysical() && "expected COPY of physical register");
13319 } else {
13320 // The start of the chain must be an INLINEASM_BR.
13321 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
13322 "end of copy chain MUST be INLINEASM_BR");
13323 }
13324
13325 return Reg;
13326}
13327
13328// We must do this walk rather than the simpler
13329// setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
13330// otherwise we will end up with copies of virtregs only valid along direct
13331// edges.
13332void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
13333 SmallVector<EVT, 8> ResultVTs;
13334 SmallVector<SDValue, 8> ResultValues;
13335 const auto *CBR =
13336 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
13337
13338 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13339 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
13340 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
13341
13342 Register InitialDef = FuncInfo.ValueMap[CBR];
13343 SDValue Chain = DAG.getRoot();
13344
13345 // Re-parse the asm constraints string.
13346 TargetLowering::AsmOperandInfoVector TargetConstraints =
13347 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
13348 for (auto &T : TargetConstraints) {
13349 SDISelAsmOperandInfo OpInfo(T);
13350 if (OpInfo.Type != InlineAsm::isOutput)
13351 continue;
13352
13353 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
13354 // individual constraint.
13355 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
13356
13357 switch (OpInfo.ConstraintType) {
13360 // Fill in OpInfo.AssignedRegs.Regs.
13361 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
13362
13363 // getRegistersForValue may produce 1 to many registers based on whether
13364 // the OpInfo.ConstraintVT is legal on the target or not.
13365 for (Register &Reg : OpInfo.AssignedRegs.Regs) {
13366 Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
13367 if (OriginalDef.isPhysical())
13368 FuncInfo.MBB->addLiveIn(OriginalDef);
13369 // Update the assigned registers to use the original defs.
13370 Reg = OriginalDef;
13371 }
13372
13373 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
13374 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
13375 ResultValues.push_back(V);
13376 ResultVTs.push_back(OpInfo.ConstraintVT);
13377 break;
13378 }
13380 SDValue Flag;
13382 OpInfo, DAG);
13383 ++InitialDef;
13384 ResultValues.push_back(V);
13385 ResultVTs.push_back(OpInfo.ConstraintVT);
13386 break;
13387 }
13388 default:
13389 break;
13390 }
13391 }
13393 DAG.getVTList(ResultVTs), ResultValues);
13394 setValue(&I, V);
13395}
unsigned NumParts
return SDValue()
static unsigned getIntrinsicID(const SDNode *N)
bool IsScalable
const TargetLowering & TLI
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:185
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:6340
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:686
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:613
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:119
bool contains(const KeyT &Key) const
Definition MapVector.h:149
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.
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 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 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.
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.
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 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...
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 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.
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 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 SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Glue, const SDLoc &DL, const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const
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 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 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:707
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:314
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:2308
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:433
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
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:144
uint64_t getScalarStoreSize() const
Definition ValueTypes.h:440
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:322
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:338
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:170
ElementCount getVectorElementCount() const
Definition ValueTypes.h:388
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:397
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
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:354
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:212
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:419
bool isFixedLengthVector() const
Definition ValueTypes.h:214
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
Definition ValueTypes.h:330
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:202
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
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:136
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:180
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
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:344
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)