| 1 | //===--- Context.cpp - Context 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 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "Context.h" |
| 10 | #include "Boolean.h" |
| 11 | #include "ByteCodeEmitter.h" |
| 12 | #include "Char.h" |
| 13 | #include "Compiler.h" |
| 14 | #include "EvalEmitter.h" |
| 15 | #include "Integral.h" |
| 16 | #include "InterpFrame.h" |
| 17 | #include "InterpHelpers.h" |
| 18 | #include "InterpStack.h" |
| 19 | #include "Pointer.h" |
| 20 | #include "PrimType.h" |
| 21 | #include "Program.h" |
| 22 | #include "clang/AST/ASTLambda.h" |
| 23 | #include "clang/AST/Expr.h" |
| 24 | #include "clang/Basic/TargetInfo.h" |
| 25 | |
| 26 | using namespace clang; |
| 27 | using namespace clang::interp; |
| 28 | |
| 29 | Context::Context(ASTContext &Ctx) : Ctx(Ctx), P(new Program(*this)) { |
| 30 | this->ShortWidth = Ctx.getTargetInfo().getShortWidth(); |
| 31 | this->IntWidth = Ctx.getTargetInfo().getIntWidth(); |
| 32 | this->LongWidth = Ctx.getTargetInfo().getLongWidth(); |
| 33 | this->LongLongWidth = Ctx.getTargetInfo().getLongLongWidth(); |
| 34 | assert(Ctx.getTargetInfo().getCharWidth() == 8 && |
| 35 | "We're assuming 8 bit chars" ); |
| 36 | } |
| 37 | |
| 38 | Context::~Context() = default; |
| 39 | |
| 40 | bool Context::isPotentialConstantExpr(State &Parent, const FunctionDecl *FD) { |
| 41 | assert(Stk.empty()); |
| 42 | |
| 43 | // Get a function handle. |
| 44 | const Function *Func = getOrCreateFunction(FuncDecl: FD); |
| 45 | if (!Func) |
| 46 | return false; |
| 47 | |
| 48 | // Compile the function. |
| 49 | Compiler<ByteCodeEmitter>(*this, *P).compileFunc( |
| 50 | FuncDecl: FD, Func: const_cast<Function *>(Func)); |
| 51 | |
| 52 | if (!Func->isValid()) |
| 53 | return false; |
| 54 | |
| 55 | ++EvalID; |
| 56 | // And run it. |
| 57 | return Run(Parent, Func); |
| 58 | } |
| 59 | |
| 60 | void Context::isPotentialConstantExprUnevaluated(State &Parent, const Expr *E, |
| 61 | const FunctionDecl *FD) { |
| 62 | assert(Stk.empty()); |
| 63 | ++EvalID; |
| 64 | size_t StackSizeBefore = Stk.size(); |
| 65 | Compiler<EvalEmitter> C(*this, *P, Parent, Stk); |
| 66 | |
| 67 | if (!C.interpretCall(FD, E)) { |
| 68 | C.cleanup(); |
| 69 | Stk.clearTo(NewSize: StackSizeBefore); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | bool Context::evaluateAsRValue(State &Parent, const Expr *E, APValue &Result) { |
| 74 | ++EvalID; |
| 75 | bool Recursing = !Stk.empty(); |
| 76 | size_t StackSizeBefore = Stk.size(); |
| 77 | Compiler<EvalEmitter> C(*this, *P, Parent, Stk); |
| 78 | |
| 79 | auto Res = C.interpretExpr(E, /*ConvertResultToRValue=*/E->isGLValue()); |
| 80 | |
| 81 | if (Res.isInvalid()) { |
| 82 | C.cleanup(); |
| 83 | Stk.clearTo(NewSize: StackSizeBefore); |
| 84 | return false; |
| 85 | } |
| 86 | |
| 87 | if (!Recursing) { |
| 88 | // We *can* actually get here with a non-empty stack, since |
| 89 | // things like InterpState::noteSideEffect() exist. |
| 90 | C.cleanup(); |
| 91 | #ifndef NDEBUG |
| 92 | // Make sure we don't rely on some value being still alive in |
| 93 | // InterpStack memory. |
| 94 | Stk.clearTo(StackSizeBefore); |
| 95 | #endif |
| 96 | } |
| 97 | |
| 98 | Result = Res.stealAPValue(); |
| 99 | |
| 100 | return true; |
| 101 | } |
| 102 | |
| 103 | bool Context::evaluate(State &Parent, const Expr *E, APValue &Result, |
| 104 | ConstantExprKind Kind) { |
| 105 | ++EvalID; |
| 106 | bool Recursing = !Stk.empty(); |
| 107 | size_t StackSizeBefore = Stk.size(); |
| 108 | Compiler<EvalEmitter> C(*this, *P, Parent, Stk); |
| 109 | |
| 110 | auto Res = C.interpretExpr(E, /*ConvertResultToRValue=*/false, |
| 111 | /*DestroyToplevelScope=*/true); |
| 112 | if (Res.isInvalid()) { |
| 113 | C.cleanup(); |
| 114 | Stk.clearTo(NewSize: StackSizeBefore); |
| 115 | return false; |
| 116 | } |
| 117 | |
| 118 | if (!Recursing) { |
| 119 | assert(Stk.empty()); |
| 120 | C.cleanup(); |
| 121 | #ifndef NDEBUG |
| 122 | // Make sure we don't rely on some value being still alive in |
| 123 | // InterpStack memory. |
| 124 | Stk.clearTo(StackSizeBefore); |
| 125 | #endif |
| 126 | } |
| 127 | |
| 128 | Result = Res.stealAPValue(); |
| 129 | return true; |
| 130 | } |
| 131 | |
| 132 | bool Context::evaluateAsInitializer(State &Parent, const VarDecl *VD, |
| 133 | const Expr *Init, APValue &Result) { |
| 134 | ++EvalID; |
| 135 | bool Recursing = !Stk.empty(); |
| 136 | size_t StackSizeBefore = Stk.size(); |
| 137 | Compiler<EvalEmitter> C(*this, *P, Parent, Stk); |
| 138 | |
| 139 | bool CheckGlobalInitialized = |
| 140 | shouldBeGloballyIndexed(VD) && |
| 141 | (VD->getType()->isRecordType() || VD->getType()->isArrayType()); |
| 142 | auto Res = C.interpretDecl(VD, Init, CheckFullyInitialized: CheckGlobalInitialized); |
| 143 | if (Res.isInvalid()) { |
| 144 | C.cleanup(); |
| 145 | Stk.clearTo(NewSize: StackSizeBefore); |
| 146 | |
| 147 | return false; |
| 148 | } |
| 149 | |
| 150 | if (!Recursing) { |
| 151 | assert(Stk.empty()); |
| 152 | C.cleanup(); |
| 153 | #ifndef NDEBUG |
| 154 | // Make sure we don't rely on some value being still alive in |
| 155 | // InterpStack memory. |
| 156 | Stk.clearTo(StackSizeBefore); |
| 157 | #endif |
| 158 | } |
| 159 | |
| 160 | Result = Res.stealAPValue(); |
| 161 | return true; |
| 162 | } |
| 163 | |
| 164 | bool Context::evaluateDestruction(State &Parent, const VarDecl *VD, |
| 165 | APValue Value) { |
| 166 | assert(Stk.empty()); |
| 167 | Compiler<EvalEmitter> C(*this, *P, Parent, Stk); |
| 168 | |
| 169 | auto Res = C.interpretDestructor(VD, Value); |
| 170 | |
| 171 | if (Res.isInvalid()) { |
| 172 | C.cleanup(); |
| 173 | Stk.clear(); |
| 174 | return false; |
| 175 | } |
| 176 | |
| 177 | assert(Stk.empty()); |
| 178 | |
| 179 | return true; |
| 180 | } |
| 181 | |
| 182 | template <typename ResultT> |
| 183 | bool Context::evaluateStringRepr(State &Parent, const Expr *SizeExpr, |
| 184 | const Expr *PtrExpr, ResultT &Result) { |
| 185 | assert(Stk.empty()); |
| 186 | Compiler<EvalEmitter> C(*this, *P, Parent, Stk); |
| 187 | |
| 188 | // Evaluate size value. |
| 189 | APValue SizeValue; |
| 190 | if (!evaluateAsRValue(Parent, E: SizeExpr, Result&: SizeValue)) |
| 191 | return false; |
| 192 | |
| 193 | if (!SizeValue.isInt()) |
| 194 | return false; |
| 195 | uint64_t Size = SizeValue.getInt().getZExtValue(); |
| 196 | |
| 197 | auto PtrRes = C.interpretAsPointer(E: PtrExpr, PtrCB: [&](InterpState &S, CodePtr OpPC, |
| 198 | const Pointer &Ptr) { |
| 199 | if (Size == 0) { |
| 200 | if constexpr (std::is_same_v<ResultT, APValue>) |
| 201 | Result = APValue(APValue::UninitArray{}, 0, 0); |
| 202 | return true; |
| 203 | } |
| 204 | |
| 205 | if (Ptr.isZero()) { |
| 206 | S.FFDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_access_null) |
| 207 | << AK_Read; |
| 208 | return false; |
| 209 | } |
| 210 | |
| 211 | if (!Ptr.isLive() || !Ptr.isInitialized() || Ptr.isUnknownSizeArray() || |
| 212 | !Ptr.inArray()) |
| 213 | return false; |
| 214 | |
| 215 | // Must be char. |
| 216 | if (Ptr.isBlockPointer() && |
| 217 | Ptr.getFieldDesc()->getElemDataSize() != 1 /*bytes*/) |
| 218 | return false; |
| 219 | if (Ptr.isStringPointer() && |
| 220 | !Ptr.asStringPointer().getLiteral()->isOrdinary()) |
| 221 | return false; |
| 222 | |
| 223 | bool Limited = false; |
| 224 | if (Size > Ptr.getNumElems()) { |
| 225 | S.FFDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_access_past_end) |
| 226 | << AK_Read; |
| 227 | Size = Ptr.getNumElems(); |
| 228 | Limited = true; |
| 229 | } |
| 230 | |
| 231 | if constexpr (std::is_same_v<ResultT, APValue>) { |
| 232 | QualType CharTy = PtrExpr->getType()->getPointeeType(); |
| 233 | Result = APValue(APValue::UninitArray{}, Size, Size); |
| 234 | for (uint64_t I = 0; I != Size; ++I) { |
| 235 | if (std::optional<APValue> ElemVal = |
| 236 | Ptr.atIndex(Idx: I).toRValue(Ctx: *this, ResultType: CharTy)) |
| 237 | Result.getArrayInitializedElt(I) = *ElemVal; |
| 238 | else |
| 239 | return false; |
| 240 | } |
| 241 | } else { |
| 242 | assert((std::is_same_v<ResultT, std::string>)); |
| 243 | if (Size < Result.max_size()) |
| 244 | Result.resize(Size); |
| 245 | |
| 246 | const char *Addr = reinterpret_cast<const char *>(Ptr.getRawAddress()); |
| 247 | |
| 248 | if (Ptr.isStringPointer()) |
| 249 | Result.assign(Addr, Size - static_cast<unsigned>(Limited)); |
| 250 | else |
| 251 | Result.assign(Addr, Size); |
| 252 | } |
| 253 | |
| 254 | return true; |
| 255 | }); |
| 256 | |
| 257 | if (PtrRes.isInvalid()) { |
| 258 | C.cleanup(); |
| 259 | Stk.clear(); |
| 260 | return false; |
| 261 | } |
| 262 | |
| 263 | return true; |
| 264 | } |
| 265 | |
| 266 | bool Context::evaluateCharRange(State &Parent, const Expr *SizeExpr, |
| 267 | const Expr *PtrExpr, APValue &Result) { |
| 268 | assert(SizeExpr); |
| 269 | assert(PtrExpr); |
| 270 | |
| 271 | return evaluateStringRepr(Parent, SizeExpr, PtrExpr, Result); |
| 272 | } |
| 273 | |
| 274 | bool Context::evaluateCharRange(State &Parent, const Expr *SizeExpr, |
| 275 | const Expr *PtrExpr, std::string &Result) { |
| 276 | assert(SizeExpr); |
| 277 | assert(PtrExpr); |
| 278 | |
| 279 | return evaluateStringRepr(Parent, SizeExpr, PtrExpr, Result); |
| 280 | } |
| 281 | |
| 282 | bool Context::evaluateString(State &Parent, const Expr *E, |
| 283 | std::string &Result) { |
| 284 | assert(Stk.empty()); |
| 285 | Compiler<EvalEmitter> C(*this, *P, Parent, Stk); |
| 286 | |
| 287 | auto PtrRes = C.interpretAsPointer(E, PtrCB: [&](InterpState &S, CodePtr OpPC, |
| 288 | const Pointer &Ptr) { |
| 289 | if (!Ptr.isReadablePointerType()) |
| 290 | return false; |
| 291 | |
| 292 | if (!Ptr.isConst()) |
| 293 | return false; |
| 294 | |
| 295 | if (Ptr.isDummy() || Ptr.isUnknownSizeArray() || Ptr.isPastEnd()) |
| 296 | return false; |
| 297 | |
| 298 | unsigned N = Ptr.getNumElems(); |
| 299 | |
| 300 | if (Ptr.elemSize() == 1 /* bytes */) { |
| 301 | const char *Chars = reinterpret_cast<const char *>(Ptr.getRawAddress()); |
| 302 | if (Ptr.isStringPointer()) { |
| 303 | Result.assign(s: Chars, n: N - 1); |
| 304 | return true; |
| 305 | } |
| 306 | unsigned Length = strnlen(string: Chars, maxlen: N); |
| 307 | // Wasn't null terminated. |
| 308 | if (N == Length) |
| 309 | return false; |
| 310 | Result.assign(s: Chars, n: Length); |
| 311 | return true; |
| 312 | } |
| 313 | |
| 314 | PrimType ElemT; |
| 315 | if (Ptr.isBlockPointer()) { |
| 316 | ElemT = Ptr.getFieldDesc()->getPrimType(); |
| 317 | } else { |
| 318 | // It may happen here that the string literal has not been decayed or |
| 319 | // indexed, so check the element type in that case. |
| 320 | assert(Ptr.isStringPointer()); |
| 321 | if (!Ptr.asStringPointer().Decayed) |
| 322 | ElemT = |
| 323 | *classify(T: Ptr.getType()->getAsArrayTypeUnsafe()->getElementType()); |
| 324 | else |
| 325 | ElemT = *classify(T: Ptr.getType()); |
| 326 | } |
| 327 | for (unsigned I = Ptr.getIndex(); I != N; ++I) { |
| 328 | INT_TYPE_SWITCH(ElemT, { |
| 329 | auto Elem = Ptr.loadElem<T>(I); |
| 330 | if (Elem.isZero()) |
| 331 | return true; |
| 332 | Result.push_back(static_cast<char>(Elem)); |
| 333 | }); |
| 334 | } |
| 335 | // We didn't find a 0 byte. |
| 336 | return false; |
| 337 | }); |
| 338 | |
| 339 | if (PtrRes.isInvalid()) { |
| 340 | C.cleanup(); |
| 341 | Stk.clear(); |
| 342 | return false; |
| 343 | } |
| 344 | return true; |
| 345 | } |
| 346 | |
| 347 | std::optional<uint64_t> Context::evaluateStrlen(State &Parent, const Expr *E) { |
| 348 | assert(Stk.empty()); |
| 349 | Compiler<EvalEmitter> C(*this, *P, Parent, Stk); |
| 350 | |
| 351 | std::optional<uint64_t> Result; |
| 352 | auto PtrRes = C.interpretAsPointer(E, PtrCB: [&](InterpState &S, CodePtr OpPC, |
| 353 | const Pointer &Ptr) { |
| 354 | if (!Ptr.isReadablePointerType()) |
| 355 | return false; |
| 356 | |
| 357 | if (Ptr.isPastEnd()) |
| 358 | return false; |
| 359 | |
| 360 | if (Ptr.isStringPointer()) { |
| 361 | const auto *Lit = Ptr.asStringPointer().getLiteral(); |
| 362 | int64_t Off = Ptr.getByteOffset(); |
| 363 | if (Off < 0) |
| 364 | return false; |
| 365 | |
| 366 | UnsignedOrNone ZeroIndex = Lit->findZeroCodeUnit(StartIndex: Off); |
| 367 | if (!ZeroIndex) |
| 368 | return false; |
| 369 | Result = *ZeroIndex; |
| 370 | return true; |
| 371 | } |
| 372 | |
| 373 | const Descriptor *FieldDesc = Ptr.getFieldDesc(); |
| 374 | if (!FieldDesc->isPrimitiveArray()) |
| 375 | return false; |
| 376 | |
| 377 | if (Ptr.isDummy() || Ptr.isUnknownSizeArray()) |
| 378 | return false; |
| 379 | |
| 380 | PrimType ElemT = FieldDesc->getPrimType(); |
| 381 | if (!isIntegerType(T: ElemT)) |
| 382 | return false; |
| 383 | |
| 384 | unsigned N = Ptr.getNumElems(); |
| 385 | if (Ptr.elemSize() == 1) { |
| 386 | unsigned Size = N - Ptr.getIndex(); |
| 387 | Result = |
| 388 | strnlen(string: reinterpret_cast<const char *>(Ptr.getRawAddress()), maxlen: Size); |
| 389 | return Result != Size; |
| 390 | } |
| 391 | |
| 392 | Result = 0; |
| 393 | for (unsigned I = Ptr.getIndex(); I != N; ++I) { |
| 394 | INT_TYPE_SWITCH(ElemT, { |
| 395 | auto Elem = Ptr.elem<T>(I); |
| 396 | if (Elem.isZero()) |
| 397 | return true; |
| 398 | ++(*Result); |
| 399 | }); |
| 400 | } |
| 401 | // We didn't find a 0 byte. |
| 402 | return false; |
| 403 | }); |
| 404 | |
| 405 | if (PtrRes.isInvalid()) { |
| 406 | C.cleanup(); |
| 407 | Stk.clear(); |
| 408 | return std::nullopt; |
| 409 | } |
| 410 | return Result; |
| 411 | } |
| 412 | |
| 413 | std::optional<uint64_t> |
| 414 | Context::tryEvaluateObjectSize(State &Parent, const Expr *E, unsigned Kind) { |
| 415 | assert(Stk.empty()); |
| 416 | Compiler<EvalEmitter> C(*this, *P, Parent, Stk); |
| 417 | |
| 418 | std::optional<uint64_t> Result; |
| 419 | |
| 420 | auto PtrRes = C.interpretAsLValuePointer(E, PtrCB: [&](InterpState &S, CodePtr OpPC, |
| 421 | const Pointer &Ptr) { |
| 422 | const Descriptor *DeclDesc = Ptr.getDeclDesc(); |
| 423 | if (!DeclDesc) |
| 424 | return false; |
| 425 | |
| 426 | QualType T = DeclDesc->getType().getNonReferenceType(); |
| 427 | if (T->isIncompleteType() || T->isFunctionType() || |
| 428 | !T->isConstantSizeType()) |
| 429 | return false; |
| 430 | |
| 431 | Pointer P = Ptr; |
| 432 | if (auto ObjectSize = evaluateBuiltinObjectSize(ASTCtx: getASTContext(), Kind, Ptr&: P)) { |
| 433 | Result = *ObjectSize; |
| 434 | return true; |
| 435 | } |
| 436 | return false; |
| 437 | }); |
| 438 | |
| 439 | if (PtrRes.isInvalid()) { |
| 440 | C.cleanup(); |
| 441 | Stk.clear(); |
| 442 | return std::nullopt; |
| 443 | } |
| 444 | return Result; |
| 445 | } |
| 446 | |
| 447 | std::optional<bool> |
| 448 | Context::evaluateWithSubstitution(State &Parent, const FunctionDecl *Callee, |
| 449 | ArrayRef<const Expr *> Args, const Expr *This, |
| 450 | const Expr *Condition) { |
| 451 | if (OptPrimType ConditionT = classify(E: Condition); |
| 452 | !ConditionT || ConditionT != PT_Bool) { |
| 453 | return std::nullopt; |
| 454 | } |
| 455 | |
| 456 | assert(Stk.empty()); |
| 457 | Compiler<EvalEmitter> C(*this, *P, Parent, Stk); |
| 458 | std::optional<bool> Result = |
| 459 | C.interpretWithSubstitutions(Callee, Args, This, Condition); |
| 460 | |
| 461 | // This is somewhat of a special case here. We don't allow |
| 462 | // evaluateWithSubstitution to recurse (see the Stk.empty() assertion above), |
| 463 | // BUT we allow the args to fail evaluation, which means they can leave some |
| 464 | // garbage on the stack. So we always clear() here, not only if the evaluation |
| 465 | // failed. |
| 466 | Stk.clear(); |
| 467 | if (!Result) { |
| 468 | C.cleanup(); |
| 469 | return std::nullopt; |
| 470 | } |
| 471 | return Result; |
| 472 | } |
| 473 | |
| 474 | const LangOptions &Context::getLangOpts() const { return Ctx.getLangOpts(); } |
| 475 | |
| 476 | static PrimType integralTypeToPrimTypeS(unsigned BitWidth) { |
| 477 | switch (BitWidth) { |
| 478 | case 64: |
| 479 | return PT_Sint64; |
| 480 | case 32: |
| 481 | return PT_Sint32; |
| 482 | case 16: |
| 483 | return PT_Sint16; |
| 484 | case 8: |
| 485 | return PT_Sint8; |
| 486 | default: |
| 487 | return PT_IntAPS; |
| 488 | } |
| 489 | llvm_unreachable("Unhandled BitWidth" ); |
| 490 | } |
| 491 | |
| 492 | static PrimType integralTypeToPrimTypeU(unsigned BitWidth) { |
| 493 | switch (BitWidth) { |
| 494 | case 64: |
| 495 | return PT_Uint64; |
| 496 | case 32: |
| 497 | return PT_Uint32; |
| 498 | case 16: |
| 499 | return PT_Uint16; |
| 500 | case 8: |
| 501 | return PT_Uint8; |
| 502 | default: |
| 503 | return PT_IntAP; |
| 504 | } |
| 505 | llvm_unreachable("Unhandled BitWidth" ); |
| 506 | } |
| 507 | |
| 508 | OptPrimType Context::classify(QualType T) const { |
| 509 | T = T.getCanonicalType(); |
| 510 | |
| 511 | if (const auto *BT = dyn_cast<BuiltinType>(Val&: T)) { |
| 512 | auto Kind = BT->getKind(); |
| 513 | if (Kind == BuiltinType::Bool) |
| 514 | return PT_Bool; |
| 515 | if (Kind == BuiltinType::NullPtr) |
| 516 | return PT_Ptr; |
| 517 | if (Kind == BuiltinType::BoundMember) |
| 518 | return PT_MemberPtr; |
| 519 | |
| 520 | // Just trying to avoid the ASTContext::getIntWidth call below. |
| 521 | if (Kind == BuiltinType::Short) |
| 522 | return integralTypeToPrimTypeS(BitWidth: this->ShortWidth); |
| 523 | if (Kind == BuiltinType::UShort) |
| 524 | return integralTypeToPrimTypeU(BitWidth: this->ShortWidth); |
| 525 | |
| 526 | if (Kind == BuiltinType::Int) |
| 527 | return integralTypeToPrimTypeS(BitWidth: this->IntWidth); |
| 528 | if (Kind == BuiltinType::UInt) |
| 529 | return integralTypeToPrimTypeU(BitWidth: this->IntWidth); |
| 530 | if (Kind == BuiltinType::Long) |
| 531 | return integralTypeToPrimTypeS(BitWidth: this->LongWidth); |
| 532 | if (Kind == BuiltinType::ULong) |
| 533 | return integralTypeToPrimTypeU(BitWidth: this->LongWidth); |
| 534 | if (Kind == BuiltinType::LongLong) |
| 535 | return integralTypeToPrimTypeS(BitWidth: this->LongLongWidth); |
| 536 | if (Kind == BuiltinType::ULongLong) |
| 537 | return integralTypeToPrimTypeU(BitWidth: this->LongLongWidth); |
| 538 | |
| 539 | if (Kind == BuiltinType::SChar || Kind == BuiltinType::Char_S) |
| 540 | return integralTypeToPrimTypeS(BitWidth: 8); |
| 541 | if (Kind == BuiltinType::UChar || Kind == BuiltinType::Char_U || |
| 542 | Kind == BuiltinType::Char8) |
| 543 | return integralTypeToPrimTypeU(BitWidth: 8); |
| 544 | |
| 545 | if (BT->isSignedInteger()) |
| 546 | return integralTypeToPrimTypeS(BitWidth: Ctx.getIntWidth(T)); |
| 547 | if (BT->isUnsignedInteger()) |
| 548 | return integralTypeToPrimTypeU(BitWidth: Ctx.getIntWidth(T)); |
| 549 | |
| 550 | if (BT->isFloatingPoint()) |
| 551 | return PT_Float; |
| 552 | } |
| 553 | |
| 554 | if (T->isPointerOrReferenceType()) |
| 555 | return PT_Ptr; |
| 556 | |
| 557 | if (T->isMemberPointerType()) |
| 558 | return PT_MemberPtr; |
| 559 | |
| 560 | if (const auto *BT = T->getAs<BitIntType>()) { |
| 561 | if (BT->isSigned()) |
| 562 | return integralTypeToPrimTypeS(BitWidth: BT->getNumBits()); |
| 563 | return integralTypeToPrimTypeU(BitWidth: BT->getNumBits()); |
| 564 | } |
| 565 | |
| 566 | if (const auto *D = T->getAsEnumDecl()) { |
| 567 | if (!D->isComplete()) |
| 568 | return std::nullopt; |
| 569 | return classify(T: D->getIntegerType()); |
| 570 | } |
| 571 | |
| 572 | if (const auto *AT = T->getAs<AtomicType>()) |
| 573 | return classify(T: AT->getValueType()); |
| 574 | |
| 575 | if (const auto *OBT = T->getAs<OverflowBehaviorType>()) |
| 576 | return classify(T: OBT->getUnderlyingType()); |
| 577 | |
| 578 | if (T->isObjCObjectPointerType() || T->isBlockPointerType()) |
| 579 | return PT_Ptr; |
| 580 | |
| 581 | if (T->isFixedPointType()) |
| 582 | return PT_FixedPoint; |
| 583 | |
| 584 | // Vector and complex types get here. |
| 585 | return std::nullopt; |
| 586 | } |
| 587 | |
| 588 | unsigned Context::getCharBit() const { |
| 589 | return Ctx.getTargetInfo().getCharWidth(); |
| 590 | } |
| 591 | |
| 592 | /// Simple wrapper around getFloatTypeSemantics() to make code a |
| 593 | /// little shorter. |
| 594 | const llvm::fltSemantics &Context::getFloatSemantics(QualType T) const { |
| 595 | return Ctx.getFloatTypeSemantics(T); |
| 596 | } |
| 597 | |
| 598 | bool Context::Run(State &Parent, const Function *Func) { |
| 599 | auto Memory = std::make_unique<char[]>(num: InterpFrame::allocSize(F: Func)); |
| 600 | InterpState State(Parent, *P, Stk, *this, Func); |
| 601 | InterpFrame *Frame = new (Memory.get()) InterpFrame( |
| 602 | State, Func, /*Caller=*/nullptr, CodePtr(), Func->getArgSize()); |
| 603 | State.Current = Frame; |
| 604 | |
| 605 | if (Interpret(S&: State)) { |
| 606 | assert(Stk.empty()); |
| 607 | return true; |
| 608 | } |
| 609 | |
| 610 | Stk.clear(); |
| 611 | Frame->~InterpFrame(); |
| 612 | State.Current = &State.BottomFrame; |
| 613 | return false; |
| 614 | } |
| 615 | |
| 616 | const CXXMethodDecl * |
| 617 | Context::getOverridingFunction(const CXXRecordDecl *DynamicDecl, |
| 618 | const CXXRecordDecl *StaticDecl, |
| 619 | const CXXMethodDecl *InitialFunction) const { |
| 620 | assert(DynamicDecl); |
| 621 | assert(StaticDecl); |
| 622 | assert(InitialFunction); |
| 623 | |
| 624 | const CXXRecordDecl *CurRecord = DynamicDecl; |
| 625 | const CXXMethodDecl *FoundFunction = InitialFunction; |
| 626 | for (;;) { |
| 627 | const CXXMethodDecl *Overrider = |
| 628 | FoundFunction->getCorrespondingMethodDeclaredInClass(RD: CurRecord, MayBeBase: false); |
| 629 | if (Overrider) |
| 630 | return Overrider; |
| 631 | |
| 632 | // Common case of only one base class. |
| 633 | if (CurRecord->getNumBases() == 1) { |
| 634 | CurRecord = CurRecord->bases_begin()->getType()->getAsCXXRecordDecl(); |
| 635 | continue; |
| 636 | } |
| 637 | |
| 638 | // Otherwise, go to the base class that will lead to the StaticDecl. |
| 639 | for (const CXXBaseSpecifier &Spec : CurRecord->bases()) { |
| 640 | const CXXRecordDecl *Base = Spec.getType()->getAsCXXRecordDecl(); |
| 641 | if (Base == StaticDecl || Base->isDerivedFrom(Base: StaticDecl)) { |
| 642 | CurRecord = Base; |
| 643 | break; |
| 644 | } |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | llvm_unreachable( |
| 649 | "Couldn't find an overriding function in the class hierarchy?" ); |
| 650 | return nullptr; |
| 651 | } |
| 652 | |
| 653 | const Function *Context::getOrCreateFunction(const FunctionDecl *FuncDecl) { |
| 654 | assert(FuncDecl); |
| 655 | if (const Function *Func = P->getFunction(F: FuncDecl)) |
| 656 | return Func; |
| 657 | |
| 658 | // Manually created functions that haven't been assigned proper |
| 659 | // parameters yet. |
| 660 | if (!FuncDecl->param_empty() && !FuncDecl->param_begin()) |
| 661 | return nullptr; |
| 662 | |
| 663 | bool IsLambdaStaticInvoker = false; |
| 664 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FuncDecl); |
| 665 | MD && MD->isLambdaStaticInvoker()) { |
| 666 | // For a lambda static invoker, we might have to pick a specialized |
| 667 | // version if the lambda is generic. In that case, the picked function |
| 668 | // will *NOT* be a static invoker anymore. However, it will still |
| 669 | // be a non-static member function, this (usually) requiring an |
| 670 | // instance pointer. We suppress that later in this function. |
| 671 | IsLambdaStaticInvoker = true; |
| 672 | } |
| 673 | // Set up argument indices. |
| 674 | unsigned ParamOffset = 0; |
| 675 | llvm::SmallVector<Function::ParamDescriptor> ParamDescriptors; |
| 676 | |
| 677 | // If the return is not a primitive, a pointer to the storage where the |
| 678 | // value is initialized in is passed as the first argument. See 'RVO' |
| 679 | // elsewhere in the code. |
| 680 | QualType Ty = FuncDecl->getReturnType(); |
| 681 | bool HasRVO = false; |
| 682 | if (!Ty->isVoidType() && !canClassify(T: Ty)) { |
| 683 | HasRVO = true; |
| 684 | ParamOffset += align(Size: primSize(Type: PT_Ptr)); |
| 685 | } |
| 686 | |
| 687 | // If the function decl is a member decl, the next parameter is |
| 688 | // the 'this' pointer. This parameter is pop()ed from the |
| 689 | // InterpStack when calling the function. |
| 690 | bool HasThisPointer = false; |
| 691 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FuncDecl)) { |
| 692 | if (!IsLambdaStaticInvoker) { |
| 693 | HasThisPointer = MD->isInstance(); |
| 694 | if (MD->isImplicitObjectMemberFunction()) |
| 695 | ParamOffset += align(Size: primSize(Type: PT_Ptr)); |
| 696 | } |
| 697 | |
| 698 | if (isLambdaCallOperator(MD)) { |
| 699 | // The parent record needs to be complete, we need to know about all |
| 700 | // the lambda captures. |
| 701 | if (!MD->getParent()->isCompleteDefinition()) |
| 702 | return nullptr; |
| 703 | if (MD->isStatic()) { |
| 704 | llvm::DenseMap<const ValueDecl *, FieldDecl *> LC; |
| 705 | FieldDecl *LTC; |
| 706 | |
| 707 | MD->getParent()->getCaptureFields(Captures&: LC, ThisCapture&: LTC); |
| 708 | // Static lambdas cannot have any captures. If this one does, |
| 709 | // it has already been diagnosed and we can only ignore it. |
| 710 | if (!LC.empty()) |
| 711 | return nullptr; |
| 712 | } |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | // Assign descriptors to all parameters. |
| 717 | // Composite objects are lowered to pointers. |
| 718 | const auto *FuncProto = FuncDecl->getType()->getAs<FunctionProtoType>(); |
| 719 | unsigned BlockOffset = 0; |
| 720 | for (auto [ParamIndex, PD] : llvm::enumerate(First: FuncDecl->parameters())) { |
| 721 | bool IsConst = PD->getType().isConstQualified(); |
| 722 | bool IsVolatile = PD->getType().isVolatileQualified(); |
| 723 | |
| 724 | if (PD->isInvalidDecl() || |
| 725 | !getASTContext().hasSameType(T1: PD->getType(), |
| 726 | T2: FuncProto->getParamType(i: ParamIndex))) |
| 727 | return nullptr; |
| 728 | |
| 729 | OptPrimType T = classify(T: PD->getType()); |
| 730 | PrimType PT = T.value_or(PT: PT_Ptr); |
| 731 | Descriptor *Desc = P->createDescriptor(D: PD, T: PT, SourceTy: nullptr, IsConst, |
| 732 | /*IsTemporary=*/false, |
| 733 | /*IsMutable=*/false, IsVolatile); |
| 734 | unsigned PrimTSize = align(Size: primSize(Type: PT)); |
| 735 | ParamDescriptors.emplace_back(Args&: Desc, Args&: ParamOffset, Args&: BlockOffset, Args&: PT); |
| 736 | ParamOffset += PrimTSize; |
| 737 | BlockOffset += sizeof(Block) + PrimTSize; |
| 738 | } |
| 739 | |
| 740 | // Create a handle over the emitted code. |
| 741 | assert(!P->getFunction(FuncDecl)); |
| 742 | const Function *Func = |
| 743 | P->createFunction(Def: FuncDecl, Args&: ParamOffset, Args: std::move(ParamDescriptors), |
| 744 | Args&: HasThisPointer, Args&: HasRVO, Args&: IsLambdaStaticInvoker); |
| 745 | return Func; |
| 746 | } |
| 747 | |
| 748 | const Function *Context::getOrCreateObjCBlock(const BlockExpr *E) { |
| 749 | const BlockDecl *BD = E->getBlockDecl(); |
| 750 | // Set up argument indices. |
| 751 | unsigned ParamOffset = 0; |
| 752 | llvm::SmallVector<Function::ParamDescriptor> ParamDescriptors; |
| 753 | |
| 754 | // Assign descriptors to all parameters. |
| 755 | // Composite objects are lowered to pointers. |
| 756 | for (const ParmVarDecl *PD : BD->parameters()) { |
| 757 | bool IsConst = PD->getType().isConstQualified(); |
| 758 | bool IsVolatile = PD->getType().isVolatileQualified(); |
| 759 | |
| 760 | OptPrimType T = classify(T: PD->getType()); |
| 761 | PrimType PT = T.value_or(PT: PT_Ptr); |
| 762 | Descriptor *Desc = P->createDescriptor(D: PD, T: PT, SourceTy: nullptr, IsConst, |
| 763 | /*IsTemporary=*/false, |
| 764 | /*IsMutable=*/false, IsVolatile); |
| 765 | ParamDescriptors.emplace_back(Args&: Desc, Args&: ParamOffset, Args: ~0u, Args&: PT); |
| 766 | ParamOffset += align(Size: primSize(Type: PT)); |
| 767 | } |
| 768 | |
| 769 | if (BD->hasCaptures()) |
| 770 | return nullptr; |
| 771 | |
| 772 | // Create a handle over the emitted code. |
| 773 | Function *Func = |
| 774 | P->createFunction(Args&: E, Args&: ParamOffset, Args: std::move(ParamDescriptors), |
| 775 | /*HasThisPointer=*/Args: false, /*HasRVO=*/Args: false, |
| 776 | /*IsLambdaStaticInvoker=*/Args: false); |
| 777 | |
| 778 | assert(Func); |
| 779 | Func->setDefined(true); |
| 780 | // We don't compile the BlockDecl code at all right now. |
| 781 | Func->setIsFullyCompiled(true); |
| 782 | |
| 783 | return Func; |
| 784 | } |
| 785 | |
| 786 | unsigned Context::collectBaseOffset(const RecordDecl *BaseDecl, |
| 787 | const RecordDecl *DerivedDecl) const { |
| 788 | assert(BaseDecl); |
| 789 | assert(DerivedDecl); |
| 790 | const auto *FinalDecl = cast<CXXRecordDecl>(Val: BaseDecl); |
| 791 | const RecordDecl *CurDecl = DerivedDecl; |
| 792 | const Record *CurRecord = P->getOrCreateRecord(RD: CurDecl); |
| 793 | assert(CurDecl && FinalDecl); |
| 794 | |
| 795 | unsigned OffsetSum = 0; |
| 796 | for (;;) { |
| 797 | assert(CurRecord->getNumBases() > 0); |
| 798 | // One level up |
| 799 | for (const Record::Base &B : CurRecord->bases()) { |
| 800 | const auto *BaseDecl = cast<CXXRecordDecl>(Val: B.Decl); |
| 801 | |
| 802 | if (BaseDecl == FinalDecl || BaseDecl->isDerivedFrom(Base: FinalDecl)) { |
| 803 | OffsetSum += B.Offset; |
| 804 | CurRecord = B.R; |
| 805 | CurDecl = BaseDecl; |
| 806 | break; |
| 807 | } |
| 808 | } |
| 809 | if (CurDecl == FinalDecl) |
| 810 | break; |
| 811 | } |
| 812 | |
| 813 | assert(OffsetSum > 0); |
| 814 | return OffsetSum; |
| 815 | } |
| 816 | |
| 817 | const Record *Context::getRecord(const RecordDecl *D) const { |
| 818 | return P->getOrCreateRecord(RD: D); |
| 819 | } |
| 820 | |
| 821 | bool Context::isUnevaluatedBuiltin(unsigned ID) { |
| 822 | return ID == Builtin::BI__builtin_classify_type || |
| 823 | ID == Builtin::BI__builtin_os_log_format_buffer_size || |
| 824 | ID == Builtin::BI__builtin_constant_p || ID == Builtin::BI__noop; |
| 825 | } |
| 826 | |