clang 24.0.0git
InterpBuiltin.cpp
Go to the documentation of this file.
1//===--- InterpBuiltin.cpp - Interpreter for the constexpr VM ---*- C++ -*-===//
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//===----------------------------------------------------------------------===//
9#include "Boolean.h"
10#include "Char.h"
11#include "EvalEmitter.h"
12#include "Interp.h"
14#include "InterpHelpers.h"
15#include "PrimType.h"
16#include "Program.h"
18#include "clang/AST/ExprCXX.h"
20#include "clang/AST/OSLog.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/Support/AllocToken.h"
27#include "llvm/Support/CRC.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/MathExtras.h"
30#include "llvm/Support/SipHash.h"
31
32namespace clang {
33namespace interp {
34
35[[maybe_unused]] static bool isNoopBuiltin(unsigned ID) {
36 switch (ID) {
37 case Builtin::BIas_const:
38 case Builtin::BIforward:
39 case Builtin::BIforward_like:
40 case Builtin::BImove:
41 case Builtin::BImove_if_noexcept:
42 case Builtin::BIaddressof:
43 case Builtin::BI__addressof:
44 case Builtin::BI__builtin_addressof:
45 case Builtin::BI__builtin_launder:
46 return true;
47 default:
48 return false;
49 }
50 return false;
51}
52
54 switch (T) {
55 case PT_Sint8:
56 case PT_Uint8:
57 case PT_Sint16:
58 case PT_Uint16:
59 case PT_Sint32:
60 case PT_Uint32:
61 case PT_Sint64:
62 case PT_Uint64:
63 case PT_Bool:
64 return true;
65 default:
66 return false;
67 }
68}
69
70static void discard(InterpStack &Stk, PrimType T) {
71 TYPE_SWITCH(T, { Stk.discard<T>(); });
72}
73
74static bool popToUInt64(const InterpState &S, const Expr *E, uint64_t &Out) {
76 const auto &Val = S.Stk.pop<T>();
77 if (!Val.isNumber())
78 return false;
79 Out = static_cast<uint64_t>(Val);
80 return true;
81 });
82}
83
84static bool popToAPSInt(InterpStack &Stk, PrimType T, APSInt &Out) {
86 const auto &Val = Stk.pop<T>();
87 if (!Val.isNumber())
88 return false;
89 Out = Val.toAPSInt();
90 return true;
91 });
92}
93
94static bool popToAPSInt(InterpState &S, const Expr *E, APSInt &Out) {
95 return popToAPSInt(S.Stk, *S.getContext().classify(E->getType()), Out);
96}
97static bool popToAPSInt(InterpState &S, QualType T, APSInt &Out) {
98 return popToAPSInt(S.Stk, *S.getContext().classify(T), Out);
99}
100
101/// Check for common reasons a pointer can't be read from, which
102/// are usually not diagnosed in a builtin function.
103static bool isReadable(const Pointer &P) {
104 if (P.isDummy())
105 return false;
106 if (!P.isReadablePointerType())
107 return false;
108 if (!P.isLive())
109 return false;
110 if (P.isOnePastEnd())
111 return false;
112 return true;
113}
114
115/// Pushes \p Val on the stack as the type given by \p QT.
116static void pushInteger(InterpState &S, const APSInt &Val, QualType QT) {
119 OptPrimType T = *S.getContext().classify(QT);
120 assert(T);
121
122 if (T == PT_IntAPS) {
123 unsigned BitWidth = S.getASTContext().getIntWidth(QT);
124 auto Result = S.allocAP<IntegralAP<true>>(BitWidth);
125 Result.copy(Val.extOrTrunc(BitWidth));
127 return;
128 }
129
130 if (T == PT_IntAP) {
131 unsigned BitWidth = S.getASTContext().getIntWidth(QT);
132 auto Result = S.allocAP<IntegralAP<false>>(BitWidth);
133 Result.copy(Val.extOrTrunc(BitWidth));
135 return;
136 }
137
138 if (isSignedType(*T)) {
139 int64_t V = Val.getSExtValue();
140 INT_TYPE_SWITCH(*T, { S.Stk.push<T>(T::from(V)); });
141 } else {
143 uint64_t V = Val.getZExtValue();
144 INT_TYPE_SWITCH(*T, { S.Stk.push<T>(T::from(V)); });
145 }
146}
147
148template <typename T>
149static void pushInteger(InterpState &S, T Val, QualType QT) {
150 if constexpr (std::is_same_v<T, APInt>)
151 pushInteger(S, APSInt(Val, !std::is_signed_v<T>), QT);
152 else if constexpr (std::is_same_v<T, APSInt>)
153 pushInteger(S, Val, QT);
154 else
155 pushInteger(S,
156 APSInt(APInt(sizeof(T) * 8, static_cast<uint64_t>(Val),
157 std::is_signed_v<T>),
158 !std::is_signed_v<T>),
159 QT);
160}
161
162static void assignIntegral(InterpState &S, const Pointer &Dest, PrimType ValueT,
163 const APSInt &Value) {
164
165 if (ValueT == PT_IntAPS) {
166 Dest.deref<IntegralAP<true>>() =
167 S.allocAP<IntegralAP<true>>(Value.getBitWidth());
168 Dest.deref<IntegralAP<true>>().copy(Value);
169 } else if (ValueT == PT_IntAP) {
170 Dest.deref<IntegralAP<false>>() =
171 S.allocAP<IntegralAP<false>>(Value.getBitWidth());
172 Dest.deref<IntegralAP<false>>().copy(Value);
173 } else if (ValueT == PT_Bool) {
174 Dest.deref<Boolean>() = Boolean::from(!Value.isZero());
175 } else {
177 ValueT, { Dest.deref<T>() = T::from(static_cast<T>(Value)); });
178 }
179}
180
181static QualType getElemType(const Pointer &P) {
182 if (P.isStringPointer()) {
183 return P.asStringPointer()
184 .getLiteral()
185 ->getType()
187 ->getElementType();
188 }
189
190 if (P.isOpaquePointer() || P.isIntegralPointer())
191 return P.getType();
192
193 const Descriptor *Desc = P.getFieldDesc();
194 QualType T = Desc->getType();
195 if (Desc->isPrimitive())
196 return T;
197 if (T->isPointerType())
198 return T->castAs<PointerType>()->getPointeeType();
199 if (Desc->isArray())
200 return Desc->getElemQualType();
201 if (const auto *AT = T->getAsArrayTypeUnsafe())
202 return AT->getElementType();
203 return T;
204}
205
207 unsigned ID) {
208 if (!S.diagnosing())
209 return;
210
211 auto Loc = S.Current->getSource(OpPC);
212 if (S.getLangOpts().CPlusPlus11)
213 S.CCEDiag(Loc, diag::note_constexpr_invalid_function)
214 << /*isConstexpr=*/0 << /*isConstructor=*/0
216 else
217 S.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
218}
219
221 const Pointer &Ptr, AccessKinds AK) {
222 S.FFDiag(S.Current->getSource(OpPC),
223 diag::note_constexpr_access_unreadable_object)
224 << AK << Ptr.toDiagnosticString(S.getASTContext());
225 noteValueLocation(S, Ptr);
226 return false;
227}
228
229static llvm::APSInt convertBoolVectorToInt(const Pointer &Val) {
230 assert(Val.getFieldDesc()->isPrimitiveArray() &&
232 "Not a boolean vector");
233 unsigned NumElems = Val.getNumElems();
234
235 // Each element is one bit, so create an integer with NumElts bits.
236 llvm::APSInt Result(NumElems, 0);
237 for (unsigned I = 0; I != NumElems; ++I) {
238 if (Val.elem<bool>(I))
239 Result.setBit(I);
240 }
241
242 return Result;
243}
244
245// Strict double -> float conversion used for X86 PD2PS/cvtsd2ss intrinsics.
246// Reject NaN/Inf/Subnormal inputs and any lossy/inexact conversions.
247static bool convertDoubleToFloatStrict(const APFloat &Src, Floating &Dst,
248 InterpState &S, const Expr *DiagExpr) {
249 if (Src.isInfinity()) {
250 if (S.diagnosing())
251 S.CCEDiag(DiagExpr, diag::note_constexpr_float_arithmetic) << 0;
252 return false;
253 }
254 if (Src.isNaN()) {
255 if (S.diagnosing())
256 S.CCEDiag(DiagExpr, diag::note_constexpr_float_arithmetic) << 1;
257 return false;
258 }
259 APFloat Val = Src;
260 bool LosesInfo = false;
261 APFloat::opStatus Status = Val.convert(
262 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
263 if (LosesInfo || Val.isDenormal()) {
264 if (S.diagnosing())
265 S.CCEDiag(DiagExpr, diag::note_constexpr_float_arithmetic_strict);
266 return false;
267 }
268 if (Status != APFloat::opOK) {
269 if (S.diagnosing())
270 S.CCEDiag(DiagExpr, diag::note_invalid_subexpr_in_const_expr);
271 return false;
272 }
273 Dst.copy(Val);
274 return true;
275}
276
278 const InterpFrame *Frame,
279 const CallExpr *Call) {
280 unsigned Depth = S.FrameDepth;
281 auto isStdCall = [](const FunctionDecl *F) -> bool {
282 return F && F->isInStdNamespace() && F->getIdentifier() &&
283 F->getIdentifier()->isStr("is_constant_evaluated");
284 };
285 const InterpFrame *Caller = Frame->Caller;
286 // The current frame is the one for __builtin_is_constant_evaluated.
287 // The one above that, potentially the one for std::is_constant_evaluated().
289 S.getEvalStatus().Diag &&
290 (Depth == 0 || (Depth == 1 && isStdCall(Frame->getCallee())))) {
291 if (Caller && isStdCall(Frame->getCallee())) {
292 const Expr *E = Caller->getExpr(Caller->getRetPC());
293 S.report(E->getExprLoc(),
294 diag::warn_is_constant_evaluated_always_true_constexpr)
295 << "std::is_constant_evaluated" << E->getSourceRange();
296 } else {
297 S.report(Call->getExprLoc(),
298 diag::warn_is_constant_evaluated_always_true_constexpr)
299 << "__builtin_is_constant_evaluated" << Call->getSourceRange();
300 }
301 }
302
304 return true;
305}
306
307// __builtin_assume
308// __assume (MS extension)
310 const InterpFrame *Frame,
311 const CallExpr *Call) {
312 // Nothing to be done here since the argument is NOT evaluated.
313 assert(Call->getNumArgs() == 1);
314 return true;
315}
316
318 const InterpFrame *Frame,
319 const CallExpr *Call, unsigned ID) {
320 uint64_t Limit = ~static_cast<uint64_t>(0);
321 if (ID == Builtin::BIstrncmp || ID == Builtin::BI__builtin_strncmp ||
322 ID == Builtin::BIwcsncmp || ID == Builtin::BI__builtin_wcsncmp) {
323 if (!popToUInt64(S, Call->getArg(2), Limit))
324 return false;
325 }
326
327 const Pointer &B = S.Stk.pop<Pointer>();
328 const Pointer &A = S.Stk.pop<Pointer>();
329 if (ID == Builtin::BIstrcmp || ID == Builtin::BIstrncmp ||
330 ID == Builtin::BIwcscmp || ID == Builtin::BIwcsncmp)
331 diagnoseNonConstexprBuiltin(S, OpPC, ID);
332
333 if (Limit == 0) {
334 pushInteger(S, 0, Call->getType());
335 return true;
336 }
337
338 if (!CheckLive(S, OpPC, A, AK_Read) || !CheckLive(S, OpPC, B, AK_Read))
339 return false;
340
341 if (!A.isReadablePointerType() || !B.isReadablePointerType())
342 return false;
343
344 if (A.isDummy() || B.isDummy() || A.isUnknownSizeArray() ||
346 return false;
347
348 bool IsWide = ID == Builtin::BIwcscmp || ID == Builtin::BIwcsncmp ||
349 ID == Builtin::BI__builtin_wcscmp ||
350 ID == Builtin::BI__builtin_wcsncmp;
351
352 QualType ElemTy = getElemType(A);
353 // Different element types shouldn't happen, but with casts they can.
354 if (!S.getASTContext().hasSameUnqualifiedType(ElemTy, getElemType(B)) ||
355 !S.getContext().canClassify(ElemTy))
356 return false;
357
358 PrimType ElemT = *S.getContext().classify(ElemTy);
359
360 auto returnResult = [&](int V) -> bool {
361 pushInteger(S, V, Call->getType());
362 return true;
363 };
364
365 unsigned IndexA = A.getIndex();
366 unsigned IndexB = B.getIndex();
367 unsigned NumElemsA = A.getNumElems();
368 unsigned NumElemsB = B.getNumElems();
369 uint64_t Steps = 0;
370 for (;; ++IndexA, ++IndexB, ++Steps) {
371
372 if (Steps >= Limit)
373 break;
374
375 // Diagnose this as a read of one-past-the-end.
376 if (IndexA >= NumElemsA || IndexB >= NumElemsB) {
377 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_past_end)
378 << AK_Read << S.Current->getRange(OpPC);
379 return false;
380 }
381
382 if (IsWide) {
383 INT_TYPE_SWITCH(ElemT, {
384 T CA = A.loadElem<T>(IndexA);
385 T CB = B.loadElem<T>(IndexB);
386 if (CA > CB)
387 return returnResult(1);
388 if (CA < CB)
389 return returnResult(-1);
390 if (CA.isZero() || CB.isZero())
391 return returnResult(0);
392 });
393 continue;
394 }
395
396 uint8_t CA = A.loadElem<uint8_t>(IndexA);
397 uint8_t CB = B.loadElem<uint8_t>(IndexB);
398
399 if (CA > CB)
400 return returnResult(1);
401 if (CA < CB)
402 return returnResult(-1);
403 if (CA == 0 || CB == 0)
404 return returnResult(0);
405 }
406
407 return returnResult(0);
408}
409
411 const InterpFrame *Frame,
412 const CallExpr *Call, unsigned ID) {
413 const Pointer &StrPtr = S.Stk.pop<Pointer>().expand();
414
415 if (ID == Builtin::BIstrlen || ID == Builtin::BIwcslen)
416 diagnoseNonConstexprBuiltin(S, OpPC, ID);
417
418 if (StrPtr.isConstexprUnknown())
419 return false;
420
421 if (!CheckArray(S, OpPC, StrPtr))
422 return false;
423
424 if (!CheckLive(S, OpPC, StrPtr, AK_Read))
425 return false;
426
427 // For string literal pointers, this is pretty simple.
428 if (StrPtr.isStringPointer()) {
429 if (StrPtr.isOnePastEnd())
430 return CheckRange(S, OpPC, StrPtr, AK_Read);
431
432 const auto *Lit = StrPtr.asStringPointer().getLiteral();
433 int64_t Off = StrPtr.getByteOffset();
434 if (Off < 0)
435 return false;
436
437 UnsignedOrNone ZeroIndex = Lit->findZeroCodeUnit(Off);
438 if (!ZeroIndex)
439 return false;
440 pushInteger(S, *ZeroIndex, Call->getType());
441 return true;
442 }
443
444 if (!StrPtr.isBlockPointer())
445 return false;
446
447 if (!CheckDummy(S, OpPC, StrPtr, AK_Read))
448 return false;
449
450 if (!StrPtr.getFieldDesc()->isPrimitiveArray())
451 return false;
452
453 assert(StrPtr.getFieldDesc()->isPrimitiveArray());
454 PrimType ElemT = StrPtr.getFieldDesc()->getPrimType();
455 if (!isFixedSizeIntegralType(ElemT))
456 return false;
457
458 unsigned ElemSize = StrPtr.getFieldDesc()->getElemDataSize();
459 if (ElemSize != 1 && ElemSize != 2 && ElemSize != 4)
460 return Invalid(S, OpPC);
461
462 if (ID == Builtin::BI__builtin_wcslen || ID == Builtin::BIwcslen) {
463 const ASTContext &AC = S.getASTContext();
464 unsigned WCharSize = AC.getTypeSizeInChars(AC.getWCharType()).getQuantity();
465 if (ElemSize != WCharSize)
466 return false;
467 }
468
469 size_t Len = 0;
470 for (size_t I = StrPtr.getIndex();; ++I, ++Len) {
471 PtrView ElemPtr = StrPtr.view().atIndex(I);
472
473 if (!CheckRange(S, OpPC, ElemPtr, AK_Read))
474 return false;
475
476 uint32_t Val;
478 ElemT, { Val = static_cast<uint32_t>(ElemPtr.deref<T>()); });
479 if (Val == 0)
480 break;
481 }
482
483 pushInteger(S, Len, Call->getType());
484
485 return true;
486}
487
489 const InterpFrame *Frame, const CallExpr *Call,
490 bool Signaling) {
491 const Pointer &Arg = S.Stk.pop<Pointer>();
492
493 if (!CheckLoad(S, OpPC, Arg))
494 return false;
495
496 // Convert the given string to an integer using StringRef's API.
497 llvm::APInt Fill;
498 if (Arg.isBlockPointer()) {
499 if (!Arg.getFieldDesc()->isPrimitiveArray())
500 return Invalid(S, OpPC);
501
502 std::string Str;
503 unsigned ArgLength = Arg.getNumElems();
504 bool FoundZero = false;
505 for (unsigned I = 0; I != ArgLength; ++I) {
506 if (!Arg.isElementInitialized(I))
507 return false;
508
509 if (Arg.loadElem<int8_t>(I) == 0) {
510 FoundZero = true;
511 break;
512 }
513 Str += Arg.elem<char>(I);
514 }
515
516 // If we didn't find a NUL byte, diagnose as a one-past-the-end read.
517 if (!FoundZero)
518 return CheckRange(S, OpPC, Arg.atIndex(ArgLength), AK_Read);
519
520 // Treat empty strings as if they were zero.
521 if (Str.empty())
522 Fill = llvm::APInt(32, 0);
523 else if (StringRef(Str).getAsInteger(0, Fill))
524 return false;
525 } else if (Arg.isStringPointer()) {
526 if (!Arg.asStringPointer().getLiteral()->isOrdinary())
527 return false;
528 StringRef Str = Arg.asStringPointer().getLiteral()->getString();
529 // Treat empty strings as if they were zero.
530 if (Str.empty())
531 Fill = llvm::APInt(32, 0);
532 else if (StringRef(Str).getAsInteger(0, Fill))
533 return false;
534 } else {
535 return false;
536 }
537
538 const llvm::fltSemantics &TargetSemantics =
540 Call->getDirectCallee()->getReturnType());
541
542 Floating Result = S.allocFloat(TargetSemantics);
544 if (Signaling)
545 Result.copy(
546 llvm::APFloat::getSNaN(TargetSemantics, /*Negative=*/false, &Fill));
547 else
548 Result.copy(
549 llvm::APFloat::getQNaN(TargetSemantics, /*Negative=*/false, &Fill));
550 } else {
551 // Prior to IEEE 754-2008, architectures were allowed to choose whether
552 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
553 // a different encoding to what became a standard in 2008, and for pre-
554 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
555 // sNaN. This is now known as "legacy NaN" encoding.
556 if (Signaling)
557 Result.copy(
558 llvm::APFloat::getQNaN(TargetSemantics, /*Negative=*/false, &Fill));
559 else
560 Result.copy(
561 llvm::APFloat::getSNaN(TargetSemantics, /*Negative=*/false, &Fill));
562 }
563
565 return true;
566}
567
569 const InterpFrame *Frame,
570 const CallExpr *Call) {
571 const llvm::fltSemantics &TargetSemantics =
573 Call->getDirectCallee()->getReturnType());
574
575 Floating Result = S.allocFloat(TargetSemantics);
576 Result.copy(APFloat::getInf(TargetSemantics));
578 return true;
579}
580
582 const InterpFrame *Frame) {
583 const Floating &Arg2 = S.Stk.pop<Floating>();
584 const Floating &Arg1 = S.Stk.pop<Floating>();
585 Floating Result = S.allocFloat(Arg1.getSemantics());
586
587 APFloat Copy = Arg1.getAPFloat();
588 Copy.copySign(Arg2.getAPFloat());
589 Result.copy(Copy);
591
592 return true;
593}
594
596 const InterpFrame *Frame, bool IsNumBuiltin) {
597 const Floating &RHS = S.Stk.pop<Floating>();
598 const Floating &LHS = S.Stk.pop<Floating>();
599 Floating Result = S.allocFloat(LHS.getSemantics());
600
601 if (IsNumBuiltin)
602 Result.copy(llvm::minimumnum(LHS.getAPFloat(), RHS.getAPFloat()));
603 else
604 Result.copy(minnum(LHS.getAPFloat(), RHS.getAPFloat()));
606 return true;
607}
608
610 const InterpFrame *Frame, bool IsNumBuiltin) {
611 const Floating &RHS = S.Stk.pop<Floating>();
612 const Floating &LHS = S.Stk.pop<Floating>();
613 Floating Result = S.allocFloat(LHS.getSemantics());
614
615 if (IsNumBuiltin)
616 Result.copy(llvm::maximumnum(LHS.getAPFloat(), RHS.getAPFloat()));
617 else
618 Result.copy(maxnum(LHS.getAPFloat(), RHS.getAPFloat()));
620 return true;
621}
622
623/// Defined as __builtin_isnan(...), to accommodate the fact that it can
624/// take a float, double, long double, etc.
625/// But for us, that's all a Floating anyway.
627 const InterpFrame *Frame,
628 const CallExpr *Call) {
629 const Floating &Arg = S.Stk.pop<Floating>();
630
631 pushInteger(S, Arg.isNan(), Call->getType());
632 return true;
633}
634
636 const InterpFrame *Frame,
637 const CallExpr *Call) {
638 const Floating &Arg = S.Stk.pop<Floating>();
639
640 pushInteger(S, Arg.isSignaling(), Call->getType());
641 return true;
642}
643
645 const InterpFrame *Frame, bool CheckSign,
646 const CallExpr *Call) {
647 const Floating &Arg = S.Stk.pop<Floating>();
648 APFloat F = Arg.getAPFloat();
649 bool IsInf = F.isInfinity();
650
651 if (CheckSign)
652 pushInteger(S, IsInf ? (F.isNegative() ? -1 : 1) : 0, Call->getType());
653 else
654 pushInteger(S, IsInf, Call->getType());
655 return true;
656}
657
659 const InterpFrame *Frame,
660 const CallExpr *Call) {
661 const Floating &Arg = S.Stk.pop<Floating>();
662
663 pushInteger(S, Arg.isFinite(), Call->getType());
664 return true;
665}
666
668 const InterpFrame *Frame,
669 const CallExpr *Call) {
670 const Floating &Arg = S.Stk.pop<Floating>();
671
672 pushInteger(S, Arg.isNormal(), Call->getType());
673 return true;
674}
675
677 const InterpFrame *Frame,
678 const CallExpr *Call) {
679 const Floating &Arg = S.Stk.pop<Floating>();
680
681 pushInteger(S, Arg.isDenormal(), Call->getType());
682 return true;
683}
684
686 const InterpFrame *Frame,
687 const CallExpr *Call) {
688 const Floating &Arg = S.Stk.pop<Floating>();
689
690 pushInteger(S, Arg.isZero(), Call->getType());
691 return true;
692}
693
695 const InterpFrame *Frame,
696 const CallExpr *Call) {
697 const Floating &Arg = S.Stk.pop<Floating>();
698
699 pushInteger(S, Arg.isNegative(), Call->getType());
700 return true;
701}
702
704 const CallExpr *Call, unsigned ID) {
705 const Floating &RHS = S.Stk.pop<Floating>();
706 const Floating &LHS = S.Stk.pop<Floating>();
707
708 // iseqsig raises "invalid" for unordered operands. Don't fold that away
709 // when FP exceptions are modeled.
710 if (ID == Builtin::BI__builtin_iseqsig && !S.inConstantContext() &&
711 LHS.compare(RHS) == ComparisonCategoryResult::Unordered &&
712 Call->getFPFeaturesInEffect(S.getASTContext().getLangOpts())
713 .isFPConstrained()) {
714 S.FFDiag(Call, diag::note_constexpr_float_arithmetic_strict);
715 return false;
716 }
717
719 S,
720 [&] {
721 switch (ID) {
722 case Builtin::BI__builtin_isgreater:
723 return LHS > RHS;
724 case Builtin::BI__builtin_isgreaterequal:
725 return LHS >= RHS;
726 case Builtin::BI__builtin_isless:
727 return LHS < RHS;
728 case Builtin::BI__builtin_islessequal:
729 return LHS <= RHS;
730 case Builtin::BI__builtin_islessgreater: {
731 ComparisonCategoryResult Cmp = LHS.compare(RHS);
734 }
735 case Builtin::BI__builtin_isunordered:
737 case Builtin::BI__builtin_iseqsig:
738 return LHS.compare(RHS) == ComparisonCategoryResult::Equal;
739 default:
740 llvm_unreachable("Unexpected builtin ID: Should be a floating point "
741 "comparison function");
742 }
743 }(),
744 Call->getType());
745 return true;
746}
747
748/// First parameter to __builtin_isfpclass is the floating value, the
749/// second one is an integral value.
751 const InterpFrame *Frame,
752 const CallExpr *Call) {
753 APSInt FPClassArg;
754 if (!popToAPSInt(S, Call->getArg(1), FPClassArg))
755 return false;
756 const Floating &F = S.Stk.pop<Floating>();
757
758 int32_t Result = static_cast<int32_t>(
759 (F.classify() & std::move(FPClassArg)).getZExtValue());
760 pushInteger(S, Result, Call->getType());
761
762 return true;
763}
764
765/// Five int values followed by one floating value.
766/// __builtin_fpclassify(int, int, int, int, int, float)
768 const InterpFrame *Frame,
769 const CallExpr *Call) {
770 const Floating &Val = S.Stk.pop<Floating>();
771
772 PrimType IntT = *S.getContext().classify(Call->getArg(0));
773 APSInt Values[5];
774 for (unsigned I = 0; I != 5; ++I) {
775 if (!popToAPSInt(S.Stk, IntT, Values[4 - I]))
776 return false;
777 }
778
779 unsigned Index;
780 switch (Val.getCategory()) {
781 case APFloat::fcNaN:
782 Index = 0;
783 break;
784 case APFloat::fcInfinity:
785 Index = 1;
786 break;
787 case APFloat::fcNormal:
788 Index = Val.isDenormal() ? 3 : 2;
789 break;
790 case APFloat::fcZero:
791 Index = 4;
792 break;
793 }
794
795 // The last argument is first on the stack.
796 assert(Index <= 4);
797
798 pushInteger(S, Values[Index], Call->getType());
799 return true;
800}
801
802static inline Floating abs(InterpState &S, const Floating &In) {
803 if (!In.isNegative())
804 return In;
805
806 Floating Output = S.allocFloat(In.getSemantics());
807 APFloat New = In.getAPFloat();
808 New.changeSign();
809 Output.copy(New);
810 return Output;
811}
812
813// The C standard says "fabs raises no floating-point exceptions,
814// even if x is a signaling NaN. The returned value is independent of
815// the current rounding direction mode." Therefore constant folding can
816// proceed without regard to the floating point settings.
817// Reference, WG14 N2478 F.10.4.3
819 const InterpFrame *Frame) {
820 const Floating &Val = S.Stk.pop<Floating>();
821 S.Stk.push<Floating>(abs(S, Val));
822 return true;
823}
824
826 const InterpFrame *Frame,
827 const CallExpr *Call) {
828 APSInt Val;
829 if (!popToAPSInt(S, Call->getArg(0), Val))
830 return false;
831 if (Val ==
832 APSInt(APInt::getSignedMinValue(Val.getBitWidth()), /*IsUnsigned=*/false))
833 return false;
834 if (Val.isNegative())
835 Val.negate();
836 pushInteger(S, Val, Call->getType());
837 return true;
838}
839
841 const InterpFrame *Frame,
842 const CallExpr *Call) {
843 APSInt Val;
844 if (Call->getArg(0)->getType()->isExtVectorBoolType()) {
845 const Pointer &Arg = S.Stk.pop<Pointer>();
846 Val = convertBoolVectorToInt(Arg);
847 } else {
848 if (!popToAPSInt(S, Call->getArg(0), Val))
849 return false;
850 }
851 pushInteger(S, Val.popcount(), Call->getType());
852 return true;
853}
854
856 const InterpFrame *Frame,
857 const CallExpr *Call,
858 unsigned DataBytes) {
859 uint64_t DataVal;
860 if (!popToUInt64(S, Call->getArg(1), DataVal))
861 return false;
862 uint64_t CRCVal;
863 if (!popToUInt64(S, Call->getArg(0), CRCVal))
864 return false;
865
866 // CRC32C polynomial (iSCSI polynomial, bit-reversed)
867 static const uint32_t CRC32C_POLY = 0x82F63B78;
868
869 uint32_t Result = llvm::calculateReflectedCRC32(
870 static_cast<uint32_t>(CRCVal), DataVal, DataBytes, CRC32C_POLY);
871
872 pushInteger(S, Result, Call->getType());
873 return true;
874}
875
877 const InterpFrame *Frame,
878 const CallExpr *Call) {
879 // This is an unevaluated call, so there are no arguments on the stack.
880 assert(Call->getNumArgs() == 1);
881 const Expr *Arg = Call->getArg(0);
882
883 GCCTypeClass ResultClass =
885 int32_t ReturnVal = static_cast<int32_t>(ResultClass);
886 pushInteger(S, ReturnVal, Call->getType());
887 return true;
888}
889
890// __builtin_expect(long, long)
891// __builtin_expect_with_probability(long, long, double)
893 const InterpFrame *Frame,
894 const CallExpr *Call) {
895 // The return value is simply the value of the first parameter.
896 // We ignore the probability.
897 unsigned NumArgs = Call->getNumArgs();
898 assert(NumArgs == 2 || NumArgs == 3);
899
900 PrimType ArgT = *S.getContext().classify(Call->getArg(0)->getType());
901 if (NumArgs == 3)
902 S.Stk.discard<Floating>();
903 discard(S.Stk, ArgT);
904 // Top of the stack is now the first paramter. Leave it there as the return
905 // value.
906
907 return true;
908}
909
911 const InterpFrame *Frame,
912 const CallExpr *Call) {
913#ifndef NDEBUG
914 assert(Call->getArg(0)->isLValue());
915 PrimType PtrT = S.getContext().classify(Call->getArg(0)).value_or(PT_Ptr);
916 assert(PtrT == PT_Ptr &&
917 "Unsupported pointer type passed to __builtin_addressof()");
918#endif
919 return true;
920}
921
923 const InterpFrame *Frame,
924 const CallExpr *Call) {
925 return Call->getDirectCallee()->isConstexpr();
926}
927
929 const InterpFrame *Frame,
930 const CallExpr *Call) {
931 APSInt Arg;
932 if (!popToAPSInt(S, Call->getArg(0), Arg))
933 return false;
934
936 Arg.getZExtValue());
937 pushInteger(S, Result, Call->getType());
938 return true;
939}
940
941// Two integral values followed by a pointer (lhs, rhs, resultOut)
943 const CallExpr *Call,
944 unsigned BuiltinOp) {
945 const Pointer &ResultPtr = S.Stk.pop<Pointer>();
946 if (ResultPtr.isDummy() || !ResultPtr.isBlockPointer())
947 return false;
948
949 PrimType RHST = *S.getContext().classify(Call->getArg(1)->getType());
950 PrimType LHST = *S.getContext().classify(Call->getArg(0)->getType());
951 APSInt RHS;
952 if (!popToAPSInt(S.Stk, RHST, RHS))
953 return false;
954 APSInt LHS;
955 if (!popToAPSInt(S.Stk, LHST, LHS))
956 return false;
957 QualType ResultType = Call->getArg(2)->getType()->getPointeeType();
958 PrimType ResultT = *S.getContext().classify(ResultType);
959 bool Overflow;
960
962 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
963 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
964 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
965 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
967 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
969 uint64_t LHSSize = LHS.getBitWidth();
970 uint64_t RHSSize = RHS.getBitWidth();
971 uint64_t ResultSize = S.getASTContext().getIntWidth(ResultType);
972 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
973
974 // Add an additional bit if the signedness isn't uniformly agreed to. We
975 // could do this ONLY if there is a signed and an unsigned that both have
976 // MaxBits, but the code to check that is pretty nasty. The issue will be
977 // caught in the shrink-to-result later anyway.
978 if (IsSigned && !AllSigned)
979 ++MaxBits;
980
981 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
982 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
983 Result = APSInt(MaxBits, !IsSigned);
984 }
985
986 // Find largest int.
987 switch (BuiltinOp) {
988 default:
989 llvm_unreachable("Invalid value for BuiltinOp");
990 case Builtin::BI__builtin_add_overflow:
991 case Builtin::BI__builtin_sadd_overflow:
992 case Builtin::BI__builtin_saddl_overflow:
993 case Builtin::BI__builtin_saddll_overflow:
994 case Builtin::BI__builtin_uadd_overflow:
995 case Builtin::BI__builtin_uaddl_overflow:
996 case Builtin::BI__builtin_uaddll_overflow:
997 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, Overflow)
998 : LHS.uadd_ov(RHS, Overflow);
999 break;
1000 case Builtin::BI__builtin_sub_overflow:
1001 case Builtin::BI__builtin_ssub_overflow:
1002 case Builtin::BI__builtin_ssubl_overflow:
1003 case Builtin::BI__builtin_ssubll_overflow:
1004 case Builtin::BI__builtin_usub_overflow:
1005 case Builtin::BI__builtin_usubl_overflow:
1006 case Builtin::BI__builtin_usubll_overflow:
1007 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, Overflow)
1008 : LHS.usub_ov(RHS, Overflow);
1009 break;
1010 case Builtin::BI__builtin_mul_overflow:
1011 case Builtin::BI__builtin_smul_overflow:
1012 case Builtin::BI__builtin_smull_overflow:
1013 case Builtin::BI__builtin_smulll_overflow:
1014 case Builtin::BI__builtin_umul_overflow:
1015 case Builtin::BI__builtin_umull_overflow:
1016 case Builtin::BI__builtin_umulll_overflow:
1017 Result = LHS.isSigned() ? LHS.smul_ov(RHS, Overflow)
1018 : LHS.umul_ov(RHS, Overflow);
1019 break;
1020 }
1021
1022 // In the case where multiple sizes are allowed, truncate and see if
1023 // the values are the same.
1024 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
1025 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
1026 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
1027 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
1028 // since it will give us the behavior of a TruncOrSelf in the case where
1029 // its parameter <= its size. We previously set Result to be at least the
1030 // integer width of the result, so getIntWidth(ResultType) <=
1031 // Result.BitWidth
1032 APSInt Temp = Result.extOrTrunc(S.getASTContext().getIntWidth(ResultType));
1033 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
1034
1035 if (!APSInt::isSameValue(Temp, Result))
1036 Overflow = true;
1037 Result = std::move(Temp);
1038 }
1039
1040 // Write Result to ResultPtr and put Overflow on the stack.
1041 assignIntegral(S, ResultPtr, ResultT, Result);
1042 ResultPtr.initialize();
1043
1044 assert(Call->getDirectCallee()->getReturnType()->isBooleanType());
1045 S.Stk.push<Boolean>(Overflow);
1046 return true;
1047}
1048
1049/// Three integral values followed by a pointer (lhs, rhs, carry, carryOut).
1051 const InterpFrame *Frame,
1052 const CallExpr *Call, unsigned BuiltinOp) {
1053 const Pointer &CarryOutPtr = S.Stk.pop<Pointer>();
1054 PrimType LHST = *S.getContext().classify(Call->getArg(0)->getType());
1055 PrimType RHST = *S.getContext().classify(Call->getArg(1)->getType());
1056 APSInt CarryIn;
1057 if (!popToAPSInt(S.Stk, LHST, CarryIn))
1058 return false;
1059 APSInt RHS;
1060 if (!popToAPSInt(S.Stk, RHST, RHS))
1061 return false;
1062 APSInt LHS;
1063 if (!popToAPSInt(S.Stk, LHST, LHS))
1064 return false;
1065
1066 if (!isReadable(CarryOutPtr))
1067 return false;
1068
1069 APSInt CarryOut;
1070
1071 APSInt Result;
1072 // Copy the number of bits and sign.
1073 Result = LHS;
1074 CarryOut = LHS;
1075
1076 bool FirstOverflowed = false;
1077 bool SecondOverflowed = false;
1078 switch (BuiltinOp) {
1079 default:
1080 llvm_unreachable("Invalid value for BuiltinOp");
1081 case Builtin::BI__builtin_addcb:
1082 case Builtin::BI__builtin_addcs:
1083 case Builtin::BI__builtin_addc:
1084 case Builtin::BI__builtin_addcl:
1085 case Builtin::BI__builtin_addcll:
1086 Result =
1087 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
1088 break;
1089 case Builtin::BI__builtin_subcb:
1090 case Builtin::BI__builtin_subcs:
1091 case Builtin::BI__builtin_subc:
1092 case Builtin::BI__builtin_subcl:
1093 case Builtin::BI__builtin_subcll:
1094 Result =
1095 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
1096 break;
1097 }
1098 // It is possible for both overflows to happen but CGBuiltin uses an OR so
1099 // this is consistent.
1100 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
1101
1102 QualType CarryOutType = Call->getArg(3)->getType()->getPointeeType();
1103 PrimType CarryOutT = *S.getContext().classify(CarryOutType);
1104 assignIntegral(S, CarryOutPtr, CarryOutT, CarryOut);
1105 CarryOutPtr.initialize();
1106
1107 assert(S.getASTContext().hasSimilarType(Call->getType(),
1108 Call->getArg(0)->getType()));
1109 pushInteger(S, Result, Call->getType());
1110 return true;
1111}
1112
1114 const InterpFrame *Frame, const CallExpr *Call,
1115 unsigned BuiltinOp) {
1116
1117 std::optional<APSInt> Fallback;
1118 if (BuiltinOp == Builtin::BI__builtin_clzg && Call->getNumArgs() == 2) {
1119 APSInt FallbackVal;
1120 if (!popToAPSInt(S, Call->getArg(1), FallbackVal))
1121 return false;
1122 Fallback = FallbackVal;
1123 }
1124
1125 APSInt Val;
1126 if (Call->getArg(0)->getType()->isExtVectorBoolType()) {
1127 const Pointer &Arg = S.Stk.pop<Pointer>();
1128 Val = convertBoolVectorToInt(Arg);
1129 } else {
1130 if (!popToAPSInt(S, Call->getArg(0), Val))
1131 return false;
1132 }
1133
1134 // When the argument is 0, the result of GCC builtins is undefined, whereas
1135 // for Microsoft intrinsics, the result is the bit-width of the argument.
1136 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
1137 BuiltinOp != Builtin::BI__lzcnt &&
1138 BuiltinOp != Builtin::BI__lzcnt64;
1139
1140 if (Val == 0) {
1141 if (Fallback) {
1142 pushInteger(S, *Fallback, Call->getType());
1143 return true;
1144 }
1145
1146 if (ZeroIsUndefined)
1147 return false;
1148 }
1149
1150 pushInteger(S, Val.countl_zero(), Call->getType());
1151 return true;
1152}
1153
1155 const InterpFrame *Frame, const CallExpr *Call,
1156 unsigned BuiltinID) {
1157 std::optional<APSInt> Fallback;
1158 if (BuiltinID == Builtin::BI__builtin_ctzg && Call->getNumArgs() == 2) {
1159 APSInt FallbackVal;
1160 if (!popToAPSInt(S, Call->getArg(1), FallbackVal))
1161 return false;
1162 Fallback = FallbackVal;
1163 }
1164
1165 APSInt Val;
1166 if (Call->getArg(0)->getType()->isExtVectorBoolType()) {
1167 const Pointer &Arg = S.Stk.pop<Pointer>();
1168 Val = convertBoolVectorToInt(Arg);
1169 } else {
1170 if (!popToAPSInt(S, Call->getArg(0), Val))
1171 return false;
1172 }
1173
1174 if (Val == 0) {
1175 if (Fallback) {
1176 pushInteger(S, *Fallback, Call->getType());
1177 return true;
1178 }
1179 return false;
1180 }
1181
1182 pushInteger(S, Val.countr_zero(), Call->getType());
1183 return true;
1184}
1185
1187 const InterpFrame *Frame,
1188 const CallExpr *Call) {
1189 APSInt Val;
1190 if (!popToAPSInt(S, Call->getArg(0), Val))
1191 return false;
1192 if (Val.getBitWidth() == 8 || Val.getBitWidth() == 1)
1193 pushInteger(S, Val, Call->getType());
1194 else
1195 pushInteger(S, Val.byteSwap(), Call->getType());
1196 return true;
1197}
1198
1199/// bool __atomic_always_lock_free(size_t, void const volatile*)
1200/// bool __atomic_is_lock_free(size_t, void const volatile*)
1202 const InterpFrame *Frame,
1203 const CallExpr *Call,
1204 unsigned BuiltinOp) {
1205 auto returnBool = [&S](bool Value) -> bool {
1206 S.Stk.push<Boolean>(Value);
1207 return true;
1208 };
1209
1210 const Pointer &Ptr = S.Stk.pop<Pointer>();
1211 uint64_t SizeVal;
1212 if (!popToUInt64(S, Call->getArg(0), SizeVal))
1213 return false;
1214
1215 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1216 // of two less than or equal to the maximum inline atomic width, we know it
1217 // is lock-free. If the size isn't a power of two, or greater than the
1218 // maximum alignment where we promote atomics, we know it is not lock-free
1219 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1220 // the answer can only be determined at runtime; for example, 16-byte
1221 // atomics have lock-free implementations on some, but not all,
1222 // x86-64 processors.
1223
1224 // Check power-of-two.
1225 CharUnits Size = CharUnits::fromQuantity(SizeVal);
1226 if (Size.isPowerOfTwo()) {
1227 // Check against inlining width.
1228 unsigned InlineWidthBits =
1230 if (Size <= S.getASTContext().toCharUnitsFromBits(InlineWidthBits)) {
1231
1232 // OK, we will inline appropriately-aligned operations of this size,
1233 // and _Atomic(T) is appropriately-aligned.
1234 if (Size == CharUnits::One())
1235 return returnBool(true);
1236
1237 // Same for null pointers.
1238 assert(BuiltinOp != Builtin::BI__c11_atomic_is_lock_free);
1239 if (Ptr.isZero())
1240 return returnBool(true);
1241
1242 if (Ptr.isIntegralPointer()) {
1243 uint64_t IntVal = Ptr.getIntegerRepresentation();
1244 if (APSInt(APInt(64, IntVal, false), true).isAligned(Size.getAsAlign()))
1245 return returnBool(true);
1246 }
1247
1248 const Expr *PtrArg = Call->getArg(1);
1249 // Otherwise, check if the type's alignment against Size.
1250 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
1251 // Drop the potential implicit-cast to 'const volatile void*', getting
1252 // the underlying type.
1253 if (ICE->getCastKind() == CK_BitCast)
1254 PtrArg = ICE->getSubExpr();
1255 }
1256
1257 if (const auto *PtrTy = PtrArg->getType()->getAs<PointerType>()) {
1258 QualType PointeeType = PtrTy->getPointeeType();
1259 if (!PointeeType->isIncompleteType() &&
1260 S.getASTContext().getTypeAlignInChars(PointeeType) >= Size) {
1261 // OK, we will inline operations on this object.
1262 return returnBool(true);
1263 }
1264 }
1265 }
1266 }
1267
1268 if (BuiltinOp == Builtin::BI__atomic_always_lock_free)
1269 return returnBool(false);
1270
1271 return Invalid(S, OpPC);
1272}
1273
1274/// bool __c11_atomic_is_lock_free(size_t)
1276 CodePtr OpPC,
1277 const InterpFrame *Frame,
1278 const CallExpr *Call) {
1279 uint64_t SizeVal;
1280 if (!popToUInt64(S, Call->getArg(0), SizeVal))
1281 return false;
1282
1283 CharUnits Size = CharUnits::fromQuantity(SizeVal);
1284 if (Size.isPowerOfTwo()) {
1285 // Check against inlining width.
1286 unsigned InlineWidthBits =
1288 if (Size <= S.getASTContext().toCharUnitsFromBits(InlineWidthBits)) {
1289 S.Stk.push<Boolean>(true);
1290 return true;
1291 }
1292 }
1293
1294 return false; // returnBool(false);
1295}
1296
1297/// __builtin_complex(Float A, float B);
1299 const InterpFrame *Frame,
1300 const CallExpr *Call) {
1301 const Floating &Arg2 = S.Stk.pop<Floating>();
1302 const Floating &Arg1 = S.Stk.pop<Floating>();
1303 Pointer &Result = S.Stk.peek<Pointer>();
1304
1305 Result.elem<Floating>(0) = Arg1;
1306 Result.elem<Floating>(1) = Arg2;
1307 Result.initializeAllElements();
1308
1309 return true;
1310}
1311
1312/// __builtin_is_aligned()
1313/// __builtin_align_up()
1314/// __builtin_align_down()
1315/// The first parameter is either an integer or a pointer.
1316/// The second parameter is the requested alignment as an integer.
1318 const InterpFrame *Frame,
1319 const CallExpr *Call,
1320 unsigned BuiltinOp) {
1321 APSInt Alignment;
1322 if (!popToAPSInt(S, Call->getArg(1), Alignment))
1323 return false;
1324
1325 if (Alignment < 0 || !Alignment.isPowerOf2()) {
1326 S.FFDiag(Call, diag::note_constexpr_invalid_alignment) << Alignment;
1327 return false;
1328 }
1329 unsigned SrcWidth = S.getASTContext().getIntWidth(Call->getArg(0)->getType());
1330 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
1331 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
1332 S.FFDiag(Call, diag::note_constexpr_alignment_too_big)
1333 << MaxValue << Call->getArg(0)->getType() << Alignment;
1334 return false;
1335 }
1336
1337 // The first parameter is either an integer or a pointer.
1338 PrimType FirstArgT = *S.Ctx.classify(Call->getArg(0));
1339
1340 if (isIntegerType(FirstArgT)) {
1341 APSInt Src;
1342 if (!popToAPSInt(S.Stk, FirstArgT, Src))
1343 return false;
1344 APInt AlignMinusOne = Alignment.extOrTrunc(Src.getBitWidth()) - 1;
1345 if (BuiltinOp == Builtin::BI__builtin_align_up) {
1346 APSInt AlignedVal =
1347 APSInt((Src + AlignMinusOne) & ~AlignMinusOne, Src.isUnsigned());
1348 pushInteger(S, AlignedVal, Call->getType());
1349 } else if (BuiltinOp == Builtin::BI__builtin_align_down) {
1350 APSInt AlignedVal = APSInt(Src & ~AlignMinusOne, Src.isUnsigned());
1351 pushInteger(S, AlignedVal, Call->getType());
1352 } else {
1353 assert(*S.Ctx.classify(Call->getType()) == PT_Bool);
1354 S.Stk.push<Boolean>((Src & AlignMinusOne) == 0);
1355 }
1356 return true;
1357 }
1358 assert(FirstArgT == PT_Ptr);
1359 const Pointer &Ptr = S.Stk.pop<Pointer>();
1360
1361 // Null pointers are always aligned. Preserve null pointers for
1362 // align_up/align_down and return true for is_aligned.
1363 if (Ptr.isZero()) {
1364 if (BuiltinOp == Builtin::BI__builtin_is_aligned) {
1365 S.Stk.push<Boolean>(true);
1366 return true;
1367 }
1368
1369 assert(BuiltinOp == Builtin::BI__builtin_align_up ||
1370 BuiltinOp == Builtin::BI__builtin_align_down);
1371
1372 S.Stk.push<Pointer>(Ptr);
1373 return true;
1374 }
1375
1376 if (!Ptr.isBlockPointer() && !Ptr.isOpaquePointer()) {
1377 S.FFDiag(Call->getArg(0), diag::note_constexpr_alignment_compute)
1378 << Alignment;
1379 return false;
1380 }
1381
1382 const VarDecl *PtrDecl = Ptr.getRootVarDecl();
1383 // We need a pointer for a declaration here.
1384 if (!PtrDecl) {
1385 if (BuiltinOp == Builtin::BI__builtin_is_aligned)
1386 S.FFDiag(Call->getArg(0), diag::note_constexpr_alignment_compute)
1387 << Alignment;
1388 else
1389 S.FFDiag(Call->getArg(0), diag::note_constexpr_alignment_adjust)
1390 << Alignment;
1391 return false;
1392 }
1393
1394 unsigned PtrOffset;
1395 if (Ptr.isBlockPointer()) {
1396 // For one-past-end pointers, we can't call getIndex() since it asserts.
1397 // Use getNumElems() instead which gives the correct index for past-end.
1398 PtrOffset = Ptr.isElementPastEnd() ? Ptr.getNumElems() : Ptr.getIndex();
1399 } else {
1400 if (std::optional<size_t> PtrOff =
1401 Ptr.computeLayoutOffset(S.getASTContext()))
1402 PtrOffset = *PtrOff;
1403 else
1404 return false;
1405 }
1406
1407 CharUnits BaseAlignment = S.getASTContext().getDeclAlign(PtrDecl);
1408 CharUnits PtrAlign =
1409 BaseAlignment.alignmentAtOffset(CharUnits::fromQuantity(PtrOffset));
1410
1411 if (BuiltinOp == Builtin::BI__builtin_is_aligned) {
1412 if (PtrAlign.getQuantity() >= Alignment) {
1413 S.Stk.push<Boolean>(true);
1414 return true;
1415 }
1416 // If the alignment is not known to be sufficient, some cases could still
1417 // be aligned at run time. However, if the requested alignment is less or
1418 // equal to the base alignment and the offset is not aligned, we know that
1419 // the run-time value can never be aligned.
1420 if (BaseAlignment.getQuantity() >= Alignment &&
1421 PtrAlign.getQuantity() < Alignment) {
1422 S.Stk.push<Boolean>(false);
1423 return true;
1424 }
1425
1426 S.FFDiag(Call->getArg(0), diag::note_constexpr_alignment_compute)
1427 << Alignment;
1428 return false;
1429 }
1430
1431 assert(BuiltinOp == Builtin::BI__builtin_align_down ||
1432 BuiltinOp == Builtin::BI__builtin_align_up);
1433
1434 // For align_up/align_down, we can return the same value if the alignment
1435 // is known to be greater or equal to the requested value.
1436 if (PtrAlign.getQuantity() >= Alignment) {
1437 S.Stk.push<Pointer>(Ptr);
1438 return true;
1439 }
1440
1441 // The alignment could be greater than the minimum at run-time, so we cannot
1442 // infer much about the resulting pointer value. One case is possible:
1443 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
1444 // can infer the correct index if the requested alignment is smaller than
1445 // the base alignment so we can perform the computation on the offset.
1446 if (BaseAlignment.getQuantity() >= Alignment) {
1447 assert(Alignment.getBitWidth() <= 64 &&
1448 "Cannot handle > 64-bit address-space");
1449 uint64_t Alignment64 = Alignment.getZExtValue();
1450 CharUnits NewOffset =
1451 CharUnits::fromQuantity(BuiltinOp == Builtin::BI__builtin_align_down
1452 ? llvm::alignDown(PtrOffset, Alignment64)
1453 : llvm::alignTo(PtrOffset, Alignment64));
1454
1455 if (Ptr.isBlockPointer()) {
1456 S.Stk.push<Pointer>(Ptr.atIndex(NewOffset.getQuantity()));
1457 return true;
1458 }
1459
1460 assert(Ptr.isOpaquePointer());
1461
1462 APSInt APOffset =
1463 APSInt(APInt(64, NewOffset.getQuantity(), /*IsSigned=*/true),
1464 /*IsUnsigned=*/false);
1465 return arrayElemPtrOpaque(S, OpPC, Ptr, std::move(APOffset),
1466 /*AllocReplace=*/true);
1467 }
1468
1469 // Otherwise, we cannot constant-evaluate the result.
1470 S.FFDiag(Call->getArg(0), diag::note_constexpr_alignment_adjust) << Alignment;
1471 return false;
1472}
1473
1474/// Returns the alignment of the object Ptr points into.
1476 const Pointer &Ptr) {
1477 CharUnits BaseAlignment;
1478 if (Ptr.isBlockPointer() && Ptr.block()->isDynamic())
1479 BaseAlignment = Ptr.getDeclDesc()->computeAlignForDynamicAlloc(ASTCtx);
1480 else if (const auto *VD = Ptr.getRootVarDecl())
1481 BaseAlignment = ASTCtx.getDeclAlign(VD);
1482 else if (const auto *E = Ptr.getRootExpr())
1483 BaseAlignment = GetAlignOfExpr(ASTCtx, E, UETT_AlignOf);
1484 return BaseAlignment;
1485}
1486
1487/// __builtin_assume_aligned(Ptr, Alignment[, ExtraOffset])
1489 const InterpFrame *Frame,
1490 const CallExpr *Call) {
1491 assert(Call->getNumArgs() == 2 || Call->getNumArgs() == 3);
1492
1493 std::optional<APSInt> ExtraOffset;
1494 if (Call->getNumArgs() == 3) {
1495 APSInt ExtraOffsetVal;
1496 if (!popToAPSInt(S.Stk, *S.Ctx.classify(Call->getArg(2)), ExtraOffsetVal))
1497 return false;
1498 ExtraOffset = ExtraOffsetVal;
1499 }
1500
1501 APSInt Alignment;
1502 if (!popToAPSInt(S.Stk, *S.Ctx.classify(Call->getArg(1)), Alignment))
1503 return false;
1504 const Pointer &Ptr = S.Stk.pop<Pointer>();
1505
1506 const ASTContext &ASTCtx = S.getASTContext();
1507 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
1508
1509 // If there is a base object, then it must have the correct alignment.
1510 if (Ptr.isBlockPointer() || Ptr.isOpaquePointer()) {
1511 CharUnits BaseAlignment = getBaseAlignment(ASTCtx, Ptr);
1512 if (BaseAlignment < Align) {
1513 S.CCEDiag(Call->getArg(0),
1514 diag::note_constexpr_baa_insufficient_alignment)
1515 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
1516 return false;
1517 }
1518 }
1519
1520 std::optional<size_t> LayoutOffset = Ptr.computeLayoutOffset(ASTCtx);
1521 if (!LayoutOffset)
1522 return false;
1523
1524 CharUnits AVOffset = CharUnits::fromQuantity(*LayoutOffset);
1525 if (ExtraOffset)
1526 AVOffset -= CharUnits::fromQuantity(ExtraOffset->getZExtValue());
1527 if (AVOffset.alignTo(Align) != AVOffset) {
1528 if (Ptr.isBlockPointer() || Ptr.isOpaquePointer())
1529 S.CCEDiag(Call->getArg(0),
1530 diag::note_constexpr_baa_insufficient_alignment)
1531 << 1 << AVOffset.getQuantity() << Align.getQuantity();
1532 else
1533 S.CCEDiag(Call->getArg(0),
1534 diag::note_constexpr_baa_value_insufficient_alignment)
1535 << AVOffset.getQuantity() << Align.getQuantity();
1536 return false;
1537 }
1538
1539 S.Stk.push<Pointer>(Ptr);
1540 return true;
1541}
1542
1543/// (CarryIn, LHS, RHS, Result)
1545 CodePtr OpPC,
1546 const InterpFrame *Frame,
1547 const CallExpr *Call,
1548 bool IsAdd) {
1549 if (Call->getNumArgs() != 4 || !Call->getArg(0)->getType()->isIntegerType() ||
1550 !Call->getArg(1)->getType()->isIntegerType() ||
1551 !Call->getArg(2)->getType()->isIntegerType())
1552 return false;
1553
1554 const Pointer &CarryOutPtr = S.Stk.pop<Pointer>();
1555
1556 APSInt RHS;
1557 if (!popToAPSInt(S, Call->getArg(2), RHS))
1558 return false;
1559 APSInt LHS;
1560 if (!popToAPSInt(S, Call->getArg(1), LHS))
1561 return false;
1562 APSInt CarryIn;
1563 if (!popToAPSInt(S, Call->getArg(0), CarryIn))
1564 return false;
1565
1566 unsigned BitWidth = LHS.getBitWidth();
1567 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
1568 APInt ExResult =
1569 IsAdd ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
1570 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
1571
1572 APInt Result = ExResult.extractBits(BitWidth, 0);
1573 APSInt CarryOut =
1574 APSInt(ExResult.extractBits(1, BitWidth), /*IsUnsigned=*/true);
1575
1576 QualType CarryOutType = Call->getArg(3)->getType()->getPointeeType();
1577 PrimType CarryOutT = *S.getContext().classify(CarryOutType);
1578 assignIntegral(S, CarryOutPtr, CarryOutT, APSInt(std::move(Result), true));
1579
1580 pushInteger(S, CarryOut, Call->getType());
1581
1582 return true;
1583}
1584
1586 CodePtr OpPC,
1587 const InterpFrame *Frame,
1588 const CallExpr *Call) {
1591 pushInteger(S, Layout.size().getQuantity(), Call->getType());
1592 return true;
1593}
1594
1595static bool
1597 const InterpFrame *Frame,
1598 const CallExpr *Call) {
1599 const auto &Ptr = S.Stk.pop<Pointer>();
1600 if (!Ptr.isStringPointer())
1601 return false;
1602
1603 uint64_t Result = getPointerAuthStableSipHash(
1604 cast<StringLiteral>(Ptr.getRootExpr())->getString());
1605 pushInteger(S, Result, Call->getType());
1606 return true;
1607}
1608
1610 const InterpFrame *Frame,
1611 const CallExpr *Call) {
1612 const ASTContext &ASTCtx = S.getASTContext();
1613 uint64_t BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
1614 auto Mode =
1615 ASTCtx.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
1616 auto MaxTokensOpt = ASTCtx.getLangOpts().AllocTokenMax;
1617 uint64_t MaxTokens =
1618 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
1619
1620 // We do not read any of the arguments; discard them.
1621 for (int I = Call->getNumArgs() - 1; I >= 0; --I)
1622 discard(S.Stk, S.getContext().classify(Call->getArg(I)).value_or(PT_Ptr));
1623
1624 // Note: Type inference from a surrounding cast is not supported in
1625 // constexpr evaluation.
1626 QualType AllocType = infer_alloc::inferPossibleType(Call, ASTCtx, nullptr);
1627 if (AllocType.isNull()) {
1628 S.CCEDiag(Call,
1629 diag::note_constexpr_infer_alloc_token_type_inference_failed);
1630 return false;
1631 }
1632
1633 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, ASTCtx);
1634 if (!ATMD) {
1635 S.CCEDiag(Call, diag::note_constexpr_infer_alloc_token_no_metadata);
1636 return false;
1637 }
1638
1639 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
1640 if (!MaybeToken) {
1641 S.CCEDiag(Call, diag::note_constexpr_infer_alloc_token_unsupported_mode);
1642 return false;
1643 }
1644
1645 pushInteger(S, llvm::APInt(BitWidth, *MaybeToken), ASTCtx.getSizeType());
1646 return true;
1647}
1648
1650 const InterpFrame *Frame,
1651 const CallExpr *Call) {
1652 // A call to __operator_new is only valid within std::allocate<>::allocate.
1653 // Walk up the call stack to find the appropriate caller and get the
1654 // element type from it.
1655 auto [NewCall, ElemType] = S.getStdAllocatorCaller("allocate");
1656
1657 if (ElemType.isNull()) {
1658 S.FFDiag(Call, S.getLangOpts().CPlusPlus20
1659 ? diag::note_constexpr_new_untyped
1660 : diag::note_constexpr_new);
1661 return false;
1662 }
1663 assert(NewCall);
1664
1665 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
1666 S.FFDiag(Call, diag::note_constexpr_new_not_complete_object_type)
1667 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
1668 return false;
1669 }
1670
1671 // We only care about the first parameter (the size), so discard all the
1672 // others.
1673 {
1674 unsigned NumArgs = Call->getNumArgs();
1675 assert(NumArgs >= 1);
1676
1677 // The std::nothrow_t arg never gets put on the stack.
1678 if (Call->getArg(NumArgs - 1)->getType()->isNothrowT())
1679 --NumArgs;
1680 auto Args = ArrayRef(Call->getArgs(), Call->getNumArgs());
1681 // First arg is needed.
1682 Args = Args.drop_front();
1683
1684 // Discard the rest.
1685 for (const Expr *Arg : Args)
1686 discard(S.Stk, *S.getContext().classify(Arg));
1687 }
1688
1689 APSInt Bytes;
1690 if (!popToAPSInt(S, Call->getArg(0), Bytes))
1691 return false;
1692 CharUnits ElemSize = S.getASTContext().getTypeSizeInChars(ElemType);
1693 assert(!ElemSize.isZero());
1694 // Divide the number of bytes by sizeof(ElemType), so we get the number of
1695 // elements we should allocate.
1696 APInt NumElems, Remainder;
1697 APInt ElemSizeAP(Bytes.getBitWidth(), ElemSize.getQuantity());
1698 APInt::udivrem(Bytes, ElemSizeAP, NumElems, Remainder);
1699 if (Remainder != 0) {
1700 // This likely indicates a bug in the implementation of 'std::allocator'.
1701 S.FFDiag(Call, diag::note_constexpr_operator_new_bad_size)
1702 << Bytes << APSInt(ElemSizeAP, true) << ElemType;
1703 return false;
1704 }
1705
1706 // NB: The same check we're using in CheckArraySize()
1707 if (NumElems.getActiveBits() >
1709 NumElems.ugt(Descriptor::MaxArrayElemBytes / ElemSize.getQuantity())) {
1710 // FIXME: NoThrow check?
1711 const SourceInfo &Loc = S.Current->getSource(OpPC);
1712 S.FFDiag(Loc, diag::note_constexpr_new_too_large)
1713 << NumElems.getZExtValue();
1714 return false;
1715 }
1716
1717 if (!CheckArraySize(S, OpPC, NumElems.getZExtValue()))
1718 return false;
1719
1720 bool IsArray = NumElems.ugt(1);
1721 OptPrimType ElemT = S.getContext().classify(ElemType);
1722 DynamicAllocator &Allocator = S.getAllocator();
1723 if (ElemT) {
1724 Block *B =
1725 Allocator.allocate(NewCall, *ElemT, NumElems.getZExtValue(),
1727 assert(B);
1728 S.Stk.push<Pointer>(Pointer(B).atIndex(0));
1729 return true;
1730 }
1731
1732 assert(!ElemT);
1733
1734 // Composite arrays
1735 if (IsArray) {
1736 const Descriptor *Desc =
1737 S.P.createDescriptor(NewCall, ElemType.getTypePtr());
1738 Block *B =
1739 Allocator.allocate(Desc, NumElems.getZExtValue(), S.Ctx.getEvalID(),
1741 assert(B);
1742 S.Stk.push<Pointer>(Pointer(B).atIndex(0).narrow());
1743 return true;
1744 }
1745
1746 // Records. Still allocate them as single-element arrays.
1748 ElemType, NumElems, nullptr, ArraySizeModifier::Normal, 0);
1749
1750 const Descriptor *Desc =
1751 S.P.createDescriptor(NewCall, AllocType.getTypePtr());
1752 Block *B = Allocator.allocate(Desc, S.getContext().getEvalID(),
1754 assert(B);
1755 S.Stk.push<Pointer>(Pointer(B).atIndex(0).narrow());
1756 return true;
1757}
1758
1760 const InterpFrame *Frame,
1761 const CallExpr *Call) {
1762 const Expr *Source = nullptr;
1763 const Block *BlockToDelete = nullptr;
1764
1765 unsigned NumArgs = Call->getNumArgs();
1766 assert(NumArgs >= 1);
1767
1768 // Args are pushed in source order. The trailing sized/aligned delete
1769 // operands are above the pointer on the stack.
1770 for (unsigned I = NumArgs - 1; I != 0; --I)
1771 discard(S.Stk, *S.getContext().classify(Call->getArg(I)));
1772
1774 S.Stk.discard<Pointer>();
1775 return false;
1776 }
1777
1778 // This is permitted only within a call to std::allocator<T>::deallocate.
1779 if (!S.getStdAllocatorCaller("deallocate")) {
1780 S.FFDiag(Call);
1781 S.Stk.discard<Pointer>();
1782 return true;
1783 }
1784
1785 {
1786 const Pointer &Ptr = S.Stk.pop<Pointer>();
1787
1788 if (Ptr.isZero()) {
1789 S.CCEDiag(Call, diag::note_constexpr_deallocate_null);
1790 return true;
1791 }
1792
1793 Source = Ptr.getRootExpr();
1794 BlockToDelete = Ptr.block();
1795
1796 if (!BlockToDelete->isDynamic()) {
1797 S.FFDiag(Call, diag::note_constexpr_delete_not_heap_alloc)
1798 << Ptr.toDiagnosticString(S.getASTContext());
1799 if (const auto *D = Ptr.getFieldDesc()->asDecl())
1800 S.Note(D->getLocation(), diag::note_declared_at);
1801 }
1802 }
1803 assert(BlockToDelete);
1804
1805 DynamicAllocator &Allocator = S.getAllocator();
1806 const Descriptor *BlockDesc = BlockToDelete->getDescriptor();
1807 std::optional<DynamicAllocator::Form> AllocForm =
1808 Allocator.getAllocationForm(Source);
1809
1810 if (!Allocator.deallocate(Source, BlockToDelete)) {
1811 // Nothing has been deallocated, this must be a double-delete.
1812 const SourceInfo &Loc = S.Current->getSource(OpPC);
1813 S.FFDiag(Loc, diag::note_constexpr_double_delete);
1814 return false;
1815 }
1816 assert(AllocForm);
1817
1818 return CheckNewDeleteForms(
1819 S, OpPC, *AllocForm, DynamicAllocator::Form::Operator, BlockDesc, Source);
1820}
1821
1823 const InterpFrame *Frame,
1824 const CallExpr *Call) {
1825 const Floating &Arg0 = S.Stk.pop<Floating>();
1826 S.Stk.push<Floating>(Arg0);
1827 return true;
1828}
1829
1831 const CallExpr *Call, unsigned ID) {
1832 const Pointer &Arg = S.Stk.pop<Pointer>();
1833 assert(Arg.getFieldDesc()->isPrimitiveArray());
1834
1835 QualType ElemType = Arg.getFieldDesc()->getElemQualType();
1836 assert(Call->getType() == ElemType);
1837 PrimType ElemT = *S.getContext().classify(ElemType);
1838 unsigned NumElems = Arg.getNumElems();
1839
1840 if (!isIntegerType(ElemT))
1841 return false;
1842
1844 T Result = Arg.elem<T>(0);
1845 unsigned BitWidth = Result.bitWidth();
1846 for (unsigned I = 1; I != NumElems; ++I) {
1847 T Elem = Arg.elem<T>(I);
1848 T PrevResult = Result;
1849
1850 if (ID == Builtin::BI__builtin_reduce_add) {
1851 if (T::add(Result, Elem, BitWidth, &Result)) {
1852 unsigned OverflowBits = BitWidth + 1;
1853 (void)handleOverflow(S, OpPC,
1854 (PrevResult.toAPSInt(OverflowBits) +
1855 Elem.toAPSInt(OverflowBits)));
1856 return false;
1857 }
1858 } else if (ID == Builtin::BI__builtin_reduce_mul) {
1859 if (T::mul(Result, Elem, BitWidth, &Result)) {
1860 unsigned OverflowBits = BitWidth * 2;
1861 (void)handleOverflow(S, OpPC,
1862 (PrevResult.toAPSInt(OverflowBits) *
1863 Elem.toAPSInt(OverflowBits)));
1864 return false;
1865 }
1866
1867 } else if (ID == Builtin::BI__builtin_reduce_and) {
1868 (void)T::bitAnd(Result, Elem, BitWidth, &Result);
1869 } else if (ID == Builtin::BI__builtin_reduce_or) {
1870 (void)T::bitOr(Result, Elem, BitWidth, &Result);
1871 } else if (ID == Builtin::BI__builtin_reduce_xor) {
1872 (void)T::bitXor(Result, Elem, BitWidth, &Result);
1873 } else if (ID == Builtin::BI__builtin_reduce_min) {
1874 if (Elem < Result)
1875 Result = Elem;
1876 } else if (ID == Builtin::BI__builtin_reduce_max) {
1877 if (Elem > Result)
1878 Result = Elem;
1879 } else {
1880 llvm_unreachable("Unhandled vector reduce builtin");
1881 }
1882 }
1883 pushInteger(S, Result.toAPSInt(), Call->getType());
1884 });
1885
1886 return true;
1887}
1888
1890 const InterpFrame *Frame,
1891 const CallExpr *Call,
1892 unsigned BuiltinID) {
1893 assert(Call->getNumArgs() == 1);
1894 QualType Ty = Call->getArg(0)->getType();
1895 if (Ty->isIntegerType()) {
1896 APSInt Val;
1897 if (!popToAPSInt(S, Call->getArg(0), Val))
1898 return false;
1899 pushInteger(S, Val.abs(), Call->getType());
1900 return true;
1901 }
1902
1903 if (Ty->isFloatingType()) {
1904 Floating Val = S.Stk.pop<Floating>();
1905 Floating Result = abs(S, Val);
1906 S.Stk.push<Floating>(Result);
1907 return true;
1908 }
1909
1910 // Otherwise, the argument must be a vector.
1911 assert(Call->getArg(0)->getType()->isVectorType());
1912 const Pointer &Arg = S.Stk.pop<Pointer>();
1913 assert(Arg.getFieldDesc()->isPrimitiveArray());
1914 const Pointer &Dst = S.Stk.peek<Pointer>();
1915 assert(Dst.getFieldDesc()->isPrimitiveArray());
1916 assert(Arg.getFieldDesc()->getNumElems() ==
1917 Dst.getFieldDesc()->getNumElems());
1918
1919 QualType ElemType = Arg.getFieldDesc()->getElemQualType();
1920 PrimType ElemT = *S.getContext().classify(ElemType);
1921 unsigned NumElems = Arg.getNumElems();
1922 // we can either have a vector of integer or a vector of floating point
1923 for (unsigned I = 0; I != NumElems; ++I) {
1924 if (ElemType->isIntegerType()) {
1926 Dst.elem<T>(I) = T::from(static_cast<T>(
1927 APSInt(Arg.elem<T>(I).toAPSInt().abs(),
1929 });
1930 } else {
1931 Floating Val = Arg.elem<Floating>(I);
1932 Dst.elem<Floating>(I) = abs(S, Val);
1933 }
1934 }
1936
1937 return true;
1938}
1939
1940/// Can be called with an integer or vector as the first and only parameter.
1942 CodePtr OpPC,
1943 const InterpFrame *Frame,
1944 const CallExpr *Call,
1945 unsigned BuiltinID) {
1946 bool HasZeroArg = Call->getNumArgs() == 2;
1947 bool IsCTTZ = BuiltinID == Builtin::BI__builtin_elementwise_ctzg;
1948 assert(Call->getNumArgs() == 1 || HasZeroArg);
1949 if (Call->getArg(0)->getType()->isIntegerType()) {
1950 PrimType ArgT = *S.getContext().classify(Call->getArg(0)->getType());
1951 APSInt Val;
1952 if (!popToAPSInt(S.Stk, ArgT, Val))
1953 return false;
1954 std::optional<APSInt> ZeroVal;
1955 if (HasZeroArg) {
1956 ZeroVal = Val;
1957 if (!popToAPSInt(S.Stk, ArgT, Val))
1958 return false;
1959 }
1960
1961 if (Val.isZero()) {
1962 if (ZeroVal) {
1963 pushInteger(S, *ZeroVal, Call->getType());
1964 return true;
1965 }
1966 // If we haven't been provided the second argument, the result is
1967 // undefined
1968 S.FFDiag(S.Current->getSource(OpPC),
1969 diag::note_constexpr_countzeroes_zero)
1970 << /*IsTrailing=*/IsCTTZ;
1971 return false;
1972 }
1973
1974 if (BuiltinID == Builtin::BI__builtin_elementwise_clzg) {
1975 pushInteger(S, Val.countLeadingZeros(), Call->getType());
1976 } else {
1977 pushInteger(S, Val.countTrailingZeros(), Call->getType());
1978 }
1979 return true;
1980 }
1981 // Otherwise, the argument must be a vector.
1982 const ASTContext &ASTCtx = S.getASTContext();
1983 Pointer ZeroArg;
1984 if (HasZeroArg) {
1985 assert(Call->getArg(1)->getType()->isVectorType() &&
1986 ASTCtx.hasSameUnqualifiedType(Call->getArg(0)->getType(),
1987 Call->getArg(1)->getType()));
1988 (void)ASTCtx;
1989 ZeroArg = S.Stk.pop<Pointer>();
1990 assert(ZeroArg.getFieldDesc()->isPrimitiveArray());
1991 }
1992 assert(Call->getArg(0)->getType()->isVectorType());
1993 const Pointer &Arg = S.Stk.pop<Pointer>();
1994 assert(Arg.getFieldDesc()->isPrimitiveArray());
1995 const Pointer &Dst = S.Stk.peek<Pointer>();
1996 assert(Dst.getFieldDesc()->isPrimitiveArray());
1997 assert(Arg.getFieldDesc()->getNumElems() ==
1998 Dst.getFieldDesc()->getNumElems());
1999
2000 QualType ElemType = Arg.getFieldDesc()->getElemQualType();
2001 PrimType ElemT = *S.getContext().classify(ElemType);
2002 unsigned NumElems = Arg.getNumElems();
2003
2004 // FIXME: Reading from uninitialized vector elements?
2005 for (unsigned I = 0; I != NumElems; ++I) {
2007 APInt EltVal = Arg.atIndex(I).deref<T>().toAPSInt();
2008 if (EltVal.isZero()) {
2009 if (HasZeroArg) {
2010 Dst.atIndex(I).deref<T>() = ZeroArg.atIndex(I).deref<T>();
2011 } else {
2012 // If we haven't been provided the second argument, the result is
2013 // undefined
2014 S.FFDiag(S.Current->getSource(OpPC),
2015 diag::note_constexpr_countzeroes_zero)
2016 << /*IsTrailing=*/IsCTTZ;
2017 return false;
2018 }
2019 } else if (IsCTTZ) {
2020 Dst.atIndex(I).deref<T>() = T::from(EltVal.countTrailingZeros());
2021 } else {
2022 Dst.atIndex(I).deref<T>() = T::from(EltVal.countLeadingZeros());
2023 }
2024 Dst.atIndex(I).initialize();
2025 });
2026 }
2027
2028 return true;
2029}
2030
2032 const InterpFrame *Frame,
2033 const CallExpr *Call, unsigned ID) {
2034 assert(Call->getNumArgs() == 3);
2035 const ASTContext &ASTCtx = S.getASTContext();
2036 uint64_t Size;
2037 if (!popToUInt64(S, Call->getArg(2), Size))
2038 return false;
2039 Pointer SrcPtr = S.Stk.pop<Pointer>().expand();
2040 Pointer DestPtr = S.Stk.pop<Pointer>().expand();
2041
2042 if (ID == Builtin::BImemcpy || ID == Builtin::BImemmove)
2043 diagnoseNonConstexprBuiltin(S, OpPC, ID);
2044
2045 bool Move =
2046 (ID == Builtin::BI__builtin_memmove || ID == Builtin::BImemmove ||
2047 ID == Builtin::BI__builtin_wmemmove || ID == Builtin::BIwmemmove);
2048 bool WChar = ID == Builtin::BIwmemcpy || ID == Builtin::BIwmemmove ||
2049 ID == Builtin::BI__builtin_wmemcpy ||
2050 ID == Builtin::BI__builtin_wmemmove;
2051
2052 // If the size is zero, we treat this as always being a valid no-op.
2053 if (Size == 0) {
2054 S.Stk.push<Pointer>(DestPtr);
2055 return true;
2056 }
2057
2058 if (SrcPtr.isZero() || DestPtr.isZero()) {
2059 Pointer DiagPtr = (SrcPtr.isZero() ? SrcPtr : DestPtr);
2060 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_memcpy_null)
2061 << /*IsMove=*/Move << /*IsWchar=*/WChar << !SrcPtr.isZero()
2062 << DiagPtr.toDiagnosticString(ASTCtx);
2063 return false;
2064 }
2065
2066 // Diagnose integral src/dest pointers specially.
2067 if (SrcPtr.isIntegralPointer() || DestPtr.isIntegralPointer()) {
2068 std::string DiagVal = "(void *)";
2069 DiagVal += SrcPtr.isIntegralPointer()
2070 ? std::to_string(SrcPtr.getIntegerRepresentation())
2071 : std::to_string(DestPtr.getIntegerRepresentation());
2072 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_memcpy_null)
2073 << Move << WChar << DestPtr.isIntegralPointer() << DiagVal;
2074 return false;
2075 }
2076
2077 if (!DestPtr.isBlockPointer())
2078 return diagnoseUnreadableObject(S, OpPC, DestPtr, AK_Assign);
2079
2080 if (!isReadable(SrcPtr))
2081 return false;
2082
2083 if (DestPtr.getType()->isIncompleteType()) {
2084 S.FFDiag(S.Current->getSource(OpPC),
2085 diag::note_constexpr_memcpy_incomplete_type)
2086 << Move << DestPtr.getType();
2087 return false;
2088 }
2089 if (SrcPtr.getType()->isIncompleteType()) {
2090 S.FFDiag(S.Current->getSource(OpPC),
2091 diag::note_constexpr_memcpy_incomplete_type)
2092 << Move << SrcPtr.getType();
2093 return false;
2094 }
2095
2096 QualType DestElemType = getElemType(DestPtr);
2097 if (DestElemType->isIncompleteType()) {
2098 S.FFDiag(S.Current->getSource(OpPC),
2099 diag::note_constexpr_memcpy_incomplete_type)
2100 << Move << DestElemType;
2101 return false;
2102 }
2103
2104 size_t RemainingDestElems;
2105 if (DestPtr.inArray()) {
2106 RemainingDestElems = DestPtr.isUnknownSizeArray()
2107 ? 0
2108 : (DestPtr.getNumElems() - DestPtr.getIndex());
2109 } else {
2110 RemainingDestElems = 1;
2111 }
2112 unsigned DestElemSize = ASTCtx.getTypeSizeInChars(DestElemType).getQuantity();
2113
2114 if (WChar) {
2115 uint64_t WCharSize =
2116 ASTCtx.getTypeSizeInChars(ASTCtx.getWCharType()).getQuantity();
2117 Size *= WCharSize;
2118 }
2119
2120 if (Size % DestElemSize != 0) {
2121 S.FFDiag(S.Current->getSource(OpPC),
2122 diag::note_constexpr_memcpy_unsupported)
2123 << Move << WChar << 0 << DestElemType << Size << DestElemSize;
2124 return false;
2125 }
2126
2127 QualType SrcElemType = getElemType(SrcPtr);
2128 size_t RemainingSrcElems;
2129 if (SrcPtr.inArray()) {
2130 RemainingSrcElems = SrcPtr.isUnknownSizeArray()
2131 ? 0
2132 : (SrcPtr.getNumElems() - SrcPtr.getIndex());
2133 } else {
2134 RemainingSrcElems = 1;
2135 }
2136 unsigned SrcElemSize = ASTCtx.getTypeSizeInChars(SrcElemType).getQuantity();
2137
2138 if (!ASTCtx.hasSameUnqualifiedType(DestElemType, SrcElemType)) {
2139 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_memcpy_type_pun)
2140 << Move << SrcElemType << DestElemType;
2141 return false;
2142 }
2143
2144 if (!DestElemType.isTriviallyCopyableType(ASTCtx)) {
2145 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_memcpy_nontrivial)
2146 << Move << DestElemType;
2147 return false;
2148 }
2149
2150 // Check if we have enough elements to read from and write to.
2151 size_t RemainingDestBytes = RemainingDestElems * DestElemSize;
2152 size_t RemainingSrcBytes = RemainingSrcElems * SrcElemSize;
2153 if (Size > RemainingDestBytes || Size > RemainingSrcBytes) {
2154 APInt N = APInt(64, Size / DestElemSize);
2155 S.FFDiag(S.Current->getSource(OpPC),
2156 diag::note_constexpr_memcpy_unsupported)
2157 << Move << WChar << (Size > RemainingSrcBytes ? 1 : 2) << DestElemType
2158 << toString(N, 10, /*Signed=*/false);
2159 return false;
2160 }
2161
2162 // Check for overlapping memory regions.
2163 if (!Move && Pointer::pointToSameBlock(SrcPtr, DestPtr)) {
2164 // Remove base casts.
2165 Pointer SrcP = SrcPtr.stripBaseCasts();
2166 Pointer DestP = DestPtr.stripBaseCasts();
2167
2168 unsigned SrcIndex = SrcP.expand().getIndex() * SrcElemSize;
2169 unsigned DstIndex = DestP.expand().getIndex() * DestElemSize;
2170
2171 if ((SrcIndex <= DstIndex && (SrcIndex + Size) > DstIndex) ||
2172 (DstIndex <= SrcIndex && (DstIndex + Size) > SrcIndex)) {
2173 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_memcpy_overlap)
2174 << /*IsWChar=*/false;
2175 return false;
2176 }
2177 }
2178
2179 assert(Size % DestElemSize == 0);
2180 if (!DoMemcpy(S, OpPC, SrcPtr, DestPtr, Bytes(Size).toBits()))
2181 return false;
2182
2183 S.Stk.push<Pointer>(DestPtr);
2184 return true;
2185}
2186
2187/// Determine if T is a character type for which we guarantee that
2188/// sizeof(T) == 1.
2190 return T->isCharType() || T->isChar8Type();
2191}
2192
2193// stdc_memreverse8(size_t N, unsigned char *P)
2195 const InterpFrame *Frame,
2196 const CallExpr *Call) {
2197 Pointer Ptr = S.Stk.pop<Pointer>();
2198
2199 uint64_t NElems;
2200 if (!popToUInt64(S, Call->getArg(0), NElems))
2201 return false;
2202
2203 if (Ptr.isZero()) {
2204 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_null)
2205 << AK_Assign;
2206 return false;
2207 }
2208
2209 if (!isReadable(Ptr) && !Ptr.isOnePastEnd())
2210 return false;
2211
2212 const Descriptor *Desc = Ptr.getFieldDesc();
2213 bool IsArray = Desc->isArray();
2214 QualType ElemTy = IsArray ? Desc->getElemQualType() : Desc->getType();
2215
2216 if (IsArray)
2217 Ptr = Ptr.expand();
2218
2219 uint64_t BaseIdx = Ptr.getIndex();
2220 uint64_t ArraySize = Ptr.getNumElems();
2221 uint64_t RemainingElems = ArraySize - BaseIdx;
2222 if (NElems > RemainingElems) {
2223 uint64_t LastIndex = llvm::SaturatingAdd(BaseIdx, NElems - 1);
2224 if (IsArray)
2225 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_array_index)
2226 << LastIndex << /*array*/ 0 << ArraySize;
2227 else
2228 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_array_index)
2229 << LastIndex << /*non-array*/ 1;
2230 return false;
2231 }
2232
2233 if (NElems <= 1)
2234 return true;
2235
2236 PrimType ElemT = *S.getContext().classify(ElemTy);
2237
2238 for (uint64_t I = 0, Half = NElems / 2; I < Half; ++I) {
2239 Pointer LoPtr = Ptr.atIndex(BaseIdx + I);
2240 Pointer HiPtr = Ptr.atIndex(BaseIdx + NElems - 1 - I);
2241
2242 if (!CheckLoad(S, OpPC, LoPtr, AK_Read) ||
2243 !CheckLoad(S, OpPC, HiPtr, AK_Read) || !CheckStore(S, OpPC, LoPtr) ||
2244 !CheckStore(S, OpPC, HiPtr))
2245 return false;
2246
2248 { std::swap(LoPtr.deref<T>(), HiPtr.deref<T>()); });
2249 LoPtr.initialize();
2250 HiPtr.initialize();
2251 }
2252 return true;
2253}
2254
2256 const InterpFrame *Frame,
2257 const CallExpr *Call, bool IsBigEndian,
2258 bool IsAligned) {
2259 Pointer Ptr = S.Stk.pop<Pointer>();
2260
2261 if (Ptr.isZero()) {
2262 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_null)
2263 << AK_Read;
2264 return false;
2265 }
2266
2267 if (!isReadable(Ptr) && !Ptr.isOnePastEnd())
2268 return false;
2269
2270 if (!Ptr.isReadablePointerType())
2271 return false;
2272
2273 if (IsAligned) {
2274 CharUnits RequiredAlign =
2275 S.getASTContext().getTypeAlignInChars(Call->getType());
2276 CharUnits BaseAlignment = getBaseAlignment(S.getASTContext(), Ptr);
2277 std::optional<size_t> LayoutOffset =
2278 Ptr.computeLayoutOffset(S.getASTContext());
2279 if (!LayoutOffset)
2280 return false;
2281 CharUnits PtrOffset = CharUnits::fromQuantity(*LayoutOffset);
2282 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(PtrOffset);
2283 if (PtrAlign < RequiredAlign) {
2284 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_load8_unaligned)
2286 Call->getBuiltinCallee())
2287 << RequiredAlign.getQuantity() << PtrAlign.getQuantity();
2288 return false;
2289 }
2290 }
2291
2292 // A string pointer has no Descriptor; treat it as an array of its
2293 // character type.
2294 bool IsArray = Ptr.isStringPointer() || Ptr.getFieldDesc()->isArray();
2295 QualType ElemTy = getElemType(Ptr);
2296
2297 if (IsArray)
2298 Ptr = Ptr.expand();
2299
2300 uint64_t BaseIdx = Ptr.getIndex();
2301 uint64_t ArraySize = Ptr.getNumElems();
2302 uint64_t RemainingElems = ArraySize - BaseIdx;
2303
2304 unsigned ByteWidth = S.getASTContext().getTypeSize(Call->getType()) / 8;
2305 if (ByteWidth > RemainingElems) {
2306 uint64_t LastIndex = llvm::SaturatingAdd(BaseIdx, uint64_t(ByteWidth - 1));
2307 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_array_index)
2308 << LastIndex << /*array*/ !IsArray << ArraySize;
2309 return false;
2310 }
2311
2312 OptPrimType ElemT = S.getContext().classify(ElemTy);
2313 if (!ElemT || !isIntegerOrBoolType(*ElemT))
2314 return false;
2315 uint64_t Result = 0;
2316
2317 if (IsArray) {
2318 // C2y §7.18.21: result = sum(b_index * 2^(8*index)) for index in [0, N/8)
2319 // where b_index = ptr[index] (LE) or ptr[N/8 - index - 1] (BE).
2320 for (unsigned I = 0; I != ByteWidth; ++I) {
2321 size_t SrcIdx = IsBigEndian ? (ByteWidth - I - 1) : I;
2322 Pointer BytePtr = Ptr.atIndex(BaseIdx + SrcIdx);
2323 if (!CheckLoad(S, OpPC, BytePtr, AK_Read))
2324 return false;
2325 INT_TYPE_SWITCH(*ElemT, {
2326 Result |= BytePtr.load<T>().toAPSInt().getZExtValue() << (8 * I);
2327 });
2328 }
2329 } else {
2330 assert(ByteWidth == 1 && "non-array pointer, expected a 1-byte load");
2331 if (!CheckLoad(S, OpPC, Ptr, AK_Read))
2332 return false;
2333 INT_TYPE_SWITCH(*ElemT,
2334 { Result = Ptr.load<T>().toAPSInt().getZExtValue(); });
2335 }
2336
2337 bool IsSigned = Call->getType()->isSignedIntegerType();
2338 pushInteger(S, APSInt(APInt(ByteWidth * 8, Result), !IsSigned),
2339 Call->getType());
2340 return true;
2341}
2342
2344 const InterpFrame *Frame,
2345 const CallExpr *Call, unsigned ID) {
2346 assert(Call->getNumArgs() == 3);
2347 uint64_t Size;
2348 if (!popToUInt64(S, Call->getArg(2), Size))
2349 return false;
2350 const Pointer &PtrB = S.Stk.pop<Pointer>();
2351 const Pointer &PtrA = S.Stk.pop<Pointer>();
2352
2353 if (ID == Builtin::BImemcmp || ID == Builtin::BIbcmp ||
2354 ID == Builtin::BIwmemcmp)
2355 diagnoseNonConstexprBuiltin(S, OpPC, ID);
2356
2357 if (Size == 0) {
2358 pushInteger(S, 0, Call->getType());
2359 return true;
2360 }
2361
2362 if (PtrA.isFunctionPointer() || PtrB.isFunctionPointer())
2363 return false;
2364
2365 bool IsWide =
2366 (ID == Builtin::BIwmemcmp || ID == Builtin::BI__builtin_wmemcmp);
2367
2368 const ASTContext &ASTCtx = S.getASTContext();
2369 QualType ElemTypeA = getElemType(PtrA);
2370 QualType ElemTypeB = getElemType(PtrB);
2371 // FIXME: This is an arbitrary limitation the current constant interpreter
2372 // had. We could remove this.
2373 if (!IsWide && (!isOneByteCharacterType(ElemTypeA) ||
2374 !isOneByteCharacterType(ElemTypeB))) {
2375 S.FFDiag(S.Current->getSource(OpPC),
2376 diag::note_constexpr_memcmp_unsupported)
2377 << ASTCtx.BuiltinInfo.getQuotedName(ID) << PtrA.getType()
2378 << PtrB.getType();
2379 return false;
2380 }
2381
2382 if (!PtrA.isReadablePointerType() || !PtrB.isReadablePointerType())
2383 return false;
2384
2385 if (!CheckLoad(S, OpPC, PtrA, AK_Read) || !CheckLoad(S, OpPC, PtrB, AK_Read))
2386 return false;
2387
2388 // Now, read both pointers to a buffer and compare those.
2389 BitcastBuffer BufferA(
2390 Bits(ASTCtx.getTypeSize(ElemTypeA) * PtrA.getNumElems()));
2391 readPointerToBuffer(S.getContext(), PtrA, BufferA, /*ReturnOnUninit=*/false);
2392
2393 // FIXME: The swapping here is UNDOING something we do when reading the
2394 // data into the buffer.
2395 if (ASTCtx.getTargetInfo().isBigEndian())
2396 swapBytes(BufferA.Data.get(), BufferA.byteSize().getQuantity());
2397
2398 BitcastBuffer BufferB(
2399 Bits(ASTCtx.getTypeSize(ElemTypeB) * PtrB.getNumElems()));
2400 readPointerToBuffer(S.getContext(), PtrB, BufferB, /*ReturnOnUninit=*/false);
2401 // FIXME: The swapping here is UNDOING something we do when reading the
2402 // data into the buffer.
2403 if (ASTCtx.getTargetInfo().isBigEndian())
2404 swapBytes(BufferB.Data.get(), BufferB.byteSize().getQuantity());
2405
2406 size_t MinBufferSize = std::min(BufferA.byteSize().getQuantity(),
2407 BufferB.byteSize().getQuantity());
2408
2409 unsigned ElemSize = 1;
2410 if (IsWide)
2411 ElemSize = ASTCtx.getTypeSizeInChars(ASTCtx.getWCharType()).getQuantity();
2412 // The Size given for the wide variants is in wide-char units. Convert it
2413 // to bytes.
2414 size_t ByteSize = Size * ElemSize;
2415 size_t CmpSize = std::min(MinBufferSize, ByteSize);
2416
2417 for (size_t I = 0; I != CmpSize; I += ElemSize) {
2418 if (IsWide) {
2420 *S.getContext().classify(ASTCtx.getWCharType()), {
2421 T A = T::bitcastFromMemory(BufferA.atByte(I), T::bitWidth());
2422 T B = T::bitcastFromMemory(BufferB.atByte(I), T::bitWidth());
2423 if (A < B) {
2424 pushInteger(S, -1, Call->getType());
2425 return true;
2426 }
2427 if (A > B) {
2428 pushInteger(S, 1, Call->getType());
2429 return true;
2430 }
2431 });
2432 } else {
2433 auto A = BufferA.deref<std::byte>(Bytes(I));
2434 auto B = BufferB.deref<std::byte>(Bytes(I));
2435
2436 if (A < B) {
2437 pushInteger(S, -1, Call->getType());
2438 return true;
2439 }
2440 if (A > B) {
2441 pushInteger(S, 1, Call->getType());
2442 return true;
2443 }
2444 }
2445 }
2446
2447 // We compared CmpSize bytes above. If the limiting factor was the Size
2448 // passed, we're done and the result is equality (0).
2449 if (ByteSize <= CmpSize) {
2450 pushInteger(S, 0, Call->getType());
2451 return true;
2452 }
2453
2454 // However, if we read all the available bytes but were instructed to read
2455 // even more, diagnose this as a "read of dereferenced one-past-the-end
2456 // pointer". This is what would happen if we called CheckLoad() on every array
2457 // element.
2458 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_past_end)
2459 << AK_Read << S.Current->getRange(OpPC);
2460 return false;
2461}
2462
2463// __builtin_memchr(ptr, int, int)
2464// __builtin_strchr(ptr, int)
2466 const CallExpr *Call, unsigned ID) {
2467 if (ID == Builtin::BImemchr || ID == Builtin::BIwcschr ||
2468 ID == Builtin::BIstrchr || ID == Builtin::BIwmemchr)
2469 diagnoseNonConstexprBuiltin(S, OpPC, ID);
2470
2471 std::optional<APSInt> MaxLength;
2472 if (Call->getNumArgs() == 3) {
2473 APSInt MaxLengthVal;
2474 if (!popToAPSInt(S, Call->getArg(2), MaxLengthVal))
2475 return false;
2476 MaxLength = MaxLengthVal;
2477 }
2478
2479 APSInt Desired;
2480 if (!popToAPSInt(S, Call->getArg(1), Desired))
2481 return false;
2482 const Pointer &Ptr = S.Stk.pop<Pointer>();
2483
2484 if (MaxLength && MaxLength->isZero()) {
2485 S.Stk.push<Pointer>();
2486 return true;
2487 }
2488
2489 if (Ptr.isDummy()) {
2490 if (Ptr.getType()->isIncompleteType())
2491 S.FFDiag(S.Current->getSource(OpPC),
2492 diag::note_constexpr_ltor_incomplete_type)
2493 << Ptr.getType();
2494 return false;
2495 }
2496
2497 // Null is only okay if the given size is 0.
2498 if (Ptr.isZero()) {
2499 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_null)
2500 << AK_Read;
2501 return false;
2502 }
2503
2504 if (!Ptr.isReadablePointerType())
2505 return false;
2506
2507 QualType ElemTy = getElemType(Ptr);
2508 bool IsRawByte = ID == Builtin::BImemchr || ID == Builtin::BI__builtin_memchr;
2509
2510 // Give up on byte-oriented matching against multibyte elements.
2511 if (IsRawByte && !isOneByteCharacterType(ElemTy)) {
2512 S.FFDiag(S.Current->getSource(OpPC),
2513 diag::note_constexpr_memchr_unsupported)
2514 << S.getASTContext().BuiltinInfo.getQuotedName(ID) << ElemTy;
2515 return false;
2516 }
2517
2518 if (!isReadable(Ptr))
2519 return false;
2520
2521 uint64_t DesiredVal;
2522 if (ID == Builtin::BIwmemchr || ID == Builtin::BI__builtin_wmemchr ||
2523 ID == Builtin::BIwcschr || ID == Builtin::BI__builtin_wcschr) {
2524 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
2525 DesiredVal = Desired.getZExtValue();
2526 } else {
2527 DesiredVal = Desired.trunc(S.getASTContext().getCharWidth()).getZExtValue();
2528 }
2529
2530 bool StopAtZero =
2531 (ID == Builtin::BIstrchr || ID == Builtin::BI__builtin_strchr ||
2532 ID == Builtin::BIwcschr || ID == Builtin::BI__builtin_wcschr);
2533
2534 PrimType ElemT =
2535 IsRawByte ? PT_Sint8 : *S.getContext().classify(getElemType(Ptr));
2536
2537 size_t Index = Ptr.getIndex();
2538 size_t Step = 0;
2539 for (;;) {
2540 const Pointer &ElemPtr =
2541 (Index + Step) > 0 ? Ptr.atIndex(Index + Step) : Ptr;
2542
2543 if (!CheckLoad(S, OpPC, ElemPtr))
2544 return false;
2545
2546 uint64_t V;
2548 ElemT, { V = static_cast<uint64_t>(ElemPtr.load<T>().toUnsigned()); });
2549
2550 if (V == DesiredVal) {
2551 S.Stk.push<Pointer>(ElemPtr);
2552 return true;
2553 }
2554
2555 if (StopAtZero && V == 0)
2556 break;
2557
2558 ++Step;
2559 if (MaxLength && Step == MaxLength->getZExtValue())
2560 break;
2561 }
2562
2563 S.Stk.push<Pointer>();
2564 return true;
2565}
2566
2568 const InterpFrame *Frame,
2569 const CallExpr *Call, bool IsDynamic) {
2570 const ASTContext &ASTCtx = S.getASTContext();
2571 // From the GCC docs:
2572 // Kind is an integer constant from 0 to 3. If the least significant bit is
2573 // clear, objects are whole variables. If it is set, a closest surrounding
2574 // subobject is considered the object a pointer points to. The second bit
2575 // determines if maximum or minimum of remaining bytes is computed.
2576 APSInt Kind;
2577 if (!popToAPSInt(S, Call->getArg(1), Kind))
2578 return false;
2579 if (Kind < 0 || Kind > 3) {
2580 S.FFDiag(Call->getArg(1), diag::note_constexpr_builtin_arg_out_of_range)
2581 << Kind << 0 << 3;
2582 return false;
2583 }
2584 unsigned KindValue = Kind.getZExtValue();
2585 Pointer Ptr = S.Stk.pop<Pointer>();
2586
2587 if (auto Result = evaluateBuiltinObjectSize(ASTCtx, KindValue, Ptr,
2588 Call->getArg(0), IsDynamic)) {
2589 pushInteger(S, *Result, Call->getType());
2590 return true;
2591 }
2592
2593 if (Call->getArg(0)->HasSideEffects(ASTCtx)) {
2594 // "If there are any side effects in them, it returns (size_t) -1
2595 // for type 0 or 1 and (size_t) 0 for type 2 or 3."
2596 pushInteger(S, KindValue <= 1 ? (size_t)-1 : (size_t)0, Call->getType());
2597 return true;
2598 }
2599
2600 switch (S.EvalMode) {
2604 // Leave it to IR generation.
2605 return Invalid(S, OpPC);
2607 // Reduce it to a constant now.
2608 pushInteger(S, ((KindValue & 2u) ? (size_t)0 : (size_t)-1),
2609 Call->getType());
2610 return true;
2611 }
2612
2613 return false;
2614}
2615
2617 const CallExpr *Call) {
2618
2619 if (!S.inConstantContext())
2620 return false;
2621
2622 const Pointer &Ptr = S.Stk.pop<Pointer>();
2623
2624 auto Error = [&](int Diag) {
2625 bool CalledFromStd = false;
2626 const auto *Callee = S.Current->getCallee();
2627 if (Callee && Callee->isInStdNamespace()) {
2628 const IdentifierInfo *Identifier = Callee->getIdentifier();
2629 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
2630 }
2631 S.CCEDiag(CalledFromStd
2633 : S.Current->getSource(OpPC),
2634 diag::err_invalid_is_within_lifetime)
2635 << (CalledFromStd ? "std::is_within_lifetime"
2636 : "__builtin_is_within_lifetime")
2637 << Diag;
2638 return false;
2639 };
2640
2641 if (Ptr.isZero())
2642 return Error(0);
2643 if (Ptr.isOnePastEnd())
2644 return Error(1);
2645
2646 bool Result = Ptr.getLifetime() != Lifetime::Ended;
2647 if (!Ptr.isActive()) {
2648 Result = false;
2649 } else {
2650 if (!CheckLive(S, OpPC, Ptr, AK_Read))
2651 return false;
2652 if (!CheckMutable(S, OpPC, Ptr))
2653 return false;
2654 if (!CheckDummy(S, OpPC, Ptr, AK_Read))
2655 return false;
2656 }
2657
2658 if (!Ptr.isBlockPointer())
2659 return diagnoseUnreadableObject(S, OpPC, Ptr, AK_Read);
2660
2661 // Check if we're currently running an initializer.
2662 if (S.initializingBlock(Ptr.block()))
2663 return Error(2);
2664 if (S.EvaluatingDecl && Ptr.getRootVarDecl() == S.EvaluatingDecl)
2665 return Error(2);
2666
2667 pushInteger(S, Result, Call->getType());
2668 return true;
2669}
2670
2672 InterpState &S, CodePtr OpPC, const CallExpr *Call,
2673 llvm::function_ref<APInt(const APSInt &)> Fn) {
2674 assert(Call->getNumArgs() == 1);
2675
2676 // Single integer case.
2677 if (!Call->getArg(0)->getType()->isVectorType()) {
2678 assert(Call->getType()->isIntegerType());
2679 APSInt Src;
2680 if (!popToAPSInt(S, Call->getArg(0), Src))
2681 return false;
2682 APInt Result = Fn(Src);
2683 pushInteger(S, APSInt(std::move(Result), !Src.isSigned()), Call->getType());
2684 return true;
2685 }
2686
2687 // Vector case.
2688 const Pointer &Arg = S.Stk.pop<Pointer>();
2689 assert(Arg.getFieldDesc()->isPrimitiveArray());
2690 const Pointer &Dst = S.Stk.peek<Pointer>();
2691 assert(Dst.getFieldDesc()->isPrimitiveArray());
2692 assert(Arg.getFieldDesc()->getNumElems() ==
2693 Dst.getFieldDesc()->getNumElems());
2694
2695 QualType ElemType = Arg.getFieldDesc()->getElemQualType();
2696 PrimType ElemT = *S.getContext().classify(ElemType);
2697 unsigned NumElems = Arg.getNumElems();
2698 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
2699
2700 for (unsigned I = 0; I != NumElems; ++I) {
2702 APSInt Src = Arg.elem<T>(I).toAPSInt();
2703 APInt Result = Fn(Src);
2704 Dst.elem<T>(I) = static_cast<T>(APSInt(std::move(Result), DestUnsigned));
2705 });
2706 }
2708
2709 return true;
2710}
2711
2713 InterpState &S, CodePtr OpPC, const CallExpr *Call,
2714 llvm::function_ref<std::optional<APFloat>(
2715 const APFloat &, const APFloat &, std::optional<APSInt> RoundingMode)>
2716 Fn,
2717 bool IsScalar = false) {
2718 assert((Call->getNumArgs() == 2) || (Call->getNumArgs() == 3));
2719 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
2720 assert(VT->getElementType()->isFloatingType());
2721 unsigned NumElems = VT->getNumElements();
2722
2723 // Vector case.
2724 assert(Call->getArg(0)->getType()->isVectorType() &&
2725 Call->getArg(1)->getType()->isVectorType());
2726 assert(VT->getElementType() ==
2727 Call->getArg(1)->getType()->castAs<VectorType>()->getElementType());
2728 assert(VT->getNumElements() ==
2729 Call->getArg(1)->getType()->castAs<VectorType>()->getNumElements());
2730
2731 std::optional<APSInt> RoundingMode = std::nullopt;
2732 if (Call->getNumArgs() == 3) {
2733 APSInt RoundingModeVal;
2734 if (!popToAPSInt(S, Call->getArg(2), RoundingModeVal))
2735 return false;
2736 RoundingMode = RoundingModeVal;
2737 }
2738
2739 const Pointer &BPtr = S.Stk.pop<Pointer>();
2740 const Pointer &APtr = S.Stk.pop<Pointer>();
2741 const Pointer &Dst = S.Stk.peek<Pointer>();
2742 for (unsigned ElemIdx = 0; ElemIdx != NumElems; ++ElemIdx) {
2743 using T = PrimConv<PT_Float>::T;
2744 if (IsScalar && ElemIdx > 0) {
2745 Dst.elem<T>(ElemIdx) = APtr.elem<T>(ElemIdx);
2746 continue;
2747 }
2748 APFloat ElemA = APtr.elem<T>(ElemIdx).getAPFloat();
2749 APFloat ElemB = BPtr.elem<T>(ElemIdx).getAPFloat();
2750 std::optional<APFloat> Result = Fn(ElemA, ElemB, RoundingMode);
2751 if (!Result)
2752 return false;
2753 Dst.elem<T>(ElemIdx) = static_cast<T>(*Result);
2754 }
2755
2757
2758 return true;
2759}
2760
2762 InterpState &S, CodePtr OpPC, const CallExpr *Call,
2763 llvm::function_ref<std::optional<APFloat>(const APFloat &, const APFloat &,
2764 std::optional<APSInt>)>
2765 Fn) {
2766 assert(Call->getNumArgs() == 5);
2767 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
2768 unsigned NumElems = VT->getNumElements();
2769
2770 APSInt RoundingMode;
2771 if (!popToAPSInt(S, Call->getArg(4), RoundingMode))
2772 return false;
2773 uint64_t MaskVal;
2774 if (!popToUInt64(S, Call->getArg(3), MaskVal))
2775 return false;
2776 const Pointer &SrcPtr = S.Stk.pop<Pointer>();
2777 const Pointer &BPtr = S.Stk.pop<Pointer>();
2778 const Pointer &APtr = S.Stk.pop<Pointer>();
2779 const Pointer &Dst = S.Stk.peek<Pointer>();
2780
2781 using T = PrimConv<PT_Float>::T;
2782
2783 if (MaskVal & 1) {
2784 APFloat ElemA = APtr.elem<T>(0).getAPFloat();
2785 APFloat ElemB = BPtr.elem<T>(0).getAPFloat();
2786 std::optional<APFloat> Result = Fn(ElemA, ElemB, RoundingMode);
2787 if (!Result)
2788 return false;
2789 Dst.elem<T>(0) = static_cast<T>(*Result);
2790 } else {
2791 Dst.elem<T>(0) = SrcPtr.elem<T>(0);
2792 }
2793
2794 for (unsigned I = 1; I < NumElems; ++I)
2795 Dst.elem<T>(I) = APtr.elem<T>(I);
2796
2797 Dst.initializeAllElements();
2798
2799 return true;
2800}
2801
2803 InterpState &S, CodePtr OpPC, const CallExpr *Call,
2804 llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
2805 assert(Call->getNumArgs() == 2);
2806
2807 // Single integer case.
2808 if (!Call->getArg(0)->getType()->isVectorType()) {
2809 assert(!Call->getArg(1)->getType()->isVectorType());
2810 APSInt RHS;
2811 if (!popToAPSInt(S, Call->getArg(1), RHS))
2812 return false;
2813 APSInt LHS;
2814 if (!popToAPSInt(S, Call->getArg(0), LHS))
2815 return false;
2816 APInt Result = Fn(LHS, RHS);
2817 pushInteger(S, APSInt(std::move(Result), !LHS.isSigned()), Call->getType());
2818 return true;
2819 }
2820
2821 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
2822 assert(VT->getElementType()->isIntegralOrEnumerationType());
2823 PrimType ElemT = *S.getContext().classify(VT->getElementType());
2824 unsigned NumElems = VT->getNumElements();
2825 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
2826
2827 // Vector + Scalar case.
2828 if (!Call->getArg(1)->getType()->isVectorType()) {
2829 assert(Call->getArg(1)->getType()->isIntegralOrEnumerationType());
2830
2831 APSInt RHS;
2832 if (!popToAPSInt(S, Call->getArg(1), RHS))
2833 return false;
2834 const Pointer &LHS = S.Stk.pop<Pointer>();
2835 const Pointer &Dst = S.Stk.peek<Pointer>();
2836
2837 for (unsigned I = 0; I != NumElems; ++I) {
2839 Dst.elem<T>(I) = static_cast<T>(
2840 APSInt(Fn(LHS.elem<T>(I).toAPSInt(), RHS), DestUnsigned));
2841 });
2842 }
2844 return true;
2845 }
2846
2847 // Vector case.
2848 assert(Call->getArg(0)->getType()->isVectorType() &&
2849 Call->getArg(1)->getType()->isVectorType());
2850 assert(VT->getElementType() ==
2851 Call->getArg(1)->getType()->castAs<VectorType>()->getElementType());
2852 assert(VT->getNumElements() ==
2853 Call->getArg(1)->getType()->castAs<VectorType>()->getNumElements());
2854 assert(VT->getElementType()->isIntegralOrEnumerationType());
2855
2856 const Pointer &RHS = S.Stk.pop<Pointer>();
2857 const Pointer &LHS = S.Stk.pop<Pointer>();
2858 const Pointer &Dst = S.Stk.peek<Pointer>();
2859 for (unsigned I = 0; I != NumElems; ++I) {
2861 APSInt Elem1 = LHS.elem<T>(I).toAPSInt();
2862 APSInt Elem2 = RHS.elem<T>(I).toAPSInt();
2863 Dst.elem<T>(I) = static_cast<T>(APSInt(Fn(Elem1, Elem2), DestUnsigned));
2864 });
2865 }
2867
2868 return true;
2869}
2870
2871static bool
2873 llvm::function_ref<APInt(const APSInt &)> PackFn) {
2874 const auto *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
2875 [[maybe_unused]] const auto *VT1 =
2876 E->getArg(1)->getType()->castAs<VectorType>();
2877 assert(VT0 && VT1 && "pack builtin VT0 and VT1 must be VectorType");
2878 assert(VT0->getElementType() == VT1->getElementType() &&
2879 VT0->getNumElements() == VT1->getNumElements() &&
2880 "pack builtin VT0 and VT1 ElementType must be same");
2881
2882 const Pointer &RHS = S.Stk.pop<Pointer>();
2883 const Pointer &LHS = S.Stk.pop<Pointer>();
2884 const Pointer &Dst = S.Stk.peek<Pointer>();
2885
2886 const ASTContext &ASTCtx = S.getASTContext();
2887 unsigned SrcBits = ASTCtx.getIntWidth(VT0->getElementType());
2888 unsigned LHSVecLen = VT0->getNumElements();
2889 unsigned SrcPerLane = 128 / SrcBits;
2890 unsigned Lanes = LHSVecLen * SrcBits / 128;
2891
2892 PrimType SrcT = *S.getContext().classify(VT0->getElementType());
2893 PrimType DstT = *S.getContext().classify(getElemType(Dst));
2894 bool IsUnsigend = getElemType(Dst)->isUnsignedIntegerType();
2895
2896 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
2897 unsigned BaseSrc = Lane * SrcPerLane;
2898 unsigned BaseDst = Lane * (2 * SrcPerLane);
2899
2900 for (unsigned I = 0; I != SrcPerLane; ++I) {
2902 APSInt A = LHS.elem<T>(BaseSrc + I).toAPSInt();
2903 APSInt B = RHS.elem<T>(BaseSrc + I).toAPSInt();
2904
2905 assignIntegral(S, Dst.atIndex(BaseDst + I), DstT,
2906 APSInt(PackFn(A), IsUnsigend));
2907 assignIntegral(S, Dst.atIndex(BaseDst + SrcPerLane + I), DstT,
2908 APSInt(PackFn(B), IsUnsigend));
2909 });
2910 }
2911 }
2912
2913 Dst.initializeAllElements();
2914 return true;
2915}
2916
2918 const CallExpr *Call,
2919 unsigned BuiltinID) {
2920 assert(Call->getNumArgs() == 2);
2921
2922 QualType Arg0Type = Call->getArg(0)->getType();
2923
2924 // TODO: Support floating-point types.
2925 if (!(Arg0Type->isIntegerType() ||
2926 (Arg0Type->isVectorType() &&
2927 Arg0Type->castAs<VectorType>()->getElementType()->isIntegerType())))
2928 return false;
2929
2930 if (!Arg0Type->isVectorType()) {
2931 assert(!Call->getArg(1)->getType()->isVectorType());
2932 APSInt RHS;
2933 if (!popToAPSInt(S, Call->getArg(1), RHS))
2934 return false;
2935 APSInt LHS;
2936 if (!popToAPSInt(S, Arg0Type, LHS))
2937 return false;
2938 APInt Result;
2939 if (BuiltinID == Builtin::BI__builtin_elementwise_max) {
2940 Result = std::max(LHS, RHS);
2941 } else if (BuiltinID == Builtin::BI__builtin_elementwise_min) {
2942 Result = std::min(LHS, RHS);
2943 } else {
2944 llvm_unreachable("Wrong builtin ID");
2945 }
2946
2947 pushInteger(S, APSInt(Result, !LHS.isSigned()), Call->getType());
2948 return true;
2949 }
2950
2951 // Vector case.
2952 assert(Call->getArg(0)->getType()->isVectorType() &&
2953 Call->getArg(1)->getType()->isVectorType());
2954 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
2955 assert(VT->getElementType() ==
2956 Call->getArg(1)->getType()->castAs<VectorType>()->getElementType());
2957 assert(VT->getNumElements() ==
2958 Call->getArg(1)->getType()->castAs<VectorType>()->getNumElements());
2959 assert(VT->getElementType()->isIntegralOrEnumerationType());
2960
2961 const Pointer &RHS = S.Stk.pop<Pointer>();
2962 const Pointer &LHS = S.Stk.pop<Pointer>();
2963 const Pointer &Dst = S.Stk.peek<Pointer>();
2964 PrimType ElemT = *S.getContext().classify(VT->getElementType());
2965 unsigned NumElems = VT->getNumElements();
2966 for (unsigned I = 0; I != NumElems; ++I) {
2967 APSInt Elem1;
2968 APSInt Elem2;
2970 Elem1 = LHS.elem<T>(I).toAPSInt();
2971 Elem2 = RHS.elem<T>(I).toAPSInt();
2972 });
2973
2974 APSInt Result;
2975 if (BuiltinID == Builtin::BI__builtin_elementwise_max) {
2976 Result = APSInt(std::max(Elem1, Elem2),
2977 Call->getType()->isUnsignedIntegerOrEnumerationType());
2978 } else if (BuiltinID == Builtin::BI__builtin_elementwise_min) {
2979 Result = APSInt(std::min(Elem1, Elem2),
2980 Call->getType()->isUnsignedIntegerOrEnumerationType());
2981 } else {
2982 llvm_unreachable("Wrong builtin ID");
2983 }
2984
2986 { Dst.elem<T>(I) = static_cast<T>(Result); });
2987 }
2988 Dst.initializeAllElements();
2989
2990 return true;
2991}
2992
2994 InterpState &S, CodePtr OpPC, const CallExpr *Call,
2995 llvm::function_ref<APInt(const APSInt &, const APSInt &, const APSInt &,
2996 const APSInt &)>
2997 Fn) {
2998 assert(Call->getArg(0)->getType()->isVectorType() &&
2999 Call->getArg(1)->getType()->isVectorType());
3000 const Pointer &RHS = S.Stk.pop<Pointer>();
3001 const Pointer &LHS = S.Stk.pop<Pointer>();
3002 const Pointer &Dst = S.Stk.peek<Pointer>();
3003
3004 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
3005 PrimType ElemT = *S.getContext().classify(VT->getElementType());
3006 unsigned NumElems = VT->getNumElements();
3007 const auto *DestVT = Call->getType()->castAs<VectorType>();
3008 PrimType DestElemT = *S.getContext().classify(DestVT->getElementType());
3009 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
3010
3011 unsigned DstElem = 0;
3012 for (unsigned I = 0; I != NumElems; I += 2) {
3013 APSInt Result;
3015 APSInt LoLHS = LHS.elem<T>(I).toAPSInt();
3016 APSInt HiLHS = LHS.elem<T>(I + 1).toAPSInt();
3017 APSInt LoRHS = RHS.elem<T>(I).toAPSInt();
3018 APSInt HiRHS = RHS.elem<T>(I + 1).toAPSInt();
3019 Result = APSInt(Fn(LoLHS, HiLHS, LoRHS, HiRHS), DestUnsigned);
3020 });
3021
3022 INT_TYPE_SWITCH_NO_BOOL(DestElemT,
3023 { Dst.elem<T>(DstElem) = static_cast<T>(Result); });
3024 ++DstElem;
3025 }
3026
3027 Dst.initializeAllElements();
3028 return true;
3029}
3030
3032 const CallExpr *Call) {
3033 assert(Call->getNumArgs() == 2);
3034
3035 const Pointer &RHS = S.Stk.pop<Pointer>();
3036 const Pointer &LHS = S.Stk.pop<Pointer>();
3037 const Pointer &Dst = S.Stk.peek<Pointer>();
3038
3039 const auto *SrcVT = Call->getArg(0)->getType()->castAs<VectorType>();
3040 PrimType SrcElemT = *S.getContext().classify(SrcVT->getElementType());
3041 unsigned SourceLen = SrcVT->getNumElements();
3042 assert((SourceLen % 8) == 0);
3043
3044 const auto *DestVT = Call->getType()->castAs<VectorType>();
3045 PrimType DestElemT = *S.getContext().classify(DestVT->getElementType());
3046 bool DestUnsigned =
3047 DestVT->getElementType()->isUnsignedIntegerOrEnumerationType();
3048
3049 unsigned DstElem = 0;
3050 for (unsigned Lane = 0; Lane != SourceLen; Lane += 8) {
3051 APInt Sum(64, 0);
3052 for (unsigned I = 0; I != 8; ++I) {
3053 INT_TYPE_SWITCH_NO_BOOL(SrcElemT, {
3054 APSInt L = LHS.elem<T>(Lane + I).toAPSInt();
3055 APSInt R = RHS.elem<T>(Lane + I).toAPSInt();
3056 Sum += llvm::APIntOps::abdu(L.extOrTrunc(8), R.extOrTrunc(8)).zext(64);
3057 });
3058 }
3059
3060 INT_TYPE_SWITCH_NO_BOOL(DestElemT, {
3061 Dst.elem<T>(DstElem) = static_cast<T>(APSInt(Sum, DestUnsigned));
3062 });
3063 ++DstElem;
3064 }
3065
3066 Dst.initializeAllElements();
3067 return true;
3068}
3069
3071 const CallExpr *Call) {
3072 assert(Call->getNumArgs() == 3);
3073 uint64_t Imm;
3074 if (!popToUInt64(S, Call->getArg(2), Imm))
3075 return false;
3076
3077 const Pointer &Src2 = S.Stk.pop<Pointer>();
3078 const Pointer &Src1 = S.Stk.pop<Pointer>();
3079 const Pointer &Dst = S.Stk.peek<Pointer>();
3080
3081 const auto *SrcVT = Call->getArg(0)->getType()->castAs<VectorType>();
3082 PrimType SrcElemT = *S.getContext().classify(SrcVT->getElementType());
3083 unsigned SourceLen = SrcVT->getNumElements();
3084
3085 const auto *DestVT = Call->getType()->castAs<VectorType>();
3086 PrimType DestElemT = *S.getContext().classify(DestVT->getElementType());
3087 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
3088
3089 constexpr unsigned LaneSize = 16; // 128-bit lane = 16 bytes
3090
3091 // Phase 1: Shuffle Src2 using all four 2-bit fields of imm8.
3092 // Within each 128-bit lane, for group j (0..3), select a 4-byte block
3093 // from Src2 based on bits [2*j+1:2*j] of imm8.
3094 SmallVector<uint8_t, 64> Shuffled(SourceLen);
3095 for (unsigned I = 0; I < SourceLen; I += LaneSize) {
3096 for (unsigned J = 0; J < 4; ++J) {
3097 unsigned Part = (Imm >> (2 * J)) & 3;
3098 for (unsigned K = 0; K < 4; ++K) {
3099 INT_TYPE_SWITCH_NO_BOOL(SrcElemT, {
3100 Shuffled[I + 4 * J + K] =
3101 static_cast<uint8_t>(Src2.elem<T>(I + 4 * Part + K));
3102 });
3103 }
3104 }
3105 }
3106
3107 // Phase 2: Sliding SAD computation.
3108 // For every group of 4 output u16 values, compute absolute differences
3109 // using overlapping windows into Src1 and the shuffled array.
3110 unsigned Size = SourceLen / 2; // number of output u16 elements
3111 for (unsigned I = 0; I < Size; I += 4) {
3112 unsigned Sad[4] = {0, 0, 0, 0};
3113 for (unsigned J = 0; J < 4; ++J) {
3114 uint8_t A1, A2;
3115 INT_TYPE_SWITCH_NO_BOOL(SrcElemT, {
3116 A1 = static_cast<uint8_t>(Src1.elem<T>(2 * I + J));
3117 A2 = static_cast<uint8_t>(Src1.elem<T>(2 * I + J + 4));
3118 });
3119 uint8_t B0 = Shuffled[2 * I + J];
3120 uint8_t B1 = Shuffled[2 * I + J + 1];
3121 uint8_t B2 = Shuffled[2 * I + J + 2];
3122 uint8_t B3 = Shuffled[2 * I + J + 3];
3123 Sad[0] += (A1 > B0) ? (A1 - B0) : (B0 - A1);
3124 Sad[1] += (A1 > B1) ? (A1 - B1) : (B1 - A1);
3125 Sad[2] += (A2 > B2) ? (A2 - B2) : (B2 - A2);
3126 Sad[3] += (A2 > B3) ? (A2 - B3) : (B3 - A2);
3127 }
3128 for (unsigned R = 0; R < 4; ++R) {
3129 INT_TYPE_SWITCH_NO_BOOL(DestElemT, {
3130 Dst.elem<T>(I + R) =
3131 static_cast<T>(APSInt(APInt(16, Sad[R]), DestUnsigned));
3132 });
3133 }
3134 }
3135
3136 Dst.initializeAllElements();
3137 return true;
3138}
3139
3141 const CallExpr *Call) {
3142 assert(Call->getNumArgs() == 3);
3143 uint64_t Imm;
3144 if (!popToUInt64(S, Call->getArg(2), Imm))
3145 return false;
3146
3147 const Pointer &Src2 = S.Stk.pop<Pointer>();
3148 const Pointer &Src1 = S.Stk.pop<Pointer>();
3149 const Pointer &Dst = S.Stk.peek<Pointer>();
3150
3151 const auto *SrcVT = Call->getArg(0)->getType()->castAs<VectorType>();
3152 PrimType SrcElemT = *S.getContext().classify(SrcVT->getElementType());
3153 unsigned SourceLen = SrcVT->getNumElements();
3154 assert((SourceLen == 16 || SourceLen == 32) &&
3155 "MPSADBW operates on 128-bit or 256-bit vectors");
3156
3157 const auto *DestVT = Call->getType()->castAs<VectorType>();
3158 PrimType DestElemT = *S.getContext().classify(DestVT->getElementType());
3159 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
3160
3161 constexpr unsigned LaneSize = 16; // 128-bit lane = 16 bytes
3162 unsigned NumLanes = SourceLen / LaneSize;
3163
3164 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
3165 unsigned Ctrl = (Imm >> (3 * Lane)) & 0x7;
3166 unsigned AOff = ((Ctrl >> 2) & 1) * 4;
3167 unsigned BOff = (Ctrl & 3) * 4;
3168 for (unsigned J = 0; J != 8; ++J) {
3169 uint16_t Sad = 0;
3170 for (unsigned K = 0; K != 4; ++K) {
3171 uint8_t A, B;
3172 INT_TYPE_SWITCH_NO_BOOL(SrcElemT, {
3173 A = static_cast<uint8_t>(
3174 Src1.elem<T>(Lane * LaneSize + AOff + J + K));
3175 B = static_cast<uint8_t>(Src2.elem<T>(Lane * LaneSize + BOff + K));
3176 });
3177 Sad += (A > B) ? (A - B) : (B - A);
3178 }
3179 INT_TYPE_SWITCH_NO_BOOL(DestElemT, {
3180 Dst.elem<T>(Lane * 8 + J) =
3181 static_cast<T>(APSInt(APInt(16, Sad), DestUnsigned));
3182 });
3183 }
3184 }
3185
3186 Dst.initializeAllElements();
3187 return true;
3188}
3189
3191 InterpState &S, CodePtr OpPC, const CallExpr *Call,
3192 llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
3193 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
3194 PrimType ElemT = *S.getContext().classify(VT->getElementType());
3195 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
3196
3197 const Pointer &RHS = S.Stk.pop<Pointer>();
3198 const Pointer &LHS = S.Stk.pop<Pointer>();
3199 const Pointer &Dst = S.Stk.peek<Pointer>();
3200 unsigned NumElts = VT->getNumElements();
3201 unsigned EltBits = S.getASTContext().getIntWidth(VT->getElementType());
3202 unsigned EltsPerLane = 128 / EltBits;
3203 unsigned Lanes = NumElts * EltBits / 128;
3204 unsigned DestIndex = 0;
3205
3206 for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
3207 unsigned LaneStart = Lane * EltsPerLane;
3208 for (unsigned I = 0; I < EltsPerLane; I += 2) {
3210 APSInt Elem1 = LHS.elem<T>(LaneStart + I).toAPSInt();
3211 APSInt Elem2 = LHS.elem<T>(LaneStart + I + 1).toAPSInt();
3212 APSInt ResL = APSInt(Fn(Elem1, Elem2), DestUnsigned);
3213 Dst.elem<T>(DestIndex++) = static_cast<T>(ResL);
3214 });
3215 }
3216
3217 for (unsigned I = 0; I < EltsPerLane; I += 2) {
3219 APSInt Elem1 = RHS.elem<T>(LaneStart + I).toAPSInt();
3220 APSInt Elem2 = RHS.elem<T>(LaneStart + I + 1).toAPSInt();
3221 APSInt ResR = APSInt(Fn(Elem1, Elem2), DestUnsigned);
3222 Dst.elem<T>(DestIndex++) = static_cast<T>(ResR);
3223 });
3224 }
3225 }
3226 Dst.initializeAllElements();
3227 return true;
3228}
3229
3231 InterpState &S, CodePtr OpPC, const CallExpr *Call,
3232 llvm::function_ref<APFloat(const APFloat &, const APFloat &,
3233 llvm::RoundingMode)>
3234 Fn) {
3235 const Pointer &RHS = S.Stk.pop<Pointer>();
3236 const Pointer &LHS = S.Stk.pop<Pointer>();
3237 const Pointer &Dst = S.Stk.peek<Pointer>();
3238 FPOptions FPO = Call->getFPFeaturesInEffect(S.Ctx.getLangOpts());
3239 llvm::RoundingMode RM = getRoundingMode(FPO);
3240 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
3241
3242 unsigned NumElts = VT->getNumElements();
3243 unsigned EltBits = S.getASTContext().getTypeSize(VT->getElementType());
3244 unsigned NumLanes = NumElts * EltBits / 128;
3245 unsigned NumElemsPerLane = NumElts / NumLanes;
3246 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
3247
3248 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
3249 using T = PrimConv<PT_Float>::T;
3250 for (unsigned E = 0; E != HalfElemsPerLane; ++E) {
3251 APFloat Elem1 = LHS.elem<T>(L + (2 * E) + 0).getAPFloat();
3252 APFloat Elem2 = LHS.elem<T>(L + (2 * E) + 1).getAPFloat();
3253 Dst.elem<T>(L + E) = static_cast<T>(Fn(Elem1, Elem2, RM));
3254 }
3255 for (unsigned E = 0; E != HalfElemsPerLane; ++E) {
3256 APFloat Elem1 = RHS.elem<T>(L + (2 * E) + 0).getAPFloat();
3257 APFloat Elem2 = RHS.elem<T>(L + (2 * E) + 1).getAPFloat();
3258 Dst.elem<T>(L + E + HalfElemsPerLane) =
3259 static_cast<T>(Fn(Elem1, Elem2, RM));
3260 }
3261 }
3262 Dst.initializeAllElements();
3263 return true;
3264}
3265
3267 const CallExpr *Call) {
3268 // Addsub: alternates between subtraction and addition
3269 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
3270 const Pointer &RHS = S.Stk.pop<Pointer>();
3271 const Pointer &LHS = S.Stk.pop<Pointer>();
3272 const Pointer &Dst = S.Stk.peek<Pointer>();
3273 FPOptions FPO = Call->getFPFeaturesInEffect(S.Ctx.getLangOpts());
3274 llvm::RoundingMode RM = getRoundingMode(FPO);
3275 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
3276 unsigned NumElems = VT->getNumElements();
3277
3278 using T = PrimConv<PT_Float>::T;
3279 for (unsigned I = 0; I != NumElems; ++I) {
3280 APFloat LElem = LHS.elem<T>(I).getAPFloat();
3281 APFloat RElem = RHS.elem<T>(I).getAPFloat();
3282 if (I % 2 == 0) {
3283 // Even indices: subtract
3284 LElem.subtract(RElem, RM);
3285 } else {
3286 // Odd indices: add
3287 LElem.add(RElem, RM);
3288 }
3289 Dst.elem<T>(I) = static_cast<T>(LElem);
3290 }
3291 Dst.initializeAllElements();
3292 return true;
3293}
3294
3296 const CallExpr *Call) {
3297 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
3298 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
3299 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
3300 assert(Call->getArg(0)->getType()->isVectorType() &&
3301 Call->getArg(1)->getType()->isVectorType());
3302
3303 // Extract imm8 argument
3304 APSInt Imm8;
3305 if (!popToAPSInt(S, Call->getArg(2), Imm8))
3306 return false;
3307 bool SelectUpperA = (Imm8 & 0x01) != 0;
3308 bool SelectUpperB = (Imm8 & 0x10) != 0;
3309
3310 const Pointer &RHS = S.Stk.pop<Pointer>();
3311 const Pointer &LHS = S.Stk.pop<Pointer>();
3312 const Pointer &Dst = S.Stk.peek<Pointer>();
3313
3314 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
3315 PrimType ElemT = *S.getContext().classify(VT->getElementType());
3316 unsigned NumElems = VT->getNumElements();
3317 const auto *DestVT = Call->getType()->castAs<VectorType>();
3318 PrimType DestElemT = *S.getContext().classify(DestVT->getElementType());
3319 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
3320
3321 // Process each 128-bit lane (2 elements at a time)
3322 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
3323 APSInt A0, A1, B0, B1;
3325 A0 = LHS.elem<T>(Lane + 0).toAPSInt();
3326 A1 = LHS.elem<T>(Lane + 1).toAPSInt();
3327 B0 = RHS.elem<T>(Lane + 0).toAPSInt();
3328 B1 = RHS.elem<T>(Lane + 1).toAPSInt();
3329 });
3330
3331 // Select the appropriate 64-bit values based on imm8
3332 APInt A = SelectUpperA ? A1 : A0;
3333 APInt B = SelectUpperB ? B1 : B0;
3334
3335 // Extend both operands to 128 bits for carry-less multiplication
3336 APInt A128 = A.zext(128);
3337 APInt B128 = B.zext(128);
3338
3339 // Use APIntOps::clmul for carry-less multiplication
3340 APInt Result = llvm::APIntOps::clmul(A128, B128);
3341
3342 // Split the 128-bit result into two 64-bit halves
3343 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
3344 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
3345
3346 INT_TYPE_SWITCH_NO_BOOL(DestElemT, {
3347 Dst.elem<T>(Lane + 0) = static_cast<T>(ResultLow);
3348 Dst.elem<T>(Lane + 1) = static_cast<T>(ResultHigh);
3349 });
3350 }
3351
3352 Dst.initializeAllElements();
3353 return true;
3354}
3355
3357 InterpState &S, CodePtr OpPC, const CallExpr *Call,
3358 llvm::function_ref<APFloat(const APFloat &, const APFloat &,
3359 const APFloat &, llvm::RoundingMode)>
3360 Fn) {
3361 assert(Call->getNumArgs() == 3);
3362
3363 FPOptions FPO = Call->getFPFeaturesInEffect(S.Ctx.getLangOpts());
3364 llvm::RoundingMode RM = getRoundingMode(FPO);
3365 QualType Arg1Type = Call->getArg(0)->getType();
3366 QualType Arg2Type = Call->getArg(1)->getType();
3367 QualType Arg3Type = Call->getArg(2)->getType();
3368
3369 // Non-vector floating point types.
3370 if (!Arg1Type->isVectorType()) {
3371 assert(!Arg2Type->isVectorType());
3372 assert(!Arg3Type->isVectorType());
3373 (void)Arg2Type;
3374 (void)Arg3Type;
3375
3376 const Floating &Z = S.Stk.pop<Floating>();
3377 const Floating &Y = S.Stk.pop<Floating>();
3378 const Floating &X = S.Stk.pop<Floating>();
3379 APFloat F = Fn(X.getAPFloat(), Y.getAPFloat(), Z.getAPFloat(), RM);
3380 Floating Result = S.allocFloat(X.getSemantics());
3381 Result.copy(F);
3382 S.Stk.push<Floating>(Result);
3383 return true;
3384 }
3385
3386 // Vector type.
3387 assert(Arg1Type->isVectorType() && Arg2Type->isVectorType() &&
3388 Arg3Type->isVectorType());
3389
3390 const VectorType *VecTy = Arg1Type->castAs<VectorType>();
3391 QualType ElemQT = VecTy->getElementType();
3392 unsigned NumElems = VecTy->getNumElements();
3393
3394 assert(ElemQT == Arg2Type->castAs<VectorType>()->getElementType() &&
3395 ElemQT == Arg3Type->castAs<VectorType>()->getElementType());
3396 assert(NumElems == Arg2Type->castAs<VectorType>()->getNumElements() &&
3397 NumElems == Arg3Type->castAs<VectorType>()->getNumElements());
3398 assert(ElemQT->isRealFloatingType());
3399 (void)ElemQT;
3400
3401 const Pointer &VZ = S.Stk.pop<Pointer>();
3402 const Pointer &VY = S.Stk.pop<Pointer>();
3403 const Pointer &VX = S.Stk.pop<Pointer>();
3404 const Pointer &Dst = S.Stk.peek<Pointer>();
3405 for (unsigned I = 0; I != NumElems; ++I) {
3406 using T = PrimConv<PT_Float>::T;
3407 APFloat X = VX.elem<T>(I).getAPFloat();
3408 APFloat Y = VY.elem<T>(I).getAPFloat();
3409 APFloat Z = VZ.elem<T>(I).getAPFloat();
3410 APFloat F = Fn(X, Y, Z, RM);
3411 Dst.elem<Floating>(I) = Floating(F);
3412 }
3414 return true;
3415}
3416
3417/// AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
3419 const CallExpr *Call) {
3420 const Pointer &RHS = S.Stk.pop<Pointer>();
3421 const Pointer &LHS = S.Stk.pop<Pointer>();
3422 APSInt Mask;
3423 if (!popToAPSInt(S, Call->getArg(0), Mask))
3424 return false;
3425 const Pointer &Dst = S.Stk.peek<Pointer>();
3426
3427 assert(LHS.getNumElems() == RHS.getNumElems());
3428 assert(LHS.getNumElems() == Dst.getNumElems());
3429 unsigned NumElems = LHS.getNumElems();
3430 PrimType ElemT = LHS.getFieldDesc()->getPrimType();
3431 PrimType DstElemT = Dst.getFieldDesc()->getPrimType();
3432
3433 for (unsigned I = 0; I != NumElems; ++I) {
3434 if (ElemT == PT_Float) {
3435 assert(DstElemT == PT_Float);
3436 Dst.elem<Floating>(I) =
3437 Mask[I] ? LHS.elem<Floating>(I) : RHS.elem<Floating>(I);
3438 } else {
3439 APSInt Elem;
3440 INT_TYPE_SWITCH(ElemT, {
3441 Elem = Mask[I] ? LHS.elem<T>(I).toAPSInt() : RHS.elem<T>(I).toAPSInt();
3442 });
3443 INT_TYPE_SWITCH_NO_BOOL(DstElemT,
3444 { Dst.elem<T>(I) = static_cast<T>(Elem); });
3445 }
3446 }
3448
3449 return true;
3450}
3451
3452/// Scalar variant of AVX512 predicated select:
3453/// Result[i] = (Mask bit 0) ? LHS[i] : RHS[i], but only element 0 may change.
3454/// All other elements are taken from RHS.
3456 const CallExpr *Call) {
3457 unsigned N =
3458 Call->getArg(1)->getType()->castAs<VectorType>()->getNumElements();
3459
3460 const Pointer &W = S.Stk.pop<Pointer>();
3461 const Pointer &A = S.Stk.pop<Pointer>();
3462 APSInt U;
3463 if (!popToAPSInt(S, Call->getArg(0), U))
3464 return false;
3465 const Pointer &Dst = S.Stk.peek<Pointer>();
3466
3467 bool TakeA0 = U.getZExtValue() & 1ULL;
3468
3469 for (unsigned I = TakeA0; I != N; ++I)
3470 Dst.elem<Floating>(I) = W.elem<Floating>(I);
3471 if (TakeA0)
3472 Dst.elem<Floating>(0) = A.elem<Floating>(0);
3473
3475 return true;
3476}
3477
3479 InterpState &S, CodePtr OpPC, const CallExpr *Call,
3480 llvm::function_ref<bool(const APInt &A, const APInt &B)> Fn) {
3481 const Pointer &RHS = S.Stk.pop<Pointer>();
3482 const Pointer &LHS = S.Stk.pop<Pointer>();
3483
3484 assert(LHS.getNumElems() == RHS.getNumElems());
3485
3486 unsigned SourceLen = LHS.getNumElems();
3487 QualType ElemQT = getElemType(LHS);
3488 OptPrimType ElemPT = S.getContext().classify(ElemQT);
3489 unsigned LaneWidth = S.getASTContext().getTypeSize(ElemQT);
3490
3491 APInt AWide(LaneWidth * SourceLen, 0);
3492 APInt BWide(LaneWidth * SourceLen, 0);
3493
3494 for (unsigned I = 0; I != SourceLen; ++I) {
3495 APInt ALane;
3496 APInt BLane;
3497
3498 if (ElemQT->isIntegerType()) { // Get value.
3499 INT_TYPE_SWITCH_NO_BOOL(*ElemPT, {
3500 ALane = LHS.elem<T>(I).toAPSInt();
3501 BLane = RHS.elem<T>(I).toAPSInt();
3502 });
3503 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
3504 using T = PrimConv<PT_Float>::T;
3505 ALane = LHS.elem<T>(I).getAPFloat().bitcastToAPInt().isNegative();
3506 BLane = RHS.elem<T>(I).getAPFloat().bitcastToAPInt().isNegative();
3507 } else { // Must be integer or floating type.
3508 return false;
3509 }
3510 AWide.insertBits(ALane, I * LaneWidth);
3511 BWide.insertBits(BLane, I * LaneWidth);
3512 }
3513 pushInteger(S, Fn(AWide, BWide), Call->getType());
3514 return true;
3515}
3516
3518 const CallExpr *Call) {
3519 assert(Call->getNumArgs() == 1);
3520
3521 const Pointer &Source = S.Stk.pop<Pointer>();
3522
3523 unsigned SourceLen = Source.getNumElems();
3524 QualType ElemQT = getElemType(Source);
3525 OptPrimType ElemT = S.getContext().classify(ElemQT);
3526 unsigned ResultLen =
3527 S.getASTContext().getTypeSize(Call->getType()); // Always 32-bit integer.
3528 APInt Result(ResultLen, 0);
3529
3530 for (unsigned I = 0; I != SourceLen; ++I) {
3531 APInt Elem;
3532 if (ElemQT->isIntegerType()) {
3533 INT_TYPE_SWITCH_NO_BOOL(*ElemT, { Elem = Source.elem<T>(I).toAPSInt(); });
3534 } else if (ElemQT->isRealFloatingType()) {
3535 using T = PrimConv<PT_Float>::T;
3536 Elem = Source.elem<T>(I).getAPFloat().bitcastToAPInt();
3537 } else {
3538 return false;
3539 }
3540 Result.setBitVal(I, Elem.isNegative());
3541 }
3542 pushInteger(S, Result, Call->getType());
3543 return true;
3544}
3545
3547 InterpState &S, CodePtr OpPC, const CallExpr *Call,
3548 llvm::function_ref<APInt(const APSInt &, const APSInt &, const APSInt &)>
3549 Fn) {
3550 assert(Call->getNumArgs() == 3);
3551
3552 QualType Arg0Type = Call->getArg(0)->getType();
3553 QualType Arg2Type = Call->getArg(2)->getType();
3554 // Non-vector integer types.
3555 if (!Arg0Type->isVectorType()) {
3556 APSInt Op2;
3557 if (!popToAPSInt(S, Arg2Type, Op2))
3558 return false;
3559 APSInt Op1;
3560 if (!popToAPSInt(S, Call->getArg(1), Op1))
3561 return false;
3562 APSInt Op0;
3563 if (!popToAPSInt(S, Arg0Type, Op0))
3564 return false;
3565 APSInt Result = APSInt(Fn(Op0, Op1, Op2), Op0.isUnsigned());
3566 pushInteger(S, Result, Call->getType());
3567 return true;
3568 }
3569
3570 const auto *VecT = Arg0Type->castAs<VectorType>();
3571 PrimType ElemT = *S.getContext().classify(VecT->getElementType());
3572 unsigned NumElems = VecT->getNumElements();
3573 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
3574
3575 // Vector + Vector + Scalar case.
3576 if (!Arg2Type->isVectorType()) {
3577 APSInt Op2;
3578 if (!popToAPSInt(S, Arg2Type, Op2))
3579 return false;
3580
3581 const Pointer &Op1 = S.Stk.pop<Pointer>();
3582 const Pointer &Op0 = S.Stk.pop<Pointer>();
3583 const Pointer &Dst = S.Stk.peek<Pointer>();
3584 for (unsigned I = 0; I != NumElems; ++I) {
3586 Dst.elem<T>(I) = static_cast<T>(APSInt(
3587 Fn(Op0.elem<T>(I).toAPSInt(), Op1.elem<T>(I).toAPSInt(), Op2),
3588 DestUnsigned));
3589 });
3590 }
3592
3593 return true;
3594 }
3595
3596 // Vector type.
3597 const Pointer &Op2 = S.Stk.pop<Pointer>();
3598 const Pointer &Op1 = S.Stk.pop<Pointer>();
3599 const Pointer &Op0 = S.Stk.pop<Pointer>();
3600 const Pointer &Dst = S.Stk.peek<Pointer>();
3601 for (unsigned I = 0; I != NumElems; ++I) {
3602 APSInt Val0, Val1, Val2;
3604 Val0 = Op0.elem<T>(I).toAPSInt();
3605 Val1 = Op1.elem<T>(I).toAPSInt();
3606 Val2 = Op2.elem<T>(I).toAPSInt();
3607 });
3608 APSInt Result = APSInt(Fn(Val0, Val1, Val2), Val0.isUnsigned());
3610 { Dst.elem<T>(I) = static_cast<T>(Result); });
3611 }
3613
3614 return true;
3615}
3616
3618 const CallExpr *Call,
3619 unsigned ID) {
3620 assert(Call->getNumArgs() == 2);
3621
3622 APSInt ImmAPS;
3623 if (!popToAPSInt(S, Call->getArg(1), ImmAPS))
3624 return false;
3625 uint64_t Index = ImmAPS.getZExtValue();
3626
3627 const Pointer &Src = S.Stk.pop<Pointer>();
3628 if (!Src.getFieldDesc()->isPrimitiveArray())
3629 return false;
3630
3631 const Pointer &Dst = S.Stk.peek<Pointer>();
3632 if (!Dst.getFieldDesc()->isPrimitiveArray())
3633 return false;
3634
3635 unsigned SrcElems = Src.getNumElems();
3636 unsigned DstElems = Dst.getNumElems();
3637
3638 unsigned NumLanes = SrcElems / DstElems;
3639 unsigned Lane = static_cast<unsigned>(Index % NumLanes);
3640 unsigned ExtractPos = Lane * DstElems;
3641
3642 PrimType ElemT = Src.getFieldDesc()->getPrimType();
3643
3644 TYPE_SWITCH(ElemT, {
3645 for (unsigned I = 0; I != DstElems; ++I) {
3646 Dst.elem<T>(I) = Src.elem<T>(ExtractPos + I);
3647 }
3648 });
3649
3651 return true;
3652}
3653
3655 CodePtr OpPC,
3656 const CallExpr *Call,
3657 unsigned ID) {
3658 assert(Call->getNumArgs() == 4);
3659
3660 APSInt MaskAPS;
3661 if (!popToAPSInt(S, Call->getArg(3), MaskAPS))
3662 return false;
3663 const Pointer &Merge = S.Stk.pop<Pointer>();
3664 APSInt ImmAPS;
3665 if (!popToAPSInt(S, Call->getArg(1), ImmAPS))
3666 return false;
3667 const Pointer &Src = S.Stk.pop<Pointer>();
3668
3669 if (!Src.getFieldDesc()->isPrimitiveArray() ||
3670 !Merge.getFieldDesc()->isPrimitiveArray())
3671 return false;
3672
3673 const Pointer &Dst = S.Stk.peek<Pointer>();
3674 if (!Dst.getFieldDesc()->isPrimitiveArray())
3675 return false;
3676
3677 unsigned SrcElems = Src.getNumElems();
3678 unsigned DstElems = Dst.getNumElems();
3679
3680 unsigned NumLanes = SrcElems / DstElems;
3681 unsigned Lane = static_cast<unsigned>(ImmAPS.getZExtValue() % NumLanes);
3682 unsigned Base = Lane * DstElems;
3683
3684 PrimType ElemT = Src.getFieldDesc()->getPrimType();
3685
3686 TYPE_SWITCH(ElemT, {
3687 for (unsigned I = 0; I != DstElems; ++I) {
3688 if (MaskAPS[I])
3689 Dst.elem<T>(I) = Src.elem<T>(Base + I);
3690 else
3691 Dst.elem<T>(I) = Merge.elem<T>(I);
3692 }
3693 });
3694
3696 return true;
3697}
3698
3700 const CallExpr *Call,
3701 unsigned ID) {
3702 assert(Call->getNumArgs() == 3);
3703
3704 APSInt ImmAPS;
3705 if (!popToAPSInt(S, Call->getArg(2), ImmAPS))
3706 return false;
3707 uint64_t Index = ImmAPS.getZExtValue();
3708
3709 const Pointer &SubVec = S.Stk.pop<Pointer>();
3710 if (!SubVec.getFieldDesc()->isPrimitiveArray())
3711 return false;
3712
3713 const Pointer &BaseVec = S.Stk.pop<Pointer>();
3714 if (!BaseVec.getFieldDesc()->isPrimitiveArray())
3715 return false;
3716
3717 const Pointer &Dst = S.Stk.peek<Pointer>();
3718
3719 unsigned BaseElements = BaseVec.getNumElems();
3720 unsigned SubElements = SubVec.getNumElems();
3721
3722 assert(SubElements != 0 && BaseElements != 0 &&
3723 (BaseElements % SubElements) == 0);
3724
3725 unsigned NumLanes = BaseElements / SubElements;
3726 unsigned Lane = static_cast<unsigned>(Index % NumLanes);
3727 unsigned InsertPos = Lane * SubElements;
3728
3729 PrimType ElemT = BaseVec.getFieldDesc()->getPrimType();
3730
3731 TYPE_SWITCH(ElemT, {
3732 for (unsigned I = 0; I != BaseElements; ++I)
3733 Dst.elem<T>(I) = BaseVec.elem<T>(I);
3734 for (unsigned I = 0; I != SubElements; ++I)
3735 Dst.elem<T>(InsertPos + I) = SubVec.elem<T>(I);
3736 });
3737
3739 return true;
3740}
3741
3743 const CallExpr *Call) {
3744 assert(Call->getNumArgs() == 1);
3745
3746 const Pointer &Source = S.Stk.pop<Pointer>();
3747 const Pointer &Dest = S.Stk.peek<Pointer>();
3748
3749 unsigned SourceLen = Source.getNumElems();
3750 QualType ElemQT = getElemType(Source);
3751 OptPrimType ElemT = S.getContext().classify(ElemQT);
3752 unsigned ElemBitWidth = S.getASTContext().getTypeSize(ElemQT);
3753
3754 bool DestUnsigned = Call->getCallReturnType(S.getASTContext())
3755 ->castAs<VectorType>()
3756 ->getElementType()
3758
3759 INT_TYPE_SWITCH_NO_BOOL(*ElemT, {
3760 APSInt MinIndex(ElemBitWidth, DestUnsigned);
3761 APSInt MinVal = Source.elem<T>(0).toAPSInt();
3762
3763 for (unsigned I = 1; I != SourceLen; ++I) {
3764 APSInt Val = Source.elem<T>(I).toAPSInt();
3765 if (MinVal.ugt(Val)) {
3766 MinVal = Val;
3767 MinIndex = I;
3768 }
3769 }
3770
3771 Dest.elem<T>(0) = static_cast<T>(MinVal);
3772 Dest.elem<T>(1) = static_cast<T>(MinIndex);
3773 for (unsigned I = 2; I != SourceLen; ++I) {
3774 Dest.elem<T>(I) = static_cast<T>(APSInt(ElemBitWidth, DestUnsigned));
3775 }
3776 });
3777 Dest.initializeAllElements();
3778 return true;
3779}
3780
3782 const CallExpr *Call, bool MaskZ) {
3783 assert(Call->getNumArgs() == 5);
3784
3785 APSInt UVal;
3786 if (!popToAPSInt(S, Call->getArg(4), UVal))
3787 return false;
3788 APInt U = UVal; // Lane mask
3789 APSInt ImmVal;
3790 if (!popToAPSInt(S, Call->getArg(3), ImmVal))
3791 return false;
3792 APInt Imm = ImmVal; // Ternary truth table
3793 const Pointer &C = S.Stk.pop<Pointer>();
3794 const Pointer &B = S.Stk.pop<Pointer>();
3795 const Pointer &A = S.Stk.pop<Pointer>();
3796 const Pointer &Dst = S.Stk.peek<Pointer>();
3797
3798 unsigned DstLen = A.getNumElems();
3799 QualType ElemQT = getElemType(A);
3800 OptPrimType ElemT = S.getContext().classify(ElemQT);
3801 unsigned LaneWidth = S.getASTContext().getTypeSize(ElemQT);
3802 bool DstUnsigned = ElemQT->isUnsignedIntegerOrEnumerationType();
3803
3804 INT_TYPE_SWITCH_NO_BOOL(*ElemT, {
3805 for (unsigned I = 0; I != DstLen; ++I) {
3806 APInt ALane = A.elem<T>(I).toAPSInt();
3807 APInt BLane = B.elem<T>(I).toAPSInt();
3808 APInt CLane = C.elem<T>(I).toAPSInt();
3809 APInt RLane(LaneWidth, 0);
3810 if (U[I]) { // If lane not masked, compute ternary logic.
3811 for (unsigned Bit = 0; Bit != LaneWidth; ++Bit) {
3812 unsigned ABit = ALane[Bit];
3813 unsigned BBit = BLane[Bit];
3814 unsigned CBit = CLane[Bit];
3815 unsigned Idx = (ABit << 2) | (BBit << 1) | (CBit);
3816 RLane.setBitVal(Bit, Imm[Idx]);
3817 }
3818 Dst.elem<T>(I) = static_cast<T>(APSInt(RLane, DstUnsigned));
3819 } else if (MaskZ) { // If zero masked, zero the lane.
3820 Dst.elem<T>(I) = static_cast<T>(APSInt(RLane, DstUnsigned));
3821 } else { // Just masked, put in A lane.
3822 Dst.elem<T>(I) = static_cast<T>(APSInt(ALane, DstUnsigned));
3823 }
3824 }
3825 });
3826 Dst.initializeAllElements();
3827 return true;
3828}
3829
3831 const CallExpr *Call, unsigned ID) {
3832 assert(Call->getNumArgs() == 2);
3833
3834 APSInt ImmAPS;
3835 if (!popToAPSInt(S, Call->getArg(1), ImmAPS))
3836 return false;
3837 const Pointer &Vec = S.Stk.pop<Pointer>();
3838 if (!Vec.getFieldDesc()->isPrimitiveArray())
3839 return false;
3840
3841 unsigned NumElems = Vec.getNumElems();
3842 unsigned Index =
3843 static_cast<unsigned>(ImmAPS.getZExtValue() & (NumElems - 1));
3844
3845 PrimType ElemT = Vec.getFieldDesc()->getPrimType();
3846 // FIXME(#161685): Replace float+int split with a numeric-only type switch
3847 if (ElemT == PT_Float) {
3848 S.Stk.push<Floating>(Vec.elem<Floating>(Index));
3849 return true;
3850 }
3852 APSInt V = Vec.elem<T>(Index).toAPSInt();
3853 pushInteger(S, V, Call->getType());
3854 });
3855
3856 return true;
3857}
3858
3860 const CallExpr *Call, unsigned ID) {
3861 assert(Call->getNumArgs() == 3);
3862
3863 APSInt ImmAPS;
3864 if (!popToAPSInt(S, Call->getArg(2), ImmAPS))
3865 return false;
3866 APSInt ValAPS;
3867 if (!popToAPSInt(S, Call->getArg(1), ValAPS))
3868 return false;
3869
3870 const Pointer &Base = S.Stk.pop<Pointer>();
3871 if (!Base.getFieldDesc()->isPrimitiveArray())
3872 return false;
3873
3874 const Pointer &Dst = S.Stk.peek<Pointer>();
3875
3876 unsigned NumElems = Base.getNumElems();
3877 unsigned Index =
3878 static_cast<unsigned>(ImmAPS.getZExtValue() & (NumElems - 1));
3879
3880 PrimType ElemT = Base.getFieldDesc()->getPrimType();
3882 for (unsigned I = 0; I != NumElems; ++I)
3883 Dst.elem<T>(I) = Base.elem<T>(I);
3884 Dst.elem<T>(Index) = static_cast<T>(ValAPS);
3885 });
3886
3888 return true;
3889}
3890
3891static bool evalICmpImm(uint8_t Imm, const APSInt &A, const APSInt &B,
3892 bool IsUnsigned) {
3893 switch (Imm & 0x7) {
3894 case 0x00: // _MM_CMPINT_EQ
3895 return (A == B);
3896 case 0x01: // _MM_CMPINT_LT
3897 return IsUnsigned ? A.ult(B) : A.slt(B);
3898 case 0x02: // _MM_CMPINT_LE
3899 return IsUnsigned ? A.ule(B) : A.sle(B);
3900 case 0x03: // _MM_CMPINT_FALSE
3901 return false;
3902 case 0x04: // _MM_CMPINT_NE
3903 return (A != B);
3904 case 0x05: // _MM_CMPINT_NLT
3905 return IsUnsigned ? A.uge(B) : A.sge(B);
3906 case 0x06: // _MM_CMPINT_NLE
3907 return IsUnsigned ? A.ugt(B) : A.sgt(B);
3908 case 0x07: // _MM_CMPINT_TRUE
3909 return true;
3910 default:
3911 llvm_unreachable("Invalid Op");
3912 }
3913}
3914
3916 const CallExpr *Call, unsigned ID,
3917 bool IsUnsigned) {
3918 assert(Call->getNumArgs() == 4);
3919
3920 APSInt Mask;
3921 if (!popToAPSInt(S, Call->getArg(3), Mask))
3922 return false;
3923 APSInt Opcode;
3924 if (!popToAPSInt(S, Call->getArg(2), Opcode))
3925 return false;
3926 unsigned CmpOp = static_cast<unsigned>(Opcode.getZExtValue());
3927 const Pointer &RHS = S.Stk.pop<Pointer>();
3928 const Pointer &LHS = S.Stk.pop<Pointer>();
3929
3930 assert(LHS.getNumElems() == RHS.getNumElems());
3931
3932 APInt RetMask = APInt::getZero(LHS.getNumElems());
3933 unsigned VectorLen = LHS.getNumElems();
3934 PrimType ElemT = LHS.getFieldDesc()->getPrimType();
3935
3936 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
3937 APSInt A, B;
3939 A = LHS.elem<T>(ElemNum).toAPSInt();
3940 B = RHS.elem<T>(ElemNum).toAPSInt();
3941 });
3942 RetMask.setBitVal(ElemNum,
3943 Mask[ElemNum] && evalICmpImm(CmpOp, A, B, IsUnsigned));
3944 }
3945 pushInteger(S, RetMask, Call->getType());
3946 return true;
3947}
3948
3950 const CallExpr *Call) {
3951 assert(Call->getNumArgs() == 1);
3952
3953 QualType Arg0Type = Call->getArg(0)->getType();
3954 const auto *VecT = Arg0Type->castAs<VectorType>();
3955 PrimType ElemT = *S.getContext().classify(VecT->getElementType());
3956 unsigned NumElems = VecT->getNumElements();
3957 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
3958 const Pointer &Src = S.Stk.pop<Pointer>();
3959 const Pointer &Dst = S.Stk.peek<Pointer>();
3960
3961 for (unsigned I = 0; I != NumElems; ++I) {
3963 APSInt ElemI = Src.elem<T>(I).toAPSInt();
3964 APInt ConflictMask(ElemI.getBitWidth(), 0);
3965 for (unsigned J = 0; J != I; ++J) {
3966 APSInt ElemJ = Src.elem<T>(J).toAPSInt();
3967 ConflictMask.setBitVal(J, ElemI == ElemJ);
3968 }
3969 Dst.elem<T>(I) = static_cast<T>(APSInt(ConflictMask, DestUnsigned));
3970 });
3971 }
3973 return true;
3974}
3975
3977 const CallExpr *Call,
3978 unsigned ID) {
3979 assert(Call->getNumArgs() == 1);
3980
3981 const Pointer &Vec = S.Stk.pop<Pointer>();
3982 unsigned RetWidth = S.getASTContext().getIntWidth(Call->getType());
3983 APInt RetMask(RetWidth, 0);
3984
3985 unsigned VectorLen = Vec.getNumElems();
3986 PrimType ElemT = Vec.getFieldDesc()->getPrimType();
3987
3988 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
3989 APSInt A;
3990 INT_TYPE_SWITCH_NO_BOOL(ElemT, { A = Vec.elem<T>(ElemNum).toAPSInt(); });
3991 unsigned MSB = A[A.getBitWidth() - 1];
3992 RetMask.setBitVal(ElemNum, MSB);
3993 }
3994 pushInteger(S, RetMask, Call->getType());
3995 return true;
3996}
3997
3999 const CallExpr *Call,
4000 unsigned ID) {
4001 assert(Call->getNumArgs() == 1);
4002
4003 APSInt Mask;
4004 if (!popToAPSInt(S, Call->getArg(0), Mask))
4005 return false;
4006
4007 const Pointer &Vec = S.Stk.peek<Pointer>();
4008 unsigned NumElems = Vec.getNumElems();
4009 PrimType ElemT = Vec.getFieldDesc()->getPrimType();
4010
4011 for (unsigned I = 0; I != NumElems; ++I) {
4012 bool BitSet = Mask[I];
4013
4015 ElemT, { Vec.elem<T>(I) = BitSet ? T::from(-1) : T::from(0); });
4016 }
4017
4019
4020 return true;
4021}
4022
4024 const CallExpr *Call,
4025 bool HasRoundingMask) {
4026 APSInt Rounding, MaskInt;
4027 Pointer Src, B, A;
4028
4029 if (HasRoundingMask) {
4030 assert(Call->getNumArgs() == 5);
4031 if (!popToAPSInt(S, Call->getArg(4), Rounding))
4032 return false;
4033 if (!popToAPSInt(S, Call->getArg(3), MaskInt))
4034 return false;
4035 Src = S.Stk.pop<Pointer>();
4036 B = S.Stk.pop<Pointer>();
4037 A = S.Stk.pop<Pointer>();
4038 if (!CheckLoad(S, OpPC, A) || !CheckLoad(S, OpPC, B) ||
4039 !CheckLoad(S, OpPC, Src))
4040 return false;
4041 } else {
4042 assert(Call->getNumArgs() == 2);
4043 B = S.Stk.pop<Pointer>();
4044 A = S.Stk.pop<Pointer>();
4045 if (!CheckLoad(S, OpPC, A) || !CheckLoad(S, OpPC, B))
4046 return false;
4047 }
4048
4049 const auto *DstVTy = Call->getType()->castAs<VectorType>();
4050 unsigned NumElems = DstVTy->getNumElements();
4051 const Pointer &Dst = S.Stk.peek<Pointer>();
4052
4053 // Copy all elements except lane 0 (overwritten below) from A to Dst.
4054 for (unsigned I = 1; I != NumElems; ++I)
4055 Dst.elem<Floating>(I) = A.elem<Floating>(I);
4056
4057 // Convert element 0 from double to float, or use Src if masked off.
4058 if (!HasRoundingMask || (MaskInt.getZExtValue() & 0x1)) {
4059 assert(S.getASTContext().FloatTy == DstVTy->getElementType() &&
4060 "cvtsd2ss requires float element type in destination vector");
4061
4062 Floating Conv = S.allocFloat(
4063 S.getASTContext().getFloatTypeSemantics(DstVTy->getElementType()));
4064 APFloat SrcVal = B.elem<Floating>(0).getAPFloat();
4065 if (!convertDoubleToFloatStrict(SrcVal, Conv, S, Call))
4066 return false;
4067 Dst.elem<Floating>(0) = Conv;
4068 } else {
4069 Dst.elem<Floating>(0) = Src.elem<Floating>(0);
4070 }
4071
4073 return true;
4074}
4075
4077 const CallExpr *Call, bool IsMasked,
4078 bool HasRounding) {
4079 APSInt MaskVal;
4080 Pointer PassThrough;
4081 Pointer Src;
4082 APSInt Rounding;
4083
4084 if (IsMasked) {
4085 // Pop in reverse order.
4086 if (HasRounding) {
4087 if (!popToAPSInt(S, Call->getArg(3), Rounding))
4088 return false;
4089 if (!popToAPSInt(S, Call->getArg(2), MaskVal))
4090 return false;
4091 PassThrough = S.Stk.pop<Pointer>();
4092 Src = S.Stk.pop<Pointer>();
4093 } else {
4094 if (!popToAPSInt(S, Call->getArg(2), MaskVal))
4095 return false;
4096 PassThrough = S.Stk.pop<Pointer>();
4097 Src = S.Stk.pop<Pointer>();
4098 }
4099
4100 if (!CheckLoad(S, OpPC, PassThrough))
4101 return false;
4102 } else {
4103 // Pop source only.
4104 Src = S.Stk.pop<Pointer>();
4105 }
4106
4107 if (!CheckLoad(S, OpPC, Src))
4108 return false;
4109
4110 const auto *RetVTy = Call->getType()->castAs<VectorType>();
4111 unsigned RetElems = RetVTy->getNumElements();
4112 unsigned SrcElems = Src.getNumElems();
4113 const Pointer &Dst = S.Stk.peek<Pointer>();
4114
4115 // Initialize destination with passthrough or zeros.
4116 for (unsigned I = 0; I != RetElems; ++I)
4117 if (IsMasked)
4118 Dst.elem<Floating>(I) = PassThrough.elem<Floating>(I);
4119 else
4120 Dst.elem<Floating>(I) = Floating(APFloat(0.0f));
4121
4122 assert(S.getASTContext().FloatTy == RetVTy->getElementType() &&
4123 "cvtpd2ps requires float element type in return vector");
4124
4125 // Convert double to float for enabled elements (only process source elements
4126 // that exist).
4127 for (unsigned I = 0; I != SrcElems; ++I) {
4128 if (IsMasked && !MaskVal[I])
4129 continue;
4130
4131 APFloat SrcVal = Src.elem<Floating>(I).getAPFloat();
4132
4133 Floating Conv = S.allocFloat(
4134 S.getASTContext().getFloatTypeSemantics(RetVTy->getElementType()));
4135 if (!convertDoubleToFloatStrict(SrcVal, Conv, S, Call))
4136 return false;
4137 Dst.elem<Floating>(I) = Conv;
4138 }
4139
4141 return true;
4142}
4143
4145 InterpState &S, CodePtr OpPC, const CallExpr *Call,
4146 llvm::function_ref<std::pair<unsigned, int>(unsigned, const APInt &)>
4147 GetSourceIndex) {
4148
4149 assert(Call->getNumArgs() == 2 || Call->getNumArgs() == 3);
4150
4151 APInt ShuffleMask;
4152 Pointer A, MaskVector, B;
4153 bool IsVectorMask = false;
4154 bool IsSingleOperand = (Call->getNumArgs() == 2);
4155
4156 if (IsSingleOperand) {
4157 QualType MaskType = Call->getArg(1)->getType();
4158 if (MaskType->isVectorType()) {
4159 IsVectorMask = true;
4160 MaskVector = S.Stk.pop<Pointer>();
4161 A = S.Stk.pop<Pointer>();
4162 B = A;
4163 } else if (MaskType->isIntegerType()) {
4164 APSInt MaskVal;
4165 if (!popToAPSInt(S, Call->getArg(1), MaskVal))
4166 return false;
4167 ShuffleMask = MaskVal;
4168 A = S.Stk.pop<Pointer>();
4169 B = A;
4170 } else {
4171 return false;
4172 }
4173 } else {
4174 QualType Arg2Type = Call->getArg(2)->getType();
4175 if (Arg2Type->isVectorType()) {
4176 IsVectorMask = true;
4177 B = S.Stk.pop<Pointer>();
4178 MaskVector = S.Stk.pop<Pointer>();
4179 A = S.Stk.pop<Pointer>();
4180 } else if (Arg2Type->isIntegerType()) {
4181 APSInt MaskVal;
4182 if (!popToAPSInt(S, Call->getArg(2), MaskVal))
4183 return false;
4184 ShuffleMask = MaskVal;
4185 B = S.Stk.pop<Pointer>();
4186 A = S.Stk.pop<Pointer>();
4187 } else {
4188 return false;
4189 }
4190 }
4191
4192 QualType Arg0Type = Call->getArg(0)->getType();
4193 const auto *VecT = Arg0Type->castAs<VectorType>();
4194 PrimType ElemT = *S.getContext().classify(VecT->getElementType());
4195 unsigned NumElems = VecT->getNumElements();
4196
4197 const Pointer &Dst = S.Stk.peek<Pointer>();
4198
4199 PrimType MaskElemT = PT_Uint32;
4200 if (IsVectorMask) {
4201 QualType Arg1Type = Call->getArg(1)->getType();
4202 const auto *MaskVecT = Arg1Type->castAs<VectorType>();
4203 QualType MaskElemType = MaskVecT->getElementType();
4204 MaskElemT = *S.getContext().classify(MaskElemType);
4205 }
4206
4207 for (unsigned DstIdx = 0; DstIdx != NumElems; ++DstIdx) {
4208 if (IsVectorMask) {
4209 INT_TYPE_SWITCH(MaskElemT,
4210 { ShuffleMask = MaskVector.elem<T>(DstIdx).toAPSInt(); });
4211 }
4212
4213 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
4214
4215 if (SrcIdx < 0) {
4216 // Zero out this element
4217 if (ElemT == PT_Float) {
4218 Dst.elem<Floating>(DstIdx) = Floating(
4219 S.getASTContext().getFloatTypeSemantics(VecT->getElementType()));
4220 } else {
4221 INT_TYPE_SWITCH_NO_BOOL(ElemT, { Dst.elem<T>(DstIdx) = T::from(0); });
4222 }
4223 } else {
4224 const Pointer &Src = (SrcVecIdx == 0) ? A : B;
4225 TYPE_SWITCH(ElemT, { Dst.elem<T>(DstIdx) = Src.elem<T>(SrcIdx); });
4226 }
4227 }
4229
4230 return true;
4231}
4232
4234 InterpState &S, CodePtr OpPC, const CallExpr *Call,
4235 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
4236 GetSourceIndex) {
4238 S, OpPC, Call,
4239 [&GetSourceIndex](unsigned DstIdx,
4240 const APInt &Mask) -> std::pair<unsigned, int> {
4241 return GetSourceIndex(DstIdx, Mask.getZExtValue());
4242 });
4243}
4244
4246 InterpState &S, CodePtr OpPC, const CallExpr *Call,
4247 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
4248 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
4249
4250 assert(Call->getNumArgs() == 2);
4251
4252 const Pointer &Count = S.Stk.pop<Pointer>();
4253 const Pointer &Source = S.Stk.pop<Pointer>();
4254
4255 QualType SourceType = Call->getArg(0)->getType();
4256 QualType CountType = Call->getArg(1)->getType();
4257 assert(SourceType->isVectorType() && CountType->isVectorType());
4258
4259 const auto *SourceVecT = SourceType->castAs<VectorType>();
4260 const auto *CountVecT = CountType->castAs<VectorType>();
4261 PrimType SourceElemT = *S.getContext().classify(SourceVecT->getElementType());
4262 PrimType CountElemT = *S.getContext().classify(CountVecT->getElementType());
4263
4264 const Pointer &Dst = S.Stk.peek<Pointer>();
4265
4266 unsigned DestEltWidth =
4267 S.getASTContext().getTypeSize(SourceVecT->getElementType());
4268 bool IsDestUnsigned = SourceVecT->getElementType()->isUnsignedIntegerType();
4269 unsigned DestLen = SourceVecT->getNumElements();
4270 unsigned CountEltWidth =
4271 S.getASTContext().getTypeSize(CountVecT->getElementType());
4272 unsigned NumBitsInQWord = 64;
4273 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
4274
4275 uint64_t CountLQWord = 0;
4276 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
4277 uint64_t Elt = 0;
4278 INT_TYPE_SWITCH(CountElemT,
4279 { Elt = static_cast<uint64_t>(Count.elem<T>(EltIdx)); });
4280 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
4281 }
4282
4283 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
4284 APSInt Elt;
4285 INT_TYPE_SWITCH(SourceElemT, { Elt = Source.elem<T>(EltIdx).toAPSInt(); });
4286
4287 APInt Result;
4288 if (CountLQWord < DestEltWidth) {
4289 Result = ShiftOp(Elt, CountLQWord);
4290 } else {
4291 Result = OverflowOp(Elt, DestEltWidth);
4292 }
4293 if (IsDestUnsigned) {
4294 INT_TYPE_SWITCH(SourceElemT, {
4295 Dst.elem<T>(EltIdx) = T::from(Result.getZExtValue());
4296 });
4297 } else {
4298 INT_TYPE_SWITCH(SourceElemT, {
4299 Dst.elem<T>(EltIdx) = T::from(Result.getSExtValue());
4300 });
4301 }
4302 }
4303
4305 return true;
4306}
4307
4309 const CallExpr *Call) {
4310
4311 assert(Call->getNumArgs() == 3);
4312
4313 QualType SourceType = Call->getArg(0)->getType();
4314 QualType ShuffleMaskType = Call->getArg(1)->getType();
4315 QualType ZeroMaskType = Call->getArg(2)->getType();
4316 if (!SourceType->isVectorType() || !ShuffleMaskType->isVectorType() ||
4317 !ZeroMaskType->isIntegerType()) {
4318 return false;
4319 }
4320
4321 Pointer Source, ShuffleMask;
4322 APSInt ZeroMask;
4323 if (!popToAPSInt(S, Call->getArg(2), ZeroMask))
4324 return false;
4325 ShuffleMask = S.Stk.pop<Pointer>();
4326 Source = S.Stk.pop<Pointer>();
4327
4328 const auto *SourceVecT = SourceType->castAs<VectorType>();
4329 const auto *ShuffleMaskVecT = ShuffleMaskType->castAs<VectorType>();
4330 assert(SourceVecT->getNumElements() == ShuffleMaskVecT->getNumElements());
4331 assert(ZeroMask.getBitWidth() == SourceVecT->getNumElements());
4332
4333 PrimType SourceElemT = *S.getContext().classify(SourceVecT->getElementType());
4334 PrimType ShuffleMaskElemT =
4335 *S.getContext().classify(ShuffleMaskVecT->getElementType());
4336
4337 unsigned NumBytesInQWord = 8;
4338 unsigned NumBitsInByte = 8;
4339 unsigned NumBytes = SourceVecT->getNumElements();
4340 unsigned NumQWords = NumBytes / NumBytesInQWord;
4341 unsigned RetWidth = ZeroMask.getBitWidth();
4342 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
4343
4344 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
4345 APInt SourceQWord(64, 0);
4346 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
4347 uint64_t Byte = 0;
4348 INT_TYPE_SWITCH(SourceElemT, {
4349 Byte = static_cast<uint64_t>(
4350 Source.elem<T>(QWordId * NumBytesInQWord + ByteIdx));
4351 });
4352 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
4353 }
4354
4355 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
4356 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
4357 unsigned M = 0;
4358 INT_TYPE_SWITCH(ShuffleMaskElemT, {
4359 M = static_cast<unsigned>(ShuffleMask.elem<T>(SelIdx)) & 0x3F;
4360 });
4361
4362 if (ZeroMask[SelIdx]) {
4363 RetMask.setBitVal(SelIdx, SourceQWord[M]);
4364 }
4365 }
4366 }
4367
4368 pushInteger(S, RetMask, Call->getType());
4369 return true;
4370}
4371
4373 const CallExpr *Call) {
4374 // Arguments are: vector of floats, rounding immediate
4375 assert(Call->getNumArgs() == 2);
4376
4377 APSInt Imm;
4378 if (!popToAPSInt(S, Call->getArg(1), Imm))
4379 return false;
4380 const Pointer &Src = S.Stk.pop<Pointer>();
4381 const Pointer &Dst = S.Stk.peek<Pointer>();
4382
4383 assert(Src.getFieldDesc()->isPrimitiveArray());
4384 assert(Dst.getFieldDesc()->isPrimitiveArray());
4385
4386 const auto *SrcVTy = Call->getArg(0)->getType()->castAs<VectorType>();
4387 unsigned SrcNumElems = SrcVTy->getNumElements();
4388 const auto *DstVTy = Call->getType()->castAs<VectorType>();
4389 unsigned DstNumElems = DstVTy->getNumElements();
4390
4391 const llvm::fltSemantics &HalfSem =
4393
4394 // imm[2] == 1 means use MXCSR rounding mode.
4395 // In that case, we can only evaluate if the conversion is exact.
4396 int ImmVal = Imm.getZExtValue();
4397 bool UseMXCSR = (ImmVal & 4) != 0;
4398 bool IsFPConstrained =
4399 Call->getFPFeaturesInEffect(S.getASTContext().getLangOpts())
4400 .isFPConstrained();
4401
4402 llvm::RoundingMode RM;
4403 if (!UseMXCSR) {
4404 switch (ImmVal & 3) {
4405 case 0:
4406 RM = llvm::RoundingMode::NearestTiesToEven;
4407 break;
4408 case 1:
4409 RM = llvm::RoundingMode::TowardNegative;
4410 break;
4411 case 2:
4412 RM = llvm::RoundingMode::TowardPositive;
4413 break;
4414 case 3:
4415 RM = llvm::RoundingMode::TowardZero;
4416 break;
4417 default:
4418 llvm_unreachable("Invalid immediate rounding mode");
4419 }
4420 } else {
4421 // For MXCSR, we must check for exactness. We can use any rounding mode
4422 // for the trial conversion since the result is the same if it's exact.
4423 RM = llvm::RoundingMode::NearestTiesToEven;
4424 }
4425
4426 QualType DstElemQT = Dst.getFieldDesc()->getElemQualType();
4427 PrimType DstElemT = *S.getContext().classify(DstElemQT);
4428
4429 for (unsigned I = 0; I != SrcNumElems; ++I) {
4430 Floating SrcVal = Src.elem<Floating>(I);
4431 APFloat DstVal = SrcVal.getAPFloat();
4432
4433 bool LostInfo;
4434 APFloat::opStatus St = DstVal.convert(HalfSem, RM, &LostInfo);
4435
4436 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
4437 S.FFDiag(S.Current->getSource(OpPC),
4438 diag::note_constexpr_dynamic_rounding);
4439 return false;
4440 }
4441
4442 INT_TYPE_SWITCH_NO_BOOL(DstElemT, {
4443 // Convert the destination value's bit pattern to an unsigned integer,
4444 // then reconstruct the element using the target type's 'from' method.
4445 uint64_t RawBits = DstVal.bitcastToAPInt().getZExtValue();
4446 Dst.elem<T>(I) = T::from(RawBits);
4447 });
4448 }
4449
4450 // Zero out remaining elements if the destination has more elements
4451 // (e.g., vcvtps2ph converting 4 floats to 8 shorts).
4452 if (DstNumElems > SrcNumElems) {
4453 for (unsigned I = SrcNumElems; I != DstNumElems; ++I) {
4454 INT_TYPE_SWITCH_NO_BOOL(DstElemT, { Dst.elem<T>(I) = T::from(0); });
4455 }
4456 }
4457
4458 Dst.initializeAllElements();
4459 return true;
4460}
4461
4463 const CallExpr *Call) {
4464 assert(Call->getNumArgs() == 2);
4465
4466 QualType ATy = Call->getArg(0)->getType();
4467 QualType BTy = Call->getArg(1)->getType();
4468 if (!ATy->isVectorType() || !BTy->isVectorType()) {
4469 return false;
4470 }
4471
4472 const Pointer &BPtr = S.Stk.pop<Pointer>();
4473 const Pointer &APtr = S.Stk.pop<Pointer>();
4474 const auto *AVecT = ATy->castAs<VectorType>();
4475 assert(AVecT->getNumElements() ==
4476 BTy->castAs<VectorType>()->getNumElements());
4477
4478 PrimType ElemT = *S.getContext().classify(AVecT->getElementType());
4479
4480 unsigned NumBytesInQWord = 8;
4481 unsigned NumBitsInByte = 8;
4482 unsigned NumBytes = AVecT->getNumElements();
4483 unsigned NumQWords = NumBytes / NumBytesInQWord;
4484 const Pointer &Dst = S.Stk.peek<Pointer>();
4485
4486 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
4487 APInt BQWord(64, 0);
4488 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
4489 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
4490 INT_TYPE_SWITCH(ElemT, {
4491 uint64_t Byte = static_cast<uint64_t>(BPtr.elem<T>(Idx));
4492 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
4493 });
4494 }
4495
4496 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
4497 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
4498 uint64_t Ctrl = 0;
4500 ElemT, { Ctrl = static_cast<uint64_t>(APtr.elem<T>(Idx)) & 0x3F; });
4501
4502 APInt Byte(8, 0);
4503 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
4504 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
4505 }
4506 INT_TYPE_SWITCH(ElemT,
4507 { Dst.elem<T>(Idx) = T::from(Byte.getZExtValue()); });
4508 }
4509 }
4510
4512
4513 return true;
4514}
4515
4517 const CallExpr *Call,
4518 bool Inverse) {
4519 assert(Call->getNumArgs() == 3);
4520 QualType XType = Call->getArg(0)->getType();
4521 QualType AType = Call->getArg(1)->getType();
4522 QualType ImmType = Call->getArg(2)->getType();
4523 if (!XType->isVectorType() || !AType->isVectorType() ||
4524 !ImmType->isIntegerType()) {
4525 return false;
4526 }
4527
4528 Pointer X, A;
4529 APSInt Imm;
4530 if (!popToAPSInt(S, Call->getArg(2), Imm))
4531 return false;
4532 A = S.Stk.pop<Pointer>();
4533 X = S.Stk.pop<Pointer>();
4534
4535 const Pointer &Dst = S.Stk.peek<Pointer>();
4536 const auto *AVecT = AType->castAs<VectorType>();
4537 assert(XType->castAs<VectorType>()->getNumElements() ==
4538 AVecT->getNumElements());
4539 unsigned NumBytesInQWord = 8;
4540 unsigned NumBytes = AVecT->getNumElements();
4541 unsigned NumBitsInQWord = 64;
4542 unsigned NumQWords = NumBytes / NumBytesInQWord;
4543 unsigned NumBitsInByte = 8;
4544 PrimType AElemT = *S.getContext().classify(AVecT->getElementType());
4545
4546 // computing A*X + Imm
4547 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
4548 // Extract the QWords from X, A
4549 APInt XQWord(NumBitsInQWord, 0);
4550 APInt AQWord(NumBitsInQWord, 0);
4551 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
4552 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
4553 uint8_t XByte;
4554 uint8_t AByte;
4555 INT_TYPE_SWITCH(AElemT, {
4556 XByte = static_cast<uint8_t>(X.elem<T>(Idx));
4557 AByte = static_cast<uint8_t>(A.elem<T>(Idx));
4558 });
4559
4560 XQWord.insertBits(APInt(NumBitsInByte, XByte), ByteIdx * NumBitsInByte);
4561 AQWord.insertBits(APInt(NumBitsInByte, AByte), ByteIdx * NumBitsInByte);
4562 }
4563
4564 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
4565 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
4566 uint8_t XByte =
4567 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
4568 INT_TYPE_SWITCH(AElemT, {
4569 Dst.elem<T>(Idx) = T::from(GFNIAffine(XByte, AQWord, Imm, Inverse));
4570 });
4571 }
4572 }
4573 Dst.initializeAllElements();
4574 return true;
4575}
4576
4578 const CallExpr *Call) {
4579 assert(Call->getNumArgs() == 2);
4580
4581 QualType AType = Call->getArg(0)->getType();
4582 QualType BType = Call->getArg(1)->getType();
4583 if (!AType->isVectorType() || !BType->isVectorType()) {
4584 return false;
4585 }
4586
4587 Pointer A, B;
4588 B = S.Stk.pop<Pointer>();
4589 A = S.Stk.pop<Pointer>();
4590
4591 const Pointer &Dst = S.Stk.peek<Pointer>();
4592 const auto *AVecT = AType->castAs<VectorType>();
4593 assert(AVecT->getNumElements() ==
4594 BType->castAs<VectorType>()->getNumElements());
4595
4596 PrimType AElemT = *S.getContext().classify(AVecT->getElementType());
4597 unsigned NumBytes = A.getNumElems();
4598
4599 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
4600 uint8_t AByte, BByte;
4601 INT_TYPE_SWITCH(AElemT, {
4602 AByte = static_cast<uint8_t>(A.elem<T>(ByteIdx));
4603 BByte = static_cast<uint8_t>(B.elem<T>(ByteIdx));
4604 Dst.elem<T>(ByteIdx) = T::from(GFNIMul(AByte, BByte));
4605 });
4606 }
4607
4608 Dst.initializeAllElements();
4609 return true;
4610}
4611
4613 const CallExpr *Call, bool IsSaturating) {
4614 assert(Call->getNumArgs() == 3);
4615
4616 QualType SrcT = Call->getArg(0)->getType();
4617 QualType OpAT = Call->getArg(1)->getType();
4618 QualType OpBT = Call->getArg(2)->getType();
4619 QualType DstT = Call->getType();
4620 if (!SrcT->isVectorType() || !OpAT->isVectorType() || !OpBT->isVectorType() ||
4621 !DstT->isVectorType())
4622 return false;
4623
4624 const auto *SrcVecT = SrcT->castAs<VectorType>();
4625 const auto *OpAVecT = OpAT->castAs<VectorType>();
4626 const auto *OpBVecT = OpBT->castAs<VectorType>();
4627 const auto *DstVecT = DstT->castAs<VectorType>();
4628
4629 assert(OpAVecT->getNumElements() == OpBVecT->getNumElements());
4630
4631 unsigned NumSrcElems = SrcVecT->getNumElements();
4632 unsigned NumOperandElems = OpAVecT->getNumElements();
4633 unsigned ElemsPerLane = NumOperandElems / NumSrcElems;
4634
4635 PrimType SrcElemT = *S.getContext().classify(SrcVecT->getElementType());
4636 PrimType OpAElemT = *S.getContext().classify(OpAVecT->getElementType());
4637 PrimType OpBElemT = *S.getContext().classify(OpBVecT->getElementType());
4638 PrimType DstElemT = *S.getContext().classify(DstVecT->getElementType());
4639
4640 assert(SrcElemT == DstElemT);
4641
4642 const Pointer &OpBPtr = S.Stk.pop<Pointer>();
4643 const Pointer &OpAPtr = S.Stk.pop<Pointer>();
4644 const Pointer &SrcPtr = S.Stk.pop<Pointer>();
4645 const Pointer &Dst = S.Stk.peek<Pointer>();
4646
4647 for (unsigned I = 0; I != NumSrcElems; ++I) {
4648 APSInt Acc;
4649 INT_TYPE_SWITCH_NO_BOOL(SrcElemT, { Acc = SrcPtr.elem<T>(I).toAPSInt(); });
4650 Acc = Acc.sext(64);
4651 for (unsigned J = 0; J != ElemsPerLane; ++J) {
4652 APSInt OpA, OpB;
4654 OpAElemT, { OpA = OpAPtr.elem<T>(ElemsPerLane * I + J).toAPSInt(); });
4656 OpBElemT, { OpB = OpBPtr.elem<T>(ElemsPerLane * I + J).toAPSInt(); });
4657 OpA = APSInt(OpA.extend(64), false);
4658 OpB = APSInt(OpB.extend(64), false);
4659 Acc += OpA * OpB;
4660 }
4661 if (IsSaturating)
4662 Acc = APSInt(Acc.truncSSat(32), false);
4663 else
4664 Acc = APSInt(Acc.trunc(32), false);
4665 INT_TYPE_SWITCH_NO_BOOL(DstElemT,
4666 { Dst.elem<T>(I) = static_cast<T>(Acc); });
4667 }
4669 return true;
4670}
4671
4672// Bit Matrix Multiply and Accumulate (AVX512BMM). Each 256-bit lane holds a
4673// 16x16 bit matrix as 16 x i16 elements; element i is row i and bit j of that
4674// element is entry [i][j]. The accumulator (third argument, src1 in the AMD
4675// ISA) provides the initial value of each result bit, into which the bit-matrix
4676// product of the first two arguments (src2 * src3) is reduced with OR (vbmacor)
4677// or XOR (vbmacxor):
4678// for i in 0..15, j in 0..15:
4679// bit = C[16*i+j]
4680// for k in 0..15: bit OP= A[16*i+k] & B[16*k+j]
4681// dest[16*i+j] = bit
4683 const CallExpr *Call, bool IsXor) {
4684 assert(Call->getNumArgs() == 3);
4685
4686 // AST-based type checks before popping the stack.
4687 QualType AType = Call->getArg(0)->getType();
4688 QualType BType = Call->getArg(1)->getType();
4689 QualType CType = Call->getArg(2)->getType();
4690 if (!AType->isVectorType() || !BType->isVectorType() ||
4691 !CType->isVectorType())
4692 return false;
4693
4694 const Pointer &C = S.Stk.pop<Pointer>();
4695 const Pointer &B = S.Stk.pop<Pointer>();
4696 const Pointer &A = S.Stk.pop<Pointer>();
4697 const Pointer &Dst = S.Stk.peek<Pointer>();
4698
4699 // check if all three primitive arrays are with 16-bit elements.
4700 auto isValid16BitArray = [](const Pointer &P) {
4701 const Descriptor *D = P.getFieldDesc();
4702 if (!D->isPrimitiveArray())
4703 return false;
4704 PrimType PT = D->getPrimType();
4705 return ((PT == PT_Sint16) || (PT == PT_Uint16));
4706 };
4707
4708 if (!isValid16BitArray(A) || !isValid16BitArray(B) || !isValid16BitArray(C))
4709 return false;
4710
4711 PrimType ElemT = A.getFieldDesc()->getPrimType();
4712 unsigned NumElems = A.getNumElems();
4713 assert(NumElems % 16 == 0 && "BMM operates on 256-bit lanes of 16 x i16");
4714 bool DstUnsigned = ElemT == PT_Uint16;
4715
4716 // Lanes are always 16-bit; gather them so the reduction below is untyped.
4717 SmallVector<uint16_t> AVals(NumElems), BVals(NumElems), Acc(NumElems);
4719 for (unsigned I = 0; I != NumElems; ++I) {
4720 AVals[I] = (uint16_t)A.elem<T>(I).toAPSInt().getZExtValue();
4721 BVals[I] = (uint16_t)B.elem<T>(I).toAPSInt().getZExtValue();
4722 Acc[I] = (uint16_t)C.elem<T>(I).toAPSInt().getZExtValue();
4723 }
4724 });
4725
4726 for (unsigned Lane = 0; Lane != NumElems; Lane += 16) {
4727 for (unsigned I = 0; I != 16; ++I) {
4728 uint16_t AVal = AVals[Lane + I], DVal = Acc[Lane + I];
4729 for (unsigned J = 0; J != 16; ++J) {
4730 // Seed the reduction with the accumulator bit, then fold in each
4731 // product term with the same operator (OR for vbmacor, XOR for
4732 // vbmacxor).
4733 unsigned Bit = (DVal >> J) & 1u;
4734 for (unsigned K = 0; K != 16; ++K) {
4735 unsigned Product = ((AVal >> K) & 1u) & ((BVals[Lane + K] >> J) & 1u);
4736 Bit = IsXor ? (Bit ^ Product) : (Bit | Product);
4737 }
4738 DVal = (DVal & ~(uint16_t(1) << J)) | (uint16_t(Bit) << J);
4739 }
4740 Acc[Lane + I] = DVal;
4741 }
4742 }
4743
4745 for (unsigned I = 0; I != NumElems; ++I)
4746 Dst.elem<T>(I) = static_cast<T>(APSInt(APInt(16, Acc[I]), DstUnsigned));
4747 });
4748 Dst.initializeAllElements();
4749 return true;
4750}
4751
4753 const CallExpr *E) {
4754 Pointer SrcVecPtr = S.Stk.pop<Pointer>();
4755 const Floating &FloatElem = SrcVecPtr.elem<Floating>(0);
4756
4757 unsigned BitWidth = S.getASTContext().getIntWidth(E->getType());
4758 bool IsUnsigned = E->getType()->isUnsignedIntegerType();
4759
4760 llvm::APSInt IntResult(BitWidth, IsUnsigned);
4761 bool IsExact = false;
4762 // We only allow exact conversions so rounding mode does not matter for cvt*
4763 // and cvtt* builtins
4764 FloatElem.getAPFloat().convertToInteger(
4765 IntResult, llvm::APFloat::rmTowardZero, &IsExact);
4766 if (!IsExact)
4767 return false;
4768
4769 pushInteger(S, IntResult, E->getType());
4770 return true;
4771}
4772
4774 const CallExpr *E) {
4775 Pointer SrcVecPtr = S.Stk.pop<Pointer>();
4776 const Pointer &Dst = S.Stk.peek<Pointer>();
4777
4778 unsigned NumSrcElems = SrcVecPtr.getNumElems();
4779 unsigned NumDstElems = Dst.getNumElems();
4780
4781 if (NumSrcElems > NumDstElems)
4782 return false;
4783
4784 QualType ElemType = Dst.getFieldDesc()->getElemQualType();
4785 unsigned BitWidth = S.getASTContext().getIntWidth(ElemType);
4786 bool IsUnsigned = ElemType->isUnsignedIntegerType();
4787
4788 PrimType ElemT = *S.getContext().classify(ElemType);
4789 for (unsigned I = 0; I != NumSrcElems; ++I) {
4790 const Floating &FloatElem = SrcVecPtr.elem<Floating>(I);
4791 llvm::APSInt IntResult(BitWidth, IsUnsigned);
4792
4793 bool IsExact = false;
4794 // We only allow exact conversions so rounding mode does not matter for
4795 // cvt* and cvtt* builtins
4796 FloatElem.getAPFloat().convertToInteger(
4797 IntResult, llvm::APFloat::rmTowardZero, &IsExact);
4798 if (!IsExact)
4799 return false;
4801 ElemT, { Dst.elem<T>(I) = T::from(IntResult.getZExtValue()); });
4802 }
4803
4804 // Zero out remaining elements if the destination has more elements
4805 // (e.g., cvtpd2dq converting 2 doubles(_m128d) to 2 ints stored in _m128i).
4806 for (unsigned I = NumSrcElems; I != NumDstElems; ++I)
4807 INT_TYPE_SWITCH_NO_BOOL(ElemT, { Dst.elem<T>(I) = T::from(0); });
4808
4809 Dst.initializeAllElements();
4810 return true;
4811}
4812
4814 const CallExpr *) {
4815 const Reflect &R = S.Stk.pop<Reflect>();
4817 return true;
4818}
4819
4821 uint32_t BuiltinID) {
4822 const InterpFrame *Frame = S.Current;
4823 switch (BuiltinID) {
4824 case Builtin::BI__builtin_is_constant_evaluated:
4826
4827 case Builtin::BI__builtin_assume:
4828 case Builtin::BI__assume:
4829 return interp__builtin_assume(S, OpPC, Frame, Call);
4830
4831 case Builtin::BI__builtin_strcmp:
4832 case Builtin::BIstrcmp:
4833 case Builtin::BI__builtin_strncmp:
4834 case Builtin::BIstrncmp:
4835 case Builtin::BI__builtin_wcsncmp:
4836 case Builtin::BIwcsncmp:
4837 case Builtin::BI__builtin_wcscmp:
4838 case Builtin::BIwcscmp:
4839 return interp__builtin_strcmp(S, OpPC, Frame, Call, BuiltinID);
4840
4841 case Builtin::BI__builtin_strlen:
4842 case Builtin::BIstrlen:
4843 case Builtin::BI__builtin_wcslen:
4844 case Builtin::BIwcslen:
4845 return interp__builtin_strlen(S, OpPC, Frame, Call, BuiltinID);
4846
4847 case Builtin::BI__builtin_nan:
4848 case Builtin::BI__builtin_nanf:
4849 case Builtin::BI__builtin_nanl:
4850 case Builtin::BI__builtin_nanf16:
4851 case Builtin::BI__builtin_nanf128:
4852 return interp__builtin_nan(S, OpPC, Frame, Call, /*Signaling=*/false);
4853
4854 case Builtin::BI__builtin_nans:
4855 case Builtin::BI__builtin_nansf:
4856 case Builtin::BI__builtin_nansl:
4857 case Builtin::BI__builtin_nansf16:
4858 case Builtin::BI__builtin_nansf128:
4859 return interp__builtin_nan(S, OpPC, Frame, Call, /*Signaling=*/true);
4860
4861 case Builtin::BI__builtin_huge_val:
4862 case Builtin::BI__builtin_huge_valf:
4863 case Builtin::BI__builtin_huge_vall:
4864 case Builtin::BI__builtin_huge_valf16:
4865 case Builtin::BI__builtin_huge_valf128:
4866 case Builtin::BI__builtin_inf:
4867 case Builtin::BI__builtin_inff:
4868 case Builtin::BI__builtin_infl:
4869 case Builtin::BI__builtin_inff16:
4870 case Builtin::BI__builtin_inff128:
4871 return interp__builtin_inf(S, OpPC, Frame, Call);
4872
4873 case Builtin::BI__builtin_copysign:
4874 case Builtin::BI__builtin_copysignf:
4875 case Builtin::BI__builtin_copysignl:
4876 case Builtin::BI__builtin_copysignf128:
4877 return interp__builtin_copysign(S, OpPC, Frame);
4878
4879 case Builtin::BI__builtin_fmin:
4880 case Builtin::BI__builtin_fminf:
4881 case Builtin::BI__builtin_fminl:
4882 case Builtin::BI__builtin_fminf16:
4883 case Builtin::BI__builtin_fminf128:
4884 return interp__builtin_fmin(S, OpPC, Frame, /*IsNumBuiltin=*/false);
4885
4886 case Builtin::BI__builtin_fminimum_num:
4887 case Builtin::BI__builtin_fminimum_numf:
4888 case Builtin::BI__builtin_fminimum_numl:
4889 case Builtin::BI__builtin_fminimum_numf16:
4890 case Builtin::BI__builtin_fminimum_numf128:
4891 return interp__builtin_fmin(S, OpPC, Frame, /*IsNumBuiltin=*/true);
4892
4893 case Builtin::BI__builtin_fmax:
4894 case Builtin::BI__builtin_fmaxf:
4895 case Builtin::BI__builtin_fmaxl:
4896 case Builtin::BI__builtin_fmaxf16:
4897 case Builtin::BI__builtin_fmaxf128:
4898 return interp__builtin_fmax(S, OpPC, Frame, /*IsNumBuiltin=*/false);
4899
4900 case Builtin::BI__builtin_fmaximum_num:
4901 case Builtin::BI__builtin_fmaximum_numf:
4902 case Builtin::BI__builtin_fmaximum_numl:
4903 case Builtin::BI__builtin_fmaximum_numf16:
4904 case Builtin::BI__builtin_fmaximum_numf128:
4905 return interp__builtin_fmax(S, OpPC, Frame, /*IsNumBuiltin=*/true);
4906
4907 case Builtin::BI__builtin_isnan:
4908 return interp__builtin_isnan(S, OpPC, Frame, Call);
4909
4910 case Builtin::BI__builtin_issignaling:
4911 return interp__builtin_issignaling(S, OpPC, Frame, Call);
4912
4913 case Builtin::BI__builtin_isinf:
4914 return interp__builtin_isinf(S, OpPC, Frame, /*Sign=*/false, Call);
4915
4916 case Builtin::BI__builtin_isinf_sign:
4917 return interp__builtin_isinf(S, OpPC, Frame, /*Sign=*/true, Call);
4918
4919 case Builtin::BI__builtin_isfinite:
4920 return interp__builtin_isfinite(S, OpPC, Frame, Call);
4921
4922 case Builtin::BI__builtin_isnormal:
4923 return interp__builtin_isnormal(S, OpPC, Frame, Call);
4924
4925 case Builtin::BI__builtin_issubnormal:
4926 return interp__builtin_issubnormal(S, OpPC, Frame, Call);
4927
4928 case Builtin::BI__builtin_iszero:
4929 return interp__builtin_iszero(S, OpPC, Frame, Call);
4930
4931 case Builtin::BI__builtin_signbit:
4932 case Builtin::BI__builtin_signbitf:
4933 case Builtin::BI__builtin_signbitl:
4934 return interp__builtin_signbit(S, OpPC, Frame, Call);
4935
4936 case Builtin::BI__builtin_isgreater:
4937 case Builtin::BI__builtin_isgreaterequal:
4938 case Builtin::BI__builtin_isless:
4939 case Builtin::BI__builtin_islessequal:
4940 case Builtin::BI__builtin_islessgreater:
4941 case Builtin::BI__builtin_isunordered:
4942 case Builtin::BI__builtin_iseqsig:
4943 return interp_floating_comparison(S, OpPC, Call, BuiltinID);
4944
4945 case Builtin::BI__builtin_isfpclass:
4946 return interp__builtin_isfpclass(S, OpPC, Frame, Call);
4947
4948 case Builtin::BI__builtin_fpclassify:
4949 return interp__builtin_fpclassify(S, OpPC, Frame, Call);
4950
4951 case Builtin::BI__builtin_fabs:
4952 case Builtin::BI__builtin_fabsf:
4953 case Builtin::BI__builtin_fabsl:
4954 case Builtin::BI__builtin_fabsf128:
4955 return interp__builtin_fabs(S, OpPC, Frame);
4956
4957 case Builtin::BI__builtin_abs:
4958 case Builtin::BI__builtin_labs:
4959 case Builtin::BI__builtin_llabs:
4960 return interp__builtin_abs(S, OpPC, Frame, Call);
4961
4962 case Builtin::BI__builtin_popcount:
4963 case Builtin::BI__builtin_popcountl:
4964 case Builtin::BI__builtin_popcountll:
4965 case Builtin::BI__builtin_popcountg:
4966 case Builtin::BI__popcnt16: // Microsoft variants of popcount
4967 case Builtin::BI__popcnt:
4968 case Builtin::BI__popcnt64:
4969 return interp__builtin_popcount(S, OpPC, Frame, Call);
4970
4971 case Builtin::BI__builtin_parity:
4972 case Builtin::BI__builtin_parityl:
4973 case Builtin::BI__builtin_parityll:
4975 S, OpPC, Call, [](const APSInt &Val) {
4976 return APInt(Val.getBitWidth(), Val.popcount() % 2);
4977 });
4978 case Builtin::BI__builtin_clrsb:
4979 case Builtin::BI__builtin_clrsbl:
4980 case Builtin::BI__builtin_clrsbll:
4982 S, OpPC, Call, [](const APSInt &Val) {
4983 return APInt(Val.getBitWidth(),
4984 Val.getBitWidth() - Val.getSignificantBits());
4985 });
4986 case Builtin::BI__builtin_bitreverseg:
4987 case Builtin::BI__builtin_bitreverse8:
4988 case Builtin::BI__builtin_bitreverse16:
4989 case Builtin::BI__builtin_bitreverse32:
4990 case Builtin::BI__builtin_bitreverse64:
4992 S, OpPC, Call, [](const APSInt &Val) { return Val.reverseBits(); });
4993
4994 case Builtin::BI__builtin_classify_type:
4995 return interp__builtin_classify_type(S, OpPC, Frame, Call);
4996
4997 case Builtin::BI__builtin_expect:
4998 case Builtin::BI__builtin_expect_with_probability:
4999 return interp__builtin_expect(S, OpPC, Frame, Call);
5000
5001 case Builtin::BI__builtin_rotateleft8:
5002 case Builtin::BI__builtin_rotateleft16:
5003 case Builtin::BI__builtin_rotateleft32:
5004 case Builtin::BI__builtin_rotateleft64:
5005 case Builtin::BI__builtin_stdc_rotate_left:
5006 case Builtin::BIstdc_rotate_left_uc:
5007 case Builtin::BIstdc_rotate_left_us:
5008 case Builtin::BIstdc_rotate_left_ui:
5009 case Builtin::BIstdc_rotate_left_ul:
5010 case Builtin::BIstdc_rotate_left_ull:
5011 case Builtin::BI_rotl8: // Microsoft variants of rotate left
5012 case Builtin::BI_rotl16:
5013 case Builtin::BI_rotl:
5014 case Builtin::BI_lrotl:
5015 case Builtin::BI_rotl64:
5016 case Builtin::BI__builtin_rotateright8:
5017 case Builtin::BI__builtin_rotateright16:
5018 case Builtin::BI__builtin_rotateright32:
5019 case Builtin::BI__builtin_rotateright64:
5020 case Builtin::BI__builtin_stdc_rotate_right:
5021 case Builtin::BIstdc_rotate_right_uc:
5022 case Builtin::BIstdc_rotate_right_us:
5023 case Builtin::BIstdc_rotate_right_ui:
5024 case Builtin::BIstdc_rotate_right_ul:
5025 case Builtin::BIstdc_rotate_right_ull:
5026 case Builtin::BI_rotr8: // Microsoft variants of rotate right
5027 case Builtin::BI_rotr16:
5028 case Builtin::BI_rotr:
5029 case Builtin::BI_lrotr:
5030 case Builtin::BI_rotr64: {
5031 // Determine if this is a rotate right operation
5032 bool IsRotateRight;
5033 switch (BuiltinID) {
5034 case Builtin::BI__builtin_rotateright8:
5035 case Builtin::BI__builtin_rotateright16:
5036 case Builtin::BI__builtin_rotateright32:
5037 case Builtin::BI__builtin_rotateright64:
5038 case Builtin::BI__builtin_stdc_rotate_right:
5039 case Builtin::BIstdc_rotate_right_uc:
5040 case Builtin::BIstdc_rotate_right_us:
5041 case Builtin::BIstdc_rotate_right_ui:
5042 case Builtin::BIstdc_rotate_right_ul:
5043 case Builtin::BIstdc_rotate_right_ull:
5044 case Builtin::BI_rotr8:
5045 case Builtin::BI_rotr16:
5046 case Builtin::BI_rotr:
5047 case Builtin::BI_lrotr:
5048 case Builtin::BI_rotr64:
5049 IsRotateRight = true;
5050 break;
5051 default:
5052 IsRotateRight = false;
5053 break;
5054 }
5055
5057 S, OpPC, Call, [IsRotateRight](const APSInt &Value, APSInt Amount) {
5058 Amount = NormalizeRotateAmount(Value, Amount);
5059 return IsRotateRight ? Value.rotr(Amount.getZExtValue())
5060 : Value.rotl(Amount.getZExtValue());
5061 });
5062 }
5063
5064 case Builtin::BIstdc_leading_zeros_uc:
5065 case Builtin::BIstdc_leading_zeros_us:
5066 case Builtin::BIstdc_leading_zeros_ui:
5067 case Builtin::BIstdc_leading_zeros_ul:
5068 case Builtin::BIstdc_leading_zeros_ull:
5069 case Builtin::BI__builtin_stdc_leading_zeros: {
5070 unsigned ResWidth = S.getASTContext().getIntWidth(Call->getType());
5072 S, OpPC, Call, [ResWidth](const APSInt &Val) {
5073 return APInt(ResWidth, Val.countl_zero());
5074 });
5075 }
5076
5077 case Builtin::BIstdc_leading_ones_uc:
5078 case Builtin::BIstdc_leading_ones_us:
5079 case Builtin::BIstdc_leading_ones_ui:
5080 case Builtin::BIstdc_leading_ones_ul:
5081 case Builtin::BIstdc_leading_ones_ull:
5082 case Builtin::BI__builtin_stdc_leading_ones: {
5083 unsigned ResWidth = S.getASTContext().getIntWidth(Call->getType());
5085 S, OpPC, Call, [ResWidth](const APSInt &Val) {
5086 return APInt(ResWidth, Val.countl_one());
5087 });
5088 }
5089
5090 case Builtin::BIstdc_trailing_zeros_uc:
5091 case Builtin::BIstdc_trailing_zeros_us:
5092 case Builtin::BIstdc_trailing_zeros_ui:
5093 case Builtin::BIstdc_trailing_zeros_ul:
5094 case Builtin::BIstdc_trailing_zeros_ull:
5095 case Builtin::BI__builtin_stdc_trailing_zeros: {
5096 unsigned ResWidth = S.getASTContext().getIntWidth(Call->getType());
5098 S, OpPC, Call, [ResWidth](const APSInt &Val) {
5099 return APInt(ResWidth, Val.countr_zero());
5100 });
5101 }
5102
5103 case Builtin::BIstdc_trailing_ones_uc:
5104 case Builtin::BIstdc_trailing_ones_us:
5105 case Builtin::BIstdc_trailing_ones_ui:
5106 case Builtin::BIstdc_trailing_ones_ul:
5107 case Builtin::BIstdc_trailing_ones_ull:
5108 case Builtin::BI__builtin_stdc_trailing_ones: {
5109 unsigned ResWidth = S.getASTContext().getIntWidth(Call->getType());
5111 S, OpPC, Call, [ResWidth](const APSInt &Val) {
5112 return APInt(ResWidth, Val.countr_one());
5113 });
5114 }
5115
5116 case Builtin::BIstdc_first_leading_zero_uc:
5117 case Builtin::BIstdc_first_leading_zero_us:
5118 case Builtin::BIstdc_first_leading_zero_ui:
5119 case Builtin::BIstdc_first_leading_zero_ul:
5120 case Builtin::BIstdc_first_leading_zero_ull:
5121 case Builtin::BI__builtin_stdc_first_leading_zero: {
5122 unsigned ResWidth = S.getASTContext().getIntWidth(Call->getType());
5124 S, OpPC, Call, [ResWidth](const APSInt &Val) {
5125 return APInt(ResWidth, Val.isAllOnes() ? 0 : Val.countl_one() + 1);
5126 });
5127 }
5128
5129 case Builtin::BIstdc_first_leading_one_uc:
5130 case Builtin::BIstdc_first_leading_one_us:
5131 case Builtin::BIstdc_first_leading_one_ui:
5132 case Builtin::BIstdc_first_leading_one_ul:
5133 case Builtin::BIstdc_first_leading_one_ull:
5134 case Builtin::BI__builtin_stdc_first_leading_one: {
5135 unsigned ResWidth = S.getASTContext().getIntWidth(Call->getType());
5137 S, OpPC, Call, [ResWidth](const APSInt &Val) {
5138 return APInt(ResWidth, Val.isZero() ? 0 : Val.countl_zero() + 1);
5139 });
5140 }
5141
5142 case Builtin::BIstdc_first_trailing_zero_uc:
5143 case Builtin::BIstdc_first_trailing_zero_us:
5144 case Builtin::BIstdc_first_trailing_zero_ui:
5145 case Builtin::BIstdc_first_trailing_zero_ul:
5146 case Builtin::BIstdc_first_trailing_zero_ull:
5147 case Builtin::BI__builtin_stdc_first_trailing_zero: {
5148 unsigned ResWidth = S.getASTContext().getIntWidth(Call->getType());
5150 S, OpPC, Call, [ResWidth](const APSInt &Val) {
5151 return APInt(ResWidth, Val.isAllOnes() ? 0 : Val.countr_one() + 1);
5152 });
5153 }
5154
5155 case Builtin::BIstdc_first_trailing_one_uc:
5156 case Builtin::BIstdc_first_trailing_one_us:
5157 case Builtin::BIstdc_first_trailing_one_ui:
5158 case Builtin::BIstdc_first_trailing_one_ul:
5159 case Builtin::BIstdc_first_trailing_one_ull:
5160 case Builtin::BI__builtin_stdc_first_trailing_one: {
5161 unsigned ResWidth = S.getASTContext().getIntWidth(Call->getType());
5163 S, OpPC, Call, [ResWidth](const APSInt &Val) {
5164 return APInt(ResWidth, Val.isZero() ? 0 : Val.countr_zero() + 1);
5165 });
5166 }
5167
5168 case Builtin::BIstdc_count_zeros_uc:
5169 case Builtin::BIstdc_count_zeros_us:
5170 case Builtin::BIstdc_count_zeros_ui:
5171 case Builtin::BIstdc_count_zeros_ul:
5172 case Builtin::BIstdc_count_zeros_ull:
5173 case Builtin::BI__builtin_stdc_count_zeros: {
5174 unsigned ResWidth = S.getASTContext().getIntWidth(Call->getType());
5176 S, OpPC, Call, [ResWidth](const APSInt &Val) {
5177 unsigned BitWidth = Val.getBitWidth();
5178 return APInt(ResWidth, BitWidth - Val.popcount());
5179 });
5180 }
5181
5182 case Builtin::BIstdc_count_ones_uc:
5183 case Builtin::BIstdc_count_ones_us:
5184 case Builtin::BIstdc_count_ones_ui:
5185 case Builtin::BIstdc_count_ones_ul:
5186 case Builtin::BIstdc_count_ones_ull:
5187 case Builtin::BI__builtin_stdc_count_ones: {
5188 unsigned ResWidth = S.getASTContext().getIntWidth(Call->getType());
5190 S, OpPC, Call, [ResWidth](const APSInt &Val) {
5191 return APInt(ResWidth, Val.popcount());
5192 });
5193 }
5194
5195 case Builtin::BIstdc_has_single_bit_uc:
5196 case Builtin::BIstdc_has_single_bit_us:
5197 case Builtin::BIstdc_has_single_bit_ui:
5198 case Builtin::BIstdc_has_single_bit_ul:
5199 case Builtin::BIstdc_has_single_bit_ull:
5200 case Builtin::BI__builtin_stdc_has_single_bit: {
5201 unsigned ResWidth = S.getASTContext().getIntWidth(Call->getType());
5203 S, OpPC, Call, [ResWidth](const APSInt &Val) {
5204 return APInt(ResWidth, Val.popcount() == 1 ? 1 : 0);
5205 });
5206 }
5207
5208 case Builtin::BIstdc_bit_width_uc:
5209 case Builtin::BIstdc_bit_width_us:
5210 case Builtin::BIstdc_bit_width_ui:
5211 case Builtin::BIstdc_bit_width_ul:
5212 case Builtin::BIstdc_bit_width_ull:
5213 case Builtin::BI__builtin_stdc_bit_width: {
5214 unsigned ResWidth = S.getASTContext().getIntWidth(Call->getType());
5216 S, OpPC, Call, [ResWidth](const APSInt &Val) {
5217 unsigned BitWidth = Val.getBitWidth();
5218 return APInt(ResWidth, BitWidth - Val.countl_zero());
5219 });
5220 }
5221
5222 case Builtin::BIstdc_bit_floor_uc:
5223 case Builtin::BIstdc_bit_floor_us:
5224 case Builtin::BIstdc_bit_floor_ui:
5225 case Builtin::BIstdc_bit_floor_ul:
5226 case Builtin::BIstdc_bit_floor_ull:
5227 case Builtin::BI__builtin_stdc_bit_floor:
5229 S, OpPC, Call, [](const APSInt &Val) {
5230 unsigned BitWidth = Val.getBitWidth();
5231 if (Val.isZero())
5232 return APInt::getZero(BitWidth);
5233 return APInt::getOneBitSet(BitWidth,
5234 BitWidth - Val.countl_zero() - 1);
5235 });
5236
5237 case Builtin::BIstdc_bit_ceil_uc:
5238 case Builtin::BIstdc_bit_ceil_us:
5239 case Builtin::BIstdc_bit_ceil_ui:
5240 case Builtin::BIstdc_bit_ceil_ul:
5241 case Builtin::BIstdc_bit_ceil_ull:
5242 case Builtin::BI__builtin_stdc_bit_ceil:
5244 S, OpPC, Call, [](const APSInt &Val) {
5245 unsigned BitWidth = Val.getBitWidth();
5246 if (Val.ule(1))
5247 return APInt(BitWidth, 1);
5248 APInt V = Val;
5249 APInt ValMinusOne = V - 1;
5250 unsigned LeadingZeros = ValMinusOne.countl_zero();
5251 if (LeadingZeros == 0)
5252 return APInt(BitWidth, 0); // overflows; wrap to 0
5253 return APInt::getOneBitSet(BitWidth, BitWidth - LeadingZeros);
5254 });
5255
5256 case Builtin::BI__builtin_ffs:
5257 case Builtin::BI__builtin_ffsl:
5258 case Builtin::BI__builtin_ffsll:
5260 S, OpPC, Call, [](const APSInt &Val) {
5261 return APInt(Val.getBitWidth(),
5262 Val.isZero() ? 0u : Val.countTrailingZeros() + 1u);
5263 });
5264
5265 case Builtin::BIaddressof:
5266 case Builtin::BI__addressof:
5267 case Builtin::BI__builtin_addressof:
5268 assert(isNoopBuiltin(BuiltinID));
5269 return interp__builtin_addressof(S, OpPC, Frame, Call);
5270
5271 case Builtin::BIas_const:
5272 case Builtin::BIforward:
5273 case Builtin::BIforward_like:
5274 case Builtin::BImove:
5275 case Builtin::BImove_if_noexcept:
5276 assert(isNoopBuiltin(BuiltinID));
5277 return interp__builtin_move(S, OpPC, Frame, Call);
5278
5279 case Builtin::BI__builtin_eh_return_data_regno:
5281
5282 case Builtin::BI__builtin_launder:
5283 assert(isNoopBuiltin(BuiltinID));
5284 return true;
5285
5286 case Builtin::BI__builtin_add_overflow:
5287 case Builtin::BI__builtin_sub_overflow:
5288 case Builtin::BI__builtin_mul_overflow:
5289 case Builtin::BI__builtin_sadd_overflow:
5290 case Builtin::BI__builtin_uadd_overflow:
5291 case Builtin::BI__builtin_uaddl_overflow:
5292 case Builtin::BI__builtin_uaddll_overflow:
5293 case Builtin::BI__builtin_usub_overflow:
5294 case Builtin::BI__builtin_usubl_overflow:
5295 case Builtin::BI__builtin_usubll_overflow:
5296 case Builtin::BI__builtin_umul_overflow:
5297 case Builtin::BI__builtin_umull_overflow:
5298 case Builtin::BI__builtin_umulll_overflow:
5299 case Builtin::BI__builtin_saddl_overflow:
5300 case Builtin::BI__builtin_saddll_overflow:
5301 case Builtin::BI__builtin_ssub_overflow:
5302 case Builtin::BI__builtin_ssubl_overflow:
5303 case Builtin::BI__builtin_ssubll_overflow:
5304 case Builtin::BI__builtin_smul_overflow:
5305 case Builtin::BI__builtin_smull_overflow:
5306 case Builtin::BI__builtin_smulll_overflow:
5307 return interp__builtin_overflowop(S, OpPC, Call, BuiltinID);
5308
5309 case Builtin::BI__builtin_addcb:
5310 case Builtin::BI__builtin_addcs:
5311 case Builtin::BI__builtin_addc:
5312 case Builtin::BI__builtin_addcl:
5313 case Builtin::BI__builtin_addcll:
5314 case Builtin::BI__builtin_subcb:
5315 case Builtin::BI__builtin_subcs:
5316 case Builtin::BI__builtin_subc:
5317 case Builtin::BI__builtin_subcl:
5318 case Builtin::BI__builtin_subcll:
5319 return interp__builtin_carryop(S, OpPC, Frame, Call, BuiltinID);
5320
5321 case Builtin::BI__builtin_clz:
5322 case Builtin::BI__builtin_clzl:
5323 case Builtin::BI__builtin_clzll:
5324 case Builtin::BI__builtin_clzs:
5325 case Builtin::BI__builtin_clzg:
5326 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
5327 case Builtin::BI__lzcnt:
5328 case Builtin::BI__lzcnt64:
5329 return interp__builtin_clz(S, OpPC, Frame, Call, BuiltinID);
5330
5331 case Builtin::BI__builtin_ctz:
5332 case Builtin::BI__builtin_ctzl:
5333 case Builtin::BI__builtin_ctzll:
5334 case Builtin::BI__builtin_ctzs:
5335 case Builtin::BI__builtin_ctzg:
5336 return interp__builtin_ctz(S, OpPC, Frame, Call, BuiltinID);
5337
5338 case Builtin::BI__builtin_elementwise_clzg:
5339 case Builtin::BI__builtin_elementwise_ctzg:
5341 BuiltinID);
5342 case Builtin::BI__builtin_bswapg:
5343 case Builtin::BI__builtin_bswap16:
5344 case Builtin::BI__builtin_bswap32:
5345 case Builtin::BI__builtin_bswap64:
5346 case Builtin::BIstdc_memreverse8u8:
5347 case Builtin::BIstdc_memreverse8u16:
5348 case Builtin::BIstdc_memreverse8u32:
5349 case Builtin::BIstdc_memreverse8u64:
5350 return interp__builtin_bswap(S, OpPC, Frame, Call);
5351
5352 case Builtin::BIstdc_memreverse8:
5353 case Builtin::BI__builtin_stdc_memreverse8:
5355
5356 case Builtin::BIstdc_load8_leu8:
5357 case Builtin::BIstdc_load8_leu16:
5358 case Builtin::BIstdc_load8_leu32:
5359 case Builtin::BIstdc_load8_leu64:
5360 case Builtin::BIstdc_load8_les8:
5361 case Builtin::BIstdc_load8_les16:
5362 case Builtin::BIstdc_load8_les32:
5363 case Builtin::BIstdc_load8_les64:
5364 return interp__builtin_load8(S, OpPC, Frame, Call, /*IsBigEndian=*/false,
5365 /*IsAligned=*/false);
5366
5367 case Builtin::BIstdc_load8_aligned_leu8:
5368 case Builtin::BIstdc_load8_aligned_leu16:
5369 case Builtin::BIstdc_load8_aligned_leu32:
5370 case Builtin::BIstdc_load8_aligned_leu64:
5371 case Builtin::BIstdc_load8_aligned_les8:
5372 case Builtin::BIstdc_load8_aligned_les16:
5373 case Builtin::BIstdc_load8_aligned_les32:
5374 case Builtin::BIstdc_load8_aligned_les64:
5375 return interp__builtin_load8(S, OpPC, Frame, Call, /*IsBigEndian=*/false,
5376 /*IsAligned=*/true);
5377
5378 case Builtin::BIstdc_load8_beu8:
5379 case Builtin::BIstdc_load8_beu16:
5380 case Builtin::BIstdc_load8_beu32:
5381 case Builtin::BIstdc_load8_beu64:
5382 case Builtin::BIstdc_load8_bes8:
5383 case Builtin::BIstdc_load8_bes16:
5384 case Builtin::BIstdc_load8_bes32:
5385 case Builtin::BIstdc_load8_bes64:
5386 return interp__builtin_load8(S, OpPC, Frame, Call, /*IsBigEndian=*/true,
5387 /*IsAligned=*/false);
5388
5389 case Builtin::BIstdc_load8_aligned_beu8:
5390 case Builtin::BIstdc_load8_aligned_beu16:
5391 case Builtin::BIstdc_load8_aligned_beu32:
5392 case Builtin::BIstdc_load8_aligned_beu64:
5393 case Builtin::BIstdc_load8_aligned_bes8:
5394 case Builtin::BIstdc_load8_aligned_bes16:
5395 case Builtin::BIstdc_load8_aligned_bes32:
5396 case Builtin::BIstdc_load8_aligned_bes64:
5397 return interp__builtin_load8(S, OpPC, Frame, Call, /*IsBigEndian=*/true,
5398 /*IsAligned=*/true);
5399
5400 case Builtin::BI__atomic_always_lock_free:
5401 case Builtin::BI__atomic_is_lock_free:
5402 return interp__builtin_atomic_lock_free(S, OpPC, Frame, Call, BuiltinID);
5403
5404 case Builtin::BI__c11_atomic_is_lock_free:
5406
5407 case Builtin::BI__builtin_complex:
5408 return interp__builtin_complex(S, OpPC, Frame, Call);
5409
5410 case Builtin::BI__builtin_is_aligned:
5411 case Builtin::BI__builtin_align_up:
5412 case Builtin::BI__builtin_align_down:
5413 return interp__builtin_is_aligned_up_down(S, OpPC, Frame, Call, BuiltinID);
5414
5415 case Builtin::BI__builtin_assume_aligned:
5416 return interp__builtin_assume_aligned(S, OpPC, Frame, Call);
5417
5418 case clang::X86::BI__builtin_ia32_crc32qi:
5419 return interp__builtin_ia32_crc32(S, OpPC, Frame, Call, 1);
5420 case clang::X86::BI__builtin_ia32_crc32hi:
5421 return interp__builtin_ia32_crc32(S, OpPC, Frame, Call, 2);
5422 case clang::X86::BI__builtin_ia32_crc32si:
5423 return interp__builtin_ia32_crc32(S, OpPC, Frame, Call, 4);
5424 case clang::X86::BI__builtin_ia32_crc32di:
5425 return interp__builtin_ia32_crc32(S, OpPC, Frame, Call, 8);
5426
5427 case clang::X86::BI__builtin_ia32_bextr_u32:
5428 case clang::X86::BI__builtin_ia32_bextr_u64:
5429 case clang::X86::BI__builtin_ia32_bextri_u32:
5430 case clang::X86::BI__builtin_ia32_bextri_u64:
5432 S, OpPC, Call, [](const APSInt &Val, const APSInt &Idx) {
5433 unsigned BitWidth = Val.getBitWidth();
5434 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
5435 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
5436 if (Length > BitWidth) {
5437 Length = BitWidth;
5438 }
5439
5440 // Handle out of bounds cases.
5441 if (Length == 0 || Shift >= BitWidth)
5442 return APInt(BitWidth, 0);
5443
5444 uint64_t Result = Val.getZExtValue() >> Shift;
5445 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
5446 return APInt(BitWidth, Result);
5447 });
5448
5449 case clang::X86::BI__builtin_ia32_bzhi_si:
5450 case clang::X86::BI__builtin_ia32_bzhi_di:
5452 S, OpPC, Call, [](const APSInt &Val, const APSInt &Idx) {
5453 unsigned BitWidth = Val.getBitWidth();
5454 uint64_t Index = Idx.extractBitsAsZExtValue(8, 0);
5455 APSInt Result = Val;
5456
5457 if (Index < BitWidth)
5458 Result.clearHighBits(BitWidth - Index);
5459
5460 return Result;
5461 });
5462
5463 case clang::X86::BI__builtin_ia32_ktestcqi:
5464 case clang::X86::BI__builtin_ia32_ktestchi:
5465 case clang::X86::BI__builtin_ia32_ktestcsi:
5466 case clang::X86::BI__builtin_ia32_ktestcdi:
5468 S, OpPC, Call, [](const APSInt &A, const APSInt &B) {
5469 return APInt(sizeof(unsigned char) * 8, (~A & B) == 0);
5470 });
5471
5472 case clang::X86::BI__builtin_ia32_ktestzqi:
5473 case clang::X86::BI__builtin_ia32_ktestzhi:
5474 case clang::X86::BI__builtin_ia32_ktestzsi:
5475 case clang::X86::BI__builtin_ia32_ktestzdi:
5477 S, OpPC, Call, [](const APSInt &A, const APSInt &B) {
5478 return APInt(sizeof(unsigned char) * 8, (A & B) == 0);
5479 });
5480
5481 case clang::X86::BI__builtin_ia32_kortestcqi:
5482 case clang::X86::BI__builtin_ia32_kortestchi:
5483 case clang::X86::BI__builtin_ia32_kortestcsi:
5484 case clang::X86::BI__builtin_ia32_kortestcdi:
5486 S, OpPC, Call, [](const APSInt &A, const APSInt &B) {
5487 return APInt(sizeof(unsigned char) * 8, ~(A | B) == 0);
5488 });
5489
5490 case clang::X86::BI__builtin_ia32_kortestzqi:
5491 case clang::X86::BI__builtin_ia32_kortestzhi:
5492 case clang::X86::BI__builtin_ia32_kortestzsi:
5493 case clang::X86::BI__builtin_ia32_kortestzdi:
5495 S, OpPC, Call, [](const APSInt &A, const APSInt &B) {
5496 return APInt(sizeof(unsigned char) * 8, (A | B) == 0);
5497 });
5498
5499 case clang::X86::BI__builtin_ia32_kshiftliqi:
5500 case clang::X86::BI__builtin_ia32_kshiftlihi:
5501 case clang::X86::BI__builtin_ia32_kshiftlisi:
5502 case clang::X86::BI__builtin_ia32_kshiftlidi:
5504 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
5505 unsigned Amt = RHS.getZExtValue() & 0xFF;
5506 if (Amt >= LHS.getBitWidth())
5507 return APInt::getZero(LHS.getBitWidth());
5508 return LHS.shl(Amt);
5509 });
5510
5511 case clang::X86::BI__builtin_ia32_kshiftriqi:
5512 case clang::X86::BI__builtin_ia32_kshiftrihi:
5513 case clang::X86::BI__builtin_ia32_kshiftrisi:
5514 case clang::X86::BI__builtin_ia32_kshiftridi:
5516 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
5517 unsigned Amt = RHS.getZExtValue() & 0xFF;
5518 if (Amt >= LHS.getBitWidth())
5519 return APInt::getZero(LHS.getBitWidth());
5520 return LHS.lshr(Amt);
5521 });
5522
5523 case clang::X86::BI__builtin_ia32_lzcnt_u16:
5524 case clang::X86::BI__builtin_ia32_lzcnt_u32:
5525 case clang::X86::BI__builtin_ia32_lzcnt_u64:
5527 S, OpPC, Call, [](const APSInt &Src) {
5528 return APInt(Src.getBitWidth(), Src.countLeadingZeros());
5529 });
5530
5531 case clang::X86::BI__builtin_ia32_tzcnt_u16:
5532 case clang::X86::BI__builtin_ia32_tzcnt_u32:
5533 case clang::X86::BI__builtin_ia32_tzcnt_u64:
5535 S, OpPC, Call, [](const APSInt &Src) {
5536 return APInt(Src.getBitWidth(), Src.countTrailingZeros());
5537 });
5538
5539 case clang::X86::BI__builtin_ia32_addcarryx_u32:
5540 case clang::X86::BI__builtin_ia32_addcarryx_u64:
5542 /*IsAdd=*/true);
5543
5544 case clang::X86::BI__builtin_ia32_subborrow_u32:
5545 case clang::X86::BI__builtin_ia32_subborrow_u64:
5547 /*IsAdd=*/false);
5548
5549 case Builtin::BI__builtin_os_log_format_buffer_size:
5551
5552 case Builtin::BI__builtin_ptrauth_string_discriminator:
5554
5555 case Builtin::BI__builtin_infer_alloc_token:
5557
5558 case Builtin::BI__noop:
5559 pushInteger(S, 0, Call->getType());
5560 return true;
5561
5562 case Builtin::BI__builtin_operator_new:
5563 return interp__builtin_operator_new(S, OpPC, Frame, Call);
5564
5565 case Builtin::BI__builtin_operator_delete:
5566 return interp__builtin_operator_delete(S, OpPC, Frame, Call);
5567
5568 case Builtin::BI__arithmetic_fence:
5570
5571 case Builtin::BI__builtin_reduce_add:
5572 case Builtin::BI__builtin_reduce_mul:
5573 case Builtin::BI__builtin_reduce_and:
5574 case Builtin::BI__builtin_reduce_or:
5575 case Builtin::BI__builtin_reduce_xor:
5576 case Builtin::BI__builtin_reduce_min:
5577 case Builtin::BI__builtin_reduce_max:
5578 return interp__builtin_vector_reduce(S, OpPC, Call, BuiltinID);
5579
5580 case Builtin::BI__builtin_elementwise_popcount:
5582 S, OpPC, Call, [](const APSInt &Src) {
5583 return APInt(Src.getBitWidth(), Src.popcount());
5584 });
5585 case Builtin::BI__builtin_elementwise_bitreverse:
5587 S, OpPC, Call, [](const APSInt &Src) { return Src.reverseBits(); });
5588
5589 case Builtin::BI__builtin_elementwise_abs:
5590 return interp__builtin_elementwise_abs(S, OpPC, Frame, Call, BuiltinID);
5591
5592 case Builtin::BI__builtin_memcpy:
5593 case Builtin::BImemcpy:
5594 case Builtin::BI__builtin_wmemcpy:
5595 case Builtin::BIwmemcpy:
5596 case Builtin::BI__builtin_memmove:
5597 case Builtin::BImemmove:
5598 case Builtin::BI__builtin_wmemmove:
5599 case Builtin::BIwmemmove:
5600 return interp__builtin_memcpy(S, OpPC, Frame, Call, BuiltinID);
5601
5602 case Builtin::BI__builtin_memcmp:
5603 case Builtin::BImemcmp:
5604 case Builtin::BI__builtin_bcmp:
5605 case Builtin::BIbcmp:
5606 case Builtin::BI__builtin_wmemcmp:
5607 case Builtin::BIwmemcmp:
5608 return interp__builtin_memcmp(S, OpPC, Frame, Call, BuiltinID);
5609
5610 case Builtin::BImemchr:
5611 case Builtin::BI__builtin_memchr:
5612 case Builtin::BIstrchr:
5613 case Builtin::BI__builtin_strchr:
5614 case Builtin::BIwmemchr:
5615 case Builtin::BI__builtin_wmemchr:
5616 case Builtin::BIwcschr:
5617 case Builtin::BI__builtin_wcschr:
5618 case Builtin::BI__builtin_char_memchr:
5619 return interp__builtin_memchr(S, OpPC, Call, BuiltinID);
5620
5621 case Builtin::BI__builtin_object_size:
5622 return interp__builtin_object_size(S, OpPC, Frame, Call,
5623 /*IsDynamic=*/false);
5624 case Builtin::BI__builtin_dynamic_object_size:
5625 return interp__builtin_object_size(S, OpPC, Frame, Call,
5626 /*IsDynamic=*/true);
5627
5628 case Builtin::BI__builtin_is_within_lifetime:
5630
5631 case Builtin::BI__builtin_elementwise_add_sat:
5633 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
5634 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
5635 });
5636
5637 case Builtin::BI__builtin_elementwise_sub_sat:
5639 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
5640 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
5641 });
5642
5643 case Builtin::BI__builtin_elementwise_pdep:
5645 llvm::APIntOps::pdep);
5646
5647 case Builtin::BI__builtin_elementwise_pext:
5649 llvm::APIntOps::pext);
5650
5651 case X86::BI__builtin_ia32_extract128i256:
5652 case X86::BI__builtin_ia32_vextractf128_pd256:
5653 case X86::BI__builtin_ia32_vextractf128_ps256:
5654 case X86::BI__builtin_ia32_vextractf128_si256:
5655 return interp__builtin_ia32_extract_vector(S, OpPC, Call, BuiltinID);
5656
5657 case X86::BI__builtin_ia32_extractf32x4_256_mask:
5658 case X86::BI__builtin_ia32_extractf32x4_mask:
5659 case X86::BI__builtin_ia32_extractf32x8_mask:
5660 case X86::BI__builtin_ia32_extractf64x2_256_mask:
5661 case X86::BI__builtin_ia32_extractf64x2_512_mask:
5662 case X86::BI__builtin_ia32_extractf64x4_mask:
5663 case X86::BI__builtin_ia32_extracti32x4_256_mask:
5664 case X86::BI__builtin_ia32_extracti32x4_mask:
5665 case X86::BI__builtin_ia32_extracti32x8_mask:
5666 case X86::BI__builtin_ia32_extracti64x2_256_mask:
5667 case X86::BI__builtin_ia32_extracti64x2_512_mask:
5668 case X86::BI__builtin_ia32_extracti64x4_mask:
5669 return interp__builtin_ia32_extract_vector_masked(S, OpPC, Call, BuiltinID);
5670
5671 case clang::X86::BI__builtin_ia32_pmulhrsw128:
5672 case clang::X86::BI__builtin_ia32_pmulhrsw256:
5673 case clang::X86::BI__builtin_ia32_pmulhrsw512:
5675 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
5676 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
5677 .extractBits(16, 1);
5678 });
5679
5680 case clang::X86::BI__builtin_ia32_movmskps:
5681 case clang::X86::BI__builtin_ia32_movmskpd:
5682 case clang::X86::BI__builtin_ia32_pmovmskb128:
5683 case clang::X86::BI__builtin_ia32_pmovmskb256:
5684 case clang::X86::BI__builtin_ia32_movmskps256:
5685 case clang::X86::BI__builtin_ia32_movmskpd256: {
5686 return interp__builtin_ia32_movmsk_op(S, OpPC, Call);
5687 }
5688
5689 case X86::BI__builtin_ia32_psignb128:
5690 case X86::BI__builtin_ia32_psignb256:
5691 case X86::BI__builtin_ia32_psignw128:
5692 case X86::BI__builtin_ia32_psignw256:
5693 case X86::BI__builtin_ia32_psignd128:
5694 case X86::BI__builtin_ia32_psignd256:
5696 S, OpPC, Call, [](const APInt &AElem, const APInt &BElem) {
5697 if (BElem.isZero())
5698 return APInt::getZero(AElem.getBitWidth());
5699 if (BElem.isNegative())
5700 return -AElem;
5701 return AElem;
5702 });
5703
5704 case clang::X86::BI__builtin_ia32_pavgb128:
5705 case clang::X86::BI__builtin_ia32_pavgw128:
5706 case clang::X86::BI__builtin_ia32_pavgb256:
5707 case clang::X86::BI__builtin_ia32_pavgw256:
5708 case clang::X86::BI__builtin_ia32_pavgb512:
5709 case clang::X86::BI__builtin_ia32_pavgw512:
5711 llvm::APIntOps::avgCeilU);
5712
5713 case clang::X86::BI__builtin_ia32_pmaddubsw128:
5714 case clang::X86::BI__builtin_ia32_pmaddubsw256:
5715 case clang::X86::BI__builtin_ia32_pmaddubsw512:
5717 S, OpPC, Call,
5718 [](const APSInt &LoLHS, const APSInt &HiLHS, const APSInt &LoRHS,
5719 const APSInt &HiRHS) {
5720 unsigned BitWidth = 2 * LoLHS.getBitWidth();
5721 return (LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
5722 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth)));
5723 });
5724
5725 case clang::X86::BI__builtin_ia32_pmaddwd128:
5726 case clang::X86::BI__builtin_ia32_pmaddwd256:
5727 case clang::X86::BI__builtin_ia32_pmaddwd512:
5729 S, OpPC, Call,
5730 [](const APSInt &LoLHS, const APSInt &HiLHS, const APSInt &LoRHS,
5731 const APSInt &HiRHS) {
5732 unsigned BitWidth = 2 * LoLHS.getBitWidth();
5733 return (LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
5734 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth));
5735 });
5736
5737 case clang::X86::BI__builtin_ia32_psadbw128:
5738 case clang::X86::BI__builtin_ia32_psadbw256:
5739 case clang::X86::BI__builtin_ia32_psadbw512:
5740 return interp__builtin_ia32_psadbw(S, OpPC, Call);
5741
5742 case clang::X86::BI__builtin_ia32_dbpsadbw128:
5743 case clang::X86::BI__builtin_ia32_dbpsadbw256:
5744 case clang::X86::BI__builtin_ia32_dbpsadbw512:
5745 return interp__builtin_ia32_dbpsadbw(S, OpPC, Call);
5746
5747 case clang::X86::BI__builtin_ia32_mpsadbw128:
5748 case clang::X86::BI__builtin_ia32_mpsadbw256:
5749 return interp__builtin_ia32_mpsadbw(S, OpPC, Call);
5750
5751 case clang::X86::BI__builtin_ia32_pmulhuw128:
5752 case clang::X86::BI__builtin_ia32_pmulhuw256:
5753 case clang::X86::BI__builtin_ia32_pmulhuw512:
5755 llvm::APIntOps::mulhu);
5756
5757 case clang::X86::BI__builtin_ia32_pmulhw128:
5758 case clang::X86::BI__builtin_ia32_pmulhw256:
5759 case clang::X86::BI__builtin_ia32_pmulhw512:
5761 llvm::APIntOps::mulhs);
5762
5763 case clang::X86::BI__builtin_ia32_psllv2di:
5764 case clang::X86::BI__builtin_ia32_psllv4di:
5765 case clang::X86::BI__builtin_ia32_psllv4si:
5766 case clang::X86::BI__builtin_ia32_psllv8di:
5767 case clang::X86::BI__builtin_ia32_psllv8hi:
5768 case clang::X86::BI__builtin_ia32_psllv8si:
5769 case clang::X86::BI__builtin_ia32_psllv16hi:
5770 case clang::X86::BI__builtin_ia32_psllv16si:
5771 case clang::X86::BI__builtin_ia32_psllv32hi:
5772 case clang::X86::BI__builtin_ia32_psllwi128:
5773 case clang::X86::BI__builtin_ia32_psllwi256:
5774 case clang::X86::BI__builtin_ia32_psllwi512:
5775 case clang::X86::BI__builtin_ia32_pslldi128:
5776 case clang::X86::BI__builtin_ia32_pslldi256:
5777 case clang::X86::BI__builtin_ia32_pslldi512:
5778 case clang::X86::BI__builtin_ia32_psllqi128:
5779 case clang::X86::BI__builtin_ia32_psllqi256:
5780 case clang::X86::BI__builtin_ia32_psllqi512:
5782 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
5783 if (RHS.uge(LHS.getBitWidth())) {
5784 return APInt::getZero(LHS.getBitWidth());
5785 }
5786 return LHS.shl(RHS.getZExtValue());
5787 });
5788
5789 case clang::X86::BI__builtin_ia32_psrav4si:
5790 case clang::X86::BI__builtin_ia32_psrav8di:
5791 case clang::X86::BI__builtin_ia32_psrav8hi:
5792 case clang::X86::BI__builtin_ia32_psrav8si:
5793 case clang::X86::BI__builtin_ia32_psrav16hi:
5794 case clang::X86::BI__builtin_ia32_psrav16si:
5795 case clang::X86::BI__builtin_ia32_psrav32hi:
5796 case clang::X86::BI__builtin_ia32_psravq128:
5797 case clang::X86::BI__builtin_ia32_psravq256:
5798 case clang::X86::BI__builtin_ia32_psrawi128:
5799 case clang::X86::BI__builtin_ia32_psrawi256:
5800 case clang::X86::BI__builtin_ia32_psrawi512:
5801 case clang::X86::BI__builtin_ia32_psradi128:
5802 case clang::X86::BI__builtin_ia32_psradi256:
5803 case clang::X86::BI__builtin_ia32_psradi512:
5804 case clang::X86::BI__builtin_ia32_psraqi128:
5805 case clang::X86::BI__builtin_ia32_psraqi256:
5806 case clang::X86::BI__builtin_ia32_psraqi512:
5808 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
5809 if (RHS.uge(LHS.getBitWidth())) {
5810 return LHS.ashr(LHS.getBitWidth() - 1);
5811 }
5812 return LHS.ashr(RHS.getZExtValue());
5813 });
5814
5815 case clang::X86::BI__builtin_ia32_psrlv2di:
5816 case clang::X86::BI__builtin_ia32_psrlv4di:
5817 case clang::X86::BI__builtin_ia32_psrlv4si:
5818 case clang::X86::BI__builtin_ia32_psrlv8di:
5819 case clang::X86::BI__builtin_ia32_psrlv8hi:
5820 case clang::X86::BI__builtin_ia32_psrlv8si:
5821 case clang::X86::BI__builtin_ia32_psrlv16hi:
5822 case clang::X86::BI__builtin_ia32_psrlv16si:
5823 case clang::X86::BI__builtin_ia32_psrlv32hi:
5824 case clang::X86::BI__builtin_ia32_psrlwi128:
5825 case clang::X86::BI__builtin_ia32_psrlwi256:
5826 case clang::X86::BI__builtin_ia32_psrlwi512:
5827 case clang::X86::BI__builtin_ia32_psrldi128:
5828 case clang::X86::BI__builtin_ia32_psrldi256:
5829 case clang::X86::BI__builtin_ia32_psrldi512:
5830 case clang::X86::BI__builtin_ia32_psrlqi128:
5831 case clang::X86::BI__builtin_ia32_psrlqi256:
5832 case clang::X86::BI__builtin_ia32_psrlqi512:
5834 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
5835 if (RHS.uge(LHS.getBitWidth())) {
5836 return APInt::getZero(LHS.getBitWidth());
5837 }
5838 return LHS.lshr(RHS.getZExtValue());
5839 });
5840 case clang::X86::BI__builtin_ia32_packsswb128:
5841 case clang::X86::BI__builtin_ia32_packsswb256:
5842 case clang::X86::BI__builtin_ia32_packsswb512:
5843 case clang::X86::BI__builtin_ia32_packssdw128:
5844 case clang::X86::BI__builtin_ia32_packssdw256:
5845 case clang::X86::BI__builtin_ia32_packssdw512:
5846 return interp__builtin_ia32_pack(S, OpPC, Call, [](const APSInt &Src) {
5847 return APInt(Src).truncSSat(Src.getBitWidth() / 2);
5848 });
5849 case clang::X86::BI__builtin_ia32_packusdw128:
5850 case clang::X86::BI__builtin_ia32_packusdw256:
5851 case clang::X86::BI__builtin_ia32_packusdw512:
5852 case clang::X86::BI__builtin_ia32_packuswb128:
5853 case clang::X86::BI__builtin_ia32_packuswb256:
5854 case clang::X86::BI__builtin_ia32_packuswb512:
5855 return interp__builtin_ia32_pack(S, OpPC, Call, [](const APSInt &Src) {
5856 return APInt(Src).truncSSatU(Src.getBitWidth() / 2);
5857 });
5858
5859 case clang::X86::BI__builtin_ia32_selectss_128:
5860 case clang::X86::BI__builtin_ia32_selectsd_128:
5861 case clang::X86::BI__builtin_ia32_selectsh_128:
5862 case clang::X86::BI__builtin_ia32_selectsbf_128:
5864 case clang::X86::BI__builtin_ia32_vprotbi:
5865 case clang::X86::BI__builtin_ia32_vprotdi:
5866 case clang::X86::BI__builtin_ia32_vprotqi:
5867 case clang::X86::BI__builtin_ia32_vprotwi:
5868 case clang::X86::BI__builtin_ia32_prold128:
5869 case clang::X86::BI__builtin_ia32_prold256:
5870 case clang::X86::BI__builtin_ia32_prold512:
5871 case clang::X86::BI__builtin_ia32_prolq128:
5872 case clang::X86::BI__builtin_ia32_prolq256:
5873 case clang::X86::BI__builtin_ia32_prolq512:
5875 S, OpPC, Call,
5876 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
5877
5878 case clang::X86::BI__builtin_ia32_prord128:
5879 case clang::X86::BI__builtin_ia32_prord256:
5880 case clang::X86::BI__builtin_ia32_prord512:
5881 case clang::X86::BI__builtin_ia32_prorq128:
5882 case clang::X86::BI__builtin_ia32_prorq256:
5883 case clang::X86::BI__builtin_ia32_prorq512:
5885 S, OpPC, Call,
5886 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
5887
5888 case Builtin::BI__builtin_elementwise_max:
5889 case Builtin::BI__builtin_elementwise_min:
5890 return interp__builtin_elementwise_maxmin(S, OpPC, Call, BuiltinID);
5891
5892 case clang::X86::BI__builtin_ia32_phaddw128:
5893 case clang::X86::BI__builtin_ia32_phaddw256:
5894 case clang::X86::BI__builtin_ia32_phaddd128:
5895 case clang::X86::BI__builtin_ia32_phaddd256:
5897 S, OpPC, Call,
5898 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
5899 case clang::X86::BI__builtin_ia32_phaddsw128:
5900 case clang::X86::BI__builtin_ia32_phaddsw256:
5902 S, OpPC, Call,
5903 [](const APSInt &LHS, const APSInt &RHS) { return LHS.sadd_sat(RHS); });
5904 case clang::X86::BI__builtin_ia32_phsubw128:
5905 case clang::X86::BI__builtin_ia32_phsubw256:
5906 case clang::X86::BI__builtin_ia32_phsubd128:
5907 case clang::X86::BI__builtin_ia32_phsubd256:
5909 S, OpPC, Call,
5910 [](const APSInt &LHS, const APSInt &RHS) { return LHS - RHS; });
5911 case clang::X86::BI__builtin_ia32_phsubsw128:
5912 case clang::X86::BI__builtin_ia32_phsubsw256:
5914 S, OpPC, Call,
5915 [](const APSInt &LHS, const APSInt &RHS) { return LHS.ssub_sat(RHS); });
5916 case clang::X86::BI__builtin_ia32_haddpd:
5917 case clang::X86::BI__builtin_ia32_haddps:
5918 case clang::X86::BI__builtin_ia32_haddpd256:
5919 case clang::X86::BI__builtin_ia32_haddps256:
5921 S, OpPC, Call,
5922 [](const APFloat &LHS, const APFloat &RHS, llvm::RoundingMode RM) {
5923 APFloat F = LHS;
5924 F.add(RHS, RM);
5925 return F;
5926 });
5927 case clang::X86::BI__builtin_ia32_hsubpd:
5928 case clang::X86::BI__builtin_ia32_hsubps:
5929 case clang::X86::BI__builtin_ia32_hsubpd256:
5930 case clang::X86::BI__builtin_ia32_hsubps256:
5932 S, OpPC, Call,
5933 [](const APFloat &LHS, const APFloat &RHS, llvm::RoundingMode RM) {
5934 APFloat F = LHS;
5935 F.subtract(RHS, RM);
5936 return F;
5937 });
5938 case clang::X86::BI__builtin_ia32_addsubpd:
5939 case clang::X86::BI__builtin_ia32_addsubps:
5940 case clang::X86::BI__builtin_ia32_addsubpd256:
5941 case clang::X86::BI__builtin_ia32_addsubps256:
5942 return interp__builtin_ia32_addsub(S, OpPC, Call);
5943
5944 case clang::X86::BI__builtin_ia32_pmuldq128:
5945 case clang::X86::BI__builtin_ia32_pmuldq256:
5946 case clang::X86::BI__builtin_ia32_pmuldq512:
5948 S, OpPC, Call,
5949 [](const APSInt &LoLHS, const APSInt &HiLHS, const APSInt &LoRHS,
5950 const APSInt &HiRHS) {
5951 return llvm::APIntOps::mulsExtended(LoLHS, LoRHS);
5952 });
5953
5954 case clang::X86::BI__builtin_ia32_pmuludq128:
5955 case clang::X86::BI__builtin_ia32_pmuludq256:
5956 case clang::X86::BI__builtin_ia32_pmuludq512:
5958 S, OpPC, Call,
5959 [](const APSInt &LoLHS, const APSInt &HiLHS, const APSInt &LoRHS,
5960 const APSInt &HiRHS) {
5961 return llvm::APIntOps::muluExtended(LoLHS, LoRHS);
5962 });
5963
5964 case clang::X86::BI__builtin_ia32_pclmulqdq128:
5965 case clang::X86::BI__builtin_ia32_pclmulqdq256:
5966 case clang::X86::BI__builtin_ia32_pclmulqdq512:
5967 return interp__builtin_ia32_pclmulqdq(S, OpPC, Call);
5968 case Builtin::BI__builtin_elementwise_clmul:
5970 llvm::APIntOps::clmul);
5971
5972 case Builtin::BI__builtin_elementwise_fma:
5974 S, OpPC, Call,
5975 [](const APFloat &X, const APFloat &Y, const APFloat &Z,
5976 llvm::RoundingMode RM) {
5977 APFloat F = X;
5978 F.fusedMultiplyAdd(Y, Z, RM);
5979 return F;
5980 });
5981
5982 case X86::BI__builtin_ia32_vpmadd52luq128:
5983 case X86::BI__builtin_ia32_vpmadd52luq256:
5984 case X86::BI__builtin_ia32_vpmadd52luq512:
5986 S, OpPC, Call, [](const APSInt &A, const APSInt &B, const APSInt &C) {
5987 return A + (B.trunc(52) * C.trunc(52)).zext(64);
5988 });
5989 case X86::BI__builtin_ia32_vpmadd52huq128:
5990 case X86::BI__builtin_ia32_vpmadd52huq256:
5991 case X86::BI__builtin_ia32_vpmadd52huq512:
5993 S, OpPC, Call, [](const APSInt &A, const APSInt &B, const APSInt &C) {
5994 return A + llvm::APIntOps::mulhu(B.trunc(52), C.trunc(52)).zext(64);
5995 });
5996
5997 case X86::BI__builtin_ia32_vpshldd128:
5998 case X86::BI__builtin_ia32_vpshldd256:
5999 case X86::BI__builtin_ia32_vpshldd512:
6000 case X86::BI__builtin_ia32_vpshldq128:
6001 case X86::BI__builtin_ia32_vpshldq256:
6002 case X86::BI__builtin_ia32_vpshldq512:
6003 case X86::BI__builtin_ia32_vpshldw128:
6004 case X86::BI__builtin_ia32_vpshldw256:
6005 case X86::BI__builtin_ia32_vpshldw512:
6007 S, OpPC, Call,
6008 [](const APSInt &Hi, const APSInt &Lo, const APSInt &Amt) {
6009 return llvm::APIntOps::fshl(Hi, Lo, Amt);
6010 });
6011
6012 case X86::BI__builtin_ia32_vpshrdd128:
6013 case X86::BI__builtin_ia32_vpshrdd256:
6014 case X86::BI__builtin_ia32_vpshrdd512:
6015 case X86::BI__builtin_ia32_vpshrdq128:
6016 case X86::BI__builtin_ia32_vpshrdq256:
6017 case X86::BI__builtin_ia32_vpshrdq512:
6018 case X86::BI__builtin_ia32_vpshrdw128:
6019 case X86::BI__builtin_ia32_vpshrdw256:
6020 case X86::BI__builtin_ia32_vpshrdw512:
6021 // NOTE: Reversed Hi/Lo operands.
6023 S, OpPC, Call,
6024 [](const APSInt &Lo, const APSInt &Hi, const APSInt &Amt) {
6025 return llvm::APIntOps::fshr(Hi, Lo, Amt);
6026 });
6027 case X86::BI__builtin_ia32_vpconflictsi_128:
6028 case X86::BI__builtin_ia32_vpconflictsi_256:
6029 case X86::BI__builtin_ia32_vpconflictsi_512:
6030 case X86::BI__builtin_ia32_vpconflictdi_128:
6031 case X86::BI__builtin_ia32_vpconflictdi_256:
6032 case X86::BI__builtin_ia32_vpconflictdi_512:
6033 return interp__builtin_ia32_vpconflict(S, OpPC, Call);
6034 case X86::BI__builtin_ia32_compressdf128_mask:
6035 case X86::BI__builtin_ia32_compressdf256_mask:
6036 case X86::BI__builtin_ia32_compressdf512_mask:
6037 case X86::BI__builtin_ia32_compressdi128_mask:
6038 case X86::BI__builtin_ia32_compressdi256_mask:
6039 case X86::BI__builtin_ia32_compressdi512_mask:
6040 case X86::BI__builtin_ia32_compresshi128_mask:
6041 case X86::BI__builtin_ia32_compresshi256_mask:
6042 case X86::BI__builtin_ia32_compresshi512_mask:
6043 case X86::BI__builtin_ia32_compressqi128_mask:
6044 case X86::BI__builtin_ia32_compressqi256_mask:
6045 case X86::BI__builtin_ia32_compressqi512_mask:
6046 case X86::BI__builtin_ia32_compresssf128_mask:
6047 case X86::BI__builtin_ia32_compresssf256_mask:
6048 case X86::BI__builtin_ia32_compresssf512_mask:
6049 case X86::BI__builtin_ia32_compresssi128_mask:
6050 case X86::BI__builtin_ia32_compresssi256_mask:
6051 case X86::BI__builtin_ia32_compresssi512_mask: {
6052 unsigned NumElems =
6053 Call->getArg(0)->getType()->castAs<VectorType>()->getNumElements();
6055 S, OpPC, Call, [NumElems](unsigned DstIdx, const APInt &ShuffleMask) {
6056 APInt CompressMask = ShuffleMask.trunc(NumElems);
6057 if (DstIdx < CompressMask.popcount()) {
6058 while (DstIdx != 0) {
6059 CompressMask = CompressMask & (CompressMask - 1);
6060 DstIdx--;
6061 }
6062 return std::pair<unsigned, int>{
6063 0, static_cast<int>(CompressMask.countr_zero())};
6064 }
6065 return std::pair<unsigned, int>{1, static_cast<int>(DstIdx)};
6066 });
6067 }
6068 case X86::BI__builtin_ia32_expanddf128_mask:
6069 case X86::BI__builtin_ia32_expanddf256_mask:
6070 case X86::BI__builtin_ia32_expanddf512_mask:
6071 case X86::BI__builtin_ia32_expanddi128_mask:
6072 case X86::BI__builtin_ia32_expanddi256_mask:
6073 case X86::BI__builtin_ia32_expanddi512_mask:
6074 case X86::BI__builtin_ia32_expandhi128_mask:
6075 case X86::BI__builtin_ia32_expandhi256_mask:
6076 case X86::BI__builtin_ia32_expandhi512_mask:
6077 case X86::BI__builtin_ia32_expandqi128_mask:
6078 case X86::BI__builtin_ia32_expandqi256_mask:
6079 case X86::BI__builtin_ia32_expandqi512_mask:
6080 case X86::BI__builtin_ia32_expandsf128_mask:
6081 case X86::BI__builtin_ia32_expandsf256_mask:
6082 case X86::BI__builtin_ia32_expandsf512_mask:
6083 case X86::BI__builtin_ia32_expandsi128_mask:
6084 case X86::BI__builtin_ia32_expandsi256_mask:
6085 case X86::BI__builtin_ia32_expandsi512_mask: {
6087 S, OpPC, Call, [](unsigned DstIdx, const APInt &ShuffleMask) {
6088 // Trunc to the sub-mask for the dst index and count the number of
6089 // src elements used prior to that.
6090 APInt ExpandMask = ShuffleMask.trunc(DstIdx + 1);
6091 if (ExpandMask[DstIdx]) {
6092 int SrcIdx = ExpandMask.popcount() - 1;
6093 return std::pair<unsigned, int>{0, SrcIdx};
6094 }
6095 return std::pair<unsigned, int>{1, static_cast<int>(DstIdx)};
6096 });
6097 }
6098 case clang::X86::BI__builtin_ia32_blendpd:
6099 case clang::X86::BI__builtin_ia32_blendpd256:
6100 case clang::X86::BI__builtin_ia32_blendps:
6101 case clang::X86::BI__builtin_ia32_blendps256:
6102 case clang::X86::BI__builtin_ia32_pblendw128:
6103 case clang::X86::BI__builtin_ia32_pblendw256:
6104 case clang::X86::BI__builtin_ia32_pblendd128:
6105 case clang::X86::BI__builtin_ia32_pblendd256:
6107 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6108 // Bit index for mask.
6109 unsigned MaskBit = (ShuffleMask >> (DstIdx % 8)) & 0x1;
6110 unsigned SrcVecIdx = MaskBit ? 1 : 0; // 1 = TrueVec, 0 = FalseVec
6111 return std::pair<unsigned, int>{SrcVecIdx, static_cast<int>(DstIdx)};
6112 });
6113
6114
6115
6116 case clang::X86::BI__builtin_ia32_blendvpd:
6117 case clang::X86::BI__builtin_ia32_blendvpd256:
6118 case clang::X86::BI__builtin_ia32_blendvps:
6119 case clang::X86::BI__builtin_ia32_blendvps256:
6121 S, OpPC, Call,
6122 [](const APFloat &F, const APFloat &T, const APFloat &C,
6123 llvm::RoundingMode) { return C.isNegative() ? T : F; });
6124
6125 case clang::X86::BI__builtin_ia32_pblendvb128:
6126 case clang::X86::BI__builtin_ia32_pblendvb256:
6128 S, OpPC, Call, [](const APSInt &F, const APSInt &T, const APSInt &C) {
6129 return ((APInt)C).isNegative() ? T : F;
6130 });
6131 case X86::BI__builtin_ia32_ptestz128:
6132 case X86::BI__builtin_ia32_ptestz256:
6133 case X86::BI__builtin_ia32_vtestzps:
6134 case X86::BI__builtin_ia32_vtestzps256:
6135 case X86::BI__builtin_ia32_vtestzpd:
6136 case X86::BI__builtin_ia32_vtestzpd256:
6138 S, OpPC, Call,
6139 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
6140 case X86::BI__builtin_ia32_ptestc128:
6141 case X86::BI__builtin_ia32_ptestc256:
6142 case X86::BI__builtin_ia32_vtestcps:
6143 case X86::BI__builtin_ia32_vtestcps256:
6144 case X86::BI__builtin_ia32_vtestcpd:
6145 case X86::BI__builtin_ia32_vtestcpd256:
6147 S, OpPC, Call,
6148 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
6149 case X86::BI__builtin_ia32_ptestnzc128:
6150 case X86::BI__builtin_ia32_ptestnzc256:
6151 case X86::BI__builtin_ia32_vtestnzcps:
6152 case X86::BI__builtin_ia32_vtestnzcps256:
6153 case X86::BI__builtin_ia32_vtestnzcpd:
6154 case X86::BI__builtin_ia32_vtestnzcpd256:
6156 S, OpPC, Call, [](const APInt &A, const APInt &B) {
6157 return ((A & B) != 0) && ((~A & B) != 0);
6158 });
6159 case X86::BI__builtin_ia32_selectb_128:
6160 case X86::BI__builtin_ia32_selectb_256:
6161 case X86::BI__builtin_ia32_selectb_512:
6162 case X86::BI__builtin_ia32_selectw_128:
6163 case X86::BI__builtin_ia32_selectw_256:
6164 case X86::BI__builtin_ia32_selectw_512:
6165 case X86::BI__builtin_ia32_selectd_128:
6166 case X86::BI__builtin_ia32_selectd_256:
6167 case X86::BI__builtin_ia32_selectd_512:
6168 case X86::BI__builtin_ia32_selectq_128:
6169 case X86::BI__builtin_ia32_selectq_256:
6170 case X86::BI__builtin_ia32_selectq_512:
6171 case X86::BI__builtin_ia32_selectph_128:
6172 case X86::BI__builtin_ia32_selectph_256:
6173 case X86::BI__builtin_ia32_selectph_512:
6174 case X86::BI__builtin_ia32_selectpbf_128:
6175 case X86::BI__builtin_ia32_selectpbf_256:
6176 case X86::BI__builtin_ia32_selectpbf_512:
6177 case X86::BI__builtin_ia32_selectps_128:
6178 case X86::BI__builtin_ia32_selectps_256:
6179 case X86::BI__builtin_ia32_selectps_512:
6180 case X86::BI__builtin_ia32_selectpd_128:
6181 case X86::BI__builtin_ia32_selectpd_256:
6182 case X86::BI__builtin_ia32_selectpd_512:
6183 return interp__builtin_ia32_select(S, OpPC, Call);
6184
6185 case X86::BI__builtin_ia32_shufps:
6186 case X86::BI__builtin_ia32_shufps256:
6187 case X86::BI__builtin_ia32_shufps512:
6189 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6190 unsigned NumElemPerLane = 4;
6191 unsigned NumSelectableElems = NumElemPerLane / 2;
6192 unsigned BitsPerElem = 2;
6193 unsigned IndexMask = 0x3;
6194 unsigned MaskBits = 8;
6195 unsigned Lane = DstIdx / NumElemPerLane;
6196 unsigned ElemInLane = DstIdx % NumElemPerLane;
6197 unsigned LaneOffset = Lane * NumElemPerLane;
6198 unsigned SrcIdx = ElemInLane >= NumSelectableElems ? 1 : 0;
6199 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
6200 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
6201 return std::pair<unsigned, int>{SrcIdx,
6202 static_cast<int>(LaneOffset + Index)};
6203 });
6204 case X86::BI__builtin_ia32_shufpd:
6205 case X86::BI__builtin_ia32_shufpd256:
6206 case X86::BI__builtin_ia32_shufpd512:
6208 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6209 unsigned NumElemPerLane = 2;
6210 unsigned NumSelectableElems = NumElemPerLane / 2;
6211 unsigned BitsPerElem = 1;
6212 unsigned IndexMask = 0x1;
6213 unsigned MaskBits = 8;
6214 unsigned Lane = DstIdx / NumElemPerLane;
6215 unsigned ElemInLane = DstIdx % NumElemPerLane;
6216 unsigned LaneOffset = Lane * NumElemPerLane;
6217 unsigned SrcIdx = ElemInLane >= NumSelectableElems ? 1 : 0;
6218 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
6219 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
6220 return std::pair<unsigned, int>{SrcIdx,
6221 static_cast<int>(LaneOffset + Index)};
6222 });
6223
6224 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
6225 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
6226 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
6227 return interp__builtin_ia32_gfni_affine(S, OpPC, Call, true);
6228 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
6229 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
6230 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi:
6231 return interp__builtin_ia32_gfni_affine(S, OpPC, Call, false);
6232
6233 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
6234 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
6235 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi:
6236 return interp__builtin_ia32_gfni_mul(S, OpPC, Call);
6237
6238 case X86::BI__builtin_ia32_bmacor16x16x16_v16hi:
6239 case X86::BI__builtin_ia32_bmacor16x16x16_v32hi:
6240 return interp__builtin_ia32_bmac(S, OpPC, Call, /*IsXor=*/false);
6241 case X86::BI__builtin_ia32_bmacxor16x16x16_v16hi:
6242 case X86::BI__builtin_ia32_bmacxor16x16x16_v32hi:
6243 return interp__builtin_ia32_bmac(S, OpPC, Call, /*IsXor=*/true);
6244
6245 case X86::BI__builtin_ia32_insertps128:
6247 S, OpPC, Call, [](unsigned DstIdx, unsigned Mask) {
6248 // Bits [3:0]: zero mask - if bit is set, zero this element
6249 if ((Mask & (1 << DstIdx)) != 0) {
6250 return std::pair<unsigned, int>{0, -1};
6251 }
6252 // Bits [7:6]: select element from source vector Y (0-3)
6253 // Bits [5:4]: select destination position (0-3)
6254 unsigned SrcElem = (Mask >> 6) & 0x3;
6255 unsigned DstElem = (Mask >> 4) & 0x3;
6256 if (DstIdx == DstElem) {
6257 // Insert element from source vector (B) at this position
6258 return std::pair<unsigned, int>{1, static_cast<int>(SrcElem)};
6259 } else {
6260 // Copy from destination vector (A)
6261 return std::pair<unsigned, int>{0, static_cast<int>(DstIdx)};
6262 }
6263 });
6264 case X86::BI__builtin_ia32_permvarsi256:
6265 case X86::BI__builtin_ia32_permvarsf256:
6266 case X86::BI__builtin_ia32_permvardf512:
6267 case X86::BI__builtin_ia32_permvardi512:
6268 case X86::BI__builtin_ia32_permvarhi128:
6270 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6271 int Offset = ShuffleMask & 0x7;
6272 return std::pair<unsigned, int>{0, Offset};
6273 });
6274 case X86::BI__builtin_ia32_permvarqi128:
6275 case X86::BI__builtin_ia32_permvarhi256:
6276 case X86::BI__builtin_ia32_permvarsi512:
6277 case X86::BI__builtin_ia32_permvarsf512:
6279 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6280 int Offset = ShuffleMask & 0xF;
6281 return std::pair<unsigned, int>{0, Offset};
6282 });
6283 case X86::BI__builtin_ia32_permvardi256:
6284 case X86::BI__builtin_ia32_permvardf256:
6286 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6287 int Offset = ShuffleMask & 0x3;
6288 return std::pair<unsigned, int>{0, Offset};
6289 });
6290 case X86::BI__builtin_ia32_permvarqi256:
6291 case X86::BI__builtin_ia32_permvarhi512:
6293 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6294 int Offset = ShuffleMask & 0x1F;
6295 return std::pair<unsigned, int>{0, Offset};
6296 });
6297 case X86::BI__builtin_ia32_permvarqi512:
6299 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6300 int Offset = ShuffleMask & 0x3F;
6301 return std::pair<unsigned, int>{0, Offset};
6302 });
6303 case X86::BI__builtin_ia32_vpermi2varq128:
6304 case X86::BI__builtin_ia32_vpermi2varpd128:
6306 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6307 int Offset = ShuffleMask & 0x1;
6308 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
6309 return std::pair<unsigned, int>{SrcIdx, Offset};
6310 });
6311 case X86::BI__builtin_ia32_vpermi2vard128:
6312 case X86::BI__builtin_ia32_vpermi2varps128:
6313 case X86::BI__builtin_ia32_vpermi2varq256:
6314 case X86::BI__builtin_ia32_vpermi2varpd256:
6316 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6317 int Offset = ShuffleMask & 0x3;
6318 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
6319 return std::pair<unsigned, int>{SrcIdx, Offset};
6320 });
6321 case X86::BI__builtin_ia32_vpermi2varhi128:
6322 case X86::BI__builtin_ia32_vpermi2vard256:
6323 case X86::BI__builtin_ia32_vpermi2varps256:
6324 case X86::BI__builtin_ia32_vpermi2varq512:
6325 case X86::BI__builtin_ia32_vpermi2varpd512:
6327 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6328 int Offset = ShuffleMask & 0x7;
6329 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
6330 return std::pair<unsigned, int>{SrcIdx, Offset};
6331 });
6332 case X86::BI__builtin_ia32_vpermi2varqi128:
6333 case X86::BI__builtin_ia32_vpermi2varhi256:
6334 case X86::BI__builtin_ia32_vpermi2vard512:
6335 case X86::BI__builtin_ia32_vpermi2varps512:
6337 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6338 int Offset = ShuffleMask & 0xF;
6339 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
6340 return std::pair<unsigned, int>{SrcIdx, Offset};
6341 });
6342 case X86::BI__builtin_ia32_vpermi2varqi256:
6343 case X86::BI__builtin_ia32_vpermi2varhi512:
6345 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6346 int Offset = ShuffleMask & 0x1F;
6347 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
6348 return std::pair<unsigned, int>{SrcIdx, Offset};
6349 });
6350 case X86::BI__builtin_ia32_vpermi2varqi512:
6352 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6353 int Offset = ShuffleMask & 0x3F;
6354 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
6355 return std::pair<unsigned, int>{SrcIdx, Offset};
6356 });
6357 case X86::BI__builtin_ia32_vperm2f128_pd256:
6358 case X86::BI__builtin_ia32_vperm2f128_ps256:
6359 case X86::BI__builtin_ia32_vperm2f128_si256:
6360 case X86::BI__builtin_ia32_permti256: {
6361 unsigned NumElements =
6362 Call->getArg(0)->getType()->castAs<VectorType>()->getNumElements();
6363 unsigned PreservedBitsCnt = NumElements >> 2;
6365 S, OpPC, Call,
6366 [PreservedBitsCnt](unsigned DstIdx, unsigned ShuffleMask) {
6367 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
6368 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
6369
6370 if (ControlBits & 0b1000)
6371 return std::make_pair(0u, -1);
6372
6373 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
6374 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
6375 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
6376 (DstIdx & PreservedBitsMask);
6377 return std::make_pair(SrcVecIdx, SrcIdx);
6378 });
6379 }
6380 case X86::BI__builtin_ia32_pshufb128:
6381 case X86::BI__builtin_ia32_pshufb256:
6382 case X86::BI__builtin_ia32_pshufb512:
6384 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6385 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
6386 if (Ctlb & 0x80)
6387 return std::make_pair(0, -1);
6388
6389 unsigned LaneBase = (DstIdx / 16) * 16;
6390 unsigned SrcOffset = Ctlb & 0x0F;
6391 unsigned SrcIdx = LaneBase + SrcOffset;
6392 return std::make_pair(0, static_cast<int>(SrcIdx));
6393 });
6394
6395 case X86::BI__builtin_ia32_pshuflw:
6396 case X86::BI__builtin_ia32_pshuflw256:
6397 case X86::BI__builtin_ia32_pshuflw512:
6399 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6400 unsigned LaneBase = (DstIdx / 8) * 8;
6401 unsigned LaneIdx = DstIdx % 8;
6402 if (LaneIdx < 4) {
6403 unsigned Sel = (ShuffleMask >> (2 * LaneIdx)) & 0x3;
6404 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
6405 }
6406
6407 return std::make_pair(0, static_cast<int>(DstIdx));
6408 });
6409
6410 case X86::BI__builtin_ia32_pshufhw:
6411 case X86::BI__builtin_ia32_pshufhw256:
6412 case X86::BI__builtin_ia32_pshufhw512:
6414 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6415 unsigned LaneBase = (DstIdx / 8) * 8;
6416 unsigned LaneIdx = DstIdx % 8;
6417 if (LaneIdx >= 4) {
6418 unsigned Sel = (ShuffleMask >> (2 * (LaneIdx - 4))) & 0x3;
6419 return std::make_pair(0, static_cast<int>(LaneBase + 4 + Sel));
6420 }
6421
6422 return std::make_pair(0, static_cast<int>(DstIdx));
6423 });
6424
6425 case X86::BI__builtin_ia32_pshufd:
6426 case X86::BI__builtin_ia32_pshufd256:
6427 case X86::BI__builtin_ia32_pshufd512:
6428 case X86::BI__builtin_ia32_vpermilps:
6429 case X86::BI__builtin_ia32_vpermilps256:
6430 case X86::BI__builtin_ia32_vpermilps512:
6432 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6433 unsigned LaneBase = (DstIdx / 4) * 4;
6434 unsigned LaneIdx = DstIdx % 4;
6435 unsigned Sel = (ShuffleMask >> (2 * LaneIdx)) & 0x3;
6436 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
6437 });
6438
6439 case X86::BI__builtin_ia32_vpermilvarpd:
6440 case X86::BI__builtin_ia32_vpermilvarpd256:
6441 case X86::BI__builtin_ia32_vpermilvarpd512:
6443 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6444 unsigned NumElemPerLane = 2;
6445 unsigned Lane = DstIdx / NumElemPerLane;
6446 unsigned Offset = ShuffleMask & 0b10 ? 1 : 0;
6447 return std::make_pair(
6448 0, static_cast<int>(Lane * NumElemPerLane + Offset));
6449 });
6450
6451 case X86::BI__builtin_ia32_vpermilvarps:
6452 case X86::BI__builtin_ia32_vpermilvarps256:
6453 case X86::BI__builtin_ia32_vpermilvarps512:
6455 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
6456 unsigned NumElemPerLane = 4;
6457 unsigned Lane = DstIdx / NumElemPerLane;
6458 unsigned Offset = ShuffleMask & 0b11;
6459 return std::make_pair(
6460 0, static_cast<int>(Lane * NumElemPerLane + Offset));
6461 });
6462
6463 case X86::BI__builtin_ia32_vpermilpd:
6464 case X86::BI__builtin_ia32_vpermilpd256:
6465 case X86::BI__builtin_ia32_vpermilpd512:
6467 S, OpPC, Call, [](unsigned DstIdx, unsigned Control) {
6468 unsigned NumElemPerLane = 2;
6469 unsigned BitsPerElem = 1;
6470 unsigned MaskBits = 8;
6471 unsigned IndexMask = 0x1;
6472 unsigned Lane = DstIdx / NumElemPerLane;
6473 unsigned LaneOffset = Lane * NumElemPerLane;
6474 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
6475 unsigned Index = (Control >> BitIndex) & IndexMask;
6476 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
6477 });
6478
6479 case X86::BI__builtin_ia32_permdf256:
6480 case X86::BI__builtin_ia32_permdi256:
6482 S, OpPC, Call, [](unsigned DstIdx, unsigned Control) {
6483 // permute4x64 operates on 4 64-bit elements
6484 // For element i (0-3), extract bits [2*i+1:2*i] from Control
6485 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
6486 return std::make_pair(0, static_cast<int>(Index));
6487 });
6488
6489 case X86::BI__builtin_ia32_vpmultishiftqb128:
6490 case X86::BI__builtin_ia32_vpmultishiftqb256:
6491 case X86::BI__builtin_ia32_vpmultishiftqb512:
6492 return interp__builtin_ia32_multishiftqb(S, OpPC, Call);
6493 case X86::BI__builtin_ia32_kandqi:
6494 case X86::BI__builtin_ia32_kandhi:
6495 case X86::BI__builtin_ia32_kandsi:
6496 case X86::BI__builtin_ia32_kanddi:
6498 S, OpPC, Call,
6499 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
6500
6501 case X86::BI__builtin_ia32_kandnqi:
6502 case X86::BI__builtin_ia32_kandnhi:
6503 case X86::BI__builtin_ia32_kandnsi:
6504 case X86::BI__builtin_ia32_kandndi:
6506 S, OpPC, Call,
6507 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
6508
6509 case X86::BI__builtin_ia32_korqi:
6510 case X86::BI__builtin_ia32_korhi:
6511 case X86::BI__builtin_ia32_korsi:
6512 case X86::BI__builtin_ia32_kordi:
6514 S, OpPC, Call,
6515 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
6516
6517 case X86::BI__builtin_ia32_kxnorqi:
6518 case X86::BI__builtin_ia32_kxnorhi:
6519 case X86::BI__builtin_ia32_kxnorsi:
6520 case X86::BI__builtin_ia32_kxnordi:
6522 S, OpPC, Call,
6523 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
6524
6525 case X86::BI__builtin_ia32_kxorqi:
6526 case X86::BI__builtin_ia32_kxorhi:
6527 case X86::BI__builtin_ia32_kxorsi:
6528 case X86::BI__builtin_ia32_kxordi:
6530 S, OpPC, Call,
6531 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
6532
6533 case X86::BI__builtin_ia32_knotqi:
6534 case X86::BI__builtin_ia32_knothi:
6535 case X86::BI__builtin_ia32_knotsi:
6536 case X86::BI__builtin_ia32_knotdi:
6538 S, OpPC, Call, [](const APSInt &Src) { return ~Src; });
6539
6540 case X86::BI__builtin_ia32_kaddqi:
6541 case X86::BI__builtin_ia32_kaddhi:
6542 case X86::BI__builtin_ia32_kaddsi:
6543 case X86::BI__builtin_ia32_kadddi:
6545 S, OpPC, Call,
6546 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
6547
6548 case X86::BI__builtin_ia32_kmovb:
6549 case X86::BI__builtin_ia32_kmovw:
6550 case X86::BI__builtin_ia32_kmovd:
6551 case X86::BI__builtin_ia32_kmovq:
6553 S, OpPC, Call, [](const APSInt &Src) { return Src; });
6554
6555 case X86::BI__builtin_ia32_kunpckhi:
6556 case X86::BI__builtin_ia32_kunpckdi:
6557 case X86::BI__builtin_ia32_kunpcksi:
6559 S, OpPC, Call, [](const APSInt &A, const APSInt &B) {
6560 // Generic kunpack: extract lower half of each operand and concatenate
6561 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
6562 unsigned BW = A.getBitWidth();
6563 return APSInt(A.trunc(BW / 2).concat(B.trunc(BW / 2)),
6564 A.isUnsigned());
6565 });
6566
6567 case X86::BI__builtin_ia32_phminposuw128:
6568 return interp__builtin_ia32_phminposuw(S, OpPC, Call);
6569
6570 case X86::BI__builtin_ia32_psraq128:
6571 case X86::BI__builtin_ia32_psraq256:
6572 case X86::BI__builtin_ia32_psraq512:
6573 case X86::BI__builtin_ia32_psrad128:
6574 case X86::BI__builtin_ia32_psrad256:
6575 case X86::BI__builtin_ia32_psrad512:
6576 case X86::BI__builtin_ia32_psraw128:
6577 case X86::BI__builtin_ia32_psraw256:
6578 case X86::BI__builtin_ia32_psraw512:
6580 S, OpPC, Call,
6581 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
6582 [](const APInt &Elt, unsigned Width) { return Elt.ashr(Width - 1); });
6583
6584 case X86::BI__builtin_ia32_psllq128:
6585 case X86::BI__builtin_ia32_psllq256:
6586 case X86::BI__builtin_ia32_psllq512:
6587 case X86::BI__builtin_ia32_pslld128:
6588 case X86::BI__builtin_ia32_pslld256:
6589 case X86::BI__builtin_ia32_pslld512:
6590 case X86::BI__builtin_ia32_psllw128:
6591 case X86::BI__builtin_ia32_psllw256:
6592 case X86::BI__builtin_ia32_psllw512:
6594 S, OpPC, Call,
6595 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
6596 [](const APInt &Elt, unsigned Width) { return APInt::getZero(Width); });
6597
6598 case X86::BI__builtin_ia32_psrlq128:
6599 case X86::BI__builtin_ia32_psrlq256:
6600 case X86::BI__builtin_ia32_psrlq512:
6601 case X86::BI__builtin_ia32_psrld128:
6602 case X86::BI__builtin_ia32_psrld256:
6603 case X86::BI__builtin_ia32_psrld512:
6604 case X86::BI__builtin_ia32_psrlw128:
6605 case X86::BI__builtin_ia32_psrlw256:
6606 case X86::BI__builtin_ia32_psrlw512:
6608 S, OpPC, Call,
6609 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
6610 [](const APInt &Elt, unsigned Width) { return APInt::getZero(Width); });
6611
6612 case X86::BI__builtin_ia32_pternlogd128_mask:
6613 case X86::BI__builtin_ia32_pternlogd256_mask:
6614 case X86::BI__builtin_ia32_pternlogd512_mask:
6615 case X86::BI__builtin_ia32_pternlogq128_mask:
6616 case X86::BI__builtin_ia32_pternlogq256_mask:
6617 case X86::BI__builtin_ia32_pternlogq512_mask:
6618 return interp__builtin_ia32_pternlog(S, OpPC, Call, /*MaskZ=*/false);
6619 case X86::BI__builtin_ia32_pternlogd128_maskz:
6620 case X86::BI__builtin_ia32_pternlogd256_maskz:
6621 case X86::BI__builtin_ia32_pternlogd512_maskz:
6622 case X86::BI__builtin_ia32_pternlogq128_maskz:
6623 case X86::BI__builtin_ia32_pternlogq256_maskz:
6624 case X86::BI__builtin_ia32_pternlogq512_maskz:
6625 return interp__builtin_ia32_pternlog(S, OpPC, Call, /*MaskZ=*/true);
6626 case Builtin::BI__builtin_elementwise_fshl:
6628 llvm::APIntOps::fshl);
6629 case Builtin::BI__builtin_elementwise_fshr:
6631 llvm::APIntOps::fshr);
6632
6633 case X86::BI__builtin_ia32_shuf_f32x4_256:
6634 case X86::BI__builtin_ia32_shuf_i32x4_256:
6635 case X86::BI__builtin_ia32_shuf_f64x2_256:
6636 case X86::BI__builtin_ia32_shuf_i64x2_256:
6637 case X86::BI__builtin_ia32_shuf_f32x4:
6638 case X86::BI__builtin_ia32_shuf_i32x4:
6639 case X86::BI__builtin_ia32_shuf_f64x2:
6640 case X86::BI__builtin_ia32_shuf_i64x2: {
6641 // Destination and sources A, B all have the same type.
6642 QualType VecQT = Call->getArg(0)->getType();
6643 const auto *VecT = VecQT->castAs<VectorType>();
6644 unsigned NumElems = VecT->getNumElements();
6645 unsigned ElemBits = S.getASTContext().getTypeSize(VecT->getElementType());
6646 unsigned LaneBits = 128u;
6647 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
6648 unsigned NumElemsPerLane = LaneBits / ElemBits;
6649
6651 S, OpPC, Call,
6652 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask) {
6653 // DstIdx determines source. ShuffleMask selects lane in source.
6654 unsigned BitsPerElem = NumLanes / 2;
6655 unsigned IndexMask = (1u << BitsPerElem) - 1;
6656 unsigned Lane = DstIdx / NumElemsPerLane;
6657 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
6658 unsigned BitIdx = BitsPerElem * Lane;
6659 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
6660 unsigned ElemInLane = DstIdx % NumElemsPerLane;
6661 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
6662 return std::pair<unsigned, int>{SrcIdx, IdxToPick};
6663 });
6664 }
6665
6666 case X86::BI__builtin_ia32_insertf32x4_256:
6667 case X86::BI__builtin_ia32_inserti32x4_256:
6668 case X86::BI__builtin_ia32_insertf64x2_256:
6669 case X86::BI__builtin_ia32_inserti64x2_256:
6670 case X86::BI__builtin_ia32_insertf32x4:
6671 case X86::BI__builtin_ia32_inserti32x4:
6672 case X86::BI__builtin_ia32_insertf64x2_512:
6673 case X86::BI__builtin_ia32_inserti64x2_512:
6674 case X86::BI__builtin_ia32_insertf32x8:
6675 case X86::BI__builtin_ia32_inserti32x8:
6676 case X86::BI__builtin_ia32_insertf64x4:
6677 case X86::BI__builtin_ia32_inserti64x4:
6678 case X86::BI__builtin_ia32_vinsertf128_ps256:
6679 case X86::BI__builtin_ia32_vinsertf128_pd256:
6680 case X86::BI__builtin_ia32_vinsertf128_si256:
6681 case X86::BI__builtin_ia32_insert128i256:
6682 return interp__builtin_ia32_insert_subvector(S, OpPC, Call, BuiltinID);
6683
6684 case clang::X86::BI__builtin_ia32_vcvtps2ph:
6685 case clang::X86::BI__builtin_ia32_vcvtps2ph256:
6686 return interp__builtin_ia32_vcvtps2ph(S, OpPC, Call);
6687
6688 case X86::BI__builtin_ia32_vec_ext_v4hi:
6689 case X86::BI__builtin_ia32_vec_ext_v16qi:
6690 case X86::BI__builtin_ia32_vec_ext_v8hi:
6691 case X86::BI__builtin_ia32_vec_ext_v4si:
6692 case X86::BI__builtin_ia32_vec_ext_v2di:
6693 case X86::BI__builtin_ia32_vec_ext_v32qi:
6694 case X86::BI__builtin_ia32_vec_ext_v16hi:
6695 case X86::BI__builtin_ia32_vec_ext_v8si:
6696 case X86::BI__builtin_ia32_vec_ext_v4di:
6697 case X86::BI__builtin_ia32_vec_ext_v4sf:
6698 return interp__builtin_ia32_vec_ext(S, OpPC, Call, BuiltinID);
6699
6700 case X86::BI__builtin_ia32_vec_set_v4hi:
6701 case X86::BI__builtin_ia32_vec_set_v16qi:
6702 case X86::BI__builtin_ia32_vec_set_v8hi:
6703 case X86::BI__builtin_ia32_vec_set_v4si:
6704 case X86::BI__builtin_ia32_vec_set_v2di:
6705 case X86::BI__builtin_ia32_vec_set_v32qi:
6706 case X86::BI__builtin_ia32_vec_set_v16hi:
6707 case X86::BI__builtin_ia32_vec_set_v8si:
6708 case X86::BI__builtin_ia32_vec_set_v4di:
6709 return interp__builtin_ia32_vec_set(S, OpPC, Call, BuiltinID);
6710
6711 case X86::BI__builtin_ia32_cvtb2mask128:
6712 case X86::BI__builtin_ia32_cvtb2mask256:
6713 case X86::BI__builtin_ia32_cvtb2mask512:
6714 case X86::BI__builtin_ia32_cvtw2mask128:
6715 case X86::BI__builtin_ia32_cvtw2mask256:
6716 case X86::BI__builtin_ia32_cvtw2mask512:
6717 case X86::BI__builtin_ia32_cvtd2mask128:
6718 case X86::BI__builtin_ia32_cvtd2mask256:
6719 case X86::BI__builtin_ia32_cvtd2mask512:
6720 case X86::BI__builtin_ia32_cvtq2mask128:
6721 case X86::BI__builtin_ia32_cvtq2mask256:
6722 case X86::BI__builtin_ia32_cvtq2mask512:
6723 return interp__builtin_ia32_cvt_vec2mask(S, OpPC, Call, BuiltinID);
6724
6725 case X86::BI__builtin_ia32_cvtmask2b128:
6726 case X86::BI__builtin_ia32_cvtmask2b256:
6727 case X86::BI__builtin_ia32_cvtmask2b512:
6728 case X86::BI__builtin_ia32_cvtmask2w128:
6729 case X86::BI__builtin_ia32_cvtmask2w256:
6730 case X86::BI__builtin_ia32_cvtmask2w512:
6731 case X86::BI__builtin_ia32_cvtmask2d128:
6732 case X86::BI__builtin_ia32_cvtmask2d256:
6733 case X86::BI__builtin_ia32_cvtmask2d512:
6734 case X86::BI__builtin_ia32_cvtmask2q128:
6735 case X86::BI__builtin_ia32_cvtmask2q256:
6736 case X86::BI__builtin_ia32_cvtmask2q512:
6737 return interp__builtin_ia32_cvt_mask2vec(S, OpPC, Call, BuiltinID);
6738
6739 case X86::BI__builtin_ia32_cvtsd2ss:
6740 return interp__builtin_ia32_cvtsd2ss(S, OpPC, Call, false);
6741
6742 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
6743 return interp__builtin_ia32_cvtsd2ss(S, OpPC, Call, true);
6744
6745 case X86::BI__builtin_ia32_cvtpd2ps:
6746 case X86::BI__builtin_ia32_cvtpd2ps256:
6747 return interp__builtin_ia32_cvtpd2ps(S, OpPC, Call, false, false);
6748 case X86::BI__builtin_ia32_cvtpd2ps_mask:
6749 return interp__builtin_ia32_cvtpd2ps(S, OpPC, Call, true, false);
6750 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
6751 return interp__builtin_ia32_cvtpd2ps(S, OpPC, Call, true, true);
6752
6753 case X86::BI__builtin_ia32_cmpb128_mask:
6754 case X86::BI__builtin_ia32_cmpw128_mask:
6755 case X86::BI__builtin_ia32_cmpd128_mask:
6756 case X86::BI__builtin_ia32_cmpq128_mask:
6757 case X86::BI__builtin_ia32_cmpb256_mask:
6758 case X86::BI__builtin_ia32_cmpw256_mask:
6759 case X86::BI__builtin_ia32_cmpd256_mask:
6760 case X86::BI__builtin_ia32_cmpq256_mask:
6761 case X86::BI__builtin_ia32_cmpb512_mask:
6762 case X86::BI__builtin_ia32_cmpw512_mask:
6763 case X86::BI__builtin_ia32_cmpd512_mask:
6764 case X86::BI__builtin_ia32_cmpq512_mask:
6765 return interp__builtin_ia32_cmp_mask(S, OpPC, Call, BuiltinID,
6766 /*IsUnsigned=*/false);
6767
6768 case X86::BI__builtin_ia32_ucmpb128_mask:
6769 case X86::BI__builtin_ia32_ucmpw128_mask:
6770 case X86::BI__builtin_ia32_ucmpd128_mask:
6771 case X86::BI__builtin_ia32_ucmpq128_mask:
6772 case X86::BI__builtin_ia32_ucmpb256_mask:
6773 case X86::BI__builtin_ia32_ucmpw256_mask:
6774 case X86::BI__builtin_ia32_ucmpd256_mask:
6775 case X86::BI__builtin_ia32_ucmpq256_mask:
6776 case X86::BI__builtin_ia32_ucmpb512_mask:
6777 case X86::BI__builtin_ia32_ucmpw512_mask:
6778 case X86::BI__builtin_ia32_ucmpd512_mask:
6779 case X86::BI__builtin_ia32_ucmpq512_mask:
6780 return interp__builtin_ia32_cmp_mask(S, OpPC, Call, BuiltinID,
6781 /*IsUnsigned=*/true);
6782
6783 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
6784 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
6785 case X86::BI__builtin_ia32_vpshufbitqmb512_mask:
6787
6788 case X86::BI__builtin_ia32_pslldqi128_byteshift:
6789 case X86::BI__builtin_ia32_pslldqi256_byteshift:
6790 case X86::BI__builtin_ia32_pslldqi512_byteshift:
6791 // These SLLDQ intrinsics always operate on byte elements (8 bits).
6792 // The lane width is hardcoded to 16 to match the SIMD register size,
6793 // but the algorithm processes one byte per iteration,
6794 // so APInt(8, ...) is correct and intentional.
6796 S, OpPC, Call,
6797 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
6798 unsigned LaneBase = (DstIdx / 16) * 16;
6799 unsigned LaneIdx = DstIdx % 16;
6800 if (LaneIdx < Shift)
6801 return std::make_pair(0, -1);
6802
6803 return std::make_pair(0,
6804 static_cast<int>(LaneBase + LaneIdx - Shift));
6805 });
6806
6807 case X86::BI__builtin_ia32_psrldqi128_byteshift:
6808 case X86::BI__builtin_ia32_psrldqi256_byteshift:
6809 case X86::BI__builtin_ia32_psrldqi512_byteshift:
6810 // These SRLDQ intrinsics always operate on byte elements (8 bits).
6811 // The lane width is hardcoded to 16 to match the SIMD register size,
6812 // but the algorithm processes one byte per iteration,
6813 // so APInt(8, ...) is correct and intentional.
6815 S, OpPC, Call,
6816 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
6817 unsigned LaneBase = (DstIdx / 16) * 16;
6818 unsigned LaneIdx = DstIdx % 16;
6819 if (LaneIdx + Shift < 16)
6820 return std::make_pair(0,
6821 static_cast<int>(LaneBase + LaneIdx + Shift));
6822
6823 return std::make_pair(0, -1);
6824 });
6825
6826 case X86::BI__builtin_ia32_palignr128:
6827 case X86::BI__builtin_ia32_palignr256:
6828 case X86::BI__builtin_ia32_palignr512:
6830 S, OpPC, Call, [](unsigned DstIdx, unsigned Shift) {
6831 // Default to -1 → zero-fill this destination element
6832 unsigned VecIdx = 1;
6833 int ElemIdx = -1;
6834
6835 int Lane = DstIdx / 16;
6836 int Offset = DstIdx % 16;
6837
6838 // Elements come from VecB first, then VecA after the shift boundary
6839 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
6840 if (ShiftedIdx < 16) { // from VecB
6841 ElemIdx = ShiftedIdx + (Lane * 16);
6842 } else if (ShiftedIdx < 32) { // from VecA
6843 VecIdx = 0;
6844 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
6845 }
6846
6847 return std::pair<unsigned, int>{VecIdx, ElemIdx};
6848 });
6849
6850 case X86::BI__builtin_ia32_alignd128:
6851 case X86::BI__builtin_ia32_alignd256:
6852 case X86::BI__builtin_ia32_alignd512:
6853 case X86::BI__builtin_ia32_alignq128:
6854 case X86::BI__builtin_ia32_alignq256:
6855 case X86::BI__builtin_ia32_alignq512: {
6856 unsigned NumElems = Call->getType()->castAs<VectorType>()->getNumElements();
6858 S, OpPC, Call, [NumElems](unsigned DstIdx, unsigned Shift) {
6859 unsigned Imm = Shift & 0xFF;
6860 unsigned EffectiveShift = Imm & (NumElems - 1);
6861 unsigned SourcePos = DstIdx + EffectiveShift;
6862 unsigned VecIdx = SourcePos < NumElems ? 1u : 0u;
6863 unsigned ElemIdx = SourcePos & (NumElems - 1);
6864 return std::pair<unsigned, int>{VecIdx, static_cast<int>(ElemIdx)};
6865 });
6866 }
6867
6868 case clang::X86::BI__builtin_ia32_minps:
6869 case clang::X86::BI__builtin_ia32_minpd:
6870 case clang::X86::BI__builtin_ia32_minph128:
6871 case clang::X86::BI__builtin_ia32_minph256:
6872 case clang::X86::BI__builtin_ia32_minps256:
6873 case clang::X86::BI__builtin_ia32_minpd256:
6874 case clang::X86::BI__builtin_ia32_minps512:
6875 case clang::X86::BI__builtin_ia32_minpd512:
6876 case clang::X86::BI__builtin_ia32_minph512:
6878 S, OpPC, Call,
6879 [](const APFloat &A, const APFloat &B,
6880 std::optional<APSInt>) -> std::optional<APFloat> {
6881 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
6882 B.isInfinity() || B.isDenormal())
6883 return std::nullopt;
6884 if (A.isZero() && B.isZero())
6885 return B;
6886 return llvm::minimum(A, B);
6887 });
6888
6889 case clang::X86::BI__builtin_ia32_minss:
6890 case clang::X86::BI__builtin_ia32_minsd:
6892 S, OpPC, Call,
6893 [](const APFloat &A, const APFloat &B,
6894 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
6895 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/true);
6896 },
6897 /*IsScalar=*/true);
6898
6899 case clang::X86::BI__builtin_ia32_minsd_round_mask:
6900 case clang::X86::BI__builtin_ia32_minss_round_mask:
6901 case clang::X86::BI__builtin_ia32_minsh_round_mask:
6902 case clang::X86::BI__builtin_ia32_maxsd_round_mask:
6903 case clang::X86::BI__builtin_ia32_maxss_round_mask:
6904 case clang::X86::BI__builtin_ia32_maxsh_round_mask: {
6905 bool IsMin = BuiltinID == clang::X86::BI__builtin_ia32_minsd_round_mask ||
6906 BuiltinID == clang::X86::BI__builtin_ia32_minss_round_mask ||
6907 BuiltinID == clang::X86::BI__builtin_ia32_minsh_round_mask;
6909 S, OpPC, Call,
6910 [IsMin](const APFloat &A, const APFloat &B,
6911 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
6912 return EvalScalarMinMaxFp(A, B, RoundingMode, IsMin);
6913 });
6914 }
6915
6916 case clang::X86::BI__builtin_ia32_maxps:
6917 case clang::X86::BI__builtin_ia32_maxpd:
6918 case clang::X86::BI__builtin_ia32_maxph128:
6919 case clang::X86::BI__builtin_ia32_maxph256:
6920 case clang::X86::BI__builtin_ia32_maxps256:
6921 case clang::X86::BI__builtin_ia32_maxpd256:
6922 case clang::X86::BI__builtin_ia32_maxps512:
6923 case clang::X86::BI__builtin_ia32_maxpd512:
6924 case clang::X86::BI__builtin_ia32_maxph512:
6926 S, OpPC, Call,
6927 [](const APFloat &A, const APFloat &B,
6928 std::optional<APSInt>) -> std::optional<APFloat> {
6929 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
6930 B.isInfinity() || B.isDenormal())
6931 return std::nullopt;
6932 if (A.isZero() && B.isZero())
6933 return B;
6934 return llvm::maximum(A, B);
6935 });
6936
6937 case clang::X86::BI__builtin_ia32_maxss:
6938 case clang::X86::BI__builtin_ia32_maxsd:
6940 S, OpPC, Call,
6941 [](const APFloat &A, const APFloat &B,
6942 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
6943 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/false);
6944 },
6945 /*IsScalar=*/true);
6946 case X86::BI__builtin_ia32_vpdpwssd128:
6947 case X86::BI__builtin_ia32_vpdpwssd256:
6948 case X86::BI__builtin_ia32_vpdpwssd512:
6949 case X86::BI__builtin_ia32_vpdpbusd128:
6950 case X86::BI__builtin_ia32_vpdpbusd256:
6951 case X86::BI__builtin_ia32_vpdpbusd512:
6952 return interp__builtin_ia32_vpdp(S, OpPC, Call, false);
6953 case X86::BI__builtin_ia32_vpdpwssds128:
6954 case X86::BI__builtin_ia32_vpdpwssds256:
6955 case X86::BI__builtin_ia32_vpdpwssds512:
6956 case X86::BI__builtin_ia32_vpdpbusds128:
6957 case X86::BI__builtin_ia32_vpdpbusds256:
6958 case X86::BI__builtin_ia32_vpdpbusds512:
6959 return interp__builtin_ia32_vpdp(S, OpPC, Call, true);
6960 case X86::BI__builtin_ia32_cvtss2si:
6961 case X86::BI__builtin_ia32_cvtsd2si:
6962 case X86::BI__builtin_ia32_cvttss2si:
6963 case X86::BI__builtin_ia32_cvttsd2si:
6964 case X86::BI__builtin_ia32_cvtss2si64:
6965 case X86::BI__builtin_ia32_cvtsd2si64:
6966 case X86::BI__builtin_ia32_cvttss2si64:
6967 case X86::BI__builtin_ia32_cvttsd2si64:
6969 case X86::BI__builtin_ia32_cvtpd2dq:
6970 case X86::BI__builtin_ia32_cvttpd2dq:
6971 case X86::BI__builtin_ia32_cvtps2dq:
6972 case X86::BI__builtin_ia32_cvtpd2dq256:
6973 case X86::BI__builtin_ia32_cvtps2dq256:
6974 case X86::BI__builtin_ia32_cvttps2dq:
6975 case X86::BI__builtin_ia32_cvttpd2dq256:
6976 case X86::BI__builtin_ia32_cvttps2dq256:
6978
6979 case Builtin::BI__builtin_meta_is_type:
6980 return interp__builtin_meta_is_type(S, OpPC, Call);
6981
6982 default:
6983 return Invalid(S, OpPC);
6984 }
6985
6986 llvm_unreachable("Unhandled builtin ID");
6987}
6988
6990 ArrayRef<int64_t> ArrayIndices, int64_t &IntResult) {
6993 unsigned N = E->getNumComponents();
6994 assert(N > 0);
6995
6996 unsigned ArrayIndex = 0;
6997 QualType CurrentType = E->getTypeSourceInfo()->getType();
6998 for (unsigned I = 0; I != N; ++I) {
6999 const OffsetOfNode &Node = E->getComponent(I);
7000 switch (Node.getKind()) {
7001 case OffsetOfNode::Field: {
7002 const FieldDecl *MemberDecl = Node.getField();
7003 const auto *RD = CurrentType->getAsRecordDecl();
7004 if (!RD || RD->isInvalidDecl())
7005 return false;
7007 unsigned FieldIndex = MemberDecl->getFieldIndex();
7008 assert(FieldIndex < RL.getFieldCount() && "offsetof field in wrong type");
7009 Result +=
7011 CurrentType = MemberDecl->getType().getNonReferenceType();
7012 break;
7013 }
7014 case OffsetOfNode::Array: {
7015 // When generating bytecode, we put all the index expressions as Sint64 on
7016 // the stack.
7017 int64_t Index = ArrayIndices[ArrayIndex];
7018 if (Index < 0)
7019 return Invalid(S, OpPC);
7020 const ArrayType *AT = S.getASTContext().getAsArrayType(CurrentType);
7021 if (!AT)
7022 return false;
7023 CurrentType = AT->getElementType();
7024 CharUnits ElementSize = S.getASTContext().getTypeSizeInChars(CurrentType);
7025 int64_t ElemSize = ElementSize.getQuantity();
7026 if (Index != 0 && ElemSize > (llvm::maxIntN(64) / Index)) {
7027 S.FFDiag(S.Current->getLocation(OpPC),
7028 diag::note_constexpr_offsetof_overflow)
7029 << S.Current->getRange(OpPC);
7030 return false;
7031 }
7032 int64_t Offset = Index * ElemSize;
7033 if (Result.getQuantity() > llvm::maxIntN(64) - Offset) {
7034 S.FFDiag(S.Current->getLocation(OpPC),
7035 diag::note_constexpr_offsetof_overflow)
7036 << S.Current->getRange(OpPC);
7037 return false;
7038 }
7040 ++ArrayIndex;
7041 break;
7042 }
7043 case OffsetOfNode::Base: {
7044 const CXXBaseSpecifier *BaseSpec = Node.getBase();
7045 if (BaseSpec->isVirtual())
7046 return false;
7047
7048 // Find the layout of the class whose base we are looking into.
7049 const auto *RD = CurrentType->getAsCXXRecordDecl();
7050 if (!RD || RD->isInvalidDecl())
7051 return false;
7053
7054 // Find the base class itself.
7055 CurrentType = BaseSpec->getType();
7056 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
7057 if (!BaseRD)
7058 return false;
7059
7060 // Add the offset to the base.
7061 Result += RL.getBaseClassOffset(BaseRD);
7062 break;
7063 }
7065 llvm_unreachable("Dependent OffsetOfExpr?");
7066 }
7067 }
7068
7069 IntResult = Result.getQuantity();
7070
7071 return true;
7072}
7073
7075 const Pointer &Ptr, const APSInt &IntValue) {
7076
7077 const Record *R = Ptr.getRecord();
7078 assert(R);
7079 assert(R->getNumFields() == 1);
7080
7081 unsigned FieldOffset = R->getField(0u)->Offset;
7082 PtrView FieldPtr = Ptr.view().atField(FieldOffset);
7083 PrimType FieldT = FieldPtr.getFieldDesc()->getPrimType();
7084
7085 INT_TYPE_SWITCH(FieldT,
7086 FieldPtr.deref<T>() = T::from(IntValue.getSExtValue()));
7087 FieldPtr.initialize();
7088 return true;
7089}
7090
7091static void zeroAll(PtrView Dest) {
7092 const Descriptor *Desc = Dest.getFieldDesc();
7093
7094 if (Desc->isPrimitive()) {
7095 TYPE_SWITCH(Desc->getPrimType(), {
7096 Dest.deref<T>().~T();
7097 new (&Dest.deref<T>()) T();
7098 });
7099 return;
7100 }
7101
7102 if (Desc->isRecord()) {
7103 const Record *R = Desc->ElemRecord;
7104 for (const Record::Field &F : R->fields()) {
7105 PtrView FieldPtr = Dest.atField(F.Offset);
7106 zeroAll(FieldPtr);
7107 }
7108 return;
7109 }
7110
7111 if (Desc->isPrimitiveArray()) {
7112 for (unsigned I = 0, N = Desc->getNumElems(); I != N; ++I) {
7113 TYPE_SWITCH(Desc->getPrimType(), {
7114 Dest.elem<T>(I).~T();
7115 new (&Dest.elem<T>(I)) T();
7116 });
7117 }
7118 return;
7119 }
7120
7121 if (Desc->isCompositeArray()) {
7122 for (unsigned I = 0, N = Desc->getNumElems(); I != N; ++I) {
7123 PtrView ElemPtr = Dest.atIndex(I).narrow();
7124 zeroAll(ElemPtr);
7125 }
7126 return;
7127 }
7128}
7129
7130static bool copyComposite(InterpState &S, CodePtr OpPC, PtrView Src,
7131 PtrView Dest, bool Activate, bool Diagnose);
7132static bool copyRecord(InterpState &S, CodePtr OpPC, PtrView Src, PtrView Dest,
7133 bool Activate = false, bool Diagnose = true) {
7134 [[maybe_unused]] const Descriptor *SrcDesc = Src.getFieldDesc();
7135 const Descriptor *DestDesc = Dest.getFieldDesc();
7136
7137 auto copyField = [&](const Record::Field &F, bool Activate) -> bool {
7138 PtrView DestField = Dest.atField(F.Offset);
7139 PtrView SrcField = Src.atField(F.Offset);
7140
7141 if (OptPrimType FT = F.T) {
7142 if (!SrcField.isInitialized()) {
7143 if (Diagnose)
7144 return diagnoseUninitialized(S, OpPC, false, SrcField.block(),
7145 SrcField.getLifetime(), AK_Read);
7146 // Just skip.
7147 return true;
7148 }
7149
7150 TYPE_SWITCH(*FT, DestField.deref<T>() = SrcField.deref<T>(););
7151 DestField.initialize();
7152 if (Activate)
7153 DestField.activate();
7154 return true;
7155 }
7156
7157 return copyComposite(S, OpPC, SrcField, DestField, Activate, Diagnose);
7158 };
7159
7160 assert(SrcDesc->isRecord());
7161 assert(SrcDesc->ElemRecord == DestDesc->ElemRecord);
7162 const Record *R = DestDesc->ElemRecord;
7163 for (const Record::Field &F : R->fields()) {
7164 PtrView FP = Src.atField(F.Offset);
7165
7166 if (!CheckMutable(S, OpPC, FP))
7167 return false;
7168
7169 if (R->isUnion()) {
7170 // For unions, only copy the active field. Zero all others.
7171 if (FP.isActive()) {
7172 if (!copyField(F, /*Activate=*/true))
7173 return false;
7174 } else {
7175 PtrView DestField = Dest.atField(F.Offset);
7176 zeroAll(DestField);
7177 }
7178 } else {
7179 if (!copyField(F, Activate))
7180 return false;
7181 }
7182 }
7183
7184 for (const Record::Base &B : R->bases()) {
7185 PtrView DestBase = Dest.atField(B.Offset);
7186 if (!copyRecord(S, OpPC, Src.atField(B.Offset), DestBase, Activate,
7187 Diagnose))
7188 return false;
7189 }
7190
7191 Dest.initialize();
7192 if (Activate)
7193 Dest.activate();
7194 return true;
7195}
7196
7197static bool copyComposite(InterpState &S, CodePtr OpPC, PtrView Src,
7198 PtrView Dest, bool Activate = false,
7199 bool Diagnose = false) {
7200 assert(Src.isLive() && Dest.isLive());
7201
7202 [[maybe_unused]] const Descriptor *SrcDesc = Src.getFieldDesc();
7203 const Descriptor *DestDesc = Dest.getFieldDesc();
7204
7205 assert(!DestDesc->isPrimitive() && !SrcDesc->isPrimitive());
7206
7207 if (DestDesc->isPrimitiveArray()) {
7208 if (!SrcDesc->isPrimitiveArray())
7209 return false;
7210 // For floating types, check the actual QualType so we don't accidentally
7211 // mix up semantics.
7212 if (SrcDesc->getPrimType() == PT_Float) {
7213 if (!S.getASTContext().hasSimilarType(SrcDesc->getElemQualType(),
7214 DestDesc->getElemQualType()))
7215 return false;
7216 }
7217
7218 assert(SrcDesc->isPrimitiveArray());
7219 assert(SrcDesc->getNumElems() == DestDesc->getNumElems());
7220 assert(SrcDesc->getPrimType() == DestDesc->getPrimType());
7221 PrimType ET = DestDesc->getPrimType();
7222 for (unsigned I = 0, N = DestDesc->getNumElems(); I != N; ++I) {
7223 PtrView DestElem = Dest.atIndex(I);
7224 TYPE_SWITCH(ET, { DestElem.deref<T>() = Src.elem<T>(I); });
7225 DestElem.initializeElement(I);
7226 }
7227 return true;
7228 }
7229
7230 if (DestDesc->isCompositeArray()) {
7231 if (!SrcDesc->isCompositeArray())
7232 return false;
7233 assert(SrcDesc->isCompositeArray());
7234 assert(SrcDesc->getNumElems() == DestDesc->getNumElems());
7235 for (unsigned I = 0, N = DestDesc->getNumElems(); I != N; ++I) {
7236 PtrView SrcElem = Src.atIndex(I).narrow();
7237 PtrView DestElem = Dest.atIndex(I).narrow();
7238 if (!copyComposite(S, OpPC, SrcElem, DestElem, Activate))
7239 return false;
7240 }
7241 return true;
7242 }
7243
7244 if (DestDesc->isRecord()) {
7245 if (!SrcDesc->isRecord())
7246 return false;
7247 return copyRecord(S, OpPC, Src, Dest, Activate, Diagnose);
7248 }
7249 return Invalid(S, OpPC);
7250}
7251
7252bool DoMemcpy(InterpState &S, CodePtr OpPC, const Pointer &Src, Pointer &Dest,
7253 bool Activate, bool Diagnose) {
7254 if (!Src.isBlockPointer() || Src.getFieldDesc()->isPrimitive())
7255 return false;
7256 if (!Dest.isBlockPointer() || Dest.getFieldDesc()->isPrimitive())
7257 return false;
7258
7259 return copyComposite(S, OpPC, Src.view(), Dest.view(), Activate, Diagnose);
7260}
7261
7262} // namespace interp
7263} // namespace clang
Defines the clang::ASTContext interface.
#define V(N, I)
Defines enum values for all the target-independent builtin functions.
llvm::APSInt APSInt
Definition Compiler.cpp:26
Defines the clang::Expr interface and subclasses for C++ expressions.
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC's builtin.
std::optional< APFloat > EvalScalarMinMaxFp(const APFloat &A, const APFloat &B, std::optional< APSInt > RoundingMode, bool IsMin)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
GCCTypeClass EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts)
EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way as GCC.
static bool isOneByteCharacterType(QualType T)
uint8_t GFNIMul(uint8_t AByte, uint8_t BByte)
uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm, bool Inverse)
APSInt NormalizeRotateAmount(const APSInt &Value, const APSInt &Amount)
#define X(type, name)
Definition Value.h:97
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
#define FIXED_SIZE_INT_TYPE_SWITCH(Expr, B)
Definition PrimType.h:281
#define INT_TYPE_SWITCH_NO_BOOL(Expr, B)
Definition PrimType.h:297
#define INT_TYPE_SWITCH(Expr, B)
Definition PrimType.h:262
#define TYPE_SWITCH(Expr, B)
Definition PrimType.h:240
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static QualType getPointeeType(const MemRegion *R)
Enumerates target-specific builtins in their own namespaces within namespace clang.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
CanQualType FloatTy
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
Builtin::Context & BuiltinInfo
Definition ASTContext.h:857
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
QualType getWCharType() const
Return the unique wchar_t type available in C++ (and available as __wchar_t as a Microsoft extension)...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
void recordOffsetOfEvaluation(const OffsetOfExpr *E)
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:974
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
CanQualType HalfTy
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
llvm::SmallString< 64 > getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:99
Represents a base class of a C++ class.
Definition DeclCXX.h:146
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:177
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
CharUnits alignTo(CharUnits Align) const
Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is a multiple...
Definition CharUnits.h:171
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
static constexpr CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:376
This represents one expression.
Definition Expr.h:114
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
Represents a member of a struct/union/class.
Definition Decl.h:3341
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3426
Represents a function declaration or definition.
Definition Decl.h:2082
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
std::optional< llvm::AllocTokenMode > AllocTokenMode
The allocation token mode.
std::optional< uint64_t > AllocTokenMax
Maximum number of allocation tokens (0 = target SIZE_MAX), nullopt if none set (use target SIZE_MAX).
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2596
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2643
TypeSourceInfo * getTypeSourceInfo() const
Definition Expr.h:2636
unsigned getNumComponents() const
Definition Expr.h:2651
Helper class for OffsetOfExpr.
Definition Expr.h:2490
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2554
@ Array
An index into an array.
Definition Expr.h:2495
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2499
@ Field
A field.
Definition Expr.h:2497
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition Expr.h:2502
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2544
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition Expr.h:2564
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:3099
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8763
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
StringRef getString() const
Definition Expr.h:1912
bool isOrdinary() const
Definition Expr.h:1977
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:854
bool isBigEndian() const
virtual int getEHDataRegisterNumber(unsigned RegNo) const
Return the register number that __builtin_eh_return_regno would return with the specified argument.
virtual bool isNan2008() const
Returns true if NaN encoding is IEEE 754-2008.
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8560
bool isBooleanType() const
Definition TypeBase.h:9341
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2417
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2485
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9484
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2662
bool isVectorType() const
Definition TypeBase.h:8954
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2535
bool isFloatingType() const
Definition Type.cpp:2519
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2462
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
Represents a GCC generic vector type.
Definition TypeBase.h:4398
unsigned getNumElements() const
Definition TypeBase.h:4413
QualType getElementType() const
Definition TypeBase.h:4412
A memory block, either on the stack or in the heap.
Definition Block.h:68
const Descriptor * getDescriptor() const
Returns the block's descriptor.
Definition Block.h:103
bool isDynamic() const
Definition Block.h:111
Wrapper around boolean types.
Definition Boolean.h:23
static Boolean from(T Value)
Definition Boolean.h:95
Pointer into the code segment.
Definition Source.h:31
const LangOptions & getLangOpts() const
Returns the language options.
Definition Context.cpp:490
OptPrimType classify(QualType T) const
Classifies a type.
Definition Context.cpp:524
bool canClassify(QualType T) const
Definition Context.h:138
unsigned getEvalID() const
Definition Context.h:190
Manages dynamic memory allocations done during bytecode interpretation.
std::optional< Form > getAllocationForm(const Expr *Source) const
Checks whether the allocation done at the given source is an array allocation.
Block * allocate(const Descriptor *D, unsigned EvalID, Form AllocForm)
Allocate ONE element of the given descriptor.
bool deallocate(const Expr *Source, const Block *BlockToDelete)
Deallocate the given source+block combination.
If a Floating is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition Floating.h:35
void copy(const APFloat &F)
Definition Floating.h:123
llvm::FPClassTest classify() const
Definition Floating.h:154
bool isSignaling() const
Definition Floating.h:149
bool isNormal() const
Definition Floating.h:152
ComparisonCategoryResult compare(const Floating &RHS) const
Definition Floating.h:157
bool isZero() const
Definition Floating.h:144
bool isNegative() const
Definition Floating.h:143
bool isFinite() const
Definition Floating.h:151
bool isDenormal() const
Definition Floating.h:153
APFloat::fltCategory getCategory() const
Definition Floating.h:155
APFloat getAPFloat() const
Definition Floating.h:64
Base class for stack frames, shared between VM and walker.
Definition Frame.h:28
virtual const FunctionDecl * getCallee() const =0
Returns the called function's declaration.
If an IntegralAP is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition IntegralAP.h:36
Frame storing local variables.
Definition InterpFrame.h:27
SourceLocation getLocation(CodePtr PC) const
InterpFrame * Caller
The frame of the previous function.
SourceInfo getSource(CodePtr PC) const
Map a location to a source.
SourceRange getRange(CodePtr PC) const
const Expr * getExpr(CodePtr PC) const
const FunctionDecl * getCallee() const override
Returns the caller.
Stack frame storing temporaries and parameters.
Definition InterpStack.h:26
T pop()
Returns the value from the top of the stack and removes it.
Definition InterpStack.h:40
void push(Tys &&...Args)
Constructs a value in place on the top of the stack.
Definition InterpStack.h:34
void discard()
Discards the top value from the stack.
Definition InterpStack.h:51
T & peek() const
Returns a reference to the value on the top of the stack.
Definition InterpStack.h:64
Interpreter context.
Definition InterpState.h:47
Context & getContext() const
Definition InterpState.h:93
bool initializingBlock(const Block *B) const
DynamicAllocator & getAllocator()
Definition InterpState.h:97
Context & Ctx
Interpreter Context.
Floating allocFloat(const llvm::fltSemantics &Sem)
InterpStack & Stk
Temporary stack.
const VarDecl * EvaluatingDecl
Declaration we're initializing/evaluting, if any.
InterpFrame * Current
The current frame.
T allocAP(unsigned BitWidth)
StdAllocatorCaller getStdAllocatorCaller(StringRef Name) const
Program & P
Reference to the module containing all bytecode.
PrimType value_or(PrimType PT) const
Definition PrimType.h:90
A pointer to a memory block, live or dead.
Definition Pointer.h:544
Pointer stripBaseCasts() const
Strip base casts from this Pointer.
Definition Pointer.h:1282
T loadElem(unsigned I) const
Definition Pointer.h:1155
Pointer atIndex(uint64_t Idx) const
Offsets a pointer inside an array.
Definition Pointer.h:613
bool isDummy() const
Checks if the pointer points to a dummy value.
Definition Pointer.h:959
int64_t getIndex() const
Returns the index into an array.
Definition Pointer.h:1028
bool isOpaquePointer() const
Definition Pointer.h:875
bool isStringPointer() const
Definition Pointer.h:874
T & deref() const
Dereferences the pointer, if it's live.
Definition Pointer.h:1106
unsigned getNumElems() const
Returns the number of elements.
Definition Pointer.h:996
bool isUnknownSizeArray() const
Checks if the structure is an array of unknown size.
Definition Pointer.h:820
bool isIntegralPointer() const
Definition Pointer.h:871
QualType getType() const
Returns the type of the innermost field.
Definition Pointer.h:724
void initializeAllElements() const
Initialize all elements of a primitive array at once.
Definition Pointer.cpp:861
void initialize() const
Initializes a field.
Definition Pointer.h:1210
bool isLive() const
Checks if the pointer is live.
Definition Pointer.h:672
bool inArray() const
Checks if the innermost field is an array.
Definition Pointer.h:793
const StringPointer & asStringPointer() const
Definition Pointer.h:861
T & elem(unsigned I) const
Dereferences the element at index I.
Definition Pointer.h:1144
uint64_t getByteOffset() const
Returns the byte offset from the start.
Definition Pointer.h:989
std::string toDiagnosticString(const ASTContext &Ctx) const
Converts the pointer to a string usable in diagnostics.
Definition Pointer.cpp:713
bool isZero() const
Checks if the pointer is null.
Definition Pointer.h:656
bool isConstexprUnknown() const
Definition Pointer.h:1182
static bool pointToSameBlock(const Pointer &A, const Pointer &B)
Checks if both given pointers point to the same block.
Definition Pointer.cpp:996
bool isOnePastEnd() const
Checks if the index is one past end.
Definition Pointer.h:1043
uint64_t getIntegerRepresentation() const
Definition Pointer.h:595
Pointer expand() const
Expands a pointer to the containing array, undoing narrowing.
Definition Pointer.h:649
bool isBlockPointer() const
Definition Pointer.h:870
bool isFunctionPointer() const
Definition Pointer.h:872
bool isReadablePointerType() const
Definition Pointer.h:1205
const Descriptor * getFieldDesc() const
Accessors for information about the innermost field.
Definition Pointer.h:714
PtrView view() const
Definition Pointer.h:603
bool isElementInitialized(unsigned Index) const
Like isInitialized(), but for primitive arrays.
Definition Pointer.h:1232
Descriptor * createDescriptor(DeclOrExpr D, PrimType T, const Type *SourceTy=nullptr, bool IsConst=false, bool IsTemporary=false, bool IsMutable=false, bool IsVolatile=false)
Creates a descriptor for a primitive type.
Definition Program.h:116
Structure/Class descriptor.
Definition Record.h:27
Describes the statement/declaration an opcode was generated from.
Definition Source.h:77
EvaluationMode EvalMode
Definition State.h:193
OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId)
Add a note to a prior diagnostic.
Definition State.cpp:86
Expr::EvalStatus & getEvalStatus() const
Definition State.h:91
DiagnosticBuilder report(SourceLocation Loc, diag::kind DiagId)
Directly reports a diagnostic message.
Definition State.cpp:98
OptionalDiagnostic FFDiag(SourceLocation Loc, diag::kind DiagId=diag::note_invalid_subexpr_in_const_expr, unsigned ExtraNotes=0)
Diagnose that the evaluation could not be folded (FF => FoldFailure)
Definition State.cpp:37
ASTContext & getASTContext() const
Definition State.h:92
OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId=diag::note_invalid_subexpr_in_const_expr, unsigned ExtraNotes=0)
Diagnose that the evaluation does not produce a C++11 core constant expression.
Definition State.cpp:60
const LangOptions & getLangOpts() const
Definition State.h:94
bool checkingPotentialConstantExpression() const
Are we checking whether the expression is a potential constant expression?
Definition State.h:125
Defines the clang::TargetInfo interface.
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
Definition OSLog.cpp:192
std::optional< llvm::AllocTokenMetadata > getAllocTokenMetadata(QualType T, const ASTContext &Ctx)
Get the information required for construction of an allocation token ID.
QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE)
Infer the possible allocated type from an allocation call expression.
static bool isNoopBuiltin(unsigned ID)
static bool interp__builtin_is_within_lifetime(InterpState &S, CodePtr OpPC, const CallExpr *Call)
static bool interp__builtin_ia32_shuffle_generic(InterpState &S, CodePtr OpPC, const CallExpr *Call, llvm::function_ref< std::pair< unsigned, int >(unsigned, const APInt &)> GetSourceIndex)
static bool interp__builtin_ia32_phminposuw(InterpState &S, CodePtr OpPC, const CallExpr *Call)
bool CheckRange(InterpState &S, CodePtr OpPC, const Pointer &Ptr, CheckSubobjectKind CSK)
Checks if a field from which a pointer is going to be derived is valid.
Definition Interp.cpp:607
static bool interp__builtin_ia32_mpsadbw(InterpState &S, CodePtr OpPC, const CallExpr *Call)
static bool interp_builtin_ia32_cvt_vector_to_int(InterpState &S, CodePtr OpPC, const CallExpr *E)
static void assignIntegral(InterpState &S, const Pointer &Dest, PrimType ValueT, const APSInt &Value)
bool readPointerToBuffer(const Context &Ctx, const Pointer &FromPtr, BitcastBuffer &Buffer, bool ReturnOnUninit)
static CharUnits getBaseAlignment(const ASTContext &ASTCtx, const Pointer &Ptr)
Returns the alignment of the object Ptr points into.
static Floating abs(InterpState &S, const Floating &In)
static bool interp__builtin_fmax(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, bool IsNumBuiltin)
static bool interp__builtin_elementwise_maxmin(InterpState &S, CodePtr OpPC, const CallExpr *Call, unsigned BuiltinID)
bool arrayElemPtrOpaque(InterpState &S, CodePtr OpPC, const Pointer &Ptr, APSInt &&Index, bool AllowReplace)
Definition Interp.cpp:3587
static bool interp__builtin_ia32_select(InterpState &S, CodePtr OpPC, const CallExpr *Call)
AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
static bool interp__builtin_bswap(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_elementwise_triop(InterpState &S, CodePtr OpPC, const CallExpr *Call, llvm::function_ref< APInt(const APSInt &, const APSInt &, const APSInt &)> Fn)
bool handleOverflow(InterpState &S, CodePtr OpPC, const T &SrcValue)
static bool interp__builtin_assume(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
bool CheckNewDeleteForms(InterpState &S, CodePtr OpPC, DynamicAllocator::Form AllocForm, DynamicAllocator::Form DeleteForm, const Descriptor *D, const Expr *NewExpr)
Diagnose mismatched new[]/delete or new/delete[] pairs.
Definition Interp.cpp:1345
static bool interp__builtin_ia32_insert_subvector(InterpState &S, CodePtr OpPC, const CallExpr *Call, unsigned ID)
static bool interp__builtin_ia32_shift_with_count(InterpState &S, CodePtr OpPC, const CallExpr *Call, llvm::function_ref< APInt(const APInt &, uint64_t)> ShiftOp, llvm::function_ref< APInt(const APInt &, unsigned)> OverflowOp)
static bool interp__builtin_isnan(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
Defined as __builtin_isnan(...), to accommodate the fact that it can take a float,...
static llvm::RoundingMode getRoundingMode(FPOptions FPO)
static bool interp__builtin_ia32_crc32(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, unsigned DataBytes)
static bool interp__builtin_elementwise_countzeroes(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, unsigned BuiltinID)
Can be called with an integer or vector as the first and only parameter.
bool Call(InterpState &S, CodePtr OpPC, const Function *Func, uint32_t VarArgSize)
Definition Interp.cpp:2131
static bool interp__builtin_classify_type(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_fmin(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, bool IsNumBuiltin)
static bool interp__builtin_meta_is_type(InterpState &S, CodePtr OpPC, const CallExpr *)
bool SetThreeWayComparisonField(InterpState &S, CodePtr OpPC, const Pointer &Ptr, const APSInt &IntValue)
Sets the given integral value to the pointer, which is of a std::{weak,partial,strong}...
static bool interp__builtin_elementwise_fp_binop(InterpState &S, CodePtr OpPC, const CallExpr *Call, llvm::function_ref< std::optional< APFloat >(const APFloat &, const APFloat &, std::optional< APSInt > RoundingMode)> Fn, bool IsScalar=false)
static bool interp__builtin_operator_delete(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_fabs(InterpState &S, CodePtr OpPC, const InterpFrame *Frame)
static bool interp__builtin_object_size(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, bool IsDynamic)
static bool interp__builtin_ia32_vpconflict(InterpState &S, CodePtr OpPC, const CallExpr *Call)
static bool interp__builtin_memcmp(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, unsigned ID)
static bool interp__builtin_atomic_lock_free(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, unsigned BuiltinOp)
bool __atomic_always_lock_free(size_t, void const volatile*) bool __atomic_is_lock_free(size_t,...
static llvm::APSInt convertBoolVectorToInt(const Pointer &Val)
constexpr bool isSignedType(PrimType T)
Definition PrimType.h:61
static bool interp__builtin_move(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
bool Error(InterpState &S)
Do nothing and just abort execution.
Definition Interp.h:3771
static bool interp__builtin_clz(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, unsigned BuiltinOp)
static bool interp__builtin_is_aligned_up_down(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, unsigned BuiltinOp)
__builtin_is_aligned() __builtin_align_up() __builtin_align_down() The first parameter is either an i...
static bool interp__builtin_ia32_select_scalar(InterpState &S, const CallExpr *Call)
Scalar variant of AVX512 predicated select: Result[i] = (Mask bit 0) ?
static bool interp__builtin_ia32_addsub(InterpState &S, CodePtr OpPC, const CallExpr *Call)
static bool popToUInt64(const InterpState &S, const Expr *E, uint64_t &Out)
static bool isOneByteCharacterType(QualType T)
Determine if T is a character type for which we guarantee that sizeof(T) == 1.
static bool interp__builtin_strcmp(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, unsigned ID)
static bool interp__builtin_ia32_cmp_mask(InterpState &S, CodePtr OpPC, const CallExpr *Call, unsigned ID, bool IsUnsigned)
static bool interp__builtin_overflowop(InterpState &S, CodePtr OpPC, const CallExpr *Call, unsigned BuiltinOp)
static bool isReadable(const Pointer &P)
Check for common reasons a pointer can't be read from, which are usually not diagnosed in a builtin f...
static bool interp__builtin_inf(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_ia32_dbpsadbw(InterpState &S, CodePtr OpPC, const CallExpr *Call)
static bool interp__builtin_ia32_test_op(InterpState &S, CodePtr OpPC, const CallExpr *Call, llvm::function_ref< bool(const APInt &A, const APInt &B)> Fn)
static bool interp__builtin_isinf(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, bool CheckSign, const CallExpr *Call)
static bool interp__builtin_os_log_format_buffer_size(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
bool InterpretOffsetOf(InterpState &S, CodePtr OpPC, const OffsetOfExpr *E, ArrayRef< int64_t > ArrayIndices, int64_t &IntResult)
Interpret an offsetof operation.
constexpr bool isIntegerOrBoolType(PrimType T)
Definition PrimType.h:54
llvm::APFloat APFloat
Definition Floating.h:27
static void discard(InterpStack &Stk, PrimType T)
bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK)
Checks if a pointer is live and accessible.
Definition Interp.cpp:484
bool diagnoseUninitialized(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK)
Definition Interp.cpp:767
static bool copyComposite(InterpState &S, CodePtr OpPC, PtrView Src, PtrView Dest, bool Activate, bool Diagnose)
bool CheckStore(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK, bool WillBeActivated)
Checks if a value can be stored in a block.
Definition Interp.cpp:1082
static bool interp__builtin_ia32_pack(InterpState &S, CodePtr, const CallExpr *E, llvm::function_ref< APInt(const APSInt &)> PackFn)
static bool interp__builtin_fpclassify(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
Five int values followed by one floating value.
static bool interp__builtin_abs(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static void zeroAll(PtrView Dest)
static bool interp_floating_comparison(InterpState &S, CodePtr OpPC, const CallExpr *Call, unsigned ID)
llvm::APInt APInt
Definition FixedPoint.h:19
constexpr bool isFixedSizeIntegralType()
Definition PrimType.h:153
static bool interp__builtin_stdc_memreverse8(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_ia32_bmac(InterpState &S, CodePtr OpPC, const CallExpr *Call, bool IsXor)
static bool interp__builtin_ia32_extract_vector(InterpState &S, CodePtr OpPC, const CallExpr *Call, unsigned ID)
static bool interp__builtin_c11_atomic_is_lock_free(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
bool __c11_atomic_is_lock_free(size_t)
static bool interp__builtin_elementwise_int_binop(InterpState &S, CodePtr OpPC, const CallExpr *Call, llvm::function_ref< APInt(const APSInt &, const APSInt &)> Fn)
static bool interp__builtin_issubnormal(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_arithmetic_fence(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_ia32_cvt_mask2vec(InterpState &S, CodePtr OpPC, const CallExpr *Call, unsigned ID)
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:35
static bool interp__builtin_isfinite(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static void noteValueLocation(InterpState &S, const Block *B)
Definition Interp.cpp:219
static bool interp__builtin_ia32_psadbw(InterpState &S, CodePtr OpPC, const CallExpr *Call)
bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const CallExpr *Call, uint32_t BuiltinID)
Interpret a builtin function.
static bool interp__builtin_expect(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_complex(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
__builtin_complex(Float A, float B);
static bool evalICmpImm(uint8_t Imm, const APSInt &A, const APSInt &B, bool IsUnsigned)
static bool interp__builtin_assume_aligned(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
__builtin_assume_aligned(Ptr, Alignment[, ExtraOffset])
static bool interp__builtin_ia32_cvt_vec2mask(InterpState &S, CodePtr OpPC, const CallExpr *Call, unsigned ID)
static bool diagnoseUnreadableObject(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK)
static bool interp__builtin_ptrauth_string_discriminator(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool Activate(InterpState &S)
Definition Interp.h:2276
static bool interp__builtin_memchr(InterpState &S, CodePtr OpPC, const CallExpr *Call, unsigned ID)
bool DoMemcpy(InterpState &S, CodePtr OpPC, const Pointer &Src, Pointer &Dest, bool Activate, bool Diagnose)
Copy the contents of Src into Dest.
static bool interp__builtin_ia32_pmul(InterpState &S, CodePtr OpPC, const CallExpr *Call, llvm::function_ref< APInt(const APSInt &, const APSInt &, const APSInt &, const APSInt &)> Fn)
static void pushInteger(InterpState &S, const APSInt &Val, QualType QT)
Pushes Val on the stack as the type given by QT.
static bool interp__builtin_operator_new(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_strlen(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, unsigned ID)
bool CheckArray(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Checks if the array is offsetable.
Definition Interp.cpp:476
static bool interp__builtin_elementwise_abs(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, unsigned BuiltinID)
static bool interp__builtin_copysign(InterpState &S, CodePtr OpPC, const InterpFrame *Frame)
static bool interp__builtin_iszero(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_addressof(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_ia32_gfni_affine(InterpState &S, CodePtr OpPC, const CallExpr *Call, bool Inverse)
static bool interp__builtin_signbit(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
bool CheckDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK)
Checks if a pointer is a dummy pointer.
Definition Interp.cpp:1417
static bool interp__builtin_ia32_vec_ext(InterpState &S, CodePtr OpPC, const CallExpr *Call, unsigned ID)
static bool interp__builtin_vector_reduce(InterpState &S, CodePtr OpPC, const CallExpr *Call, unsigned ID)
static bool interp__builtin_ia32_movmsk_op(InterpState &S, CodePtr OpPC, const CallExpr *Call)
static bool interp__builtin_memcpy(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, unsigned ID)
static bool interp__builtin_ia32_vec_set(InterpState &S, CodePtr OpPC, const CallExpr *Call, unsigned ID)
static bool popToAPSInt(InterpStack &Stk, PrimType T, APSInt &Out)
static bool interp_builtin_horizontal_fp_binop(InterpState &S, CodePtr OpPC, const CallExpr *Call, llvm::function_ref< APFloat(const APFloat &, const APFloat &, llvm::RoundingMode)> Fn)
static bool interp__builtin_ia32_pclmulqdq(InterpState &S, CodePtr OpPC, const CallExpr *Call)
static bool interp__builtin_elementwise_triop_fp(InterpState &S, CodePtr OpPC, const CallExpr *Call, llvm::function_ref< APFloat(const APFloat &, const APFloat &, const APFloat &, llvm::RoundingMode)> Fn)
bool CheckMutable(InterpState &S, CodePtr OpPC, PtrView Ptr, AccessKinds AK)
Checks if a pointer points to a mutable field.
Definition Interp.cpp:693
static bool interp__builtin_popcount(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_ia32_extract_vector_masked(InterpState &S, CodePtr OpPC, const CallExpr *Call, unsigned ID)
static bool convertDoubleToFloatStrict(const APFloat &Src, Floating &Dst, InterpState &S, const Expr *DiagExpr)
static bool interp__builtin_carryop(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, unsigned BuiltinOp)
Three integral values followed by a pointer (lhs, rhs, carry, carryOut).
bool CheckArraySize(InterpState &S, CodePtr OpPC, uint64_t NumElems)
static bool interp__builtin_scalar_fp_round_mask_binop(InterpState &S, CodePtr OpPC, const CallExpr *Call, llvm::function_ref< std::optional< APFloat >(const APFloat &, const APFloat &, std::optional< APSInt >)> Fn)
static bool interp__builtin_ctz(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, unsigned BuiltinID)
static bool interp__builtin_is_constant_evaluated(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_isfpclass(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
First parameter to __builtin_isfpclass is the floating value, the second one is an integral value.
static bool interp__builtin_ia32_vcvtps2ph(InterpState &S, CodePtr OpPC, const CallExpr *Call)
static bool interp__builtin_issignaling(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_ia32_multishiftqb(InterpState &S, CodePtr OpPC, const CallExpr *Call)
bool CheckLoad(InterpState &S, CodePtr OpPC, PtrView Ptr, AccessKinds AK)
Definition Interp.cpp:933
UnsignedOrNone evaluateBuiltinObjectSize(const ASTContext &ASTCtx, unsigned Kind, Pointer &Ptr, const Expr *E, bool IsDynamic)
Evaluate __builtin_object_size or __builtin_dynamic_object_size for the given pointer and Kind.
static bool interp__builtin_load8(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, bool IsBigEndian, bool IsAligned)
static bool interp__builtin_ia32_shufbitqmb_mask(InterpState &S, CodePtr OpPC, const CallExpr *Call)
static bool interp__builtin_nan(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, bool Signaling)
static bool interp__builtin_elementwise_int_unaryop(InterpState &S, CodePtr OpPC, const CallExpr *Call, llvm::function_ref< APInt(const APSInt &)> Fn)
constexpr bool isIntegerType(PrimType T)
Definition PrimType.h:55
static bool interp__builtin_eh_return_data_regno(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp__builtin_infer_alloc_token(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static bool interp_builtin_horizontal_int_binop(InterpState &S, CodePtr OpPC, const CallExpr *Call, llvm::function_ref< APInt(const APSInt &, const APSInt &)> Fn)
static bool interp__builtin_ia32_cvtsd2ss(InterpState &S, CodePtr OpPC, const CallExpr *Call, bool HasRoundingMask)
static void diagnoseNonConstexprBuiltin(InterpState &S, CodePtr OpPC, unsigned ID)
llvm::APSInt APSInt
Definition FixedPoint.h:20
static bool interp_builtin_ia32_cvt_scalar_to_int(InterpState &S, CodePtr OpPC, const CallExpr *E)
static bool interp__builtin_ia32_gfni_mul(InterpState &S, CodePtr OpPC, const CallExpr *Call)
static bool interp__builtin_ia32_vpdp(InterpState &S, CodePtr OpPC, const CallExpr *Call, bool IsSaturating)
static bool interp__builtin_ia32_addcarry_subborrow(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call, bool IsAdd)
(CarryIn, LHS, RHS, Result)
static QualType getElemType(const Pointer &P)
static bool interp__builtin_ia32_pternlog(InterpState &S, CodePtr OpPC, const CallExpr *Call, bool MaskZ)
static bool copyRecord(InterpState &S, CodePtr OpPC, PtrView Src, PtrView Dest, bool Activate=false, bool Diagnose=true)
static bool interp__builtin_isnormal(InterpState &S, CodePtr OpPC, const InterpFrame *Frame, const CallExpr *Call)
static void swapBytes(std::byte *M, size_t N)
static bool interp__builtin_ia32_cvtpd2ps(InterpState &S, CodePtr OpPC, const CallExpr *Call, bool IsMasked, bool HasRounding)
Top level wrappers for InstallAPI frontend operations.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition State.h:28
@ AK_Read
Definition State.h:29
@ AK_Assign
Definition State.h:31
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
@ Off
Never emit colors regardless of the output stream.
@ ConstantFold
Fold the expression to a constant.
Definition State.h:69
@ ConstantExpressionUnevaluated
Evaluate as a constant expression.
Definition State.h:65
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:58
@ IgnoreSideEffects
Evaluate in any way we know how.
Definition State.h:73
U cast(CodeGen::Address addr)
Definition Address.h:327
int32_t uint32_t uint32_t __builtin_riscv_mhracc_i32 __builtin_riscv_mhraccu_u32 __builtin_riscv_mhraccsu_i32 __builtin_riscv_mhacc_h1_i32 __builtin_riscv_mhaccsu_h1_i32 __builtin_riscv_mulqr_i32 __builtin_riscv_mqrwacc_i64 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 uint16_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:651
Track what bits have been initialized to known values and which ones have indeterminate value.
T deref(Bytes Offset) const
Dereferences the value at the given offset.
std::unique_ptr< std::byte[]> Data
A quantity in bits.
A quantity in bytes.
size_t getQuantity() const
Describes a memory block created by an allocation site.
Definition Descriptor.h:126
unsigned getNumElems() const
Returns the number of elements stored in the block.
Definition Descriptor.h:249
bool isPrimitive() const
Checks if the descriptor is of a primitive.
Definition Descriptor.h:263
QualType getElemQualType() const
bool isCompositeArray() const
Checks if the descriptor is of an array of composites.
Definition Descriptor.h:256
static constexpr unsigned MaxArrayElemBytes
Maximum number of bytes to be used for array elements.
Definition Descriptor.h:146
QualType getType() const
unsigned getElemDataSize() const
Returns the element data size, i.e.
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:254
PrimType getPrimType() const
Definition Descriptor.h:234
bool isRecord() const
Checks if the descriptor is of a record.
Definition Descriptor.h:268
const Record *const ElemRecord
Pointer to the record, if block contains records.
Definition Descriptor.h:150
bool isArray() const
Checks if the descriptor is of an array.
Definition Descriptor.h:266
Mapping from primitive types to their representation.
Definition PrimType.h:164
PtrView atField(unsigned Offset) const
Definition Pointer.h:271
const Descriptor * getFieldDesc() const
Definition Pointer.h:82
PtrView atIndex(unsigned Idx) const
Definition Pointer.h:211
void activate() const
Definition Pointer.cpp:893
PtrView narrow() const
Definition Pointer.h:92
T & elem(unsigned I) const
Definition Pointer.h:253
const Block * block() const
Definition Pointer.h:62
bool isInitialized() const
Definition Pointer.h:299
void initializeElement(unsigned Index) const
Definition Pointer.cpp:844
void initialize() const
Definition Pointer.cpp:817
Lifetime getLifetime() const
Definition Pointer.cpp:763
bool isActive() const
Definition Pointer.h:45
bool isLive() const
Definition Pointer.h:44
T & deref() const
Definition Pointer.h:246
const StringLiteral * getLiteral() const
Definition Pointer.h:397