LLVM 24.0.0git
SelectionDAGBuilder.cpp
Go to the documentation of this file.
1//===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements routines for translating from LLVM IR into SelectionDAG IR.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SelectionDAGBuilder.h"
14#include "SDNodeDbgValue.h"
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.h"
26#include "llvm/Analysis/Loads.h"
58#include "llvm/IR/Argument.h"
59#include "llvm/IR/Attributes.h"
60#include "llvm/IR/BasicBlock.h"
61#include "llvm/IR/CFG.h"
62#include "llvm/IR/CallingConv.h"
63#include "llvm/IR/Constant.h"
65#include "llvm/IR/Constants.h"
66#include "llvm/IR/DataLayout.h"
67#include "llvm/IR/DebugInfo.h"
72#include "llvm/IR/Function.h"
74#include "llvm/IR/InlineAsm.h"
75#include "llvm/IR/InstrTypes.h"
78#include "llvm/IR/Intrinsics.h"
79#include "llvm/IR/IntrinsicsAArch64.h"
80#include "llvm/IR/IntrinsicsAMDGPU.h"
81#include "llvm/IR/IntrinsicsWebAssembly.h"
82#include "llvm/IR/LLVMContext.h"
84#include "llvm/IR/Metadata.h"
85#include "llvm/IR/Module.h"
86#include "llvm/IR/Operator.h"
88#include "llvm/IR/Statepoint.h"
89#include "llvm/IR/Type.h"
90#include "llvm/IR/User.h"
91#include "llvm/IR/Value.h"
92#include "llvm/MC/MCContext.h"
97#include "llvm/Support/Debug.h"
105#include <cstddef>
106#include <limits>
107#include <optional>
108#include <tuple>
109
110using namespace llvm;
111using namespace PatternMatch;
112using namespace SwitchCG;
113
114#define DEBUG_TYPE "isel"
115
116/// LimitFloatPrecision - Generate low-precision inline sequences for
117/// some float libcalls (6, 8 or 12 bits).
118static unsigned LimitFloatPrecision;
119
120static cl::opt<bool>
121 InsertAssertAlign("insert-assert-align", cl::init(true),
122 cl::desc("Insert the experimental `assertalign` node."),
124
126 LimitFPPrecision("limit-float-precision",
127 cl::desc("Generate low-precision inline sequences "
128 "for some float libcalls"),
130 cl::init(0));
131
133 "switch-peel-threshold", cl::Hidden, cl::init(66),
134 cl::desc("Set the case probability threshold for peeling the case from a "
135 "switch statement. A value greater than 100 will void this "
136 "optimization"));
137
138// Limit the width of DAG chains. This is important in general to prevent
139// DAG-based analysis from blowing up. For example, alias analysis and
140// load clustering may not complete in reasonable time. It is difficult to
141// recognize and avoid this situation within each individual analysis, and
142// future analyses are likely to have the same behavior. Limiting DAG width is
143// the safe approach and will be especially important with global DAGs.
144//
145// MaxParallelChains default is arbitrarily high to avoid affecting
146// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
147// sequence over this should have been converted to llvm.memcpy by the
148// frontend. It is easy to induce this behavior with .ll code such as:
149// %buffer = alloca [4096 x i8]
150// %data = load [4096 x i8]* %argPtr
151// store [4096 x i8] %data, [4096 x i8]* %buffer
152static const unsigned MaxParallelChains = 64;
153
155 const SDValue *Parts, unsigned NumParts,
156 MVT PartVT, EVT ValueVT, const Value *V,
157 SDValue InChain,
158 std::optional<CallingConv::ID> CC);
159
160/// getCopyFromParts - Create a value that contains the specified legal parts
161/// combined into the value they represent. If the parts combine to a type
162/// larger than ValueVT then AssertOp can be used to specify whether the extra
163/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
164/// (ISD::AssertSext).
165static SDValue
166getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
167 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
168 SDValue InChain,
169 std::optional<CallingConv::ID> CC = std::nullopt,
170 std::optional<ISD::NodeType> AssertOp = std::nullopt) {
171 // Let the target assemble the parts if it wants to
172 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
173 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
174 PartVT, ValueVT, CC))
175 return Val;
176
177 if (ValueVT.isVector())
178 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
179 InChain, CC);
180
181 assert(NumParts > 0 && "No parts to assemble!");
182 SDValue Val = Parts[0];
183
184 if (NumParts > 1) {
185 // Assemble the value from multiple parts.
186 if (ValueVT.isInteger()) {
187 unsigned PartBits = PartVT.getSizeInBits();
188 unsigned ValueBits = ValueVT.getSizeInBits();
189
190 // Assemble the power of 2 part.
191 unsigned RoundParts = llvm::bit_floor(NumParts);
192 unsigned RoundBits = PartBits * RoundParts;
193 EVT RoundVT = RoundBits == ValueBits ?
194 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
195 SDValue Lo, Hi;
196
197 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
198
199 if (RoundParts > 2) {
200 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
201 InChain);
202 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
203 PartVT, HalfVT, V, InChain);
204 } else {
205 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
206 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
207 }
208
209 if (DAG.getDataLayout().isBigEndian())
210 std::swap(Lo, Hi);
211
212 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
213
214 if (RoundParts < NumParts) {
215 // Assemble the trailing non-power-of-2 part.
216 unsigned OddParts = NumParts - RoundParts;
217 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
218 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
219 OddVT, V, InChain, CC);
220
221 // Combine the round and odd parts.
222 Lo = Val;
223 if (DAG.getDataLayout().isBigEndian())
224 std::swap(Lo, Hi);
225 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
226 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
227 Hi = DAG.getNode(
228 ISD::SHL, DL, TotalVT, Hi,
229 DAG.getShiftAmountConstant(Lo.getValueSizeInBits(), TotalVT, DL));
230 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
231 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
232 }
233 } else if (PartVT.isFloatingPoint()) {
234 // FP split into multiple FP parts (for ppcf128)
235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
236 "Unexpected split");
237 SDValue Lo, Hi;
238 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
239 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
240 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
241 std::swap(Lo, Hi);
242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
243 } else {
244 // FP split into integer parts (soft fp)
245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
246 !PartVT.isVector() && "Unexpected split");
247 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
249 InChain, CC);
250 }
251 }
252
253 // There is now one part, held in Val. Correct it to match ValueVT.
254 // PartEVT is the type of the register class that holds the value.
255 // ValueVT is the type of the inline asm operation.
256 EVT PartEVT = Val.getValueType();
257
258 if (PartEVT == ValueVT)
259 return Val;
260
261 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
262 ValueVT.bitsLT(PartEVT)) {
263 // For an FP value in an integer part, we need to truncate to the right
264 // width first.
265 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
266 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
267 }
268
269 // Handle types that have the same size.
270 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
271 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
272
273 // Handle types with different sizes.
274 if (PartEVT.isInteger() && ValueVT.isInteger()) {
275 if (ValueVT.bitsLT(PartEVT)) {
276 // For a truncate, see if we have any information to
277 // indicate whether the truncated bits will always be
278 // zero or sign-extension.
279 if (AssertOp)
280 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
281 DAG.getValueType(ValueVT));
282 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
283 }
284 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
285 }
286
287 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
288 // FP_ROUND's are always exact here.
289 if (ValueVT.bitsLT(Val.getValueType())) {
290
291 SDValue NoChange =
293
294 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
295 llvm::Attribute::StrictFP)) {
296 return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
297 DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
298 NoChange);
299 }
300
301 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
302 }
303
304 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
305 }
306
307 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
308 // then truncating.
309 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
310 ValueVT.bitsLT(PartEVT)) {
311 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
312 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
313 }
314
315 report_fatal_error("Unknown mismatch in getCopyFromParts!");
316}
317
319 const Twine &ErrMsg) {
321 if (!I)
322 return Ctx.emitError(ErrMsg);
323
324 if (const CallInst *CI = dyn_cast<CallInst>(I))
325 if (CI->isInlineAsm()) {
326 return Ctx.diagnose(DiagnosticInfoInlineAsm(
327 *CI, ErrMsg + ", possible invalid constraint for vector type"));
328 }
329
330 return Ctx.emitError(I, ErrMsg);
331}
332
333/// getCopyFromPartsVector - Create a value that contains the specified legal
334/// parts combined into the value they represent. If the parts combine to a
335/// type larger than ValueVT then AssertOp can be used to specify whether the
336/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
337/// ValueVT (ISD::AssertSext).
339 const SDValue *Parts, unsigned NumParts,
340 MVT PartVT, EVT ValueVT, const Value *V,
341 SDValue InChain,
342 std::optional<CallingConv::ID> CallConv) {
343 assert(ValueVT.isVector() && "Not a vector value");
344 assert(NumParts > 0 && "No parts to assemble!");
345 const bool IsABIRegCopy = CallConv.has_value();
346
347 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
348 SDValue Val = Parts[0];
349
350 // Handle a multi-element vector.
351 if (NumParts > 1) {
352 EVT IntermediateVT;
353 MVT RegisterVT;
354 unsigned NumIntermediates;
355 unsigned NumRegs;
356
357 if (IsABIRegCopy) {
359 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
360 NumIntermediates, RegisterVT);
361 } else {
362 NumRegs =
363 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
364 NumIntermediates, RegisterVT);
365 }
366
367 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
368 NumParts = NumRegs; // Silence a compiler warning.
369 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
370 assert(RegisterVT.getSizeInBits() ==
371 Parts[0].getSimpleValueType().getSizeInBits() &&
372 "Part type sizes don't match!");
373
374 // Assemble the parts into intermediate operands.
375 SmallVector<SDValue, 8> Ops(NumIntermediates);
376 if (NumIntermediates == NumParts) {
377 // If the register was not expanded, truncate or copy the value,
378 // as appropriate.
379 for (unsigned i = 0; i != NumParts; ++i)
380 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
381 V, InChain, CallConv);
382 } else if (NumParts > 0) {
383 // If the intermediate type was expanded, build the intermediate
384 // operands from the parts.
385 assert(NumParts % NumIntermediates == 0 &&
386 "Must expand into a divisible number of parts!");
387 unsigned Factor = NumParts / NumIntermediates;
388 for (unsigned i = 0; i != NumIntermediates; ++i)
389 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
390 IntermediateVT, V, InChain, CallConv);
391 }
392
393 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
394 // intermediate operands.
395 EVT BuiltVectorTy =
396 IntermediateVT.isVector()
398 *DAG.getContext(), IntermediateVT.getScalarType(),
399 IntermediateVT.getVectorElementCount() * NumParts)
401 IntermediateVT.getScalarType(),
402 NumIntermediates);
403 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
405 DL, BuiltVectorTy, Ops);
406 }
407
408 // There is now one part, held in Val. Correct it to match ValueVT.
409 EVT PartEVT = Val.getValueType();
410
411 if (PartEVT == ValueVT)
412 return Val;
413
414 if (PartEVT.isVector()) {
415 // Vector/Vector bitcast.
416 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
417 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
418
419 // If the parts vector has more elements than the value vector, then we
420 // have a vector widening case (e.g. <2 x float> -> <4 x float>).
421 // Extract the elements we want.
422 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
425 (PartEVT.getVectorElementCount().isScalable() ==
426 ValueVT.getVectorElementCount().isScalable()) &&
427 "Cannot narrow, it would be a lossy transformation");
428 PartEVT =
430 ValueVT.getVectorElementCount());
431 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
432 DAG.getVectorIdxConstant(0, DL));
433 if (PartEVT == ValueVT)
434 return Val;
435 if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
436 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
437
438 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
439 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
440 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
441 }
442
443 // Promoted vector extract
444 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
445 }
446
447 // Trivial bitcast if the types are the same size and the destination
448 // vector type is legal.
449 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
450 TLI.isTypeLegal(ValueVT))
451 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
452
453 if (ValueVT.getVectorNumElements() != 1) {
454 // Certain ABIs require that vectors are passed as integers. For vectors
455 // are the same size, this is an obvious bitcast.
456 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
457 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
458 } else if (ValueVT.bitsLT(PartEVT)) {
459 const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
460 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
461 // Drop the extra bits.
462 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
463 return DAG.getBitcast(ValueVT, Val);
464 }
465
467 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
468 return DAG.getUNDEF(ValueVT);
469 }
470
471 // Handle cases such as i8 -> <1 x i1>
472 EVT ValueSVT = ValueVT.getVectorElementType();
473 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
474 unsigned ValueSize = ValueSVT.getSizeInBits();
475 if (ValueSize == PartEVT.getSizeInBits()) {
476 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
477 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
478 // It's possible a scalar floating point type gets softened to integer and
479 // then promoted to a larger integer. If PartEVT is the larger integer
480 // we need to truncate it and then bitcast to the FP type.
481 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
482 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
483 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
484 Val = DAG.getBitcast(ValueSVT, Val);
485 } else {
486 Val = ValueVT.isFloatingPoint()
487 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
488 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
489 }
490 }
491
492 return DAG.getBuildVector(ValueVT, DL, Val);
493}
494
495static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
496 SDValue Val, SDValue *Parts, unsigned NumParts,
497 MVT PartVT, const Value *V,
498 std::optional<CallingConv::ID> CallConv);
499
500/// getCopyToParts - Create a series of nodes that contain the specified value
501/// split into legal parts. If the parts contain more bits than Val, then, for
502/// integers, ExtendKind can be used to specify how to generate the extra bits.
503static void
505 unsigned NumParts, MVT PartVT, const Value *V,
506 std::optional<CallingConv::ID> CallConv = std::nullopt,
507 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
508 // Let the target split the parts if it wants to
509 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
510 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
511 CallConv))
512 return;
513 EVT ValueVT = Val.getValueType();
514
515 // Handle the vector case separately.
516 if (ValueVT.isVector())
517 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
518 CallConv);
519
520 unsigned OrigNumParts = NumParts;
522 "Copying to an illegal type!");
523
524 if (NumParts == 0)
525 return;
526
527 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
528 EVT PartEVT = PartVT;
529 if (PartEVT == ValueVT) {
530 assert(NumParts == 1 && "No-op copy with multiple parts!");
531 Parts[0] = Val;
532 return;
533 }
534
535 unsigned PartBits = PartVT.getSizeInBits();
536 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
537 // If the parts cover more bits than the value has, promote the value.
538 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
539 assert(NumParts == 1 && "Do not know what to promote to!");
540 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
541 } else {
542 if (ValueVT.isFloatingPoint()) {
543 // FP values need to be bitcast, then extended if they are being put
544 // into a larger container.
545 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
546 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
547 }
548 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
549 ValueVT.isInteger() &&
550 "Unknown mismatch!");
551 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
552 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
553 if (PartVT == MVT::x86mmx)
554 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
555 }
556 } else if (PartBits == ValueVT.getSizeInBits()) {
557 // Different types of the same size.
558 assert(NumParts == 1 && PartEVT != ValueVT);
559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
560 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
561 // If the parts cover less bits than value has, truncate the value.
562 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
563 ValueVT.isInteger() &&
564 "Unknown mismatch!");
565 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
566 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
567 if (PartVT == MVT::x86mmx)
568 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
569 }
570
571 // The value may have changed - recompute ValueVT.
572 ValueVT = Val.getValueType();
573 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
574 "Failed to tile the value with PartVT!");
575
576 if (NumParts == 1) {
577 if (PartEVT != ValueVT) {
579 "scalar-to-vector conversion failed");
580 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
581 }
582
583 Parts[0] = Val;
584 return;
585 }
586
587 // Expand the value into multiple parts.
588 if (NumParts & (NumParts - 1)) {
589 // The number of parts is not a power of 2. Split off and copy the tail.
590 assert(PartVT.isInteger() && ValueVT.isInteger() &&
591 "Do not know what to expand to!");
592 unsigned RoundParts = llvm::bit_floor(NumParts);
593 unsigned RoundBits = RoundParts * PartBits;
594 unsigned OddParts = NumParts - RoundParts;
595 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
596 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
597
598 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
599 CallConv);
600
601 if (DAG.getDataLayout().isBigEndian())
602 // The odd parts were reversed by getCopyToParts - unreverse them.
603 std::reverse(Parts + RoundParts, Parts + NumParts);
604
605 NumParts = RoundParts;
606 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
607 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
608 }
609
610 // The number of parts is a power of 2. Repeatedly bisect the value using
611 // EXTRACT_ELEMENT.
612 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
614 ValueVT.getSizeInBits()),
615 Val);
616
617 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
618 for (unsigned i = 0; i < NumParts; i += StepSize) {
619 unsigned ThisBits = StepSize * PartBits / 2;
620 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
621 SDValue &Part0 = Parts[i];
622 SDValue &Part1 = Parts[i+StepSize/2];
623
624 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
625 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
626 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
627 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
628
629 if (ThisBits == PartBits && ThisVT != PartVT) {
630 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
631 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
632 }
633 }
634 }
635
636 if (DAG.getDataLayout().isBigEndian())
637 std::reverse(Parts, Parts + OrigNumParts);
638}
639
641 const SDLoc &DL, EVT PartVT) {
642 if (!PartVT.isVector())
643 return SDValue();
644
645 EVT ValueVT = Val.getValueType();
646 EVT PartEVT = PartVT.getVectorElementType();
647 EVT ValueEVT = ValueVT.getVectorElementType();
648 ElementCount PartNumElts = PartVT.getVectorElementCount();
649 ElementCount ValueNumElts = ValueVT.getVectorElementCount();
650
651 // We only support widening vectors with equivalent element types and
652 // fixed/scalable properties. If a target needs to widen a fixed-length type
653 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
654 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
655 PartNumElts.isScalable() != ValueNumElts.isScalable())
656 return SDValue();
657
658 // Have a try for bf16 because some targets share its ABI with fp16.
659 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
661 "Cannot widen to illegal type");
662 Val = DAG.getNode(
664 ValueVT.changeVectorElementType(*DAG.getContext(), MVT::f16), Val);
665 } else if (PartEVT != ValueEVT) {
666 return SDValue();
667 }
668
669 // Widening a scalable vector to another scalable vector is done by inserting
670 // the vector into a larger undef one.
671 if (PartNumElts.isScalable())
672 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
673 Val, DAG.getVectorIdxConstant(0, DL));
674
675 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
676 // undef elements.
678 DAG.ExtractVectorElements(Val, Ops);
679 SDValue EltUndef = DAG.getUNDEF(PartEVT);
680 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
681
682 // FIXME: Use CONCAT for 2x -> 4x.
683 return DAG.getBuildVector(PartVT, DL, Ops);
684}
685
686/// getCopyToPartsVector - Create a series of nodes that contain the specified
687/// value split into legal parts.
688static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
689 SDValue Val, SDValue *Parts, unsigned NumParts,
690 MVT PartVT, const Value *V,
691 std::optional<CallingConv::ID> CallConv) {
692 EVT ValueVT = Val.getValueType();
693 assert(ValueVT.isVector() && "Not a vector");
694 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
695 const bool IsABIRegCopy = CallConv.has_value();
696
697 if (NumParts == 1) {
698 EVT PartEVT = PartVT;
699 if (PartEVT == ValueVT) {
700 // Nothing to do.
701 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
702 // Bitconvert vector->vector case.
703 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
704 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
705 Val = Widened;
706 } else if (PartVT.isVector() &&
708 ValueVT.getVectorElementType()) &&
709 PartEVT.getVectorElementCount() ==
710 ValueVT.getVectorElementCount()) {
711
712 // Promoted vector extract
713 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
714 } else if (PartEVT.isVector() &&
715 PartEVT.getVectorElementType() !=
716 ValueVT.getVectorElementType() &&
717 TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
719 // Combination of widening and promotion.
720 EVT WidenVT =
722 PartVT.getVectorElementCount());
723 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
724 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
725 } else {
726 // Don't extract an integer from a float vector. This can happen if the
727 // FP type gets softened to integer and then promoted. The promotion
728 // prevents it from being picked up by the earlier bitcast case.
729 if (ValueVT.getVectorElementCount().isScalar() &&
730 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
731 // If we reach this condition and PartVT is FP, this means that
732 // ValueVT is also FP and both have a different size, otherwise we
733 // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
734 // would be invalid since that would mean the smaller FP type has to
735 // be extended to the larger one.
736 if (PartVT.isFloatingPoint()) {
737 Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
738 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
739 } else
740 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
741 DAG.getVectorIdxConstant(0, DL));
742 } else {
743 uint64_t ValueSize = ValueVT.getFixedSizeInBits();
744 assert(PartVT.getFixedSizeInBits() > ValueSize &&
745 "lossy conversion of vector to scalar type");
746 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
747 Val = DAG.getBitcast(IntermediateType, Val);
748 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
749 }
750 }
751
752 assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
753 Parts[0] = Val;
754 return;
755 }
756
757 // Handle a multi-element vector.
758 EVT IntermediateVT;
759 MVT RegisterVT;
760 unsigned NumIntermediates;
761 unsigned NumRegs;
762 if (IsABIRegCopy) {
764 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
765 RegisterVT);
766 } else {
767 NumRegs =
768 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
769 NumIntermediates, RegisterVT);
770 }
771
772 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
773 NumParts = NumRegs; // Silence a compiler warning.
774 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
775
776 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
777 "Mixing scalable and fixed vectors when copying in parts");
778
779 std::optional<ElementCount> DestEltCnt;
780
781 if (IntermediateVT.isVector())
782 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
783 else
784 DestEltCnt = ElementCount::getFixed(NumIntermediates);
785
786 EVT BuiltVectorTy = EVT::getVectorVT(
787 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
788
789 if (ValueVT == BuiltVectorTy) {
790 // Nothing to do.
791 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
792 // Bitconvert vector->vector case.
793 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
794 } else {
795 if (BuiltVectorTy.getVectorElementType().bitsGT(
796 ValueVT.getVectorElementType())) {
797 // Integer promotion.
798 ValueVT = EVT::getVectorVT(*DAG.getContext(),
799 BuiltVectorTy.getVectorElementType(),
800 ValueVT.getVectorElementCount());
801 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
802 }
803
804 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
805 Val = Widened;
806 }
807 }
808
809 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
810
811 // Split the vector into intermediate operands.
812 SmallVector<SDValue, 8> Ops(NumIntermediates);
813 for (unsigned i = 0; i != NumIntermediates; ++i) {
814 if (IntermediateVT.isVector()) {
815 // This does something sensible for scalable vectors - see the
816 // definition of EXTRACT_SUBVECTOR for further details.
817 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
818 Ops[i] =
819 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
820 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
821 } else {
822 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
823 DAG.getVectorIdxConstant(i, DL));
824 }
825 }
826
827 // Split the intermediate operands into legal parts.
828 if (NumParts == NumIntermediates) {
829 // If the register was not expanded, promote or copy the value,
830 // as appropriate.
831 for (unsigned i = 0; i != NumParts; ++i)
832 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
833 } else if (NumParts > 0) {
834 // If the intermediate type was expanded, split each the value into
835 // legal parts.
836 assert(NumIntermediates != 0 && "division by zero");
837 assert(NumParts % NumIntermediates == 0 &&
838 "Must expand into a divisible number of parts!");
839 unsigned Factor = NumParts / NumIntermediates;
840 for (unsigned i = 0; i != NumIntermediates; ++i)
841 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
842 CallConv);
843 }
844}
845
846static void failForInvalidBundles(const CallBase &I, StringRef Name,
847 ArrayRef<uint32_t> AllowedBundles) {
848 if (I.hasOperandBundlesOtherThan(AllowedBundles)) {
849 ListSeparator LS;
850 std::string Error;
852 for (unsigned i = 0, e = I.getNumOperandBundles(); i != e; ++i) {
853 OperandBundleUse U = I.getOperandBundleAt(i);
854 if (!is_contained(AllowedBundles, U.getTagID()))
855 OS << LS << U.getTagName();
856 }
858 Twine("cannot lower ", Name)
859 .concat(Twine(" with arbitrary operand bundles: ", Error)));
860 }
861}
862
864 EVT valuevt, std::optional<CallingConv::ID> CC)
865 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
866 RegCount(1, regs.size()), CallConv(CC) {}
867
869 const DataLayout &DL, Register Reg, Type *Ty,
870 std::optional<CallingConv::ID> CC) {
871 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
872
873 CallConv = CC;
874
875 for (EVT ValueVT : ValueVTs) {
876 unsigned NumRegs =
878 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
879 : TLI.getNumRegisters(Context, ValueVT);
880 MVT RegisterVT =
882 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
883 : TLI.getRegisterType(Context, ValueVT);
884 for (unsigned i = 0; i != NumRegs; ++i)
885 Regs.push_back(Reg + i);
886 RegVTs.push_back(RegisterVT);
887 RegCount.push_back(NumRegs);
888 Reg = Reg.id() + NumRegs;
889 }
890}
891
893 FunctionLoweringInfo &FuncInfo,
894 const SDLoc &dl, SDValue &Chain,
895 SDValue *Glue, const Value *V) const {
896 // A Value with type {} or [0 x %t] needs no registers.
897 if (ValueVTs.empty())
898 return SDValue();
899
900 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
901
902 // Assemble the legal parts into the final values.
905 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
906 // Copy the legal parts from the registers.
907 EVT ValueVT = ValueVTs[Value];
908 unsigned NumRegs = RegCount[Value];
909 MVT RegisterVT = isABIMangled()
911 *DAG.getContext(), *CallConv, RegVTs[Value])
912 : RegVTs[Value];
913
914 Parts.resize(NumRegs);
915 for (unsigned i = 0; i != NumRegs; ++i) {
916 SDValue P;
917 if (!Glue) {
918 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
919 } else {
920 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
921 *Glue = P.getValue(2);
922 }
923
924 Chain = P.getValue(1);
925 Parts[i] = P;
926
927 // If the source register was virtual and if we know something about it,
928 // add an assert node.
929 if (!Regs[Part + i].isVirtual() || !RegisterVT.isInteger())
930 continue;
931
933 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
934 if (!LOI)
935 continue;
936
937 unsigned RegSize = RegisterVT.getScalarSizeInBits();
938 unsigned NumSignBits = LOI->NumSignBits;
939 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
940
941 if (NumZeroBits == RegSize) {
942 // The current value is a zero.
943 // Explicitly express that as it would be easier for
944 // optimizations to kick in.
945 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
946 continue;
947 }
948
949 // FIXME: We capture more information than the dag can represent. For
950 // now, just use the tightest assertzext/assertsext possible.
951 bool isSExt;
952 EVT FromVT(MVT::Other);
953 if (NumZeroBits) {
954 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
955 isSExt = false;
956 } else if (NumSignBits > 1) {
957 FromVT =
958 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
959 isSExt = true;
960 } else {
961 continue;
962 }
963 // Add an assertion node.
964 assert(FromVT != MVT::Other);
965 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
966 RegisterVT, P, DAG.getValueType(FromVT));
967 }
968
969 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
970 RegisterVT, ValueVT, V, Chain, CallConv);
971 Part += NumRegs;
972 Parts.clear();
973 }
974
975 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
976}
977
979 const SDLoc &dl, SDValue &Chain, SDValue *Glue,
980 const Value *V,
981 ISD::NodeType PreferredExtendType) const {
982 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
983 ISD::NodeType ExtendKind = PreferredExtendType;
984
985 // Get the list of the values's legal parts.
986 unsigned NumRegs = Regs.size();
987 SmallVector<SDValue, 8> Parts(NumRegs);
988 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
989 unsigned NumParts = RegCount[Value];
990
991 MVT RegisterVT = isABIMangled()
993 *DAG.getContext(), *CallConv, RegVTs[Value])
994 : RegVTs[Value];
995
996 if (ExtendKind == ISD::ANY_EXTEND)
997 if (TLI.isZExtFree(peekThroughFreeze(Val), RegisterVT))
998 ExtendKind = ISD::ZERO_EXTEND;
999
1000 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
1001 NumParts, RegisterVT, V, CallConv, ExtendKind);
1002 Part += NumParts;
1003 }
1004
1005 // Copy the parts into the registers.
1006 SmallVector<SDValue, 8> Chains(NumRegs);
1007 for (unsigned i = 0; i != NumRegs; ++i) {
1008 SDValue Part;
1009 if (!Glue) {
1010 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
1011 } else {
1012 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
1013 *Glue = Part.getValue(1);
1014 }
1015
1016 Chains[i] = Part.getValue(0);
1017 }
1018
1019 if (NumRegs == 1 || Glue)
1020 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1021 // flagged to it. That is the CopyToReg nodes and the user are considered
1022 // a single scheduling unit. If we create a TokenFactor and return it as
1023 // chain, then the TokenFactor is both a predecessor (operand) of the
1024 // user as well as a successor (the TF operands are flagged to the user).
1025 // c1, f1 = CopyToReg
1026 // c2, f2 = CopyToReg
1027 // c3 = TokenFactor c1, c2
1028 // ...
1029 // = op c3, ..., f2
1030 Chain = Chains[NumRegs-1];
1031 else
1032 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1033}
1034
1036 unsigned MatchingIdx, const SDLoc &dl,
1037 SelectionDAG &DAG,
1038 std::vector<SDValue> &Ops) const {
1039 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1040
1041 InlineAsm::Flag Flag(Code, Regs.size());
1042 if (HasMatching)
1043 Flag.setMatchingOp(MatchingIdx);
1044 else if (!Regs.empty() && Regs.front().isVirtual()) {
1045 // Put the register class of the virtual registers in the flag word. That
1046 // way, later passes can recompute register class constraints for inline
1047 // assembly as well as normal instructions.
1048 // Don't do this for tied operands that can use the regclass information
1049 // from the def.
1051 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1052 Flag.setRegClass(RC->getID());
1053 }
1054
1055 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1056 Ops.push_back(Res);
1057
1058 if (Code == InlineAsm::Kind::Clobber) {
1059 // Clobbers should always have a 1:1 mapping with registers, and may
1060 // reference registers that have illegal (e.g. vector) types. Hence, we
1061 // shouldn't try to apply any sort of splitting logic to them.
1062 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1063 "No 1:1 mapping from clobbers to regs?");
1065 (void)SP;
1066 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1067 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1068 assert(
1069 (Regs[I] != SP ||
1071 "If we clobbered the stack pointer, MFI should know about it.");
1072 }
1073 return;
1074 }
1075
1076 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1077 MVT RegisterVT = RegVTs[Value];
1078 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1079 RegisterVT);
1080 for (unsigned i = 0; i != NumRegs; ++i) {
1081 assert(Reg < Regs.size() && "Mismatch in # registers expected");
1082 Register TheReg = Regs[Reg++];
1083 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1084 }
1085 }
1086}
1087
1091 unsigned I = 0;
1092 for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1093 unsigned RegCount = std::get<0>(CountAndVT);
1094 MVT RegisterVT = std::get<1>(CountAndVT);
1095 TypeSize RegisterSize = RegisterVT.getSizeInBits();
1096 for (unsigned E = I + RegCount; I != E; ++I)
1097 OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1098 }
1099 return OutVec;
1100}
1101
1103 AssumptionCache *ac, const TargetLibraryInfo *li,
1104 const TargetTransformInfo &TTI) {
1105 BatchAA = aa;
1106 AC = ac;
1107 GFI = gfi;
1108 LibInfo = li;
1109 Context = DAG.getContext();
1110 LPadToCallSiteMap.clear();
1111 this->TTI = &TTI;
1112 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1113 AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1114 *DAG.getMachineFunction().getFunction().getParent());
1115}
1116
1118 NodeMap.clear();
1119 UnusedArgNodeMap.clear();
1120 PendingLoads.clear();
1121 PendingExports.clear();
1122 PendingConstrainedFP.clear();
1123 PendingConstrainedFPStrict.clear();
1124 CurInst = nullptr;
1125 HasTailCall = false;
1126 SDNodeOrder = LowestSDNodeOrder;
1127 StatepointLowering.clear();
1128}
1129
1131 DanglingDebugInfoMap.clear();
1132}
1133
1134// Update DAG root to include dependencies on Pending chains.
1135SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1136 SDValue Root = DAG.getRoot();
1137
1138 if (Pending.empty())
1139 return Root;
1140
1141 // Add current root to PendingChains, unless we already indirectly
1142 // depend on it.
1143 if (Root.getOpcode() != ISD::EntryToken) {
1144 unsigned i = 0, e = Pending.size();
1145 for (; i != e; ++i) {
1146 assert(Pending[i].getNode()->getNumOperands() > 1);
1147 if (Pending[i].getNode()->getOperand(0) == Root)
1148 break; // Don't add the root if we already indirectly depend on it.
1149 }
1150
1151 if (i == e)
1152 Pending.push_back(Root);
1153 }
1154
1155 if (Pending.size() == 1)
1156 Root = Pending[0];
1157 else
1158 Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1159
1160 DAG.setRoot(Root);
1161 Pending.clear();
1162 return Root;
1163}
1164
1168
1170 // If the new exception behavior differs from that of the pending
1171 // ones, chain up them and update the root.
1172 switch (EB) {
1175 // Floating-point exceptions produced by such operations are not intended
1176 // to be observed, so the sequence of these operations does not need to be
1177 // preserved.
1178 //
1179 // They however must not be mixed with the instructions that have strict
1180 // exception behavior. Placing an operation with 'ebIgnore' behavior between
1181 // 'ebStrict' operations could distort the observed exception behavior.
1182 if (!PendingConstrainedFPStrict.empty()) {
1183 assert(PendingConstrainedFP.empty());
1184 updateRoot(PendingConstrainedFPStrict);
1185 }
1186 break;
1188 // Floating-point exception produced by these operations may be observed, so
1189 // they must be correctly chained. If trapping on FP exceptions is
1190 // disabled, the exceptions can be observed only by functions that read
1191 // exception flags, like 'llvm.get_fpenv' or 'fetestexcept'. It means that
1192 // the order of operations is not significant between barriers.
1193 //
1194 // If trapping is enabled, each operation becomes an implicit observation
1195 // point, so the operations must be sequenced according their original
1196 // source order.
1197 if (!PendingConstrainedFP.empty()) {
1198 assert(PendingConstrainedFPStrict.empty());
1199 updateRoot(PendingConstrainedFP);
1200 }
1201 // TODO: Add support for trapping-enabled scenarios.
1202 }
1203 return DAG.getRoot();
1204}
1205
1207 // Chain up all pending constrained intrinsics together with all
1208 // pending loads, by simply appending them to PendingLoads and
1209 // then calling getMemoryRoot().
1210 PendingLoads.reserve(PendingLoads.size() +
1211 PendingConstrainedFP.size() +
1212 PendingConstrainedFPStrict.size());
1213 PendingLoads.append(PendingConstrainedFP.begin(),
1214 PendingConstrainedFP.end());
1215 PendingLoads.append(PendingConstrainedFPStrict.begin(),
1216 PendingConstrainedFPStrict.end());
1217 PendingConstrainedFP.clear();
1218 PendingConstrainedFPStrict.clear();
1219 return getMemoryRoot();
1220}
1221
1223 // We need to emit pending fpexcept.strict constrained intrinsics,
1224 // so append them to the PendingExports list.
1225 PendingExports.append(PendingConstrainedFPStrict.begin(),
1226 PendingConstrainedFPStrict.end());
1227 PendingConstrainedFPStrict.clear();
1228 return updateRoot(PendingExports);
1229}
1230
1232 DILocalVariable *Variable,
1234 DebugLoc DL) {
1235 assert(Variable && "Missing variable");
1236
1237 // Check if address has undef value.
1238 if (!Address || isa<UndefValue>(Address) ||
1239 (Address->use_empty() && !isa<Argument>(Address))) {
1240 LLVM_DEBUG(
1241 dbgs()
1242 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1243 return;
1244 }
1245
1246 bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1247
1248 SDValue &N = NodeMap[Address];
1249 if (!N.getNode() && isa<Argument>(Address))
1250 // Check unused arguments map.
1251 N = UnusedArgNodeMap[Address];
1252 SDDbgValue *SDV;
1253 if (N.getNode()) {
1254 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1255 Address = BCI->getOperand(0);
1256 // Parameters are handled specially.
1257 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1258 if (IsParameter && FINode) {
1259 // Byval parameter. We have a frame index at this point.
1260 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1261 /*IsIndirect*/ true, DL, SDNodeOrder);
1262 } else if (isa<Argument>(Address)) {
1263 // Address is an argument, so try to emit its dbg value using
1264 // virtual register info from the FuncInfo.ValueMap.
1265 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1266 FuncArgumentDbgValueKind::Declare, N);
1267 return;
1268 } else {
1269 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1270 true, DL, SDNodeOrder);
1271 }
1272 DAG.AddDbgValue(SDV, IsParameter);
1273 } else {
1274 // If Address is an argument then try to emit its dbg value using
1275 // virtual register info from the FuncInfo.ValueMap.
1276 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1277 FuncArgumentDbgValueKind::Declare, N)) {
1278 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1279 << " (could not emit func-arg dbg_value)\n");
1280 }
1281 }
1282}
1283
1285 // Add SDDbgValue nodes for any var locs here. Do so before updating
1286 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1287 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1288 // Add SDDbgValue nodes for any var locs here. Do so before updating
1289 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1290 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1291 It != End; ++It) {
1292 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1293 dropDanglingDebugInfo(Var, It->Expr);
1294 if (It->Values.isKillLocation(It->Expr)) {
1295 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1296 continue;
1297 }
1298 SmallVector<Value *> Values(It->Values.location_ops());
1299 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1300 It->Values.hasArgList())) {
1301 SmallVector<Value *, 4> Vals(It->Values.location_ops());
1303 FnVarLocs->getDILocalVariable(It->VariableID),
1304 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1305 }
1306 }
1307 }
1308
1309 // We must skip DbgVariableRecords if they've already been processed above as
1310 // we have just emitted the debug values resulting from assignment tracking
1311 // analysis, making any existing DbgVariableRecords redundant (and probably
1312 // less correct). We still need to process DbgLabelRecords. This does sink
1313 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1314 // be important as it does so deterministcally and ordering between
1315 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1316 // printing).
1317 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1318 // Is there is any debug-info attached to this instruction, in the form of
1319 // DbgRecord non-instruction debug-info records.
1320 for (DbgRecord &DR : I.getDbgRecordRange()) {
1321 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1322 assert(DLR->getLabel() && "Missing label");
1323 SDDbgLabel *SDV =
1324 DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1325 DAG.AddDbgLabel(SDV);
1326 continue;
1327 }
1328
1329 if (SkipDbgVariableRecords)
1330 continue;
1332 DILocalVariable *Variable = DVR.getVariable();
1335
1337 if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1338 continue;
1339 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1340 << "\n");
1342 DVR.getDebugLoc());
1343 continue;
1344 }
1345
1346 // A DbgVariableRecord with no locations is a kill location.
1348 if (Values.empty()) {
1350 SDNodeOrder);
1351 continue;
1352 }
1353
1354 // A DbgVariableRecord with an undef or absent location is also a kill
1355 // location.
1356 if (llvm::any_of(Values,
1357 [](Value *V) { return !V || isa<UndefValue>(V); })) {
1359 SDNodeOrder);
1360 continue;
1361 }
1362
1363 bool IsVariadic = DVR.hasArgList();
1364 if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1365 SDNodeOrder, IsVariadic)) {
1366 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1367 DVR.getDebugLoc(), SDNodeOrder);
1368 }
1369 }
1370}
1371
1373 visitDbgInfo(I);
1374
1375 // Set up outgoing PHI node register values before emitting the terminator.
1376 if (I.isTerminator()) {
1377 HandlePHINodesInSuccessorBlocks(I.getParent());
1378 }
1379
1380 ++SDNodeOrder;
1381 CurInst = &I;
1382
1383 // Set inserted listener only if required.
1384 bool NodeInserted = false;
1385 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1386 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1387 MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1388 if (PCSectionsMD || MMRA) {
1389 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1390 DAG, [&](SDNode *) { NodeInserted = true; });
1391 }
1392
1393 visit(I.getOpcode(), I);
1394
1395 if (!I.isTerminator() && !HasTailCall &&
1396 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1398
1399 // Handle metadata.
1400 if (PCSectionsMD || MMRA) {
1401 auto It = NodeMap.find(&I);
1402 if (It != NodeMap.end()) {
1403 if (PCSectionsMD)
1404 DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1405 if (MMRA)
1406 DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1407 } else if (NodeInserted) {
1408 // This should not happen; if it does, don't let it go unnoticed so we can
1409 // fix it. Relevant visit*() function is probably missing a setValue().
1410 errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1411 << I.getModule()->getName() << "]\n";
1412 LLVM_DEBUG(I.dump());
1413 assert(false);
1414 }
1415 }
1416
1417 CurInst = nullptr;
1418}
1419
1420void SelectionDAGBuilder::visitPHI(const PHINode &) {
1421 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1422}
1423
1424void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1425 // Note: this doesn't use InstVisitor, because it has to work with
1426 // ConstantExpr's in addition to instructions.
1427 switch (Opcode) {
1428 default: llvm_unreachable("Unknown instruction type encountered!");
1429 // Build the switch statement using the Instruction.def file.
1430#define HANDLE_INST(NUM, OPCODE, CLASS) \
1431 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1432#include "llvm/IR/Instruction.def"
1433 }
1434}
1435
1437 DILocalVariable *Variable,
1438 DebugLoc DL, unsigned Order,
1441 // For variadic dbg_values we will now insert poison.
1442 // FIXME: We can potentially recover these!
1444 for (const Value *V : Values) {
1445 auto *Poison = PoisonValue::get(V->getType());
1447 }
1448 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1449 /*IsIndirect=*/false, DL, Order,
1450 /*IsVariadic=*/true);
1451 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1452 return true;
1453}
1454
1456 DILocalVariable *Var,
1457 DIExpression *Expr,
1458 bool IsVariadic, DebugLoc DL,
1459 unsigned Order) {
1460 if (IsVariadic) {
1461 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1462 return;
1463 }
1464 // TODO: Dangling debug info will eventually either be resolved or produce
1465 // a poison DBG_VALUE. However in the resolution case, a gap may appear
1466 // between the original dbg.value location and its resolved DBG_VALUE,
1467 // which we should ideally fill with an extra poison DBG_VALUE.
1468 assert(Values.size() == 1);
1469 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1470}
1471
1473 const DIExpression *Expr) {
1474 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1475 DIVariable *DanglingVariable = DDI.getVariable();
1476 DIExpression *DanglingExpr = DDI.getExpression();
1477 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1478 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1479 << printDDI(nullptr, DDI) << "\n");
1480 return true;
1481 }
1482 return false;
1483 };
1484
1485 for (auto &DDIMI : DanglingDebugInfoMap) {
1486 DanglingDebugInfoVector &DDIV = DDIMI.second;
1487
1488 // If debug info is to be dropped, run it through final checks to see
1489 // whether it can be salvaged.
1490 for (auto &DDI : DDIV)
1491 if (isMatchingDbgValue(DDI))
1492 salvageUnresolvedDbgValue(DDIMI.first, DDI);
1493
1494 erase_if(DDIV, isMatchingDbgValue);
1495 }
1496}
1497
1498// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1499// generate the debug data structures now that we've seen its definition.
1501 SDValue Val) {
1502 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1503 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1504 return;
1505
1506 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1507 for (auto &DDI : DDIV) {
1508 DebugLoc DL = DDI.getDebugLoc();
1509 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1510 DILocalVariable *Variable = DDI.getVariable();
1511 DIExpression *Expr = DDI.getExpression();
1512 assert(Variable->isValidLocationForIntrinsic(DL) &&
1513 "Expected inlined-at fields to agree");
1514 SDDbgValue *SDV;
1515 if (Val.getNode()) {
1516 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1517 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1518 // we couldn't resolve it directly when examining the DbgValue intrinsic
1519 // in the first place we should not be more successful here). Unless we
1520 // have some test case that prove this to be correct we should avoid
1521 // calling EmitFuncArgumentDbgValue here.
1522 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1523 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1524 FuncArgumentDbgValueKind::Value, Val)) {
1525 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1526 << printDDI(V, DDI) << "\n");
1527 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1528 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1529 // inserted after the definition of Val when emitting the instructions
1530 // after ISel. An alternative could be to teach
1531 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1532 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1533 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1534 << ValSDNodeOrder << "\n");
1535 SDV = getDbgValue(Val, Variable, Expr, DL,
1536 std::max(DbgSDNodeOrder, ValSDNodeOrder));
1537 DAG.AddDbgValue(SDV, false);
1538 } else
1539 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1540 << printDDI(V, DDI)
1541 << " in EmitFuncArgumentDbgValue\n");
1542 } else {
1543 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1544 << "\n");
1545 auto Poison = PoisonValue::get(V->getType());
1546 auto SDV =
1547 DAG.getConstantDbgValue(Variable, Expr, Poison, DL, DbgSDNodeOrder);
1548 DAG.AddDbgValue(SDV, false);
1549 }
1550 }
1551 DDIV.clear();
1552}
1553
1555 DanglingDebugInfo &DDI) {
1556 // TODO: For the variadic implementation, instead of only checking the fail
1557 // state of `handleDebugValue`, we need know specifically which values were
1558 // invalid, so that we attempt to salvage only those values when processing
1559 // a DIArgList.
1560 const Value *OrigV = V;
1561 DILocalVariable *Var = DDI.getVariable();
1562 DIExpression *Expr = DDI.getExpression();
1563 DebugLoc DL = DDI.getDebugLoc();
1564 unsigned SDOrder = DDI.getSDNodeOrder();
1565
1566 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1567 // that DW_OP_stack_value is desired.
1568 bool StackValue = true;
1569
1570 // Can this Value can be encoded without any further work?
1571 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1572 return;
1573
1574 // Attempt to salvage back through as many instructions as possible. Bail if
1575 // a non-instruction is seen, such as a constant expression or global
1576 // variable. FIXME: Further work could recover those too.
1577 while (isa<Instruction>(V)) {
1578 const Instruction &VAsInst = *cast<const Instruction>(V);
1579 // Temporary "0", awaiting real implementation.
1581 SmallVector<Value *, 4> AdditionalValues;
1582 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1583 Expr->getNumLocationOperands(), Ops,
1584 AdditionalValues);
1585 // If we cannot salvage any further, and haven't yet found a suitable debug
1586 // expression, bail out.
1587 if (!V)
1588 break;
1589
1590 // TODO: If AdditionalValues isn't empty, then the salvage can only be
1591 // represented with a DBG_VALUE_LIST, so we give up. When we have support
1592 // here for variadic dbg_values, remove that condition.
1593 if (!AdditionalValues.empty())
1594 break;
1595
1596 // New value and expr now represent this debuginfo.
1597 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1598
1599 // Some kind of simplification occurred: check whether the operand of the
1600 // salvaged debug expression can be encoded in this DAG.
1601 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1602 LLVM_DEBUG(
1603 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n"
1604 << *OrigV << "\nBy stripping back to:\n " << *V << "\n");
1605 return;
1606 }
1607 }
1608
1609 // This was the final opportunity to salvage this debug information, and it
1610 // couldn't be done. Place a poison DBG_VALUE at this location to terminate
1611 // any earlier variable location.
1612 assert(OrigV && "V shouldn't be null");
1613 auto *Poison = PoisonValue::get(OrigV->getType());
1614 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Poison, DL, SDNodeOrder);
1615 DAG.AddDbgValue(SDV, false);
1616 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n "
1617 << printDDI(OrigV, DDI) << "\n");
1618}
1619
1621 DIExpression *Expr,
1622 DebugLoc DbgLoc,
1623 unsigned Order) {
1627 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1628 /*IsVariadic*/ false);
1629}
1630
1632 DILocalVariable *Var,
1633 DIExpression *Expr, DebugLoc DbgLoc,
1634 unsigned Order, bool IsVariadic) {
1635 if (Values.empty())
1636 return true;
1637
1638 // Filter EntryValue locations out early.
1639 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1640 return true;
1641
1642 SmallVector<SDDbgOperand> LocationOps;
1643 SmallVector<SDNode *> Dependencies;
1644 for (const Value *V : Values) {
1645 // Constant value.
1648 LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1649 continue;
1650 }
1651
1652 // Look through IntToPtr constants.
1653 if (auto *CE = dyn_cast<ConstantExpr>(V))
1654 if (CE->getOpcode() == Instruction::IntToPtr) {
1655 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1656 continue;
1657 }
1658
1659 // If the Value is a frame index, we can create a FrameIndex debug value
1660 // without relying on the DAG at all.
1661 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1662 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1663 if (SI != FuncInfo.StaticAllocaMap.end()) {
1664 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1665 continue;
1666 }
1667 }
1668
1669 // Do not use getValue() in here; we don't want to generate code at
1670 // this point if it hasn't been done yet.
1671 SDValue N = NodeMap[V];
1672 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1673 N = UnusedArgNodeMap[V];
1674
1675 if (N.getNode()) {
1676 // Only emit func arg dbg value for non-variadic dbg.values for now.
1677 if (!IsVariadic &&
1678 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1679 FuncArgumentDbgValueKind::Value, N))
1680 return true;
1681 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1682 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1683 // describe stack slot locations.
1684 //
1685 // Consider "int x = 0; int *px = &x;". There are two kinds of
1686 // interesting debug values here after optimization:
1687 //
1688 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
1689 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1690 //
1691 // Both describe the direct values of their associated variables.
1692 Dependencies.push_back(N.getNode());
1693 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1694 continue;
1695 }
1696 LocationOps.emplace_back(
1697 SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1698 continue;
1699 }
1700
1701 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1702 // Special rules apply for the first dbg.values of parameter variables in a
1703 // function. Identify them by the fact they reference Argument Values, that
1704 // they're parameters, and they are parameters of the current function. We
1705 // need to let them dangle until they get an SDNode.
1706 bool IsParamOfFunc =
1707 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1708 if (IsParamOfFunc)
1709 return false;
1710
1711 // The value is not used in this block yet (or it would have an SDNode).
1712 // We still want the value to appear for the user if possible -- if it has
1713 // an associated VReg, we can refer to that instead.
1714 auto VMI = FuncInfo.ValueMap.find(V);
1715 if (VMI != FuncInfo.ValueMap.end()) {
1716 Register Reg = VMI->second;
1717 // If this is a PHI node, it may be split up into several MI PHI nodes
1718 // (in FunctionLoweringInfo::set).
1719 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1720 V->getType(), std::nullopt);
1721 if (RFV.occupiesMultipleRegs()) {
1722 // FIXME: We could potentially support variadic dbg_values here.
1723 if (IsVariadic)
1724 return false;
1725 unsigned Offset = 0;
1726 unsigned BitsToDescribe = 0;
1727 if (auto VarSize = Var->getSizeInBits())
1728 BitsToDescribe = *VarSize;
1729 if (auto Fragment = Expr->getFragmentInfo())
1730 BitsToDescribe = Fragment->SizeInBits;
1731 for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1732 // Bail out if all bits are described already.
1733 if (Offset >= BitsToDescribe)
1734 break;
1735 // TODO: handle scalable vectors.
1736 unsigned RegisterSize = RegAndSize.second;
1737 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1738 ? BitsToDescribe - Offset
1739 : RegisterSize;
1740 auto FragmentExpr = DIExpression::createFragmentExpression(
1741 Expr, Offset, FragmentSize);
1742 if (!FragmentExpr)
1743 continue;
1744 SDDbgValue *SDV = DAG.getVRegDbgValue(
1745 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1746 DAG.AddDbgValue(SDV, false);
1747 Offset += RegisterSize;
1748 }
1749 return true;
1750 }
1751 // We can use simple vreg locations for variadic dbg_values as well.
1752 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1753 continue;
1754 }
1755 // We failed to create a SDDbgOperand for V.
1756 return false;
1757 }
1758
1759 // We have created a SDDbgOperand for each Value in Values.
1760 assert(!LocationOps.empty());
1761 SDDbgValue *SDV =
1762 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1763 /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1764 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1765 return true;
1766}
1767
1769 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1770 for (auto &Pair : DanglingDebugInfoMap)
1771 for (auto &DDI : Pair.second)
1772 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1774}
1775
1776/// getCopyFromRegs - If there was virtual register allocated for the value V
1777/// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1779 auto It = FuncInfo.ValueMap.find(V);
1780 SDValue Result;
1781
1782 if (It != FuncInfo.ValueMap.end()) {
1783 Register InReg = It->second;
1784
1785 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1786 DAG.getDataLayout(), InReg, Ty,
1787 std::nullopt); // This is not an ABI copy.
1788 SDValue Chain = DAG.getEntryNode();
1789 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1790 V);
1791 resolveDanglingDebugInfo(V, Result);
1792 }
1793
1794 return Result;
1795}
1796
1797/// getValue - Return an SDValue for the given Value.
1799 // If we already have an SDValue for this value, use it. It's important
1800 // to do this first, so that we don't create a CopyFromReg if we already
1801 // have a regular SDValue.
1802 SDValue &N = NodeMap[V];
1803 if (N.getNode()) return N;
1804
1805 // If there's a virtual register allocated and initialized for this
1806 // value, use it.
1807 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1808 return copyFromReg;
1809
1810 // Otherwise create a new SDValue and remember it.
1811 SDValue Val = getValueImpl(V);
1812 NodeMap[V] = Val;
1814 return Val;
1815}
1816
1817void SelectionDAGBuilder::setValueToPoison(const Value *V, const SDLoc &dl) {
1818 if (V->getType()->isVoidTy())
1819 return;
1820
1821 SmallVector<EVT, 4> ValueVTs;
1822 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
1823 V->getType(), ValueVTs);
1824 setValue(V, DAG.getErrorMergeValues(ValueVTs, SDValue(), dl));
1825}
1826
1827/// getNonRegisterValue - Return an SDValue for the given Value, but
1828/// don't look in FuncInfo.ValueMap for a virtual register.
1830 // If we already have an SDValue for this value, use it.
1831 SDValue &N = NodeMap[V];
1832 if (N.getNode()) {
1833 if (isIntOrFPConstant(N)) {
1834 // Remove the debug location from the node as the node is about to be used
1835 // in a location which may differ from the original debug location. This
1836 // is relevant to Constant and ConstantFP nodes because they can appear
1837 // as constant expressions inside PHI nodes.
1838 N->setDebugLoc(DebugLoc());
1839 }
1840 return N;
1841 }
1842
1843 // Otherwise create a new SDValue and remember it.
1844 SDValue Val = getValueImpl(V);
1845 NodeMap[V] = Val;
1847 return Val;
1848}
1849
1850/// getValueImpl - Helper function for getValue and getNonRegisterValue.
1851/// Create an SDValue for the given value.
1853 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1854
1855 if (const Constant *C = dyn_cast<Constant>(V)) {
1856 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1857
1858 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1859 SDLoc DL = getCurSDLoc();
1860
1861 // DAG.getConstant() may attempt to legalise the vector constant which can
1862 // significantly change the combines applied to the DAG. To reduce the
1863 // divergence when enabling ConstantInt based vectors we try to construct
1864 // the DAG in the same way as shufflevector based splats. TODO: The
1865 // divergence sometimes leads to better optimisations. Ideally we should
1866 // prevent DAG.getConstant() from legalising too early but there are some
1867 // degradations preventing this.
1868 if (VT.isScalableVector())
1869 return DAG.getNode(
1870 ISD::SPLAT_VECTOR, DL, VT,
1871 DAG.getConstant(CI->getValue(), DL, VT.getVectorElementType()));
1872 if (VT.isFixedLengthVector())
1873 return DAG.getSplatBuildVector(
1874 VT, DL,
1875 DAG.getConstant(CI->getValue(), DL, VT.getVectorElementType()));
1876 return DAG.getConstant(*CI, DL, VT);
1877 }
1878
1879 if (const ConstantByte *CB = dyn_cast<ConstantByte>(C))
1880 return DAG.getConstant(CB->getValue(), getCurSDLoc(), VT);
1881
1882 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1883 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1884
1885 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) {
1886 return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT,
1887 getValue(CPA->getPointer()), getValue(CPA->getKey()),
1888 getValue(CPA->getAddrDiscriminator()),
1889 getValue(CPA->getDiscriminator()));
1890 }
1891
1893 return DAG.getConstant(0, getCurSDLoc(), VT);
1894
1895 if (match(C, m_VScale()))
1896 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1897
1898 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1899 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1900
1901 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1902 return isa<PoisonValue>(C) ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
1903
1904 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1905 visit(CE->getOpcode(), *CE);
1906 SDValue N1 = NodeMap[V];
1907 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1908 return N1;
1909 }
1910
1912 SmallVector<SDValue, 4> Constants;
1913 for (const Use &U : C->operands()) {
1914 SDNode *Val = getValue(U).getNode();
1915 // If the operand is an empty aggregate, there are no values.
1916 if (!Val) continue;
1917 // Add each leaf value from the operand to the Constants list
1918 // to form a flattened list of all the values.
1919 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1920 Constants.push_back(SDValue(Val, i));
1921 }
1922
1923 return DAG.getMergeValues(Constants, getCurSDLoc());
1924 }
1925
1926 if (const ConstantDataSequential *CDS =
1929 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i) {
1930 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1931 // Add each leaf value from the operand to the Constants list
1932 // to form a flattened list of all the values.
1933 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1934 Ops.push_back(SDValue(Val, i));
1935 }
1936
1937 if (isa<ArrayType>(CDS->getType()))
1938 return DAG.getMergeValues(Ops, getCurSDLoc());
1939 return DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1940 }
1941
1942 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1944 "Unknown struct or array constant!");
1945
1946 SmallVector<EVT, 4> ValueVTs;
1947 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1948 unsigned NumElts = ValueVTs.size();
1949 if (NumElts == 0)
1950 return SDValue(); // empty struct
1951 SmallVector<SDValue, 4> Constants(NumElts);
1952 for (unsigned i = 0; i != NumElts; ++i) {
1953 EVT EltVT = ValueVTs[i];
1954 if (isa<UndefValue>(C))
1955 Constants[i] = DAG.getUNDEF(EltVT);
1956 else if (EltVT.isFloatingPoint())
1957 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1958 else
1959 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1960 }
1961
1962 return DAG.getMergeValues(Constants, getCurSDLoc());
1963 }
1964
1965 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1966 return DAG.getBlockAddress(BA, VT);
1967
1968 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1969 return getValue(Equiv->getGlobalValue());
1970
1971 if (const auto *NC = dyn_cast<NoCFIValue>(C))
1972 return getValue(NC->getGlobalValue());
1973
1974 if (VT == MVT::aarch64svcount) {
1975 assert(C->isNullValue() && "Can only zero this target type!");
1976 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1977 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1978 }
1979
1980 if (VT.isRISCVVectorTuple()) {
1981 assert(C->isNullValue() && "Can only zero this target type!");
1982 return DAG.getNode(
1984 DAG.getNode(
1986 EVT::getVectorVT(*DAG.getContext(), MVT::i8,
1987 VT.getSizeInBits().getKnownMinValue() / 8, true),
1988 DAG.getConstant(0, getCurSDLoc(), MVT::getIntegerVT(8))));
1989 }
1990
1991 if (VT == MVT::externref || VT == MVT::funcref) {
1992 assert(C->isNullValue() && "Can only zero this target type!");
1993 // The zero value of a WebAssembly reference type is the null reference,
1994 // materialized with ref.null.
1995 Intrinsic::ID IID = VT == MVT::externref ? Intrinsic::wasm_ref_null_extern
1996 : Intrinsic::wasm_ref_null_func;
1997 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VT,
1998 DAG.getTargetConstant(IID, getCurSDLoc(), MVT::i32));
1999 }
2000
2001 VectorType *VecTy = cast<VectorType>(V->getType());
2002
2003 // Now that we know the number and type of the elements, get that number of
2004 // elements into the Ops array based on what kind of constant it is.
2005 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
2007 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
2008 for (unsigned i = 0; i != NumElements; ++i)
2009 Ops.push_back(getValue(CV->getOperand(i)));
2010
2011 return DAG.getBuildVector(VT, getCurSDLoc(), Ops);
2012 }
2013
2015 EVT EltVT =
2016 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
2017
2018 SDValue Op;
2019 if (EltVT.isFloatingPoint())
2020 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
2021 else
2022 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
2023
2024 return DAG.getSplat(VT, getCurSDLoc(), Op);
2025 }
2026
2027 llvm_unreachable("Unknown vector constant");
2028 }
2029
2030 // If this is a static alloca, generate it as the frameindex instead of
2031 // computation.
2032 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
2033 auto SI = FuncInfo.StaticAllocaMap.find(AI);
2034 if (SI != FuncInfo.StaticAllocaMap.end())
2035 return DAG.getFrameIndex(
2036 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
2037 }
2038
2039 // If this is an instruction which fast-isel has deferred, select it now.
2040 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
2041 Register InReg = FuncInfo.InitializeRegForValue(Inst);
2042 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
2043 Inst->getType(), std::nullopt);
2044 SDValue Chain = DAG.getEntryNode();
2045 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
2046 }
2047
2048 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
2049 return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
2050
2051 if (const auto *BB = dyn_cast<BasicBlock>(V))
2052 return DAG.getBasicBlock(FuncInfo.getMBB(BB));
2053
2054 llvm_unreachable("Can't get register for value!");
2055}
2056
2057void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
2059 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
2060 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
2061 bool IsSEH = isAsynchronousEHPersonality(Pers);
2062 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
2063 if (IsSEH) {
2064 // For SEH, EHCont Guard needs to know that this catchpad is a target.
2065 CatchPadMBB->setIsEHContTarget(true);
2067 } else
2068 CatchPadMBB->setIsEHScopeEntry();
2069 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
2070 if (IsMSVCCXX || IsCoreCLR)
2071 CatchPadMBB->setIsEHFuncletEntry();
2072}
2073
2074void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
2075 // Update machine-CFG edge.
2076 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor());
2077 FuncInfo.MBB->addSuccessor(TargetMBB);
2078
2079 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2080 bool IsSEH = isAsynchronousEHPersonality(Pers);
2081 if (IsSEH) {
2082 // If this is not a fall-through branch or optimizations are switched off,
2083 // emit the branch.
2084 if (TargetMBB != NextBlock(FuncInfo.MBB) ||
2085 TM.getOptLevel() == CodeGenOptLevel::None)
2086 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2087 getControlRoot(), DAG.getBasicBlock(TargetMBB)));
2088 return;
2089 }
2090
2091 // For non-SEH, EHCont Guard needs to know that this catchret is a target.
2092 TargetMBB->setIsEHContTarget(true);
2093 DAG.getMachineFunction().setHasEHContTarget(true);
2094
2095 // Figure out the funclet membership for the catchret's successor.
2096 // This will be used by the FuncletLayout pass to determine how to order the
2097 // BB's.
2098 // A 'catchret' returns to the outer scope's color.
2099 Value *ParentPad = I.getCatchSwitchParentPad();
2100 const BasicBlock *SuccessorColor;
2101 if (isa<ConstantTokenNone>(ParentPad))
2102 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2103 else
2104 SuccessorColor = cast<Instruction>(ParentPad)->getParent();
2105 assert(SuccessorColor && "No parent funclet for catchret!");
2106 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor);
2107 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2108
2109 // Create the terminator node.
2110 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2111 getControlRoot(), DAG.getBasicBlock(TargetMBB),
2112 DAG.getBasicBlock(SuccessorColorMBB));
2113 DAG.setRoot(Ret);
2114}
2115
2116void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2117 // Don't emit any special code for the cleanuppad instruction. It just marks
2118 // the start of an EH scope/funclet.
2119 FuncInfo.MBB->setIsEHScopeEntry();
2120 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2121 if (Pers != EHPersonality::Wasm_CXX) {
2122 FuncInfo.MBB->setIsEHFuncletEntry();
2123 FuncInfo.MBB->setIsCleanupFuncletEntry();
2124 }
2125}
2126
2127/// When an invoke or a cleanupret unwinds to the next EH pad, there are
2128/// many places it could ultimately go. In the IR, we have a single unwind
2129/// destination, but in the machine CFG, we enumerate all the possible blocks.
2130/// This function skips over imaginary basic blocks that hold catchswitch
2131/// instructions, and finds all the "real" machine
2132/// basic block destinations. As those destinations may not be successors of
2133/// EHPadBB, here we also calculate the edge probability to those destinations.
2134/// The passed-in Prob is the edge probability to EHPadBB.
2136 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2137 BranchProbability Prob,
2138 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2139 &UnwindDests) {
2140 EHPersonality Personality =
2142 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2143 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2144 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2145 bool IsSEH = isAsynchronousEHPersonality(Personality);
2146
2147 while (EHPadBB) {
2149 BasicBlock *NewEHPadBB = nullptr;
2150 if (isa<LandingPadInst>(Pad)) {
2151 // Stop on landingpads. They are not funclets.
2152 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2153 break;
2154 } else if (isa<CleanupPadInst>(Pad)) {
2155 // Stop on cleanup pads. Cleanups are always funclet entries for all known
2156 // personalities except Wasm. And in Wasm this becomes a catch_all(_ref),
2157 // which always catches an exception.
2158 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2159 UnwindDests.back().first->setIsEHScopeEntry();
2160 // In Wasm, EH scopes are not funclets
2161 if (!IsWasmCXX)
2162 UnwindDests.back().first->setIsEHFuncletEntry();
2163 break;
2164 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2165 // Add the catchpad handlers to the possible destinations.
2166 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2167 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2168 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2169 if (IsMSVCCXX || IsCoreCLR)
2170 UnwindDests.back().first->setIsEHFuncletEntry();
2171 if (!IsSEH)
2172 UnwindDests.back().first->setIsEHScopeEntry();
2173 }
2174 NewEHPadBB = CatchSwitch->getUnwindDest();
2175 } else {
2176 continue;
2177 }
2178
2179 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2180 if (BPI && NewEHPadBB)
2181 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2182 EHPadBB = NewEHPadBB;
2183 }
2184}
2185
2186void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2187 // Update successor info.
2189 auto UnwindDest = I.getUnwindDest();
2190 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2191 BranchProbability UnwindDestProb =
2192 (BPI && UnwindDest)
2193 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2195 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2196 for (auto &UnwindDest : UnwindDests) {
2197 UnwindDest.first->setIsEHPad();
2198 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2199 }
2200 FuncInfo.MBB->normalizeSuccProbs();
2201
2202 // Create the terminator node.
2203 MachineBasicBlock *CleanupPadMBB =
2204 FuncInfo.getMBB(I.getCleanupPad()->getParent());
2205 SDValue Ret = DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other,
2206 getControlRoot(), DAG.getBasicBlock(CleanupPadMBB));
2207 DAG.setRoot(Ret);
2208}
2209
2210void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2211 report_fatal_error("visitCatchSwitch not yet implemented!");
2212}
2213
2214void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2215 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2216 auto &DL = DAG.getDataLayout();
2217 SDValue Chain = getControlRoot();
2220
2221 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2222 // lower
2223 //
2224 // %val = call <ty> @llvm.experimental.deoptimize()
2225 // ret <ty> %val
2226 //
2227 // differently.
2228 if (I.getParent()->getTerminatingDeoptimizeCall()) {
2230 return;
2231 }
2232
2233 if (!FuncInfo.CanLowerReturn) {
2234 Register DemoteReg = FuncInfo.DemoteRegister;
2235
2236 // Emit a store of the return value through the virtual register.
2237 // Leave Outs empty so that LowerReturn won't try to load return
2238 // registers the usual way.
2239 MVT PtrValueVT = TLI.getPointerTy(DL, DL.getAllocaAddrSpace());
2240 SDValue RetPtr =
2241 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVT);
2242 Type *RetTy = I.getOperand(0)->getType();
2243 Align BaseAlign = DL.getPrefTypeAlign(RetTy);
2244 RetPtr =
2245 TLI.annotateStackObjectPointer(RetPtr, DAG, getCurSDLoc(), BaseAlign);
2246 SDValue RetOp = getValue(I.getOperand(0));
2247
2248 SmallVector<EVT, 4> ValueVTs, MemVTs;
2249 SmallVector<uint64_t, 4> Offsets;
2250 ComputeValueVTs(TLI, DL, RetTy, ValueVTs, &MemVTs, &Offsets, 0);
2251 unsigned NumValues = ValueVTs.size();
2252
2253 SmallVector<SDValue, 4> Chains(NumValues);
2254 for (unsigned i = 0; i != NumValues; ++i) {
2255 // An aggregate return value cannot wrap around the address space, so
2256 // offsets to its parts don't wrap either.
2257 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2258 TypeSize::getFixed(Offsets[i]));
2259
2260 SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2261 if (MemVTs[i] != ValueVTs[i])
2262 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2263 Chains[i] = DAG.getStore(
2264 Chain, getCurSDLoc(), Val,
2265 // FIXME: better loc info would be nice.
2266 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2267 commonAlignment(BaseAlign, Offsets[i]));
2268 }
2269
2270 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2271 MVT::Other, Chains);
2272 } else if (I.getNumOperands() != 0) {
2274 ComputeValueTypes(DL, I.getOperand(0)->getType(), Types);
2275 unsigned NumValues = Types.size();
2276 if (NumValues) {
2277 SDValue RetOp = getValue(I.getOperand(0));
2278
2279 const Function *F = I.getParent()->getParent();
2280
2281 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2282 I.getOperand(0)->getType(), F->getCallingConv(),
2283 /*IsVarArg*/ false, DL);
2284
2285 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2286 if (F->getAttributes().hasRetAttr(Attribute::SExt))
2287 ExtendKind = ISD::SIGN_EXTEND;
2288 else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2289 ExtendKind = ISD::ZERO_EXTEND;
2290
2291 LLVMContext &Context = F->getContext();
2292 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2293
2294 for (unsigned j = 0; j != NumValues; ++j) {
2295 EVT VT = TLI.getValueType(DL, Types[j]);
2296
2297 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2298 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2299
2300 CallingConv::ID CC = F->getCallingConv();
2301
2302 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2303 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2304 SmallVector<SDValue, 4> Parts(NumParts);
2306 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2307 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2308
2309 // 'inreg' on function refers to return value
2310 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2311 if (RetInReg)
2312 Flags.setInReg();
2313
2314 if (I.getOperand(0)->getType()->isPointerTy()) {
2315 Flags.setPointer();
2316 Flags.setPointerAddrSpace(
2317 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2318 }
2319
2320 if (NeedsRegBlock) {
2321 Flags.setInConsecutiveRegs();
2322 if (j == NumValues - 1)
2323 Flags.setInConsecutiveRegsLast();
2324 }
2325
2326 // Propagate extension type if any
2327 if (ExtendKind == ISD::SIGN_EXTEND)
2328 Flags.setSExt();
2329 else if (ExtendKind == ISD::ZERO_EXTEND)
2330 Flags.setZExt();
2331 else if (F->getAttributes().hasRetAttr(Attribute::NoExt))
2332 Flags.setNoExt();
2333
2334 for (unsigned i = 0; i < NumParts; ++i) {
2335 Outs.push_back(ISD::OutputArg(Flags,
2336 Parts[i].getValueType().getSimpleVT(),
2337 VT, Types[j], 0, 0));
2338 OutVals.push_back(Parts[i]);
2339 }
2340 }
2341 }
2342 }
2343
2344 // Push in swifterror virtual register as the last element of Outs. This makes
2345 // sure swifterror virtual register will be returned in the swifterror
2346 // physical register.
2347 const Function *F = I.getParent()->getParent();
2348 if (TLI.supportSwiftError() &&
2349 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2350 assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2351 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2352 Flags.setSwiftError();
2353 Outs.push_back(ISD::OutputArg(Flags, /*vt=*/TLI.getPointerTy(DL),
2354 /*argvt=*/EVT(TLI.getPointerTy(DL)),
2355 PointerType::getUnqual(*DAG.getContext()),
2356 /*origidx=*/1, /*partOffs=*/0));
2357 // Create SDNode for the swifterror virtual register.
2358 OutVals.push_back(
2359 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2360 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2361 EVT(TLI.getPointerTy(DL))));
2362 }
2363
2364 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2365 CallingConv::ID CallConv =
2366 DAG.getMachineFunction().getFunction().getCallingConv();
2367 Chain = DAG.getTargetLoweringInfo().LowerReturn(
2368 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2369
2370 // Verify that the target's LowerReturn behaved as expected.
2371 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2372 "LowerReturn didn't return a valid chain!");
2373
2374 // Update the DAG with the new chain value resulting from return lowering.
2375 DAG.setRoot(Chain);
2376}
2377
2378/// CopyToExportRegsIfNeeded - If the given value has virtual registers
2379/// created for it, emit nodes to copy the value into the virtual
2380/// registers.
2382 // Skip empty types
2383 if (V->getType()->isEmptyTy())
2384 return;
2385
2386 auto VMI = FuncInfo.ValueMap.find(V);
2387 if (VMI != FuncInfo.ValueMap.end()) {
2388 assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2389 "Unused value assigned virtual registers!");
2390 CopyValueToVirtualRegister(V, VMI->second);
2391 }
2392}
2393
2394/// ExportFromCurrentBlock - If this condition isn't known to be exported from
2395/// the current basic block, add it to ValueMap now so that we'll get a
2396/// CopyTo/FromReg.
2398 // No need to export constants.
2399 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2400
2401 // Already exported?
2402 if (FuncInfo.isExportedInst(V)) return;
2403
2404 Register Reg = FuncInfo.InitializeRegForValue(V);
2406}
2407
2409 const BasicBlock *FromBB) {
2410 // The operands of the setcc have to be in this block. We don't know
2411 // how to export them from some other block.
2412 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2413 // Can export from current BB.
2414 if (VI->getParent() == FromBB)
2415 return true;
2416
2417 // Is already exported, noop.
2418 return FuncInfo.isExportedInst(V);
2419 }
2420
2421 // If this is an argument, we can export it if the BB is the entry block or
2422 // if it is already exported.
2423 if (isa<Argument>(V)) {
2424 if (FromBB->isEntryBlock())
2425 return true;
2426
2427 // Otherwise, can only export this if it is already exported.
2428 return FuncInfo.isExportedInst(V);
2429 }
2430
2431 // Otherwise, constants can always be exported.
2432 return true;
2433}
2434
2435/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2437SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2438 const MachineBasicBlock *Dst) const {
2440 const BasicBlock *SrcBB = Src->getBasicBlock();
2441 const BasicBlock *DstBB = Dst->getBasicBlock();
2442 if (!BPI) {
2443 // If BPI is not available, set the default probability as 1 / N, where N is
2444 // the number of successors.
2445 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2446 return BranchProbability(1, SuccSize);
2447 }
2448 return BPI->getEdgeProbability(SrcBB, DstBB);
2449}
2450
2451void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2452 MachineBasicBlock *Dst,
2453 BranchProbability Prob) {
2454 if (!FuncInfo.BPI)
2455 Src->addSuccessorWithoutProb(Dst);
2456 else {
2457 if (Prob.isUnknown())
2458 Prob = getEdgeProbability(Src, Dst);
2459 Src->addSuccessor(Dst, Prob);
2460 }
2461}
2462
2463static bool InBlock(const Value *V, const BasicBlock *BB) {
2464 if (const Instruction *I = dyn_cast<Instruction>(V))
2465 return I->getParent() == BB;
2466 return true;
2467}
2468
2469/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2470/// This function emits a branch and is used at the leaves of an OR or an
2471/// AND operator tree.
2472void
2475 MachineBasicBlock *FBB,
2476 MachineBasicBlock *CurBB,
2477 MachineBasicBlock *SwitchBB,
2478 BranchProbability TProb,
2479 BranchProbability FProb,
2480 bool InvertCond) {
2481 const BasicBlock *BB = CurBB->getBasicBlock();
2482
2483 // If the leaf of the tree is a comparison, merge the condition into
2484 // the caseblock.
2485 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2486 // The operands of the cmp have to be in this block. We don't know
2487 // how to export them from some other block. If this is the first block
2488 // of the sequence, no exporting is needed.
2489 if (CurBB == SwitchBB ||
2490 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2491 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2492 ISD::CondCode Condition;
2493 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2494 ICmpInst::Predicate Pred =
2495 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2496 Condition = getICmpCondCode(Pred);
2497 } else {
2498 const FCmpInst *FC = cast<FCmpInst>(Cond);
2499 FCmpInst::Predicate Pred =
2500 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2501 Condition = getFCmpCondCode(Pred);
2502 if (FC->hasNoNaNs() ||
2503 (isKnownNeverNaN(FC->getOperand(0),
2504 SimplifyQuery(DAG.getDataLayout(), FC)) &&
2505 isKnownNeverNaN(FC->getOperand(1),
2506 SimplifyQuery(DAG.getDataLayout(), FC))))
2507 Condition = getFCmpCodeWithoutNaN(Condition);
2508 }
2509
2510 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2511 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2512 SL->SwitchCases.push_back(CB);
2513 return;
2514 }
2515 }
2516
2517 // Create a CaseBlock record representing this branch.
2518 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2519 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2520 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2521 SL->SwitchCases.push_back(CB);
2522}
2523
2524// Collect dependencies on V recursively. This is used for the cost analysis in
2525// `shouldKeepJumpConditionsTogether`.
2529 unsigned Depth = 0) {
2530 // Return false if we have an incomplete count.
2532 return false;
2533
2534 auto *I = dyn_cast<Instruction>(V);
2535 if (I == nullptr)
2536 return true;
2537
2538 if (Necessary != nullptr) {
2539 // This instruction is necessary for the other side of the condition so
2540 // don't count it.
2541 if (Necessary->contains(I))
2542 return true;
2543 }
2544
2545 // Already added this dep.
2546 if (!Deps->try_emplace(I, false).second)
2547 return true;
2548
2549 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2550 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2551 Depth + 1))
2552 return false;
2553 return true;
2554}
2555
2558 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2560 if (Params.BaseCost < 0)
2561 return false;
2562
2563 // Baseline cost.
2564 InstructionCost CostThresh = Params.BaseCost;
2565
2566 BranchProbabilityInfo *BPI = nullptr;
2567 if (Params.LikelyBias || Params.UnlikelyBias)
2568 BPI = FuncInfo.BPI;
2569 if (BPI != nullptr) {
2570 // See if we are either likely to get an early out or compute both lhs/rhs
2571 // of the condition.
2572 BasicBlock *IfFalse = I.getSuccessor(0);
2573 BasicBlock *IfTrue = I.getSuccessor(1);
2574
2575 std::optional<bool> Likely;
2576 if (BPI->isEdgeHot(I.getParent(), IfTrue))
2577 Likely = true;
2578 else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2579 Likely = false;
2580
2581 if (Likely) {
2582 if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2583 // Its likely we will have to compute both lhs and rhs of condition
2584 CostThresh += Params.LikelyBias;
2585 else {
2586 if (Params.UnlikelyBias < 0)
2587 return false;
2588 // Its likely we will get an early out.
2589 CostThresh -= Params.UnlikelyBias;
2590 }
2591 }
2592 }
2593
2594 if (CostThresh <= 0)
2595 return false;
2596
2597 // Collect "all" instructions that lhs condition is dependent on.
2598 // Use map for stable iteration (to avoid non-determanism of iteration of
2599 // SmallPtrSet). The `bool` value is just a dummy.
2601 collectInstructionDeps(&LhsDeps, Lhs);
2602 // Collect "all" instructions that rhs condition is dependent on AND are
2603 // dependencies of lhs. This gives us an estimate on which instructions we
2604 // stand to save by splitting the condition.
2605 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2606 return false;
2607 // Add the compare instruction itself unless its a dependency on the LHS.
2608 if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2609 if (!LhsDeps.contains(RhsI))
2610 RhsDeps.try_emplace(RhsI, false);
2611
2612 InstructionCost CostOfIncluding = 0;
2613 // See if this instruction will need to computed independently of whether RHS
2614 // is.
2615 Value *BrCond = I.getCondition();
2616 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2617 for (const auto *U : Ins->users()) {
2618 // If user is independent of RHS calculation we don't need to count it.
2619 if (auto *UIns = dyn_cast<Instruction>(U))
2620 if (UIns != BrCond && !RhsDeps.contains(UIns))
2621 return false;
2622 }
2623 return true;
2624 };
2625
2626 // Prune instructions from RHS Deps that are dependencies of unrelated
2627 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2628 // arbitrary and just meant to cap the how much time we spend in the pruning
2629 // loop. Its highly unlikely to come into affect.
2630 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2631 // Stop after a certain point. No incorrectness from including too many
2632 // instructions.
2633 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2634 const Instruction *ToDrop = nullptr;
2635 for (const auto &InsPair : RhsDeps) {
2636 if (!ShouldCountInsn(InsPair.first)) {
2637 ToDrop = InsPair.first;
2638 break;
2639 }
2640 }
2641 if (ToDrop == nullptr)
2642 break;
2643 RhsDeps.erase(ToDrop);
2644 }
2645
2646 for (const auto &InsPair : RhsDeps) {
2647 // Finally accumulate latency that we can only attribute to computing the
2648 // RHS condition. Use latency because we are essentially trying to calculate
2649 // the cost of the dependency chain.
2650 // Possible TODO: We could try to estimate ILP and make this more precise.
2651 CostOfIncluding += TTI->getInstructionCost(
2652 InsPair.first, TargetTransformInfo::TCK_Latency);
2653
2654 if (CostOfIncluding > CostThresh)
2655 return false;
2656 }
2657 return true;
2658}
2659
2662 MachineBasicBlock *FBB,
2663 MachineBasicBlock *CurBB,
2664 MachineBasicBlock *SwitchBB,
2666 BranchProbability TProb,
2667 BranchProbability FProb,
2668 bool InvertCond) {
2669 // Skip over not part of the tree and remember to invert op and operands at
2670 // next level.
2671 Value *NotCond;
2672 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2673 InBlock(NotCond, CurBB->getBasicBlock())) {
2674 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2675 !InvertCond);
2676 return;
2677 }
2678
2680 const Value *BOpOp0, *BOpOp1;
2681 // Compute the effective opcode for Cond, taking into account whether it needs
2682 // to be inverted, e.g.
2683 // and (not (or A, B)), C
2684 // gets lowered as
2685 // and (and (not A, not B), C)
2687 if (BOp) {
2688 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2689 ? Instruction::And
2690 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2691 ? Instruction::Or
2693 if (InvertCond) {
2694 if (BOpc == Instruction::And)
2695 BOpc = Instruction::Or;
2696 else if (BOpc == Instruction::Or)
2697 BOpc = Instruction::And;
2698 }
2699 }
2700
2701 // If this node is not part of the or/and tree, emit it as a branch.
2702 // Note that all nodes in the tree should have same opcode.
2703 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2704 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2705 !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2706 !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2707 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2708 TProb, FProb, InvertCond);
2709 return;
2710 }
2711
2712 // Create TmpBB after CurBB.
2713 MachineFunction::iterator BBI(CurBB);
2714 MachineFunction &MF = DAG.getMachineFunction();
2716 CurBB->getParent()->insert(++BBI, TmpBB);
2717
2718 if (Opc == Instruction::Or) {
2719 // Codegen X | Y as:
2720 // BB1:
2721 // jmp_if_X TBB
2722 // jmp TmpBB
2723 // TmpBB:
2724 // jmp_if_Y TBB
2725 // jmp FBB
2726 //
2727
2728 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2729 // The requirement is that
2730 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2731 // = TrueProb for original BB.
2732 // Assuming the original probabilities are A and B, one choice is to set
2733 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2734 // A/(1+B) and 2B/(1+B). This choice assumes that
2735 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2736 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2737 // TmpBB, but the math is more complicated.
2738
2739 auto NewTrueProb = TProb / 2;
2740 auto NewFalseProb = TProb / 2 + FProb;
2741 // Emit the LHS condition.
2742 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2743 NewFalseProb, InvertCond);
2744
2745 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2746 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2748 // Emit the RHS condition into TmpBB.
2749 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2750 Probs[1], InvertCond);
2751 } else {
2752 assert(Opc == Instruction::And && "Unknown merge op!");
2753 // Codegen X & Y as:
2754 // BB1:
2755 // jmp_if_X TmpBB
2756 // jmp FBB
2757 // TmpBB:
2758 // jmp_if_Y TBB
2759 // jmp FBB
2760 //
2761 // This requires creation of TmpBB after CurBB.
2762
2763 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2764 // The requirement is that
2765 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2766 // = FalseProb for original BB.
2767 // Assuming the original probabilities are A and B, one choice is to set
2768 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2769 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2770 // TrueProb for BB1 * FalseProb for TmpBB.
2771
2772 auto NewTrueProb = TProb + FProb / 2;
2773 auto NewFalseProb = FProb / 2;
2774 // Emit the LHS condition.
2775 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2776 NewFalseProb, InvertCond);
2777
2778 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2779 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2781 // Emit the RHS condition into TmpBB.
2782 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2783 Probs[1], InvertCond);
2784 }
2785}
2786
2787/// If the set of cases should be emitted as a series of branches, return true.
2788/// If we should emit this as a bunch of and/or'd together conditions, return
2789/// false.
2790bool
2791SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2792 if (Cases.size() != 2) return true;
2793
2794 // If this is two comparisons of the same values or'd or and'd together, they
2795 // will get folded into a single comparison, so don't emit two blocks.
2796 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2797 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2798 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2799 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2800 return false;
2801 }
2802
2803 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2804 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2805 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2806 Cases[0].CC == Cases[1].CC &&
2807 isa<Constant>(Cases[0].CmpRHS) &&
2808 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2809 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2810 return false;
2811 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2812 return false;
2813 }
2814
2815 return true;
2816}
2817
2818void SelectionDAGBuilder::visitUncondBr(const UncondBrInst &I) {
2820
2821 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2822
2823 // Update machine-CFG edges.
2824 BrMBB->addSuccessor(Succ0MBB);
2825
2826 // If this is not a fall-through branch or optimizations are switched off,
2827 // emit the branch.
2828 if (Succ0MBB != NextBlock(BrMBB) ||
2830 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2831 DAG.getBasicBlock(Succ0MBB));
2832 setValue(&I, Br);
2833 DAG.setRoot(Br);
2834 }
2835}
2836
2837void SelectionDAGBuilder::visitCondBr(const CondBrInst &I) {
2838 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2839
2840 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2841
2842 // If this condition is one of the special cases we handle, do special stuff
2843 // now.
2844 const Value *CondVal = I.getCondition();
2845 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1));
2846
2847 // If this is a series of conditions that are or'd or and'd together, emit
2848 // this as a sequence of branches instead of setcc's with and/or operations.
2849 // As long as jumps are not expensive (exceptions for multi-use logic ops,
2850 // unpredictable branches, and vector extracts because those jumps are likely
2851 // expensive for any target), this should improve performance.
2852 // For example, instead of something like:
2853 // cmp A, B
2854 // C = seteq
2855 // cmp D, E
2856 // F = setle
2857 // or C, F
2858 // jnz foo
2859 // Emit:
2860 // cmp A, B
2861 // je foo
2862 // cmp D, E
2863 // jle foo
2864 bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2865 const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2866 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2867 BOp->hasOneUse() && !IsUnpredictable) {
2868 Value *Vec;
2869 const Value *BOp0, *BOp1;
2871 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2872 Opcode = Instruction::And;
2873 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2874 Opcode = Instruction::Or;
2875
2876 if (Opcode &&
2877 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2878 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2880 FuncInfo, I, Opcode, BOp0, BOp1,
2881 DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2882 Opcode, BOp0, BOp1, FuncInfo.Fn))) {
2883 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2884 getEdgeProbability(BrMBB, Succ0MBB),
2885 getEdgeProbability(BrMBB, Succ1MBB),
2886 /*InvertCond=*/false);
2887 // If the compares in later blocks need to use values not currently
2888 // exported from this block, export them now. This block should always
2889 // be the first entry.
2890 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2891
2892 // Allow some cases to be rejected.
2893 if (ShouldEmitAsBranches(SL->SwitchCases)) {
2894 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2895 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2896 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2897 }
2898
2899 // Emit the branch for this block.
2900 visitSwitchCase(SL->SwitchCases[0], BrMBB);
2901 SL->SwitchCases.erase(SL->SwitchCases.begin());
2902 return;
2903 }
2904
2905 // Okay, we decided not to do this, remove any inserted MBB's and clear
2906 // SwitchCases.
2907 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2908 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2909
2910 SL->SwitchCases.clear();
2911 }
2912 }
2913
2914 // Create a CaseBlock record representing this branch.
2915 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2916 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2918 IsUnpredictable);
2919
2920 // Use visitSwitchCase to actually insert the fast branch sequence for this
2921 // cond branch.
2922 visitSwitchCase(CB, BrMBB);
2923}
2924
2925/// visitSwitchCase - Emits the necessary code to represent a single node in
2926/// the binary search tree resulting from lowering a switch instruction.
2928 MachineBasicBlock *SwitchBB) {
2929 SDValue Cond;
2930 SDValue CondLHS = getValue(CB.CmpLHS);
2931 SDLoc dl = CB.DL;
2932
2933 if (CB.CC == ISD::SETTRUE) {
2934 // Branch or fall through to TrueBB.
2935 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2936 SwitchBB->normalizeSuccProbs();
2937 if (CB.TrueBB != NextBlock(SwitchBB)) {
2938 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2939 DAG.getBasicBlock(CB.TrueBB)));
2940 }
2941 return;
2942 }
2943
2944 auto &TLI = DAG.getTargetLoweringInfo();
2945 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2946
2947 // Build the setcc now.
2948 if (!CB.CmpMHS) {
2949 // Fold "(X == true)" to X and "(X == false)" to !X to
2950 // handle common cases produced by branch lowering.
2951 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2952 CB.CC == ISD::SETEQ)
2953 Cond = CondLHS;
2954 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2955 CB.CC == ISD::SETEQ) {
2956 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2957 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2958 } else {
2959 SDValue CondRHS = getValue(CB.CmpRHS);
2960
2961 // If a pointer's DAG type is larger than its memory type then the DAG
2962 // values are zero-extended. This breaks signed comparisons so truncate
2963 // back to the underlying type before doing the compare.
2964 if (CondLHS.getValueType() != MemVT) {
2965 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2966 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2967 }
2968 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2969 }
2970 } else {
2971 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2972
2973 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2974 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2975
2976 SDValue CmpOp = getValue(CB.CmpMHS);
2977 EVT VT = CmpOp.getValueType();
2978
2979 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2980 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2981 ISD::SETLE);
2982 } else {
2983 SDValue SUB = DAG.getNode(ISD::SUB, dl,
2984 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2985 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2986 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2987 }
2988 }
2989
2990 // Update successor info
2991 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2992 // TrueBB and FalseBB are always different unless the incoming IR is
2993 // degenerate. This only happens when running llc on weird IR.
2994 if (CB.TrueBB != CB.FalseBB)
2995 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2996 SwitchBB->normalizeSuccProbs();
2997
2998 // If the lhs block is the next block, invert the condition so that we can
2999 // fall through to the lhs instead of the rhs block.
3000 if (CB.TrueBB == NextBlock(SwitchBB)) {
3001 std::swap(CB.TrueBB, CB.FalseBB);
3002 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
3003 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
3004 }
3005
3006 SDNodeFlags Flags;
3008 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3009 Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
3010
3011 setValue(CurInst, BrCond);
3012
3013 // Insert the false branch. Do this even if it's a fall through branch,
3014 // this makes it easier to do DAG optimizations which require inverting
3015 // the branch condition.
3016 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3017 DAG.getBasicBlock(CB.FalseBB));
3018
3019 DAG.setRoot(BrCond);
3020}
3021
3022/// visitJumpTable - Emit JumpTable node in the current MBB
3024 // Emit the code for the jump table
3025 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3026 assert(JT.Reg && "Should lower JT Header first!");
3027 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
3028 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
3029 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
3030 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
3031 Index.getValue(1), Table, Index);
3032 DAG.setRoot(BrJumpTable);
3033}
3034
3035/// visitJumpTableHeader - This function emits necessary code to produce index
3036/// in the JumpTable from switch case.
3038 JumpTableHeader &JTH,
3039 MachineBasicBlock *SwitchBB) {
3040 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3041 const SDLoc &dl = *JT.SL;
3042
3043 // Subtract the lowest switch case value from the value being switched on.
3044 SDValue SwitchOp = getValue(JTH.SValue);
3045 EVT VT = SwitchOp.getValueType();
3046 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3047 DAG.getConstant(JTH.First, dl, VT));
3048
3049 // The SDNode we just created, which holds the value being switched on minus
3050 // the smallest case value, needs to be copied to a virtual register so it
3051 // can be used as an index into the jump table in a subsequent basic block.
3052 // This value may be smaller or larger than the target's pointer type, and
3053 // therefore require extension or truncating.
3054 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3055 SwitchOp =
3056 DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3057
3058 Register JumpTableReg =
3059 FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3060 SDValue CopyTo =
3061 DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3062 JT.Reg = JumpTableReg;
3063
3064 if (!JTH.FallthroughUnreachable) {
3065 // Emit the range check for the jump table, and branch to the default block
3066 // for the switch statement if the value being switched on exceeds the
3067 // largest case in the switch.
3068 SDValue CMP = DAG.getSetCC(
3069 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3070 Sub.getValueType()),
3071 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3072
3073 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3074 MVT::Other, CopyTo, CMP,
3075 DAG.getBasicBlock(JT.Default));
3076
3077 // Avoid emitting unnecessary branches to the next block.
3078 if (JT.MBB != NextBlock(SwitchBB))
3079 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3080 DAG.getBasicBlock(JT.MBB));
3081
3082 DAG.setRoot(BrCond);
3083 } else {
3084 // Avoid emitting unnecessary branches to the next block.
3085 if (JT.MBB != NextBlock(SwitchBB))
3086 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3087 DAG.getBasicBlock(JT.MBB)));
3088 else
3089 DAG.setRoot(CopyTo);
3090 }
3091}
3092
3093/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3094/// variable if there exists one.
3096 SDValue &Chain) {
3097 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3098 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3099 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3101 Value *Global =
3104 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3105 if (Global) {
3106 MachinePointerInfo MPInfo(Global);
3110 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
3111 DAG.setNodeMemRefs(Node, {MemRef});
3112 }
3113 if (PtrTy != PtrMemTy)
3114 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3115 return SDValue(Node, 0);
3116}
3117
3118/// Codegen a new tail for a stack protector check ParentMBB which has had its
3119/// tail spliced into a stack protector check success bb.
3120///
3121/// For a high level explanation of how this fits into the stack protector
3122/// generation see the comment on the declaration of class
3123/// StackProtectorDescriptor.
3125 MachineBasicBlock *ParentBB) {
3126
3127 // First create the loads to the guard/stack slot for the comparison.
3128 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3129 auto &DL = DAG.getDataLayout();
3130 EVT PtrTy = TLI.getFrameIndexTy(DL);
3131 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3132
3133 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3134 int FI = MFI.getStackProtectorIndex();
3135
3136 SDValue Guard;
3137 SDLoc dl = getCurSDLoc();
3138 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3139 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3140 Align Align = DL.getPrefTypeAlign(
3141 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3142
3143 // Generate code to load the content of the guard slot.
3144 SDValue GuardVal = DAG.getLoad(
3145 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3146 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3148
3149 // If cookie mixing is enabled, unmix the stored GuardVal to get back the
3150 // original cookie for comparison. The prologue stored (FP - Cookie) or
3151 // (FP XOR Cookie), so we apply the same operation again to unmix:
3152 // FP - (FP - Cookie) = Cookie, or (FP XOR Cookie) XOR FP = Cookie.
3153 if (TLI.useStackGuardMixFP())
3154 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3155
3156 // If we're using function-based instrumentation, call the guard check
3157 // function
3159 // Get the guard check function from the target and verify it exists since
3160 // we're using function-based instrumentation
3161 const Function *GuardCheckFn =
3162 TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3163 assert(GuardCheckFn && "Guard check function is null");
3164
3165 // The target provides a guard check function to validate the guard value.
3166 // Generate a call to that function with the content of the guard slot as
3167 // argument.
3168 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3169 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3170
3172 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3173 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3174 Entry.IsInReg = true;
3175 Args.push_back(Entry);
3176
3179 .setChain(DAG.getEntryNode())
3180 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3181 getValue(GuardCheckFn), std::move(Args));
3182
3183 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3184 DAG.setRoot(Result.second);
3185 return;
3186 }
3187
3188 // Load the fresh guard value for comparison.
3189 // For targets that mix the cookie in LOAD_STACK_GUARD expansion, we need to
3190 // load directly without using LOAD_STACK_GUARD to avoid unwanted mixing.
3191 SDValue Chain = DAG.getEntryNode();
3192 if (TLI.useStackGuardMixFP()) {
3193 // Mixing targets: load cookie directly to avoid mixing in LOAD_STACK_GUARD
3194 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3195 SDValue GuardPtr = getValue(IRGuard);
3196 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3197 MachinePointerInfo(IRGuard, 0), Align,
3199 } else {
3200 LLVMContext &Ctx = *DAG.getContext();
3201 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3202 Guard = DAG.getPOISON(PtrMemTy);
3203 }
3204 } else {
3205 // Non-mixing targets: use LOAD_STACK_GUARD or direct load as usual
3206 if (TLI.useLoadStackGuardNode(M)) {
3207 Guard = getLoadStackGuard(DAG, dl, Chain);
3208 } else {
3209 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3210 SDValue GuardPtr = getValue(IRGuard);
3211 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3212 MachinePointerInfo(IRGuard, 0), Align,
3214 } else {
3215 LLVMContext &Ctx = *DAG.getContext();
3216 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3217 Guard = DAG.getPOISON(PtrMemTy);
3218 }
3219 }
3220 }
3221
3222 // Now both Guard (fresh cookie) and GuardVal (unmixed from stored value)
3223 // contain unmixed cookie values that can be compared directly.
3224
3225 // Perform the comparison via a getsetcc.
3226 SDValue Cmp = DAG.getSetCC(
3227 dl, TLI.getSetCCResultType(DL, *DAG.getContext(), Guard.getValueType()),
3228 Guard, GuardVal, ISD::SETNE);
3229
3230 // If the guard/stackslot do not equal, branch to failure MBB.
3231 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3232 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3233 // Otherwise branch to success MBB.
3234 SDValue Br = DAG.getNode(ISD::BR, dl,
3235 MVT::Other, BrCond,
3236 DAG.getBasicBlock(SPD.getSuccessMBB()));
3237
3238 DAG.setRoot(Br);
3239}
3240
3241/// Codegen the failure basic block for a stack protector check.
3242///
3243/// A failure stack protector machine basic block consists simply of a call to
3244/// __stack_chk_fail().
3245///
3246/// For a high level explanation of how this fits into the stack protector
3247/// generation see the comment on the declaration of class
3248/// StackProtectorDescriptor.
3251
3252 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3253 MachineBasicBlock *ParentBB = SPD.getParentMBB();
3254 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3255 SDValue Chain;
3256
3257 // For -Oz builds with a guard check function, we use function-based
3258 // instrumentation. Otherwise, if we have a guard check function, we call it
3259 // in the failure block.
3260 auto *GuardCheckFn = TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3261 if (GuardCheckFn && !SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3262 // First create the loads to the guard/stack slot for the comparison.
3263 auto &DL = DAG.getDataLayout();
3264 EVT PtrTy = TLI.getFrameIndexTy(DL);
3265 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3266
3267 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3268 int FI = MFI.getStackProtectorIndex();
3269
3270 SDLoc dl = getCurSDLoc();
3271 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3272 Align Align = DL.getPrefTypeAlign(
3273 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3274
3275 // Generate code to load the content of the guard slot.
3276 SDValue GuardVal = DAG.getLoad(
3277 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3278 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3280
3281 if (TLI.useStackGuardMixFP())
3282 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3283
3284 // The target provides a guard check function to validate the guard value.
3285 // Generate a call to that function with the content of the guard slot as
3286 // argument.
3287 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3288 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3289
3291 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3292 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3293 Entry.IsInReg = true;
3294 Args.push_back(Entry);
3295
3298 .setChain(DAG.getEntryNode())
3299 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3300 getValue(GuardCheckFn), std::move(Args));
3301
3302 Chain = TLI.LowerCallTo(CLI).second;
3303 } else {
3305 CallOptions.setDiscardResult(true);
3306 Chain = TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3307 {}, CallOptions, getCurSDLoc())
3308 .second;
3309 }
3310
3311 // Emit a trap instruction if we are required to do so.
3312 const TargetOptions &TargetOpts = DAG.getTarget().Options;
3313 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3314 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3315
3316 DAG.setRoot(Chain);
3317}
3318
3319/// visitBitTestHeader - This function emits necessary code to produce value
3320/// suitable for "bit tests"
3322 MachineBasicBlock *SwitchBB) {
3323 SDLoc dl = getCurSDLoc();
3324
3325 // Subtract the minimum value.
3326 SDValue SwitchOp = getValue(B.SValue);
3327 EVT VT = SwitchOp.getValueType();
3328 SDValue RangeSub =
3329 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3330
3331 // Determine the type of the test operands.
3332 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3333 bool UsePtrType = false;
3334 if (!TLI.isTypeLegal(VT)) {
3335 UsePtrType = true;
3336 } else {
3337 for (const BitTestCase &Case : B.Cases)
3338 if (!isUIntN(VT.getSizeInBits(), Case.Mask)) {
3339 // Switch table case range are encoded into series of masks.
3340 // Just use pointer type, it's guaranteed to fit.
3341 UsePtrType = true;
3342 break;
3343 }
3344 }
3345 SDValue Sub = RangeSub;
3346 if (UsePtrType) {
3347 VT = TLI.getPointerTy(DAG.getDataLayout());
3348 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3349 }
3350
3351 B.RegVT = VT.getSimpleVT();
3352 B.Reg = FuncInfo.CreateReg(B.RegVT);
3353 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3354
3355 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3356
3357 if (!B.FallthroughUnreachable)
3358 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3359 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3360 SwitchBB->normalizeSuccProbs();
3361
3362 SDValue Root = CopyTo;
3363 if (!B.FallthroughUnreachable) {
3364 // Conditional branch to the default block.
3365 SDValue RangeCmp = DAG.getSetCC(dl,
3366 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3367 RangeSub.getValueType()),
3368 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3369 ISD::SETUGT);
3370
3371 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3372 DAG.getBasicBlock(B.Default));
3373 }
3374
3375 // Avoid emitting unnecessary branches to the next block.
3376 if (MBB != NextBlock(SwitchBB))
3377 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3378
3379 DAG.setRoot(Root);
3380}
3381
3382/// visitBitTestCase - this function produces one "bit test"
3384 MachineBasicBlock *NextMBB,
3385 BranchProbability BranchProbToNext,
3386 Register Reg, BitTestCase &B,
3387 MachineBasicBlock *SwitchBB) {
3388 SDLoc dl = getCurSDLoc();
3389 MVT VT = BB.RegVT;
3390 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3391 SDValue Cmp;
3392 unsigned PopCount = llvm::popcount(B.Mask);
3393 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3394 if (PopCount == 1) {
3395 // Testing for a single bit; just compare the shift count with what it
3396 // would need to be to shift a 1 bit in that position.
3397 Cmp = DAG.getSetCC(
3398 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3399 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3400 ISD::SETEQ);
3401 } else if (PopCount == BB.Range) {
3402 // There is only one zero bit in the range, test for it directly.
3403 Cmp = DAG.getSetCC(
3404 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3405 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3406 } else {
3407 // Make desired shift
3408 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3409 DAG.getConstant(1, dl, VT), ShiftOp);
3410
3411 // Emit bit tests and jumps
3412 SDValue AndOp = DAG.getNode(ISD::AND, dl,
3413 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3414 Cmp = DAG.getSetCC(
3415 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3416 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3417 }
3418
3419 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3420 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3421 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3422 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3423 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3424 // one as they are relative probabilities (and thus work more like weights),
3425 // and hence we need to normalize them to let the sum of them become one.
3426 SwitchBB->normalizeSuccProbs();
3427
3428 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3429 MVT::Other, getControlRoot(),
3430 Cmp, DAG.getBasicBlock(B.TargetBB));
3431
3432 // Avoid emitting unnecessary branches to the next block.
3433 if (NextMBB != NextBlock(SwitchBB))
3434 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3435 DAG.getBasicBlock(NextMBB));
3436
3437 DAG.setRoot(BrAnd);
3438}
3439
3440void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3441 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3442
3443 // Retrieve successors. Look through artificial IR level blocks like
3444 // catchswitch for successors.
3445 MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0));
3446 const BasicBlock *EHPadBB = I.getSuccessor(1);
3447 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB);
3448
3449 // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3450 // have to do anything here to lower funclet bundles.
3451 failForInvalidBundles(I, "invokes",
3457
3458 const Value *Callee(I.getCalledOperand());
3459 const Function *Fn = dyn_cast<Function>(Callee);
3460 if (isa<InlineAsm>(Callee))
3461 visitInlineAsm(I, EHPadBB);
3462 else if (Fn && Fn->isIntrinsic()) {
3463 switch (Fn->getIntrinsicID()) {
3464 default:
3465 llvm_unreachable("Cannot invoke this intrinsic");
3466 case Intrinsic::donothing:
3467 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3468 case Intrinsic::seh_try_begin:
3469 case Intrinsic::seh_scope_begin:
3470 case Intrinsic::seh_try_end:
3471 case Intrinsic::seh_scope_end:
3472 if (EHPadMBB)
3473 // a block referenced by EH table
3474 // so dtor-funclet not removed by opts
3475 EHPadMBB->setMachineBlockAddressTaken();
3476 break;
3477 case Intrinsic::experimental_patchpoint_void:
3478 case Intrinsic::experimental_patchpoint:
3479 visitPatchpoint(I, EHPadBB);
3480 break;
3481 case Intrinsic::experimental_gc_statepoint:
3483 break;
3484 // wasm_throw, wasm_rethrow: This is usually done in visitTargetIntrinsic,
3485 // but these intrinsics are special because they can be invoked, so we
3486 // manually lower it to a DAG node here.
3487 case Intrinsic::wasm_throw: {
3489 std::array<SDValue, 4> Ops = {
3490 getControlRoot(), // inchain for the terminator node
3491 DAG.getTargetConstant(Intrinsic::wasm_throw, getCurSDLoc(),
3493 getValue(I.getArgOperand(0)), // tag
3494 getValue(I.getArgOperand(1)) // thrown value
3495 };
3496 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3497 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3498 break;
3499 }
3500 case Intrinsic::wasm_rethrow: {
3501 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3502 std::array<SDValue, 2> Ops = {
3503 getControlRoot(), // inchain for the terminator node
3504 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3505 TLI.getPointerTy(DAG.getDataLayout()))};
3506 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3507 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3508 break;
3509 }
3510 }
3511 } else if (I.hasDeoptState()) {
3512 // Currently we do not lower any intrinsic calls with deopt operand bundles.
3513 // Eventually we will support lowering the @llvm.experimental.deoptimize
3514 // intrinsic, and right now there are no plans to support other intrinsics
3515 // with deopt state.
3516 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3517 } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3519 } else {
3520 LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3521 }
3522
3523 // If the value of the invoke is used outside of its defining block, make it
3524 // available as a virtual register.
3525 // We already took care of the exported value for the statepoint instruction
3526 // during call to the LowerStatepoint.
3527 if (!isa<GCStatepointInst>(I)) {
3529 }
3530
3532 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3533 BranchProbability EHPadBBProb =
3534 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3536 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3537
3538 // Update successor info.
3539 addSuccessorWithProb(InvokeMBB, Return);
3540 for (auto &UnwindDest : UnwindDests) {
3541 UnwindDest.first->setIsEHPad();
3542 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3543 }
3544 InvokeMBB->normalizeSuccProbs();
3545
3546 // Drop into normal successor.
3547 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3548 DAG.getBasicBlock(Return)));
3549}
3550
3551/// The intrinsics currently supported by callbr are implicit control flow
3552/// intrinsics such as amdgcn.kill.
3553/// - they should be called (no "dontcall-" attributes)
3554/// - they do not touch memory on the target (= !TLI.getTgtMemIntrinsic())
3555/// - they do not need custom argument handling (no
3556/// TLI.CollectTargetIntrinsicOperands())
3557void SelectionDAGBuilder::visitCallBrIntrinsic(const CallBrInst &I) {
3558#ifndef NDEBUG
3560 DAG.getTargetLoweringInfo().getTgtMemIntrinsic(
3561 Infos, I, DAG.getMachineFunction(), I.getIntrinsicID());
3562 assert(Infos.empty() && "Intrinsic touches memory");
3563#endif
3564
3565 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
3566
3568 getTargetIntrinsicOperands(I, HasChain, OnlyLoad);
3569 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
3570
3571 // Create the node.
3572 SDValue Result =
3573 getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
3574 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
3575
3576 setValue(&I, Result);
3577}
3578
3579void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3580 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3581
3582 if (I.isInlineAsm()) {
3583 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3584 // have to do anything here to lower funclet bundles.
3585 failForInvalidBundles(I, "callbrs",
3587 visitInlineAsm(I);
3588 } else {
3589 assert(!I.hasOperandBundles() &&
3590 "Can't have operand bundles for intrinsics");
3591 visitCallBrIntrinsic(I);
3592 }
3594
3595 // Retrieve successors.
3596 SmallPtrSet<BasicBlock *, 8> Dests;
3597 Dests.insert(I.getDefaultDest());
3598 MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest());
3599
3600 // Update successor info.
3601 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3602 // TODO: For most of the cases where there is an intrinsic callbr, we're
3603 // having exactly one indirect target, which will be unreachable. As soon as
3604 // this changes, we might need to enhance
3605 // Target->setIsInlineAsmBrIndirectTarget or add something similar for
3606 // intrinsic indirect branches.
3607 if (I.isInlineAsm()) {
3608 for (BasicBlock *Dest : I.getIndirectDests()) {
3609 MachineBasicBlock *Target = FuncInfo.getMBB(Dest);
3610 Target->setIsInlineAsmBrIndirectTarget();
3611 // If we introduce a type of asm goto statement that is permitted to use
3612 // an indirect call instruction to jump to its labels, then we should add
3613 // a call to Target->setMachineBlockAddressTaken() here, to mark the
3614 // target block as requiring a BTI.
3615
3616 Target->setLabelMustBeEmitted();
3617 // Don't add duplicate machine successors.
3618 if (Dests.insert(Dest).second)
3619 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3620 }
3621 }
3622 CallBrMBB->normalizeSuccProbs();
3623
3624 // Drop into default successor.
3625 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3626 MVT::Other, getControlRoot(),
3627 DAG.getBasicBlock(Return)));
3628}
3629
3630void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3631 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3632}
3633
3634void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3635 assert(FuncInfo.MBB->isEHPad() &&
3636 "Call to landingpad not in landing pad!");
3637
3638 // If there aren't registers to copy the values into (e.g., during SjLj
3639 // exceptions), then don't bother to create these DAG nodes.
3640 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3641 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3643 TLI.getTargetMachine().getExceptionModel(), PersonalityFn) == 0 &&
3645 TLI.getTargetMachine().getExceptionModel(), PersonalityFn) == 0)
3646 return;
3647
3648 // If landingpad's return type is token type, we don't create DAG nodes
3649 // for its exception pointer and selector value. The extraction of exception
3650 // pointer or selector value from token type landingpads is not currently
3651 // supported.
3652 if (LP.getType()->isTokenTy())
3653 return;
3654
3655 SmallVector<EVT, 2> ValueVTs;
3656 SDLoc dl = getCurSDLoc();
3657 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3658 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3659
3660 // Get the two live-in registers as SDValues. The physregs have already been
3661 // copied into virtual registers.
3662 SDValue Ops[2];
3663 if (FuncInfo.ExceptionPointerVirtReg) {
3664 Ops[0] = DAG.getZExtOrTrunc(
3665 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3666 FuncInfo.ExceptionPointerVirtReg,
3667 TLI.getPointerTy(DAG.getDataLayout())),
3668 dl, ValueVTs[0]);
3669 } else {
3670 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3671 }
3672 Ops[1] = DAG.getZExtOrTrunc(
3673 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3674 FuncInfo.ExceptionSelectorVirtReg,
3675 TLI.getPointerTy(DAG.getDataLayout())),
3676 dl, ValueVTs[1]);
3677
3678 // Merge into one.
3679 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3680 DAG.getVTList(ValueVTs), Ops);
3681 setValue(&LP, Res);
3682}
3683
3686 // Update JTCases.
3687 for (JumpTableBlock &JTB : SL->JTCases)
3688 if (JTB.first.HeaderBB == First)
3689 JTB.first.HeaderBB = Last;
3690
3691 // Update BitTestCases.
3692 for (BitTestBlock &BTB : SL->BitTestCases)
3693 if (BTB.Parent == First)
3694 BTB.Parent = Last;
3695}
3696
3697void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3698 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3699
3700 // Update machine-CFG edges with unique successors.
3702 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3703 BasicBlock *BB = I.getSuccessor(i);
3704 bool Inserted = Done.insert(BB).second;
3705 if (!Inserted)
3706 continue;
3707
3708 MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3709 addSuccessorWithProb(IndirectBrMBB, Succ);
3710 }
3711 IndirectBrMBB->normalizeSuccProbs();
3712
3714 MVT::Other, getControlRoot(),
3715 getValue(I.getAddress())));
3716}
3717
3718void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3719 if (!I.shouldLowerToTrap(DAG.getTarget().Options.TrapUnreachable,
3720 DAG.getTarget().Options.NoTrapAfterNoreturn))
3721 return;
3722
3723 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3724}
3725
3726void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3727 SDNodeFlags Flags;
3728 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3729 Flags.copyFMF(*FPOp);
3730
3731 SDValue Op = getValue(I.getOperand(0));
3732 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3733 Op, Flags);
3734 setValue(&I, UnNodeValue);
3735}
3736
3737void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3738 SDNodeFlags Flags;
3739 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3740 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3741 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3742 }
3743 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3744 Flags.setExact(ExactOp->isExact());
3745 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3746 Flags.setDisjoint(DisjointOp->isDisjoint());
3747 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3748 Flags.copyFMF(*FPOp);
3749
3750 SDValue Op1 = getValue(I.getOperand(0));
3751 SDValue Op2 = getValue(I.getOperand(1));
3752 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3753 Op1, Op2, Flags);
3754 setValue(&I, BinNodeValue);
3755}
3756
3757void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3758 SDValue Op1 = getValue(I.getOperand(0));
3759 SDValue Op2 = getValue(I.getOperand(1));
3760
3761 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3762 Op1.getValueType(), DAG.getDataLayout());
3763
3764 // Coerce the shift amount to the right type if we can. This exposes the
3765 // truncate or zext to optimization early.
3766 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3768 "Unexpected shift type");
3769 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3770 }
3771
3772 bool nuw = false;
3773 bool nsw = false;
3774 bool exact = false;
3775
3776 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3777
3778 if (const OverflowingBinaryOperator *OFBinOp =
3780 nuw = OFBinOp->hasNoUnsignedWrap();
3781 nsw = OFBinOp->hasNoSignedWrap();
3782 }
3783 if (const PossiblyExactOperator *ExactOp =
3785 exact = ExactOp->isExact();
3786 }
3787 SDNodeFlags Flags;
3788 Flags.setExact(exact);
3789 Flags.setNoSignedWrap(nsw);
3790 Flags.setNoUnsignedWrap(nuw);
3791 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3792 Flags);
3793 setValue(&I, Res);
3794}
3795
3796void SelectionDAGBuilder::visitSDiv(const User &I) {
3797 SDValue Op1 = getValue(I.getOperand(0));
3798 SDValue Op2 = getValue(I.getOperand(1));
3799
3800 SDNodeFlags Flags;
3801 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3802 cast<PossiblyExactOperator>(&I)->isExact());
3803 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3804 Op2, Flags));
3805}
3806
3807void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3808 ICmpInst::Predicate predicate = I.getPredicate();
3809 SDValue Op1 = getValue(I.getOperand(0));
3810 SDValue Op2 = getValue(I.getOperand(1));
3811 ISD::CondCode Opcode = getICmpCondCode(predicate);
3812
3813 auto &TLI = DAG.getTargetLoweringInfo();
3814 EVT MemVT =
3815 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3816
3817 // If a pointer's DAG type is larger than its memory type then the DAG values
3818 // are zero-extended. This breaks signed comparisons so truncate back to the
3819 // underlying type before doing the compare.
3820 if (Op1.getValueType() != MemVT) {
3821 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3822 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3823 }
3824
3825 SDNodeFlags Flags;
3826 Flags.setSameSign(I.hasSameSign());
3827
3828 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3829 I.getType());
3830 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode,
3831 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3832}
3833
3834void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3835 FCmpInst::Predicate predicate = I.getPredicate();
3836 SDValue Op1 = getValue(I.getOperand(0));
3837 SDValue Op2 = getValue(I.getOperand(1));
3838
3839 ISD::CondCode Condition = getFCmpCondCode(predicate);
3840 auto *FPMO = cast<FPMathOperator>(&I);
3841 if (FPMO->hasNoNaNs() ||
3842 (DAG.isKnownNeverNaN(Op1) && DAG.isKnownNeverNaN(Op2)))
3843 Condition = getFCmpCodeWithoutNaN(Condition);
3844
3845 SDNodeFlags Flags;
3846 Flags.copyFMF(*FPMO);
3847
3848 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3849 I.getType());
3850 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition,
3851 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3852}
3853
3854// Check if the condition of the select has one use or two users that are both
3855// selects with the same condition.
3856static bool hasOnlySelectUsers(const Value *Cond) {
3857 return llvm::all_of(Cond->users(), [](const Value *V) {
3858 return isa<SelectInst>(V);
3859 });
3860}
3861
3862void SelectionDAGBuilder::visitSelect(const User &I) {
3863 SmallVector<EVT, 4> ValueVTs;
3864 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3865 ValueVTs);
3866 unsigned NumValues = ValueVTs.size();
3867 if (NumValues == 0) return;
3868
3870 SDValue Cond = getValue(I.getOperand(0));
3871 SDValue LHSVal = getValue(I.getOperand(1));
3872 SDValue RHSVal = getValue(I.getOperand(2));
3873 SmallVector<SDValue, 1> BaseOps(1, Cond);
3875 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3876
3877 bool IsUnaryAbs = false;
3878 bool Negate = false;
3879
3880 SDNodeFlags Flags;
3881 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3882 Flags.copyFMF(*FPOp);
3883
3884 Flags.setUnpredictable(
3885 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3886
3887 // Min/max matching is only viable if all output VTs are the same.
3888 if (all_equal(ValueVTs)) {
3889 EVT VT = ValueVTs[0];
3890 LLVMContext &Ctx = *DAG.getContext();
3891 auto &TLI = DAG.getTargetLoweringInfo();
3892
3893 // We care about the legality of the operation after it has been type
3894 // legalized.
3895 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3896 VT = TLI.getTypeToTransformTo(Ctx, VT);
3897
3898 // If the vselect is legal, assume we want to leave this as a vector setcc +
3899 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3900 // min/max is legal on the scalar type.
3901 bool UseScalarMinMax = VT.isVector() &&
3903
3904 // ValueTracking's select pattern matching does not account for -0.0,
3905 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3906 // -0.0 is less than +0.0.
3907 const Value *LHS, *RHS;
3908 auto SPR = matchSelectPattern(&I, LHS, RHS);
3910 switch (SPR.Flavor) {
3911 case SPF_UMAX: Opc = ISD::UMAX; break;
3912 case SPF_UMIN: Opc = ISD::UMIN; break;
3913 case SPF_SMAX: Opc = ISD::SMAX; break;
3914 case SPF_SMIN: Opc = ISD::SMIN; break;
3915 case SPF_FMINNUM:
3917 break;
3918
3919 switch (SPR.NaNBehavior) {
3920 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3921 case SPNB_RETURNS_ANY:
3922 case SPNB_RETURNS_NAN:
3923 break;
3924 case SPNB_RETURNS_OTHER:
3926 Flags.setNoSignedZeros(true);
3927 break;
3928 }
3929 break;
3930 case SPF_FMAXNUM:
3932 break;
3933
3934 switch (SPR.NaNBehavior) {
3935 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3936 case SPNB_RETURNS_NAN:
3937 case SPNB_RETURNS_ANY:
3938 break;
3939 case SPNB_RETURNS_OTHER:
3941 Flags.setNoSignedZeros(true);
3942 break;
3943 }
3944 break;
3945 case SPF_NABS:
3946 Negate = true;
3947 [[fallthrough]];
3948 case SPF_ABS:
3949 IsUnaryAbs = true;
3950 Opc = ISD::ABS;
3951 break;
3952 default: break;
3953 }
3954
3955 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3956 (TLI.isOperationLegalOrCustom(Opc, VT) ||
3957 (UseScalarMinMax &&
3959 // If the underlying comparison instruction is used by any other
3960 // instruction, the consumed instructions won't be destroyed, so it is
3961 // not profitable to convert to a min/max.
3963 OpCode = Opc;
3964 LHSVal = getValue(LHS);
3965 RHSVal = getValue(RHS);
3966 BaseOps.clear();
3967 }
3968
3969 if (IsUnaryAbs) {
3970 OpCode = Opc;
3971 LHSVal = getValue(LHS);
3972 BaseOps.clear();
3973 }
3974 }
3975
3976 if (IsUnaryAbs) {
3977 for (unsigned i = 0; i != NumValues; ++i) {
3978 SDLoc dl = getCurSDLoc();
3979 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3980 Values[i] =
3981 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3982 if (Negate)
3983 Values[i] = DAG.getNegative(Values[i], dl, VT);
3984 }
3985 } else {
3986 for (unsigned i = 0; i != NumValues; ++i) {
3987 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3988 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3989 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3990 Values[i] = DAG.getNode(
3991 OpCode, getCurSDLoc(),
3992 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3993 }
3994 }
3995
3997 DAG.getVTList(ValueVTs), Values));
3998}
3999
4000void SelectionDAGBuilder::visitTrunc(const User &I) {
4001 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
4002 SDValue N = getValue(I.getOperand(0));
4003 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4004 I.getType());
4005 SDNodeFlags Flags;
4006 if (auto *Trunc = dyn_cast<TruncInst>(&I)) {
4007 Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
4008 Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
4009 }
4010
4011 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N, Flags));
4012}
4013
4014void SelectionDAGBuilder::visitZExt(const User &I) {
4015 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4016 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
4017 SDValue N = getValue(I.getOperand(0));
4018 auto &TLI = DAG.getTargetLoweringInfo();
4019 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4020
4021 SDNodeFlags Flags;
4022 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
4023 Flags.setNonNeg(PNI->hasNonNeg());
4024
4025 // Eagerly use nonneg information to canonicalize towards sign_extend if
4026 // that is the target's preference.
4027 // TODO: Let the target do this later.
4028 if (Flags.hasNonNeg() &&
4029 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
4030 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4031 return;
4032 }
4033
4034 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4035}
4036
4037void SelectionDAGBuilder::visitSExt(const User &I) {
4038 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4039 // SExt also can't be a cast to bool for same reason. So, nothing much to do
4040 SDValue N = getValue(I.getOperand(0));
4041 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4042 I.getType());
4043 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4044}
4045
4046void SelectionDAGBuilder::visitFPTrunc(const User &I) {
4047 // FPTrunc is never a no-op cast, no need to check
4048 SDValue N = getValue(I.getOperand(0));
4049 SDLoc dl = getCurSDLoc();
4050 SDNodeFlags Flags;
4051 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4052 Flags.copyFMF(*FPOp);
4053 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4054 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4055 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
4056 DAG.getTargetConstant(
4057 0, dl, TLI.getPointerTy(DAG.getDataLayout())),
4058 Flags));
4059}
4060
4061void SelectionDAGBuilder::visitFPExt(const User &I) {
4062 // FPExt is never a no-op cast, no need to check
4063 SDValue N = getValue(I.getOperand(0));
4064 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4065 I.getType());
4066 SDNodeFlags Flags;
4067 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4068 Flags.copyFMF(*FPOp);
4069 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4070}
4071
4072void SelectionDAGBuilder::visitFPToUI(const User &I) {
4073 // FPToUI is never a no-op cast, no need to check
4074 SDValue N = getValue(I.getOperand(0));
4075 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4076 I.getType());
4077 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
4078}
4079
4080void SelectionDAGBuilder::visitFPToSI(const User &I) {
4081 // FPToSI is never a no-op cast, no need to check
4082 SDValue N = getValue(I.getOperand(0));
4083 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4084 I.getType());
4085 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
4086}
4087
4088void SelectionDAGBuilder::visitUIToFP(const User &I) {
4089 // UIToFP is never a no-op cast, no need to check
4090 SDValue N = getValue(I.getOperand(0));
4091 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4092 I.getType());
4093 SDNodeFlags Flags;
4094 Flags.setNonNeg(cast<PossiblyNonNegInst>(&I)->hasNonNeg());
4095 Flags.copyFMF(*cast<FPMathOperator>(&I));
4096
4097 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4098}
4099
4100void SelectionDAGBuilder::visitSIToFP(const User &I) {
4101 // SIToFP is never a no-op cast, no need to check
4102 SDValue N = getValue(I.getOperand(0));
4103 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4104 I.getType());
4105 SDNodeFlags Flags;
4106 Flags.copyFMF(*cast<FPMathOperator>(&I));
4107
4108 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4109}
4110
4111void SelectionDAGBuilder::visitPtrToAddr(const User &I) {
4112 SDValue N = getValue(I.getOperand(0));
4113 // By definition the type of the ptrtoaddr must be equal to the address type.
4114 const auto &TLI = DAG.getTargetLoweringInfo();
4115 EVT AddrVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4116 // The address width must be smaller or equal to the pointer representation
4117 // width, so we lower ptrtoaddr as a truncate (possibly folded to a no-op).
4118 N = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), AddrVT, N);
4119 setValue(&I, N);
4120}
4121
4122void SelectionDAGBuilder::visitPtrToInt(const User &I) {
4123 // What to do depends on the size of the integer and the size of the pointer.
4124 // We can either truncate, zero extend, or no-op, accordingly.
4125 SDValue N = getValue(I.getOperand(0));
4126 auto &TLI = DAG.getTargetLoweringInfo();
4127 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4128 I.getType());
4129 EVT PtrMemVT =
4130 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
4131 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4132 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
4133 setValue(&I, N);
4134}
4135
4136void SelectionDAGBuilder::visitIntToPtr(const User &I) {
4137 // What to do depends on the size of the integer and the size of the pointer.
4138 // We can either truncate, zero extend, or no-op, accordingly.
4139 SDValue N = getValue(I.getOperand(0));
4140 auto &TLI = DAG.getTargetLoweringInfo();
4141 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4142 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4143 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4144 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
4145 setValue(&I, N);
4146}
4147
4148void SelectionDAGBuilder::visitBitCast(const User &I) {
4149 SDValue N = getValue(I.getOperand(0));
4150 SDLoc dl = getCurSDLoc();
4151 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4152 I.getType());
4153
4154 // BitCast assures us that source and destination are the same size so this is
4155 // either a BITCAST or a no-op.
4156 if (DestVT != N.getValueType())
4157 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
4158 DestVT, N)); // convert types.
4159 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
4160 // might fold any kind of constant expression to an integer constant and that
4161 // is not what we are looking for. Only recognize a bitcast of a genuine
4162 // constant integer as an opaque constant.
4163 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
4164 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
4165 /*isOpaque*/true));
4166 else
4167 setValue(&I, N); // noop cast.
4168}
4169
4170void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
4171 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4172 const Value *SV = I.getOperand(0);
4173 SDValue N = getValue(SV);
4174 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4175
4176 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
4177 unsigned DestAS = I.getType()->getPointerAddressSpace();
4178
4179 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) {
4180 SDNodeFlags Flags;
4181 if (const auto *ASC = dyn_cast<AddrSpaceCastInst>(&I))
4182 Flags.setNonNull(ASC->hasNonNull());
4183 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS, Flags);
4184 }
4185
4186 setValue(&I, N);
4187}
4188
4189void SelectionDAGBuilder::visitInsertElement(const User &I) {
4190 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4191 SDValue InVec = getValue(I.getOperand(0));
4192 SDValue InVal = getValue(I.getOperand(1));
4193 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
4194 TLI.getVectorIdxTy(DAG.getDataLayout()));
4196 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4197 InVec, InVal, InIdx));
4198}
4199
4200void SelectionDAGBuilder::visitExtractElement(const User &I) {
4201 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4202 SDValue InVec = getValue(I.getOperand(0));
4203 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
4204 TLI.getVectorIdxTy(DAG.getDataLayout()));
4206 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4207 InVec, InIdx));
4208}
4209
4210void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4211 SDValue Src1 = getValue(I.getOperand(0));
4212 SDValue Src2 = getValue(I.getOperand(1));
4213 ArrayRef<int> Mask;
4214 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4215 Mask = SVI->getShuffleMask();
4216 else
4217 Mask = cast<ConstantExpr>(I).getShuffleMask();
4218 SDLoc DL = getCurSDLoc();
4219 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4220 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4221 EVT SrcVT = Src1.getValueType();
4222
4223 if (all_of(Mask, equal_to(0)) && VT.isScalableVector()) {
4224 // Canonical splat form of first element of first input vector.
4225 SDValue FirstElt =
4226 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4227 DAG.getVectorIdxConstant(0, DL));
4228 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4229 return;
4230 }
4231
4232 // For now, we only handle splats for scalable vectors.
4233 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4234 // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4235 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4236
4237 unsigned SrcNumElts = SrcVT.getVectorNumElements();
4238 unsigned MaskNumElts = Mask.size();
4239
4240 if (SrcNumElts == MaskNumElts) {
4241 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4242 return;
4243 }
4244
4245 // Normalize the shuffle vector since mask and vector length don't match.
4246 if (SrcNumElts < MaskNumElts) {
4247 // Mask is longer than the source vectors. We can use concatenate vector to
4248 // make the mask and vectors lengths match.
4249
4250 if (MaskNumElts % SrcNumElts == 0) {
4251 // Mask length is a multiple of the source vector length.
4252 // Check if the shuffle is some kind of concatenation of the input
4253 // vectors.
4254 unsigned NumConcat = MaskNumElts / SrcNumElts;
4255 bool IsConcat = true;
4256 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4257 for (unsigned i = 0; i != MaskNumElts; ++i) {
4258 int Idx = Mask[i];
4259 if (Idx < 0)
4260 continue;
4261 // Ensure the indices in each SrcVT sized piece are sequential and that
4262 // the same source is used for the whole piece.
4263 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4264 (ConcatSrcs[i / SrcNumElts] >= 0 &&
4265 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4266 IsConcat = false;
4267 break;
4268 }
4269 // Remember which source this index came from.
4270 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4271 }
4272
4273 // The shuffle is concatenating multiple vectors together. Just emit
4274 // a CONCAT_VECTORS operation.
4275 if (IsConcat) {
4276 SmallVector<SDValue, 8> ConcatOps;
4277 for (auto Src : ConcatSrcs) {
4278 if (Src < 0)
4279 ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4280 else if (Src == 0)
4281 ConcatOps.push_back(Src1);
4282 else
4283 ConcatOps.push_back(Src2);
4284 }
4285 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4286 return;
4287 }
4288 }
4289
4290 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4291 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4292 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4293 PaddedMaskNumElts);
4294
4295 // Pad both vectors with undefs to make them the same length as the mask.
4296 SDValue UndefVal = DAG.getUNDEF(SrcVT);
4297
4298 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4299 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4300 MOps1[0] = Src1;
4301 MOps2[0] = Src2;
4302
4303 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4304 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4305
4306 // Readjust mask for new input vector length.
4307 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4308 for (unsigned i = 0; i != MaskNumElts; ++i) {
4309 int Idx = Mask[i];
4310 if (Idx >= (int)SrcNumElts)
4311 Idx -= SrcNumElts - PaddedMaskNumElts;
4312 MappedOps[i] = Idx;
4313 }
4314
4315 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4316
4317 // If the concatenated vector was padded, extract a subvector with the
4318 // correct number of elements.
4319 if (MaskNumElts != PaddedMaskNumElts)
4320 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4321 DAG.getVectorIdxConstant(0, DL));
4322
4323 setValue(&I, Result);
4324 return;
4325 }
4326
4327 assert(SrcNumElts > MaskNumElts);
4328
4329 // Analyze the access pattern of the vector to see if we can extract
4330 // two subvectors and do the shuffle.
4331 int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4332 bool CanExtract = true;
4333 for (int Idx : Mask) {
4334 unsigned Input = 0;
4335 if (Idx < 0)
4336 continue;
4337
4338 if (Idx >= (int)SrcNumElts) {
4339 Input = 1;
4340 Idx -= SrcNumElts;
4341 }
4342
4343 // If all the indices come from the same MaskNumElts sized portion of
4344 // the sources we can use extract. Also make sure the extract wouldn't
4345 // extract past the end of the source.
4346 int NewStartIdx = alignDown(Idx, MaskNumElts);
4347 if (NewStartIdx + MaskNumElts > SrcNumElts ||
4348 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4349 CanExtract = false;
4350 // Make sure we always update StartIdx as we use it to track if all
4351 // elements are undef.
4352 StartIdx[Input] = NewStartIdx;
4353 }
4354
4355 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4356 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4357 return;
4358 }
4359 if (CanExtract) {
4360 // Extract appropriate subvector and generate a vector shuffle
4361 for (unsigned Input = 0; Input < 2; ++Input) {
4362 SDValue &Src = Input == 0 ? Src1 : Src2;
4363 if (StartIdx[Input] < 0)
4364 Src = DAG.getUNDEF(VT);
4365 else {
4366 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4367 DAG.getVectorIdxConstant(StartIdx[Input], DL));
4368 }
4369 }
4370
4371 // Calculate new mask.
4372 SmallVector<int, 8> MappedOps(Mask);
4373 for (int &Idx : MappedOps) {
4374 if (Idx >= (int)SrcNumElts)
4375 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4376 else if (Idx >= 0)
4377 Idx -= StartIdx[0];
4378 }
4379
4380 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4381 return;
4382 }
4383
4384 // We can't use either concat vectors or extract subvectors so fall back to
4385 // replacing the shuffle with extract and build vector.
4386 // to insert and build vector.
4387 EVT EltVT = VT.getVectorElementType();
4389 for (int Idx : Mask) {
4390 SDValue Res;
4391
4392 if (Idx < 0) {
4393 Res = DAG.getUNDEF(EltVT);
4394 } else {
4395 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4396 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4397
4398 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4399 DAG.getVectorIdxConstant(Idx, DL));
4400 }
4401
4402 Ops.push_back(Res);
4403 }
4404
4405 setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4406}
4407
4408void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4409 ArrayRef<unsigned> Indices = I.getIndices();
4410 const Value *Op0 = I.getOperand(0);
4411 const Value *Op1 = I.getOperand(1);
4412 Type *AggTy = I.getType();
4413 Type *ValTy = Op1->getType();
4414 bool IntoUndef = isa<UndefValue>(Op0);
4415 bool FromUndef = isa<UndefValue>(Op1);
4416
4417 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4418
4419 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4420 SmallVector<EVT, 4> AggValueVTs;
4421 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4422 SmallVector<EVT, 4> ValValueVTs;
4423 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4424
4425 unsigned NumAggValues = AggValueVTs.size();
4426 unsigned NumValValues = ValValueVTs.size();
4427 SmallVector<SDValue, 4> Values(NumAggValues);
4428
4429 // Ignore an insertvalue that produces an empty object
4430 if (!NumAggValues) {
4431 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4432 return;
4433 }
4434
4435 SDValue Agg = getValue(Op0);
4436 unsigned i = 0;
4437 // Copy the beginning value(s) from the original aggregate.
4438 for (; i != LinearIndex; ++i)
4439 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4440 SDValue(Agg.getNode(), Agg.getResNo() + i);
4441 // Copy values from the inserted value(s).
4442 if (NumValValues) {
4443 SDValue Val = getValue(Op1);
4444 for (; i != LinearIndex + NumValValues; ++i)
4445 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4446 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4447 }
4448 // Copy remaining value(s) from the original aggregate.
4449 for (; i != NumAggValues; ++i)
4450 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4451 SDValue(Agg.getNode(), Agg.getResNo() + i);
4452
4454 DAG.getVTList(AggValueVTs), Values));
4455}
4456
4457void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4458 ArrayRef<unsigned> Indices = I.getIndices();
4459 const Value *Op0 = I.getOperand(0);
4460 Type *AggTy = Op0->getType();
4461 Type *ValTy = I.getType();
4462 bool OutOfUndef = isa<UndefValue>(Op0);
4463
4464 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4465
4466 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4467 SmallVector<EVT, 4> ValValueVTs;
4468 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4469
4470 unsigned NumValValues = ValValueVTs.size();
4471
4472 // Ignore a extractvalue that produces an empty object
4473 if (!NumValValues) {
4474 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4475 return;
4476 }
4477
4478 SmallVector<SDValue, 4> Values(NumValValues);
4479
4480 SDValue Agg = getValue(Op0);
4481 // Copy out the selected value(s).
4482 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4483 Values[i - LinearIndex] =
4484 OutOfUndef ?
4485 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4486 SDValue(Agg.getNode(), Agg.getResNo() + i);
4487
4489 DAG.getVTList(ValValueVTs), Values));
4490}
4491
4492void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4493 Value *Op0 = I.getOperand(0);
4494 // Note that the pointer operand may be a vector of pointers. Take the scalar
4495 // element which holds a pointer.
4496 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4497 SDValue N = getValue(Op0);
4498 SDLoc dl = getCurSDLoc();
4499 auto &TLI = DAG.getTargetLoweringInfo();
4500 GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4501
4502 // For a vector GEP, keep the prefix scalar as long as possible, then
4503 // convert any scalars encountered after the first vector operand to vectors.
4504 bool IsVectorGEP = I.getType()->isVectorTy();
4505 ElementCount VectorElementCount =
4506 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4508
4510 GTI != E; ++GTI) {
4511 const Value *Idx = GTI.getOperand();
4512 if (StructType *StTy = GTI.getStructTypeOrNull()) {
4513 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4514 if (Field) {
4515 // N = N + Offset
4517 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4518
4519 // In an inbounds GEP with an offset that is nonnegative even when
4520 // interpreted as signed, assume there is no unsigned overflow.
4521 SDNodeFlags Flags;
4522 if (NW.hasNoUnsignedWrap() ||
4523 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4525 Flags.setInBounds(NW.isInBounds());
4526
4527 N = DAG.getMemBasePlusOffset(
4528 N, DAG.getConstant(Offset, dl, N.getValueType()), dl, Flags);
4529 }
4530 } else {
4531 // IdxSize is the width of the arithmetic according to IR semantics.
4532 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4533 // (and fix up the result later).
4534 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4535 MVT IdxTy = MVT::getIntegerVT(IdxSize);
4536 TypeSize ElementSize =
4537 GTI.getSequentialElementStride(DAG.getDataLayout());
4538 // We intentionally mask away the high bits here; ElementSize may not
4539 // fit in IdxTy.
4540 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4541 /*isSigned=*/false, /*implicitTrunc=*/true);
4542 bool ElementScalable = ElementSize.isScalable();
4543
4544 // If this is a scalar constant or a splat vector of constants,
4545 // handle it quickly.
4546 const auto *C = dyn_cast<Constant>(Idx);
4547 if (C && isa<VectorType>(C->getType()))
4548 C = C->getSplatValue();
4549
4550 const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4551 if (CI && CI->isZero())
4552 continue;
4553 if (CI && !ElementScalable) {
4554 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4555 LLVMContext &Context = *DAG.getContext();
4556 SDValue OffsVal;
4557 if (N.getValueType().isVector())
4558 OffsVal = DAG.getConstant(
4559 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4560 else
4561 OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4562
4563 // In an inbounds GEP with an offset that is nonnegative even when
4564 // interpreted as signed, assume there is no unsigned overflow.
4565 SDNodeFlags Flags;
4566 if (NW.hasNoUnsignedWrap() ||
4567 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4568 Flags.setNoUnsignedWrap(true);
4569 Flags.setInBounds(NW.isInBounds());
4570
4571 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4572
4573 N = DAG.getMemBasePlusOffset(N, OffsVal, dl, Flags);
4574 continue;
4575 }
4576
4577 // N = N + Idx * ElementMul;
4578 SDValue IdxN = getValue(Idx);
4579
4580 if (IdxN.getValueType().isVector() != N.getValueType().isVector()) {
4581 if (N.getValueType().isVector()) {
4582 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4583 VectorElementCount);
4584 IdxN = DAG.getSplat(VT, dl, IdxN);
4585 } else {
4586 EVT VT =
4587 EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4588 N = DAG.getSplat(VT, dl, N);
4589 }
4590 }
4591
4592 // If the index is smaller or larger than intptr_t, truncate or extend
4593 // it.
4594 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4595
4596 SDNodeFlags ScaleFlags;
4597 // The multiplication of an index by the type size does not wrap the
4598 // pointer index type in a signed sense (mul nsw).
4600
4601 // The multiplication of an index by the type size does not wrap the
4602 // pointer index type in an unsigned sense (mul nuw).
4603 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4604
4605 if (ElementScalable) {
4606 EVT VScaleTy = N.getValueType().getScalarType();
4607 SDValue VScale = DAG.getNode(
4608 ISD::VSCALE, dl, VScaleTy,
4609 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4610 if (N.getValueType().isVector())
4611 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4612 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale,
4613 ScaleFlags);
4614 } else {
4615 // If this is a multiply by a power of two, turn it into a shl
4616 // immediately. This is a very common case.
4617 if (ElementMul != 1) {
4618 if (ElementMul.isPowerOf2()) {
4619 unsigned Amt = ElementMul.logBase2();
4620 IdxN = DAG.getNode(
4621 ISD::SHL, dl, N.getValueType(), IdxN,
4622 DAG.getShiftAmountConstant(Amt, N.getValueType(), dl),
4623 ScaleFlags);
4624 } else {
4625 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4626 IdxN.getValueType());
4627 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, Scale,
4628 ScaleFlags);
4629 }
4630 }
4631 }
4632
4633 // The successive addition of the current address, truncated to the
4634 // pointer index type and interpreted as an unsigned number, and each
4635 // offset, also interpreted as an unsigned number, does not wrap the
4636 // pointer index type (add nuw).
4637 SDNodeFlags AddFlags;
4638 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4639 AddFlags.setInBounds(NW.isInBounds());
4640
4641 N = DAG.getMemBasePlusOffset(N, IdxN, dl, AddFlags);
4642 }
4643 }
4644
4645 if (IsVectorGEP && !N.getValueType().isVector()) {
4646 EVT VT = EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4647 N = DAG.getSplat(VT, dl, N);
4648 }
4649
4650 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4651 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4652 if (IsVectorGEP) {
4653 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4654 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4655 }
4656
4657 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4658 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4659
4660 setValue(&I, N);
4661}
4662
4663void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4664 // If this is a fixed sized alloca in the entry block of the function,
4665 // allocate it statically on the stack.
4666 if (FuncInfo.StaticAllocaMap.count(&I))
4667 return; // getValue will auto-populate this.
4668
4669 SDLoc dl = getCurSDLoc();
4670 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4671 auto &DL = DAG.getDataLayout();
4672 TypeSize TySize = I.getAllocationBaseSize(DL);
4673 MaybeAlign Alignment = I.getAlign();
4674
4675 SDValue AllocSize = getValue(I.getArraySize());
4676
4677 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4678 if (AllocSize.getValueType() != IntPtr)
4679 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4680
4681 AllocSize = DAG.getNode(
4682 ISD::MUL, dl, IntPtr, AllocSize,
4683 DAG.getZExtOrTrunc(DAG.getTypeSize(dl, MVT::i64, TySize), dl, IntPtr));
4684
4685 // Handle alignment. If the requested alignment is less than or equal to
4686 // the stack alignment, ignore it. If the size is greater than or equal to
4687 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4688 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4689 if (*Alignment <= StackAlign)
4690 Alignment = std::nullopt;
4691
4692 const uint64_t StackAlignMask = StackAlign.value() - 1U;
4693 // Round the size of the allocation up to the stack alignment size
4694 // by add SA-1 to the size. This doesn't overflow because we're computing
4695 // an address inside an alloca.
4696 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4697 DAG.getConstant(StackAlignMask, dl, IntPtr),
4699
4700 // Mask out the low bits for alignment purposes.
4701 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4702 DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4703
4704 SDValue Ops[] = {
4705 getRoot(), AllocSize,
4706 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4707 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4708 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4709 setValue(&I, DSA);
4710 DAG.setRoot(DSA.getValue(1));
4711
4712 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4713}
4714
4715static const MDNode *getRangeMetadata(const Instruction &I) {
4716 return I.getMetadata(LLVMContext::MD_range);
4717}
4718
4719static std::optional<ConstantRange> getRange(const Instruction &I) {
4720 if (const auto *CB = dyn_cast<CallBase>(&I))
4721 if (std::optional<ConstantRange> CR = CB->getRange())
4722 return CR;
4723 if (const MDNode *Range = getRangeMetadata(I))
4725 return std::nullopt;
4726}
4727
4729 if (const auto *CB = dyn_cast<CallBase>(&I))
4730 return CB->getRetNoFPClass();
4731 return fcNone;
4732}
4733
4734void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4735 if (I.isAtomic())
4736 return visitAtomicLoad(I);
4737
4738 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4739 const Value *SV = I.getOperand(0);
4740 if (TLI.supportSwiftError()) {
4741 // Swifterror values can come from either a function parameter with
4742 // swifterror attribute or an alloca with swifterror attribute.
4743 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4744 if (Arg->hasSwiftErrorAttr())
4745 return visitLoadFromSwiftError(I);
4746 }
4747
4748 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4749 if (Alloca->isSwiftError())
4750 return visitLoadFromSwiftError(I);
4751 }
4752 }
4753
4754 SDValue Ptr = getValue(SV);
4755
4756 Type *Ty = I.getType();
4757 SmallVector<EVT, 4> ValueVTs, MemVTs;
4759 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4760 unsigned NumValues = ValueVTs.size();
4761 if (NumValues == 0)
4762 return;
4763
4764 Align Alignment = I.getAlign();
4765 AAMDNodes AAInfo = I.getAAMetadata();
4766 const MDNode *Ranges = getRangeMetadata(I);
4767 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
4768 bool isVolatile = I.isVolatile();
4769 MachineMemOperand::Flags MMOFlags =
4770 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4771
4772 SDValue Root;
4773 bool ConstantMemory = false;
4774 if (isVolatile)
4775 // Serialize volatile loads with other side effects.
4776 Root = getRoot();
4777 else if (NumValues > MaxParallelChains)
4778 Root = getMemoryRoot();
4779 else if (BatchAA &&
4780 BatchAA->pointsToConstantMemory(MemoryLocation(
4781 SV,
4782 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4783 AAInfo))) {
4784 // Do not serialize (non-volatile) loads of constant memory with anything.
4785 Root = DAG.getEntryNode();
4786 ConstantMemory = true;
4788 } else {
4789 // Do not serialize non-volatile loads against each other.
4790 Root = DAG.getRoot();
4791 }
4792
4793 SDLoc dl = getCurSDLoc();
4794
4795 if (isVolatile)
4796 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4797
4799 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4800
4801 unsigned ChainI = 0;
4802 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4803 // Serializing loads here may result in excessive register pressure, and
4804 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4805 // could recover a bit by hoisting nodes upward in the chain by recognizing
4806 // they are side-effect free or do not alias. The optimizer should really
4807 // avoid this case by converting large object/array copies to llvm.memcpy
4808 // (MaxParallelChains should always remain as failsafe).
4809 if (ChainI == MaxParallelChains) {
4810 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4811 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4812 ArrayRef(Chains.data(), ChainI));
4813 Root = Chain;
4814 ChainI = 0;
4815 }
4816
4817 // TODO: MachinePointerInfo only supports a fixed length offset.
4818 MachinePointerInfo PtrInfo =
4819 !Offsets[i].isScalable() || Offsets[i].isZero()
4820 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4821 : MachinePointerInfo();
4822
4823 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4824 SDValue L =
4825 DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, MMOFlags,
4826 MMOMetadata(AAInfo, Ranges, MemCacheHint));
4827 Chains[ChainI] = L.getValue(1);
4828
4829 if (MemVTs[i] != ValueVTs[i])
4830 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4831
4832 if (MDNode *NoFPClassMD = I.getMetadata(LLVMContext::MD_nofpclass)) {
4833 uint64_t FPTestInt =
4834 cast<ConstantInt>(
4835 cast<ConstantAsMetadata>(NoFPClassMD->getOperand(0))->getValue())
4836 ->getZExtValue();
4837 if (FPTestInt != fcNone) {
4838 SDValue FPTestConst =
4839 DAG.getTargetConstant(FPTestInt, SDLoc(), MVT::i32);
4840 L = DAG.getNode(ISD::AssertNoFPClass, dl, L.getValueType(), L,
4841 FPTestConst);
4842 }
4843 }
4844 Values[i] = L;
4845 }
4846
4847 if (!ConstantMemory) {
4848 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4849 ArrayRef(Chains.data(), ChainI));
4850 if (isVolatile)
4851 DAG.setRoot(Chain);
4852 else
4853 PendingLoads.push_back(Chain);
4854 }
4855
4856 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4857 DAG.getVTList(ValueVTs), Values));
4858}
4859
4860void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4861 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4862 "call visitStoreToSwiftError when backend supports swifterror");
4863
4864 SmallVector<EVT, 4> ValueVTs;
4865 SmallVector<uint64_t, 4> Offsets;
4866 const Value *SrcV = I.getOperand(0);
4867 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4868 SrcV->getType(), ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
4869 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4870 "expect a single EVT for swifterror");
4871
4872 SDValue Src = getValue(SrcV);
4873 // Create a virtual register, then update the virtual register.
4874 Register VReg =
4875 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4876 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4877 // Chain can be getRoot or getControlRoot.
4878 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4879 SDValue(Src.getNode(), Src.getResNo()));
4880 DAG.setRoot(CopyNode);
4881}
4882
4883void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4884 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4885 "call visitLoadFromSwiftError when backend supports swifterror");
4886
4887 assert(!I.isVolatile() &&
4888 !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4889 !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4890 "Support volatile, non temporal, invariant for load_from_swift_error");
4891
4892 const Value *SV = I.getOperand(0);
4893 Type *Ty = I.getType();
4894 assert(
4895 (!BatchAA ||
4896 !BatchAA->pointsToConstantMemory(MemoryLocation(
4897 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4898 I.getAAMetadata()))) &&
4899 "load_from_swift_error should not be constant memory");
4900
4901 SmallVector<EVT, 4> ValueVTs;
4902 SmallVector<uint64_t, 4> Offsets;
4903 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4904 ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
4905 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4906 "expect a single EVT for swifterror");
4907
4908 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4909 SDValue L = DAG.getCopyFromReg(
4910 getRoot(), getCurSDLoc(),
4911 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4912
4913 setValue(&I, L);
4914}
4915
4916void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4917 if (I.isAtomic())
4918 return visitAtomicStore(I);
4919
4920 const Value *SrcV = I.getOperand(0);
4921 const Value *PtrV = I.getOperand(1);
4922
4923 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4924 if (TLI.supportSwiftError()) {
4925 // Swifterror values can come from either a function parameter with
4926 // swifterror attribute or an alloca with swifterror attribute.
4927 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4928 if (Arg->hasSwiftErrorAttr())
4929 return visitStoreToSwiftError(I);
4930 }
4931
4932 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4933 if (Alloca->isSwiftError())
4934 return visitStoreToSwiftError(I);
4935 }
4936 }
4937
4938 SmallVector<EVT, 4> ValueVTs, MemVTs;
4940 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4941 SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4942 unsigned NumValues = ValueVTs.size();
4943 if (NumValues == 0)
4944 return;
4945
4946 // Get the lowered operands. Note that we do this after
4947 // checking if NumResults is zero, because with zero results
4948 // the operands won't have values in the map.
4949 SDValue Src = getValue(SrcV);
4950 SDValue Ptr = getValue(PtrV);
4951
4952 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4953 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4954 SDLoc dl = getCurSDLoc();
4955 Align Alignment = I.getAlign();
4956 AAMDNodes AAInfo = I.getAAMetadata();
4957 const MDNode *MemCacheHint =
4958 getMemCacheHintMetadata(I, I.getPointerOperandIndex());
4959
4960 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4961
4962 unsigned ChainI = 0;
4963 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4964 // See visitLoad comments.
4965 if (ChainI == MaxParallelChains) {
4966 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4967 ArrayRef(Chains.data(), ChainI));
4968 Root = Chain;
4969 ChainI = 0;
4970 }
4971
4972 // TODO: MachinePointerInfo only supports a fixed length offset.
4973 MachinePointerInfo PtrInfo =
4974 !Offsets[i].isScalable() || Offsets[i].isZero()
4975 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4976 : MachinePointerInfo();
4977
4978 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4979 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4980 if (MemVTs[i] != ValueVTs[i])
4981 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4982 SDValue St =
4983 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags,
4984 MMOMetadata(AAInfo, /*Ranges=*/nullptr, MemCacheHint));
4985 Chains[ChainI] = St;
4986 }
4987
4988 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4989 ArrayRef(Chains.data(), ChainI));
4990 setValue(&I, StoreNode);
4991 DAG.setRoot(StoreNode);
4992}
4993
4994void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4995 bool IsCompressing) {
4996 SDLoc sdl = getCurSDLoc();
4997
4998 Value *Src0Operand = I.getArgOperand(0);
4999 Value *PtrOperand = I.getArgOperand(1);
5000 Value *MaskOperand = I.getArgOperand(2);
5001 Align Alignment = I.getParamAlign(1).valueOrOne();
5002
5003 SDValue Ptr = getValue(PtrOperand);
5004 SDValue Src0 = getValue(Src0Operand);
5005 SDValue Mask = getValue(MaskOperand);
5006 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5007
5008 EVT VT = Src0.getValueType();
5009
5010 const auto &TLI = DAG.getTargetLoweringInfo();
5011
5012 auto MMOFlags = MachineMemOperand::MOStore;
5013 MMOFlags |= TLI.getTargetMMOFlags(I);
5014 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5016
5017 const MDNode *MemCacheHint = getMemCacheHintMetadata(I, /*OperandNo=*/1);
5018
5019 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5020 MachinePointerInfo(PtrOperand), MMOFlags,
5021 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5022 MMOMetadata(I.getAAMetadata(), /*Ranges=*/nullptr, MemCacheHint));
5023
5024 SDValue StoreNode =
5025 !IsCompressing && TTI->hasConditionalLoadStoreForType(
5026 I.getArgOperand(0)->getType(), /*IsStore=*/true)
5027 ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
5028 Mask)
5029 : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
5030 VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
5031 IsCompressing);
5032 DAG.setRoot(StoreNode);
5033 setValue(&I, StoreNode);
5034}
5035
5036// Get a uniform base for the Gather/Scatter intrinsic.
5037// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
5038// We try to represent it as a base pointer + vector of indices.
5039// Usually, the vector of pointers comes from a 'getelementptr' instruction.
5040// The first operand of the GEP may be a single pointer or a vector of pointers
5041// Example:
5042// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
5043// or
5044// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
5045// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
5046//
5047// When the first GEP operand is a single pointer - it is the uniform base we
5048// are looking for. If first operand of the GEP is a splat vector - we
5049// extract the splat value and use it as a uniform base.
5050// In all other cases the function returns 'false'.
5051static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
5052 SDValue &Scale, SelectionDAGBuilder *SDB,
5053 const BasicBlock *CurBB, uint64_t ElemSize) {
5054 SelectionDAG& DAG = SDB->DAG;
5055 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5056 const DataLayout &DL = DAG.getDataLayout();
5057
5058 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
5059
5060 // Handle splat constant pointer.
5061 if (auto *C = dyn_cast<Constant>(Ptr)) {
5062 C = C->getSplatValue();
5063 if (!C)
5064 return false;
5065
5066 Base = SDB->getValue(C);
5067
5068 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
5069 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
5070 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
5071 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5072 return true;
5073 }
5074
5076 if (!GEP || GEP->getParent() != CurBB)
5077 return false;
5078
5079 if (GEP->getNumOperands() != 2)
5080 return false;
5081
5082 const Value *BasePtr = GEP->getPointerOperand();
5083 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
5084
5085 // Make sure the base is scalar and the index is a vector.
5086 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
5087 return false;
5088
5089 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
5090 if (ScaleVal.isScalable())
5091 return false;
5092
5093 // Target may not support the required addressing mode.
5094 if (ScaleVal != 1 &&
5095 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
5096 return false;
5097
5098 Base = SDB->getValue(BasePtr);
5099 Index = SDB->getValue(IndexVal);
5100
5101 Scale =
5102 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5103 return true;
5104}
5105
5106void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
5107 SDLoc sdl = getCurSDLoc();
5108
5109 // llvm.masked.scatter.*(Src0, Ptrs, Mask)
5110 const Value *Ptr = I.getArgOperand(1);
5111 SDValue Src0 = getValue(I.getArgOperand(0));
5112 SDValue Mask = getValue(I.getArgOperand(2));
5113 EVT VT = Src0.getValueType();
5114 Align Alignment = I.getParamAlign(1).valueOrOne();
5115 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5116
5117 SDValue Base;
5118 SDValue Index;
5119 SDValue Scale;
5120 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5121 I.getParent(), VT.getScalarStoreSize());
5122
5123 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5124 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5125 MachinePointerInfo(AS), MachineMemOperand::MOStore,
5126 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
5127 if (!UniformBase) {
5128 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5129 Index = getValue(Ptr);
5130 Scale =
5131 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5132 }
5133
5134 EVT IdxVT = Index.getValueType();
5135 EVT EltTy = IdxVT.getVectorElementType();
5136 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5137 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5138 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5139 }
5140
5141 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
5142 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
5143 Ops, MMO, ISD::SIGNED_SCALED, false);
5144 DAG.setRoot(Scatter);
5145 setValue(&I, Scatter);
5146}
5147
5148void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
5149 SDLoc sdl = getCurSDLoc();
5150
5151 Value *PtrOperand = I.getArgOperand(0);
5152 Value *MaskOperand = I.getArgOperand(1);
5153 Value *Src0Operand = I.getArgOperand(2);
5154 Align Alignment = I.getParamAlign(0).valueOrOne();
5155
5156 SDValue Ptr = getValue(PtrOperand);
5157 SDValue Src0 = getValue(Src0Operand);
5158 SDValue Mask = getValue(MaskOperand);
5159 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5160
5161 EVT VT = Src0.getValueType();
5162 AAMDNodes AAInfo = I.getAAMetadata();
5163 const MDNode *Ranges = getRangeMetadata(I);
5164 const MDNode *MemCacheHint = getMemCacheHintMetadata(I, /*OperandNo=*/0);
5165
5166 // Do not serialize masked loads of constant memory with anything.
5167 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
5168 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
5169
5170 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
5171
5172 const auto &TLI = DAG.getTargetLoweringInfo();
5173
5174 auto MMOFlags = MachineMemOperand::MOLoad;
5175 MMOFlags |= TLI.getTargetMMOFlags(I);
5176 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5178 if (I.hasMetadata(LLVMContext::MD_invariant_load))
5180
5181 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5182 MachinePointerInfo(PtrOperand), MMOFlags,
5183 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5184 MMOMetadata(AAInfo, Ranges, MemCacheHint));
5185
5186 // The Load/Res may point to different values and both of them are output
5187 // variables.
5188 SDValue Load;
5189 SDValue Res;
5190 if (!IsExpanding &&
5191 TTI->hasConditionalLoadStoreForType(Src0Operand->getType(),
5192 /*IsStore=*/false))
5193 Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
5194 else
5195 Res = Load =
5196 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
5197 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5198 if (AddToChain)
5199 PendingLoads.push_back(Load.getValue(1));
5200 setValue(&I, Res);
5201}
5202
5203void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5204 SDLoc sdl = getCurSDLoc();
5205
5206 // @llvm.masked.gather.*(Ptrs, Mask, Src0)
5207 const Value *Ptr = I.getArgOperand(0);
5208 SDValue Src0 = getValue(I.getArgOperand(2));
5209 SDValue Mask = getValue(I.getArgOperand(1));
5210
5211 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5212 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5213 Align Alignment = I.getParamAlign(0).valueOrOne();
5214
5215 const MDNode *Ranges = getRangeMetadata(I);
5216
5217 SDValue Root = DAG.getRoot();
5218 SDValue Base;
5219 SDValue Index;
5220 SDValue Scale;
5221 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5222 I.getParent(), VT.getScalarStoreSize());
5223 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5224 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5225 MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5227 MMOMetadata(I.getAAMetadata(), Ranges));
5228
5229 if (!UniformBase) {
5230 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5231 Index = getValue(Ptr);
5232 Scale =
5233 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5234 }
5235
5236 EVT IdxVT = Index.getValueType();
5237 EVT EltTy = IdxVT.getVectorElementType();
5238 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5239 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5240 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5241 }
5242
5243 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5244 SDValue Gather =
5245 DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, Ops, MMO,
5247
5248 PendingLoads.push_back(Gather.getValue(1));
5249 setValue(&I, Gather);
5250}
5251
5252void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5253 SDLoc dl = getCurSDLoc();
5254 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5255 AtomicOrdering FailureOrdering = I.getFailureOrdering();
5256 SyncScope::ID SSID = I.getSyncScopeID();
5257
5258 SDValue InChain = getRoot();
5259
5260 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5261 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5262
5263 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5264 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5265
5266 MachineFunction &MF = DAG.getMachineFunction();
5267 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5268 MachineMemOperand *MMO = MF.getMachineMemOperand(
5269 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5270 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5271 SSID, SuccessOrdering, FailureOrdering);
5272
5274 dl, MemVT, VTs, InChain,
5275 getValue(I.getPointerOperand()),
5276 getValue(I.getCompareOperand()),
5277 getValue(I.getNewValOperand()), MMO);
5278
5279 SDValue OutChain = L.getValue(2);
5280
5281 setValue(&I, L);
5282 DAG.setRoot(OutChain);
5283}
5284
5285void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5286 SDLoc dl = getCurSDLoc();
5288 switch (I.getOperation()) {
5289 default: llvm_unreachable("Unknown atomicrmw operation");
5307 break;
5310 break;
5313 break;
5316 break;
5319 break;
5322 break;
5325 break;
5328 break;
5329 }
5330 AtomicOrdering Ordering = I.getOrdering();
5331 SyncScope::ID SSID = I.getSyncScopeID();
5332
5333 SDValue InChain = getRoot();
5334
5335 auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5336 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5337 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5338
5339 MachineFunction &MF = DAG.getMachineFunction();
5340 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5341 MachineMemOperand *MMO = MF.getMachineMemOperand(
5342 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5343 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5344 SSID, Ordering);
5345
5346 SDValue L =
5347 DAG.getAtomic(NT, dl, MemVT, InChain,
5348 getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5349 MMO);
5350
5351 SDValue OutChain = L.getValue(1);
5352
5353 setValue(&I, L);
5354 DAG.setRoot(OutChain);
5355}
5356
5357void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5358 SDLoc dl = getCurSDLoc();
5359 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5360 SDValue Ops[3];
5361 Ops[0] = getRoot();
5362 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5363 TLI.getFenceOperandTy(DAG.getDataLayout()));
5364 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5365 TLI.getFenceOperandTy(DAG.getDataLayout()));
5366 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5367 setValue(&I, N);
5368 DAG.setRoot(N);
5369}
5370
5371void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5372 SDLoc dl = getCurSDLoc();
5373 AtomicOrdering Order = I.getOrdering();
5374 SyncScope::ID SSID = I.getSyncScopeID();
5375
5376 SDValue InChain = getRoot();
5377
5378 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5379 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5380 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5381
5382 if (!TLI.isAtomicAlignmentSupported(I.getAlign(), MemVT.getSizeInBits() / 8))
5383 report_fatal_error("Cannot generate unaligned atomic load");
5384
5385 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5386
5387 const MDNode *Ranges = getRangeMetadata(I);
5388 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5389 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5390 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5391 I.getAlign(), MMOMetadata(AAMDNodes(), Ranges, MemCacheHint), SSID,
5392 Order);
5393
5394 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5395
5396 SDValue Ptr = getValue(I.getPointerOperand());
5397 SDValue L =
5398 DAG.getAtomicLoad(ISD::NON_EXTLOAD, dl, MemVT, MemVT, InChain, Ptr, MMO);
5399
5400 SDValue OutChain = L.getValue(1);
5401 if (MemVT != VT)
5402 L = DAG.getPtrExtOrTrunc(L, dl, VT);
5403
5404 setValue(&I, L);
5405 DAG.setRoot(OutChain);
5406}
5407
5408void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5409 SDLoc dl = getCurSDLoc();
5410
5411 AtomicOrdering Ordering = I.getOrdering();
5412 SyncScope::ID SSID = I.getSyncScopeID();
5413
5414 SDValue InChain = getRoot();
5415
5416 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5417 EVT MemVT =
5418 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5419
5420 if (!TLI.isAtomicAlignmentSupported(I.getAlign(), MemVT.getSizeInBits() / 8))
5421 report_fatal_error("Cannot generate unaligned atomic store");
5422
5423 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5424
5425 MachineFunction &MF = DAG.getMachineFunction();
5426 const MDNode *MemCacheHint =
5427 getMemCacheHintMetadata(I, I.getPointerOperandIndex());
5428 MachineMemOperand *MMO = MF.getMachineMemOperand(
5429 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5430 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5431 SSID, Ordering);
5432
5433 SDValue Val = getValue(I.getValueOperand());
5434 if (Val.getValueType() != MemVT)
5435 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5436 SDValue Ptr = getValue(I.getPointerOperand());
5437
5438 SDValue OutChain =
5439 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5440
5441 setValue(&I, OutChain);
5442 DAG.setRoot(OutChain);
5443}
5444
5445/// Check if this intrinsic call depends on the chain (1st return value)
5446/// and if it only *loads* memory.
5447/// Ignore the callsite's attributes. A specific call site may be marked with
5448/// readnone, but the lowering code will expect the chain based on the
5449/// definition.
5450std::pair<bool, bool>
5451SelectionDAGBuilder::getTargetIntrinsicCallProperties(const CallBase &I) {
5452 const Function *F = I.getCalledFunction();
5453 bool HasChain = !F->doesNotAccessMemory();
5454 bool OnlyLoad =
5455 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5456
5457 return {HasChain, OnlyLoad};
5458}
5459
5460SmallVector<SDValue, 8> SelectionDAGBuilder::getTargetIntrinsicOperands(
5461 const CallBase &I, bool HasChain, bool OnlyLoad,
5462 TargetLowering::IntrinsicInfo *TgtMemIntrinsicInfo) {
5463 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5464
5465 // Build the operand list.
5467 if (HasChain) { // If this intrinsic has side-effects, chainify it.
5468 if (OnlyLoad) {
5469 // We don't need to serialize loads against other loads.
5470 Ops.push_back(DAG.getRoot());
5471 } else {
5472 Ops.push_back(getRoot());
5473 }
5474 }
5475
5476 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5477 if (!TgtMemIntrinsicInfo || TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_VOID ||
5478 TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_W_CHAIN)
5479 Ops.push_back(DAG.getTargetConstant(I.getIntrinsicID(), getCurSDLoc(),
5480 TLI.getPointerTy(DAG.getDataLayout())));
5481
5482 // Add all operands of the call to the operand list.
5483 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5484 const Value *Arg = I.getArgOperand(i);
5485 if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5486 Ops.push_back(getValue(Arg));
5487 continue;
5488 }
5489
5490 // Use TargetConstant instead of a regular constant for immarg.
5491 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5492 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5493 assert(CI->getBitWidth() <= 64 &&
5494 "large intrinsic immediates not handled");
5495 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5496 } else {
5497 Ops.push_back(
5498 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5499 }
5500 }
5501
5502 if (std::optional<OperandBundleUse> Bundle =
5503 I.getOperandBundle(LLVMContext::OB_deactivation_symbol)) {
5504 auto *Sym = Bundle->Inputs[0].get();
5505 SDValue SDSym = getValue(Sym);
5506 SDSym = DAG.getDeactivationSymbol(cast<GlobalValue>(Sym));
5507 Ops.push_back(SDSym);
5508 }
5509
5510 if (std::optional<OperandBundleUse> Bundle =
5511 I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5512 Value *Token = Bundle->Inputs[0].get();
5513 SDValue ConvControlToken = getValue(Token);
5514 assert(Ops.back().getValueType() != MVT::Glue &&
5515 "Did not expect another glue node here.");
5516 ConvControlToken =
5517 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5518 Ops.push_back(ConvControlToken);
5519 }
5520
5521 return Ops;
5522}
5523
5524SDVTList SelectionDAGBuilder::getTargetIntrinsicVTList(const CallBase &I,
5525 bool HasChain) {
5526 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5527
5528 SmallVector<EVT, 4> ValueVTs;
5529 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5530
5531 if (HasChain)
5532 ValueVTs.push_back(MVT::Other);
5533
5534 return DAG.getVTList(ValueVTs);
5535}
5536
5537/// Get an INTRINSIC node for a target intrinsic which does not touch memory.
5538SDValue SelectionDAGBuilder::getTargetNonMemIntrinsicNode(
5539 const Type &IntrinsicVT, bool HasChain, ArrayRef<SDValue> Ops,
5540 const SDVTList &VTs) {
5541 if (!HasChain)
5542 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5543 if (!IntrinsicVT.isVoidTy())
5544 return DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5545 return DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5546}
5547
5548/// Set root, convert return type if necessary and check alignment.
5549SDValue SelectionDAGBuilder::handleTargetIntrinsicRet(const CallBase &I,
5550 bool HasChain,
5551 bool OnlyLoad,
5552 SDValue Result) {
5553 if (HasChain) {
5554 SDValue Chain = Result.getValue(Result.getNode()->getNumValues() - 1);
5555 if (OnlyLoad)
5556 PendingLoads.push_back(Chain);
5557 else
5558 DAG.setRoot(Chain);
5559 }
5560
5561 if (I.getType()->isVoidTy())
5562 return Result;
5563
5564 if (MaybeAlign Alignment = I.getRetAlign(); InsertAssertAlign && Alignment) {
5565 // Insert `assertalign` node if there's an alignment.
5566 Result = DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5567 } else if (!isa<VectorType>(I.getType())) {
5568 Result = lowerRangeToAssertZExt(DAG, I, Result);
5569 }
5570
5571 return Result;
5572}
5573
5574/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5575/// node.
5576void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5577 unsigned Intrinsic) {
5578 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
5579 Intrinsic::ID IntrinsicID = static_cast<Intrinsic::ID>(Intrinsic);
5580
5581 if (!DAG.getMachineFunction().getSubtarget().isIntrinsicSupported(
5582 Intrinsic)) {
5583 SDLoc DL = getCurSDLoc();
5584 DAG.getContext()->diagnose(DiagnosticInfoUnsupportedTargetIntrinsic(
5585 *I.getFunction(), IntrinsicID, DL.getDebugLoc()));
5586
5587 // The intrinsic is not available on this subtarget. Preserve the chain for
5588 // side-effecting intrinsics and lower any result to poison so that
5589 // compilation can continue and collect further diagnostics.
5590 if (HasChain && !OnlyLoad)
5591 DAG.setRoot(getRoot());
5592
5594 return;
5595 }
5596
5597 // Infos is set by getTgtMemIntrinsic.
5599 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5600 TLI.getTgtMemIntrinsic(Infos, I, DAG.getMachineFunction(), Intrinsic);
5601 // Use the first (primary) info determines the node opcode.
5602 TargetLowering::IntrinsicInfo *Info = !Infos.empty() ? &Infos[0] : nullptr;
5603
5605 getTargetIntrinsicOperands(I, HasChain, OnlyLoad, Info);
5606 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
5607
5608 // Propagate fast-math-flags from IR to node(s).
5609 SDNodeFlags Flags;
5610 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5611 Flags.copyFMF(*FPMO);
5612 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5613
5614 // Create the node.
5616
5617 // In some cases, custom collection of operands from CallInst I may be needed.
5619 if (!Infos.empty()) {
5620 // This is target intrinsic that touches memory
5621 // Create MachineMemOperands for each memory access described by the target.
5622 MachineFunction &MF = DAG.getMachineFunction();
5624 for (const auto &Info : Infos) {
5625 // TODO: We currently just fallback to address space 0 if
5626 // getTgtMemIntrinsic didn't yield anything useful.
5627 MachinePointerInfo MPI;
5628 if (Info.ptrVal)
5629 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5630 else if (Info.fallbackAddressSpace)
5631 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5632 EVT MemVT = Info.memVT;
5633 LocationSize Size = LocationSize::precise(Info.size);
5634 if (Size.hasValue() && !Size.getValue())
5636 Align Alignment = Info.align.value_or(DAG.getEVTAlign(MemVT));
5637 MachineMemOperand *MMO = MF.getMachineMemOperand(
5638 MPI, Info.flags, Size, Alignment, I.getAAMetadata(), Info.ssid,
5639 Info.order, Info.failureOrder);
5640 MMOs.push_back(MMO);
5641 }
5642
5643 Result = DAG.getMemIntrinsicNode(Info->opc, getCurSDLoc(), VTs, Ops,
5644 Info->memVT, MMOs);
5645 } else {
5646 Result = getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
5647 }
5648
5649 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
5650
5651 setValue(&I, Result);
5652}
5653
5654/// GetSignificand - Get the significand and build it into a floating-point
5655/// number with exponent of 1:
5656///
5657/// Op = (Op & 0x007fffff) | 0x3f800000;
5658///
5659/// where Op is the hexadecimal representation of floating point value.
5661 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5662 DAG.getConstant(0x007fffff, dl, MVT::i32));
5663 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5664 DAG.getConstant(0x3f800000, dl, MVT::i32));
5665 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5666}
5667
5668/// GetExponent - Get the exponent:
5669///
5670/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5671///
5672/// where Op is the hexadecimal representation of floating point value.
5674 const TargetLowering &TLI, const SDLoc &dl) {
5675 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5676 DAG.getConstant(0x7f800000, dl, MVT::i32));
5677 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
5678 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5679 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5680 DAG.getConstant(127, dl, MVT::i32));
5681 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5682}
5683
5684/// getF32Constant - Get 32-bit floating point constant.
5685static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5686 const SDLoc &dl) {
5687 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5688 MVT::f32);
5689}
5690
5692 SelectionDAG &DAG) {
5693 // TODO: What fast-math-flags should be set on the floating-point nodes?
5694
5695 // IntegerPartOfX = ((int32_t)(t0);
5696 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5697
5698 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
5699 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5700 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5701
5702 // IntegerPartOfX <<= 23;
5703 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5704 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5705
5706 SDValue TwoToFractionalPartOfX;
5707 if (LimitFloatPrecision <= 6) {
5708 // For floating-point precision of 6:
5709 //
5710 // TwoToFractionalPartOfX =
5711 // 0.997535578f +
5712 // (0.735607626f + 0.252464424f * x) * x;
5713 //
5714 // error 0.0144103317, which is 6 bits
5715 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5716 getF32Constant(DAG, 0x3e814304, dl));
5717 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5718 getF32Constant(DAG, 0x3f3c50c8, dl));
5719 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5720 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5721 getF32Constant(DAG, 0x3f7f5e7e, dl));
5722 } else if (LimitFloatPrecision <= 12) {
5723 // For floating-point precision of 12:
5724 //
5725 // TwoToFractionalPartOfX =
5726 // 0.999892986f +
5727 // (0.696457318f +
5728 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
5729 //
5730 // error 0.000107046256, which is 13 to 14 bits
5731 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5732 getF32Constant(DAG, 0x3da235e3, dl));
5733 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5734 getF32Constant(DAG, 0x3e65b8f3, dl));
5735 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5736 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5737 getF32Constant(DAG, 0x3f324b07, dl));
5738 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5739 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5740 getF32Constant(DAG, 0x3f7ff8fd, dl));
5741 } else { // LimitFloatPrecision <= 18
5742 // For floating-point precision of 18:
5743 //
5744 // TwoToFractionalPartOfX =
5745 // 0.999999982f +
5746 // (0.693148872f +
5747 // (0.240227044f +
5748 // (0.554906021e-1f +
5749 // (0.961591928e-2f +
5750 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5751 // error 2.47208000*10^(-7), which is better than 18 bits
5752 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5753 getF32Constant(DAG, 0x3924b03e, dl));
5754 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5755 getF32Constant(DAG, 0x3ab24b87, dl));
5756 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5757 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5758 getF32Constant(DAG, 0x3c1d8c17, dl));
5759 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5760 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5761 getF32Constant(DAG, 0x3d634a1d, dl));
5762 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5763 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5764 getF32Constant(DAG, 0x3e75fe14, dl));
5765 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5766 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5767 getF32Constant(DAG, 0x3f317234, dl));
5768 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5769 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5770 getF32Constant(DAG, 0x3f800000, dl));
5771 }
5772
5773 // Add the exponent into the result in integer domain.
5774 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5775 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5776 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5777}
5778
5779/// expandExp - Lower an exp intrinsic. Handles the special sequences for
5780/// limited-precision mode.
5782 const TargetLowering &TLI, SDNodeFlags Flags) {
5783 if (Op.getValueType() == MVT::f32 &&
5785
5786 // Put the exponent in the right bit position for later addition to the
5787 // final result:
5788 //
5789 // t0 = Op * log2(e)
5790
5791 // TODO: What fast-math-flags should be set here?
5792 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5793 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5794 return getLimitedPrecisionExp2(t0, dl, DAG);
5795 }
5796
5797 // No special expansion.
5798 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5799}
5800
5801/// expandLog - Lower a log intrinsic. Handles the special sequences for
5802/// limited-precision mode.
5804 const TargetLowering &TLI, SDNodeFlags Flags) {
5805 // TODO: What fast-math-flags should be set on the floating-point nodes?
5806
5807 if (Op.getValueType() == MVT::f32 &&
5809 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5810
5811 // Scale the exponent by log(2).
5812 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5813 SDValue LogOfExponent =
5814 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5815 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5816
5817 // Get the significand and build it into a floating-point number with
5818 // exponent of 1.
5819 SDValue X = GetSignificand(DAG, Op1, dl);
5820
5821 SDValue LogOfMantissa;
5822 if (LimitFloatPrecision <= 6) {
5823 // For floating-point precision of 6:
5824 //
5825 // LogofMantissa =
5826 // -1.1609546f +
5827 // (1.4034025f - 0.23903021f * x) * x;
5828 //
5829 // error 0.0034276066, which is better than 8 bits
5830 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5831 getF32Constant(DAG, 0xbe74c456, dl));
5832 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5833 getF32Constant(DAG, 0x3fb3a2b1, dl));
5834 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5835 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5836 getF32Constant(DAG, 0x3f949a29, dl));
5837 } else if (LimitFloatPrecision <= 12) {
5838 // For floating-point precision of 12:
5839 //
5840 // LogOfMantissa =
5841 // -1.7417939f +
5842 // (2.8212026f +
5843 // (-1.4699568f +
5844 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5845 //
5846 // error 0.000061011436, which is 14 bits
5847 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5848 getF32Constant(DAG, 0xbd67b6d6, dl));
5849 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5850 getF32Constant(DAG, 0x3ee4f4b8, dl));
5851 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5852 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5853 getF32Constant(DAG, 0x3fbc278b, dl));
5854 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5855 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5856 getF32Constant(DAG, 0x40348e95, dl));
5857 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5858 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5859 getF32Constant(DAG, 0x3fdef31a, dl));
5860 } else { // LimitFloatPrecision <= 18
5861 // For floating-point precision of 18:
5862 //
5863 // LogOfMantissa =
5864 // -2.1072184f +
5865 // (4.2372794f +
5866 // (-3.7029485f +
5867 // (2.2781945f +
5868 // (-0.87823314f +
5869 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5870 //
5871 // error 0.0000023660568, which is better than 18 bits
5872 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5873 getF32Constant(DAG, 0xbc91e5ac, dl));
5874 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5875 getF32Constant(DAG, 0x3e4350aa, dl));
5876 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5877 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5878 getF32Constant(DAG, 0x3f60d3e3, dl));
5879 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5880 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5881 getF32Constant(DAG, 0x4011cdf0, dl));
5882 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5883 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5884 getF32Constant(DAG, 0x406cfd1c, dl));
5885 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5886 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5887 getF32Constant(DAG, 0x408797cb, dl));
5888 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5889 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5890 getF32Constant(DAG, 0x4006dcab, dl));
5891 }
5892
5893 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5894 }
5895
5896 // No special expansion.
5897 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5898}
5899
5900/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5901/// limited-precision mode.
5903 const TargetLowering &TLI, SDNodeFlags Flags) {
5904 // TODO: What fast-math-flags should be set on the floating-point nodes?
5905
5906 if (Op.getValueType() == MVT::f32 &&
5908 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5909
5910 // Get the exponent.
5911 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5912
5913 // Get the significand and build it into a floating-point number with
5914 // exponent of 1.
5915 SDValue X = GetSignificand(DAG, Op1, dl);
5916
5917 // Different possible minimax approximations of significand in
5918 // floating-point for various degrees of accuracy over [1,2].
5919 SDValue Log2ofMantissa;
5920 if (LimitFloatPrecision <= 6) {
5921 // For floating-point precision of 6:
5922 //
5923 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5924 //
5925 // error 0.0049451742, which is more than 7 bits
5926 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5927 getF32Constant(DAG, 0xbeb08fe0, dl));
5928 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5929 getF32Constant(DAG, 0x40019463, dl));
5930 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5931 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5932 getF32Constant(DAG, 0x3fd6633d, dl));
5933 } else if (LimitFloatPrecision <= 12) {
5934 // For floating-point precision of 12:
5935 //
5936 // Log2ofMantissa =
5937 // -2.51285454f +
5938 // (4.07009056f +
5939 // (-2.12067489f +
5940 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5941 //
5942 // error 0.0000876136000, which is better than 13 bits
5943 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5944 getF32Constant(DAG, 0xbda7262e, dl));
5945 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5946 getF32Constant(DAG, 0x3f25280b, dl));
5947 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5948 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5949 getF32Constant(DAG, 0x4007b923, dl));
5950 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5951 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5952 getF32Constant(DAG, 0x40823e2f, dl));
5953 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5954 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5955 getF32Constant(DAG, 0x4020d29c, dl));
5956 } else { // LimitFloatPrecision <= 18
5957 // For floating-point precision of 18:
5958 //
5959 // Log2ofMantissa =
5960 // -3.0400495f +
5961 // (6.1129976f +
5962 // (-5.3420409f +
5963 // (3.2865683f +
5964 // (-1.2669343f +
5965 // (0.27515199f -
5966 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5967 //
5968 // error 0.0000018516, which is better than 18 bits
5969 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5970 getF32Constant(DAG, 0xbcd2769e, dl));
5971 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5972 getF32Constant(DAG, 0x3e8ce0b9, dl));
5973 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5974 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5975 getF32Constant(DAG, 0x3fa22ae7, dl));
5976 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5977 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5978 getF32Constant(DAG, 0x40525723, dl));
5979 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5980 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5981 getF32Constant(DAG, 0x40aaf200, dl));
5982 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5983 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5984 getF32Constant(DAG, 0x40c39dad, dl));
5985 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5986 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5987 getF32Constant(DAG, 0x4042902c, dl));
5988 }
5989
5990 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5991 }
5992
5993 // No special expansion.
5994 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5995}
5996
5997/// expandLog10 - Lower a log10 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 log10(2) [0.30102999f].
6008 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
6009 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
6010 getF32Constant(DAG, 0x3e9a209a, dl));
6011
6012 // Get the significand and build it into a floating-point number with
6013 // exponent of 1.
6014 SDValue X = GetSignificand(DAG, Op1, dl);
6015
6016 SDValue Log10ofMantissa;
6017 if (LimitFloatPrecision <= 6) {
6018 // For floating-point precision of 6:
6019 //
6020 // Log10ofMantissa =
6021 // -0.50419619f +
6022 // (0.60948995f - 0.10380950f * x) * x;
6023 //
6024 // error 0.0014886165, which is 6 bits
6025 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6026 getF32Constant(DAG, 0xbdd49a13, dl));
6027 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6028 getF32Constant(DAG, 0x3f1c0789, dl));
6029 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6030 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6031 getF32Constant(DAG, 0x3f011300, dl));
6032 } else if (LimitFloatPrecision <= 12) {
6033 // For floating-point precision of 12:
6034 //
6035 // Log10ofMantissa =
6036 // -0.64831180f +
6037 // (0.91751397f +
6038 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
6039 //
6040 // error 0.00019228036, which is better than 12 bits
6041 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6042 getF32Constant(DAG, 0x3d431f31, dl));
6043 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6044 getF32Constant(DAG, 0x3ea21fb2, dl));
6045 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6046 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6047 getF32Constant(DAG, 0x3f6ae232, dl));
6048 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6049 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6050 getF32Constant(DAG, 0x3f25f7c3, dl));
6051 } else { // LimitFloatPrecision <= 18
6052 // For floating-point precision of 18:
6053 //
6054 // Log10ofMantissa =
6055 // -0.84299375f +
6056 // (1.5327582f +
6057 // (-1.0688956f +
6058 // (0.49102474f +
6059 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
6060 //
6061 // error 0.0000037995730, which is better than 18 bits
6062 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6063 getF32Constant(DAG, 0x3c5d51ce, dl));
6064 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6065 getF32Constant(DAG, 0x3e00685a, dl));
6066 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6067 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6068 getF32Constant(DAG, 0x3efb6798, dl));
6069 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6070 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6071 getF32Constant(DAG, 0x3f88d192, dl));
6072 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6073 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
6074 getF32Constant(DAG, 0x3fc4316c, dl));
6075 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6076 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
6077 getF32Constant(DAG, 0x3f57ce70, dl));
6078 }
6079
6080 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
6081 }
6082
6083 // No special expansion.
6084 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
6085}
6086
6087/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
6088/// limited-precision mode.
6090 const TargetLowering &TLI, SDNodeFlags Flags) {
6091 if (Op.getValueType() == MVT::f32 &&
6093 return getLimitedPrecisionExp2(Op, dl, DAG);
6094
6095 // No special expansion.
6096 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
6097}
6098
6099/// visitPow - Lower a pow intrinsic. Handles the special sequences for
6100/// limited-precision mode with x == 10.0f.
6102 SelectionDAG &DAG, const TargetLowering &TLI,
6103 SDNodeFlags Flags) {
6104 bool IsExp10 = false;
6105 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
6108 APFloat Ten(10.0f);
6109 IsExp10 = LHSC->isExactlyValue(Ten);
6110 }
6111 }
6112
6113 // TODO: What fast-math-flags should be set on the FMUL node?
6114 if (IsExp10) {
6115 // Put the exponent in the right bit position for later addition to the
6116 // final result:
6117 //
6118 // #define LOG2OF10 3.3219281f
6119 // t0 = Op * LOG2OF10;
6120 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
6121 getF32Constant(DAG, 0x40549a78, dl));
6122 return getLimitedPrecisionExp2(t0, dl, DAG);
6123 }
6124
6125 // No special expansion.
6126 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
6127}
6128
6129/// ExpandPowI - Expand a llvm.powi intrinsic.
6131 SelectionDAG &DAG) {
6132 // If RHS is a constant, we can expand this out to a multiplication tree if
6133 // it's beneficial on the target, otherwise we end up lowering to a call to
6134 // __powidf2 (for example).
6136 unsigned Val = RHSC->getSExtValue();
6137
6138 // powi(x, 0) -> 1.0
6139 if (Val == 0)
6140 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
6141
6143 Val, DAG.shouldOptForSize())) {
6144 // Get the exponent as a positive value.
6145 if ((int)Val < 0)
6146 Val = -Val;
6147 // We use the simple binary decomposition method to generate the multiply
6148 // sequence. There are more optimal ways to do this (for example,
6149 // powi(x,15) generates one more multiply than it should), but this has
6150 // the benefit of being both really simple and much better than a libcall.
6151 SDValue Res; // Logically starts equal to 1.0
6152 SDValue CurSquare = LHS;
6153 // TODO: Intrinsics should have fast-math-flags that propagate to these
6154 // nodes.
6155 while (Val) {
6156 if (Val & 1) {
6157 if (Res.getNode())
6158 Res =
6159 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
6160 else
6161 Res = CurSquare; // 1.0*CurSquare.
6162 }
6163
6164 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
6165 CurSquare, CurSquare);
6166 Val >>= 1;
6167 }
6168
6169 // If the original was negative, invert the result, producing 1/(x*x*x).
6170 if (RHSC->getSExtValue() < 0)
6171 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
6172 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
6173 return Res;
6174 }
6175 }
6176
6177 // Otherwise, expand to a libcall.
6178 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
6179}
6180
6181static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
6182 SDValue LHS, SDValue RHS, SDValue Scale,
6183 SelectionDAG &DAG, const TargetLowering &TLI) {
6184 EVT VT = LHS.getValueType();
6185 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
6186 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
6187 LLVMContext &Ctx = *DAG.getContext();
6188
6189 // If the type is legal but the operation isn't, this node might survive all
6190 // the way to operation legalization. If we end up there and we do not have
6191 // the ability to widen the type (if VT*2 is not legal), we cannot expand the
6192 // node.
6193
6194 // Coax the legalizer into expanding the node during type legalization instead
6195 // by bumping the size by one bit. This will force it to Promote, enabling the
6196 // early expansion and avoiding the need to expand later.
6197
6198 // We don't have to do this if Scale is 0; that can always be expanded, unless
6199 // it's a saturating signed operation. Those can experience true integer
6200 // division overflow, a case which we must avoid.
6201
6202 // FIXME: We wouldn't have to do this (or any of the early
6203 // expansion/promotion) if it was possible to expand a libcall of an
6204 // illegal type during operation legalization. But it's not, so things
6205 // get a bit hacky.
6206 unsigned ScaleInt = Scale->getAsZExtVal();
6207 if ((ScaleInt > 0 || (Saturating && Signed)) &&
6208 (TLI.isTypeLegal(VT) ||
6209 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
6211 Opcode, VT, ScaleInt);
6212 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
6213 EVT PromVT;
6214 if (VT.isScalarInteger())
6215 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
6216 else if (VT.isVector()) {
6217 PromVT = VT.getVectorElementType();
6218 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
6219 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
6220 } else
6221 llvm_unreachable("Wrong VT for DIVFIX?");
6222 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
6223 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
6224 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
6225 // For saturating operations, we need to shift up the LHS to get the
6226 // proper saturation width, and then shift down again afterwards.
6227 if (Saturating)
6228 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
6229 DAG.getConstant(1, DL, ShiftTy));
6230 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
6231 if (Saturating)
6232 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
6233 DAG.getConstant(1, DL, ShiftTy));
6234 return DAG.getZExtOrTrunc(Res, DL, VT);
6235 }
6236 }
6237
6238 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
6239}
6240
6241// getUnderlyingArgRegs - Find underlying registers used for a truncated,
6242// bitcasted, or split argument. Returns a list of <Register, size in bits>
6243static void
6244getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
6245 const SDValue &N) {
6246 switch (N.getOpcode()) {
6247 case ISD::CopyFromReg: {
6248 SDValue Op = N.getOperand(1);
6249 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
6250 Op.getValueType().getSizeInBits());
6251 return;
6252 }
6253 case ISD::BITCAST:
6254 case ISD::AssertZext:
6255 case ISD::AssertSext:
6256 case ISD::TRUNCATE:
6257 getUnderlyingArgRegs(Regs, N.getOperand(0));
6258 return;
6259 case ISD::BUILD_PAIR:
6260 case ISD::BUILD_VECTOR:
6262 for (SDValue Op : N->op_values())
6263 getUnderlyingArgRegs(Regs, Op);
6264 return;
6265 default:
6266 return;
6267 }
6268}
6269
6270/// If the DbgValueInst is a dbg_value of a function argument, create the
6271/// corresponding DBG_VALUE machine instruction for it now. At the end of
6272/// instruction selection, they will be inserted to the entry BB.
6273/// We don't currently support this for variadic dbg_values, as they shouldn't
6274/// appear for function arguments or in the prologue.
6275bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6276 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6277 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6278 const Argument *Arg = dyn_cast<Argument>(V);
6279 if (!Arg)
6280 return false;
6281
6282 MachineFunction &MF = DAG.getMachineFunction();
6283 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6284
6285 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6286 // we've been asked to pursue.
6287 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6288 bool Indirect) {
6289 if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6290 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6291 // pointing at the VReg, which will be patched up later.
6292 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6294 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6295 /* isKill */ false, /* isDead */ false,
6296 /* isUndef */ false, /* isEarlyClobber */ false,
6297 /* SubReg */ 0, /* isDebug */ true)});
6298
6299 auto *NewDIExpr = FragExpr;
6300 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6301 // the DIExpression.
6302 if (Indirect)
6303 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6305 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6306 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6307 } else {
6308 // Create a completely standard DBG_VALUE.
6309 auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6310 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6311 }
6312 };
6313
6314 if (Kind == FuncArgumentDbgValueKind::Value) {
6315 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6316 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6317 // the entry block.
6318 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6319 if (!IsInEntryBlock)
6320 return false;
6321
6322 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6323 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6324 // variable that also is a param.
6325 //
6326 // Although, if we are at the top of the entry block already, we can still
6327 // emit using ArgDbgValue. This might catch some situations when the
6328 // dbg.value refers to an argument that isn't used in the entry block, so
6329 // any CopyToReg node would be optimized out and the only way to express
6330 // this DBG_VALUE is by using the physical reg (or FI) as done in this
6331 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
6332 // we should only emit as ArgDbgValue if the Variable is an argument to the
6333 // current function, and the dbg.value intrinsic is found in the entry
6334 // block.
6335 bool VariableIsFunctionInputArg = Variable->isParameter() &&
6336 !DL->getInlinedAt();
6337 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6338 if (!IsInPrologue && !VariableIsFunctionInputArg)
6339 return false;
6340
6341 // Here we assume that a function argument on IR level only can be used to
6342 // describe one input parameter on source level. If we for example have
6343 // source code like this
6344 //
6345 // struct A { long x, y; };
6346 // void foo(struct A a, long b) {
6347 // ...
6348 // b = a.x;
6349 // ...
6350 // }
6351 //
6352 // and IR like this
6353 //
6354 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
6355 // entry:
6356 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6357 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6358 // call void @llvm.dbg.value(metadata i32 %b, "b",
6359 // ...
6360 // call void @llvm.dbg.value(metadata i32 %a1, "b"
6361 // ...
6362 //
6363 // then the last dbg.value is describing a parameter "b" using a value that
6364 // is an argument. But since we already has used %a1 to describe a parameter
6365 // we should not handle that last dbg.value here (that would result in an
6366 // incorrect hoisting of the DBG_VALUE to the function entry).
6367 // Notice that we allow one dbg.value per IR level argument, to accommodate
6368 // for the situation with fragments above.
6369 // If there is no node for the value being handled, we return true to skip
6370 // the normal generation of debug info, as it would kill existing debug
6371 // info for the parameter in case of duplicates.
6372 if (VariableIsFunctionInputArg) {
6373 unsigned ArgNo = Arg->getArgNo();
6374 if (ArgNo >= FuncInfo.DescribedArgs.size())
6375 FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6376 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6377 return !NodeMap[V].getNode();
6378 FuncInfo.DescribedArgs.set(ArgNo);
6379 }
6380 }
6381
6382 bool IsIndirect = false;
6383 std::optional<MachineOperand> Op;
6384 // Some arguments' frame index is recorded during argument lowering.
6385 int FI = FuncInfo.getArgumentFrameIndex(Arg);
6386 if (FI != std::numeric_limits<int>::max())
6388
6390 if (!Op && N.getNode()) {
6391 getUnderlyingArgRegs(ArgRegsAndSizes, N);
6392 Register Reg;
6393 if (ArgRegsAndSizes.size() == 1)
6394 Reg = ArgRegsAndSizes.front().first;
6395
6396 if (Reg && Reg.isVirtual()) {
6397 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6398 Register PR = RegInfo.getLiveInPhysReg(Reg);
6399 if (PR)
6400 Reg = PR;
6401 }
6402 if (Reg) {
6404 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6405 }
6406 }
6407
6408 if (!Op && N.getNode()) {
6409 // Check if frame index is available.
6410 SDValue LCandidate = peekThroughBitcasts(N);
6411 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6412 if (FrameIndexSDNode *FINode =
6413 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6414 Op = MachineOperand::CreateFI(FINode->getIndex());
6415 }
6416
6417 if (!Op) {
6418 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6419 auto splitMultiRegDbgValue =
6420 [&](ArrayRef<std::pair<Register, TypeSize>> SplitRegs) -> bool {
6421 unsigned Offset = 0;
6422 for (const auto &[Reg, RegSizeInBits] : SplitRegs) {
6423 // FIXME: Scalable sizes are not supported in fragment expressions.
6424 if (RegSizeInBits.isScalable())
6425 return false;
6426
6427 // If the expression is already a fragment, the current register
6428 // offset+size might extend beyond the fragment. In this case, only
6429 // the register bits that are inside the fragment are relevant.
6430 int RegFragmentSizeInBits = RegSizeInBits.getFixedValue();
6431 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6432 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6433 // The register is entirely outside the expression fragment,
6434 // so is irrelevant for debug info.
6435 if (Offset >= ExprFragmentSizeInBits)
6436 break;
6437 // The register is partially outside the expression fragment, only
6438 // the low bits within the fragment are relevant for debug info.
6439 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6440 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6441 }
6442 }
6443
6444 auto FragmentExpr = DIExpression::createFragmentExpression(
6445 Expr, Offset, RegFragmentSizeInBits);
6446 Offset += RegSizeInBits.getFixedValue();
6447 // If a valid fragment expression cannot be created, the variable's
6448 // correct value cannot be determined and so it is set as poison.
6449 if (!FragmentExpr) {
6450 SDDbgValue *SDV = DAG.getConstantDbgValue(
6451 Variable, Expr, PoisonValue::get(V->getType()), DL, SDNodeOrder);
6452 DAG.AddDbgValue(SDV, false);
6453 continue;
6454 }
6455 MachineInstr *NewMI = MakeVRegDbgValue(
6456 Reg, *FragmentExpr, Kind != FuncArgumentDbgValueKind::Value);
6457 FuncInfo.ArgDbgValues.push_back(NewMI);
6458 }
6459
6460 return true;
6461 };
6462
6463 // Check if ValueMap has reg number.
6465 VMI = FuncInfo.ValueMap.find(V);
6466 if (VMI != FuncInfo.ValueMap.end()) {
6467 const auto &TLI = DAG.getTargetLoweringInfo();
6468 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6469 V->getType(), std::nullopt);
6470 if (RFV.occupiesMultipleRegs())
6471 return splitMultiRegDbgValue(RFV.getRegsAndSizes());
6472
6473 Op = MachineOperand::CreateReg(VMI->second, false);
6474 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6475 } else if (ArgRegsAndSizes.size() > 1) {
6476 // This was split due to the calling convention, and no virtual register
6477 // mapping exists for the value.
6478 return splitMultiRegDbgValue(ArgRegsAndSizes);
6479 }
6480 }
6481
6482 if (!Op)
6483 return false;
6484
6485 assert(Variable->isValidLocationForIntrinsic(DL) &&
6486 "Expected inlined-at fields to agree");
6487 MachineInstr *NewMI = nullptr;
6488
6489 if (Op->isReg())
6490 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6491 else
6492 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6493 Variable, Expr);
6494
6495 // Otherwise, use ArgDbgValues.
6496 FuncInfo.ArgDbgValues.push_back(NewMI);
6497 return true;
6498}
6499
6500/// Return the appropriate SDDbgValue based on N.
6501SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6502 DILocalVariable *Variable,
6503 DIExpression *Expr,
6504 const DebugLoc &dl,
6505 unsigned DbgSDNodeOrder) {
6506 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6507 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6508 // stack slot locations.
6509 //
6510 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6511 // debug values here after optimization:
6512 //
6513 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
6514 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6515 //
6516 // Both describe the direct values of their associated variables.
6517 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6518 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6519 }
6520 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6521 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6522}
6523
6524static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6525 switch (Intrinsic) {
6526 case Intrinsic::smul_fix:
6527 return ISD::SMULFIX;
6528 case Intrinsic::umul_fix:
6529 return ISD::UMULFIX;
6530 case Intrinsic::smul_fix_sat:
6531 return ISD::SMULFIXSAT;
6532 case Intrinsic::umul_fix_sat:
6533 return ISD::UMULFIXSAT;
6534 case Intrinsic::sdiv_fix:
6535 return ISD::SDIVFIX;
6536 case Intrinsic::udiv_fix:
6537 return ISD::UDIVFIX;
6538 case Intrinsic::sdiv_fix_sat:
6539 return ISD::SDIVFIXSAT;
6540 case Intrinsic::udiv_fix_sat:
6541 return ISD::UDIVFIXSAT;
6542 default:
6543 llvm_unreachable("Unhandled fixed point intrinsic");
6544 }
6545}
6546
6547/// Given a @llvm.call.preallocated.setup, return the corresponding
6548/// preallocated call.
6549static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6550 assert(cast<CallBase>(PreallocatedSetup)
6552 ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6553 "expected call_preallocated_setup Value");
6554 for (const auto *U : PreallocatedSetup->users()) {
6555 auto *UseCall = cast<CallBase>(U);
6556 const Function *Fn = UseCall->getCalledFunction();
6557 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6558 return UseCall;
6559 }
6560 }
6561 llvm_unreachable("expected corresponding call to preallocated setup/arg");
6562}
6563
6564/// If DI is a debug value with an EntryValue expression, lower it using the
6565/// corresponding physical register of the associated Argument value
6566/// (guaranteed to exist by the verifier).
6567bool SelectionDAGBuilder::visitEntryValueDbgValue(
6569 DIExpression *Expr, DebugLoc DbgLoc) {
6570 if (!Expr->isEntryValue() || !hasSingleElement(Values))
6571 return false;
6572
6573 // These properties are guaranteed by the verifier.
6574 const Argument *Arg = cast<Argument>(Values[0]);
6575 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6576
6577 auto ArgIt = FuncInfo.ValueMap.find(Arg);
6578 if (ArgIt == FuncInfo.ValueMap.end()) {
6579 LLVM_DEBUG(
6580 dbgs() << "Dropping dbg.value: expression is entry_value but "
6581 "couldn't find an associated register for the Argument\n");
6582 return true;
6583 }
6584 Register ArgVReg = ArgIt->getSecond();
6585
6586 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6587 if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6588 SDDbgValue *SDV = DAG.getVRegDbgValue(
6589 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6590 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6591 return true;
6592 }
6593 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6594 "couldn't find a physical register\n");
6595 return true;
6596}
6597
6598/// Lower the call to the specified intrinsic function.
6599void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6600 unsigned Intrinsic) {
6601 SDLoc sdl = getCurSDLoc();
6602 switch (Intrinsic) {
6603 case Intrinsic::experimental_convergence_anchor:
6604 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6605 break;
6606 case Intrinsic::experimental_convergence_entry:
6607 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6608 break;
6609 case Intrinsic::experimental_convergence_loop: {
6610 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6611 auto *Token = Bundle->Inputs[0].get();
6612 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6613 getValue(Token)));
6614 break;
6615 }
6616 }
6617}
6618
6619void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6620 unsigned IntrinsicID) {
6621 // For now, we're only lowering an 'add' histogram.
6622 // We can add others later, e.g. saturating adds, min/max.
6623 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6624 "Tried to lower unsupported histogram type");
6625 SDLoc sdl = getCurSDLoc();
6626 Value *Ptr = I.getOperand(0);
6627 SDValue Inc = getValue(I.getOperand(1));
6628 SDValue Mask = getValue(I.getOperand(2));
6629
6630 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6631 DataLayout TargetDL = DAG.getDataLayout();
6632 EVT VT = Inc.getValueType();
6633 Align Alignment = DAG.getEVTAlign(VT);
6634
6635 const MDNode *Ranges = getRangeMetadata(I);
6636
6637 SDValue Root = DAG.getRoot();
6638 SDValue Base;
6639 SDValue Index;
6640 SDValue Scale;
6641 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
6642 I.getParent(), VT.getScalarStoreSize());
6643
6644 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6645
6646 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6647 MachinePointerInfo(AS),
6649 MemoryLocation::UnknownSize, Alignment,
6650 MMOMetadata(I.getAAMetadata(), Ranges));
6651
6652 if (!UniformBase) {
6653 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6654 Index = getValue(Ptr);
6655 Scale =
6656 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6657 }
6658
6659 EVT IdxVT = Index.getValueType();
6660
6661 // Avoid using e.g. i32 as index type when the increment must be performed
6662 // on i64's.
6663 bool MustExtendIndex = VT.getScalarSizeInBits() > IdxVT.getScalarSizeInBits();
6664 EVT EltTy = MustExtendIndex ? VT : IdxVT.getVectorElementType();
6665 if (MustExtendIndex || TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6666 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
6667 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6668 }
6669
6670 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6671
6672 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6673 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6674 Ops, MMO, ISD::SIGNED_SCALED);
6675
6676 setValue(&I, Histogram);
6677 DAG.setRoot(Histogram);
6678}
6679
6680void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6681 unsigned Intrinsic) {
6682 assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6683 "Tried lowering invalid vector extract last");
6684 SDLoc sdl = getCurSDLoc();
6685 const DataLayout &Layout = DAG.getDataLayout();
6686 SDValue Data = getValue(I.getOperand(0));
6687 SDValue Mask = getValue(I.getOperand(1));
6688
6689 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6690 EVT ResVT = TLI.getValueType(Layout, I.getType());
6691
6692 EVT ExtVT = TLI.getVectorIdxTy(Layout);
6693 SDValue Idx = DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, sdl, ExtVT, Mask);
6694 SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl, ResVT, Data, Idx);
6695
6696 Value *Default = I.getOperand(2);
6698 SDValue PassThru = getValue(Default);
6699 EVT BoolVT = Mask.getValueType().getScalarType();
6700 SDValue AnyActive = DAG.getNode(ISD::VECREDUCE_OR, sdl, BoolVT, Mask);
6701 Result = DAG.getSelect(sdl, ResVT, AnyActive, Result, PassThru);
6702 }
6703
6704 setValue(&I, Result);
6705}
6706
6707/// Lower the call to the specified intrinsic function.
6708void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6709 unsigned Intrinsic) {
6710 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6711 SDLoc sdl = getCurSDLoc();
6712 DebugLoc dl = getCurDebugLoc();
6713 SDValue Res;
6714
6715 SDNodeFlags Flags;
6716 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6717 Flags.copyFMF(*FPOp);
6718
6719 switch (Intrinsic) {
6720 default:
6721 // By default, turn this into a target intrinsic node.
6722 visitTargetIntrinsic(I, Intrinsic);
6723 return;
6724 case Intrinsic::vscale: {
6725 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6726 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6727 return;
6728 }
6729 case Intrinsic::vastart: visitVAStart(I); return;
6730 case Intrinsic::vaend: visitVAEnd(I); return;
6731 case Intrinsic::vacopy: visitVACopy(I); return;
6732 case Intrinsic::returnaddress:
6733 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6734 TLI.getValueType(DAG.getDataLayout(), I.getType()),
6735 getValue(I.getArgOperand(0))));
6736 return;
6737 case Intrinsic::addressofreturnaddress:
6738 setValue(&I,
6739 DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6740 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6741 return;
6742 case Intrinsic::sponentry:
6743 setValue(&I,
6744 DAG.getNode(ISD::SPONENTRY, sdl,
6745 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6746 return;
6747 case Intrinsic::frameaddress:
6748 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6749 TLI.getFrameIndexTy(DAG.getDataLayout()),
6750 getValue(I.getArgOperand(0))));
6751 return;
6752 case Intrinsic::read_volatile_register:
6753 case Intrinsic::read_register: {
6754 Value *Reg = I.getArgOperand(0);
6755 SDValue Chain = getRoot();
6757 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6758 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6759 Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6760 DAG.getVTList(VT, MVT::Other), Chain, RegName);
6761 setValue(&I, Res);
6762 DAG.setRoot(Res.getValue(1));
6763 return;
6764 }
6765 case Intrinsic::write_register: {
6766 Value *Reg = I.getArgOperand(0);
6767 Value *RegValue = I.getArgOperand(1);
6768 SDValue Chain = getRoot();
6770 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6771 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6772 RegName, getValue(RegValue)));
6773 return;
6774 }
6775 case Intrinsic::write_volatile_register: {
6776 Value *Reg = I.getArgOperand(0);
6777 Value *RegValue = I.getArgOperand(1);
6778 SDValue Chain = getRoot();
6779 const MDNode *MD = cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata());
6780 SDValue RegName = DAG.getMDNode(MD);
6781 EVT VT = TLI.getValueType(DAG.getDataLayout(), RegValue->getType());
6782 SDValue WriteChain = DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other,
6783 Chain, RegName, getValue(RegValue));
6784 // FAKE_USE of the physical register marks it live after the WRITE_REGISTER,
6785 // preventing the backend from dead-eliminating the write. This is
6786 // preferred over READ_REGISTER, which would emit extra register copies
6787 // (e.g. fmov xN, dN for FP/SIMD registers).
6788 const MDString *RegStr = cast<MDString>(MD->getOperand(0));
6789 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
6790 const MachineFunction &MF = DAG.getMachineFunction();
6791 Register PhysReg =
6792 TLI.getRegisterByName(RegStr->getString().data(), Ty, MF);
6793 if (PhysReg.isValid()) {
6794 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6795 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysReg);
6796 MVT RegVT = *TRI->legalclasstypes_begin(*RC);
6797 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other,
6798 {WriteChain, DAG.getRegister(PhysReg, RegVT)}));
6799 } else {
6800 DAG.setRoot(WriteChain);
6801 }
6802 return;
6803 }
6804 case Intrinsic::memcpy:
6805 case Intrinsic::memcpy_inline: {
6806 const auto &MCI = cast<MemCpyInst>(I);
6807 SDValue Dst = getValue(I.getArgOperand(0));
6808 SDValue Src = getValue(I.getArgOperand(1));
6809 SDValue Size = getValue(I.getArgOperand(2));
6810 assert((!MCI.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6811 "memcpy_inline needs constant size");
6812 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6813 Align DstAlign = MCI.getDestAlign().valueOrOne();
6814 Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6815 bool isVol = MCI.isVolatile();
6816 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6817 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, DstAlign, SrcAlign,
6818 isVol, MCI.isForceInlined(), &I, std::nullopt,
6819 MachinePointerInfo(I.getArgOperand(0)),
6820 MachinePointerInfo(I.getArgOperand(1)),
6821 I.getAAMetadata(), BatchAA);
6822 updateDAGForMaybeTailCall(MC);
6823 return;
6824 }
6825 case Intrinsic::memset:
6826 case Intrinsic::memset_inline: {
6827 const auto &MSII = cast<MemSetInst>(I);
6828 SDValue Dst = getValue(I.getArgOperand(0));
6829 SDValue Value = getValue(I.getArgOperand(1));
6830 SDValue Size = getValue(I.getArgOperand(2));
6831 assert((!MSII.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6832 "memset_inline needs constant size");
6833 // @llvm.memset defines 0 and 1 to both mean no alignment.
6834 Align DstAlign = MSII.getDestAlign().valueOrOne();
6835 bool isVol = MSII.isVolatile();
6836 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6837 SDValue MC = DAG.getMemset(
6838 Root, sdl, Dst, Value, Size, DstAlign, isVol, MSII.isForceInlined(),
6839 &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6840 updateDAGForMaybeTailCall(MC);
6841 return;
6842 }
6843 case Intrinsic::memmove: {
6844 const auto &MMI = cast<MemMoveInst>(I);
6845 SDValue Op1 = getValue(I.getArgOperand(0));
6846 SDValue Op2 = getValue(I.getArgOperand(1));
6847 SDValue Op3 = getValue(I.getArgOperand(2));
6848 // @llvm.memmove defines 0 and 1 to both mean no alignment.
6849 Align DstAlign = MMI.getDestAlign().valueOrOne();
6850 Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6851 bool isVol = MMI.isVolatile();
6852 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6853 SDValue MM = DAG.getMemmove(
6854 Root, sdl, Op1, Op2, Op3, DstAlign, SrcAlign, isVol, &I,
6855 /* OverrideTailCall */ std::nullopt,
6856 MachinePointerInfo(I.getArgOperand(0)),
6857 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), BatchAA);
6858 updateDAGForMaybeTailCall(MM);
6859 return;
6860 }
6861 case Intrinsic::memcpy_element_unordered_atomic: {
6862 auto &MI = cast<AnyMemCpyInst>(I);
6863 SDValue Dst = getValue(MI.getRawDest());
6864 SDValue Src = getValue(MI.getRawSource());
6865 SDValue Length = getValue(MI.getLength());
6866
6867 Type *LengthTy = MI.getLength()->getType();
6868 unsigned ElemSz = MI.getElementSizeInBytes();
6869 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6870 SDValue MC =
6871 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6872 isTC, MachinePointerInfo(MI.getRawDest()),
6873 MachinePointerInfo(MI.getRawSource()));
6874 updateDAGForMaybeTailCall(MC);
6875 return;
6876 }
6877 case Intrinsic::memmove_element_unordered_atomic: {
6878 auto &MI = cast<AnyMemMoveInst>(I);
6879 SDValue Dst = getValue(MI.getRawDest());
6880 SDValue Src = getValue(MI.getRawSource());
6881 SDValue Length = getValue(MI.getLength());
6882
6883 Type *LengthTy = MI.getLength()->getType();
6884 unsigned ElemSz = MI.getElementSizeInBytes();
6885 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6886 SDValue MC =
6887 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6888 isTC, MachinePointerInfo(MI.getRawDest()),
6889 MachinePointerInfo(MI.getRawSource()));
6890 updateDAGForMaybeTailCall(MC);
6891 return;
6892 }
6893 case Intrinsic::memset_element_unordered_atomic: {
6894 auto &MI = cast<AnyMemSetInst>(I);
6895 SDValue Dst = getValue(MI.getRawDest());
6896 SDValue Val = getValue(MI.getValue());
6897 SDValue Length = getValue(MI.getLength());
6898
6899 Type *LengthTy = MI.getLength()->getType();
6900 unsigned ElemSz = MI.getElementSizeInBytes();
6901 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6902 SDValue MC =
6903 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6904 isTC, MachinePointerInfo(MI.getRawDest()));
6905 updateDAGForMaybeTailCall(MC);
6906 return;
6907 }
6908 case Intrinsic::call_preallocated_setup: {
6909 const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6910 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6911 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6912 getRoot(), SrcValue);
6913 setValue(&I, Res);
6914 DAG.setRoot(Res);
6915 return;
6916 }
6917 case Intrinsic::call_preallocated_arg: {
6918 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6919 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6920 SDValue Ops[3];
6921 Ops[0] = getRoot();
6922 Ops[1] = SrcValue;
6923 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6924 MVT::i32); // arg index
6925 SDValue Res = DAG.getNode(
6927 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6928 setValue(&I, Res);
6929 DAG.setRoot(Res.getValue(1));
6930 return;
6931 }
6932
6933 case Intrinsic::eh_typeid_for: {
6934 // Find the type id for the given typeinfo.
6935 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6936 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6937 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6938 setValue(&I, Res);
6939 return;
6940 }
6941
6942 case Intrinsic::eh_return_i32:
6943 case Intrinsic::eh_return_i64:
6944 DAG.getMachineFunction().setCallsEHReturn(true);
6945 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6946 MVT::Other,
6948 getValue(I.getArgOperand(0)),
6949 getValue(I.getArgOperand(1))));
6950 return;
6951 case Intrinsic::eh_unwind_init:
6952 DAG.getMachineFunction().setCallsUnwindInit(true);
6953 return;
6954 case Intrinsic::eh_dwarf_cfa:
6955 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6956 TLI.getPointerTy(DAG.getDataLayout()),
6957 getValue(I.getArgOperand(0))));
6958 return;
6959 case Intrinsic::eh_sjlj_callsite: {
6960 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6961 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6962
6963 FuncInfo.setCurrentCallSite(CI->getZExtValue());
6964 return;
6965 }
6966 case Intrinsic::eh_sjlj_functioncontext: {
6967 // Get and store the index of the function context.
6968 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6969 AllocaInst *FnCtx =
6970 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6971 int FI = FuncInfo.StaticAllocaMap[FnCtx];
6973 return;
6974 }
6975 case Intrinsic::eh_sjlj_setjmp: {
6976 SDValue Ops[2];
6977 Ops[0] = getRoot();
6978 Ops[1] = getValue(I.getArgOperand(0));
6979 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6980 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6981 setValue(&I, Op.getValue(0));
6982 DAG.setRoot(Op.getValue(1));
6983 return;
6984 }
6985 case Intrinsic::eh_sjlj_longjmp:
6986 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6987 getRoot(), getValue(I.getArgOperand(0))));
6988 return;
6989 case Intrinsic::eh_sjlj_setup_dispatch:
6990 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6991 getRoot()));
6992 return;
6993 case Intrinsic::masked_gather:
6994 visitMaskedGather(I);
6995 return;
6996 case Intrinsic::masked_load:
6997 visitMaskedLoad(I);
6998 return;
6999 case Intrinsic::masked_scatter:
7000 visitMaskedScatter(I);
7001 return;
7002 case Intrinsic::masked_store:
7003 visitMaskedStore(I);
7004 return;
7005 case Intrinsic::masked_expandload:
7006 visitMaskedLoad(I, true /* IsExpanding */);
7007 return;
7008 case Intrinsic::masked_compressstore:
7009 visitMaskedStore(I, true /* IsCompressing */);
7010 return;
7011 case Intrinsic::powi:
7012 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
7013 getValue(I.getArgOperand(1)), DAG));
7014 return;
7015 case Intrinsic::log:
7016 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7017 return;
7018 case Intrinsic::log2:
7019 setValue(&I,
7020 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7021 return;
7022 case Intrinsic::log10:
7023 setValue(&I,
7024 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7025 return;
7026 case Intrinsic::exp:
7027 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7028 return;
7029 case Intrinsic::exp2:
7030 setValue(&I,
7031 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7032 return;
7033 case Intrinsic::pow:
7034 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
7035 getValue(I.getArgOperand(1)), DAG, TLI, Flags));
7036 return;
7037 case Intrinsic::sqrt:
7038 case Intrinsic::fabs:
7039 case Intrinsic::sin:
7040 case Intrinsic::cos:
7041 case Intrinsic::tan:
7042 case Intrinsic::asin:
7043 case Intrinsic::acos:
7044 case Intrinsic::atan:
7045 case Intrinsic::sinh:
7046 case Intrinsic::cosh:
7047 case Intrinsic::tanh:
7048 case Intrinsic::exp10:
7049 case Intrinsic::floor:
7050 case Intrinsic::ceil:
7051 case Intrinsic::trunc:
7052 case Intrinsic::rint:
7053 case Intrinsic::nearbyint:
7054 case Intrinsic::round:
7055 case Intrinsic::roundeven:
7056 case Intrinsic::canonicalize: {
7057 unsigned Opcode;
7058 // clang-format off
7059 switch (Intrinsic) {
7060 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7061 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
7062 case Intrinsic::fabs: Opcode = ISD::FABS; break;
7063 case Intrinsic::sin: Opcode = ISD::FSIN; break;
7064 case Intrinsic::cos: Opcode = ISD::FCOS; break;
7065 case Intrinsic::tan: Opcode = ISD::FTAN; break;
7066 case Intrinsic::asin: Opcode = ISD::FASIN; break;
7067 case Intrinsic::acos: Opcode = ISD::FACOS; break;
7068 case Intrinsic::atan: Opcode = ISD::FATAN; break;
7069 case Intrinsic::sinh: Opcode = ISD::FSINH; break;
7070 case Intrinsic::cosh: Opcode = ISD::FCOSH; break;
7071 case Intrinsic::tanh: Opcode = ISD::FTANH; break;
7072 case Intrinsic::exp10: Opcode = ISD::FEXP10; break;
7073 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
7074 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
7075 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
7076 case Intrinsic::rint: Opcode = ISD::FRINT; break;
7077 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
7078 case Intrinsic::round: Opcode = ISD::FROUND; break;
7079 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
7080 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
7081 }
7082 // clang-format on
7083
7084 setValue(&I, DAG.getNode(Opcode, sdl,
7085 getValue(I.getArgOperand(0)).getValueType(),
7086 getValue(I.getArgOperand(0)), Flags));
7087 return;
7088 }
7089 case Intrinsic::atan2:
7090 setValue(&I, DAG.getNode(ISD::FATAN2, sdl,
7091 getValue(I.getArgOperand(0)).getValueType(),
7092 getValue(I.getArgOperand(0)),
7093 getValue(I.getArgOperand(1)), Flags));
7094 return;
7095 case Intrinsic::lround:
7096 case Intrinsic::llround:
7097 case Intrinsic::lrint:
7098 case Intrinsic::llrint: {
7099 unsigned Opcode;
7100 // clang-format off
7101 switch (Intrinsic) {
7102 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7103 case Intrinsic::lround: Opcode = ISD::LROUND; break;
7104 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
7105 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
7106 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
7107 }
7108 // clang-format on
7109
7110 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7111 setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
7112 getValue(I.getArgOperand(0))));
7113 return;
7114 }
7115 case Intrinsic::minnum:
7116 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
7117 getValue(I.getArgOperand(0)).getValueType(),
7118 getValue(I.getArgOperand(0)),
7119 getValue(I.getArgOperand(1)), Flags));
7120 return;
7121 case Intrinsic::maxnum:
7122 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
7123 getValue(I.getArgOperand(0)).getValueType(),
7124 getValue(I.getArgOperand(0)),
7125 getValue(I.getArgOperand(1)), Flags));
7126 return;
7127 case Intrinsic::minimum:
7128 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
7129 getValue(I.getArgOperand(0)).getValueType(),
7130 getValue(I.getArgOperand(0)),
7131 getValue(I.getArgOperand(1)), Flags));
7132 return;
7133 case Intrinsic::maximum:
7134 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
7135 getValue(I.getArgOperand(0)).getValueType(),
7136 getValue(I.getArgOperand(0)),
7137 getValue(I.getArgOperand(1)), Flags));
7138 return;
7139 case Intrinsic::minimumnum:
7140 setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
7141 getValue(I.getArgOperand(0)).getValueType(),
7142 getValue(I.getArgOperand(0)),
7143 getValue(I.getArgOperand(1)), Flags));
7144 return;
7145 case Intrinsic::maximumnum:
7146 setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
7147 getValue(I.getArgOperand(0)).getValueType(),
7148 getValue(I.getArgOperand(0)),
7149 getValue(I.getArgOperand(1)), Flags));
7150 return;
7151 case Intrinsic::copysign:
7152 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
7153 getValue(I.getArgOperand(0)).getValueType(),
7154 getValue(I.getArgOperand(0)),
7155 getValue(I.getArgOperand(1)), Flags));
7156 return;
7157 case Intrinsic::ldexp:
7158 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
7159 getValue(I.getArgOperand(0)).getValueType(),
7160 getValue(I.getArgOperand(0)),
7161 getValue(I.getArgOperand(1)), Flags));
7162 return;
7163 case Intrinsic::modf:
7164 case Intrinsic::sincos:
7165 case Intrinsic::sincospi:
7166 case Intrinsic::frexp: {
7167 unsigned Opcode;
7168 switch (Intrinsic) {
7169 default:
7170 llvm_unreachable("unexpected intrinsic");
7171 case Intrinsic::sincos:
7172 Opcode = ISD::FSINCOS;
7173 break;
7174 case Intrinsic::sincospi:
7175 Opcode = ISD::FSINCOSPI;
7176 break;
7177 case Intrinsic::modf:
7178 Opcode = ISD::FMODF;
7179 break;
7180 case Intrinsic::frexp:
7181 Opcode = ISD::FFREXP;
7182 break;
7183 }
7184 SmallVector<EVT, 2> ValueVTs;
7185 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
7186 SDVTList VTs = DAG.getVTList(ValueVTs);
7187 setValue(
7188 &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags));
7189 return;
7190 }
7191 case Intrinsic::arithmetic_fence: {
7192 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
7193 getValue(I.getArgOperand(0)).getValueType(),
7194 getValue(I.getArgOperand(0)), Flags));
7195 return;
7196 }
7197 case Intrinsic::fma:
7198 setValue(&I, DAG.getNode(
7199 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
7200 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
7201 getValue(I.getArgOperand(2)), Flags));
7202 return;
7203#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
7204 case Intrinsic::INTRINSIC:
7205#include "llvm/IR/ConstrainedOps.def"
7206 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
7207 return;
7208#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7209#include "llvm/IR/VPIntrinsics.def"
7210 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
7211 return;
7212 case Intrinsic::fptrunc_round: {
7213 // Get the last argument, the metadata and convert it to an integer in the
7214 // call
7215 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7216 std::optional<RoundingMode> RoundMode =
7217 convertStrToRoundingMode(cast<MDString>(MD)->getString());
7218
7219 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7220
7221 // Propagate fast-math-flags from IR to node(s).
7222 SDNodeFlags Flags;
7223 Flags.copyFMF(*cast<FPMathOperator>(&I));
7224 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7225
7227 Result = DAG.getNode(
7228 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
7229 DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
7230 setValue(&I, Result);
7231
7232 return;
7233 }
7234 case Intrinsic::fmuladd: {
7235 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7236 if (TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7237 setValue(&I, DAG.getNode(ISD::FMA, sdl,
7238 getValue(I.getArgOperand(0)).getValueType(),
7239 getValue(I.getArgOperand(0)),
7240 getValue(I.getArgOperand(1)),
7241 getValue(I.getArgOperand(2)), Flags));
7242 } else if (TLI.isOperationLegalOrCustom(ISD::FMULADD, VT)) {
7243 // TODO: Support splitting the vector.
7244 setValue(&I, DAG.getNode(ISD::FMULADD, sdl,
7245 getValue(I.getArgOperand(0)).getValueType(),
7246 getValue(I.getArgOperand(0)),
7247 getValue(I.getArgOperand(1)),
7248 getValue(I.getArgOperand(2)), Flags));
7249 } else {
7250 // TODO: Intrinsic calls should have fast-math-flags.
7251 SDValue Mul = DAG.getNode(
7252 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
7253 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
7254 SDValue Add = DAG.getNode(ISD::FADD, sdl,
7255 getValue(I.getArgOperand(0)).getValueType(),
7256 Mul, getValue(I.getArgOperand(2)), Flags);
7257 setValue(&I, Add);
7258 }
7259 return;
7260 }
7261 case Intrinsic::fptosi_sat: {
7262 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7263 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7264 getValue(I.getArgOperand(0)),
7265 DAG.getValueType(VT.getScalarType())));
7266 return;
7267 }
7268 case Intrinsic::fptoui_sat: {
7269 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7270 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7271 getValue(I.getArgOperand(0)),
7272 DAG.getValueType(VT.getScalarType())));
7273 return;
7274 }
7275 case Intrinsic::convert_from_arbitrary_fp: {
7276 // Extract format metadata and convert to semantics enum.
7277 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7278 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7279 StringRef FormatStr = cast<MDString>(MD)->getString();
7280 const fltSemantics *SrcSem =
7282 if (!SrcSem) {
7283 DAG.getContext()->emitError(
7284 "convert_from_arbitrary_fp: not implemented format '" + FormatStr +
7285 "'");
7286 setValue(&I, DAG.getPOISON(DstVT));
7287 return;
7288 }
7290
7291 SDValue IntVal = getValue(I.getArgOperand(0));
7292
7293 // Emit ISD::CONVERT_FROM_ARBITRARY_FP node.
7294 SDValue SemConst =
7295 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7296 setValue(&I, DAG.getNode(ISD::CONVERT_FROM_ARBITRARY_FP, sdl, DstVT, IntVal,
7297 SemConst));
7298 return;
7299 }
7300 case Intrinsic::convert_to_arbitrary_fp: {
7301 // Extract format metadata and convert to semantics enum.
7302 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7303 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7304 StringRef FormatStr = cast<MDString>(MD)->getString();
7305 const fltSemantics *DstSem =
7307 if (!DstSem) {
7308 DAG.getContext()->emitError(
7309 "convert_to_arbitrary_fp: not implemented format '" + FormatStr +
7310 "'");
7311 setValue(&I, DAG.getPOISON(DstVT));
7312 return;
7313 }
7315
7316 Metadata *RoundMD =
7317 cast<MetadataAsValue>(I.getArgOperand(2))->getMetadata();
7318 StringRef RoundStr = cast<MDString>(RoundMD)->getString();
7319 std::optional<RoundingMode> RoundMode = convertStrToRoundingMode(RoundStr);
7320 assert(RoundMode && *RoundMode != RoundingMode::Dynamic &&
7321 "Dynamic rounding mode should have been rejected by the verifier");
7322
7323 uint64_t Saturate =
7324 cast<ConstantInt>(I.getArgOperand(3))->getZExtValue() ? 1 : 0;
7325
7326 SDValue FloatVal = getValue(I.getArgOperand(0));
7327
7328 SDValue SemConst =
7329 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7330 SDValue RoundConst =
7331 DAG.getTargetConstant(static_cast<int>(*RoundMode), sdl, MVT::i32);
7332 SDValue SatConst = DAG.getTargetConstant(Saturate, sdl, MVT::i32);
7333 setValue(&I, DAG.getNode(ISD::CONVERT_TO_ARBITRARY_FP, sdl, DstVT, FloatVal,
7334 SemConst, RoundConst, SatConst));
7335 return;
7336 }
7337 case Intrinsic::set_rounding:
7338 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7339 {getRoot(), getValue(I.getArgOperand(0))});
7340 setValue(&I, Res);
7341 DAG.setRoot(Res.getValue(0));
7342 return;
7343 case Intrinsic::is_fpclass: {
7344 const DataLayout DLayout = DAG.getDataLayout();
7345 EVT DestVT = TLI.getValueType(DLayout, I.getType());
7346 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7347 FPClassTest Test = static_cast<FPClassTest>(
7348 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7349 MachineFunction &MF = DAG.getMachineFunction();
7350 const Function &F = MF.getFunction();
7351 SDValue Op = getValue(I.getArgOperand(0));
7352 SDNodeFlags Flags;
7353 Flags.setNoFPExcept(
7354 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7355 // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7356 // expansion can use illegal types. Making expansion early allows
7357 // legalizing these types prior to selection.
7358 if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7359 !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) {
7360 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7361 setValue(&I, Result);
7362 return;
7363 }
7364
7365 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7366 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7367 setValue(&I, V);
7368 return;
7369 }
7370 case Intrinsic::get_fpenv: {
7371 const DataLayout DLayout = DAG.getDataLayout();
7372 EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7373 Align TempAlign = DAG.getEVTAlign(EnvVT);
7374 SDValue Chain = getRoot();
7375 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7376 // and temporary storage in stack.
7377 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7378 Res = DAG.getNode(
7379 ISD::GET_FPENV, sdl,
7380 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7381 MVT::Other),
7382 Chain);
7383 } else {
7384 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7385 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7386 auto MPI =
7387 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7388 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7390 TempAlign);
7391 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7392 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7393 }
7394 setValue(&I, Res);
7395 DAG.setRoot(Res.getValue(1));
7396 return;
7397 }
7398 case Intrinsic::set_fpenv: {
7399 const DataLayout DLayout = DAG.getDataLayout();
7400 SDValue Env = getValue(I.getArgOperand(0));
7401 EVT EnvVT = Env.getValueType();
7402 Align TempAlign = DAG.getEVTAlign(EnvVT);
7403 SDValue Chain = getRoot();
7404 // If SET_FPENV is custom or legal, use it. Otherwise use loading
7405 // environment from memory.
7406 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7407 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7408 } else {
7409 // Allocate space in stack, copy environment bits into it and use this
7410 // memory in SET_FPENV_MEM.
7411 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7412 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7413 auto MPI =
7414 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7415 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7417 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7419 TempAlign);
7420 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7421 }
7422 DAG.setRoot(Chain);
7423 return;
7424 }
7425 case Intrinsic::reset_fpenv:
7426 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7427 return;
7428 case Intrinsic::get_fpmode:
7429 Res = DAG.getNode(
7430 ISD::GET_FPMODE, sdl,
7431 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7432 MVT::Other),
7433 DAG.getRoot());
7434 setValue(&I, Res);
7435 DAG.setRoot(Res.getValue(1));
7436 return;
7437 case Intrinsic::set_fpmode:
7438 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7439 getValue(I.getArgOperand(0)));
7440 DAG.setRoot(Res);
7441 return;
7442 case Intrinsic::reset_fpmode: {
7443 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7444 DAG.setRoot(Res);
7445 return;
7446 }
7447 case Intrinsic::pcmarker: {
7448 SDValue Tmp = getValue(I.getArgOperand(0));
7449 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7450 return;
7451 }
7452 case Intrinsic::readcyclecounter: {
7453 SDValue Op = getRoot();
7454 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7455 DAG.getVTList(MVT::i64, MVT::Other), Op);
7456 setValue(&I, Res);
7457 DAG.setRoot(Res.getValue(1));
7458 return;
7459 }
7460 case Intrinsic::readsteadycounter: {
7461 SDValue Op = getRoot();
7462 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7463 DAG.getVTList(MVT::i64, MVT::Other), Op);
7464 setValue(&I, Res);
7465 DAG.setRoot(Res.getValue(1));
7466 return;
7467 }
7468 case Intrinsic::bitreverse:
7469 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7470 getValue(I.getArgOperand(0)).getValueType(),
7471 getValue(I.getArgOperand(0))));
7472 return;
7473 case Intrinsic::bswap:
7474 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7475 getValue(I.getArgOperand(0)).getValueType(),
7476 getValue(I.getArgOperand(0))));
7477 return;
7478 case Intrinsic::cttz: {
7479 SDValue Arg = getValue(I.getArgOperand(0));
7480 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7481 EVT Ty = Arg.getValueType();
7482 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_POISON,
7483 sdl, Ty, Arg));
7484 return;
7485 }
7486 case Intrinsic::ctlz: {
7487 SDValue Arg = getValue(I.getArgOperand(0));
7488 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7489 EVT Ty = Arg.getValueType();
7490 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_POISON,
7491 sdl, Ty, Arg));
7492 return;
7493 }
7494 case Intrinsic::ctpop: {
7495 SDValue Arg = getValue(I.getArgOperand(0));
7496 EVT Ty = Arg.getValueType();
7497 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7498 return;
7499 }
7500 case Intrinsic::fshl:
7501 case Intrinsic::fshr: {
7502 bool IsFSHL = Intrinsic == Intrinsic::fshl;
7503 SDValue X = getValue(I.getArgOperand(0));
7504 SDValue Y = getValue(I.getArgOperand(1));
7505 SDValue Z = getValue(I.getArgOperand(2));
7506 EVT VT = X.getValueType();
7507
7508 if (X == Y) {
7509 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7510 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7511 } else {
7512 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7513 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7514 }
7515 return;
7516 }
7517 case Intrinsic::clmul: {
7518 SDValue X = getValue(I.getArgOperand(0));
7519 SDValue Y = getValue(I.getArgOperand(1));
7520 setValue(&I, DAG.getNode(ISD::CLMUL, sdl, X.getValueType(), X, Y));
7521 return;
7522 }
7523 case Intrinsic::pext: {
7524 SDValue X = getValue(I.getArgOperand(0));
7525 SDValue Y = getValue(I.getArgOperand(1));
7526 setValue(&I, DAG.getNode(ISD::PEXT, sdl, X.getValueType(), X, Y));
7527 return;
7528 }
7529 case Intrinsic::pdep: {
7530 SDValue X = getValue(I.getArgOperand(0));
7531 SDValue Y = getValue(I.getArgOperand(1));
7532 setValue(&I, DAG.getNode(ISD::PDEP, sdl, X.getValueType(), X, Y));
7533 return;
7534 }
7535 case Intrinsic::sadd_sat: {
7536 SDValue Op1 = getValue(I.getArgOperand(0));
7537 SDValue Op2 = getValue(I.getArgOperand(1));
7538 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7539 return;
7540 }
7541 case Intrinsic::uadd_sat: {
7542 SDValue Op1 = getValue(I.getArgOperand(0));
7543 SDValue Op2 = getValue(I.getArgOperand(1));
7544 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7545 return;
7546 }
7547 case Intrinsic::ssub_sat: {
7548 SDValue Op1 = getValue(I.getArgOperand(0));
7549 SDValue Op2 = getValue(I.getArgOperand(1));
7550 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7551 return;
7552 }
7553 case Intrinsic::usub_sat: {
7554 SDValue Op1 = getValue(I.getArgOperand(0));
7555 SDValue Op2 = getValue(I.getArgOperand(1));
7556 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7557 return;
7558 }
7559 case Intrinsic::sshl_sat:
7560 case Intrinsic::ushl_sat: {
7561 SDValue Op1 = getValue(I.getArgOperand(0));
7562 SDValue Op2 = getValue(I.getArgOperand(1));
7563
7564 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
7565 Op1.getValueType(), DAG.getDataLayout());
7566
7567 // Coerce the shift amount to the right type if we can. This exposes the
7568 // truncate or zext to optimization early.
7569 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
7570 assert(ShiftTy.getSizeInBits() >=
7572 "Unexpected shift type");
7573 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
7574 }
7575
7576 unsigned Opc =
7577 Intrinsic == Intrinsic::sshl_sat ? ISD::SSHLSAT : ISD::USHLSAT;
7578 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1, Op2));
7579 return;
7580 }
7581 case Intrinsic::smul_fix:
7582 case Intrinsic::umul_fix:
7583 case Intrinsic::smul_fix_sat:
7584 case Intrinsic::umul_fix_sat: {
7585 SDValue Op1 = getValue(I.getArgOperand(0));
7586 SDValue Op2 = getValue(I.getArgOperand(1));
7587 SDValue Op3 = getValue(I.getArgOperand(2));
7588 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7589 Op1.getValueType(), Op1, Op2, Op3));
7590 return;
7591 }
7592 case Intrinsic::sdiv_fix:
7593 case Intrinsic::udiv_fix:
7594 case Intrinsic::sdiv_fix_sat:
7595 case Intrinsic::udiv_fix_sat: {
7596 SDValue Op1 = getValue(I.getArgOperand(0));
7597 SDValue Op2 = getValue(I.getArgOperand(1));
7598 SDValue Op3 = getValue(I.getArgOperand(2));
7600 Op1, Op2, Op3, DAG, TLI));
7601 return;
7602 }
7603 case Intrinsic::smax: {
7604 SDValue Op1 = getValue(I.getArgOperand(0));
7605 SDValue Op2 = getValue(I.getArgOperand(1));
7606 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7607 return;
7608 }
7609 case Intrinsic::smin: {
7610 SDValue Op1 = getValue(I.getArgOperand(0));
7611 SDValue Op2 = getValue(I.getArgOperand(1));
7612 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7613 return;
7614 }
7615 case Intrinsic::umax: {
7616 SDValue Op1 = getValue(I.getArgOperand(0));
7617 SDValue Op2 = getValue(I.getArgOperand(1));
7618 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7619 return;
7620 }
7621 case Intrinsic::umin: {
7622 SDValue Op1 = getValue(I.getArgOperand(0));
7623 SDValue Op2 = getValue(I.getArgOperand(1));
7624 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7625 return;
7626 }
7627 case Intrinsic::abs: {
7628 SDValue Op1 = getValue(I.getArgOperand(0));
7629 bool IntMinIsPoison = cast<ConstantInt>(I.getArgOperand(1))->isOne();
7630 unsigned Opc = IntMinIsPoison ? ISD::ABS_MIN_POISON : ISD::ABS;
7631 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1));
7632 return;
7633 }
7634 case Intrinsic::scmp: {
7635 SDValue Op1 = getValue(I.getArgOperand(0));
7636 SDValue Op2 = getValue(I.getArgOperand(1));
7637 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7638 setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7639 break;
7640 }
7641 case Intrinsic::ucmp: {
7642 SDValue Op1 = getValue(I.getArgOperand(0));
7643 SDValue Op2 = getValue(I.getArgOperand(1));
7644 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7645 setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7646 break;
7647 }
7648 case Intrinsic::stackaddress:
7649 case Intrinsic::stacksave: {
7650 unsigned SDOpcode = Intrinsic == Intrinsic::stackaddress ? ISD::STACKADDRESS
7652 SDValue Op = getRoot();
7653 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7654 Res = DAG.getNode(SDOpcode, sdl, DAG.getVTList(VT, MVT::Other), Op);
7655 setValue(&I, Res);
7656 DAG.setRoot(Res.getValue(1));
7657 return;
7658 }
7659 case Intrinsic::stackrestore:
7660 Res = getValue(I.getArgOperand(0));
7661 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7662 return;
7663 case Intrinsic::get_dynamic_area_offset: {
7664 SDValue Op = getRoot();
7665 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7666 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7667 Op);
7668 DAG.setRoot(Op);
7669 setValue(&I, Res);
7670 return;
7671 }
7672 case Intrinsic::stackguard: {
7673 MachineFunction &MF = DAG.getMachineFunction();
7674 const Module &M = *MF.getFunction().getParent();
7675 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7676 SDValue Chain = getRoot();
7677 if (TLI.useLoadStackGuardNode(M)) {
7678 Res = getLoadStackGuard(DAG, sdl, Chain);
7679 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7680 } else {
7681 const Value *Global = TLI.getSDagStackGuard(M, DAG.getLibcalls());
7682 if (!Global) {
7683 LLVMContext &Ctx = *DAG.getContext();
7684 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
7685 setValue(&I, DAG.getPOISON(PtrTy));
7686 return;
7687 }
7688
7689 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7690 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7691 MachinePointerInfo(Global, 0), Align,
7693 }
7694 // Mix the cookie with FP if enabled. Skip if using LOAD_STACK_GUARD
7695 // with post-RA mixing (AArch64 MSVCRT), as the mixing will be done during
7696 // post-RA expansion of LOAD_STACK_GUARD.
7697 if (TLI.useStackGuardMixFP() && !TLI.useLoadStackGuardNode(M))
7698 Res = TLI.emitStackGuardMixFP(DAG, Res, sdl);
7699 DAG.setRoot(Chain);
7700 setValue(&I, Res);
7701 return;
7702 }
7703 case Intrinsic::stackprotector: {
7704 // Emit code into the DAG to store the stack guard onto the stack.
7705 MachineFunction &MF = DAG.getMachineFunction();
7706 MachineFrameInfo &MFI = MF.getFrameInfo();
7707 const Module &M = *MF.getFunction().getParent();
7708 SDValue Src, Chain = getRoot();
7709
7710 if (TLI.useLoadStackGuardNode(M))
7711 Src = getLoadStackGuard(DAG, sdl, Chain);
7712 else
7713 Src = getValue(I.getArgOperand(0)); // The guard's value.
7714
7715 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7716
7717 int FI = FuncInfo.StaticAllocaMap[Slot];
7718 MFI.setStackProtectorIndex(FI);
7719 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7720
7721 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7722
7723 // Store the stack protector onto the stack.
7724 Res = DAG.getStore(
7725 Chain, sdl, Src, FIN,
7726 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7727 MaybeAlign(), MachineMemOperand::MOVolatile);
7728 setValue(&I, Res);
7729 DAG.setRoot(Res);
7730 return;
7731 }
7732 case Intrinsic::objectsize:
7733 llvm_unreachable("llvm.objectsize.* should have been lowered already");
7734
7735 case Intrinsic::is_constant:
7736 llvm_unreachable("llvm.is.constant.* should have been lowered already");
7737
7738 case Intrinsic::annotation:
7739 case Intrinsic::ptr_annotation:
7740 case Intrinsic::launder_invariant_group:
7741 case Intrinsic::strip_invariant_group:
7742 // Drop the intrinsic, but forward the value
7743 setValue(&I, getValue(I.getOperand(0)));
7744 return;
7745
7746 case Intrinsic::type_test:
7747 case Intrinsic::public_type_test:
7748 case Intrinsic::type_checked_load:
7749 case Intrinsic::type_checked_load_relative: {
7750 // These intrinsics are expected to be lowered by the LowerTypeTests pass
7751 // before code generation. Surviving until here usually indicates a
7752 // misconfiguration, for instance when devirtualization is enabled but LTO
7753 // does not actually run.
7754 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
7755 *I.getFunction(),
7756 Intrinsic::getBaseName(Intrinsic) +
7757 " intrinsic must be lowered by the LowerTypeTests pass "
7758 "before code generation",
7759 sdl.getDebugLoc()));
7760
7761 // Lower the result to poison so that compilation can continue and collect
7762 // any further diagnostics.
7763 setValueToPoison(&I, sdl);
7764 return;
7765 }
7766
7767 case Intrinsic::assume:
7768 case Intrinsic::experimental_noalias_scope_decl:
7769 case Intrinsic::var_annotation:
7770 case Intrinsic::sideeffect:
7771 // Discard annotate attributes, noalias scope declarations, assumptions, and
7772 // artificial side-effects.
7773 return;
7774
7775 case Intrinsic::codeview_annotation: {
7776 // Emit a label associated with this metadata.
7777 MachineFunction &MF = DAG.getMachineFunction();
7778 MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7779 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7780 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7781 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7782 DAG.setRoot(Res);
7783 return;
7784 }
7785
7786 case Intrinsic::init_trampoline: {
7787 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7788
7789 SDValue Ops[6];
7790 Ops[0] = getRoot();
7791 Ops[1] = getValue(I.getArgOperand(0));
7792 Ops[2] = getValue(I.getArgOperand(1));
7793 Ops[3] = getValue(I.getArgOperand(2));
7794 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7795 Ops[5] = DAG.getSrcValue(F);
7796
7797 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7798
7799 DAG.setRoot(Res);
7800 return;
7801 }
7802 case Intrinsic::adjust_trampoline:
7803 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7804 TLI.getPointerTy(DAG.getDataLayout()),
7805 getValue(I.getArgOperand(0))));
7806 return;
7807 case Intrinsic::gcroot: {
7808 assert(DAG.getMachineFunction().getFunction().hasGC() &&
7809 "only valid in functions with gc specified, enforced by Verifier");
7810 assert(GFI && "implied by previous");
7811 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7812 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7813
7814 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7815 GFI->addStackRoot(FI->getIndex(), TypeMap);
7816 return;
7817 }
7818 case Intrinsic::gcread:
7819 case Intrinsic::gcwrite:
7820 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7821 case Intrinsic::get_rounding:
7822 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7823 setValue(&I, Res);
7824 DAG.setRoot(Res.getValue(1));
7825 return;
7826
7827 case Intrinsic::expect:
7828 case Intrinsic::expect_with_probability:
7829 // Just replace __builtin_expect(exp, c) and
7830 // __builtin_expect_with_probability(exp, c, p) with EXP.
7831 setValue(&I, getValue(I.getArgOperand(0)));
7832 return;
7833
7834 case Intrinsic::ubsantrap:
7835 case Intrinsic::debugtrap:
7836 case Intrinsic::trap: {
7837 StringRef TrapFuncName =
7838 I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7839 if (TrapFuncName.empty()) {
7840 switch (Intrinsic) {
7841 case Intrinsic::trap:
7842 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7843 break;
7844 case Intrinsic::debugtrap:
7845 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7846 break;
7847 case Intrinsic::ubsantrap:
7848 DAG.setRoot(DAG.getNode(
7849 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7850 DAG.getTargetConstant(
7851 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7852 MVT::i32)));
7853 break;
7854 default: llvm_unreachable("unknown trap intrinsic");
7855 }
7856 DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
7857 I.hasFnAttr(Attribute::NoMerge));
7858 return;
7859 }
7861 if (Intrinsic == Intrinsic::ubsantrap) {
7862 Value *Arg = I.getArgOperand(0);
7863 Args.emplace_back(Arg, getValue(Arg));
7864 }
7865
7866 TargetLowering::CallLoweringInfo CLI(DAG);
7867 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7868 CallingConv::C, I.getType(),
7869 DAG.getExternalSymbol(TrapFuncName.data(),
7870 TLI.getPointerTy(DAG.getDataLayout())),
7871 std::move(Args));
7872 CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
7873 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7874 DAG.setRoot(Result.second);
7875 return;
7876 }
7877
7878 case Intrinsic::allow_runtime_check:
7879 case Intrinsic::allow_ubsan_check:
7880 setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7881 return;
7882
7883 case Intrinsic::uadd_with_overflow:
7884 case Intrinsic::sadd_with_overflow:
7885 case Intrinsic::usub_with_overflow:
7886 case Intrinsic::ssub_with_overflow:
7887 case Intrinsic::umul_with_overflow:
7888 case Intrinsic::smul_with_overflow: {
7890 switch (Intrinsic) {
7891 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7892 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7893 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7894 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7895 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7896 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7897 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7898 }
7899 SDValue Op1 = getValue(I.getArgOperand(0));
7900 SDValue Op2 = getValue(I.getArgOperand(1));
7901
7902 EVT ResultVT = Op1.getValueType();
7903 EVT OverflowVT = ResultVT.changeElementType(*Context, MVT::i1);
7904
7905 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7906 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7907 return;
7908 }
7909 case Intrinsic::prefetch: {
7910 SDValue Ops[5];
7911 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7913 Ops[0] = DAG.getRoot();
7914 Ops[1] = getValue(I.getArgOperand(0));
7915 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7916 MVT::i32);
7917 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7918 MVT::i32);
7919 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7920 MVT::i32);
7921 SDValue Result = DAG.getMemIntrinsicNode(
7922 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7923 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7924 /* align */ std::nullopt, Flags);
7925
7926 // Chain the prefetch in parallel with any pending loads, to stay out of
7927 // the way of later optimizations.
7928 PendingLoads.push_back(Result);
7929 Result = getRoot();
7930 DAG.setRoot(Result);
7931 return;
7932 }
7933 case Intrinsic::lifetime_start:
7934 case Intrinsic::lifetime_end: {
7935 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7936 // Stack coloring is not enabled in O0, discard region information.
7937 if (TM.getOptLevel() == CodeGenOptLevel::None)
7938 return;
7939
7940 const AllocaInst *LifetimeObject = dyn_cast<AllocaInst>(I.getArgOperand(0));
7941 if (!LifetimeObject)
7942 return;
7943
7944 // First check that the Alloca is static, otherwise it won't have a
7945 // valid frame index.
7946 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7947 if (SI == FuncInfo.StaticAllocaMap.end())
7948 return;
7949
7950 const int FrameIndex = SI->second;
7951 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex);
7952 DAG.setRoot(Res);
7953 return;
7954 }
7955 case Intrinsic::pseudoprobe: {
7956 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7957 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7958 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7959 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7960 DAG.setRoot(Res);
7961 return;
7962 }
7963 case Intrinsic::invariant_start:
7964 // Discard region information.
7965 setValue(&I,
7966 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7967 return;
7968 case Intrinsic::invariant_end:
7969 // Discard region information.
7970 return;
7971 case Intrinsic::clear_cache: {
7972 SDValue InputChain = DAG.getRoot();
7973 SDValue StartVal = getValue(I.getArgOperand(0));
7974 SDValue EndVal = getValue(I.getArgOperand(1));
7975 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7976 {InputChain, StartVal, EndVal});
7977 setValue(&I, Res);
7978 DAG.setRoot(Res);
7979 return;
7980 }
7981 case Intrinsic::donothing:
7982 case Intrinsic::seh_try_begin:
7983 case Intrinsic::seh_scope_begin:
7984 case Intrinsic::seh_try_end:
7985 case Intrinsic::seh_scope_end:
7986 // ignore
7987 return;
7988 case Intrinsic::experimental_stackmap:
7989 visitStackmap(I);
7990 return;
7991 case Intrinsic::experimental_patchpoint_void:
7992 case Intrinsic::experimental_patchpoint:
7993 visitPatchpoint(I);
7994 return;
7995 case Intrinsic::experimental_gc_statepoint:
7997 return;
7998 case Intrinsic::experimental_gc_result:
7999 visitGCResult(cast<GCResultInst>(I));
8000 return;
8001 case Intrinsic::experimental_gc_relocate:
8002 visitGCRelocate(cast<GCRelocateInst>(I));
8003 return;
8004 case Intrinsic::instrprof_cover:
8005 llvm_unreachable("instrprof failed to lower a cover");
8006 case Intrinsic::instrprof_increment:
8007 llvm_unreachable("instrprof failed to lower an increment");
8008 case Intrinsic::instrprof_timestamp:
8009 llvm_unreachable("instrprof failed to lower a timestamp");
8010 case Intrinsic::instrprof_value_profile:
8011 llvm_unreachable("instrprof failed to lower a value profiling call");
8012 case Intrinsic::instrprof_mcdc_parameters:
8013 llvm_unreachable("instrprof failed to lower mcdc parameters");
8014 case Intrinsic::instrprof_mcdc_tvbitmap_update:
8015 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
8016 case Intrinsic::localescape: {
8017 MachineFunction &MF = DAG.getMachineFunction();
8018 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
8019
8020 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
8021 // is the same on all targets.
8022 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
8023 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
8024 if (isa<ConstantPointerNull>(Arg))
8025 continue; // Skip null pointers. They represent a hole in index space.
8026 AllocaInst *Slot = cast<AllocaInst>(Arg);
8027 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
8028 "can only escape static allocas");
8029 int FI = FuncInfo.StaticAllocaMap[Slot];
8030 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8032 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
8033 TII->get(TargetOpcode::LOCAL_ESCAPE))
8034 .addSym(FrameAllocSym)
8035 .addFrameIndex(FI);
8036 }
8037
8038 return;
8039 }
8040
8041 case Intrinsic::localrecover: {
8042 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
8043 MachineFunction &MF = DAG.getMachineFunction();
8044
8045 // Get the symbol that defines the frame offset.
8046 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
8047 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
8048 unsigned IdxVal =
8049 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
8050 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8052
8053 Value *FP = I.getArgOperand(1);
8054 SDValue FPVal = getValue(FP);
8055 EVT PtrVT = FPVal.getValueType();
8056
8057 // Create a MCSymbol for the label to avoid any target lowering
8058 // that would make this PC relative.
8059 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
8060 SDValue OffsetVal =
8061 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
8062
8063 // Add the offset to the FP.
8064 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
8065 setValue(&I, Add);
8066
8067 return;
8068 }
8069
8070 case Intrinsic::fake_use: {
8071 Value *V = I.getArgOperand(0);
8072 SDValue Ops[2];
8073 // For Values not declared or previously used in this basic block, the
8074 // NodeMap will not have an entry, and `getValue` will assert if V has no
8075 // valid register value.
8076 auto FakeUseValue = [&]() -> SDValue {
8077 SDValue &N = NodeMap[V];
8078 if (N.getNode())
8079 return N;
8080
8081 // If there's a virtual register allocated and initialized for this
8082 // value, use it.
8083 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
8084 return copyFromReg;
8085 // FIXME: Do we want to preserve constants? It seems pointless.
8086 if (isa<Constant>(V))
8087 return getValue(V);
8088 return SDValue();
8089 }();
8090 if (!FakeUseValue || FakeUseValue.isUndef())
8091 return;
8092 Ops[0] = getRoot();
8093 Ops[1] = FakeUseValue;
8094 // Also, do not translate a fake use with an undef operand, or any other
8095 // empty SDValues.
8096 if (!Ops[1] || Ops[1].isUndef())
8097 return;
8098 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
8099 return;
8100 }
8101
8102 case Intrinsic::reloc_none: {
8103 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
8104 StringRef SymbolName = cast<MDString>(MD)->getString();
8105 SDValue Ops[2] = {
8106 getRoot(),
8107 DAG.getTargetExternalSymbol(
8108 SymbolName.data(), TLI.getProgramPointerTy(DAG.getDataLayout()))};
8109 DAG.setRoot(DAG.getNode(ISD::RELOC_NONE, sdl, MVT::Other, Ops));
8110 return;
8111 }
8112
8113 case Intrinsic::cond_loop: {
8114 SDValue InputChain = DAG.getRoot();
8115 SDValue P = getValue(I.getArgOperand(0));
8116 Res = DAG.getNode(ISD::COND_LOOP, sdl, DAG.getVTList(MVT::Other),
8117 {InputChain, P});
8118 setValue(&I, Res);
8119 DAG.setRoot(Res);
8120 return;
8121 }
8122
8123 case Intrinsic::eh_exceptionpointer:
8124 case Intrinsic::eh_exceptioncode: {
8125 // Get the exception pointer vreg, copy from it, and resize it to fit.
8126 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
8127 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
8128 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
8129 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
8130 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
8131 if (Intrinsic == Intrinsic::eh_exceptioncode)
8132 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
8133 setValue(&I, N);
8134 return;
8135 }
8136 case Intrinsic::xray_customevent: {
8137 // Here we want to make sure that the intrinsic behaves as if it has a
8138 // specific calling convention.
8139 const auto &Triple = DAG.getTarget().getTargetTriple();
8140 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8141 Triple.getArch() != Triple::hexagon)
8142 return;
8143
8145
8146 // We want to say that we always want the arguments in registers.
8147 SDValue LogEntryVal = getValue(I.getArgOperand(0));
8148 SDValue StrSizeVal = getValue(I.getArgOperand(1));
8149 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8150 SDValue Chain = getRoot();
8151 Ops.push_back(LogEntryVal);
8152 Ops.push_back(StrSizeVal);
8153 Ops.push_back(Chain);
8154
8155 // We need to enforce the calling convention for the callsite, so that
8156 // argument ordering is enforced correctly, and that register allocation can
8157 // see that some registers may be assumed clobbered and have to preserve
8158 // them across calls to the intrinsic.
8159 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
8160 sdl, NodeTys, Ops);
8161 SDValue patchableNode = SDValue(MN, 0);
8162 DAG.setRoot(patchableNode);
8163 setValue(&I, patchableNode);
8164 return;
8165 }
8166 case Intrinsic::xray_typedevent: {
8167 // Here we want to make sure that the intrinsic behaves as if it has a
8168 // specific calling convention.
8169 const auto &Triple = DAG.getTarget().getTargetTriple();
8170 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8171 Triple.getArch() != Triple::hexagon)
8172 return;
8173
8175
8176 // We want to say that we always want the arguments in registers.
8177 // It's unclear to me how manipulating the selection DAG here forces callers
8178 // to provide arguments in registers instead of on the stack.
8179 SDValue LogTypeId = getValue(I.getArgOperand(0));
8180 SDValue LogEntryVal = getValue(I.getArgOperand(1));
8181 SDValue StrSizeVal = getValue(I.getArgOperand(2));
8182 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8183 SDValue Chain = getRoot();
8184 Ops.push_back(LogTypeId);
8185 Ops.push_back(LogEntryVal);
8186 Ops.push_back(StrSizeVal);
8187 Ops.push_back(Chain);
8188
8189 // We need to enforce the calling convention for the callsite, so that
8190 // argument ordering is enforced correctly, and that register allocation can
8191 // see that some registers may be assumed clobbered and have to preserve
8192 // them across calls to the intrinsic.
8193 MachineSDNode *MN = DAG.getMachineNode(
8194 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
8195 SDValue patchableNode = SDValue(MN, 0);
8196 DAG.setRoot(patchableNode);
8197 setValue(&I, patchableNode);
8198 return;
8199 }
8200 case Intrinsic::experimental_deoptimize:
8202 return;
8203 case Intrinsic::stepvector:
8204 visitStepVector(I);
8205 return;
8206 case Intrinsic::vector_reduce_fadd:
8207 case Intrinsic::vector_reduce_fmul:
8208 case Intrinsic::vector_reduce_add:
8209 case Intrinsic::vector_reduce_mul:
8210 case Intrinsic::vector_reduce_and:
8211 case Intrinsic::vector_reduce_or:
8212 case Intrinsic::vector_reduce_xor:
8213 case Intrinsic::vector_reduce_smax:
8214 case Intrinsic::vector_reduce_smin:
8215 case Intrinsic::vector_reduce_umax:
8216 case Intrinsic::vector_reduce_umin:
8217 case Intrinsic::vector_reduce_fmax:
8218 case Intrinsic::vector_reduce_fmin:
8219 case Intrinsic::vector_reduce_fmaximum:
8220 case Intrinsic::vector_reduce_fminimum:
8221 case Intrinsic::vector_reduce_fmaximumnum:
8222 case Intrinsic::vector_reduce_fminimumnum:
8223 visitVectorReduce(I, Intrinsic);
8224 return;
8225
8226 case Intrinsic::icall_branch_funnel: {
8228 Ops.push_back(getValue(I.getArgOperand(0)));
8229
8230 int64_t Offset;
8232 I.getArgOperand(1), Offset, DAG.getDataLayout()));
8233 if (!Base)
8235 "llvm.icall.branch.funnel operand must be a GlobalValue");
8236 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
8237
8238 struct BranchFunnelTarget {
8239 int64_t Offset;
8241 };
8243
8244 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
8246 I.getArgOperand(Op), Offset, DAG.getDataLayout()));
8247 if (ElemBase != Base)
8248 report_fatal_error("all llvm.icall.branch.funnel operands must refer "
8249 "to the same GlobalValue");
8250
8251 SDValue Val = getValue(I.getArgOperand(Op + 1));
8252 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
8253 if (!GA)
8255 "llvm.icall.branch.funnel operand must be a GlobalValue");
8256 Targets.push_back({Offset, DAG.getTargetGlobalAddress(
8257 GA->getGlobal(), sdl, Val.getValueType(),
8258 GA->getOffset())});
8259 }
8260 llvm::sort(Targets,
8261 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
8262 return T1.Offset < T2.Offset;
8263 });
8264
8265 for (auto &T : Targets) {
8266 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
8267 Ops.push_back(T.Target);
8268 }
8269
8270 Ops.push_back(DAG.getRoot()); // Chain
8271 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
8272 MVT::Other, Ops),
8273 0);
8274 DAG.setRoot(N);
8275 setValue(&I, N);
8276 HasTailCall = true;
8277 return;
8278 }
8279
8280 case Intrinsic::wasm_landingpad_index:
8281 // Information this intrinsic contained has been transferred to
8282 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
8283 // delete it now.
8284 return;
8285
8286 case Intrinsic::aarch64_settag:
8287 case Intrinsic::aarch64_settag_zero: {
8288 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8289 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
8291 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
8292 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
8293 ZeroMemory);
8294 DAG.setRoot(Val);
8295 setValue(&I, Val);
8296 return;
8297 }
8298 case Intrinsic::amdgcn_cs_chain: {
8299 // At this point we don't care if it's amdgpu_cs_chain or
8300 // amdgpu_cs_chain_preserve.
8302
8303 Type *RetTy = I.getType();
8304 assert(RetTy->isVoidTy() && "Should not return");
8305
8306 SDValue Callee = getValue(I.getOperand(0));
8307
8308 // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8309 // We'll also tack the value of the EXEC mask at the end.
8311 Args.reserve(3);
8312
8313 for (unsigned Idx : {2, 3, 1}) {
8314 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8315 I.getOperand(Idx)->getType());
8316 Arg.setAttributes(&I, Idx);
8317 Args.push_back(Arg);
8318 }
8319
8320 assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8321 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8322 Args[2].IsInReg = true; // EXEC should be inreg
8323
8324 // Forward the flags and any additional arguments.
8325 for (unsigned Idx = 4; Idx < I.arg_size(); ++Idx) {
8326 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8327 I.getOperand(Idx)->getType());
8328 Arg.setAttributes(&I, Idx);
8329 Args.push_back(Arg);
8330 }
8331
8332 TargetLowering::CallLoweringInfo CLI(DAG);
8333 CLI.setDebugLoc(getCurSDLoc())
8334 .setChain(getRoot())
8335 .setCallee(CC, RetTy, Callee, std::move(Args))
8336 .setNoReturn(true)
8337 .setTailCall(true)
8338 .setConvergent(I.isConvergent());
8339 CLI.CB = &I;
8340 std::pair<SDValue, SDValue> Result =
8341 lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8342 (void)Result;
8343 assert(!Result.first.getNode() && !Result.second.getNode() &&
8344 "Should've lowered as tail call");
8345
8346 HasTailCall = true;
8347 return;
8348 }
8349 case Intrinsic::amdgcn_call_whole_wave: {
8351 bool isTailCall = I.isTailCall();
8352
8353 // The first argument is the callee. Skip it when assembling the call args.
8354 for (unsigned Idx = 1; Idx < I.arg_size(); ++Idx) {
8355 TargetLowering::ArgListEntry Arg(getValue(I.getArgOperand(Idx)),
8356 I.getArgOperand(Idx)->getType());
8357 Arg.setAttributes(&I, Idx);
8358
8359 // If we have an explicit sret argument that is an Instruction, (i.e., it
8360 // might point to function-local memory), we can't meaningfully tail-call.
8361 if (Arg.IsSRet && isa<Instruction>(I.getArgOperand(Idx)))
8362 isTailCall = false;
8363
8364 Args.push_back(Arg);
8365 }
8366
8367 SDValue ConvControlToken;
8368 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8369 auto *Token = Bundle->Inputs[0].get();
8370 ConvControlToken = getValue(Token);
8371 }
8372
8373 TargetLowering::CallLoweringInfo CLI(DAG);
8374 CLI.setDebugLoc(getCurSDLoc())
8375 .setChain(getRoot())
8376 .setCallee(CallingConv::AMDGPU_Gfx_WholeWave, I.getType(),
8377 getValue(I.getArgOperand(0)), std::move(Args))
8378 .setTailCall(isTailCall && canTailCall(I))
8379 .setIsPreallocated(
8380 I.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8381 .setConvergent(I.isConvergent())
8382 .setConvergenceControlToken(ConvControlToken);
8383 CLI.CB = &I;
8384
8385 std::pair<SDValue, SDValue> Result =
8386 lowerInvokable(CLI, /*EHPadBB=*/nullptr);
8387
8388 if (Result.first.getNode())
8389 setValue(&I, Result.first);
8390 return;
8391 }
8392 case Intrinsic::ptrmask: {
8393 SDValue Ptr = getValue(I.getOperand(0));
8394 SDValue Mask = getValue(I.getOperand(1));
8395
8396 // On arm64_32, pointers are 32 bits when stored in memory, but
8397 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to
8398 // match the index type, but the pointer is 64 bits, so the mask must be
8399 // zero-extended up to 64 bits to match the pointer.
8400 EVT PtrVT =
8401 TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8402 EVT MemVT =
8403 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8404 assert(PtrVT == Ptr.getValueType());
8405 if (Mask.getValueType().getFixedSizeInBits() < MemVT.getFixedSizeInBits()) {
8406 // For AMDGPU buffer descriptors the mask is 48 bits, but the pointer is
8407 // 128-bit, so we have to pad the mask with ones for unused bits.
8408 auto HighOnes = DAG.getNode(
8409 ISD::SHL, sdl, PtrVT, DAG.getAllOnesConstant(sdl, PtrVT),
8410 DAG.getShiftAmountConstant(Mask.getValueType().getFixedSizeInBits(),
8411 PtrVT, sdl));
8412 Mask = DAG.getNode(ISD::OR, sdl, PtrVT,
8413 DAG.getZExtOrTrunc(Mask, sdl, PtrVT), HighOnes);
8414 } else if (Mask.getValueType() != PtrVT)
8415 Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
8416
8417 assert(Mask.getValueType() == PtrVT);
8418 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
8419 return;
8420 }
8421 case Intrinsic::threadlocal_address: {
8422 setValue(&I, getValue(I.getOperand(0)));
8423 return;
8424 }
8425 case Intrinsic::get_active_lane_mask: {
8426 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8427 SDValue Index = getValue(I.getOperand(0));
8428 SDValue TripCount = getValue(I.getOperand(1));
8429 EVT ElementVT = Index.getValueType();
8430
8431 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
8432 setValue(&I, DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, sdl, CCVT, Index,
8433 TripCount));
8434 return;
8435 }
8436
8437 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
8438 CCVT.getVectorElementCount());
8439
8440 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
8441 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
8442 SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
8443 SDValue VectorInduction = DAG.getNode(
8444 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
8445 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
8446 VectorTripCount, ISD::CondCode::SETULT);
8447 setValue(&I, SetCC);
8448 return;
8449 }
8450 case Intrinsic::experimental_get_vector_length: {
8451 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8452 "Expected positive VF");
8453 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
8454 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
8455
8456 SDValue Count = getValue(I.getOperand(0));
8457 EVT CountVT = Count.getValueType();
8458
8459 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8460 visitTargetIntrinsic(I, Intrinsic);
8461 return;
8462 }
8463
8464 // Expand to a umin between the trip count and the maximum elements the type
8465 // can hold.
8466 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8467
8468 // Extend the trip count to at least the result VT.
8469 if (CountVT.bitsLT(VT)) {
8470 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
8471 CountVT = VT;
8472 }
8473
8474 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
8475 ElementCount::get(VF, IsScalable));
8476
8477 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8478 // Clip to the result type if needed.
8479 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8480
8481 setValue(&I, Trunc);
8482 return;
8483 }
8484 case Intrinsic::vector_partial_reduce_add: {
8485 SDValue Acc = getValue(I.getOperand(0));
8486 SDValue Input = getValue(I.getOperand(1));
8487 setValue(&I,
8488 DAG.getNode(ISD::PARTIAL_REDUCE_UMLA, sdl, Acc.getValueType(), Acc,
8489 Input, DAG.getConstant(1, sdl, Input.getValueType())));
8490 return;
8491 }
8492 case Intrinsic::vector_partial_reduce_fadd: {
8493 SDValue Acc = getValue(I.getOperand(0));
8494 SDValue Input = getValue(I.getOperand(1));
8495 setValue(&I, DAG.getNode(
8496 ISD::PARTIAL_REDUCE_FMLA, sdl, Acc.getValueType(), Acc,
8497 Input, DAG.getConstantFP(1.0, sdl, Input.getValueType())));
8498 return;
8499 }
8500 case Intrinsic::experimental_cttz_elts: {
8501 SDValue Op = getValue(I.getOperand(0));
8502 EVT OpVT = Op.getValueType();
8503 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8504 bool ZeroIsPoison =
8505 !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8506 if (OpVT.getVectorElementType() != MVT::i1) {
8507 // Compare the input vector elements to zero & use to count trailing
8508 // zeros.
8509 SDValue AllZero = DAG.getConstant(0, sdl, OpVT);
8510 EVT I1OpVT = OpVT.changeVectorElementType(*DAG.getContext(), MVT::i1);
8511 Op = DAG.getSetCC(sdl, I1OpVT, Op, AllZero, ISD::SETNE);
8512 }
8513 setValue(&I, DAG.getNode(ZeroIsPoison ? ISD::CTTZ_ELTS_ZERO_POISON
8515 sdl, RetTy, Op));
8516 return;
8517 }
8518 case Intrinsic::vector_insert: {
8519 SDValue Vec = getValue(I.getOperand(0));
8520 SDValue SubVec = getValue(I.getOperand(1));
8521 SDValue Index = getValue(I.getOperand(2));
8522
8523 // The intrinsic's index type is i64, but the SDNode requires an index type
8524 // suitable for the target. Convert the index as required.
8525 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8526 if (Index.getValueType() != VectorIdxTy)
8527 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8528
8529 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8530 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8531 Index));
8532 return;
8533 }
8534 case Intrinsic::vector_extract: {
8535 SDValue Vec = getValue(I.getOperand(0));
8536 SDValue Index = getValue(I.getOperand(1));
8537 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8538
8539 // The intrinsic's index type is i64, but the SDNode requires an index type
8540 // suitable for the target. Convert the index as required.
8541 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8542 if (Index.getValueType() != VectorIdxTy)
8543 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8544
8545 setValue(&I,
8546 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8547 return;
8548 }
8549 case Intrinsic::experimental_vector_match: {
8550 SDValue Op1 = getValue(I.getOperand(0));
8551 SDValue Op2 = getValue(I.getOperand(1));
8552 SDValue Mask = getValue(I.getOperand(2));
8553 EVT ResVT = Mask.getValueType();
8554 setValue(&I, DAG.getNode(ISD::VECTOR_MATCH, sdl, ResVT, Op1, Op2, Mask));
8555 return;
8556 }
8557 case Intrinsic::vector_reverse:
8558 visitVectorReverse(I);
8559 return;
8560 case Intrinsic::vector_splice_left:
8561 case Intrinsic::vector_splice_right:
8562 visitVectorSplice(I);
8563 return;
8564 case Intrinsic::callbr_landingpad:
8565 visitCallBrLandingPad(I);
8566 return;
8567 case Intrinsic::vector_interleave2:
8568 visitVectorInterleave(I, 2);
8569 return;
8570 case Intrinsic::vector_interleave3:
8571 visitVectorInterleave(I, 3);
8572 return;
8573 case Intrinsic::vector_interleave4:
8574 visitVectorInterleave(I, 4);
8575 return;
8576 case Intrinsic::vector_interleave5:
8577 visitVectorInterleave(I, 5);
8578 return;
8579 case Intrinsic::vector_interleave6:
8580 visitVectorInterleave(I, 6);
8581 return;
8582 case Intrinsic::vector_interleave7:
8583 visitVectorInterleave(I, 7);
8584 return;
8585 case Intrinsic::vector_interleave8:
8586 visitVectorInterleave(I, 8);
8587 return;
8588 case Intrinsic::vector_deinterleave2:
8589 visitVectorDeinterleave(I, 2);
8590 return;
8591 case Intrinsic::vector_deinterleave3:
8592 visitVectorDeinterleave(I, 3);
8593 return;
8594 case Intrinsic::vector_deinterleave4:
8595 visitVectorDeinterleave(I, 4);
8596 return;
8597 case Intrinsic::vector_deinterleave5:
8598 visitVectorDeinterleave(I, 5);
8599 return;
8600 case Intrinsic::vector_deinterleave6:
8601 visitVectorDeinterleave(I, 6);
8602 return;
8603 case Intrinsic::vector_deinterleave7:
8604 visitVectorDeinterleave(I, 7);
8605 return;
8606 case Intrinsic::vector_deinterleave8:
8607 visitVectorDeinterleave(I, 8);
8608 return;
8609 case Intrinsic::experimental_vector_compress:
8610 setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8611 getValue(I.getArgOperand(0)).getValueType(),
8612 getValue(I.getArgOperand(0)),
8613 getValue(I.getArgOperand(1)),
8614 getValue(I.getArgOperand(2)), Flags));
8615 return;
8616 case Intrinsic::experimental_convergence_anchor:
8617 case Intrinsic::experimental_convergence_entry:
8618 case Intrinsic::experimental_convergence_loop:
8619 visitConvergenceControl(I, Intrinsic);
8620 return;
8621 case Intrinsic::experimental_vector_histogram_add: {
8622 visitVectorHistogram(I, Intrinsic);
8623 return;
8624 }
8625 case Intrinsic::experimental_vector_extract_last_active: {
8626 visitVectorExtractLastActive(I, Intrinsic);
8627 return;
8628 }
8629 case Intrinsic::loop_dependence_war_mask:
8630 setValue(&I,
8632 EVT::getEVT(I.getType()), getValue(I.getOperand(0)),
8633 getValue(I.getOperand(1)), getValue(I.getOperand(2)),
8634 DAG.getConstant(0, sdl, MVT::i64)));
8635 return;
8636 case Intrinsic::loop_dependence_raw_mask:
8637 setValue(&I,
8639 EVT::getEVT(I.getType()), getValue(I.getOperand(0)),
8640 getValue(I.getOperand(1)), getValue(I.getOperand(2)),
8641 DAG.getConstant(0, sdl, MVT::i64)));
8642 return;
8643 case Intrinsic::masked_udiv:
8644 setValue(&I,
8645 DAG.getNode(ISD::MASKED_UDIV, sdl, EVT::getEVT(I.getType()),
8646 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8647 getValue(I.getOperand(2))));
8648 return;
8649 case Intrinsic::masked_sdiv:
8650 setValue(&I,
8651 DAG.getNode(ISD::MASKED_SDIV, sdl, EVT::getEVT(I.getType()),
8652 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8653 getValue(I.getOperand(2))));
8654 return;
8655 case Intrinsic::masked_urem:
8656 setValue(&I,
8657 DAG.getNode(ISD::MASKED_UREM, sdl, EVT::getEVT(I.getType()),
8658 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8659 getValue(I.getOperand(2))));
8660 return;
8661 case Intrinsic::masked_srem:
8662 setValue(&I,
8663 DAG.getNode(ISD::MASKED_SREM, sdl, EVT::getEVT(I.getType()),
8664 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8665 getValue(I.getOperand(2))));
8666 return;
8667 }
8668}
8669
8670void SelectionDAGBuilder::pushFPOpOutChain(SDValue Result,
8672 assert(Result.getNode()->getNumValues() == 2);
8673 SDValue OutChain = Result.getValue(1);
8674 assert(OutChain.getValueType() == MVT::Other);
8675
8676 // Instead of updating the root immediately, push the produced chain to the
8677 // appropriate list, deferring the update until the root is requested. In this
8678 // case, the nodes from the lists are chained using TokenFactor, indicating
8679 // that the operations are independent.
8680 //
8681 // In particular, the root is updated before any call that might access the
8682 // floating-point environment, except for constrained intrinsics.
8683 switch (EB) {
8686 PendingConstrainedFP.push_back(OutChain);
8687 break;
8689 PendingConstrainedFPStrict.push_back(OutChain);
8690 break;
8691 }
8692}
8693
8694void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8695 const ConstrainedFPIntrinsic &FPI) {
8696 SDLoc sdl = getCurSDLoc();
8697
8698 // We do not need to serialize constrained FP intrinsics against
8699 // each other or against (nonvolatile) loads, so they can be
8700 // chained like loads.
8702 SDValue Chain = getFPOperationRoot(EB);
8704 Opers.push_back(Chain);
8705 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8706 Opers.push_back(getValue(FPI.getArgOperand(I)));
8707
8708 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8709 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8710 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8711
8712 SDNodeFlags Flags;
8714 Flags.setNoFPExcept(true);
8715
8716 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8717 Flags.copyFMF(*FPOp);
8718
8719 unsigned Opcode;
8720 switch (FPI.getIntrinsicID()) {
8721 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8722#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8723 case Intrinsic::INTRINSIC: \
8724 Opcode = ISD::STRICT_##DAGN; \
8725 break;
8726#include "llvm/IR/ConstrainedOps.def"
8727 case Intrinsic::experimental_constrained_fmuladd: {
8728 Opcode = ISD::STRICT_FMA;
8729 // Break fmuladd into fmul and fadd.
8730 if (!TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8731 Opers.pop_back();
8732 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8733 pushFPOpOutChain(Mul, EB);
8734 Opcode = ISD::STRICT_FADD;
8735 Opers.clear();
8736 Opers.push_back(Mul.getValue(1));
8737 Opers.push_back(Mul.getValue(0));
8738 Opers.push_back(getValue(FPI.getArgOperand(2)));
8739 }
8740 break;
8741 }
8742 }
8743
8744 // A few strict DAG nodes carry additional operands that are not
8745 // set up by the default code above.
8746 switch (Opcode) {
8747 default: break;
8749 Opers.push_back(
8750 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8751 break;
8752 case ISD::STRICT_FSETCC:
8753 case ISD::STRICT_FSETCCS: {
8754 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8755 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8756 if (DAG.isKnownNeverNaN(Opers[1]) && DAG.isKnownNeverNaN(Opers[2]))
8757 Condition = getFCmpCodeWithoutNaN(Condition);
8758 Opers.push_back(DAG.getCondCode(Condition));
8759 break;
8760 }
8761 }
8762
8763 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8764 pushFPOpOutChain(Result, EB);
8765
8766 SDValue FPResult = Result.getValue(0);
8767 setValue(&FPI, FPResult);
8768}
8769
8770static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8771 std::optional<unsigned> ResOPC;
8772 switch (VPIntrin.getIntrinsicID()) {
8773 case Intrinsic::vp_cttz_elts: {
8774 bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8775 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_POISON : ISD::VP_CTTZ_ELTS;
8776 break;
8777 }
8778#define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \
8779 case Intrinsic::VPID: \
8780 ResOPC = ISD::VPSD; \
8781 break;
8782#include "llvm/IR/VPIntrinsics.def"
8783 }
8784
8785 if (!ResOPC)
8787 "Inconsistency: no SDNode available for this VPIntrinsic!");
8788
8789 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8790 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8791 if (VPIntrin.getFastMathFlags().allowReassoc())
8792 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8793 : ISD::VP_REDUCE_FMUL;
8794 }
8795
8796 return *ResOPC;
8797}
8798
8799void SelectionDAGBuilder::visitVPLoad(
8800 const VPIntrinsic &VPIntrin, EVT VT,
8801 const SmallVectorImpl<SDValue> &OpValues) {
8802 SDLoc DL = getCurSDLoc();
8803 Value *PtrOperand = VPIntrin.getArgOperand(0);
8804 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8805 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8806 const MDNode *Ranges = getRangeMetadata(VPIntrin);
8807 SDValue LD;
8808 // Do not serialize variable-length loads of constant memory with
8809 // anything.
8810 if (!Alignment)
8811 Alignment = DAG.getEVTAlign(VT);
8812 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8813 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
8814 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8815 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8816 MachineMemOperand::Flags MMOFlags =
8817 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8818 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8819 MachinePointerInfo(PtrOperand), MMOFlags,
8821 MMOMetadata(AAInfo, Ranges));
8822 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8823 MMO, false /*IsExpanding */);
8824 if (AddToChain)
8825 PendingLoads.push_back(LD.getValue(1));
8826 setValue(&VPIntrin, LD);
8827}
8828
8829void SelectionDAGBuilder::visitVPLoadFF(
8830 const VPIntrinsic &VPIntrin, EVT VT, EVT EVLVT,
8831 const SmallVectorImpl<SDValue> &OpValues) {
8832 assert(OpValues.size() == 3 && "Unexpected number of operands");
8833 SDLoc DL = getCurSDLoc();
8834 Value *PtrOperand = VPIntrin.getArgOperand(0);
8835 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8836 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8837 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
8838 SDValue LD;
8839 // Do not serialize variable-length loads of constant memory with
8840 // anything.
8841 if (!Alignment)
8842 Alignment = DAG.getEVTAlign(VT);
8843 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8844 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
8845 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8846 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8847 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8849 MMOMetadata(AAInfo, Ranges));
8850 LD = DAG.getLoadFFVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8851 MMO);
8852 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, EVLVT, LD.getValue(1));
8853 if (AddToChain)
8854 PendingLoads.push_back(LD.getValue(2));
8855 setValue(&VPIntrin, DAG.getMergeValues({LD.getValue(0), Trunc}, DL));
8856}
8857
8858void SelectionDAGBuilder::visitVPGather(
8859 const VPIntrinsic &VPIntrin, EVT VT,
8860 const SmallVectorImpl<SDValue> &OpValues) {
8861 SDLoc DL = getCurSDLoc();
8862 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8863 Value *PtrOperand = VPIntrin.getArgOperand(0);
8864 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8865 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8866 const MDNode *Ranges = getRangeMetadata(VPIntrin);
8867 SDValue LD;
8868 if (!Alignment)
8869 Alignment = DAG.getEVTAlign(VT.getScalarType());
8870 unsigned AS =
8871 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8872 MachineMemOperand::Flags MMOFlags =
8873 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8874 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8875 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
8876 *Alignment, MMOMetadata(AAInfo, Ranges));
8877 SDValue Base, Index, Scale;
8878 bool UniformBase =
8879 getUniformBase(PtrOperand, Base, Index, Scale, this, VPIntrin.getParent(),
8880 VT.getScalarStoreSize());
8881 if (!UniformBase) {
8882 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8883 Index = getValue(PtrOperand);
8884 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8885 }
8886 EVT IdxVT = Index.getValueType();
8887 EVT EltTy = IdxVT.getVectorElementType();
8888 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8889 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
8890 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8891 }
8892 LD = DAG.getGatherVP(
8893 DAG.getVTList(VT, MVT::Other), VT, DL,
8894 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8896 PendingLoads.push_back(LD.getValue(1));
8897 setValue(&VPIntrin, LD);
8898}
8899
8900void SelectionDAGBuilder::visitVPStore(
8901 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8902 SDLoc DL = getCurSDLoc();
8903 Value *PtrOperand = VPIntrin.getArgOperand(1);
8904 EVT VT = OpValues[0].getValueType();
8905 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8906 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8907 SDValue ST;
8908 if (!Alignment)
8909 Alignment = DAG.getEVTAlign(VT);
8910 SDValue Ptr = OpValues[1];
8911 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
8912 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8913 MachineMemOperand::Flags MMOFlags =
8914 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8915 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8916 MachinePointerInfo(PtrOperand), MMOFlags,
8917 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8918 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8919 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8920 /* IsTruncating */ false, /*IsCompressing*/ false);
8921 DAG.setRoot(ST);
8922 setValue(&VPIntrin, ST);
8923}
8924
8925void SelectionDAGBuilder::visitVPScatter(
8926 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8927 SDLoc DL = getCurSDLoc();
8928 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8929 Value *PtrOperand = VPIntrin.getArgOperand(1);
8930 EVT VT = OpValues[0].getValueType();
8931 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8932 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8933 SDValue ST;
8934 if (!Alignment)
8935 Alignment = DAG.getEVTAlign(VT.getScalarType());
8936 unsigned AS =
8937 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8938 MachineMemOperand::Flags MMOFlags =
8939 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8940 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8941 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
8942 *Alignment, AAInfo);
8943 SDValue Base, Index, Scale;
8944 bool UniformBase =
8945 getUniformBase(PtrOperand, Base, Index, Scale, this, VPIntrin.getParent(),
8946 VT.getScalarStoreSize());
8947 if (!UniformBase) {
8948 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8949 Index = getValue(PtrOperand);
8950 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8951 }
8952 EVT IdxVT = Index.getValueType();
8953 EVT EltTy = IdxVT.getVectorElementType();
8954 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8955 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
8956 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8957 }
8958 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8959 {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8960 OpValues[2], OpValues[3]},
8961 MMO, ISD::SIGNED_SCALED);
8962 DAG.setRoot(ST);
8963 setValue(&VPIntrin, ST);
8964}
8965
8966void SelectionDAGBuilder::visitVPStridedLoad(
8967 const VPIntrinsic &VPIntrin, EVT VT,
8968 const SmallVectorImpl<SDValue> &OpValues) {
8969 SDLoc DL = getCurSDLoc();
8970 Value *PtrOperand = VPIntrin.getArgOperand(0);
8971 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8972 if (!Alignment)
8973 Alignment = DAG.getEVTAlign(VT.getScalarType());
8974 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8975 const MDNode *Ranges = getRangeMetadata(VPIntrin);
8976 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8977 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
8978 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8979 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8980 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8981 MachineMemOperand::Flags MMOFlags =
8982 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
8983 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8984 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
8985 *Alignment, MMOMetadata(AAInfo, Ranges));
8986
8987 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8988 OpValues[2], OpValues[3], MMO,
8989 false /*IsExpanding*/);
8990
8991 if (AddToChain)
8992 PendingLoads.push_back(LD.getValue(1));
8993 setValue(&VPIntrin, LD);
8994}
8995
8996void SelectionDAGBuilder::visitVPStridedStore(
8997 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8998 SDLoc DL = getCurSDLoc();
8999 Value *PtrOperand = VPIntrin.getArgOperand(1);
9000 EVT VT = OpValues[0].getValueType();
9001 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9002 if (!Alignment)
9003 Alignment = DAG.getEVTAlign(VT.getScalarType());
9004 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9005 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9006 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9007 MachineMemOperand::Flags MMOFlags =
9008 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9009 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9010 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9011 *Alignment, AAInfo);
9012
9013 SDValue ST = DAG.getStridedStoreVP(
9014 getMemoryRoot(), DL, OpValues[0], OpValues[1],
9015 DAG.getPOISON(OpValues[1].getValueType()), OpValues[2], OpValues[3],
9016 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
9017 /*IsCompressing*/ false);
9018
9019 DAG.setRoot(ST);
9020 setValue(&VPIntrin, ST);
9021}
9022
9023void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
9024 const VPIntrinsic &VPIntrin) {
9025 SDLoc DL = getCurSDLoc();
9026 unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
9027
9028 auto IID = VPIntrin.getIntrinsicID();
9029
9030 SmallVector<EVT, 4> ValueVTs;
9031 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9032 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
9033 SDVTList VTs = DAG.getVTList(ValueVTs);
9034
9035 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
9036
9037 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
9038 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
9039 "Unexpected target EVL type");
9040
9041 // Request operands.
9042 SmallVector<SDValue, 7> OpValues;
9043 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
9044 auto Op = getValue(VPIntrin.getArgOperand(I));
9045 if (I == EVLParamPos)
9046 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
9047 OpValues.push_back(Op);
9048 }
9049
9050 switch (Opcode) {
9051 default: {
9052 SDNodeFlags SDFlags;
9053 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
9054 SDFlags.copyFMF(*FPMO);
9055 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
9056 setValue(&VPIntrin, Result);
9057 break;
9058 }
9059 case ISD::VP_LOAD:
9060 visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
9061 break;
9062 case ISD::VP_LOAD_FF:
9063 visitVPLoadFF(VPIntrin, ValueVTs[0], ValueVTs[1], OpValues);
9064 break;
9065 case ISD::VP_GATHER:
9066 visitVPGather(VPIntrin, ValueVTs[0], OpValues);
9067 break;
9068 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
9069 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
9070 break;
9071 case ISD::VP_STORE:
9072 visitVPStore(VPIntrin, OpValues);
9073 break;
9074 case ISD::VP_SCATTER:
9075 visitVPScatter(VPIntrin, OpValues);
9076 break;
9077 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
9078 visitVPStridedStore(VPIntrin, OpValues);
9079 break;
9080 case ISD::VP_CTTZ_ELTS_ZERO_POISON:
9081 case ISD::VP_CTTZ_ELTS: {
9082 SDValue Result =
9083 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
9084 setValue(&VPIntrin, Result);
9085 break;
9086 }
9087 }
9088}
9089
9091 const BasicBlock *EHPadBB,
9092 MCSymbol *&BeginLabel) {
9093 MachineFunction &MF = DAG.getMachineFunction();
9094
9095 // Insert a label before the invoke call to mark the try range. This can be
9096 // used to detect deletion of the invoke via the MachineModuleInfo.
9097 BeginLabel = MF.getContext().createTempSymbol();
9098
9099 // For SjLj, keep track of which landing pads go with which invokes
9100 // so as to maintain the ordering of pads in the LSDA.
9101 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
9102 if (CallSiteIndex) {
9103 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
9104 LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
9105
9106 // Now that the call site is handled, stop tracking it.
9107 FuncInfo.setCurrentCallSite(0);
9108 }
9109
9110 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
9111}
9112
9113SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
9114 const BasicBlock *EHPadBB,
9115 MCSymbol *BeginLabel) {
9116 assert(BeginLabel && "BeginLabel should've been set");
9117
9119
9120 // Insert a label at the end of the invoke call to mark the try range. This
9121 // can be used to detect deletion of the invoke via the MachineModuleInfo.
9122 MCSymbol *EndLabel = MF.getContext().createTempSymbol();
9123 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
9124
9125 // Inform MachineModuleInfo of range.
9127 // There is a platform (e.g. wasm) that uses funclet style IR but does not
9128 // actually use outlined funclets and their LSDA info style.
9129 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
9130 assert(II && "II should've been set");
9131 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
9132 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
9133 } else if (!isScopedEHPersonality(Pers)) {
9134 assert(EHPadBB);
9135 MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
9136 }
9137
9138 return Chain;
9139}
9140
9141std::pair<SDValue, SDValue>
9143 const BasicBlock *EHPadBB) {
9144 MCSymbol *BeginLabel = nullptr;
9145
9146 if (EHPadBB) {
9147 // Both PendingLoads and PendingExports must be flushed here;
9148 // this call might not return.
9149 (void)getRoot();
9150 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
9151 CLI.setChain(getRoot());
9152 }
9153
9154 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9155 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
9156
9157 assert((CLI.IsTailCall || Result.second.getNode()) &&
9158 "Non-null chain expected with non-tail call!");
9159 assert((Result.second.getNode() || !Result.first.getNode()) &&
9160 "Null value expected with tail call!");
9161
9162 if (!Result.second.getNode()) {
9163 // As a special case, a null chain means that a tail call has been emitted
9164 // and the DAG root is already updated.
9165 HasTailCall = true;
9166
9167 // Since there's no actual continuation from this block, nothing can be
9168 // relying on us setting vregs for them.
9169 PendingExports.clear();
9170 } else {
9171 DAG.setRoot(Result.second);
9172 }
9173
9174 if (EHPadBB) {
9175 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
9176 BeginLabel));
9177 Result.second = getRoot();
9178 }
9179
9180 return Result;
9181}
9182
9184 bool isMustTailCall = CB.isMustTailCall();
9185
9186 // Avoid emitting tail calls in functions with the disable-tail-calls
9187 // attribute.
9188 const Function *Caller = CB.getParent()->getParent();
9189 if (!isMustTailCall &&
9190 Caller->getFnAttribute("disable-tail-calls").getValueAsBool())
9191 return false;
9192
9193 // We can't tail call inside a function with a swifterror argument. Lowering
9194 // does not support this yet. It would have to move into the swifterror
9195 // register before the call.
9196 if (DAG.hasSwiftErrorArg())
9197 return false;
9198
9199 // Check if target-independent constraints permit a tail call here.
9200 // Target-dependent constraints are checked within TLI->LowerCallTo.
9201 return isInTailCallPosition(CB, DAG.getTarget());
9202}
9203
9205 bool isTailCall, bool isMustTailCall,
9206 const BasicBlock *EHPadBB,
9207 const TargetLowering::PtrAuthInfo *PAI) {
9208 auto &DL = DAG.getDataLayout();
9209 FunctionType *FTy = CB.getFunctionType();
9210 Type *RetTy = CB.getType();
9211
9213 Args.reserve(CB.arg_size());
9214
9215 const Value *SwiftErrorVal = nullptr;
9216 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9217
9218 if (isTailCall)
9219 isTailCall = canTailCall(CB);
9220
9221 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
9222 const Value *V = *I;
9223
9224 // Skip empty types
9225 if (V->getType()->isEmptyTy())
9226 continue;
9227
9228 SDValue ArgNode = getValue(V);
9229 TargetLowering::ArgListEntry Entry(ArgNode, V->getType());
9230 Entry.setAttributes(&CB, I - CB.arg_begin());
9231
9232 // Use swifterror virtual register as input to the call.
9233 if (Entry.IsSwiftError && TLI.supportSwiftError()) {
9234 SwiftErrorVal = V;
9235 // We find the virtual register for the actual swifterror argument.
9236 // Instead of using the Value, we use the virtual register instead.
9237 Entry.Node =
9238 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
9239 EVT(TLI.getPointerTy(DL)));
9240 }
9241
9242 Args.push_back(Entry);
9243
9244 // If we have an explicit sret argument that is an Instruction, (i.e., it
9245 // might point to function-local memory), we can't meaningfully tail-call.
9246 if (Entry.IsSRet && isa<Instruction>(V))
9247 isTailCall = false;
9248 }
9249
9250 // If call site has a cfguardtarget operand bundle, create and add an
9251 // additional ArgListEntry.
9252 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
9253 Value *V = Bundle->Inputs[0];
9255 Entry.IsCFGuardTarget = true;
9256 Args.push_back(Entry);
9257 }
9258
9259 // Disable tail calls if there is an swifterror argument. Targets have not
9260 // been updated to support tail calls.
9261 if (TLI.supportSwiftError() && SwiftErrorVal)
9262 isTailCall = false;
9263
9264 ConstantInt *CFIType = nullptr;
9265 if (CB.isIndirectCall()) {
9266 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
9267 if (!TLI.supportKCFIBundles())
9269 "Target doesn't support calls with kcfi operand bundles.");
9270 CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
9271 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
9272 }
9273 }
9274
9275 SDValue ConvControlToken;
9276 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
9277 auto *Token = Bundle->Inputs[0].get();
9278 ConvControlToken = getValue(Token);
9279 }
9280
9281 GlobalValue *DeactivationSymbol = nullptr;
9283 DeactivationSymbol = cast<GlobalValue>(Bundle->Inputs[0].get());
9284 }
9285
9288 .setChain(getRoot())
9289 .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
9290 .setTailCall(isTailCall)
9294 .setCFIType(CFIType)
9295 .setConvergenceControlToken(ConvControlToken)
9296 .setDeactivationSymbol(DeactivationSymbol);
9297
9298 // Set the pointer authentication info if we have it.
9299 if (PAI) {
9300 if (!TLI.supportPtrAuthBundles())
9302 "This target doesn't support calls with ptrauth operand bundles.");
9303 CLI.setPtrAuth(*PAI);
9304 }
9305
9306 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9307
9308 if (Result.first.getNode()) {
9309 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
9310 Result.first = lowerNoFPClassToAssertNoFPClass(DAG, CB, Result.first);
9311 setValue(&CB, Result.first);
9312 }
9313
9314 // The last element of CLI.InVals has the SDValue for swifterror return.
9315 // Here we copy it to a virtual register and update SwiftErrorMap for
9316 // book-keeping.
9317 if (SwiftErrorVal && TLI.supportSwiftError()) {
9318 // Get the last element of InVals.
9319 SDValue Src = CLI.InVals.back();
9320 Register VReg =
9321 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
9322 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
9323 DAG.setRoot(CopyNode);
9324 }
9325}
9326
9327static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
9328 SelectionDAGBuilder &Builder) {
9329 // Check to see if this load can be trivially constant folded, e.g. if the
9330 // input is from a string literal.
9331 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
9332 // Cast pointer to the type we really want to load.
9333 Type *LoadTy =
9334 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
9335 if (LoadVT.isVector())
9336 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
9337 if (const Constant *LoadCst =
9338 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
9339 LoadTy, Builder.DAG.getDataLayout()))
9340 return Builder.getValue(LoadCst);
9341 }
9342
9343 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
9344 // still constant memory, the input chain can be the entry node.
9345 SDValue Root;
9346 bool ConstantMemory = false;
9347
9348 // Do not serialize (non-volatile) loads of constant memory with anything.
9349 if (Builder.BatchAA && Builder.BatchAA->pointsToConstantMemory(PtrVal)) {
9350 Root = Builder.DAG.getEntryNode();
9351 ConstantMemory = true;
9352 } else {
9353 // Do not serialize non-volatile loads against each other.
9354 Root = Builder.DAG.getRoot();
9355 }
9356
9357 SDValue Ptr = Builder.getValue(PtrVal);
9358 SDValue LoadVal =
9359 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
9360 MachinePointerInfo(PtrVal), Align(1));
9361
9362 if (!ConstantMemory)
9363 Builder.PendingLoads.push_back(LoadVal.getValue(1));
9364 return LoadVal;
9365}
9366
9367/// Record the value for an instruction that produces an integer result,
9368/// converting the type where necessary.
9369void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
9370 SDValue Value,
9371 bool IsSigned) {
9372 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9373 I.getType(), true);
9374 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
9375 setValue(&I, Value);
9376}
9377
9378/// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
9379/// true and lower it. Otherwise return false, and it will be lowered like a
9380/// normal call.
9381/// The caller already checked that \p I calls the appropriate LibFunc with a
9382/// correct prototype.
9383bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
9384 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
9385 const Value *Size = I.getArgOperand(2);
9386 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
9387 if (CSize && CSize->getZExtValue() == 0) {
9388 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9389 I.getType(), true);
9390 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
9391 return true;
9392 }
9393
9394 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9395 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9396 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
9397 getValue(Size), &I);
9398 if (Res.first.getNode()) {
9399 processIntegerCallValue(I, Res.first, true);
9400 PendingLoads.push_back(Res.second);
9401 return true;
9402 }
9403
9404 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
9405 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
9406 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
9407 return false;
9408
9409 // If the target has a fast compare for the given size, it will return a
9410 // preferred load type for that size. Require that the load VT is legal and
9411 // that the target supports unaligned loads of that type. Otherwise, return
9412 // INVALID.
9413 auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9414 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9415 MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9416 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9417 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9418 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9419 // TODO: Check alignment of src and dest ptrs.
9420 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9421 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9422 if (!TLI.isTypeLegal(LVT) ||
9423 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
9424 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
9426 }
9427
9428 return LVT;
9429 };
9430
9431 // This turns into unaligned loads. We only do this if the target natively
9432 // supports the MVT we'll be loading or if it is small enough (<= 4) that
9433 // we'll only produce a small number of byte loads.
9434 MVT LoadVT;
9435 unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9436 switch (NumBitsToCompare) {
9437 default:
9438 return false;
9439 case 16:
9440 LoadVT = MVT::i16;
9441 break;
9442 case 32:
9443 LoadVT = MVT::i32;
9444 break;
9445 case 64:
9446 case 128:
9447 case 256:
9448 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9449 break;
9450 }
9451
9452 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9453 return false;
9454
9455 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9456 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9457
9458 // Bitcast to a wide integer type if the loads are vectors.
9459 if (LoadVT.isVector()) {
9460 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9461 LoadL = DAG.getBitcast(CmpVT, LoadL);
9462 LoadR = DAG.getBitcast(CmpVT, LoadR);
9463 }
9464
9465 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9466 processIntegerCallValue(I, Cmp, false);
9467 return true;
9468}
9469
9470/// See if we can lower a memchr call into an optimized form. If so, return
9471/// true and lower it. Otherwise return false, and it will be lowered like a
9472/// normal call.
9473/// The caller already checked that \p I calls the appropriate LibFunc with a
9474/// correct prototype.
9475bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9476 const Value *Src = I.getArgOperand(0);
9477 const Value *Char = I.getArgOperand(1);
9478 const Value *Length = I.getArgOperand(2);
9479
9480 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9481 std::pair<SDValue, SDValue> Res =
9482 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9483 getValue(Src), getValue(Char), getValue(Length),
9484 MachinePointerInfo(Src));
9485 if (Res.first.getNode()) {
9486 setValue(&I, Res.first);
9487 PendingLoads.push_back(Res.second);
9488 return true;
9489 }
9490
9491 return false;
9492}
9493
9494/// See if we can lower a memccpy call into an optimized form. If so, return
9495/// true and lower it, otherwise return false and it will be lowered like a
9496/// normal call.
9497/// The caller already checked that \p I calls the appropriate LibFunc with a
9498/// correct prototype.
9499bool SelectionDAGBuilder::visitMemCCpyCall(const CallInst &I) {
9500 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9501 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemccpy(
9502 DAG, getCurSDLoc(), DAG.getRoot(), getValue(I.getArgOperand(0)),
9503 getValue(I.getArgOperand(1)), getValue(I.getArgOperand(2)),
9504 getValue(I.getArgOperand(3)), &I);
9505
9506 if (Res.first) {
9507 processIntegerCallValue(I, Res.first, true);
9508 PendingLoads.push_back(Res.second);
9509 return true;
9510 }
9511 return false;
9512}
9513
9514/// See if we can lower a mempcpy call into an optimized form. If so, return
9515/// true and lower it. Otherwise return false, and it will be lowered like a
9516/// normal call.
9517/// The caller already checked that \p I calls the appropriate LibFunc with a
9518/// correct prototype.
9519bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9520 SDValue Dst = getValue(I.getArgOperand(0));
9521 SDValue Src = getValue(I.getArgOperand(1));
9522 SDValue Size = getValue(I.getArgOperand(2));
9523
9524 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9525 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9526
9527 SDLoc sdl = getCurSDLoc();
9528
9529 // In the mempcpy context we need to pass in a false value for isTailCall
9530 // because the return pointer needs to be adjusted by the size of
9531 // the copied memory.
9532 SDValue Root = getMemoryRoot();
9533 SDValue MC = DAG.getMemcpy(
9534 Root, sdl, Dst, Src, Size, DstAlign, SrcAlign, false, false,
9535 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9536 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9537 assert(MC.getNode() != nullptr &&
9538 "** memcpy should not be lowered as TailCall in mempcpy context **");
9539 DAG.setRoot(MC);
9540
9541 // Check if Size needs to be truncated or extended.
9542 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9543
9544 // Adjust return pointer to point just past the last dst byte.
9545 SDValue DstPlusSize = DAG.getMemBasePlusOffset(Dst, Size, sdl);
9546 setValue(&I, DstPlusSize);
9547 return true;
9548}
9549
9550/// See if we can lower a strcpy call into an optimized form. If so, return
9551/// true and lower it, otherwise return false and it will be lowered like a
9552/// normal call.
9553/// The caller already checked that \p I calls the appropriate LibFunc with a
9554/// correct prototype.
9555bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9556 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9557
9558 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9559 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcpy(
9560 DAG, getCurSDLoc(), getRoot(), getValue(Arg0), getValue(Arg1),
9561 MachinePointerInfo(Arg0), MachinePointerInfo(Arg1), isStpcpy, &I);
9562 if (Res.first.getNode()) {
9563 setValue(&I, Res.first);
9564 DAG.setRoot(Res.second);
9565 return true;
9566 }
9567
9568 return false;
9569}
9570
9571/// See if we can lower a strcmp call into an optimized form. If so, return
9572/// true and lower it, otherwise return false and it will be lowered like a
9573/// normal call.
9574/// The caller already checked that \p I calls the appropriate LibFunc with a
9575/// correct prototype.
9576bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9577 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9578
9579 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9580 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcmp(
9581 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), getValue(Arg1),
9582 MachinePointerInfo(Arg0), MachinePointerInfo(Arg1), &I);
9583 if (Res.first.getNode()) {
9584 processIntegerCallValue(I, Res.first, true);
9585 PendingLoads.push_back(Res.second);
9586 return true;
9587 }
9588
9589 return false;
9590}
9591
9592/// See if we can lower a strlen call into an optimized form. If so, return
9593/// true and lower it, otherwise return false and it will be lowered like a
9594/// normal call.
9595/// The caller already checked that \p I calls the appropriate LibFunc with a
9596/// correct prototype.
9597bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9598 const Value *Arg0 = I.getArgOperand(0);
9599
9600 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9601 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrlen(
9602 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), &I);
9603 if (Res.first.getNode()) {
9604 processIntegerCallValue(I, Res.first, false);
9605 PendingLoads.push_back(Res.second);
9606 return true;
9607 }
9608
9609 return false;
9610}
9611
9612/// See if we can lower a strnlen call into an optimized form. If so, return
9613/// true and lower it, otherwise return false and it will be lowered like a
9614/// normal call.
9615/// The caller already checked that \p I calls the appropriate LibFunc with a
9616/// correct prototype.
9617bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9618 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9619
9620 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9621 std::pair<SDValue, SDValue> Res =
9622 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9623 getValue(Arg0), getValue(Arg1),
9624 MachinePointerInfo(Arg0));
9625 if (Res.first.getNode()) {
9626 processIntegerCallValue(I, Res.first, false);
9627 PendingLoads.push_back(Res.second);
9628 return true;
9629 }
9630
9631 return false;
9632}
9633
9634/// See if we can lower a Strstr call into an optimized form. If so, return
9635/// true and lower it, otherwise return false and it will be lowered like a
9636/// normal call.
9637/// The caller already checked that \p I calls the appropriate LibFunc with a
9638/// correct prototype.
9639bool SelectionDAGBuilder::visitStrstrCall(const CallInst &I) {
9640 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9641 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9642 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrstr(
9643 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), getValue(Arg1), &I);
9644 if (Res.first) {
9645 processIntegerCallValue(I, Res.first, false);
9646 PendingLoads.push_back(Res.second);
9647 return true;
9648 }
9649 return false;
9650}
9651
9652/// See if we can lower a unary floating-point operation into an SDNode with
9653/// the specified Opcode. If so, return true and lower it, otherwise return
9654/// false and it will be lowered like a normal call.
9655/// The caller already checked that \p I calls the appropriate LibFunc with a
9656/// correct prototype.
9657bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9658 unsigned Opcode) {
9659 // We already checked this call's prototype; verify it doesn't modify errno.
9660 // Do not perform optimizations for call sites that require strict
9661 // floating-point semantics.
9662 if (!I.onlyReadsMemory() || I.isStrictFP())
9663 return false;
9664
9665 SDNodeFlags Flags;
9666 Flags.copyFMF(cast<FPMathOperator>(I));
9667
9668 SDValue Tmp = getValue(I.getArgOperand(0));
9669 setValue(&I,
9670 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9671 return true;
9672}
9673
9674/// See if we can lower a binary floating-point operation into an SDNode with
9675/// the specified Opcode. If so, return true and lower it. Otherwise return
9676/// false, and it will be lowered like a normal call.
9677/// The caller already checked that \p I calls the appropriate LibFunc with a
9678/// correct prototype.
9679bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9680 unsigned Opcode) {
9681 // We already checked this call's prototype; verify it doesn't modify errno.
9682 // Do not perform optimizations for call sites that require strict
9683 // floating-point semantics.
9684 if (!I.onlyReadsMemory() || I.isStrictFP())
9685 return false;
9686
9687 SDNodeFlags Flags;
9688 Flags.copyFMF(cast<FPMathOperator>(I));
9689
9690 SDValue Tmp0 = getValue(I.getArgOperand(0));
9691 SDValue Tmp1 = getValue(I.getArgOperand(1));
9692 EVT VT = Tmp0.getValueType();
9693 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9694 return true;
9695}
9696
9697void SelectionDAGBuilder::visitCall(const CallInst &I) {
9698 // Handle inline assembly differently.
9699 if (I.isInlineAsm()) {
9700 visitInlineAsm(I);
9701 return;
9702 }
9703
9705
9706 if (Function *F = I.getCalledFunction()) {
9707 if (F->isDeclaration()) {
9708 // Is this an LLVM intrinsic?
9709 if (unsigned IID = F->getIntrinsicID()) {
9710 visitIntrinsicCall(I, IID);
9711 return;
9712 }
9713 }
9714
9715 // Check for well-known libc/libm calls. If the function is internal, it
9716 // can't be a library call. Don't do the check if marked as nobuiltin for
9717 // some reason.
9718 // This code should not handle libcalls that are already canonicalized to
9719 // intrinsics by the middle-end.
9720 LibFunc Func = !I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName()
9721 ? LibInfo->getLibFunc(*F)
9722 : NotLibFunc;
9723 if (LibInfo->hasOptimizedCodeGen(Func)) {
9724 switch (Func) {
9725 default: break;
9726 case LibFunc_bcmp:
9727 if (visitMemCmpBCmpCall(I))
9728 return;
9729 break;
9730 case LibFunc_copysign:
9731 case LibFunc_copysignf:
9732 case LibFunc_copysignl:
9733 // We already checked this call's prototype; verify it doesn't modify
9734 // errno.
9735 if (I.onlyReadsMemory()) {
9736 SDValue LHS = getValue(I.getArgOperand(0));
9737 SDValue RHS = getValue(I.getArgOperand(1));
9739 LHS.getValueType(), LHS, RHS));
9740 return;
9741 }
9742 break;
9743 case LibFunc_sin:
9744 case LibFunc_sinf:
9745 case LibFunc_sinl:
9746 if (visitUnaryFloatCall(I, ISD::FSIN))
9747 return;
9748 break;
9749 case LibFunc_cos:
9750 case LibFunc_cosf:
9751 case LibFunc_cosl:
9752 if (visitUnaryFloatCall(I, ISD::FCOS))
9753 return;
9754 break;
9755 case LibFunc_tan:
9756 case LibFunc_tanf:
9757 case LibFunc_tanl:
9758 if (visitUnaryFloatCall(I, ISD::FTAN))
9759 return;
9760 break;
9761 case LibFunc_asin:
9762 case LibFunc_asinf:
9763 case LibFunc_asinl:
9764 if (visitUnaryFloatCall(I, ISD::FASIN))
9765 return;
9766 break;
9767 case LibFunc_acos:
9768 case LibFunc_acosf:
9769 case LibFunc_acosl:
9770 if (visitUnaryFloatCall(I, ISD::FACOS))
9771 return;
9772 break;
9773 case LibFunc_atan:
9774 case LibFunc_atanf:
9775 case LibFunc_atanl:
9776 if (visitUnaryFloatCall(I, ISD::FATAN))
9777 return;
9778 break;
9779 case LibFunc_atan2:
9780 case LibFunc_atan2f:
9781 case LibFunc_atan2l:
9782 if (visitBinaryFloatCall(I, ISD::FATAN2))
9783 return;
9784 break;
9785 case LibFunc_sinh:
9786 case LibFunc_sinhf:
9787 case LibFunc_sinhl:
9788 if (visitUnaryFloatCall(I, ISD::FSINH))
9789 return;
9790 break;
9791 case LibFunc_cosh:
9792 case LibFunc_coshf:
9793 case LibFunc_coshl:
9794 if (visitUnaryFloatCall(I, ISD::FCOSH))
9795 return;
9796 break;
9797 case LibFunc_tanh:
9798 case LibFunc_tanhf:
9799 case LibFunc_tanhl:
9800 if (visitUnaryFloatCall(I, ISD::FTANH))
9801 return;
9802 break;
9803 case LibFunc_sqrt:
9804 case LibFunc_sqrtf:
9805 case LibFunc_sqrtl:
9806 case LibFunc_sqrt_finite:
9807 case LibFunc_sqrtf_finite:
9808 case LibFunc_sqrtl_finite:
9809 if (visitUnaryFloatCall(I, ISD::FSQRT))
9810 return;
9811 break;
9812 case LibFunc_log2:
9813 case LibFunc_log2f:
9814 case LibFunc_log2l:
9815 if (visitUnaryFloatCall(I, ISD::FLOG2))
9816 return;
9817 break;
9818 case LibFunc_exp2:
9819 case LibFunc_exp2f:
9820 case LibFunc_exp2l:
9821 if (visitUnaryFloatCall(I, ISD::FEXP2))
9822 return;
9823 break;
9824 case LibFunc_exp10:
9825 case LibFunc_exp10f:
9826 case LibFunc_exp10l:
9827 if (visitUnaryFloatCall(I, ISD::FEXP10))
9828 return;
9829 break;
9830 case LibFunc_ldexp:
9831 case LibFunc_ldexpf:
9832 case LibFunc_ldexpl:
9833 if (visitBinaryFloatCall(I, ISD::FLDEXP))
9834 return;
9835 break;
9836 case LibFunc_strstr:
9837 if (visitStrstrCall(I))
9838 return;
9839 break;
9840 case LibFunc_memcmp:
9841 if (visitMemCmpBCmpCall(I))
9842 return;
9843 break;
9844 case LibFunc_memccpy:
9845 if (visitMemCCpyCall(I))
9846 return;
9847 break;
9848 case LibFunc_mempcpy:
9849 if (visitMemPCpyCall(I))
9850 return;
9851 break;
9852 case LibFunc_memchr:
9853 if (visitMemChrCall(I))
9854 return;
9855 break;
9856 case LibFunc_strcpy:
9857 if (visitStrCpyCall(I, false))
9858 return;
9859 break;
9860 case LibFunc_stpcpy:
9861 if (visitStrCpyCall(I, true))
9862 return;
9863 break;
9864 case LibFunc_strcmp:
9865 if (visitStrCmpCall(I))
9866 return;
9867 break;
9868 case LibFunc_strlen:
9869 if (visitStrLenCall(I))
9870 return;
9871 break;
9872 case LibFunc_strnlen:
9873 if (visitStrNLenCall(I))
9874 return;
9875 break;
9876 }
9877 }
9878 }
9879
9880 if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9881 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9882 return;
9883 }
9884
9885 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9886 // have to do anything here to lower funclet bundles.
9887 // CFGuardTarget bundles are lowered in LowerCallTo.
9889 I, "calls",
9894
9895 SDValue Callee = getValue(I.getCalledOperand());
9896
9897 if (I.hasDeoptState())
9898 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9899 else
9900 // Check if we can potentially perform a tail call. More detailed checking
9901 // is be done within LowerCallTo, after more information about the call is
9902 // known.
9903 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9904}
9905
9907 const CallBase &CB, const BasicBlock *EHPadBB) {
9908 auto PAB = CB.getOperandBundle("ptrauth");
9909 const Value *CalleeV = CB.getCalledOperand();
9910
9911 // Gather the call ptrauth data from the operand bundle:
9912 // [ i32 <key>, i64 <discriminator> ]
9913 const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9914 const Value *Discriminator = PAB->Inputs[1];
9915
9916 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9917 assert(Discriminator->getType()->isIntegerTy(64) &&
9918 "Invalid ptrauth discriminator");
9919
9920 // Look through ptrauth constants to find the raw callee.
9921 // Do a direct unauthenticated call if we found it and everything matches.
9922 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
9923 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9924 DAG.getDataLayout()))
9925 return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
9926 CB.isMustTailCall(), EHPadBB);
9927
9928 // Functions should never be ptrauth-called directly.
9929 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9930
9931 // Otherwise, do an authenticated indirect call.
9932 TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9933 getValue(Discriminator)};
9934
9935 LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9936 EHPadBB, &PAI);
9937}
9938
9939namespace {
9940
9941/// AsmOperandInfo - This contains information for each constraint that we are
9942/// lowering.
9943class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9944public:
9945 /// CallOperand - If this is the result output operand or a clobber
9946 /// this is null, otherwise it is the incoming operand to the CallInst.
9947 /// This gets modified as the asm is processed.
9948 SDValue CallOperand;
9949
9950 /// AssignedRegs - If this is a register or register class operand, this
9951 /// contains the set of register corresponding to the operand.
9952 RegsForValue AssignedRegs;
9953
9954 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9955 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9956 }
9957
9958 /// Whether or not this operand accesses memory
9959 bool hasMemory(const TargetLowering &TLI) const {
9960 // Indirect operand accesses access memory.
9961 if (isIndirect)
9962 return true;
9963
9964 for (const auto &Code : Codes)
9966 return true;
9967
9968 return false;
9969 }
9970};
9971
9972
9973} // end anonymous namespace
9974
9975/// Make sure that the output operand \p OpInfo and its corresponding input
9976/// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9977/// out).
9978static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9979 SDISelAsmOperandInfo &MatchingOpInfo,
9980 SelectionDAG &DAG) {
9981 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9982 return;
9983
9985 const auto &TLI = DAG.getTargetLoweringInfo();
9986
9987 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9988 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9989 OpInfo.ConstraintVT);
9990 std::pair<unsigned, const TargetRegisterClass *> InputRC =
9991 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9992 MatchingOpInfo.ConstraintVT);
9993 const bool OutOpIsIntOrFP =
9994 OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
9995 const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
9996 MatchingOpInfo.ConstraintVT.isFloatingPoint();
9997 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
9998 // FIXME: error out in a more elegant fashion
9999 report_fatal_error("Unsupported asm: input constraint"
10000 " with a matching output constraint of"
10001 " incompatible type!");
10002 }
10003 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
10004}
10005
10006/// Get a direct memory input to behave well as an indirect operand.
10007/// This may introduce stores, hence the need for a \p Chain.
10008/// \return The (possibly updated) chain.
10009static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
10010 SDISelAsmOperandInfo &OpInfo,
10011 SelectionDAG &DAG) {
10012 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10013
10014 // If we don't have an indirect input, put it in the constpool if we can,
10015 // otherwise spill it to a stack slot.
10016 // TODO: This isn't quite right. We need to handle these according to
10017 // the addressing mode that the constraint wants. Also, this may take
10018 // an additional register for the computation and we don't want that
10019 // either.
10020
10021 // If the operand is a float, integer, or vector constant, spill to a
10022 // constant pool entry to get its address.
10023 const Value *OpVal = OpInfo.CallOperandVal;
10024 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
10026 OpInfo.CallOperand = DAG.getConstantPool(
10027 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
10028 return Chain;
10029 }
10030
10031 // Otherwise, create a stack slot and emit a store to it before the asm.
10032 Type *Ty = OpVal->getType();
10033 auto &DL = DAG.getDataLayout();
10034 TypeSize TySize = DL.getTypeAllocSize(Ty);
10037 int StackID = 0;
10038 if (TySize.isScalable())
10039 StackID = TFI->getStackIDForScalableVectors();
10040 int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
10041 DL.getPrefTypeAlign(Ty), false,
10042 nullptr, StackID);
10043 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
10044 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
10046 TLI.getMemValueType(DL, Ty));
10047 OpInfo.CallOperand = StackSlot;
10048
10049 return Chain;
10050}
10051
10052/// GetRegistersForValue - Assign registers (virtual or physical) for the
10053/// specified operand. We prefer to assign virtual registers, to allow the
10054/// register allocator to handle the assignment process. However, if the asm
10055/// uses features that we can't model on machineinstrs, we have SDISel do the
10056/// allocation. This produces generally horrible, but correct, code.
10057///
10058/// OpInfo describes the operand
10059/// RefOpInfo describes the matching operand if any, the operand otherwise
10060static std::optional<unsigned>
10062 SDISelAsmOperandInfo &OpInfo,
10063 SDISelAsmOperandInfo &RefOpInfo) {
10064 LLVMContext &Context = *DAG.getContext();
10065 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10066
10070
10071 // No work to do for memory/address operands.
10072 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
10073 OpInfo.ConstraintType == TargetLowering::C_Address)
10074 return std::nullopt;
10075
10076 // If this is a constraint for a single physreg, or a constraint for a
10077 // register class, find it.
10078 unsigned AssignedReg;
10079 const TargetRegisterClass *RC;
10080 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
10081 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
10082 // RC is unset only on failure. Return immediately.
10083 if (!RC)
10084 return std::nullopt;
10085
10086 // Get the actual register value type. This is important, because the user
10087 // may have asked for (e.g.) the AX register in i32 type. We need to
10088 // remember that AX is actually i16 to get the right extension.
10089 const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
10090
10091 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
10092 // If this is an FP operand in an integer register (or visa versa), or more
10093 // generally if the operand value disagrees with the register class we plan
10094 // to stick it in, fix the operand type.
10095 //
10096 // If this is an input value, the bitcast to the new type is done now.
10097 // Bitcast for output value is done at the end of visitInlineAsm().
10098 if ((OpInfo.Type == InlineAsm::isOutput ||
10099 OpInfo.Type == InlineAsm::isInput) &&
10100 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
10101 // Try to convert to the first EVT that the reg class contains. If the
10102 // types are identical size, use a bitcast to convert (e.g. two differing
10103 // vector types). Note: output bitcast is done at the end of
10104 // visitInlineAsm().
10105 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
10106 // Exclude indirect inputs while they are unsupported because the code
10107 // to perform the load is missing and thus OpInfo.CallOperand still
10108 // refers to the input address rather than the pointed-to value.
10109 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
10110 OpInfo.CallOperand =
10111 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
10112 OpInfo.ConstraintVT = RegVT;
10113 // If the operand is an FP value and we want it in integer registers,
10114 // use the corresponding integer type. This turns an f64 value into
10115 // i64, which can be passed with two i32 values on a 32-bit machine.
10116 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
10117 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
10118 if (OpInfo.Type == InlineAsm::isInput)
10119 OpInfo.CallOperand =
10120 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
10121 OpInfo.ConstraintVT = VT;
10122 }
10123 }
10124 }
10125
10126 // No need to allocate a matching input constraint since the constraint it's
10127 // matching to has already been allocated.
10128 if (OpInfo.isMatchingInputConstraint())
10129 return std::nullopt;
10130
10131 EVT ValueVT = OpInfo.ConstraintVT;
10132 if (OpInfo.ConstraintVT == MVT::Other)
10133 ValueVT = RegVT;
10134
10135 // Initialize NumRegs.
10136 unsigned NumRegs = 1;
10137 if (OpInfo.ConstraintVT != MVT::Other)
10138 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
10139
10140 // If this is a constraint for a specific physical register, like {r17},
10141 // assign it now.
10142
10143 // If this associated to a specific register, initialize iterator to correct
10144 // place. If virtual, make sure we have enough registers
10145
10146 // Initialize iterator if necessary
10149
10150 // Do not check for single registers.
10151 if (AssignedReg) {
10152 I = std::find(I, RC->end(), AssignedReg);
10153 if (I == RC->end()) {
10154 // RC does not contain the selected register, which indicates a
10155 // mismatch between the register and the required type/bitwidth.
10156 return {AssignedReg};
10157 }
10158 }
10159
10160 for (; NumRegs; --NumRegs, ++I) {
10161 assert(I != RC->end() && "Ran out of registers to allocate!");
10162 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
10163 Regs.push_back(R);
10164 }
10165
10166 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
10167 return std::nullopt;
10168}
10169
10170static unsigned
10172 const std::vector<SDValue> &AsmNodeOperands) {
10173 // Scan until we find the definition we already emitted of this operand.
10174 unsigned CurOp = InlineAsm::Op_FirstOperand;
10175 for (; OperandNo; --OperandNo) {
10176 // Advance to the next operand.
10177 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
10178 const InlineAsm::Flag F(OpFlag);
10179 assert(
10180 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
10181 "Skipped past definitions?");
10182 CurOp += F.getNumOperandRegisters() + 1;
10183 }
10184 return CurOp;
10185}
10186
10187namespace {
10188
10189class ExtraFlags {
10190 unsigned Flags = 0;
10191
10192public:
10193 explicit ExtraFlags(const CallBase &Call) {
10194 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
10195 if (IA->hasSideEffects())
10197 if (IA->isAlignStack())
10199 if (IA->canThrow())
10201 if (Call.isConvergent())
10203 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
10204 }
10205
10206 void update(const TargetLowering::AsmOperandInfo &OpInfo) {
10207 // Ideally, we would only check against memory constraints. However, the
10208 // meaning of an Other constraint can be target-specific and we can't easily
10209 // reason about it. Therefore, be conservative and set MayLoad/MayStore
10210 // for Other constraints as well.
10213 if (OpInfo.Type == InlineAsm::isInput)
10215 else if (OpInfo.Type == InlineAsm::isOutput)
10217 else if (OpInfo.Type == InlineAsm::isClobber)
10219 }
10220 }
10221
10222 unsigned get() const { return Flags; }
10223};
10224
10225} // end anonymous namespace
10226
10227static bool isFunction(SDValue Op) {
10228 if (Op && Op.getOpcode() == ISD::GlobalAddress) {
10229 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10230 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
10231
10232 // In normal "call dllimport func" instruction (non-inlineasm) it force
10233 // indirect access by specifing call opcode. And usually specially print
10234 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
10235 // not do in this way now. (In fact, this is similar with "Data Access"
10236 // action). So here we ignore dllimport function.
10237 if (Fn && !Fn->hasDLLImportStorageClass())
10238 return true;
10239 }
10240 }
10241 return false;
10242}
10243
10244namespace {
10245
10246struct ConstraintDecisionInfo {
10247 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
10248 std::vector<SDValue> AsmNodeOperands;
10249 SDValue Glue, Chain;
10250 bool HasSideEffect = false;
10251 MCSymbol *BeginLabel = nullptr;
10252
10253 SmallVector<char> Buffer;
10254 raw_svector_ostream ErrorMsg;
10255
10256 ConstraintDecisionInfo() : ErrorMsg(Buffer) {}
10257};
10258
10259} // end anonymous namespace
10260
10261/// Construct operand info objects.
10262static bool
10263constructOperandInfo(ConstraintDecisionInfo &Info,
10264 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10265 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10266 ExtraFlags &ExtraInfo) {
10267 for (auto &T : TargetConstraints) {
10268 Info.ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
10269 SDISelAsmOperandInfo &OpInfo = Info.ConstraintOperands.back();
10270
10271 if (OpInfo.CallOperandVal)
10272 OpInfo.CallOperand = Builder.getValue(OpInfo.CallOperandVal);
10273
10274 if (!Info.HasSideEffect)
10275 Info.HasSideEffect = OpInfo.hasMemory(TLI);
10276
10277 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
10278 // FIXME: Could we compute this on OpInfo rather than T?
10279
10280 // Compute the constraint code and ConstraintType to use.
10282
10283 if (T.ConstraintType == TargetLowering::C_Immediate && OpInfo.CallOperand &&
10284 !isa<ConstantSDNode>(OpInfo.CallOperand)) {
10285 // We've delayed emitting a diagnostic like the "n" constraint because
10286 // inlining could cause an integer showing up.
10287 Info.ErrorMsg << "constraint '" << T.ConstraintCode
10288 << "' expects an integer constant expression";
10289 return true;
10290 }
10291
10292 ExtraInfo.update(T);
10293 }
10294
10295 return false;
10296}
10297
10298/// Compute which constraint option to use for each operand.
10299static void
10300computeConstraintToUse(ConstraintDecisionInfo &Info, const CallBase &Call,
10301 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10302 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10303 const TargetMachine &TM, SelectionDAG &DAG) {
10304 const auto *IA = cast<InlineAsm>(Call.getCalledOperand());
10306 IA->collectAsmStrs(AsmStrs);
10307
10308 int OpNo = -1;
10309 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10310 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
10311 OpNo++;
10312
10313 // If this is an output operand with a matching input operand, look up the
10314 // matching input. If their types mismatch, e.g. one is an integer, the
10315 // other is floating point, or their sizes are different, flag it as an
10316 // error.
10317 if (OpInfo.hasMatchingInput()) {
10318 SDISelAsmOperandInfo &Input =
10319 Info.ConstraintOperands[OpInfo.MatchingInput];
10320 patchMatchingInput(OpInfo, Input, DAG);
10321 }
10322
10323 // Compute the constraint code and ConstraintType to use.
10324 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
10325
10326 if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
10327 OpInfo.Type == InlineAsm::isClobber) ||
10328 OpInfo.ConstraintType == TargetLowering::C_Address)
10329 continue;
10330
10331 // In Linux PIC model, there are 4 cases about value/label addressing:
10332 //
10333 // 1: Function call or Label jmp inside the module.
10334 // 2: Data access (such as global variable, static variable) inside module.
10335 // 3: Function call or Label jmp outside the module.
10336 // 4: Data access (such as global variable) outside the module.
10337 //
10338 // Due to current llvm inline asm architecture designed to not "recognize"
10339 // the asm code, there are quite troubles for us to treat mem addressing
10340 // differently for same value/adress used in different instuctions.
10341 // For example, in pic model, call a func may in plt way or direclty
10342 // pc-related, but lea/mov a function adress may use got.
10343 //
10344 // Here we try to "recognize" function call for the case 1 and case 3 in
10345 // inline asm. And try to adjust the constraint for them.
10346 //
10347 // TODO: Due to current inline asm didn't encourage to jmp to the outsider
10348 // label, so here we don't handle jmp function label now, but we need to
10349 // enhance it (especilly in PIC model) if we meet meaningful requirements.
10350 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
10351 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
10353 OpInfo.isIndirect = false;
10354 OpInfo.ConstraintType = TargetLowering::C_Address;
10355 }
10356
10357 // If this is a memory input, and if the operand is not indirect, do what we
10358 // need to provide an address for the memory input.
10359 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
10360 !OpInfo.isIndirect) {
10361 assert((OpInfo.isMultipleAlternative ||
10362 (OpInfo.Type == InlineAsm::isInput)) &&
10363 "Can only indirectify direct input operands!");
10364
10365 // Memory operands really want the address of the value.
10366 Info.Chain = getAddressForMemoryInput(Info.Chain, Builder.getCurSDLoc(),
10367 OpInfo, DAG);
10368
10369 // There is no longer a Value* corresponding to this operand.
10370 OpInfo.CallOperandVal = nullptr;
10371
10372 // It is now an indirect operand.
10373 OpInfo.isIndirect = true;
10374 }
10375 }
10376}
10377
10378/// Prepare DAG-level operands. As part of this, assign virtual and physical
10379/// registers for inputs and output.
10380static bool prepareDAGLevelOperands(ConstraintDecisionInfo &Info,
10381 const CallBase &Call,
10382 SelectionDAGBuilder &Builder,
10383 const TargetLowering &TLI,
10384 SelectionDAG &DAG) {
10385 SDLoc DL = Builder.getCurSDLoc();
10386 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10387 // Assign Registers.
10388 SDISelAsmOperandInfo &RefOpInfo =
10389 OpInfo.isMatchingInputConstraint()
10390 ? Info.ConstraintOperands[OpInfo.getMatchedOperand()]
10391 : OpInfo;
10392 const auto RegError = getRegistersForValue(DAG, DL, OpInfo, RefOpInfo);
10393 if (RegError) {
10394 const MachineFunction &MF = DAG.getMachineFunction();
10396 const char *RegName = TRI.getName(*RegError);
10397 Info.ErrorMsg << "register '" << RegName << "' allocated for constraint '"
10398 << OpInfo.ConstraintCode
10399 << "' does not match required type";
10400 return true;
10401 }
10402
10403 auto DetectWriteToReservedRegister = [&]() {
10404 const MachineFunction &MF = DAG.getMachineFunction();
10406
10407 for (Register Reg : OpInfo.AssignedRegs.Regs) {
10408 if (Reg.isPhysical() && TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
10409 Info.ErrorMsg << "write to reserved register '"
10410 << TRI.getRegAsmName(Reg) << "'";
10411 return true;
10412 }
10413 }
10414
10415 return false;
10416 };
10417 assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10418 (OpInfo.Type == InlineAsm::isInput &&
10419 !OpInfo.isMatchingInputConstraint())) &&
10420 "Only address as input operand is allowed.");
10421
10422 switch (OpInfo.Type) {
10424 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10425 const InlineAsm::ConstraintCode ConstraintID =
10426 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10428 "Failed to convert memory constraint code to constraint id.");
10429
10430 // Add information to the INLINEASM node to know about this output.
10432 OpFlags.setMemConstraint(ConstraintID);
10433 Info.AsmNodeOperands.push_back(
10434 DAG.getTargetConstant(OpFlags, DL, MVT::i32));
10435 Info.AsmNodeOperands.push_back(OpInfo.CallOperand);
10436 } else {
10437 // Otherwise, this outputs to a register (directly for C_Register /
10438 // C_RegisterClass, and a target-defined fashion for
10439 // C_Immediate/C_Other). Find a register that we can use.
10440 if (OpInfo.AssignedRegs.Regs.empty()) {
10441 Info.ErrorMsg << "could not allocate output register for "
10442 << "constraint '" << OpInfo.ConstraintCode << "'";
10443 return true;
10444 }
10445
10446 if (DetectWriteToReservedRegister())
10447 return true;
10448
10449 // Add information to the INLINEASM node to know that this register is
10450 // set.
10451 OpInfo.AssignedRegs.AddInlineAsmOperands(
10452 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10454 false, 0, DL, DAG, Info.AsmNodeOperands);
10455 }
10456 break;
10457
10458 case InlineAsm::isInput:
10459 case InlineAsm::isLabel: {
10460 SDValue InOperandVal = OpInfo.CallOperand;
10461
10462 if (OpInfo.isMatchingInputConstraint()) {
10463 // If this is required to match an output register we have already set,
10464 // just use its register.
10465 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10466 Info.AsmNodeOperands);
10467 InlineAsm::Flag Flag(Info.AsmNodeOperands[CurOp]->getAsZExtVal());
10468 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10469 if (OpInfo.isIndirect) {
10470 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10471 Info.ErrorMsg << "inline asm not supported yet: cannot handle "
10472 << "tied indirect register inputs";
10473 return true;
10474 }
10475
10478 MachineRegisterInfo &MRI = MF.getRegInfo();
10480 auto *R = cast<RegisterSDNode>(Info.AsmNodeOperands[CurOp + 1]);
10481 Register TiedReg = R->getReg();
10482 MVT RegVT = R->getSimpleValueType(0);
10483 const TargetRegisterClass *RC =
10484 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg)
10485 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10486 : TRI.getMinimalPhysRegClass(TiedReg);
10487 for (unsigned I = 0, E = Flag.getNumOperandRegisters(); I != E; ++I)
10488 Regs.push_back(MRI.createVirtualRegister(RC));
10489
10490 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10491
10492 // Use the produced MatchedRegs object to
10493 MatchedRegs.getCopyToRegs(InOperandVal, DAG, DL, Info.Chain,
10494 &Info.Glue, &Call);
10496 OpInfo.getMatchedOperand(), DL, DAG,
10497 Info.AsmNodeOperands);
10498 break;
10499 }
10500
10501 assert(Flag.isMemKind() && "Unknown matching constraint!");
10502 assert(Flag.getNumOperandRegisters() == 1 &&
10503 "Unexpected number of operands");
10504
10505 // Add information to the INLINEASM node to know about this input.
10506 // See InlineAsm.h isUseOperandTiedToDef.
10507 Flag.clearMemConstraint();
10508 Flag.setMatchingOp(OpInfo.getMatchedOperand());
10509 Info.AsmNodeOperands.push_back(DAG.getTargetConstant(
10510 Flag, DL, TLI.getPointerTy(DAG.getDataLayout())));
10511 Info.AsmNodeOperands.push_back(Info.AsmNodeOperands[CurOp + 1]);
10512 break;
10513 }
10514
10515 // Treat indirect 'X' constraint as memory.
10516 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10517 OpInfo.isIndirect)
10518 OpInfo.ConstraintType = TargetLowering::C_Memory;
10519
10520 if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10521 OpInfo.ConstraintType == TargetLowering::C_Other) {
10522 std::vector<SDValue> Ops;
10523 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10524 Ops, DAG);
10525 if (Ops.empty()) {
10526 if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10527 if (isa<ConstantSDNode>(InOperandVal)) {
10528 Info.ErrorMsg << "value out of range for constraint '"
10529 << OpInfo.ConstraintCode << "'";
10530 return true;
10531 }
10532
10533 Info.ErrorMsg << "invalid operand for inline asm constraint '"
10534 << OpInfo.ConstraintCode << "'";
10535 return true;
10536 }
10537
10538 // Add information to the INLINEASM node to know about this input.
10539 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10540 Info.AsmNodeOperands.push_back(DAG.getTargetConstant(
10541 ResOpType, DL, TLI.getPointerTy(DAG.getDataLayout())));
10542 llvm::append_range(Info.AsmNodeOperands, Ops);
10543 break;
10544 }
10545
10546 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10547 assert((OpInfo.isIndirect ||
10548 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10549 "Operand must be indirect to be a mem!");
10550 assert(InOperandVal.getValueType() ==
10551 TLI.getPointerTy(DAG.getDataLayout()) &&
10552 "Memory operands expect pointer values");
10553
10554 const InlineAsm::ConstraintCode ConstraintID =
10555 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10557 "Failed to convert memory constraint code to constraint id.");
10558
10559 // Add information to the INLINEASM node to know about this input.
10561 ResOpType.setMemConstraint(ConstraintID);
10562 Info.AsmNodeOperands.push_back(
10563 DAG.getTargetConstant(ResOpType, DL, MVT::i32));
10564 Info.AsmNodeOperands.push_back(InOperandVal);
10565 break;
10566 }
10567
10568 if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10569 const InlineAsm::ConstraintCode ConstraintID =
10570 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10572 "Failed to convert memory constraint code to constraint id.");
10573
10575
10576 SDValue AsmOp = InOperandVal;
10577 if (isFunction(InOperandVal)) {
10578 auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10579 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10580 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10581 InOperandVal.getValueType(),
10582 GA->getOffset());
10583 }
10584
10585 // Add information to the INLINEASM node to know about this input.
10586 ResOpType.setMemConstraint(ConstraintID);
10587
10588 Info.AsmNodeOperands.push_back(
10589 DAG.getTargetConstant(ResOpType, DL, MVT::i32));
10590 Info.AsmNodeOperands.push_back(AsmOp);
10591 break;
10592 }
10593
10594 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10595 OpInfo.ConstraintType != TargetLowering::C_Register) {
10596 Info.ErrorMsg << "unknown asm constraint '" << OpInfo.ConstraintCode
10597 << "'";
10598 return true;
10599 }
10600
10601 // TODO: Support this.
10602 if (OpInfo.isIndirect) {
10603 Info.ErrorMsg << "cannot handle indirect register inputs yet for "
10604 << "constraint '" << OpInfo.ConstraintCode << "'";
10605 return true;
10606 }
10607
10608 // Copy the input into the appropriate registers.
10609 if (OpInfo.AssignedRegs.Regs.empty()) {
10610 Info.ErrorMsg << "could not allocate input reg for constraint '"
10611 << OpInfo.ConstraintCode << "'";
10612 return true;
10613 }
10614
10615 if (DetectWriteToReservedRegister())
10616 return true;
10617
10618 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, DL, Info.Chain,
10619 &Info.Glue, &Call);
10620 OpInfo.AssignedRegs.AddInlineAsmOperands(
10621 InlineAsm::Kind::RegUse, false, 0, DL, DAG, Info.AsmNodeOperands);
10622 break;
10623 }
10624
10626 // Add the clobbered value to the operand list, so that the register
10627 // allocator is aware that the physreg got clobbered.
10628 if (!OpInfo.AssignedRegs.Regs.empty())
10629 OpInfo.AssignedRegs.AddInlineAsmOperands(
10630 InlineAsm::Kind::Clobber, false, 0, DL, DAG, Info.AsmNodeOperands);
10631 break;
10632 }
10633 }
10634
10635 return false;
10636}
10637
10638/// DetermineConstraints - Find the constraints to use for inline asm operands.
10639static bool
10640determineConstraints(ConstraintDecisionInfo &Info,
10641 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10642 const CallBase &Call, SelectionDAGBuilder &Builder,
10643 const TargetLowering &TLI, const TargetMachine &TM,
10644 SelectionDAG &DAG, const BasicBlock *EHPadBB) {
10645 const auto *IA = cast<InlineAsm>(Call.getCalledOperand());
10646 ExtraFlags ExtraInfo(Call);
10647
10648 // First pass: Construct operand info objects.
10649 Info.HasSideEffect = IA->hasSideEffects();
10650 if (constructOperandInfo(Info, TargetConstraints, Builder, TLI, ExtraInfo))
10651 return true;
10652
10653 // We won't need to flush pending loads if this asm doesn't touch
10654 // memory and is nonvolatile.
10655 Info.Chain = Info.HasSideEffect ? Builder.getRoot() : DAG.getRoot();
10656
10657 bool IsCallBr = isa<CallBrInst>(Call);
10658 bool EmitEHLabels = isa<InvokeInst>(Call);
10659 if (IsCallBr || EmitEHLabels)
10660 // If this is a callbr or invoke we need to flush pending exports since
10661 // inlineasm_br and invoke are terminators.
10662 // We need to do this before nodes are glued to the inlineasm_br node.
10663 Info.Chain = Builder.getControlRoot();
10664
10665 if (EmitEHLabels)
10666 Info.Chain = Builder.lowerStartEH(Info.Chain, EHPadBB, Info.BeginLabel);
10667
10668 // Second pass: Compute which constraint option to use.
10669 computeConstraintToUse(Info, Call, TargetConstraints, Builder, TLI, TM, DAG);
10670
10671 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10672 Info.AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
10673 Info.AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
10674 IA->getAsmString().data(), TLI.getProgramPointerTy(DAG.getDataLayout())));
10675
10676 // If we have a !srcloc metadata node associated with it, we want to attach
10677 // this to the ultimately generated inline asm machineinstr. To do this, we
10678 // pass in the third operand as this (potentially null) inline asm MDNode.
10679 const MDNode *SrcLoc = Call.getMetadata("srcloc");
10680 Info.AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
10681
10682 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10683 // bits as operand 3.
10684 Info.AsmNodeOperands.push_back(
10685 DAG.getTargetConstant(ExtraInfo.get(), Builder.getCurSDLoc(),
10686 TLI.getPointerTy(DAG.getDataLayout())));
10687
10688 // Third pass: Prepare DAG-level operands
10689 return prepareDAGLevelOperands(Info, Call, Builder, TLI, DAG);
10690}
10691
10692/// visitInlineAsm - Handle a call to an InlineAsm object.
10693void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
10694 const BasicBlock *EHPadBB) {
10695 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10697 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
10698
10699 assert((!isa<InvokeInst>(Call) || EHPadBB) &&
10700 "InvokeInst must have an EHPadBB");
10701
10702 ConstraintDecisionInfo Info;
10703 if (determineConstraints(Info, TargetConstraints, Call, *this, TLI, TM, DAG,
10704 EHPadBB))
10705 return emitInlineAsmError(Call, Info.ErrorMsg.str());
10706
10707 SDValue Glue = Info.Glue;
10708 SDValue Chain = Info.Chain;
10709
10710 // Finish up input operands. Set the input chain and add the flag last.
10711 Info.AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10712 if (Glue.getNode())
10713 Info.AsmNodeOperands.push_back(Glue);
10714
10715 bool IsCallBr = isa<CallBrInst>(Call);
10716 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10717 Chain =
10718 DAG.getNode(ISDOpc, getCurSDLoc(), DAG.getVTList(MVT::Other, MVT::Glue),
10719 Info.AsmNodeOperands);
10720 Glue = Chain.getValue(1);
10721
10722 // Do additional work to generate outputs.
10723
10724 SmallVector<EVT, 1> ResultVTs;
10725 SmallVector<SDValue, 1> ResultValues;
10726 SmallVector<SDValue, 8> OutChains;
10727
10728 llvm::Type *CallResultType = Call.getType();
10729 ArrayRef<Type *> ResultTypes;
10730 if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10731 ResultTypes = StructResult->elements();
10732 else if (!CallResultType->isVoidTy())
10733 ResultTypes = ArrayRef(CallResultType);
10734
10735 auto CurResultType = ResultTypes.begin();
10736 auto handleRegAssign = [&](SDValue V) {
10737 assert(CurResultType != ResultTypes.end() && "Unexpected value");
10738 assert((*CurResultType)->isSized() && "Unexpected unsized type");
10739 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10740 ++CurResultType;
10741 // If the type of the inline asm call site return value is different but has
10742 // same size as the type of the asm output bitcast it. One example of this
10743 // is for vectors with different width / number of elements. This can
10744 // happen for register classes that can contain multiple different value
10745 // types. The preg or vreg allocated may not have the same VT as was
10746 // expected.
10747 //
10748 // This can also happen for a return value that disagrees with the register
10749 // class it is put in, eg. a double in a general-purpose register on a
10750 // 32-bit machine.
10751 if (ResultVT != V.getValueType() &&
10752 ResultVT.getSizeInBits() == V.getValueSizeInBits())
10753 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10754 else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10755 V.getValueType().isInteger()) {
10756 // If a result value was tied to an input value, the computed result
10757 // may have a wider width than the expected result. Extract the
10758 // relevant portion.
10759 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10760 }
10761 assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10762 ResultVTs.push_back(ResultVT);
10763 ResultValues.push_back(V);
10764 };
10765
10766 // Deal with output operands.
10767 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10768 if (OpInfo.Type == InlineAsm::isOutput) {
10769 SDValue Val;
10770 // Skip trivial output operands.
10771 if (OpInfo.AssignedRegs.Regs.empty())
10772 continue;
10773
10774 switch (OpInfo.ConstraintType) {
10777 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10778 Chain, &Glue, &Call);
10779 break;
10782 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10783 OpInfo, DAG);
10784 break;
10786 break; // Already handled.
10788 break; // Silence warning.
10790 assert(false && "Unexpected unknown constraint");
10791 }
10792
10793 // Indirect output manifest as stores. Record output chains.
10794 if (OpInfo.isIndirect) {
10795 const Value *Ptr = OpInfo.CallOperandVal;
10796 assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10797 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10798 MachinePointerInfo(Ptr));
10799 OutChains.push_back(Store);
10800 } else {
10801 // generate CopyFromRegs to associated registers.
10802 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10803 if (Val.getOpcode() == ISD::MERGE_VALUES) {
10804 for (const SDValue &V : Val->op_values())
10805 handleRegAssign(V);
10806 } else
10807 handleRegAssign(Val);
10808 }
10809 }
10810 }
10811
10812 // Set results.
10813 if (!ResultValues.empty()) {
10814 assert(CurResultType == ResultTypes.end() &&
10815 "Mismatch in number of ResultTypes");
10816 assert(ResultValues.size() == ResultTypes.size() &&
10817 "Mismatch in number of output operands in asm result");
10818
10820 DAG.getVTList(ResultVTs), ResultValues);
10821 setValue(&Call, V);
10822 }
10823
10824 // Collect store chains.
10825 if (!OutChains.empty())
10826 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10827
10828 if (const auto *II = dyn_cast<InvokeInst>(&Call))
10829 Chain = lowerEndEH(Chain, II, EHPadBB, Info.BeginLabel);
10830
10831 // Only Update Root if inline assembly has a memory effect.
10832 if (ResultValues.empty() || Info.HasSideEffect || !OutChains.empty() ||
10833 IsCallBr || isa<InvokeInst>(Call))
10834 DAG.setRoot(Chain);
10835}
10836
10837void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10838 const Twine &Message) {
10839 LLVMContext &Ctx = *DAG.getContext();
10840 Ctx.diagnose(DiagnosticInfoInlineAsm(Call, Message));
10841
10842 // Make sure we leave the DAG in a valid state
10843 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10844 SmallVector<EVT, 1> ValueVTs;
10845 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10846
10847 if (ValueVTs.empty())
10848 return;
10849
10851 for (const EVT &VT : ValueVTs)
10852 Ops.push_back(DAG.getUNDEF(VT));
10853
10854 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10855}
10856
10857void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10858 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10859 MVT::Other, getRoot(),
10860 getValue(I.getArgOperand(0)),
10861 DAG.getSrcValue(I.getArgOperand(0))));
10862}
10863
10864void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10865 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10866 const DataLayout &DL = DAG.getDataLayout();
10867 SDValue V = DAG.getVAArg(
10868 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10869 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10870 DL.getABITypeAlign(I.getType()).value());
10871 DAG.setRoot(V.getValue(1));
10872
10873 if (I.getType()->isPointerTy())
10874 V = DAG.getPtrExtOrTrunc(
10875 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10876 setValue(&I, V);
10877}
10878
10879void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10880 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10881 MVT::Other, getRoot(),
10882 getValue(I.getArgOperand(0)),
10883 DAG.getSrcValue(I.getArgOperand(0))));
10884}
10885
10886void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10887 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10888 MVT::Other, getRoot(),
10889 getValue(I.getArgOperand(0)),
10890 getValue(I.getArgOperand(1)),
10891 DAG.getSrcValue(I.getArgOperand(0)),
10892 DAG.getSrcValue(I.getArgOperand(1))));
10893}
10894
10896 const Instruction &I,
10897 SDValue Op) {
10898 std::optional<ConstantRange> CR = getRange(I);
10899
10900 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10901 return Op;
10902
10903 APInt Hi = CR->getUnsignedMax();
10904 unsigned Bits = std::max(Hi.getActiveBits(),
10905 static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10906
10907 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10908
10909 SDLoc SL = getCurSDLoc();
10910
10911 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10912 DAG.getValueType(SmallVT));
10913 unsigned NumVals = Op.getNode()->getNumValues();
10914 if (NumVals == 1)
10915 return ZExt;
10916
10918
10919 Ops.push_back(ZExt);
10920 for (unsigned I = 1; I != NumVals; ++I)
10921 Ops.push_back(Op.getValue(I));
10922
10923 return DAG.getMergeValues(Ops, SL);
10924}
10925
10927 SelectionDAG &DAG, const Instruction &I, SDValue Op) {
10928 FPClassTest Classes = getNoFPClass(I);
10929 if (Classes == fcNone)
10930 return Op;
10931
10932 SDLoc SL = getCurSDLoc();
10933 SDValue TestConst = DAG.getTargetConstant(Classes, SDLoc(), MVT::i32);
10934
10935 if (Op.getOpcode() != ISD::MERGE_VALUES) {
10936 return DAG.getNode(ISD::AssertNoFPClass, SL, Op.getValueType(), Op,
10937 TestConst);
10938 }
10939
10940 SmallVector<SDValue, 8> Ops(Op.getNumOperands());
10941 for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
10942 SDValue MergeOp = Op.getOperand(I);
10943 Ops[I] = DAG.getNode(ISD::AssertNoFPClass, SL, MergeOp.getValueType(),
10944 MergeOp, TestConst);
10945 }
10946
10947 return DAG.getMergeValues(Ops, SL);
10948}
10949
10950/// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10951/// the call being lowered.
10952///
10953/// This is a helper for lowering intrinsics that follow a target calling
10954/// convention or require stack pointer adjustment. Only a subset of the
10955/// intrinsic's operands need to participate in the calling convention.
10958 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10959 AttributeSet RetAttrs, bool IsPatchPoint) {
10961 Args.reserve(NumArgs);
10962
10963 // Populate the argument list.
10964 // Attributes for args start at offset 1, after the return attribute.
10965 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10966 ArgI != ArgE; ++ArgI) {
10967 const Value *V = Call->getOperand(ArgI);
10968
10969 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10970
10971 TargetLowering::ArgListEntry Entry(getValue(V), V->getType());
10972 Entry.setAttributes(Call, ArgI);
10973 Args.push_back(Entry);
10974 }
10975
10977 .setChain(getRoot())
10978 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10979 RetAttrs)
10980 .setDiscardResult(Call->use_empty())
10981 .setIsPatchPoint(IsPatchPoint)
10983 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10984}
10985
10986/// Add a stack map intrinsic call's live variable operands to a stackmap
10987/// or patchpoint target node's operand list.
10988///
10989/// Constants are converted to TargetConstants purely as an optimization to
10990/// avoid constant materialization and register allocation.
10991///
10992/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10993/// generate addess computation nodes, and so FinalizeISel can convert the
10994/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10995/// address materialization and register allocation, but may also be required
10996/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10997/// alloca in the entry block, then the runtime may assume that the alloca's
10998/// StackMap location can be read immediately after compilation and that the
10999/// location is valid at any point during execution (this is similar to the
11000/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
11001/// only available in a register, then the runtime would need to trap when
11002/// execution reaches the StackMap in order to read the alloca's location.
11003static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
11005 SelectionDAGBuilder &Builder) {
11006 SelectionDAG &DAG = Builder.DAG;
11007 for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
11008 SDValue Op = Builder.getValue(Call.getArgOperand(I));
11009
11010 // Things on the stack are pointer-typed, meaning that they are already
11011 // legal and can be emitted directly to target nodes.
11013 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
11014 } else {
11015 // Otherwise emit a target independent node to be legalised.
11016 Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
11017 }
11018 }
11019}
11020
11021/// Lower llvm.experimental.stackmap.
11022void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
11023 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
11024 // [live variables...])
11025
11026 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
11027
11028 SDValue Chain, InGlue, Callee;
11030
11031 SDLoc DL = getCurSDLoc();
11033
11034 // The stackmap intrinsic only records the live variables (the arguments
11035 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
11036 // intrinsic, this won't be lowered to a function call. This means we don't
11037 // have to worry about calling conventions and target specific lowering code.
11038 // Instead we perform the call lowering right here.
11039 //
11040 // chain, flag = CALLSEQ_START(chain, 0, 0)
11041 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
11042 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
11043 //
11044 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
11045 InGlue = Chain.getValue(1);
11046
11047 // Add the STACKMAP operands, starting with DAG house-keeping.
11048 Ops.push_back(Chain);
11049 Ops.push_back(InGlue);
11050
11051 // Add the <id>, <numShadowBytes> operands.
11052 //
11053 // These do not require legalisation, and can be emitted directly to target
11054 // constant nodes.
11056 assert(ID.getValueType() == MVT::i64);
11057 SDValue IDConst =
11058 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
11059 Ops.push_back(IDConst);
11060
11061 SDValue Shad = getValue(CI.getArgOperand(1));
11062 assert(Shad.getValueType() == MVT::i32);
11063 SDValue ShadConst =
11064 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
11065 Ops.push_back(ShadConst);
11066
11067 // Add the live variables.
11068 addStackMapLiveVars(CI, 2, DL, Ops, *this);
11069
11070 // Create the STACKMAP node.
11071 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11072 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
11073 InGlue = Chain.getValue(1);
11074
11075 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
11076
11077 // Stackmaps don't generate values, so nothing goes into the NodeMap.
11078
11079 // Set the root to the target-lowered call chain.
11080 DAG.setRoot(Chain);
11081
11082 // Inform the Frame Information that we have a stackmap in this function.
11083 FuncInfo.MF->getFrameInfo().setHasStackMap();
11084}
11085
11086/// Lower llvm.experimental.patchpoint directly to its target opcode.
11087void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
11088 const BasicBlock *EHPadBB) {
11089 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
11090 // i32 <numBytes>,
11091 // i8* <target>,
11092 // i32 <numArgs>,
11093 // [Args...],
11094 // [live variables...])
11095
11097 bool IsAnyRegCC = CC == CallingConv::AnyReg;
11098 bool HasDef = !CB.getType()->isVoidTy();
11099 SDLoc dl = getCurSDLoc();
11101
11102 // Handle immediate and symbolic callees.
11103 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
11104 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
11105 /*isTarget=*/true);
11106 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
11107 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
11108 SDLoc(SymbolicCallee),
11109 SymbolicCallee->getValueType(0));
11110
11111 // Get the real number of arguments participating in the call <numArgs>
11113 unsigned NumArgs = NArgVal->getAsZExtVal();
11114
11115 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
11116 // Intrinsics include all meta-operands up to but not including CC.
11117 unsigned NumMetaOpers = PatchPointOpers::CCPos;
11118 assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
11119 "Not enough arguments provided to the patchpoint intrinsic");
11120
11121 // For AnyRegCC the arguments are lowered later on manually.
11122 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
11123 Type *ReturnTy =
11124 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
11125
11126 TargetLowering::CallLoweringInfo CLI(DAG);
11127 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
11128 ReturnTy, CB.getAttributes().getRetAttrs(), true);
11129 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
11130
11131 SDNode *CallEnd = Result.second.getNode();
11132 if (CallEnd->getOpcode() == ISD::EH_LABEL)
11133 CallEnd = CallEnd->getOperand(0).getNode();
11134 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
11135 CallEnd = CallEnd->getOperand(0).getNode();
11136
11137 /// Get a call instruction from the call sequence chain.
11138 /// Tail calls are not allowed.
11139 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
11140 "Expected a callseq node.");
11141 SDNode *Call = CallEnd->getOperand(0).getNode();
11142 bool HasGlue = Call->getGluedNode();
11143
11144 // Replace the target specific call node with the patchable intrinsic.
11146
11147 // Push the chain.
11148 Ops.push_back(*(Call->op_begin()));
11149
11150 // Optionally, push the glue (if any).
11151 if (HasGlue)
11152 Ops.push_back(*(Call->op_end() - 1));
11153
11154 // Push the register mask info.
11155 if (HasGlue)
11156 Ops.push_back(*(Call->op_end() - 2));
11157 else
11158 Ops.push_back(*(Call->op_end() - 1));
11159
11160 // Add the <id> and <numBytes> constants.
11162 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
11164 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
11165
11166 // Add the callee.
11167 Ops.push_back(Callee);
11168
11169 // Adjust <numArgs> to account for any arguments that have been passed on the
11170 // stack instead.
11171 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
11172 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
11173 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
11174 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
11175
11176 // Add the calling convention
11177 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
11178
11179 // Add the arguments we omitted previously. The register allocator should
11180 // place these in any free register.
11181 if (IsAnyRegCC)
11182 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
11183 Ops.push_back(getValue(CB.getArgOperand(i)));
11184
11185 // Push the arguments from the call instruction.
11186 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
11187 Ops.append(Call->op_begin() + 2, e);
11188
11189 // Push live variables for the stack map.
11190 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
11191
11192 SDVTList NodeTys;
11193 if (IsAnyRegCC && HasDef) {
11194 // Create the return types based on the intrinsic definition
11195 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11196 SmallVector<EVT, 3> ValueVTs;
11197 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
11198 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
11199
11200 // There is always a chain and a glue type at the end
11201 ValueVTs.push_back(MVT::Other);
11202 ValueVTs.push_back(MVT::Glue);
11203 NodeTys = DAG.getVTList(ValueVTs);
11204 } else
11205 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11206
11207 // Replace the target specific call node with a PATCHPOINT node.
11208 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
11209
11210 // Update the NodeMap.
11211 if (HasDef) {
11212 if (IsAnyRegCC)
11213 setValue(&CB, SDValue(PPV.getNode(), 0));
11214 else
11215 setValue(&CB, Result.first);
11216 }
11217
11218 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
11219 // call sequence. Furthermore the location of the chain and glue can change
11220 // when the AnyReg calling convention is used and the intrinsic returns a
11221 // value.
11222 if (IsAnyRegCC && HasDef) {
11223 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
11224 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
11225 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11226 } else
11227 DAG.ReplaceAllUsesWith(Call, PPV.getNode());
11228 DAG.DeleteNode(Call);
11229
11230 // Inform the Frame Information that we have a patchpoint in this function.
11231 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
11232}
11233
11234void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
11235 unsigned Intrinsic) {
11236 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11237 SDValue Op1 = getValue(I.getArgOperand(0));
11238 SDValue Op2;
11239 if (I.arg_size() > 1)
11240 Op2 = getValue(I.getArgOperand(1));
11241 SDLoc dl = getCurSDLoc();
11242 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11243 SDValue Res;
11244 SDNodeFlags SDFlags;
11245 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
11246 SDFlags.copyFMF(*FPMO);
11247
11248 switch (Intrinsic) {
11249 case Intrinsic::vector_reduce_fadd:
11250 if (SDFlags.hasAllowReassociation())
11251 Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
11252 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
11253 SDFlags);
11254 else
11255 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
11256 break;
11257 case Intrinsic::vector_reduce_fmul:
11258 if (SDFlags.hasAllowReassociation())
11259 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
11260 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
11261 SDFlags);
11262 else
11263 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
11264 break;
11265 case Intrinsic::vector_reduce_add:
11266 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
11267 break;
11268 case Intrinsic::vector_reduce_mul:
11269 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
11270 break;
11271 case Intrinsic::vector_reduce_and:
11272 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
11273 break;
11274 case Intrinsic::vector_reduce_or:
11275 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
11276 break;
11277 case Intrinsic::vector_reduce_xor:
11278 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
11279 break;
11280 case Intrinsic::vector_reduce_smax:
11281 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
11282 break;
11283 case Intrinsic::vector_reduce_smin:
11284 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
11285 break;
11286 case Intrinsic::vector_reduce_umax:
11287 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
11288 break;
11289 case Intrinsic::vector_reduce_umin:
11290 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
11291 break;
11292 case Intrinsic::vector_reduce_fmax:
11293 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
11294 break;
11295 case Intrinsic::vector_reduce_fmin:
11296 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
11297 break;
11298 case Intrinsic::vector_reduce_fmaximum:
11299 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
11300 break;
11301 case Intrinsic::vector_reduce_fminimum:
11302 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
11303 break;
11304 case Intrinsic::vector_reduce_fmaximumnum:
11305 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUMNUM, dl, VT, Op1, SDFlags);
11306 break;
11307 case Intrinsic::vector_reduce_fminimumnum:
11308 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUMNUM, dl, VT, Op1, SDFlags);
11309 break;
11310 default:
11311 llvm_unreachable("Unhandled vector reduce intrinsic");
11312 }
11313 setValue(&I, Res);
11314}
11315
11316/// Returns an AttributeList representing the attributes applied to the return
11317/// value of the given call.
11320 if (CLI.RetSExt)
11321 Attrs.push_back(Attribute::SExt);
11322 if (CLI.RetZExt)
11323 Attrs.push_back(Attribute::ZExt);
11324 if (CLI.IsInReg)
11325 Attrs.push_back(Attribute::InReg);
11326
11327 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
11328 Attrs);
11329}
11330
11331/// TargetLowering::LowerCallTo - This is the default LowerCallTo
11332/// implementation, which just calls LowerCall.
11333/// FIXME: When all targets are
11334/// migrated to using LowerCall, this hook should be integrated into SDISel.
11335std::pair<SDValue, SDValue>
11337 LLVMContext &Context = CLI.RetTy->getContext();
11338
11339 // Handle the incoming return values from the call.
11340 CLI.Ins.clear();
11341 SmallVector<Type *, 4> RetOrigTys;
11343 auto &DL = CLI.DAG.getDataLayout();
11344 ComputeValueTypes(DL, CLI.OrigRetTy, RetOrigTys, &Offsets);
11345
11346 SmallVector<EVT, 4> RetVTs;
11347 if (CLI.RetTy != CLI.OrigRetTy) {
11348 assert(RetOrigTys.size() == 1 &&
11349 "Only supported for non-aggregate returns");
11350 RetVTs.push_back(getValueType(DL, CLI.RetTy));
11351 } else {
11352 for (Type *Ty : RetOrigTys)
11353 RetVTs.push_back(getValueType(DL, Ty));
11354 }
11355
11356 if (CLI.IsPostTypeLegalization) {
11357 // If we are lowering a libcall after legalization, split the return type.
11358 SmallVector<Type *, 4> OldRetOrigTys;
11359 SmallVector<EVT, 4> OldRetVTs;
11360 SmallVector<TypeSize, 4> OldOffsets;
11361 RetOrigTys.swap(OldRetOrigTys);
11362 RetVTs.swap(OldRetVTs);
11363 Offsets.swap(OldOffsets);
11364
11365 for (size_t i = 0, e = OldRetVTs.size(); i != e; ++i) {
11366 EVT RetVT = OldRetVTs[i];
11367 uint64_t Offset = OldOffsets[i];
11368 MVT RegisterVT = getRegisterType(Context, RetVT);
11369 unsigned NumRegs = getNumRegisters(Context, RetVT);
11370 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
11371 RetOrigTys.append(NumRegs, OldRetOrigTys[i]);
11372 RetVTs.append(NumRegs, RegisterVT);
11373 for (unsigned j = 0; j != NumRegs; ++j)
11374 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
11375 }
11376 }
11377
11379 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
11380
11381 bool CanLowerReturn =
11383 CLI.IsVarArg, Outs, Context, CLI.RetTy);
11384
11385 SDValue DemoteStackSlot;
11386 int DemoteStackIdx = -100;
11387 if (!CanLowerReturn) {
11388 // FIXME: equivalent assert?
11389 // assert(!CS.hasInAllocaArgument() &&
11390 // "sret demotion is incompatible with inalloca");
11391 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
11392 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
11394 DemoteStackIdx =
11395 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
11396 Type *StackSlotPtrType = PointerType::get(Context, DL.getAllocaAddrSpace());
11397
11398 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
11399 ArgListEntry Entry(DemoteStackSlot, StackSlotPtrType);
11400 Entry.IsSRet = true;
11401 Entry.Alignment = Alignment;
11402 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
11403 CLI.NumFixedArgs += 1;
11404 CLI.getArgs()[0].IndirectType = CLI.RetTy;
11405 CLI.RetTy = CLI.OrigRetTy = Type::getVoidTy(Context);
11406
11407 // sret demotion isn't compatible with tail-calls, since the sret argument
11408 // points into the callers stack frame.
11409 CLI.IsTailCall = false;
11410 } else {
11411 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11412 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
11413 for (unsigned I = 0, E = RetVTs.size(); I != E; ++I) {
11414 ISD::ArgFlagsTy Flags;
11415 if (NeedsRegBlock) {
11416 Flags.setInConsecutiveRegs();
11417 if (I == RetVTs.size() - 1)
11418 Flags.setInConsecutiveRegsLast();
11419 }
11420 EVT VT = RetVTs[I];
11421 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11422 unsigned NumRegs =
11423 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11424 for (unsigned i = 0; i != NumRegs; ++i) {
11425 ISD::InputArg Ret(Flags, RegisterVT, VT, RetOrigTys[I],
11427 if (CLI.RetTy->isPointerTy()) {
11428 Ret.Flags.setPointer();
11430 cast<PointerType>(CLI.RetTy)->getAddressSpace());
11431 }
11432 if (CLI.RetSExt)
11433 Ret.Flags.setSExt();
11434 if (CLI.RetZExt)
11435 Ret.Flags.setZExt();
11436 if (CLI.IsInReg)
11437 Ret.Flags.setInReg();
11438 CLI.Ins.push_back(Ret);
11439 }
11440 }
11441 }
11442
11443 // We push in swifterror return as the last element of CLI.Ins.
11444 ArgListTy &Args = CLI.getArgs();
11445 if (supportSwiftError()) {
11446 for (const ArgListEntry &Arg : Args) {
11447 if (Arg.IsSwiftError) {
11448 ISD::ArgFlagsTy Flags;
11449 Flags.setSwiftError();
11451 PointerType::getUnqual(Context),
11452 /*Used=*/true, ISD::InputArg::NoArgIndex, 0);
11453 CLI.Ins.push_back(Ret);
11454 }
11455 }
11456 }
11457
11458 // Handle all of the outgoing arguments.
11459 CLI.Outs.clear();
11460 CLI.OutVals.clear();
11461 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11462 SmallVector<Type *, 4> OrigArgTys;
11463 ComputeValueTypes(DL, Args[i].OrigTy, OrigArgTys);
11464 // FIXME: Split arguments if CLI.IsPostTypeLegalization
11465 Type *FinalType = Args[i].Ty;
11466 if (Args[i].IsByVal)
11467 FinalType = Args[i].IndirectType;
11468 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11469 FinalType, CLI.CallConv, CLI.IsVarArg, DL);
11470 for (unsigned Value = 0, NumValues = OrigArgTys.size(); Value != NumValues;
11471 ++Value) {
11472 Type *OrigArgTy = OrigArgTys[Value];
11473 Type *ArgTy = OrigArgTy;
11474 if (Args[i].Ty != Args[i].OrigTy) {
11475 assert(Value == 0 && "Only supported for non-aggregate arguments");
11476 ArgTy = Args[i].Ty;
11477 }
11478
11479 EVT VT = getValueType(DL, ArgTy);
11480 SDValue Op = SDValue(Args[i].Node.getNode(),
11481 Args[i].Node.getResNo() + Value);
11482 ISD::ArgFlagsTy Flags;
11483
11484 // Certain targets (such as MIPS), may have a different ABI alignment
11485 // for a type depending on the context. Give the target a chance to
11486 // specify the alignment it wants.
11487 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11488 Flags.setOrigAlign(OriginalAlignment);
11489
11490 if (i >= CLI.NumFixedArgs)
11491 Flags.setVarArg();
11492 if (ArgTy->isPointerTy()) {
11493 Flags.setPointer();
11494 Flags.setPointerAddrSpace(cast<PointerType>(ArgTy)->getAddressSpace());
11495 }
11496 if (Args[i].IsZExt)
11497 Flags.setZExt();
11498 if (Args[i].IsSExt)
11499 Flags.setSExt();
11500 if (Args[i].IsNoExt)
11501 Flags.setNoExt();
11502 if (Args[i].IsInReg) {
11503 // If we are using vectorcall calling convention, a structure that is
11504 // passed InReg - is surely an HVA
11506 isa<StructType>(FinalType)) {
11507 // The first value of a structure is marked
11508 if (0 == Value)
11509 Flags.setHvaStart();
11510 Flags.setHva();
11511 }
11512 // Set InReg Flag
11513 Flags.setInReg();
11514 }
11515 if (Args[i].IsSRet)
11516 Flags.setSRet();
11517 if (Args[i].IsSwiftSelf)
11518 Flags.setSwiftSelf();
11519 if (Args[i].IsSwiftAsync)
11520 Flags.setSwiftAsync();
11521 if (Args[i].IsSwiftError)
11522 Flags.setSwiftError();
11523 if (Args[i].IsCFGuardTarget)
11524 Flags.setCFGuardTarget();
11525 if (Args[i].IsByVal)
11526 Flags.setByVal();
11527 if (Args[i].IsByRef)
11528 Flags.setByRef();
11529 if (Args[i].IsPreallocated) {
11530 Flags.setPreallocated();
11531 // Set the byval flag for CCAssignFn callbacks that don't know about
11532 // preallocated. This way we can know how many bytes we should've
11533 // allocated and how many bytes a callee cleanup function will pop. If
11534 // we port preallocated to more targets, we'll have to add custom
11535 // preallocated handling in the various CC lowering callbacks.
11536 Flags.setByVal();
11537 }
11538 if (Args[i].IsInAlloca) {
11539 Flags.setInAlloca();
11540 // Set the byval flag for CCAssignFn callbacks that don't know about
11541 // inalloca. This way we can know how many bytes we should've allocated
11542 // and how many bytes a callee cleanup function will pop. If we port
11543 // inalloca to more targets, we'll have to add custom inalloca handling
11544 // in the various CC lowering callbacks.
11545 Flags.setByVal();
11546 }
11547 Align MemAlign;
11548 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11549 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11550 Flags.setByValSize(FrameSize);
11551
11552 // info is not there but there are cases it cannot get right.
11553 if (auto MA = Args[i].Alignment)
11554 MemAlign = *MA;
11555 else
11556 MemAlign = getByValTypeAlignment(Args[i].IndirectType, DL);
11557 } else if (auto MA = Args[i].Alignment) {
11558 MemAlign = *MA;
11559 } else {
11560 MemAlign = OriginalAlignment;
11561 }
11562 Flags.setMemAlign(MemAlign);
11563 if (Args[i].IsNest)
11564 Flags.setNest();
11565 if (NeedsRegBlock)
11566 Flags.setInConsecutiveRegs();
11567
11568 MVT PartVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11569 unsigned NumParts =
11570 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11571 SmallVector<SDValue, 4> Parts(NumParts);
11572 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11573
11574 if (Args[i].IsSExt)
11575 ExtendKind = ISD::SIGN_EXTEND;
11576 else if (Args[i].IsZExt)
11577 ExtendKind = ISD::ZERO_EXTEND;
11578
11579 // Conservatively only handle 'returned' on non-vectors that can be lowered,
11580 // for now.
11581 if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11583 assert((CLI.RetTy == Args[i].Ty ||
11584 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11586 Args[i].Ty->getPointerAddressSpace())) &&
11587 RetVTs.size() == NumValues && "unexpected use of 'returned'");
11588 // Before passing 'returned' to the target lowering code, ensure that
11589 // either the register MVT and the actual EVT are the same size or that
11590 // the return value and argument are extended in the same way; in these
11591 // cases it's safe to pass the argument register value unchanged as the
11592 // return register value (although it's at the target's option whether
11593 // to do so)
11594 // TODO: allow code generation to take advantage of partially preserved
11595 // registers rather than clobbering the entire register when the
11596 // parameter extension method is not compatible with the return
11597 // extension method
11598 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11599 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11600 CLI.RetZExt == Args[i].IsZExt))
11601 Flags.setReturned();
11602 }
11603
11604 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11605 CLI.CallConv, ExtendKind);
11606
11607 for (unsigned j = 0; j != NumParts; ++j) {
11608 // if it isn't first piece, alignment must be 1
11609 // For scalable vectors the scalable part is currently handled
11610 // by individual targets, so we just use the known minimum size here.
11611 ISD::OutputArg MyFlags(
11612 Flags, Parts[j].getValueType().getSimpleVT(), VT, OrigArgTy, i,
11613 j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11614 if (NumParts > 1 && j == 0)
11615 MyFlags.Flags.setSplit();
11616 else if (j != 0) {
11617 MyFlags.Flags.setOrigAlign(Align(1));
11618 if (j == NumParts - 1)
11619 MyFlags.Flags.setSplitEnd();
11620 }
11621
11622 CLI.Outs.push_back(MyFlags);
11623 CLI.OutVals.push_back(Parts[j]);
11624 }
11625
11626 if (NeedsRegBlock && Value == NumValues - 1)
11627 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11628 }
11629 }
11630
11632 CLI.Chain = LowerCall(CLI, InVals);
11633
11634 // Update CLI.InVals to use outside of this function.
11635 CLI.InVals = InVals;
11636
11637 // Verify that the target's LowerCall behaved as expected.
11638 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11639 "LowerCall didn't return a valid chain!");
11640 assert((!CLI.IsTailCall || InVals.empty()) &&
11641 "LowerCall emitted a return value for a tail call!");
11642 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11643 "LowerCall didn't emit the correct number of values!");
11644
11645 // For a tail call, the return value is merely live-out and there aren't
11646 // any nodes in the DAG representing it. Return a special value to
11647 // indicate that a tail call has been emitted and no more Instructions
11648 // should be processed in the current block.
11649 if (CLI.IsTailCall) {
11650 CLI.DAG.setRoot(CLI.Chain);
11651 return std::make_pair(SDValue(), SDValue());
11652 }
11653
11654#ifndef NDEBUG
11655 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11656 assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11657 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11658 "LowerCall emitted a value with the wrong type!");
11659 }
11660#endif
11661
11662 SmallVector<SDValue, 4> ReturnValues;
11663 if (!CanLowerReturn) {
11664 // The instruction result is the result of loading from the
11665 // hidden sret parameter.
11666 MVT PtrVT = getPointerTy(DL, DL.getAllocaAddrSpace());
11667
11668 unsigned NumValues = RetVTs.size();
11669 ReturnValues.resize(NumValues);
11670 SmallVector<SDValue, 4> Chains(NumValues);
11671
11672 // An aggregate return value cannot wrap around the address space, so
11673 // offsets to its parts don't wrap either.
11675 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11676 for (unsigned i = 0; i < NumValues; ++i) {
11678 DemoteStackSlot, CLI.DAG.getConstant(Offsets[i], CLI.DL, PtrVT),
11680 SDValue L = CLI.DAG.getLoad(
11681 RetVTs[i], CLI.DL, CLI.Chain, Add,
11683 DemoteStackIdx, Offsets[i]),
11684 HiddenSRetAlign);
11685 ReturnValues[i] = L;
11686 Chains[i] = L.getValue(1);
11687 }
11688
11689 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11690 } else {
11691 // Collect the legal value parts into potentially illegal values
11692 // that correspond to the original function's return values.
11693 std::optional<ISD::NodeType> AssertOp;
11694 if (CLI.RetSExt)
11695 AssertOp = ISD::AssertSext;
11696 else if (CLI.RetZExt)
11697 AssertOp = ISD::AssertZext;
11698 unsigned CurReg = 0;
11699 for (EVT VT : RetVTs) {
11700 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11701 unsigned NumRegs =
11702 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11703
11704 ReturnValues.push_back(getCopyFromParts(
11705 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11706 CLI.Chain, CLI.CallConv, AssertOp));
11707 CurReg += NumRegs;
11708 }
11709
11710 // For a function returning void, there is no return value. We can't create
11711 // such a node, so we just return a null return value in that case. In
11712 // that case, nothing will actually look at the value.
11713 if (ReturnValues.empty())
11714 return std::make_pair(SDValue(), CLI.Chain);
11715 }
11716
11717 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11718 CLI.DAG.getVTList(RetVTs), ReturnValues);
11719 return std::make_pair(Res, CLI.Chain);
11720}
11721
11722/// Places new result values for the node in Results (their number
11723/// and types must exactly match those of the original return values of
11724/// the node), or leaves Results empty, which indicates that the node is not
11725/// to be custom lowered after all.
11728 SelectionDAG &DAG) const {
11729 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11730
11731 if (!Res.getNode())
11732 return;
11733
11734 // If the original node has one result, take the return value from
11735 // LowerOperation as is. It might not be result number 0.
11736 if (N->getNumValues() == 1) {
11737 Results.push_back(Res);
11738 return;
11739 }
11740
11741 // If the original node has multiple results, then the return node should
11742 // have the same number of results.
11743 assert((N->getNumValues() == Res->getNumValues()) &&
11744 "Lowering returned the wrong number of results!");
11745
11746 // Places new result values base on N result number.
11747 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11748 Results.push_back(Res.getValue(I));
11749}
11750
11752 llvm_unreachable("LowerOperation not implemented for this target!");
11753}
11754
11756 Register Reg,
11757 ISD::NodeType ExtendType) {
11759 assert((Op.getOpcode() != ISD::CopyFromReg ||
11760 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11761 "Copy from a reg to the same reg!");
11762 assert(!Reg.isPhysical() && "Is a physreg");
11763
11764 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11765 // If this is an InlineAsm we have to match the registers required, not the
11766 // notional registers required by the type.
11767
11768 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11769 std::nullopt); // This is not an ABI copy.
11770 SDValue Chain = DAG.getEntryNode();
11771
11772 if (ExtendType == ISD::ANY_EXTEND) {
11773 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11774 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11775 ExtendType = PreferredExtendIt->second;
11776 }
11777 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11778 PendingExports.push_back(Chain);
11779}
11780
11782
11783/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11784/// entry block, return true. This includes arguments used by switches, since
11785/// the switch may expand into multiple basic blocks.
11786static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11787 // With FastISel active, we may be splitting blocks, so force creation
11788 // of virtual registers for all non-dead arguments.
11789 if (FastISel)
11790 return A->use_empty();
11791
11792 const BasicBlock &Entry = A->getParent()->front();
11793 for (const User *U : A->users())
11794 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11795 return false; // Use not in entry block.
11796
11797 return true;
11798}
11799
11801 DenseMap<const Argument *,
11802 std::pair<const AllocaInst *, const StoreInst *>>;
11803
11804/// Scan the entry block of the function in FuncInfo for arguments that look
11805/// like copies into a local alloca. Record any copied arguments in
11806/// ArgCopyElisionCandidates.
11807static void
11809 FunctionLoweringInfo *FuncInfo,
11810 ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11811 // Record the state of every static alloca used in the entry block. Argument
11812 // allocas are all used in the entry block, so we need approximately as many
11813 // entries as we have arguments.
11814 enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11816 unsigned NumArgs = FuncInfo->Fn->arg_size();
11817 StaticAllocas.reserve(NumArgs * 2);
11818
11819 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11820 if (!V)
11821 return nullptr;
11822 V = V->stripPointerCasts();
11823 const auto *AI = dyn_cast<AllocaInst>(V);
11824 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11825 return nullptr;
11826 auto Iter = StaticAllocas.insert({AI, Unknown});
11827 return &Iter.first->second;
11828 };
11829
11830 // Look for stores of arguments to static allocas. Look through bitcasts and
11831 // GEPs to handle type coercions, as long as the alloca is fully initialized
11832 // by the store. Any non-store use of an alloca escapes it and any subsequent
11833 // unanalyzed store might write it.
11834 // FIXME: Handle structs initialized with multiple stores.
11835 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11836 // Look for stores, and handle non-store uses conservatively.
11837 const auto *SI = dyn_cast<StoreInst>(&I);
11838 if (!SI) {
11839 // We will look through cast uses, so ignore them completely.
11840 if (I.isCast())
11841 continue;
11842 // Ignore debug info and pseudo op intrinsics, they don't escape or store
11843 // to allocas.
11844 if (I.isDebugOrPseudoInst())
11845 continue;
11846 // This is an unknown instruction. Assume it escapes or writes to all
11847 // static alloca operands.
11848 for (const Use &U : I.operands()) {
11849 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11850 *Info = StaticAllocaInfo::Clobbered;
11851 }
11852 continue;
11853 }
11854
11855 // If the stored value is a static alloca, mark it as escaped.
11856 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11857 *Info = StaticAllocaInfo::Clobbered;
11858
11859 // Check if the destination is a static alloca.
11860 const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11861 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11862 if (!Info)
11863 continue;
11864 const AllocaInst *AI = cast<AllocaInst>(Dst);
11865
11866 // Skip allocas that have been initialized or clobbered.
11867 if (*Info != StaticAllocaInfo::Unknown)
11868 continue;
11869
11870 // Check if the stored value is an argument, and that this store fully
11871 // initializes the alloca.
11872 // If the argument type has padding bits we can't directly forward a pointer
11873 // as the upper bits may contain garbage.
11874 // Don't elide copies from the same argument twice.
11875 const Value *Val = SI->getValueOperand()->stripPointerCasts();
11876 const auto *Arg = dyn_cast<Argument>(Val);
11877 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL);
11878 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11879 Arg->getType()->isEmptyTy() || !AllocaSize ||
11880 DL.getTypeStoreSize(Arg->getType()) != *AllocaSize ||
11881 !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11882 ArgCopyElisionCandidates.count(Arg)) {
11883 *Info = StaticAllocaInfo::Clobbered;
11884 continue;
11885 }
11886
11887 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11888 << '\n');
11889
11890 // Mark this alloca and store for argument copy elision.
11891 *Info = StaticAllocaInfo::Elidable;
11892 ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11893
11894 // Stop scanning if we've seen all arguments. This will happen early in -O0
11895 // builds, which is useful, because -O0 builds have large entry blocks and
11896 // many allocas.
11897 if (ArgCopyElisionCandidates.size() == NumArgs)
11898 break;
11899 }
11900}
11901
11902/// Try to elide argument copies from memory into a local alloca. Succeeds if
11903/// ArgVal is a load from a suitable fixed stack object.
11906 DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11907 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11908 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11909 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11910 // Check if this is a load from a fixed stack object.
11911 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11912 if (!LNode)
11913 return;
11914 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11915 if (!FINode)
11916 return;
11917
11918 // Check that the fixed stack object is the right size and alignment.
11919 // Look at the alignment that the user wrote on the alloca instead of looking
11920 // at the stack object.
11921 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11922 assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11923 const AllocaInst *AI = ArgCopyIter->second.first;
11924 int FixedIndex = FINode->getIndex();
11925 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11926 int OldIndex = AllocaIndex;
11927 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11928 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11929 LLVM_DEBUG(
11930 dbgs() << " argument copy elision failed due to bad fixed stack "
11931 "object size\n");
11932 return;
11933 }
11934 Align RequiredAlignment = AI->getAlign();
11935 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11936 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
11937 "greater than stack argument alignment ("
11938 << DebugStr(RequiredAlignment) << " vs "
11939 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11940 return;
11941 }
11942
11943 // Perform the elision. Delete the old stack object and replace its only use
11944 // in the variable info map. Mark the stack object as mutable and aliased.
11945 LLVM_DEBUG({
11946 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11947 << " Replacing frame index " << OldIndex << " with " << FixedIndex
11948 << '\n';
11949 });
11950 MFI.RemoveStackObject(OldIndex);
11951 MFI.setIsImmutableObjectIndex(FixedIndex, false);
11952 MFI.setIsAliasedObjectIndex(FixedIndex, true);
11953 AllocaIndex = FixedIndex;
11954 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11955 for (SDValue ArgVal : ArgVals)
11956 Chains.push_back(ArgVal.getValue(1));
11957
11958 // Avoid emitting code for the store implementing the copy.
11959 const StoreInst *SI = ArgCopyIter->second.second;
11960 ElidedArgCopyInstrs.insert(SI);
11961
11962 // Check for uses of the argument again so that we can avoid exporting ArgVal
11963 // if it is't used by anything other than the store.
11964 for (const Value *U : Arg.users()) {
11965 if (U != SI) {
11966 ArgHasUses = true;
11967 break;
11968 }
11969 }
11970}
11971
11972void SelectionDAGISel::LowerArguments(const Function &F) {
11973 SelectionDAG &DAG = SDB->DAG;
11974 SDLoc dl = SDB->getCurSDLoc();
11975 const DataLayout &DL = DAG.getDataLayout();
11977
11978 // In Naked functions we aren't going to save any registers.
11979 if (F.hasFnAttribute(Attribute::Naked))
11980 return;
11981
11982 if (!FuncInfo->CanLowerReturn) {
11983 // Put in an sret pointer parameter before all the other parameters.
11984 MVT ValueVT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
11985
11986 ISD::ArgFlagsTy Flags;
11987 Flags.setSRet();
11988 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVT);
11989 ISD::InputArg RetArg(Flags, RegisterVT, ValueVT, F.getReturnType(), true,
11991 Ins.push_back(RetArg);
11992 }
11993
11994 // Look for stores of arguments to static allocas. Mark such arguments with a
11995 // flag to ask the target to give us the memory location of that argument if
11996 // available.
11997 ArgCopyElisionMapTy ArgCopyElisionCandidates;
11999 ArgCopyElisionCandidates);
12000
12001 // Set up the incoming argument description vector.
12002 for (const Argument &Arg : F.args()) {
12003 unsigned ArgNo = Arg.getArgNo();
12005 ComputeValueTypes(DAG.getDataLayout(), Arg.getType(), Types);
12006 bool isArgValueUsed = !Arg.use_empty();
12007 Type *FinalType = Arg.getType();
12008 if (Arg.hasAttribute(Attribute::ByVal))
12009 FinalType = Arg.getParamByValType();
12010 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
12011 FinalType, F.getCallingConv(), F.isVarArg(), DL);
12012 for (unsigned Value = 0, NumValues = Types.size(); Value != NumValues;
12013 ++Value) {
12014 Type *ArgTy = Types[Value];
12015 EVT VT = TLI->getValueType(DL, ArgTy);
12016 ISD::ArgFlagsTy Flags;
12017
12018 if (ArgTy->isPointerTy()) {
12019 Flags.setPointer();
12020 Flags.setPointerAddrSpace(cast<PointerType>(ArgTy)->getAddressSpace());
12021 }
12022 if (Arg.hasAttribute(Attribute::ZExt))
12023 Flags.setZExt();
12024 if (Arg.hasAttribute(Attribute::SExt))
12025 Flags.setSExt();
12026 if (Arg.hasAttribute(Attribute::InReg)) {
12027 // If we are using vectorcall calling convention, a structure that is
12028 // passed InReg - is surely an HVA
12029 if (F.getCallingConv() == CallingConv::X86_VectorCall &&
12030 isa<StructType>(Arg.getType())) {
12031 // The first value of a structure is marked
12032 if (0 == Value)
12033 Flags.setHvaStart();
12034 Flags.setHva();
12035 }
12036 // Set InReg Flag
12037 Flags.setInReg();
12038 }
12039 if (Arg.hasAttribute(Attribute::StructRet))
12040 Flags.setSRet();
12041 if (Arg.hasAttribute(Attribute::SwiftSelf))
12042 Flags.setSwiftSelf();
12043 if (Arg.hasAttribute(Attribute::SwiftAsync))
12044 Flags.setSwiftAsync();
12045 if (Arg.hasAttribute(Attribute::SwiftError))
12046 Flags.setSwiftError();
12047 if (Arg.hasAttribute(Attribute::ByVal))
12048 Flags.setByVal();
12049 if (Arg.hasAttribute(Attribute::ByRef))
12050 Flags.setByRef();
12051 if (Arg.hasAttribute(Attribute::InAlloca)) {
12052 Flags.setInAlloca();
12053 // Set the byval flag for CCAssignFn callbacks that don't know about
12054 // inalloca. This way we can know how many bytes we should've allocated
12055 // and how many bytes a callee cleanup function will pop. If we port
12056 // inalloca to more targets, we'll have to add custom inalloca handling
12057 // in the various CC lowering callbacks.
12058 Flags.setByVal();
12059 }
12060 if (Arg.hasAttribute(Attribute::Preallocated)) {
12061 Flags.setPreallocated();
12062 // Set the byval flag for CCAssignFn callbacks that don't know about
12063 // preallocated. This way we can know how many bytes we should've
12064 // allocated and how many bytes a callee cleanup function will pop. If
12065 // we port preallocated to more targets, we'll have to add custom
12066 // preallocated handling in the various CC lowering callbacks.
12067 Flags.setByVal();
12068 }
12069
12070 // Certain targets (such as MIPS), may have a different ABI alignment
12071 // for a type depending on the context. Give the target a chance to
12072 // specify the alignment it wants.
12073 const Align OriginalAlignment(
12074 TLI->getABIAlignmentForCallingConv(ArgTy, DL));
12075 Flags.setOrigAlign(OriginalAlignment);
12076
12077 Align MemAlign;
12078 Type *ArgMemTy = nullptr;
12079 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
12080 Flags.isByRef()) {
12081 if (!ArgMemTy)
12082 ArgMemTy = Arg.getPointeeInMemoryValueType();
12083
12084 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
12085
12086 // For in-memory arguments, size and alignment should be passed from FE.
12087 // BE will guess if this info is not there but there are cases it cannot
12088 // get right.
12089 if (auto ParamAlign = Arg.getParamStackAlign())
12090 MemAlign = *ParamAlign;
12091 else if ((ParamAlign = Arg.getParamAlign()))
12092 MemAlign = *ParamAlign;
12093 else
12094 MemAlign = TLI->getByValTypeAlignment(ArgMemTy, DL);
12095 if (Flags.isByRef())
12096 Flags.setByRefSize(MemSize);
12097 else
12098 Flags.setByValSize(MemSize);
12099 } else if (auto ParamAlign = Arg.getParamStackAlign()) {
12100 MemAlign = *ParamAlign;
12101 } else {
12102 MemAlign = OriginalAlignment;
12103 }
12104 Flags.setMemAlign(MemAlign);
12105
12106 if (Arg.hasAttribute(Attribute::Nest))
12107 Flags.setNest();
12108 if (NeedsRegBlock)
12109 Flags.setInConsecutiveRegs();
12110 if (ArgCopyElisionCandidates.count(&Arg))
12111 Flags.setCopyElisionCandidate();
12112 if (Arg.hasAttribute(Attribute::Returned))
12113 Flags.setReturned();
12114
12115 MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
12116 *CurDAG->getContext(), F.getCallingConv(), VT);
12117 unsigned NumRegs = TLI->getNumRegistersForCallingConv(
12118 *CurDAG->getContext(), F.getCallingConv(), VT);
12119 for (unsigned i = 0; i != NumRegs; ++i) {
12120 // For scalable vectors, use the minimum size; individual targets
12121 // are responsible for handling scalable vector arguments and
12122 // return values.
12123 ISD::InputArg MyFlags(
12124 Flags, RegisterVT, VT, ArgTy, isArgValueUsed, ArgNo,
12125 i * RegisterVT.getStoreSize().getKnownMinValue());
12126 if (NumRegs > 1 && i == 0)
12127 MyFlags.Flags.setSplit();
12128 // if it isn't first piece, alignment must be 1
12129 else if (i > 0) {
12130 MyFlags.Flags.setOrigAlign(Align(1));
12131 if (i == NumRegs - 1)
12132 MyFlags.Flags.setSplitEnd();
12133 }
12134 Ins.push_back(MyFlags);
12135 }
12136 if (NeedsRegBlock && Value == NumValues - 1)
12137 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
12138 }
12139 }
12140
12141 // Call the target to set up the argument values.
12143 SDValue NewRoot = TLI->LowerFormalArguments(
12144 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
12145
12146 // Verify that the target's LowerFormalArguments behaved as expected.
12147 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
12148 "LowerFormalArguments didn't return a valid chain!");
12149 assert(InVals.size() == Ins.size() &&
12150 "LowerFormalArguments didn't emit the correct number of values!");
12151 assert(all_of(InVals, [](SDValue InVal) { return InVal.getNode(); }) &&
12152 "LowerFormalArguments emitted a null value!");
12153
12154 // Update the DAG with the new chain value resulting from argument lowering.
12155 DAG.setRoot(NewRoot);
12156
12157 // Set up the argument values.
12158 unsigned i = 0;
12159 if (!FuncInfo->CanLowerReturn) {
12160 // Create a virtual register for the sret pointer, and put in a copy
12161 // from the sret argument into it.
12162 MVT VT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
12163 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
12164 std::optional<ISD::NodeType> AssertOp;
12165 SDValue ArgValue =
12166 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
12167 F.getCallingConv(), AssertOp);
12168
12169 MachineFunction& MF = SDB->DAG.getMachineFunction();
12170 MachineRegisterInfo& RegInfo = MF.getRegInfo();
12171 Register SRetReg =
12172 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
12173 FuncInfo->DemoteRegister = SRetReg;
12174 NewRoot =
12175 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
12176 DAG.setRoot(NewRoot);
12177
12178 // i indexes lowered arguments. Bump it past the hidden sret argument.
12179 ++i;
12180 }
12181
12183 DenseMap<int, int> ArgCopyElisionFrameIndexMap;
12184 for (const Argument &Arg : F.args()) {
12185 SmallVector<SDValue, 4> ArgValues;
12186 SmallVector<EVT, 4> ValueVTs;
12187 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
12188 unsigned NumValues = ValueVTs.size();
12189 if (NumValues == 0)
12190 continue;
12191
12192 bool ArgHasUses = !Arg.use_empty();
12193
12194 // Elide the copying store if the target loaded this argument from a
12195 // suitable fixed stack object.
12196 if (Ins[i].Flags.isCopyElisionCandidate()) {
12197 unsigned NumParts = 0;
12198 for (EVT VT : ValueVTs)
12199 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
12200 F.getCallingConv(), VT);
12201
12202 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
12203 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
12204 ArrayRef(&InVals[i], NumParts), ArgHasUses);
12205 }
12206
12207 // If this argument is unused then remember its value. It is used to generate
12208 // debugging information.
12209 bool isSwiftErrorArg =
12210 TLI->supportSwiftError() &&
12211 Arg.hasAttribute(Attribute::SwiftError);
12212 if (!ArgHasUses && !isSwiftErrorArg) {
12213 SDB->setUnusedArgValue(&Arg, InVals[i]);
12214
12215 // Also remember any frame index for use in FastISel.
12216 if (FrameIndexSDNode *FI =
12218 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12219 }
12220
12221 for (unsigned Val = 0; Val != NumValues; ++Val) {
12222 EVT VT = ValueVTs[Val];
12223 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
12224 F.getCallingConv(), VT);
12225 unsigned NumParts = TLI->getNumRegistersForCallingConv(
12226 *CurDAG->getContext(), F.getCallingConv(), VT);
12227
12228 // Even an apparent 'unused' swifterror argument needs to be returned. So
12229 // we do generate a copy for it that can be used on return from the
12230 // function.
12231 if (ArgHasUses || isSwiftErrorArg) {
12232 std::optional<ISD::NodeType> AssertOp;
12233 if (Arg.hasAttribute(Attribute::SExt))
12234 AssertOp = ISD::AssertSext;
12235 else if (Arg.hasAttribute(Attribute::ZExt))
12236 AssertOp = ISD::AssertZext;
12237
12238 SDValue OutVal =
12239 getCopyFromParts(DAG, dl, &InVals[i], NumParts, PartVT, VT, nullptr,
12240 NewRoot, F.getCallingConv(), AssertOp);
12241
12242 FPClassTest NoFPClass = Arg.getNoFPClass();
12243 if (NoFPClass != fcNone) {
12244 SDValue SDNoFPClass = DAG.getTargetConstant(
12245 static_cast<uint64_t>(NoFPClass), dl, MVT::i32);
12246 OutVal = DAG.getNode(ISD::AssertNoFPClass, dl, OutVal.getValueType(),
12247 OutVal, SDNoFPClass);
12248 }
12249 ArgValues.push_back(OutVal);
12250 }
12251
12252 i += NumParts;
12253 }
12254
12255 // We don't need to do anything else for unused arguments.
12256 if (ArgValues.empty())
12257 continue;
12258
12259 // Note down frame index.
12260 if (FrameIndexSDNode *FI =
12261 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
12262 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12263
12264 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
12265 SDB->getCurSDLoc());
12266
12267 SDB->setValue(&Arg, Res);
12268 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
12269 // We want to associate the argument with the frame index, among
12270 // involved operands, that correspond to the lowest address. The
12271 // getCopyFromParts function, called earlier, is swapping the order of
12272 // the operands to BUILD_PAIR depending on endianness. The result of
12273 // that swapping is that the least significant bits of the argument will
12274 // be in the first operand of the BUILD_PAIR node, and the most
12275 // significant bits will be in the second operand.
12276 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
12277 if (LoadSDNode *LNode =
12278 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
12279 if (FrameIndexSDNode *FI =
12280 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
12281 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12282 }
12283
12284 // Analyses past this point are naive and don't expect an assertion.
12285 if (Res.getOpcode() == ISD::AssertZext)
12286 Res = Res.getOperand(0);
12287
12288 // Update the SwiftErrorVRegDefMap.
12289 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
12290 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
12291 if (Reg.isVirtual())
12292 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
12293 Reg);
12294 }
12295
12296 // If this argument is live outside of the entry block, insert a copy from
12297 // wherever we got it to the vreg that other BB's will reference it as.
12298 if (Res.getOpcode() == ISD::CopyFromReg) {
12299 // If we can, though, try to skip creating an unnecessary vreg.
12300 // FIXME: This isn't very clean... it would be nice to make this more
12301 // general.
12302 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
12303 if (Reg.isVirtual()) {
12304 FuncInfo->ValueMap[&Arg] = Reg;
12305 continue;
12306 }
12307 }
12308 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
12309 FuncInfo->InitializeRegForValue(&Arg);
12310 SDB->CopyToExportRegsIfNeeded(&Arg);
12311 }
12312 }
12313
12314 if (!Chains.empty()) {
12315 Chains.push_back(NewRoot);
12316 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
12317 }
12318
12319 DAG.setRoot(NewRoot);
12320
12321 assert(i == InVals.size() && "Argument register count mismatch!");
12322
12323 // If any argument copy elisions occurred and we have debug info, update the
12324 // stale frame indices used in the dbg.declare variable info table.
12325 if (!ArgCopyElisionFrameIndexMap.empty()) {
12326 for (MachineFunction::VariableDbgInfo &VI :
12327 MF->getInStackSlotVariableDbgInfo()) {
12328 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
12329 if (I != ArgCopyElisionFrameIndexMap.end())
12330 VI.updateStackSlot(I->second);
12331 }
12332 }
12333
12334 // Finally, if the target has anything special to do, allow it to do so.
12336}
12337
12338/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
12339/// ensure constants are generated when needed. Remember the virtual registers
12340/// that need to be added to the Machine PHI nodes as input. We cannot just
12341/// directly add them, because expansion might result in multiple MBB's for one
12342/// BB. As such, the start of the BB might correspond to a different MBB than
12343/// the end.
12344void
12345SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
12346 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12347
12348 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
12349
12350 // Check PHI nodes in successors that expect a value to be available from this
12351 // block.
12352 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
12353 if (!isa<PHINode>(SuccBB->begin())) continue;
12354 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
12355
12356 // If this terminator has multiple identical successors (common for
12357 // switches), only handle each succ once.
12358 if (!SuccsHandled.insert(SuccMBB).second)
12359 continue;
12360
12362
12363 // At this point we know that there is a 1-1 correspondence between LLVM PHI
12364 // nodes and Machine PHI nodes, but the incoming operands have not been
12365 // emitted yet.
12366 for (const PHINode &PN : SuccBB->phis()) {
12367 // Ignore dead phi's.
12368 if (PN.use_empty())
12369 continue;
12370
12371 // Skip empty types
12372 if (PN.getType()->isEmptyTy())
12373 continue;
12374
12375 Register Reg;
12376 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
12377
12378 if (const auto *C = dyn_cast<Constant>(PHIOp)) {
12379 Register &RegOut = ConstantsOut[C];
12380 if (!RegOut) {
12381 RegOut = FuncInfo.CreateRegs(&PN);
12382 // We need to zero/sign extend ConstantInt phi operands to match
12383 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
12384 ISD::NodeType ExtendType = ISD::ANY_EXTEND;
12385 if (auto *CI = dyn_cast<ConstantInt>(C))
12386 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
12388 CopyValueToVirtualRegister(C, RegOut, ExtendType);
12389 }
12390 Reg = RegOut;
12391 } else {
12392 auto I = FuncInfo.ValueMap.find(PHIOp);
12393 if (I != FuncInfo.ValueMap.end())
12394 Reg = I->second;
12395 else {
12396 assert(isa<AllocaInst>(PHIOp) &&
12397 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
12398 "Didn't codegen value into a register!??");
12399 Reg = FuncInfo.CreateRegs(&PN);
12401 }
12402 }
12403
12404 // Remember that this register needs to added to the machine PHI node as
12405 // the input for this MBB.
12406 SmallVector<EVT, 4> ValueVTs;
12407 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
12408 for (EVT VT : ValueVTs) {
12409 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
12410 for (unsigned i = 0; i != NumRegisters; ++i)
12411 FuncInfo.PHINodesToUpdate.emplace_back(&*MBBI++, Reg + i);
12412 Reg += NumRegisters;
12413 }
12414 }
12415 }
12416
12417 ConstantsOut.clear();
12418}
12419
12420MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
12422 if (++I == FuncInfo.MF->end())
12423 return nullptr;
12424 return &*I;
12425}
12426
12427/// During lowering new call nodes can be created (such as memset, etc.).
12428/// Those will become new roots of the current DAG, but complications arise
12429/// when they are tail calls. In such cases, the call lowering will update
12430/// the root, but the builder still needs to know that a tail call has been
12431/// lowered in order to avoid generating an additional return.
12432void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12433 // If the node is null, we do have a tail call.
12434 if (MaybeTC.getNode() != nullptr)
12435 DAG.setRoot(MaybeTC);
12436 else
12437 HasTailCall = true;
12438}
12439
12440void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12441 MachineBasicBlock *SwitchMBB,
12442 MachineBasicBlock *DefaultMBB) {
12443 MachineFunction *CurMF = FuncInfo.MF;
12444 MachineBasicBlock *NextMBB = nullptr;
12446 if (++BBI != FuncInfo.MF->end())
12447 NextMBB = &*BBI;
12448
12449 unsigned Size = W.LastCluster - W.FirstCluster + 1;
12450
12451 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12452
12453 if (Size == 2 && W.MBB == SwitchMBB) {
12454 // If any two of the cases has the same destination, and if one value
12455 // is the same as the other, but has one bit unset that the other has set,
12456 // use bit manipulation to do two compares at once. For example:
12457 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12458 // TODO: This could be extended to merge any 2 cases in switches with 3
12459 // cases.
12460 // TODO: Handle cases where W.CaseBB != SwitchBB.
12461 CaseCluster &Small = *W.FirstCluster;
12462 CaseCluster &Big = *W.LastCluster;
12463
12464 if (Small.Low == Small.High && Big.Low == Big.High &&
12465 Small.MBB == Big.MBB) {
12466 const APInt &SmallValue = Small.Low->getValue();
12467 const APInt &BigValue = Big.Low->getValue();
12468
12469 // Check that there is only one bit different.
12470 APInt CommonBit = BigValue ^ SmallValue;
12471 if (CommonBit.isPowerOf2()) {
12472 SDValue CondLHS = getValue(Cond);
12473 EVT VT = CondLHS.getValueType();
12474 SDLoc DL = getCurSDLoc();
12475
12476 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
12477 DAG.getConstant(CommonBit, DL, VT));
12478 SDValue Cond = DAG.getSetCC(
12479 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
12480 ISD::SETEQ);
12481
12482 // Update successor info.
12483 // Both Small and Big will jump to Small.BB, so we sum up the
12484 // probabilities.
12485 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
12486 if (BPI)
12487 addSuccessorWithProb(
12488 SwitchMBB, DefaultMBB,
12489 // The default destination is the first successor in IR.
12490 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12491 else
12492 addSuccessorWithProb(SwitchMBB, DefaultMBB);
12493
12494 // Insert the true branch.
12495 SDValue BrCond =
12496 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12497 DAG.getBasicBlock(Small.MBB));
12498 // Insert the false branch.
12499 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12500 DAG.getBasicBlock(DefaultMBB));
12501
12502 DAG.setRoot(BrCond);
12503 return;
12504 }
12505 }
12506 }
12507
12508 if (TM.getOptLevel() != CodeGenOptLevel::None) {
12509 // Here, we order cases by probability so the most likely case will be
12510 // checked first. However, two clusters can have the same probability in
12511 // which case their relative ordering is non-deterministic. So we use Low
12512 // as a tie-breaker as clusters are guaranteed to never overlap.
12513 llvm::sort(W.FirstCluster, W.LastCluster + 1,
12514 [](const CaseCluster &a, const CaseCluster &b) {
12515 return a.Prob != b.Prob ?
12516 a.Prob > b.Prob :
12517 a.Low->getValue().slt(b.Low->getValue());
12518 });
12519
12520 // Rearrange the case blocks so that the last one falls through if possible
12521 // without changing the order of probabilities.
12522 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12523 --I;
12524 if (I->Prob > W.LastCluster->Prob)
12525 break;
12526 if (I->Kind == CC_Range && I->MBB == NextMBB) {
12527 std::swap(*I, *W.LastCluster);
12528 break;
12529 }
12530 }
12531 }
12532
12533 // Compute total probability.
12534 BranchProbability DefaultProb = W.DefaultProb;
12535 BranchProbability UnhandledProbs = DefaultProb;
12536 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12537 UnhandledProbs += I->Prob;
12538
12539 MachineBasicBlock *CurMBB = W.MBB;
12540 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12541 bool FallthroughUnreachable = false;
12542 MachineBasicBlock *Fallthrough;
12543 if (I == W.LastCluster) {
12544 // For the last cluster, fall through to the default destination.
12545 Fallthrough = DefaultMBB;
12546 FallthroughUnreachable = isa<UnreachableInst>(
12547 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12548 } else {
12549 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12550 CurMF->insert(BBI, Fallthrough);
12551 // Put Cond in a virtual register to make it available from the new blocks.
12553 }
12554 UnhandledProbs -= I->Prob;
12555
12556 switch (I->Kind) {
12557 case CC_JumpTable: {
12558 // FIXME: Optimize away range check based on pivot comparisons.
12559 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12560 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12561
12562 // The jump block hasn't been inserted yet; insert it here.
12563 MachineBasicBlock *JumpMBB = JT->MBB;
12564 CurMF->insert(BBI, JumpMBB);
12565
12566 auto JumpProb = I->Prob;
12567 auto FallthroughProb = UnhandledProbs;
12568
12569 // If the default statement is a target of the jump table, we evenly
12570 // distribute the default probability to successors of CurMBB. Also
12571 // update the probability on the edge from JumpMBB to Fallthrough.
12572 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12573 SE = JumpMBB->succ_end();
12574 SI != SE; ++SI) {
12575 if (*SI == DefaultMBB) {
12576 JumpProb += DefaultProb / 2;
12577 FallthroughProb -= DefaultProb / 2;
12578 JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12579 JumpMBB->normalizeSuccProbs();
12580 break;
12581 }
12582 }
12583
12584 // If the default clause is unreachable, propagate that knowledge into
12585 // JTH->FallthroughUnreachable which will use it to suppress the range
12586 // check.
12587 //
12588 // However, don't do this if we're doing branch target enforcement,
12589 // because a table branch _without_ a range check can be a tempting JOP
12590 // gadget - out-of-bounds inputs that are impossible in correct
12591 // execution become possible again if an attacker can influence the
12592 // control flow. So if an attacker doesn't already have a BTI bypass
12593 // available, we don't want them to be able to get one out of this
12594 // table branch.
12595 if (FallthroughUnreachable) {
12596 Function &CurFunc = CurMF->getFunction();
12597 if (!CurFunc.hasFnAttribute("branch-target-enforcement"))
12598 JTH->FallthroughUnreachable = true;
12599 }
12600
12601 if (!JTH->FallthroughUnreachable)
12602 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12603 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12604 CurMBB->normalizeSuccProbs();
12605
12606 // The jump table header will be inserted in our current block, do the
12607 // range check, and fall through to our fallthrough block.
12608 JTH->HeaderBB = CurMBB;
12609 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12610
12611 // If we're in the right place, emit the jump table header right now.
12612 if (CurMBB == SwitchMBB) {
12613 visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12614 JTH->Emitted = true;
12615 }
12616 break;
12617 }
12618 case CC_BitTests: {
12619 // FIXME: Optimize away range check based on pivot comparisons.
12620 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12621
12622 // The bit test blocks haven't been inserted yet; insert them here.
12623 for (BitTestCase &BTC : BTB->Cases)
12624 CurMF->insert(BBI, BTC.ThisBB);
12625
12626 // Fill in fields of the BitTestBlock.
12627 BTB->Parent = CurMBB;
12628 BTB->Default = Fallthrough;
12629
12630 BTB->DefaultProb = UnhandledProbs;
12631 // If the cases in bit test don't form a contiguous range, we evenly
12632 // distribute the probability on the edge to Fallthrough to two
12633 // successors of CurMBB.
12634 if (!BTB->ContiguousRange) {
12635 BTB->Prob += DefaultProb / 2;
12636 BTB->DefaultProb -= DefaultProb / 2;
12637 }
12638
12639 if (FallthroughUnreachable)
12640 BTB->FallthroughUnreachable = true;
12641
12642 // If we're in the right place, emit the bit test header right now.
12643 if (CurMBB == SwitchMBB) {
12644 visitBitTestHeader(*BTB, SwitchMBB);
12645 BTB->Emitted = true;
12646 }
12647 break;
12648 }
12649 case CC_Range: {
12650 const Value *RHS, *LHS, *MHS;
12651 ISD::CondCode CC;
12652 if (I->Low == I->High) {
12653 // Check Cond == I->Low.
12654 CC = ISD::SETEQ;
12655 LHS = Cond;
12656 RHS=I->Low;
12657 MHS = nullptr;
12658 } else {
12659 // Check I->Low <= Cond <= I->High.
12660 CC = ISD::SETLE;
12661 LHS = I->Low;
12662 MHS = Cond;
12663 RHS = I->High;
12664 }
12665
12666 // If Fallthrough is unreachable, fold away the comparison.
12667 if (FallthroughUnreachable)
12668 CC = ISD::SETTRUE;
12669
12670 // The false probability is the sum of all unhandled cases.
12671 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12672 getCurSDLoc(), I->Prob, UnhandledProbs);
12673
12674 if (CurMBB == SwitchMBB)
12675 visitSwitchCase(CB, SwitchMBB);
12676 else
12677 SL->SwitchCases.push_back(CB);
12678
12679 break;
12680 }
12681 }
12682 CurMBB = Fallthrough;
12683 }
12684}
12685
12686void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12687 const SwitchWorkListItem &W,
12688 Value *Cond,
12689 MachineBasicBlock *SwitchMBB) {
12690 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12691 "Clusters not sorted?");
12692 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12693
12694 auto [LastLeft, FirstRight, LeftProb, RightProb] =
12695 SL->computeSplitWorkItemInfo(W);
12696
12697 // Use the first element on the right as pivot since we will make less-than
12698 // comparisons against it.
12699 CaseClusterIt PivotCluster = FirstRight;
12700 assert(PivotCluster > W.FirstCluster);
12701 assert(PivotCluster <= W.LastCluster);
12702
12703 CaseClusterIt FirstLeft = W.FirstCluster;
12704 CaseClusterIt LastRight = W.LastCluster;
12705
12706 const ConstantInt *Pivot = PivotCluster->Low;
12707
12708 // New blocks will be inserted immediately after the current one.
12710 ++BBI;
12711
12712 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12713 // we can branch to its destination directly if it's squeezed exactly in
12714 // between the known lower bound and Pivot - 1.
12715 MachineBasicBlock *LeftMBB;
12716 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12717 FirstLeft->Low == W.GE &&
12718 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12719 LeftMBB = FirstLeft->MBB;
12720 } else {
12721 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12722 FuncInfo.MF->insert(BBI, LeftMBB);
12723 WorkList.push_back(
12724 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12725 // Put Cond in a virtual register to make it available from the new blocks.
12727 }
12728
12729 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12730 // single cluster, RHS.Low == Pivot, and we can branch to its destination
12731 // directly if RHS.High equals the current upper bound.
12732 MachineBasicBlock *RightMBB;
12733 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12734 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12735 RightMBB = FirstRight->MBB;
12736 } else {
12737 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12738 FuncInfo.MF->insert(BBI, RightMBB);
12739 WorkList.push_back(
12740 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12741 // Put Cond in a virtual register to make it available from the new blocks.
12743 }
12744
12745 // Create the CaseBlock record that will be used to lower the branch.
12746 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12747 getCurSDLoc(), LeftProb, RightProb);
12748
12749 if (W.MBB == SwitchMBB)
12750 visitSwitchCase(CB, SwitchMBB);
12751 else
12752 SL->SwitchCases.push_back(CB);
12753}
12754
12755// Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12756// from the swith statement.
12758 BranchProbability PeeledCaseProb) {
12759 if (PeeledCaseProb == BranchProbability::getOne())
12761 BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12762
12763 uint32_t Numerator = CaseProb.getNumerator();
12764 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12765 return BranchProbability(Numerator, std::max(Numerator, Denominator));
12766}
12767
12768// Try to peel the top probability case if it exceeds the threshold.
12769// Return current MachineBasicBlock for the switch statement if the peeling
12770// does not occur.
12771// If the peeling is performed, return the newly created MachineBasicBlock
12772// for the peeled switch statement. Also update Clusters to remove the peeled
12773// case. PeeledCaseProb is the BranchProbability for the peeled case.
12774MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12775 const SwitchInst &SI, CaseClusterVector &Clusters,
12776 BranchProbability &PeeledCaseProb) {
12777 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12778 // Don't perform if there is only one cluster or optimizing for size.
12779 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12780 TM.getOptLevel() == CodeGenOptLevel::None ||
12781 SwitchMBB->getParent()->getFunction().hasMinSize())
12782 return SwitchMBB;
12783
12784 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12785 unsigned PeeledCaseIndex = 0;
12786 bool SwitchPeeled = false;
12787 for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12788 CaseCluster &CC = Clusters[Index];
12789 if (CC.Prob < TopCaseProb)
12790 continue;
12791 TopCaseProb = CC.Prob;
12792 PeeledCaseIndex = Index;
12793 SwitchPeeled = true;
12794 }
12795 if (!SwitchPeeled)
12796 return SwitchMBB;
12797
12798 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12799 << TopCaseProb << "\n");
12800
12801 // Record the MBB for the peeled switch statement.
12802 MachineFunction::iterator BBI(SwitchMBB);
12803 ++BBI;
12804 MachineBasicBlock *PeeledSwitchMBB =
12805 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12806 FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12807
12808 ExportFromCurrentBlock(SI.getCondition());
12809 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12810 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12811 nullptr, nullptr, TopCaseProb.getCompl()};
12812 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12813
12814 Clusters.erase(PeeledCaseIt);
12815 for (CaseCluster &CC : Clusters) {
12816 LLVM_DEBUG(
12817 dbgs() << "Scale the probablity for one cluster, before scaling: "
12818 << CC.Prob << "\n");
12819 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12820 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12821 }
12822 PeeledCaseProb = TopCaseProb;
12823 return PeeledSwitchMBB;
12824}
12825
12826void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12827 // Extract cases from the switch.
12828 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12829 CaseClusterVector Clusters;
12830 Clusters.reserve(SI.getNumCases());
12831 for (auto I : SI.cases()) {
12832 MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
12833 const ConstantInt *CaseVal = I.getCaseValue();
12834 BranchProbability Prob =
12835 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12836 : BranchProbability(1, SI.getNumCases() + 1);
12837 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12838 }
12839
12840 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
12841
12842 // Cluster adjacent cases with the same destination. We do this at all
12843 // optimization levels because it's cheap to do and will make codegen faster
12844 // if there are many clusters.
12845 sortAndRangeify(Clusters);
12846
12847 // The branch probablity of the peeled case.
12848 BranchProbability PeeledCaseProb = BranchProbability::getZero();
12849 MachineBasicBlock *PeeledSwitchMBB =
12850 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12851
12852 // If there is only the default destination, jump there directly.
12853 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12854 if (Clusters.empty()) {
12855 assert(PeeledSwitchMBB == SwitchMBB);
12856 SwitchMBB->addSuccessor(DefaultMBB);
12857 if (DefaultMBB != NextBlock(SwitchMBB)) {
12858 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12859 getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12860 }
12861 return;
12862 }
12863
12864 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12865 DAG.getBFI());
12866 SL->findBitTestClusters(Clusters, &SI);
12867
12868 LLVM_DEBUG({
12869 dbgs() << "Case clusters: ";
12870 for (const CaseCluster &C : Clusters) {
12871 if (C.Kind == CC_JumpTable)
12872 dbgs() << "JT:";
12873 if (C.Kind == CC_BitTests)
12874 dbgs() << "BT:";
12875
12876 C.Low->getValue().print(dbgs(), true);
12877 if (C.Low != C.High) {
12878 dbgs() << '-';
12879 C.High->getValue().print(dbgs(), true);
12880 }
12881 dbgs() << ' ';
12882 }
12883 dbgs() << '\n';
12884 });
12885
12886 assert(!Clusters.empty());
12887 SwitchWorkList WorkList;
12888 CaseClusterIt First = Clusters.begin();
12889 CaseClusterIt Last = Clusters.end() - 1;
12890 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12891 // Scale the branchprobability for DefaultMBB if the peel occurs and
12892 // DefaultMBB is not replaced.
12893 if (PeeledCaseProb != BranchProbability::getZero() &&
12894 DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
12895 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12896 WorkList.push_back(
12897 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12898
12899 while (!WorkList.empty()) {
12900 SwitchWorkListItem W = WorkList.pop_back_val();
12901 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12902
12903 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12904 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12905 // For optimized builds, lower large range as a balanced binary tree.
12906 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12907 continue;
12908 }
12909
12910 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12911 }
12912}
12913
12914void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12915 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12916 auto DL = getCurSDLoc();
12917 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12918 setValue(&I, DAG.getStepVector(DL, ResultVT));
12919}
12920
12921void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12922 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12923 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12924
12925 SDLoc DL = getCurSDLoc();
12926 SDValue V = getValue(I.getOperand(0));
12927 assert(VT == V.getValueType() && "Malformed vector.reverse!");
12928
12929 if (VT.isScalableVector()) {
12930 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12931 return;
12932 }
12933
12934 // Use VECTOR_SHUFFLE for the fixed-length vector
12935 // to maintain existing behavior.
12936 SmallVector<int, 8> Mask;
12937 unsigned NumElts = VT.getVectorMinNumElements();
12938 for (unsigned i = 0; i != NumElts; ++i)
12939 Mask.push_back(NumElts - 1 - i);
12940
12941 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12942}
12943
12944void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I,
12945 unsigned Factor) {
12946 auto DL = getCurSDLoc();
12947 SDValue InVec = getValue(I.getOperand(0));
12948
12949 SmallVector<EVT, 4> ValueVTs;
12950 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12951 ValueVTs);
12952
12953 EVT OutVT = ValueVTs[0];
12954 unsigned OutNumElts = OutVT.getVectorMinNumElements();
12955
12956 SmallVector<SDValue, 4> SubVecs(Factor);
12957 for (unsigned i = 0; i != Factor; ++i) {
12958 assert(ValueVTs[i] == OutVT && "Expected VTs to be the same");
12959 SubVecs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12960 DAG.getVectorIdxConstant(OutNumElts * i, DL));
12961 }
12962
12963 // Use VECTOR_SHUFFLE for fixed-length vectors with factor of 2 to benefit
12964 // from existing legalisation and combines.
12965 if (OutVT.isFixedLengthVector() && Factor == 2) {
12966 SDValue Even = DAG.getVectorShuffle(OutVT, DL, SubVecs[0], SubVecs[1],
12967 createStrideMask(0, 2, OutNumElts));
12968 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, SubVecs[0], SubVecs[1],
12969 createStrideMask(1, 2, OutNumElts));
12970 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12971 setValue(&I, Res);
12972 return;
12973 }
12974
12975 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12976 DAG.getVTList(ValueVTs), SubVecs);
12977 setValue(&I, Res);
12978}
12979
12980void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I,
12981 unsigned Factor) {
12982 auto DL = getCurSDLoc();
12983 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12984 EVT InVT = getValue(I.getOperand(0)).getValueType();
12985 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12986
12987 SmallVector<SDValue, 8> InVecs(Factor);
12988 for (unsigned i = 0; i < Factor; ++i) {
12989 InVecs[i] = getValue(I.getOperand(i));
12990 assert(InVecs[i].getValueType() == InVecs[0].getValueType() &&
12991 "Expected VTs to be the same");
12992 }
12993
12994 // Use VECTOR_SHUFFLE for fixed-length vectors with factor of 2 to benefit
12995 // from existing legalisation and combines.
12996 if (OutVT.isFixedLengthVector() && Factor == 2) {
12997 unsigned NumElts = InVT.getVectorMinNumElements();
12998 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVecs);
12999 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
13000 createInterleaveMask(NumElts, 2)));
13001 return;
13002 }
13003
13004 SmallVector<EVT, 8> ValueVTs(Factor, InVT);
13005 SDValue Res =
13006 DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, DAG.getVTList(ValueVTs), InVecs);
13007
13009 for (unsigned i = 0; i < Factor; ++i)
13010 Results[i] = Res.getValue(i);
13011
13012 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Results);
13013 setValue(&I, Res);
13014}
13015
13016void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
13017 SmallVector<EVT, 4> ValueVTs;
13018 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
13019 ValueVTs);
13020 unsigned NumValues = ValueVTs.size();
13021 if (NumValues == 0) return;
13022
13024 SDValue Op = getValue(I.getOperand(0));
13025
13026 for (unsigned i = 0; i != NumValues; ++i)
13027 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
13028 SDValue(Op.getNode(), Op.getResNo() + i));
13029
13031 DAG.getVTList(ValueVTs), Values));
13032}
13033
13034void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
13035 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13036 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13037
13038 SDLoc DL = getCurSDLoc();
13039 SDValue V1 = getValue(I.getOperand(0));
13040 SDValue V2 = getValue(I.getOperand(1));
13041 const bool IsLeft = I.getIntrinsicID() == Intrinsic::vector_splice_left;
13042
13043 // VECTOR_SHUFFLE doesn't support a scalable or non-constant mask.
13044 if (VT.isScalableVector() || !isa<ConstantInt>(I.getOperand(2))) {
13045 SDValue Offset = DAG.getZExtOrTrunc(
13046 getValue(I.getOperand(2)), DL, TLI.getVectorIdxTy(DAG.getDataLayout()));
13047 setValue(&I, DAG.getNode(IsLeft ? ISD::VECTOR_SPLICE_LEFT
13049 DL, VT, V1, V2, Offset));
13050 return;
13051 }
13052 uint64_t Imm = cast<ConstantInt>(I.getOperand(2))->getZExtValue();
13053
13054 unsigned NumElts = VT.getVectorNumElements();
13055
13056 uint64_t Idx = IsLeft ? Imm : NumElts - Imm;
13057
13058 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
13059 SmallVector<int, 8> Mask;
13060 for (unsigned i = 0; i < NumElts; ++i)
13061 Mask.push_back(Idx + i);
13062 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
13063}
13064
13065// Consider the following MIR after SelectionDAG, which produces output in
13066// phyregs in the first case or virtregs in the second case.
13067//
13068// INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
13069// %5:gr32 = COPY $ebx
13070// %6:gr32 = COPY $edx
13071// %1:gr32 = COPY %6:gr32
13072// %0:gr32 = COPY %5:gr32
13073//
13074// INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
13075// %1:gr32 = COPY %6:gr32
13076// %0:gr32 = COPY %5:gr32
13077//
13078// Given %0, we'd like to return $ebx in the first case and %5 in the second.
13079// Given %1, we'd like to return $edx in the first case and %6 in the second.
13080//
13081// If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
13082// to a single virtreg (such as %0). The remaining outputs monotonically
13083// increase in virtreg number from there. If a callbr has no outputs, then it
13084// should not have a corresponding callbr landingpad; in fact, the callbr
13085// landingpad would not even be able to refer to such a callbr.
13088 // There is definitely at least one copy.
13089 assert(MI->getOpcode() == TargetOpcode::COPY &&
13090 "start of copy chain MUST be COPY");
13091 Reg = MI->getOperand(1).getReg();
13092
13093 // If the copied register in the first copy must be virtual.
13094 assert(Reg.isVirtual() && "expected COPY of virtual register");
13095 MI = MRI.def_begin(Reg)->getParent();
13096
13097 // There may be an optional second copy.
13098 if (MI->getOpcode() == TargetOpcode::COPY) {
13099 assert(Reg.isVirtual() && "expected COPY of virtual register");
13100 Reg = MI->getOperand(1).getReg();
13101 assert(Reg.isPhysical() && "expected COPY of physical register");
13102 } else {
13103 // The start of the chain must be an INLINEASM_BR.
13104 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
13105 "end of copy chain MUST be INLINEASM_BR");
13106 }
13107
13108 return Reg;
13109}
13110
13111// We must do this walk rather than the simpler
13112// setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
13113// otherwise we will end up with copies of virtregs only valid along direct
13114// edges.
13115void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
13116 SmallVector<EVT, 8> ResultVTs;
13117 SmallVector<SDValue, 8> ResultValues;
13118 const auto *CBR =
13119 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
13120
13121 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13122 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
13123 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
13124
13125 Register InitialDef = FuncInfo.ValueMap[CBR];
13126 SDValue Chain = DAG.getRoot();
13127
13128 // Re-parse the asm constraints string.
13129 TargetLowering::AsmOperandInfoVector TargetConstraints =
13130 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
13131 for (auto &T : TargetConstraints) {
13132 SDISelAsmOperandInfo OpInfo(T);
13133 if (OpInfo.Type != InlineAsm::isOutput)
13134 continue;
13135
13136 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
13137 // individual constraint.
13138 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
13139
13140 switch (OpInfo.ConstraintType) {
13143 // Fill in OpInfo.AssignedRegs.Regs.
13144 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
13145
13146 // getRegistersForValue may produce 1 to many registers based on whether
13147 // the OpInfo.ConstraintVT is legal on the target or not.
13148 for (Register &Reg : OpInfo.AssignedRegs.Regs) {
13149 Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
13150 if (OriginalDef.isPhysical())
13151 FuncInfo.MBB->addLiveIn(OriginalDef);
13152 // Update the assigned registers to use the original defs.
13153 Reg = OriginalDef;
13154 }
13155
13156 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
13157 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
13158 ResultValues.push_back(V);
13159 ResultVTs.push_back(OpInfo.ConstraintVT);
13160 break;
13161 }
13163 SDValue Flag;
13164 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
13165 OpInfo, DAG);
13166 ++InitialDef;
13167 ResultValues.push_back(V);
13168 ResultVTs.push_back(OpInfo.ConstraintVT);
13169 break;
13170 }
13171 default:
13172 break;
13173 }
13174 }
13176 DAG.getVTList(ResultVTs), ResultValues);
13177 setValue(&I, V);
13178}
return SDValue()
static unsigned getIntrinsicID(const SDNode *N)
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
unsigned Imm
unsigned uint64_t
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:857
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:942
#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)
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
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 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 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.
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:183
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:6131
Class for arbitrary precision integers.
Definition APInt.h:78
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:331
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:437
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:336
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:407
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.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
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:43
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 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
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
bool empty() const
Definition DenseMap.h:171
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:134
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:176
Diagnostic information for inline asm reporting.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:311
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:316
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:867
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:742
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:730
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.
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:68
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)
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.
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:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:633
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.
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.
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.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
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,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
def_iterator def_begin(Register RegNo) const
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI MCRegister getLiveInPhysReg(Register VReg) const
getLiveInPhysReg - If VReg is a live-in virtual register, return the corresponding live-in physical r...
An SDNode that represents everything that will be needed to construct a MachineInstr.
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition MapVector.h:118
bool contains(const KeyT &Key) const
Definition MapVector.h:148
static MemoryLocation getAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location after Ptr, while remaining within the underlying objec...
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:184
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
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:911
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)
Holds the information from a dbg_value node through SDISel.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
const DebugLoc & getDebugLoc() const
Represents one node in the SelectionDAG.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
iterator_range< value_op_iterator > op_values() const
unsigned getIROrder() const
Return the node ordering.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getOpcode() const
SelectionDAGBuilder - This is the common target-independent lowering implementation that is parameter...
SDValue getValue(const Value *V)
getValue - Return an SDValue for the given Value.
bool shouldKeepJumpConditionsTogether(const FunctionLoweringInfo &FuncInfo, const CondBrInst &I, Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, TargetLoweringBase::CondMergingParams Params) const
DenseMap< const Constant *, Register > ConstantsOut
void addDanglingDebugInfo(SmallVectorImpl< Value * > &Values, DILocalVariable *Var, DIExpression *Expr, bool IsVariadic, DebugLoc DL, unsigned Order)
Register a dbg_value which relies on a Value which we have not yet seen.
void visitDbgInfo(const Instruction &I)
void clearDanglingDebugInfo()
Clear the dangling debug information map.
SDValue lowerStartEH(SDValue Chain, const BasicBlock *EHPadBB, MCSymbol *&BeginLabel)
void LowerCallTo(const CallBase &CB, SDValue Callee, bool IsTailCall, bool IsMustTailCall, const BasicBlock *EHPadBB=nullptr, const TargetLowering::PtrAuthInfo *PAI=nullptr)
void clear()
Clear out the current SelectionDAG and the associated state and prepare this SelectionDAGBuilder obje...
void visitBitTestHeader(SwitchCG::BitTestBlock &B, MachineBasicBlock *SwitchBB)
visitBitTestHeader - This function emits necessary code to produce value suitable for "bit tests"
void LowerStatepoint(const GCStatepointInst &I, const BasicBlock *EHPadBB=nullptr)
std::unique_ptr< SDAGSwitchLowering > SL
SDValue lowerRangeToAssertZExt(SelectionDAG &DAG, const Instruction &I, SDValue Op)
bool HasTailCall
This is set to true if a call in the current block has been translated as a tail call.
bool ShouldEmitAsBranches(const std::vector< SwitchCG::CaseBlock > &Cases)
If the set of cases should be emitted as a series of branches, return true.
void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB, MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB, BranchProbability TProb, BranchProbability FProb, bool InvertCond)
EmitBranchForMergedCondition - Helper method for FindMergedConditions.
void LowerDeoptimizeCall(const CallInst *CI)
void LowerCallSiteWithDeoptBundle(const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB)
SwiftErrorValueTracking & SwiftError
Information about the swifterror values used throughout the function.
SDValue getNonRegisterValue(const Value *V)
getNonRegisterValue - Return an SDValue for the given Value, but don't look in FuncInfo....
const TargetTransformInfo * TTI
DenseMap< MachineBasicBlock *, SmallVector< unsigned, 4 > > LPadToCallSiteMap
Map a landing pad to the call site indexes.
SDValue lowerNoFPClassToAssertNoFPClass(SelectionDAG &DAG, const Instruction &I, SDValue Op)
void handleDebugDeclare(Value *Address, DILocalVariable *Variable, DIExpression *Expression, DebugLoc DL)
StatepointLoweringState StatepointLowering
State used while lowering a statepoint sequence (gc_statepoint, gc_relocate, and gc_result).
void setValueToPoison(const Value *V, const SDLoc &dl)
void visitBitTestCase(SwitchCG::BitTestBlock &BB, MachineBasicBlock *NextMBB, BranchProbability BranchProbToNext, Register Reg, SwitchCG::BitTestCase &B, MachineBasicBlock *SwitchBB)
visitBitTestCase - this function produces one "bit test"
bool canTailCall(const CallBase &CB) const
void populateCallLoweringInfo(TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, AttributeSet RetAttrs, bool IsPatchPoint)
Populate a CallLowerinInfo (into CLI) based on the properties of the call being lowered.
void CopyValueToVirtualRegister(const Value *V, Register Reg, ISD::NodeType ExtendType=ISD::ANY_EXTEND)
void salvageUnresolvedDbgValue(const Value *V, DanglingDebugInfo &DDI)
For the given dangling debuginfo record, perform last-ditch efforts to resolve the debuginfo to somet...
SmallVector< SDValue, 8 > PendingLoads
Loads are not emitted to the program immediately.
GCFunctionInfo * GFI
Garbage collection metadata for the function.
void init(GCFunctionInfo *gfi, BatchAAResults *BatchAA, AssumptionCache *AC, const TargetLibraryInfo *li, const TargetTransformInfo &TTI)
SDValue getRoot()
Similar to getMemoryRoot, but also flushes PendingConstrainedFP(Strict) items.
void ExportFromCurrentBlock(const Value *V)
ExportFromCurrentBlock - If this condition isn't known to be exported from the current basic block,...
void resolveOrClearDbgInfo()
Evict any dangling debug information, attempting to salvage it first.
std::pair< SDValue, SDValue > lowerInvokable(TargetLowering::CallLoweringInfo &CLI, const BasicBlock *EHPadBB=nullptr)
SDValue getMemoryRoot()
Return the current virtual root of the Selection DAG, flushing any PendingLoad items.
void resolveDanglingDebugInfo(const Value *V, SDValue Val)
If we saw an earlier dbg_value referring to V, generate the debug data structures now that we've seen...
void visit(const Instruction &I)
void dropDanglingDebugInfo(const DILocalVariable *Variable, const DIExpression *Expr)
If we have dangling debug info that describes Variable, or an overlapping part of variable considerin...
SDValue getCopyFromRegs(const Value *V, Type *Ty)
If there was virtual register allocated for the value V emit CopyFromReg of the specified type Ty.
void CopyToExportRegsIfNeeded(const Value *V)
CopyToExportRegsIfNeeded - If the given value has virtual registers created for it,...
void handleKillDebugValue(DILocalVariable *Var, DIExpression *Expr, DebugLoc DbgLoc, unsigned Order)
Create a record for a kill location debug intrinsic.
void visitJumpTable(SwitchCG::JumpTable &JT)
visitJumpTable - Emit JumpTable node in the current MBB
SDValue getFPOperationRoot(fp::ExceptionBehavior EB)
Return the current virtual root of the Selection DAG, flushing PendingConstrainedFP or PendingConstra...
void visitJumpTableHeader(SwitchCG::JumpTable &JT, SwitchCG::JumpTableHeader &JTH, MachineBasicBlock *SwitchBB)
visitJumpTableHeader - This function emits necessary code to produce index in the JumpTable from swit...
void LowerCallSiteWithPtrAuthBundle(const CallBase &CB, const BasicBlock *EHPadBB)
static const unsigned LowestSDNodeOrder
Lowest valid SDNodeOrder.
FunctionLoweringInfo & FuncInfo
Information about the function as a whole.
void setValue(const Value *V, SDValue NewN)
void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB, MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB, Instruction::BinaryOps Opc, BranchProbability TProb, BranchProbability FProb, bool InvertCond)
const TargetLibraryInfo * LibInfo
bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB)
void visitSPDescriptorParent(StackProtectorDescriptor &SPD, MachineBasicBlock *ParentBB)
Codegen a new tail for a stack protector check ParentMBB which has had its tail spliced into a stack ...
bool handleDebugValue(ArrayRef< const Value * > Values, DILocalVariable *Var, DIExpression *Expr, DebugLoc DbgLoc, unsigned Order, bool IsVariadic)
For a given list of Values, attempt to create and record a SDDbgValue in the SelectionDAG.
SDValue getControlRoot()
Similar to getRoot, but instead of flushing all the PendingLoad items, flush all the PendingExports (...
void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last)
When an MBB was split during scheduling, update the references that need to refer to the last resulti...
SDValue getValueImpl(const Value *V)
getValueImpl - Helper function for getValue and getNonRegisterValue.
void visitSwitchCase(SwitchCG::CaseBlock &CB, MachineBasicBlock *SwitchBB)
visitSwitchCase - Emits the necessary code to represent a single node in the binary search tree resul...
void visitSPDescriptorFailure(StackProtectorDescriptor &SPD)
Codegen the failure basic block for a stack protector check.
std::unique_ptr< FunctionLoweringInfo > FuncInfo
SmallPtrSet< const Instruction *, 4 > ElidedArgCopyInstrs
const TargetLowering * TLI
MachineRegisterInfo * RegInfo
std::unique_ptr< SwiftErrorValueTracking > SwiftError
virtual void emitFunctionEntryCode()
std::unique_ptr< SelectionDAGBuilder > SDB
virtual std::pair< SDValue, SDValue > EmitTargetCodeForMemccpy(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, SDValue C, SDValue Size, const CallInst *CI) const
Emit target-specific code that performs a memccpy, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrnlen(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, SDValue Src, SDValue MaxLength, MachinePointerInfo SrcPtrInfo) const
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrlen(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, SDValue Src, const CallInst *CI) const
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrstr(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Op1, SDValue Op2, const CallInst *CI) const
Emit target-specific code that performs a strstr, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForMemchr(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Src, SDValue Char, SDValue Length, MachinePointerInfo SrcPtrInfo) const
Emit target-specific code that performs a memchr, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrcmp(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Op1, SDValue Op2, MachinePointerInfo Op1PtrInfo, MachinePointerInfo Op2PtrInfo, const CallInst *CI) const
Emit target-specific code that performs a strcmp, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForMemcmp(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Op1, SDValue Op2, SDValue Op3, const CallInst *CI) const
Emit target-specific code that performs a memcmp/bcmp, in cases where that is faster than a libcall.
virtual SDValue EmitTargetCodeForSetTag(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Addr, SDValue Size, MachinePointerInfo DstPtrInfo, bool ZeroData) const
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrcpy(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, SDValue Dest, SDValue Src, MachinePointerInfo DestPtrInfo, MachinePointerInfo SrcPtrInfo, bool isStpcpy, const CallInst *CI) const
Emit target-specific code that performs a strcpy or stpcpy, in cases where that is faster than a libc...
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT, unsigned Opcode)
Convert Op, which must be of integer type, to the integer type VT, by either any/sign/zero-extending ...
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI void ExtractVectorElements(SDValue Op, SmallVectorImpl< SDValue > &Args, unsigned Start=0, unsigned Count=0, EVT EltVT=EVT())
Append the extracted elements from Start to Count out of the vector Op in Args.
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
LLVM_ABI bool shouldOptForSize() const
const TargetLowering & getTargetLoweringInfo() const
static constexpr unsigned MaxRecursionDepth
LLVM_ABI void AddDbgValue(SDDbgValue *DB, bool isParameter)
Add a dbg_value SDNode.
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
LLVM_ABI SDDbgValue * getDbgValueList(DIVariable *Var, DIExpression *Expr, ArrayRef< SDDbgOperand > Locs, ArrayRef< SDNode * > Dependencies, bool IsIndirect, const DebugLoc &DL, unsigned O, bool IsVariadic)
Creates a SDDbgValue node from a list of locations.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
const DataLayout & getDataLayout() const
SDValue getTargetFrameIndex(int FI, EVT VT)
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
LLVM_ABI SDValue getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI SDValue getBasicBlock(MachineBasicBlock *MBB)
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getEHLabel(const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI SDValue getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either truncating it or perform...
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
const LibcallLoweringInfo & getLibcalls() const
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
MachineFunction & getMachineFunction() const
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVMContext * getContext() const
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void swap(SmallVectorImpl &RHS)
void resize(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Encapsulates all of the information needed to generate a stack protector check, and signals to isel w...
MachineBasicBlock * getSuccessMBB()
MachineBasicBlock * getFailureMBB()
MachineBasicBlock * getParentMBB()
bool shouldEmitFunctionBasedCheckStackProtector() const
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Multiway switch.
Information about stack frame layout on the target.
virtual TargetStackID::Value getStackIDForScalableVectors() const
Returns the StackID that scalable vectors should be associated with.
Provides information about what library functions are available for the current target.
virtual Align getByValTypeAlignment(Type *Ty, const DataLayout &DL) const
Returns the desired alignment for ByVal or InAlloca aggregate function arguments in the caller parame...
virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT) const
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
EVT getMemValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
virtual bool isAtomicAlignmentSupported(Align Alignment, uint64_t SizeInBytes) const
Return true if the target supports an atomic access of SizeInBytes bytes at the given Alignment.
Function * getSSPStackGuardCheck(const Module &M, const LibcallLoweringInfo &Libcalls) const
If the target has a standard stack protection check function that performs validation and error handl...
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
LegalizeAction
This enum indicates whether operations are valid for a target, and if not, what action should be used...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
virtual bool isLegalScaleForGatherScatter(uint64_t Scale, uint64_t ElemSize) const
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
const TargetMachine & getTargetMachine() const
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
virtual MachineMemOperand::Flags getTargetMMOFlags(const Instruction &I) const
This callback is used to inspect load/store instructions and add target-specific MachineMemOperand fl...
virtual Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception typeid on entry to a la...
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
virtual bool useStackGuardMixFP() const
If this function returns true, stack protection checks should mix the frame pointer (or whichever poi...
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
virtual unsigned getNumRegisters(LLVMContext &Context, EVT VT, std::optional< MVT > RegisterVT=std::nullopt) const
Return the number of registers that this ValueType will eventually require.
MachineMemOperand::Flags getLoadMemOperandFlags(const LoadInst &LI, const DataLayout &DL, AssumptionCache *AC=nullptr, const TargetLibraryInfo *LibInfo=nullptr, CodeGenOptLevel OptLevel=CodeGenOptLevel::Default) const
virtual bool shouldExtendGSIndex(EVT VT, EVT &EltTy) const
Returns true if the index type for a masked gather/scatter requires extending.
virtual unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
LegalizeAction getFixedPointOperationAction(unsigned Op, EVT VT, unsigned Scale) const
Some fixed point operations may be natively supported by the target but only for specific scales.
MachineMemOperand::Flags getAtomicMemOperandFlags(const Instruction &AI, const DataLayout &DL) const
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
bool isOperationCustom(unsigned Op, EVT VT) const
Return true if the operation uses custom lowering, regardless of whether the type is legal or not.
bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const
When splitting a value of the specified type into parts, does the Lo or Hi part come first?
EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const
Returns the type for the shift amount of a shift opcode.
virtual Align getABIAlignmentForCallingConv(Type *ArgTy, const DataLayout &DL) const
Certain targets have context sensitive alignment requirements, where one type has the alignment requi...
MachineMemOperand::Flags getVPIntrinsicMemOperandFlags(const VPIntrinsic &VPIntrin) const
virtual bool shouldExpandGetActiveLaneMask(EVT VT, EVT OpVT) const
Return true if the @llvm.get.active.lane.mask intrinsic should be expanded using generic code in Sele...
virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const
Return the ValueType of the result of SETCC operations.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
MVT getProgramPointerTy(const DataLayout &DL) const
Return the type for code pointers, which is determined by the program address space specified through...
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const
virtual MVT getFenceOperandTy(const DataLayout &DL) const
Return the type for operands of fence.
virtual bool shouldExpandGetVectorLength(EVT CountVT, unsigned VF, bool IsScalable) const
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Vector types are broken down into some number of legal first class types.
virtual MVT hasFastEqualityCompare(unsigned NumBits) const
Return the preferred operand type if the target has a quick way to compare integer values of the give...
MachineMemOperand::Flags getStoreMemOperandFlags(const StoreInst &SI, const DataLayout &DL) const
virtual void getTgtMemIntrinsic(SmallVectorImpl< IntrinsicInfo > &Infos, const CallBase &I, MachineFunction &MF, unsigned Intrinsic) const
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
virtual bool signExtendConstant(const ConstantInt *C) const
Return true if this constant should be sign extended when promoting to a larger type.
virtual Value * getSDagStackGuard(const Module &M, const LibcallLoweringInfo &Libcalls) const
Return the variable that's previously inserted by insertSSPDeclarations, if any, otherwise return nul...
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
std::vector< ArgListEntry > ArgListTy
virtual Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception address on entry to an ...
bool isBeneficialToExpandPowI(int64_t Exponent, bool OptForSize) const
Return true if it is beneficial to expand an @llvm.powi.
MVT getFrameIndexTy(const DataLayout &DL) const
Return the type for frame index, which is determined by the alloca address space specified through th...
virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS=0) const
Return the in-memory pointer type for the given address space, defaults to the pointer type from the ...
virtual MVT getVPExplicitVectorLengthTy() const
Returns the type to be used for the EVL/AVL operand of VP nodes: ISD::VP_UDIV, ISD::VP_SDIV,...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual bool supportKCFIBundles() const
Return true if the target supports kcfi operand bundles.
virtual bool supportPtrAuthBundles() const
Return true if the target supports ptrauth operand bundles.
virtual bool supportSwiftError() const
Return true if the target supports swifterror attribute.
virtual SDValue visitMaskedLoad(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, MachineMemOperand *MMO, SDValue &NewLoad, SDValue Ptr, SDValue PassThru, SDValue Mask) const
virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT, ISD::NodeType) const
Return the type that should be used to zero or sign extend a zeroext/signext integer return value.
virtual Register getRegisterByName(const char *RegName, LLT Ty, const MachineFunction &MF) const
Return the register ID of the name passed in.
virtual InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const
std::vector< AsmOperandInfo > AsmOperandInfoVector
SDValue expandIS_FPCLASS(EVT ResultVT, SDValue Op, FPClassTest Test, SDNodeFlags Flags, const SDLoc &DL, SelectionDAG &DAG) const
Expand check for floating point class.
virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL, SelectionDAG &DAG) const
This callback is used to prepare for a volatile or atomic load.
virtual SDValue emitStackGuardMixFP(SelectionDAG &DAG, SDValue Val, const SDLoc &DL) const
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual bool splitValueIntoRegisterParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, std::optional< CallingConv::ID > CC) const
Target-specific splitting of values into parts that fit a register storing a legal type.
virtual SDValue joinRegisterPartsIntoValue(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, std::optional< CallingConv::ID > CC) const
Target-specific combining of register parts into its original value.
virtual SDValue LowerCall(CallLoweringInfo &, SmallVectorImpl< SDValue > &) const
This hook must be implemented to lower calls into the specified DAG.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
virtual SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Glue, const SDLoc &DL, const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, const CallBase &Call) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const
This callback is invoked for operations that are unsupported by the target, which are registered to u...
virtual bool functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv, bool isVarArg, const DataLayout &DL) const
For some targets, an LLVM struct type must be broken down into multiple simple types,...
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo,...
virtual void CollectTargetIntrinsicOperands(const CallInst &I, SmallVectorImpl< SDValue > &Ops, SelectionDAG &DAG) const
virtual SDValue visitMaskedStore(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, MachineMemOperand *MMO, SDValue Ptr, SDValue Val, SDValue Mask) const
virtual bool useLoadStackGuardNode(const Module &M) const
If this function returns true, SelectionDAGBuilder emits a LOAD_STACK_GUARD node when it is lowering ...
SDValue annotateStackObjectPointer(SDValue Ptr, SelectionDAG &DAG, const SDLoc &DL, Align Alignment) const
Annotate a stack object pointer with known-bits assertions.
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
virtual void LowerOperationWrapper(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const
This callback is invoked by the type legalizer to legalize nodes with an illegal operand type but leg...
virtual bool isInlineAsmTargetBranch(const SmallVectorImpl< StringRef > &AsmStrs, unsigned OpNo) const
On x86, return true if the operand with index OpNo is a CALL or JUMP instruction, which can use eithe...
virtual MVT getJumpTableRegTy(const DataLayout &DL) const
virtual bool CanLowerReturn(CallingConv::ID, MachineFunction &, bool, const SmallVectorImpl< ISD::OutputArg > &, LLVMContext &, const Type *RetTy) const
This hook should be implemented to check whether the return values described by the Outs array can fi...
Primary interface to the complete machine description for the target machine.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
ExceptionHandling getExceptionModel() const
Return the ExceptionHandling to use, considering TargetOptions and the Triple's default.
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:339
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:180
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
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:282
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
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:306
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:236
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
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:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
bool use_empty() const
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
Base class of all SIMD vector types.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
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:41
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:261
@ 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:513
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:45
@ SET_FPENV
Sets the current floating-point environment.
@ ATOMIC_LOAD_FMINIMUMNUM
@ LOOP_DEPENDENCE_RAW_MASK
@ 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:168
@ VECREDUCE_FMINIMUMNUM
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:602
@ STACKADDRESS
STACKADDRESS - Represents the llvm.stackaddress intrinsic.
Definition ISDOpcodes.h:127
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:789
@ SMULFIX
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition ISDOpcodes.h:394
@ 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:264
@ SMULFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:400
@ 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:863
@ 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:520
@ 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:220
@ EH_SJLJ_SETUP_DISPATCH
OUTCHAIN = EH_SJLJ_SETUP_DISPATCH(INCHAIN) The target initializes the dispatch table here.
Definition ISDOpcodes.h:172
@ GlobalAddress
Definition ISDOpcodes.h:88
@ 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:890
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:586
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:417
@ 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:749
@ 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:530
@ FPTRUNC_ROUND
FPTRUNC_ROUND - This corresponds to the fptrunc_round intrinsic.
Definition ISDOpcodes.h:517
@ 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:254
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:780
@ 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:407
@ 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:798
@ EH_RETURN
OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER) - This node represents 'eh_return' gcc dwarf builtin,...
Definition ISDOpcodes.h:156
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
@ SET_ROUNDING
Set rounding mode.
Definition ISDOpcodes.h:985
@ CONVERGENCECTRL_GLUE
This does not correspond to any convergence control intrinsic.
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:854
@ 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:117
@ 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:352
@ 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:637
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:543
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:550
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:374
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:806
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:247
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:674
@ 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:81
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:230
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:348
@ 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:980
@ 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:771
@ AssertNoFPClass
AssertNoFPClass - These nodes record if a register contains a float value that is known to be not som...
Definition ISDOpcodes.h:78
@ PtrAuthGlobalAddress
A ptrauth constant.
Definition ISDOpcodes.h:100
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:616
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition ISDOpcodes.h:48
@ READ_REGISTER
READ_REGISTER, WRITE_REGISTER - This node represents llvm.register on the DAG, which implements the n...
Definition ISDOpcodes.h:139
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:578
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:860
@ 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:135
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ 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:386
@ PATCHPOINT
The llvm.experimental.patchpoint.
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:356
@ 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:655
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:729
@ 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:642
@ SDIVFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:413
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:988
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:815
@ 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:150
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:110
@ ATOMIC_LOAD_UDEC_WRAP
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:785
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:502
@ FMINIMUM
FMINIMUM/FMAXIMUM - NaN-propagating minimum/maximum that also treat -0.0 as less than 0....
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:936
@ 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:741
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:205
@ SCMP
[US]CMP - 3-way comparison of signed or unsigned integers.
Definition ISDOpcodes.h:737
@ 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:659
@ STRICT_FADD
Constrained versions of the binary floating point operators.
Definition ISDOpcodes.h:427
@ 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:241
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:567
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:53
@ 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:797
@ 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:969
@ VECTOR_COMPRESS
VECTOR_COMPRESS(Vec, Mask, Passthru) consecutively place vector elements based on mask e....
Definition ISDOpcodes.h:701
@ SPONENTRY
SPONENTRY - Represents the llvm.sponentry intrinsic.
Definition ISDOpcodes.h:122
@ 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:955
@ VECREDUCE_FMINIMUM
@ EH_SJLJ_SETJMP
RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer) This corresponds to the eh.sjlj....
Definition ISDOpcodes.h:162
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:866
@ 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:62
@ ATOMIC_LOAD_UINC_WRAP
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:536
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:365
@ VECTOR_DEINTERLEAVE
VECTOR_DEINTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor ...
Definition ISDOpcodes.h:626
@ 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 - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ 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:213
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:753
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:558
@ 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
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 ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred)
getICmpCondCode - Return the ISD condition code corresponding to the given LLVM IR integer condition ...
Definition Analysis.cpp:237
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:1739
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:1669
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
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
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:119
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
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)
@ 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:2208
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:541
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:2173
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:1151
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:72
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:1746
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
@ 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:853
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
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:144
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:299
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:203
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:2304
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.
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
@ 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
@ 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:539
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:225
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:2192
LLVM_ABI GlobalValue * ExtractTypeInfo(Value *V)
ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Definition Analysis.cpp:181
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
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:2166
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:33
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
@ Default
The result value is uniform if and only if all operands are uniform.
Definition Uniformity.h:20
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:77
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
uint64_t getScalarStoreSize() const
Definition ValueTypes.h:425
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
ElementCount getVectorElementCount() const
Definition ValueTypes.h:373
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:382
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
EVT changeVectorElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a vector type whose attributes match ourselves with the exception of the element type...
Definition ValueTypes.h:98
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
bool isRISCVVectorTuple() const
Return true if this is a vector value type.
Definition ValueTypes.h:197
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:404
bool isFixedLengthVector() const
Definition ValueTypes.h:199
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
Definition ValueTypes.h:315
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:187
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
EVT changeElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a type whose attributes match ourselves with the exception of the element type that i...
Definition ValueTypes.h:121
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
void setPointerAddrSpace(unsigned AS)
InputArg - This struct carries flags and type information about a single incoming (formal) argument o...
static const unsigned NoArgIndex
Sentinel value for implicit machine-level input arguments.
OutputArg - This struct carries flags and a value for a single outgoing (actual) argument or outgoing...
ConstraintPrefix Type
Type - The basic type of the constraint: input/output/clobber/label.
Definition InlineAsm.h:128
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getUnknownStack(MachineFunction &MF)
Stack memory without other information.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
A lightweight accessor for an operand bundle meant to be passed around by value.
This struct represents the registers (physical or virtual) that a particular set of values is assigne...
SmallVector< std::pair< Register, TypeSize >, 4 > getRegsAndSizes() const
Return a list of registers and their sizes.
RegsForValue()=default
SmallVector< unsigned, 4 > RegCount
This list holds the number of registers for each value.
SmallVector< EVT, 4 > ValueVTs
The value types of the values, which may not be legal, and may need be promoted or synthesized from o...
SmallVector< Register, 4 > Regs
This list holds the registers assigned to the values.
void AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, unsigned MatchingIdx, const SDLoc &dl, SelectionDAG &DAG, std::vector< SDValue > &Ops) const
Add this value to the specified inlineasm node operand list.
SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo, const SDLoc &dl, SDValue &Chain, SDValue *Glue, const Value *V=nullptr) const
Emit a series of CopyFromReg nodes that copies from this value and returns the result as a ValueVTs v...
SmallVector< MVT, 4 > RegVTs
The value types of the registers.
void getCopyToRegs(SDValue Val, SelectionDAG &DAG, const SDLoc &dl, SDValue &Chain, SDValue *Glue, const Value *V=nullptr, ISD::NodeType PreferredExtendType=ISD::ANY_EXTEND) const
Emit a series of CopyToReg nodes that copies the specified value into the registers specified by this...
std::optional< CallingConv::ID > CallConv
Records if this value needs to be treated in an ABI dependant manner, different to normal type legali...
bool occupiesMultipleRegs() const
Check if the total RegCount is greater than one.
These are IR-level optimization flags that may be propagated to SDNodes.
void copyFMF(const FPMathOperator &FPMO)
Propagate the fast-math-flags from an IR FPMathOperator.
void setUnpredictable(bool b)
bool hasAllowReassociation() const
void setNoUnsignedWrap(bool b)
void setNoSignedWrap(bool b)
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342
This structure is used to communicate between SelectionDAGBuilder and SDISel for the code generation ...
SDLoc DL
The debug location of the instruction this CaseBlock was produced from.
static CaseCluster range(const ConstantInt *Low, const ConstantInt *High, MachineBasicBlock *MBB, BranchProbability Prob)
Register Reg
The virtual register containing the index of the jump table entry to jump to.
MachineBasicBlock * Default
The MBB of the default bb, which is a successor of the range check MBB.
unsigned JTI
The JumpTableIndex for this jump table in the function.
MachineBasicBlock * MBB
The MBB into which to emit the code for the indirect jump.
std::optional< SDLoc > SL
The debug location of the instruction this JumpTable was produced from.
This contains information for each constraint that we are lowering.
TargetLowering::ConstraintType ConstraintType
Information about the constraint code, e.g.
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setConvergent(bool Value=true)
CallLoweringInfo & setDeactivationSymbol(GlobalValue *Sym)
CallLoweringInfo & setCFIType(const ConstantInt *Type)
SmallVector< ISD::InputArg, 32 > Ins
Type * OrigRetTy
Original unlegalized return type.
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setIsPatchPoint(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setTailCall(bool Value=true)
CallLoweringInfo & setIsPreallocated(bool Value=true)
CallLoweringInfo & setConvergenceControlToken(SDValue Token)
SmallVector< ISD::OutputArg, 32 > Outs
Type * RetTy
Same as OrigRetTy, or partially legalized for soft float libcalls.
CallLoweringInfo & setChain(SDValue InChain)
CallLoweringInfo & setPtrAuth(PtrAuthInfo Value)
CallLoweringInfo & setCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList, AttributeSet ResultAttrs={})
This structure is used to pass arguments to makeLibCall function.
MakeLibCallOptions & setDiscardResult(bool Value=true)
This structure contains the information necessary for lowering pointer-authenticating indirect calls.
LLVM_ABI void addIPToStateRange(const InvokeInst *II, MCSymbol *InvokeBegin, MCSymbol *InvokeEnd)