clang 22.0.0git
Compiler.cpp
Go to the documentation of this file.
1//===--- Compiler.cpp - Code generator for expressions ---*- 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 "Compiler.h"
10#include "ByteCodeEmitter.h"
11#include "Context.h"
12#include "FixedPoint.h"
13#include "Floating.h"
14#include "Function.h"
15#include "InterpShared.h"
16#include "PrimType.h"
17#include "Program.h"
18#include "clang/AST/Attr.h"
19
20using namespace clang;
21using namespace clang::interp;
22
23using APSInt = llvm::APSInt;
24
25namespace clang {
26namespace interp {
27
28static std::optional<bool> getBoolValue(const Expr *E) {
29 if (const auto *CE = dyn_cast_if_present<ConstantExpr>(E);
30 CE && CE->hasAPValueResult() &&
31 CE->getResultAPValueKind() == APValue::ValueKind::Int) {
32 return CE->getResultAsAPSInt().getBoolValue();
33 }
34
35 return std::nullopt;
36}
37
38/// Scope used to handle temporaries in toplevel variable declarations.
39template <class Emitter> class DeclScope final : public LocalScope<Emitter> {
40public:
42 : LocalScope<Emitter>(Ctx, VD), Scope(Ctx->P),
43 OldInitializingDecl(Ctx->InitializingDecl) {
44 Ctx->InitializingDecl = VD;
45 Ctx->InitStack.push_back(InitLink::Decl(VD));
46 }
47
49 this->Ctx->InitializingDecl = OldInitializingDecl;
50 this->Ctx->InitStack.pop_back();
51 }
52
53private:
55 const ValueDecl *OldInitializingDecl;
56};
57
58/// Scope used to handle initialization methods.
59template <class Emitter> class OptionScope final {
60public:
61 /// Root constructor, compiling or discarding primitives.
62 OptionScope(Compiler<Emitter> *Ctx, bool NewDiscardResult,
63 bool NewInitializing, bool NewToLValue)
64 : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult),
65 OldInitializing(Ctx->Initializing), OldToLValue(Ctx->ToLValue) {
66 Ctx->DiscardResult = NewDiscardResult;
67 Ctx->Initializing = NewInitializing;
68 Ctx->ToLValue = NewToLValue;
69 }
70
72 Ctx->DiscardResult = OldDiscardResult;
73 Ctx->Initializing = OldInitializing;
74 Ctx->ToLValue = OldToLValue;
75 }
76
77private:
78 /// Parent context.
80 /// Old discard flag to restore.
81 bool OldDiscardResult;
82 bool OldInitializing;
83 bool OldToLValue;
84};
85
86template <class Emitter>
87bool InitLink::emit(Compiler<Emitter> *Ctx, const Expr *E) const {
88 switch (Kind) {
89 case K_This:
90 return Ctx->emitThis(E);
91 case K_Field:
92 // We're assuming there's a base pointer on the stack already.
93 return Ctx->emitGetPtrFieldPop(Offset, E);
94 case K_Temp:
95 return Ctx->emitGetPtrLocal(Offset, E);
96 case K_Decl:
97 return Ctx->visitDeclRef(D, E);
98 case K_Elem:
99 if (!Ctx->emitConstUint32(Offset, E))
100 return false;
101 return Ctx->emitArrayElemPtrPopUint32(E);
102 case K_RVO:
103 return Ctx->emitRVOPtr(E);
104 case K_InitList:
105 return true;
106 default:
107 llvm_unreachable("Unhandled InitLink kind");
108 }
109 return true;
110}
111
112/// Sets the context for break/continue statements.
113template <class Emitter> class LoopScope final {
114public:
118
119 LoopScope(Compiler<Emitter> *Ctx, const Stmt *Name, LabelTy BreakLabel,
120 LabelTy ContinueLabel)
121 : Ctx(Ctx) {
122#ifndef NDEBUG
123 for (const LabelInfo &LI : Ctx->LabelInfoStack)
124 assert(LI.Name != Name);
125#endif
126
127 this->Ctx->LabelInfoStack.emplace_back(Name, BreakLabel, ContinueLabel,
128 /*DefaultLabel=*/std::nullopt,
129 Ctx->VarScope);
130 }
131
132 ~LoopScope() { this->Ctx->LabelInfoStack.pop_back(); }
133
134private:
136};
137
138// Sets the context for a switch scope, mapping labels.
139template <class Emitter> class SwitchScope final {
140public:
145
146 SwitchScope(Compiler<Emitter> *Ctx, const Stmt *Name, CaseMap &&CaseLabels,
147 LabelTy BreakLabel, OptLabelTy DefaultLabel)
148 : Ctx(Ctx), OldCaseLabels(std::move(this->Ctx->CaseLabels)) {
149#ifndef NDEBUG
150 for (const LabelInfo &LI : Ctx->LabelInfoStack)
151 assert(LI.Name != Name);
152#endif
153
154 this->Ctx->CaseLabels = std::move(CaseLabels);
155 this->Ctx->LabelInfoStack.emplace_back(Name, BreakLabel,
156 /*ContinueLabel=*/std::nullopt,
157 DefaultLabel, Ctx->VarScope);
158 }
159
161 this->Ctx->CaseLabels = std::move(OldCaseLabels);
162 this->Ctx->LabelInfoStack.pop_back();
163 }
164
165private:
167 CaseMap OldCaseLabels;
168};
169
170template <class Emitter> class StmtExprScope final {
171public:
172 StmtExprScope(Compiler<Emitter> *Ctx) : Ctx(Ctx), OldFlag(Ctx->InStmtExpr) {
173 Ctx->InStmtExpr = true;
174 }
175
176 ~StmtExprScope() { Ctx->InStmtExpr = OldFlag; }
177
178private:
180 bool OldFlag;
181};
182
183/// When generating code for e.g. implicit field initializers in constructors,
184/// we don't have anything to point to in case the initializer causes an error.
185/// In that case, we need to disable location tracking for the initializer so
186/// we later point to the call range instead.
187template <class Emitter> class LocOverrideScope final {
188public:
190 bool Enabled = true)
191 : Ctx(Ctx), OldFlag(Ctx->LocOverride), Enabled(Enabled) {
192
193 if (Enabled)
194 Ctx->LocOverride = NewValue;
195 }
196
198 if (Enabled)
199 Ctx->LocOverride = OldFlag;
200 }
201
202private:
204 std::optional<SourceInfo> OldFlag;
205 bool Enabled;
206};
207
208} // namespace interp
209} // namespace clang
210
211template <class Emitter>
213 const Expr *SubExpr = CE->getSubExpr();
214
215 if (DiscardResult)
216 return this->delegate(SubExpr);
217
218 switch (CE->getCastKind()) {
219 case CK_LValueToRValue: {
220 if (ToLValue && CE->getType()->isPointerType())
221 return this->delegate(SubExpr);
222
223 if (SubExpr->getType().isVolatileQualified())
224 return this->emitInvalidCast(CastKind::Volatile, /*Fatal=*/true, CE);
225
226 OptPrimType SubExprT = classify(SubExpr->getType());
227 // Try to load the value directly. This is purely a performance
228 // optimization.
229 if (SubExprT) {
230 if (const auto *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
231 const ValueDecl *D = DRE->getDecl();
232 bool IsReference = D->getType()->isReferenceType();
233
234 if (!IsReference) {
236 if (auto GlobalIndex = P.getGlobal(D))
237 return this->emitGetGlobal(*SubExprT, *GlobalIndex, CE);
238 } else if (auto It = Locals.find(D); It != Locals.end()) {
239 return this->emitGetLocal(*SubExprT, It->second.Offset, CE);
240 } else if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
241 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
242 return this->emitGetParam(*SubExprT, It->second.Offset, CE);
243 }
244 }
245 }
246 }
247 }
248
249 // Prepare storage for the result.
250 if (!Initializing && !SubExprT) {
251 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
252 if (!LocalIndex)
253 return false;
254 if (!this->emitGetPtrLocal(*LocalIndex, CE))
255 return false;
256 }
257
258 if (!this->visit(SubExpr))
259 return false;
260
261 if (SubExprT)
262 return this->emitLoadPop(*SubExprT, CE);
263
264 // If the subexpr type is not primitive, we need to perform a copy here.
265 // This happens for example in C when dereferencing a pointer of struct
266 // type.
267 return this->emitMemcpy(CE);
268 }
269
270 case CK_DerivedToBaseMemberPointer: {
271 assert(classifyPrim(CE->getType()) == PT_MemberPtr);
272 assert(classifyPrim(SubExpr->getType()) == PT_MemberPtr);
273 const auto *FromMP = SubExpr->getType()->castAs<MemberPointerType>();
274 const auto *ToMP = CE->getType()->castAs<MemberPointerType>();
275
276 unsigned DerivedOffset =
277 Ctx.collectBaseOffset(ToMP->getMostRecentCXXRecordDecl(),
278 FromMP->getMostRecentCXXRecordDecl());
279
280 if (!this->delegate(SubExpr))
281 return false;
282
283 return this->emitGetMemberPtrBasePop(DerivedOffset, CE);
284 }
285
286 case CK_BaseToDerivedMemberPointer: {
287 assert(classifyPrim(CE) == PT_MemberPtr);
288 assert(classifyPrim(SubExpr) == PT_MemberPtr);
289 const auto *FromMP = SubExpr->getType()->castAs<MemberPointerType>();
290 const auto *ToMP = CE->getType()->castAs<MemberPointerType>();
291
292 unsigned DerivedOffset =
293 Ctx.collectBaseOffset(FromMP->getMostRecentCXXRecordDecl(),
295
296 if (!this->delegate(SubExpr))
297 return false;
298 return this->emitGetMemberPtrBasePop(-DerivedOffset, CE);
299 }
300
301 case CK_UncheckedDerivedToBase:
302 case CK_DerivedToBase: {
303 if (!this->delegate(SubExpr))
304 return false;
305
306 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
307 if (const auto *PT = dyn_cast<PointerType>(Ty))
308 return PT->getPointeeType()->getAsCXXRecordDecl();
309 return Ty->getAsCXXRecordDecl();
310 };
311
312 // FIXME: We can express a series of non-virtual casts as a single
313 // GetPtrBasePop op.
314 QualType CurType = SubExpr->getType();
315 for (const CXXBaseSpecifier *B : CE->path()) {
316 if (B->isVirtual()) {
317 if (!this->emitGetPtrVirtBasePop(extractRecordDecl(B->getType()), CE))
318 return false;
319 CurType = B->getType();
320 } else {
321 unsigned DerivedOffset = collectBaseOffset(B->getType(), CurType);
322 if (!this->emitGetPtrBasePop(
323 DerivedOffset, /*NullOK=*/CE->getType()->isPointerType(), CE))
324 return false;
325 CurType = B->getType();
326 }
327 }
328
329 return true;
330 }
331
332 case CK_BaseToDerived: {
333 if (!this->delegate(SubExpr))
334 return false;
335 unsigned DerivedOffset =
336 collectBaseOffset(SubExpr->getType(), CE->getType());
337
338 const Type *TargetType = CE->getType().getTypePtr();
339 if (TargetType->isPointerOrReferenceType())
340 TargetType = TargetType->getPointeeType().getTypePtr();
341 return this->emitGetPtrDerivedPop(DerivedOffset,
342 /*NullOK=*/CE->getType()->isPointerType(),
343 TargetType, CE);
344 }
345
346 case CK_FloatingCast: {
347 // HLSL uses CK_FloatingCast to cast between vectors.
348 if (!SubExpr->getType()->isFloatingType() ||
349 !CE->getType()->isFloatingType())
350 return false;
351 if (!this->visit(SubExpr))
352 return false;
353 const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
354 return this->emitCastFP(TargetSemantics, getRoundingMode(CE), CE);
355 }
356
357 case CK_IntegralToFloating: {
358 if (!CE->getType()->isRealFloatingType())
359 return false;
360 if (!this->visit(SubExpr))
361 return false;
362 const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
363 return this->emitCastIntegralFloating(
364 classifyPrim(SubExpr), TargetSemantics, getFPOptions(CE), CE);
365 }
366
367 case CK_FloatingToBoolean: {
368 if (!SubExpr->getType()->isRealFloatingType() ||
369 !CE->getType()->isBooleanType())
370 return false;
371 if (const auto *FL = dyn_cast<FloatingLiteral>(SubExpr))
372 return this->emitConstBool(FL->getValue().isNonZero(), CE);
373 if (!this->visit(SubExpr))
374 return false;
375 return this->emitCastFloatingIntegralBool(getFPOptions(CE), CE);
376 }
377
378 case CK_FloatingToIntegral: {
380 return false;
381 if (!this->visit(SubExpr))
382 return false;
383 PrimType ToT = classifyPrim(CE);
384 if (ToT == PT_IntAP)
385 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(CE->getType()),
386 getFPOptions(CE), CE);
387 if (ToT == PT_IntAPS)
388 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(CE->getType()),
389 getFPOptions(CE), CE);
390
391 return this->emitCastFloatingIntegral(ToT, getFPOptions(CE), CE);
392 }
393
394 case CK_NullToPointer:
395 case CK_NullToMemberPointer: {
396 if (!this->discard(SubExpr))
397 return false;
398 const Descriptor *Desc = nullptr;
399 const QualType PointeeType = CE->getType()->getPointeeType();
400 if (!PointeeType.isNull()) {
401 if (OptPrimType T = classify(PointeeType))
402 Desc = P.createDescriptor(SubExpr, *T);
403 else
404 Desc = P.createDescriptor(SubExpr, PointeeType.getTypePtr(),
405 std::nullopt, /*IsConst=*/true);
406 }
407
408 uint64_t Val = Ctx.getASTContext().getTargetNullPointerValue(CE->getType());
409 return this->emitNull(classifyPrim(CE->getType()), Val, Desc, CE);
410 }
411
412 case CK_PointerToIntegral: {
413 if (!this->visit(SubExpr))
414 return false;
415
416 // If SubExpr doesn't result in a pointer, make it one.
417 if (PrimType FromT = classifyPrim(SubExpr->getType()); FromT != PT_Ptr) {
418 assert(isPtrType(FromT));
419 if (!this->emitDecayPtr(FromT, PT_Ptr, CE))
420 return false;
421 }
422
424 if (T == PT_IntAP)
425 return this->emitCastPointerIntegralAP(Ctx.getBitWidth(CE->getType()),
426 CE);
427 if (T == PT_IntAPS)
428 return this->emitCastPointerIntegralAPS(Ctx.getBitWidth(CE->getType()),
429 CE);
430 return this->emitCastPointerIntegral(T, CE);
431 }
432
433 case CK_ArrayToPointerDecay: {
434 if (!this->visit(SubExpr))
435 return false;
436 return this->emitArrayDecay(CE);
437 }
438
439 case CK_IntegralToPointer: {
440 QualType IntType = SubExpr->getType();
441 assert(IntType->isIntegralOrEnumerationType());
442 if (!this->visit(SubExpr))
443 return false;
444 // FIXME: I think the discard is wrong since the int->ptr cast might cause a
445 // diagnostic.
446 PrimType T = classifyPrim(IntType);
447 QualType PtrType = CE->getType();
448 const Descriptor *Desc;
449 if (OptPrimType T = classify(PtrType->getPointeeType()))
450 Desc = P.createDescriptor(SubExpr, *T);
451 else if (PtrType->getPointeeType()->isVoidType())
452 Desc = nullptr;
453 else
454 Desc = P.createDescriptor(CE, PtrType->getPointeeType().getTypePtr(),
455 Descriptor::InlineDescMD, /*IsConst=*/true);
456
457 if (!this->emitGetIntPtr(T, Desc, CE))
458 return false;
459
460 PrimType DestPtrT = classifyPrim(PtrType);
461 if (DestPtrT == PT_Ptr)
462 return true;
463
464 // In case we're converting the integer to a non-Pointer.
465 return this->emitDecayPtr(PT_Ptr, DestPtrT, CE);
466 }
467
468 case CK_AtomicToNonAtomic:
469 case CK_ConstructorConversion:
470 case CK_FunctionToPointerDecay:
471 case CK_NonAtomicToAtomic:
472 case CK_NoOp:
473 case CK_UserDefinedConversion:
474 case CK_AddressSpaceConversion:
475 case CK_CPointerToObjCPointerCast:
476 return this->delegate(SubExpr);
477
478 case CK_BitCast: {
479 // Reject bitcasts to atomic types.
480 if (CE->getType()->isAtomicType()) {
481 if (!this->discard(SubExpr))
482 return false;
483 return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, CE);
484 }
485 QualType SubExprTy = SubExpr->getType();
486 OptPrimType FromT = classify(SubExprTy);
487 // Casts from integer/vector to vector.
488 if (CE->getType()->isVectorType())
489 return this->emitBuiltinBitCast(CE);
490
491 OptPrimType ToT = classify(CE->getType());
492 if (!FromT || !ToT)
493 return false;
494
495 assert(isPtrType(*FromT));
496 assert(isPtrType(*ToT));
497 if (FromT == ToT) {
498 if (CE->getType()->isVoidPointerType() &&
499 !SubExprTy->isFunctionPointerType()) {
500 return this->delegate(SubExpr);
501 }
502
503 if (!this->visit(SubExpr))
504 return false;
505 if (CE->getType()->isFunctionPointerType() ||
506 SubExprTy->isFunctionPointerType()) {
507 return this->emitFnPtrCast(CE);
508 }
509 if (FromT == PT_Ptr)
510 return this->emitPtrPtrCast(SubExprTy->isVoidPointerType(), CE);
511 return true;
512 }
513
514 if (!this->visit(SubExpr))
515 return false;
516 return this->emitDecayPtr(*FromT, *ToT, CE);
517 }
518 case CK_IntegralToBoolean:
519 case CK_FixedPointToBoolean: {
520 // HLSL uses this to cast to one-element vectors.
521 OptPrimType FromT = classify(SubExpr->getType());
522 if (!FromT)
523 return false;
524
525 if (const auto *IL = dyn_cast<IntegerLiteral>(SubExpr))
526 return this->emitConst(IL->getValue(), CE);
527 if (!this->visit(SubExpr))
528 return false;
529 return this->emitCast(*FromT, classifyPrim(CE), CE);
530 }
531
532 case CK_BooleanToSignedIntegral:
533 case CK_IntegralCast: {
534 OptPrimType FromT = classify(SubExpr->getType());
535 OptPrimType ToT = classify(CE->getType());
536 if (!FromT || !ToT)
537 return false;
538
539 // Try to emit a casted known constant value directly.
540 if (const auto *IL = dyn_cast<IntegerLiteral>(SubExpr)) {
541 if (ToT != PT_IntAP && ToT != PT_IntAPS && FromT != PT_IntAP &&
542 FromT != PT_IntAPS && !CE->getType()->isEnumeralType())
543 return this->emitConst(IL->getValue(), CE);
544 if (!this->emitConst(IL->getValue(), SubExpr))
545 return false;
546 } else {
547 if (!this->visit(SubExpr))
548 return false;
549 }
550
551 // Possibly diagnose casts to enum types if the target type does not
552 // have a fixed size.
553 if (Ctx.getLangOpts().CPlusPlus && CE->getType()->isEnumeralType()) {
554 const auto *ED = CE->getType()->castAsEnumDecl();
555 if (!ED->isFixed()) {
556 if (!this->emitCheckEnumValue(*FromT, ED, CE))
557 return false;
558 }
559 }
560
561 if (ToT == PT_IntAP) {
562 if (!this->emitCastAP(*FromT, Ctx.getBitWidth(CE->getType()), CE))
563 return false;
564 } else if (ToT == PT_IntAPS) {
565 if (!this->emitCastAPS(*FromT, Ctx.getBitWidth(CE->getType()), CE))
566 return false;
567 } else {
568 if (FromT == ToT)
569 return true;
570 if (!this->emitCast(*FromT, *ToT, CE))
571 return false;
572 }
573 if (CE->getCastKind() == CK_BooleanToSignedIntegral)
574 return this->emitNeg(*ToT, CE);
575 return true;
576 }
577
578 case CK_PointerToBoolean:
579 case CK_MemberPointerToBoolean: {
580 PrimType PtrT = classifyPrim(SubExpr->getType());
581
582 if (!this->visit(SubExpr))
583 return false;
584 return this->emitIsNonNull(PtrT, CE);
585 }
586
587 case CK_IntegralComplexToBoolean:
588 case CK_FloatingComplexToBoolean: {
589 if (!this->visit(SubExpr))
590 return false;
591 return this->emitComplexBoolCast(SubExpr);
592 }
593
594 case CK_IntegralComplexToReal:
595 case CK_FloatingComplexToReal:
596 return this->emitComplexReal(SubExpr);
597
598 case CK_IntegralRealToComplex:
599 case CK_FloatingRealToComplex: {
600 // We're creating a complex value here, so we need to
601 // allocate storage for it.
602 if (!Initializing) {
603 UnsignedOrNone LocalIndex = allocateTemporary(CE);
604 if (!LocalIndex)
605 return false;
606 if (!this->emitGetPtrLocal(*LocalIndex, CE))
607 return false;
608 }
609
610 PrimType T = classifyPrim(SubExpr->getType());
611 // Init the complex value to {SubExpr, 0}.
612 if (!this->visitArrayElemInit(0, SubExpr, T))
613 return false;
614 // Zero-init the second element.
615 if (!this->visitZeroInitializer(T, SubExpr->getType(), SubExpr))
616 return false;
617 return this->emitInitElem(T, 1, SubExpr);
618 }
619
620 case CK_IntegralComplexCast:
621 case CK_FloatingComplexCast:
622 case CK_IntegralComplexToFloatingComplex:
623 case CK_FloatingComplexToIntegralComplex: {
624 assert(CE->getType()->isAnyComplexType());
625 assert(SubExpr->getType()->isAnyComplexType());
626 if (!Initializing) {
627 UnsignedOrNone LocalIndex = allocateLocal(CE);
628 if (!LocalIndex)
629 return false;
630 if (!this->emitGetPtrLocal(*LocalIndex, CE))
631 return false;
632 }
633
634 // Location for the SubExpr.
635 // Since SubExpr is of complex type, visiting it results in a pointer
636 // anyway, so we just create a temporary pointer variable.
637 unsigned SubExprOffset =
638 allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
639 if (!this->visit(SubExpr))
640 return false;
641 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, CE))
642 return false;
643
644 PrimType SourceElemT = classifyComplexElementType(SubExpr->getType());
645 QualType DestElemType =
646 CE->getType()->getAs<ComplexType>()->getElementType();
647 PrimType DestElemT = classifyPrim(DestElemType);
648 // Cast both elements individually.
649 for (unsigned I = 0; I != 2; ++I) {
650 if (!this->emitGetLocal(PT_Ptr, SubExprOffset, CE))
651 return false;
652 if (!this->emitArrayElemPop(SourceElemT, I, CE))
653 return false;
654
655 // Do the cast.
656 if (!this->emitPrimCast(SourceElemT, DestElemT, DestElemType, CE))
657 return false;
658
659 // Save the value.
660 if (!this->emitInitElem(DestElemT, I, CE))
661 return false;
662 }
663 return true;
664 }
665
666 case CK_VectorSplat: {
667 assert(!canClassify(CE->getType()));
668 assert(canClassify(SubExpr->getType()));
669 assert(CE->getType()->isVectorType());
670
671 if (!Initializing) {
672 UnsignedOrNone LocalIndex = allocateLocal(CE);
673 if (!LocalIndex)
674 return false;
675 if (!this->emitGetPtrLocal(*LocalIndex, CE))
676 return false;
677 }
678
679 const auto *VT = CE->getType()->getAs<VectorType>();
680 PrimType ElemT = classifyPrim(SubExpr->getType());
681 unsigned ElemOffset =
682 allocateLocalPrimitive(SubExpr, ElemT, /*IsConst=*/true);
683
684 // Prepare a local variable for the scalar value.
685 if (!this->visit(SubExpr))
686 return false;
687 if (classifyPrim(SubExpr) == PT_Ptr && !this->emitLoadPop(ElemT, CE))
688 return false;
689
690 if (!this->emitSetLocal(ElemT, ElemOffset, CE))
691 return false;
692
693 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
694 if (!this->emitGetLocal(ElemT, ElemOffset, CE))
695 return false;
696 if (!this->emitInitElem(ElemT, I, CE))
697 return false;
698 }
699
700 return true;
701 }
702
703 case CK_HLSLVectorTruncation: {
704 assert(SubExpr->getType()->isVectorType());
705 if (OptPrimType ResultT = classify(CE)) {
706 assert(!DiscardResult);
707 // Result must be either a float or integer. Take the first element.
708 if (!this->visit(SubExpr))
709 return false;
710 return this->emitArrayElemPop(*ResultT, 0, CE);
711 }
712 // Otherwise, this truncates from one vector type to another.
713 assert(CE->getType()->isVectorType());
714
715 if (!Initializing) {
716 UnsignedOrNone LocalIndex = allocateTemporary(CE);
717 if (!LocalIndex)
718 return false;
719 if (!this->emitGetPtrLocal(*LocalIndex, CE))
720 return false;
721 }
722 unsigned ToSize = CE->getType()->getAs<VectorType>()->getNumElements();
723 assert(SubExpr->getType()->getAs<VectorType>()->getNumElements() > ToSize);
724 if (!this->visit(SubExpr))
725 return false;
726 return this->emitCopyArray(classifyVectorElementType(CE->getType()), 0, 0,
727 ToSize, CE);
728 };
729
730 case CK_IntegralToFixedPoint: {
731 if (!this->visit(SubExpr))
732 return false;
733
734 auto Sem =
735 Ctx.getASTContext().getFixedPointSemantics(CE->getType()).toOpaqueInt();
736 return this->emitCastIntegralFixedPoint(classifyPrim(SubExpr->getType()),
737 Sem, CE);
738 }
739 case CK_FloatingToFixedPoint: {
740 if (!this->visit(SubExpr))
741 return false;
742
743 auto Sem =
744 Ctx.getASTContext().getFixedPointSemantics(CE->getType()).toOpaqueInt();
745 return this->emitCastFloatingFixedPoint(Sem, CE);
746 }
747 case CK_FixedPointToFloating: {
748 if (!this->visit(SubExpr))
749 return false;
750 const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
751 return this->emitCastFixedPointFloating(TargetSemantics, CE);
752 }
753 case CK_FixedPointToIntegral: {
754 if (!this->visit(SubExpr))
755 return false;
756 return this->emitCastFixedPointIntegral(classifyPrim(CE->getType()), CE);
757 }
758 case CK_FixedPointCast: {
759 if (!this->visit(SubExpr))
760 return false;
761 auto Sem =
762 Ctx.getASTContext().getFixedPointSemantics(CE->getType()).toOpaqueInt();
763 return this->emitCastFixedPoint(Sem, CE);
764 }
765
766 case CK_ToVoid:
767 return discard(SubExpr);
768
769 default:
770 return this->emitInvalid(CE);
771 }
772 llvm_unreachable("Unhandled clang::CastKind enum");
773}
774
775template <class Emitter>
777 return this->emitBuiltinBitCast(E);
778}
779
780template <class Emitter>
782 if (DiscardResult)
783 return true;
784
785 return this->emitConst(LE->getValue(), LE);
786}
787
788template <class Emitter>
790 if (DiscardResult)
791 return true;
792
793 APFloat F = E->getValue();
794 return this->emitFloat(F, E);
795}
796
797template <class Emitter>
799 assert(E->getType()->isAnyComplexType());
800 if (DiscardResult)
801 return true;
802
803 if (!Initializing) {
804 UnsignedOrNone LocalIndex = allocateTemporary(E);
805 if (!LocalIndex)
806 return false;
807 if (!this->emitGetPtrLocal(*LocalIndex, E))
808 return false;
809 }
810
811 const Expr *SubExpr = E->getSubExpr();
812 PrimType SubExprT = classifyPrim(SubExpr->getType());
813
814 if (!this->visitZeroInitializer(SubExprT, SubExpr->getType(), SubExpr))
815 return false;
816 if (!this->emitInitElem(SubExprT, 0, SubExpr))
817 return false;
818 return this->visitArrayElemInit(1, SubExpr, SubExprT);
819}
820
821template <class Emitter>
823 assert(E->getType()->isFixedPointType());
824 assert(classifyPrim(E) == PT_FixedPoint);
825
826 if (DiscardResult)
827 return true;
828
829 auto Sem = Ctx.getASTContext().getFixedPointSemantics(E->getType());
830 APInt Value = E->getValue();
831 return this->emitConstFixedPoint(FixedPoint(Value, Sem), E);
832}
833
834template <class Emitter>
836 return this->delegate(E->getSubExpr());
837}
838
839template <class Emitter>
841 // Need short-circuiting for these.
842 if (BO->isLogicalOp() && !BO->getType()->isVectorType())
843 return this->VisitLogicalBinOp(BO);
844
845 const Expr *LHS = BO->getLHS();
846 const Expr *RHS = BO->getRHS();
847
848 // Handle comma operators. Just discard the LHS
849 // and delegate to RHS.
850 if (BO->isCommaOp()) {
851 if (!this->discard(LHS))
852 return false;
853 if (RHS->getType()->isVoidType())
854 return this->discard(RHS);
855
856 return this->delegate(RHS);
857 }
858
859 if (BO->getType()->isAnyComplexType())
860 return this->VisitComplexBinOp(BO);
861 if (BO->getType()->isVectorType())
862 return this->VisitVectorBinOp(BO);
863 if ((LHS->getType()->isAnyComplexType() ||
864 RHS->getType()->isAnyComplexType()) &&
865 BO->isComparisonOp())
866 return this->emitComplexComparison(LHS, RHS, BO);
867 if (LHS->getType()->isFixedPointType() || RHS->getType()->isFixedPointType())
868 return this->VisitFixedPointBinOp(BO);
869
870 if (BO->isPtrMemOp()) {
871 if (!this->visit(LHS))
872 return false;
873
874 if (!this->visit(RHS))
875 return false;
876
877 if (!this->emitToMemberPtr(BO))
878 return false;
879
880 if (classifyPrim(BO) == PT_MemberPtr)
881 return true;
882
883 if (!this->emitCastMemberPtrPtr(BO))
884 return false;
885 return DiscardResult ? this->emitPopPtr(BO) : true;
886 }
887
888 // Typecheck the args.
889 OptPrimType LT = classify(LHS);
890 OptPrimType RT = classify(RHS);
891 OptPrimType T = classify(BO->getType());
892
893 // Special case for C++'s three-way/spaceship operator <=>, which
894 // returns a std::{strong,weak,partial}_ordering (which is a class, so doesn't
895 // have a PrimType).
896 if (!T && BO->getOpcode() == BO_Cmp) {
897 if (DiscardResult)
898 return true;
899 const ComparisonCategoryInfo *CmpInfo =
900 Ctx.getASTContext().CompCategories.lookupInfoForType(BO->getType());
901 assert(CmpInfo);
902
903 // We need a temporary variable holding our return value.
904 if (!Initializing) {
905 UnsignedOrNone ResultIndex = this->allocateLocal(BO);
906 if (!this->emitGetPtrLocal(*ResultIndex, BO))
907 return false;
908 }
909
910 if (!visit(LHS) || !visit(RHS))
911 return false;
912
913 return this->emitCMP3(*LT, CmpInfo, BO);
914 }
915
916 if (!LT || !RT || !T)
917 return false;
918
919 // Pointer arithmetic special case.
920 if (BO->getOpcode() == BO_Add || BO->getOpcode() == BO_Sub) {
921 if (isPtrType(*T) || (isPtrType(*LT) && isPtrType(*RT)))
922 return this->VisitPointerArithBinOp(BO);
923 }
924
925 if (BO->getOpcode() == BO_Assign)
926 return this->visitAssignment(LHS, RHS, BO);
927
928 if (!visit(LHS) || !visit(RHS))
929 return false;
930
931 // For languages such as C, cast the result of one
932 // of our comparision opcodes to T (which is usually int).
933 auto MaybeCastToBool = [this, T, BO](bool Result) {
934 if (!Result)
935 return false;
936 if (DiscardResult)
937 return this->emitPopBool(BO);
938 if (T != PT_Bool)
939 return this->emitCast(PT_Bool, *T, BO);
940 return true;
941 };
942
943 auto Discard = [this, T, BO](bool Result) {
944 if (!Result)
945 return false;
946 return DiscardResult ? this->emitPop(*T, BO) : true;
947 };
948
949 switch (BO->getOpcode()) {
950 case BO_EQ:
951 return MaybeCastToBool(this->emitEQ(*LT, BO));
952 case BO_NE:
953 return MaybeCastToBool(this->emitNE(*LT, BO));
954 case BO_LT:
955 return MaybeCastToBool(this->emitLT(*LT, BO));
956 case BO_LE:
957 return MaybeCastToBool(this->emitLE(*LT, BO));
958 case BO_GT:
959 return MaybeCastToBool(this->emitGT(*LT, BO));
960 case BO_GE:
961 return MaybeCastToBool(this->emitGE(*LT, BO));
962 case BO_Sub:
963 if (BO->getType()->isFloatingType())
964 return Discard(this->emitSubf(getFPOptions(BO), BO));
965 return Discard(this->emitSub(*T, BO));
966 case BO_Add:
967 if (BO->getType()->isFloatingType())
968 return Discard(this->emitAddf(getFPOptions(BO), BO));
969 return Discard(this->emitAdd(*T, BO));
970 case BO_Mul:
971 if (BO->getType()->isFloatingType())
972 return Discard(this->emitMulf(getFPOptions(BO), BO));
973 return Discard(this->emitMul(*T, BO));
974 case BO_Rem:
975 return Discard(this->emitRem(*T, BO));
976 case BO_Div:
977 if (BO->getType()->isFloatingType())
978 return Discard(this->emitDivf(getFPOptions(BO), BO));
979 return Discard(this->emitDiv(*T, BO));
980 case BO_And:
981 return Discard(this->emitBitAnd(*T, BO));
982 case BO_Or:
983 return Discard(this->emitBitOr(*T, BO));
984 case BO_Shl:
985 return Discard(this->emitShl(*LT, *RT, BO));
986 case BO_Shr:
987 return Discard(this->emitShr(*LT, *RT, BO));
988 case BO_Xor:
989 return Discard(this->emitBitXor(*T, BO));
990 case BO_LOr:
991 case BO_LAnd:
992 llvm_unreachable("Already handled earlier");
993 default:
994 return false;
995 }
996
997 llvm_unreachable("Unhandled binary op");
998}
999
1000/// Perform addition/subtraction of a pointer and an integer or
1001/// subtraction of two pointers.
1002template <class Emitter>
1004 BinaryOperatorKind Op = E->getOpcode();
1005 const Expr *LHS = E->getLHS();
1006 const Expr *RHS = E->getRHS();
1007
1008 if ((Op != BO_Add && Op != BO_Sub) ||
1009 (!LHS->getType()->isPointerType() && !RHS->getType()->isPointerType()))
1010 return false;
1011
1012 OptPrimType LT = classify(LHS);
1013 OptPrimType RT = classify(RHS);
1014
1015 if (!LT || !RT)
1016 return false;
1017
1018 // Visit the given pointer expression and optionally convert to a PT_Ptr.
1019 auto visitAsPointer = [&](const Expr *E, PrimType T) -> bool {
1020 if (!this->visit(E))
1021 return false;
1022 if (T != PT_Ptr)
1023 return this->emitDecayPtr(T, PT_Ptr, E);
1024 return true;
1025 };
1026
1027 if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) {
1028 if (Op != BO_Sub)
1029 return false;
1030
1031 assert(E->getType()->isIntegerType());
1032 if (!visitAsPointer(RHS, *RT) || !visitAsPointer(LHS, *LT))
1033 return false;
1034
1035 PrimType IntT = classifyPrim(E->getType());
1036 if (!this->emitSubPtr(IntT, E))
1037 return false;
1038 return DiscardResult ? this->emitPop(IntT, E) : true;
1039 }
1040
1041 PrimType OffsetType;
1042 if (LHS->getType()->isIntegerType()) {
1043 if (!visitAsPointer(RHS, *RT))
1044 return false;
1045 if (!this->visit(LHS))
1046 return false;
1047 OffsetType = *LT;
1048 } else if (RHS->getType()->isIntegerType()) {
1049 if (!visitAsPointer(LHS, *LT))
1050 return false;
1051 if (!this->visit(RHS))
1052 return false;
1053 OffsetType = *RT;
1054 } else {
1055 return false;
1056 }
1057
1058 // Do the operation and optionally transform to
1059 // result pointer type.
1060 if (Op == BO_Add) {
1061 if (!this->emitAddOffset(OffsetType, E))
1062 return false;
1063
1064 if (classifyPrim(E) != PT_Ptr)
1065 return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
1066 return true;
1067 }
1068 if (Op == BO_Sub) {
1069 if (!this->emitSubOffset(OffsetType, E))
1070 return false;
1071
1072 if (classifyPrim(E) != PT_Ptr)
1073 return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
1074 return true;
1075 }
1076
1077 return false;
1078}
1079
1080template <class Emitter>
1082 assert(E->isLogicalOp());
1083 BinaryOperatorKind Op = E->getOpcode();
1084 const Expr *LHS = E->getLHS();
1085 const Expr *RHS = E->getRHS();
1086 OptPrimType T = classify(E->getType());
1087
1088 if (Op == BO_LOr) {
1089 // Logical OR. Visit LHS and only evaluate RHS if LHS was FALSE.
1090 LabelTy LabelTrue = this->getLabel();
1091 LabelTy LabelEnd = this->getLabel();
1092
1093 if (!this->visitBool(LHS))
1094 return false;
1095 if (!this->jumpTrue(LabelTrue))
1096 return false;
1097
1098 if (!this->visitBool(RHS))
1099 return false;
1100 if (!this->jump(LabelEnd))
1101 return false;
1102
1103 this->emitLabel(LabelTrue);
1104 this->emitConstBool(true, E);
1105 this->fallthrough(LabelEnd);
1106 this->emitLabel(LabelEnd);
1107
1108 } else {
1109 assert(Op == BO_LAnd);
1110 // Logical AND.
1111 // Visit LHS. Only visit RHS if LHS was TRUE.
1112 LabelTy LabelFalse = this->getLabel();
1113 LabelTy LabelEnd = this->getLabel();
1114
1115 if (!this->visitBool(LHS))
1116 return false;
1117 if (!this->jumpFalse(LabelFalse))
1118 return false;
1119
1120 if (!this->visitBool(RHS))
1121 return false;
1122 if (!this->jump(LabelEnd))
1123 return false;
1124
1125 this->emitLabel(LabelFalse);
1126 this->emitConstBool(false, E);
1127 this->fallthrough(LabelEnd);
1128 this->emitLabel(LabelEnd);
1129 }
1130
1131 if (DiscardResult)
1132 return this->emitPopBool(E);
1133
1134 // For C, cast back to integer type.
1135 assert(T);
1136 if (T != PT_Bool)
1137 return this->emitCast(PT_Bool, *T, E);
1138 return true;
1139}
1140
1141template <class Emitter>
1143 // Prepare storage for result.
1144 if (!Initializing) {
1145 UnsignedOrNone LocalIndex = allocateTemporary(E);
1146 if (!LocalIndex)
1147 return false;
1148 if (!this->emitGetPtrLocal(*LocalIndex, E))
1149 return false;
1150 }
1151
1152 // Both LHS and RHS might _not_ be of complex type, but one of them
1153 // needs to be.
1154 const Expr *LHS = E->getLHS();
1155 const Expr *RHS = E->getRHS();
1156
1157 PrimType ResultElemT = this->classifyComplexElementType(E->getType());
1158 unsigned ResultOffset = ~0u;
1159 if (!DiscardResult)
1160 ResultOffset = this->allocateLocalPrimitive(E, PT_Ptr, /*IsConst=*/true);
1161
1162 // Save result pointer in ResultOffset
1163 if (!this->DiscardResult) {
1164 if (!this->emitDupPtr(E))
1165 return false;
1166 if (!this->emitSetLocal(PT_Ptr, ResultOffset, E))
1167 return false;
1168 }
1169 QualType LHSType = LHS->getType();
1170 if (const auto *AT = LHSType->getAs<AtomicType>())
1171 LHSType = AT->getValueType();
1172 QualType RHSType = RHS->getType();
1173 if (const auto *AT = RHSType->getAs<AtomicType>())
1174 RHSType = AT->getValueType();
1175
1176 bool LHSIsComplex = LHSType->isAnyComplexType();
1177 unsigned LHSOffset;
1178 bool RHSIsComplex = RHSType->isAnyComplexType();
1179
1180 // For ComplexComplex Mul, we have special ops to make their implementation
1181 // easier.
1182 BinaryOperatorKind Op = E->getOpcode();
1183 if (Op == BO_Mul && LHSIsComplex && RHSIsComplex) {
1184 assert(classifyPrim(LHSType->getAs<ComplexType>()->getElementType()) ==
1186 PrimType ElemT =
1188 if (!this->visit(LHS))
1189 return false;
1190 if (!this->visit(RHS))
1191 return false;
1192 return this->emitMulc(ElemT, E);
1193 }
1194
1195 if (Op == BO_Div && RHSIsComplex) {
1196 QualType ElemQT = RHSType->getAs<ComplexType>()->getElementType();
1197 PrimType ElemT = classifyPrim(ElemQT);
1198 // If the LHS is not complex, we still need to do the full complex
1199 // division, so just stub create a complex value and stub it out with
1200 // the LHS and a zero.
1201
1202 if (!LHSIsComplex) {
1203 // This is using the RHS type for the fake-complex LHS.
1204 UnsignedOrNone LocalIndex = allocateTemporary(RHS);
1205 if (!LocalIndex)
1206 return false;
1207 LHSOffset = *LocalIndex;
1208
1209 if (!this->emitGetPtrLocal(LHSOffset, E))
1210 return false;
1211
1212 if (!this->visit(LHS))
1213 return false;
1214 // real is LHS
1215 if (!this->emitInitElem(ElemT, 0, E))
1216 return false;
1217 // imag is zero
1218 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1219 return false;
1220 if (!this->emitInitElem(ElemT, 1, E))
1221 return false;
1222 } else {
1223 if (!this->visit(LHS))
1224 return false;
1225 }
1226
1227 if (!this->visit(RHS))
1228 return false;
1229 return this->emitDivc(ElemT, E);
1230 }
1231
1232 // Evaluate LHS and save value to LHSOffset.
1233 if (LHSType->isAnyComplexType()) {
1234 LHSOffset = this->allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
1235 if (!this->visit(LHS))
1236 return false;
1237 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
1238 return false;
1239 } else {
1240 PrimType LHST = classifyPrim(LHSType);
1241 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, /*IsConst=*/true);
1242 if (!this->visit(LHS))
1243 return false;
1244 if (!this->emitSetLocal(LHST, LHSOffset, E))
1245 return false;
1246 }
1247
1248 // Same with RHS.
1249 unsigned RHSOffset;
1250 if (RHSType->isAnyComplexType()) {
1251 RHSOffset = this->allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
1252 if (!this->visit(RHS))
1253 return false;
1254 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
1255 return false;
1256 } else {
1257 PrimType RHST = classifyPrim(RHSType);
1258 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, /*IsConst=*/true);
1259 if (!this->visit(RHS))
1260 return false;
1261 if (!this->emitSetLocal(RHST, RHSOffset, E))
1262 return false;
1263 }
1264
1265 // For both LHS and RHS, either load the value from the complex pointer, or
1266 // directly from the local variable. For index 1 (i.e. the imaginary part),
1267 // just load 0 and do the operation anyway.
1268 auto loadComplexValue = [this](bool IsComplex, bool LoadZero,
1269 unsigned ElemIndex, unsigned Offset,
1270 const Expr *E) -> bool {
1271 if (IsComplex) {
1272 if (!this->emitGetLocal(PT_Ptr, Offset, E))
1273 return false;
1274 return this->emitArrayElemPop(classifyComplexElementType(E->getType()),
1275 ElemIndex, E);
1276 }
1277 if (ElemIndex == 0 || !LoadZero)
1278 return this->emitGetLocal(classifyPrim(E->getType()), Offset, E);
1279 return this->visitZeroInitializer(classifyPrim(E->getType()), E->getType(),
1280 E);
1281 };
1282
1283 // Now we can get pointers to the LHS and RHS from the offsets above.
1284 for (unsigned ElemIndex = 0; ElemIndex != 2; ++ElemIndex) {
1285 // Result pointer for the store later.
1286 if (!this->DiscardResult) {
1287 if (!this->emitGetLocal(PT_Ptr, ResultOffset, E))
1288 return false;
1289 }
1290
1291 // The actual operation.
1292 switch (Op) {
1293 case BO_Add:
1294 if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1295 return false;
1296
1297 if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1298 return false;
1299 if (ResultElemT == PT_Float) {
1300 if (!this->emitAddf(getFPOptions(E), E))
1301 return false;
1302 } else {
1303 if (!this->emitAdd(ResultElemT, E))
1304 return false;
1305 }
1306 break;
1307 case BO_Sub:
1308 if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1309 return false;
1310
1311 if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1312 return false;
1313 if (ResultElemT == PT_Float) {
1314 if (!this->emitSubf(getFPOptions(E), E))
1315 return false;
1316 } else {
1317 if (!this->emitSub(ResultElemT, E))
1318 return false;
1319 }
1320 break;
1321 case BO_Mul:
1322 if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1323 return false;
1324
1325 if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1326 return false;
1327
1328 if (ResultElemT == PT_Float) {
1329 if (!this->emitMulf(getFPOptions(E), E))
1330 return false;
1331 } else {
1332 if (!this->emitMul(ResultElemT, E))
1333 return false;
1334 }
1335 break;
1336 case BO_Div:
1337 assert(!RHSIsComplex);
1338 if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1339 return false;
1340
1341 if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1342 return false;
1343
1344 if (ResultElemT == PT_Float) {
1345 if (!this->emitDivf(getFPOptions(E), E))
1346 return false;
1347 } else {
1348 if (!this->emitDiv(ResultElemT, E))
1349 return false;
1350 }
1351 break;
1352
1353 default:
1354 return false;
1355 }
1356
1357 if (!this->DiscardResult) {
1358 // Initialize array element with the value we just computed.
1359 if (!this->emitInitElemPop(ResultElemT, ElemIndex, E))
1360 return false;
1361 } else {
1362 if (!this->emitPop(ResultElemT, E))
1363 return false;
1364 }
1365 }
1366 return true;
1367}
1368
1369template <class Emitter>
1371 const Expr *LHS = E->getLHS();
1372 const Expr *RHS = E->getRHS();
1373 assert(!E->isCommaOp() &&
1374 "Comma op should be handled in VisitBinaryOperator");
1375 assert(E->getType()->isVectorType());
1376 assert(LHS->getType()->isVectorType());
1377 assert(RHS->getType()->isVectorType());
1378
1379 // We can only handle vectors with primitive element types.
1381 return false;
1382
1383 // Prepare storage for result.
1384 if (!Initializing && !E->isCompoundAssignmentOp() && !E->isAssignmentOp()) {
1385 UnsignedOrNone LocalIndex = allocateTemporary(E);
1386 if (!LocalIndex)
1387 return false;
1388 if (!this->emitGetPtrLocal(*LocalIndex, E))
1389 return false;
1390 }
1391
1392 const auto *VecTy = E->getType()->getAs<VectorType>();
1393 auto Op = E->isCompoundAssignmentOp()
1395 : E->getOpcode();
1396
1397 PrimType ElemT = this->classifyVectorElementType(LHS->getType());
1398 PrimType RHSElemT = this->classifyVectorElementType(RHS->getType());
1399 PrimType ResultElemT = this->classifyVectorElementType(E->getType());
1400
1401 if (E->getOpcode() == BO_Assign) {
1402 assert(Ctx.getASTContext().hasSameUnqualifiedType(
1404 RHS->getType()->castAs<VectorType>()->getElementType()));
1405 if (!this->visit(LHS))
1406 return false;
1407 if (!this->visit(RHS))
1408 return false;
1409 if (!this->emitCopyArray(ElemT, 0, 0, VecTy->getNumElements(), E))
1410 return false;
1411 if (DiscardResult)
1412 return this->emitPopPtr(E);
1413 return true;
1414 }
1415
1416 // Evaluate LHS and save value to LHSOffset.
1417 unsigned LHSOffset =
1418 this->allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
1419 if (!this->visit(LHS))
1420 return false;
1421 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
1422 return false;
1423
1424 // Evaluate RHS and save value to RHSOffset.
1425 unsigned RHSOffset =
1426 this->allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
1427 if (!this->visit(RHS))
1428 return false;
1429 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
1430 return false;
1431
1432 if (E->isCompoundAssignmentOp() && !this->emitGetLocal(PT_Ptr, LHSOffset, E))
1433 return false;
1434
1435 // BitAdd/BitOr/BitXor/Shl/Shr doesn't support bool type, we need perform the
1436 // integer promotion.
1437 bool NeedIntPromot = ElemT == PT_Bool && (E->isBitwiseOp() || E->isShiftOp());
1438 QualType PromotTy;
1439 PrimType PromotT = PT_Bool;
1440 PrimType OpT = ElemT;
1441 if (NeedIntPromot) {
1442 PromotTy =
1443 Ctx.getASTContext().getPromotedIntegerType(Ctx.getASTContext().BoolTy);
1444 PromotT = classifyPrim(PromotTy);
1445 OpT = PromotT;
1446 }
1447
1448 auto getElem = [=](unsigned Offset, PrimType ElemT, unsigned Index) {
1449 if (!this->emitGetLocal(PT_Ptr, Offset, E))
1450 return false;
1451 if (!this->emitArrayElemPop(ElemT, Index, E))
1452 return false;
1453 if (E->isLogicalOp()) {
1454 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
1455 return false;
1456 if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), E))
1457 return false;
1458 } else if (NeedIntPromot) {
1459 if (!this->emitPrimCast(ElemT, PromotT, PromotTy, E))
1460 return false;
1461 }
1462 return true;
1463 };
1464
1465#define EMIT_ARITH_OP(OP) \
1466 { \
1467 if (ElemT == PT_Float) { \
1468 if (!this->emit##OP##f(getFPOptions(E), E)) \
1469 return false; \
1470 } else { \
1471 if (!this->emit##OP(ElemT, E)) \
1472 return false; \
1473 } \
1474 break; \
1475 }
1476
1477 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
1478 if (!getElem(LHSOffset, ElemT, I))
1479 return false;
1480 if (!getElem(RHSOffset, RHSElemT, I))
1481 return false;
1482 switch (Op) {
1483 case BO_Add:
1485 case BO_Sub:
1487 case BO_Mul:
1489 case BO_Div:
1491 case BO_Rem:
1492 if (!this->emitRem(ElemT, E))
1493 return false;
1494 break;
1495 case BO_And:
1496 if (!this->emitBitAnd(OpT, E))
1497 return false;
1498 break;
1499 case BO_Or:
1500 if (!this->emitBitOr(OpT, E))
1501 return false;
1502 break;
1503 case BO_Xor:
1504 if (!this->emitBitXor(OpT, E))
1505 return false;
1506 break;
1507 case BO_Shl:
1508 if (!this->emitShl(OpT, RHSElemT, E))
1509 return false;
1510 break;
1511 case BO_Shr:
1512 if (!this->emitShr(OpT, RHSElemT, E))
1513 return false;
1514 break;
1515 case BO_EQ:
1516 if (!this->emitEQ(ElemT, E))
1517 return false;
1518 break;
1519 case BO_NE:
1520 if (!this->emitNE(ElemT, E))
1521 return false;
1522 break;
1523 case BO_LE:
1524 if (!this->emitLE(ElemT, E))
1525 return false;
1526 break;
1527 case BO_LT:
1528 if (!this->emitLT(ElemT, E))
1529 return false;
1530 break;
1531 case BO_GE:
1532 if (!this->emitGE(ElemT, E))
1533 return false;
1534 break;
1535 case BO_GT:
1536 if (!this->emitGT(ElemT, E))
1537 return false;
1538 break;
1539 case BO_LAnd:
1540 // a && b is equivalent to a!=0 & b!=0
1541 if (!this->emitBitAnd(ResultElemT, E))
1542 return false;
1543 break;
1544 case BO_LOr:
1545 // a || b is equivalent to a!=0 | b!=0
1546 if (!this->emitBitOr(ResultElemT, E))
1547 return false;
1548 break;
1549 default:
1550 return this->emitInvalid(E);
1551 }
1552
1553 // The result of the comparison is a vector of the same width and number
1554 // of elements as the comparison operands with a signed integral element
1555 // type.
1556 //
1557 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
1558 if (E->isComparisonOp()) {
1559 if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), E))
1560 return false;
1561 if (!this->emitNeg(ResultElemT, E))
1562 return false;
1563 }
1564
1565 // If we performed an integer promotion, we need to cast the compute result
1566 // into result vector element type.
1567 if (NeedIntPromot &&
1568 !this->emitPrimCast(PromotT, ResultElemT, VecTy->getElementType(), E))
1569 return false;
1570
1571 // Initialize array element with the value we just computed.
1572 if (!this->emitInitElem(ResultElemT, I, E))
1573 return false;
1574 }
1575
1576 if (DiscardResult && E->isCompoundAssignmentOp() && !this->emitPopPtr(E))
1577 return false;
1578 return true;
1579}
1580
1581template <class Emitter>
1583 const Expr *LHS = E->getLHS();
1584 const Expr *RHS = E->getRHS();
1585 const ASTContext &ASTCtx = Ctx.getASTContext();
1586
1587 assert(LHS->getType()->isFixedPointType() ||
1588 RHS->getType()->isFixedPointType());
1589
1590 auto LHSSema = ASTCtx.getFixedPointSemantics(LHS->getType());
1591 auto LHSSemaInt = LHSSema.toOpaqueInt();
1592 auto RHSSema = ASTCtx.getFixedPointSemantics(RHS->getType());
1593 auto RHSSemaInt = RHSSema.toOpaqueInt();
1594
1595 if (!this->visit(LHS))
1596 return false;
1597 if (!LHS->getType()->isFixedPointType()) {
1598 if (!this->emitCastIntegralFixedPoint(classifyPrim(LHS->getType()),
1599 LHSSemaInt, E))
1600 return false;
1601 }
1602
1603 if (!this->visit(RHS))
1604 return false;
1605 if (!RHS->getType()->isFixedPointType()) {
1606 if (!this->emitCastIntegralFixedPoint(classifyPrim(RHS->getType()),
1607 RHSSemaInt, E))
1608 return false;
1609 }
1610
1611 // Convert the result to the target semantics.
1612 auto ConvertResult = [&](bool R) -> bool {
1613 if (!R)
1614 return false;
1615 auto ResultSema = ASTCtx.getFixedPointSemantics(E->getType()).toOpaqueInt();
1616 auto CommonSema = LHSSema.getCommonSemantics(RHSSema).toOpaqueInt();
1617 if (ResultSema != CommonSema)
1618 return this->emitCastFixedPoint(ResultSema, E);
1619 return true;
1620 };
1621
1622 auto MaybeCastToBool = [&](bool Result) {
1623 if (!Result)
1624 return false;
1625 PrimType T = classifyPrim(E);
1626 if (DiscardResult)
1627 return this->emitPop(T, E);
1628 if (T != PT_Bool)
1629 return this->emitCast(PT_Bool, T, E);
1630 return true;
1631 };
1632
1633 switch (E->getOpcode()) {
1634 case BO_EQ:
1635 return MaybeCastToBool(this->emitEQFixedPoint(E));
1636 case BO_NE:
1637 return MaybeCastToBool(this->emitNEFixedPoint(E));
1638 case BO_LT:
1639 return MaybeCastToBool(this->emitLTFixedPoint(E));
1640 case BO_LE:
1641 return MaybeCastToBool(this->emitLEFixedPoint(E));
1642 case BO_GT:
1643 return MaybeCastToBool(this->emitGTFixedPoint(E));
1644 case BO_GE:
1645 return MaybeCastToBool(this->emitGEFixedPoint(E));
1646 case BO_Add:
1647 return ConvertResult(this->emitAddFixedPoint(E));
1648 case BO_Sub:
1649 return ConvertResult(this->emitSubFixedPoint(E));
1650 case BO_Mul:
1651 return ConvertResult(this->emitMulFixedPoint(E));
1652 case BO_Div:
1653 return ConvertResult(this->emitDivFixedPoint(E));
1654 case BO_Shl:
1655 return ConvertResult(this->emitShiftFixedPoint(/*Left=*/true, E));
1656 case BO_Shr:
1657 return ConvertResult(this->emitShiftFixedPoint(/*Left=*/false, E));
1658
1659 default:
1660 return this->emitInvalid(E);
1661 }
1662
1663 llvm_unreachable("unhandled binop opcode");
1664}
1665
1666template <class Emitter>
1668 const Expr *SubExpr = E->getSubExpr();
1669 assert(SubExpr->getType()->isFixedPointType());
1670
1671 switch (E->getOpcode()) {
1672 case UO_Plus:
1673 return this->delegate(SubExpr);
1674 case UO_Minus:
1675 if (!this->visit(SubExpr))
1676 return false;
1677 return this->emitNegFixedPoint(E);
1678 default:
1679 return false;
1680 }
1681
1682 llvm_unreachable("Unhandled unary opcode");
1683}
1684
1685template <class Emitter>
1687 const ImplicitValueInitExpr *E) {
1688 QualType QT = E->getType();
1689
1690 if (OptPrimType T = classify(QT))
1691 return this->visitZeroInitializer(*T, QT, E);
1692
1693 if (QT->isRecordType()) {
1694 const RecordDecl *RD = QT->getAsRecordDecl();
1695 assert(RD);
1696 if (RD->isInvalidDecl())
1697 return false;
1698
1699 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1700 CXXRD && CXXRD->getNumVBases() > 0) {
1701 // TODO: Diagnose.
1702 return false;
1703 }
1704
1705 const Record *R = getRecord(QT);
1706 if (!R)
1707 return false;
1708
1709 assert(Initializing);
1710 return this->visitZeroRecordInitializer(R, E);
1711 }
1712
1713 if (QT->isIncompleteArrayType())
1714 return true;
1715
1716 if (QT->isArrayType())
1717 return this->visitZeroArrayInitializer(QT, E);
1718
1719 if (const auto *ComplexTy = E->getType()->getAs<ComplexType>()) {
1720 assert(Initializing);
1721 QualType ElemQT = ComplexTy->getElementType();
1722 PrimType ElemT = classifyPrim(ElemQT);
1723 for (unsigned I = 0; I < 2; ++I) {
1724 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1725 return false;
1726 if (!this->emitInitElem(ElemT, I, E))
1727 return false;
1728 }
1729 return true;
1730 }
1731
1732 if (const auto *VecT = E->getType()->getAs<VectorType>()) {
1733 unsigned NumVecElements = VecT->getNumElements();
1734 QualType ElemQT = VecT->getElementType();
1735 PrimType ElemT = classifyPrim(ElemQT);
1736
1737 for (unsigned I = 0; I < NumVecElements; ++I) {
1738 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1739 return false;
1740 if (!this->emitInitElem(ElemT, I, E))
1741 return false;
1742 }
1743 return true;
1744 }
1745
1746 return false;
1747}
1748
1749template <class Emitter>
1751 const Expr *LHS = E->getLHS();
1752 const Expr *RHS = E->getRHS();
1753 const Expr *Index = E->getIdx();
1754 const Expr *Base = E->getBase();
1755
1756 // C++17's rules require us to evaluate the LHS first, regardless of which
1757 // side is the base.
1758 bool Success = true;
1759 for (const Expr *SubExpr : {LHS, RHS}) {
1760 if (!this->visit(SubExpr)) {
1761 Success = false;
1762 continue;
1763 }
1764
1765 // Expand the base if this is a subscript on a
1766 // pointer expression.
1767 if (SubExpr == Base && Base->getType()->isPointerType()) {
1768 if (!this->emitExpandPtr(E))
1769 Success = false;
1770 }
1771 }
1772
1773 if (!Success)
1774 return false;
1775
1776 OptPrimType IndexT = classify(Index->getType());
1777 // In error-recovery cases, the index expression has a dependent type.
1778 if (!IndexT)
1779 return this->emitError(E);
1780 // If the index is first, we need to change that.
1781 if (LHS == Index) {
1782 if (!this->emitFlip(PT_Ptr, *IndexT, E))
1783 return false;
1784 }
1785
1786 if (!this->emitArrayElemPtrPop(*IndexT, E))
1787 return false;
1788 if (DiscardResult)
1789 return this->emitPopPtr(E);
1790 return true;
1791}
1792
1793template <class Emitter>
1795 const Expr *ArrayFiller, const Expr *E) {
1797
1798 QualType QT = E->getType();
1799 if (const auto *AT = QT->getAs<AtomicType>())
1800 QT = AT->getValueType();
1801
1802 if (QT->isVoidType()) {
1803 if (Inits.size() == 0)
1804 return true;
1805 return this->emitInvalid(E);
1806 }
1807
1808 // Handle discarding first.
1809 if (DiscardResult) {
1810 for (const Expr *Init : Inits) {
1811 if (!this->discard(Init))
1812 return false;
1813 }
1814 return true;
1815 }
1816
1817 // Primitive values.
1818 if (OptPrimType T = classify(QT)) {
1819 assert(!DiscardResult);
1820 if (Inits.size() == 0)
1821 return this->visitZeroInitializer(*T, QT, E);
1822 assert(Inits.size() == 1);
1823 return this->delegate(Inits[0]);
1824 }
1825
1826 if (QT->isRecordType()) {
1827 const Record *R = getRecord(QT);
1828
1829 if (Inits.size() == 1 && E->getType() == Inits[0]->getType())
1830 return this->delegate(Inits[0]);
1831
1832 if (!R)
1833 return false;
1834
1835 auto initPrimitiveField = [=](const Record::Field *FieldToInit,
1836 const Expr *Init, PrimType T,
1837 bool Activate = false) -> bool {
1839 InitLinkScope<Emitter> ILS(this, InitLink::Field(FieldToInit->Offset));
1840 if (!this->visit(Init))
1841 return false;
1842
1843 bool BitField = FieldToInit->isBitField();
1844 if (BitField && Activate)
1845 return this->emitInitBitFieldActivate(T, FieldToInit, E);
1846 if (BitField)
1847 return this->emitInitBitField(T, FieldToInit, E);
1848 if (Activate)
1849 return this->emitInitFieldActivate(T, FieldToInit->Offset, E);
1850 return this->emitInitField(T, FieldToInit->Offset, E);
1851 };
1852
1853 auto initCompositeField = [=](const Record::Field *FieldToInit,
1854 const Expr *Init,
1855 bool Activate = false) -> bool {
1857 InitLinkScope<Emitter> ILS(this, InitLink::Field(FieldToInit->Offset));
1858
1859 // Non-primitive case. Get a pointer to the field-to-initialize
1860 // on the stack and recurse into visitInitializer().
1861 if (!this->emitGetPtrField(FieldToInit->Offset, Init))
1862 return false;
1863
1864 if (Activate && !this->emitActivate(E))
1865 return false;
1866
1867 if (!this->visitInitializer(Init))
1868 return false;
1869 return this->emitPopPtr(E);
1870 };
1871
1872 if (R->isUnion()) {
1873 if (Inits.size() == 0) {
1874 if (!this->visitZeroRecordInitializer(R, E))
1875 return false;
1876 } else {
1877 const Expr *Init = Inits[0];
1878 const FieldDecl *FToInit = nullptr;
1879 if (const auto *ILE = dyn_cast<InitListExpr>(E))
1880 FToInit = ILE->getInitializedFieldInUnion();
1881 else
1882 FToInit = cast<CXXParenListInitExpr>(E)->getInitializedFieldInUnion();
1883
1884 const Record::Field *FieldToInit = R->getField(FToInit);
1885 if (OptPrimType T = classify(Init)) {
1886 if (!initPrimitiveField(FieldToInit, Init, *T, /*Activate=*/true))
1887 return false;
1888 } else {
1889 if (!initCompositeField(FieldToInit, Init, /*Activate=*/true))
1890 return false;
1891 }
1892 }
1893 return this->emitFinishInit(E);
1894 }
1895
1896 assert(!R->isUnion());
1897 unsigned InitIndex = 0;
1898 for (const Expr *Init : Inits) {
1899 // Skip unnamed bitfields.
1900 while (InitIndex < R->getNumFields() &&
1901 R->getField(InitIndex)->isUnnamedBitField())
1902 ++InitIndex;
1903
1904 if (OptPrimType T = classify(Init)) {
1905 const Record::Field *FieldToInit = R->getField(InitIndex);
1906 if (!initPrimitiveField(FieldToInit, Init, *T))
1907 return false;
1908 ++InitIndex;
1909 } else {
1910 // Initializer for a direct base class.
1911 if (const Record::Base *B = R->getBase(Init->getType())) {
1912 if (!this->emitGetPtrBase(B->Offset, Init))
1913 return false;
1914
1915 if (!this->visitInitializer(Init))
1916 return false;
1917
1918 if (!this->emitFinishInitPop(E))
1919 return false;
1920 // Base initializers don't increase InitIndex, since they don't count
1921 // into the Record's fields.
1922 } else {
1923 const Record::Field *FieldToInit = R->getField(InitIndex);
1924 if (!initCompositeField(FieldToInit, Init))
1925 return false;
1926 ++InitIndex;
1927 }
1928 }
1929 }
1930 return this->emitFinishInit(E);
1931 }
1932
1933 if (QT->isArrayType()) {
1934 if (Inits.size() == 1 && QT == Inits[0]->getType())
1935 return this->delegate(Inits[0]);
1936
1937 const ConstantArrayType *CAT =
1938 Ctx.getASTContext().getAsConstantArrayType(QT);
1939 uint64_t NumElems = CAT->getZExtSize();
1940
1941 if (!this->emitCheckArraySize(NumElems, E))
1942 return false;
1943
1944 OptPrimType InitT = classify(CAT->getElementType());
1945 unsigned ElementIndex = 0;
1946 for (const Expr *Init : Inits) {
1947 if (const auto *EmbedS =
1948 dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
1949 PrimType TargetT = classifyPrim(Init->getType());
1950
1951 auto Eval = [&](const IntegerLiteral *IL, unsigned ElemIndex) {
1952 if (TargetT == PT_Float) {
1953 if (!this->emitConst(IL->getValue(), classifyPrim(IL), Init))
1954 return false;
1955 const auto *Sem = &Ctx.getFloatSemantics(CAT->getElementType());
1956 if (!this->emitCastIntegralFloating(classifyPrim(IL), Sem,
1957 getFPOptions(E), E))
1958 return false;
1959 } else {
1960 if (!this->emitConst(IL->getValue(), TargetT, Init))
1961 return false;
1962 }
1963 return this->emitInitElem(TargetT, ElemIndex, IL);
1964 };
1965 if (!EmbedS->doForEachDataElement(Eval, ElementIndex))
1966 return false;
1967 } else {
1968 if (!this->visitArrayElemInit(ElementIndex, Init, InitT))
1969 return false;
1970 ++ElementIndex;
1971 }
1972 }
1973
1974 // Expand the filler expression.
1975 // FIXME: This should go away.
1976 if (ArrayFiller) {
1977 for (; ElementIndex != NumElems; ++ElementIndex) {
1978 if (!this->visitArrayElemInit(ElementIndex, ArrayFiller, InitT))
1979 return false;
1980 }
1981 }
1982
1983 return this->emitFinishInit(E);
1984 }
1985
1986 if (const auto *ComplexTy = QT->getAs<ComplexType>()) {
1987 unsigned NumInits = Inits.size();
1988
1989 if (NumInits == 1)
1990 return this->delegate(Inits[0]);
1991
1992 QualType ElemQT = ComplexTy->getElementType();
1993 PrimType ElemT = classifyPrim(ElemQT);
1994 if (NumInits == 0) {
1995 // Zero-initialize both elements.
1996 for (unsigned I = 0; I < 2; ++I) {
1997 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1998 return false;
1999 if (!this->emitInitElem(ElemT, I, E))
2000 return false;
2001 }
2002 } else if (NumInits == 2) {
2003 unsigned InitIndex = 0;
2004 for (const Expr *Init : Inits) {
2005 if (!this->visit(Init))
2006 return false;
2007
2008 if (!this->emitInitElem(ElemT, InitIndex, E))
2009 return false;
2010 ++InitIndex;
2011 }
2012 }
2013 return true;
2014 }
2015
2016 if (const auto *VecT = QT->getAs<VectorType>()) {
2017 unsigned NumVecElements = VecT->getNumElements();
2018 assert(NumVecElements >= Inits.size());
2019
2020 QualType ElemQT = VecT->getElementType();
2021 PrimType ElemT = classifyPrim(ElemQT);
2022
2023 // All initializer elements.
2024 unsigned InitIndex = 0;
2025 for (const Expr *Init : Inits) {
2026 if (!this->visit(Init))
2027 return false;
2028
2029 // If the initializer is of vector type itself, we have to deconstruct
2030 // that and initialize all the target fields from the initializer fields.
2031 if (const auto *InitVecT = Init->getType()->getAs<VectorType>()) {
2032 if (!this->emitCopyArray(ElemT, 0, InitIndex,
2033 InitVecT->getNumElements(), E))
2034 return false;
2035 InitIndex += InitVecT->getNumElements();
2036 } else {
2037 if (!this->emitInitElem(ElemT, InitIndex, E))
2038 return false;
2039 ++InitIndex;
2040 }
2041 }
2042
2043 assert(InitIndex <= NumVecElements);
2044
2045 // Fill the rest with zeroes.
2046 for (; InitIndex != NumVecElements; ++InitIndex) {
2047 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2048 return false;
2049 if (!this->emitInitElem(ElemT, InitIndex, E))
2050 return false;
2051 }
2052 return true;
2053 }
2054
2055 return false;
2056}
2057
2058/// Pointer to the array(not the element!) must be on the stack when calling
2059/// this.
2060template <class Emitter>
2061bool Compiler<Emitter>::visitArrayElemInit(unsigned ElemIndex, const Expr *Init,
2062 OptPrimType InitT) {
2063 if (InitT) {
2064 // Visit the primitive element like normal.
2065 if (!this->visit(Init))
2066 return false;
2067 return this->emitInitElem(*InitT, ElemIndex, Init);
2068 }
2069
2070 InitLinkScope<Emitter> ILS(this, InitLink::Elem(ElemIndex));
2071 // Advance the pointer currently on the stack to the given
2072 // dimension.
2073 if (!this->emitConstUint32(ElemIndex, Init))
2074 return false;
2075 if (!this->emitArrayElemPtrUint32(Init))
2076 return false;
2077 if (!this->visitInitializer(Init))
2078 return false;
2079 return this->emitFinishInitPop(Init);
2080}
2081
2082template <class Emitter>
2084 const FunctionDecl *FuncDecl,
2085 bool Activate, bool IsOperatorCall) {
2086 assert(VarScope->getKind() == ScopeKind::Call);
2087 llvm::BitVector NonNullArgs;
2088 if (FuncDecl && FuncDecl->hasAttr<NonNullAttr>())
2089 NonNullArgs = collectNonNullArgs(FuncDecl, Args);
2090
2091 bool ExplicitMemberFn = false;
2092 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl))
2093 ExplicitMemberFn = MD->isExplicitObjectMemberFunction();
2094
2095 unsigned ArgIndex = 0;
2096 for (const Expr *Arg : Args) {
2097 if (canClassify(Arg)) {
2098 if (!this->visit(Arg))
2099 return false;
2100 } else {
2101
2102 DeclTy Source = Arg;
2103 if (FuncDecl) {
2104 // Try to use the parameter declaration instead of the argument
2105 // expression as a source.
2106 unsigned DeclIndex = ArgIndex - IsOperatorCall + ExplicitMemberFn;
2107 if (DeclIndex < FuncDecl->getNumParams())
2108 Source = FuncDecl->getParamDecl(ArgIndex - IsOperatorCall +
2109 ExplicitMemberFn);
2110 }
2111
2112 UnsignedOrNone LocalIndex =
2113 allocateLocal(std::move(Source), Arg->getType(),
2114 /*ExtendingDecl=*/nullptr, ScopeKind::Call);
2115 if (!LocalIndex)
2116 return false;
2117
2118 if (!this->emitGetPtrLocal(*LocalIndex, Arg))
2119 return false;
2120 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
2121 if (!this->visitInitializer(Arg))
2122 return false;
2123 }
2124
2125 if (ArgIndex == 1 && Activate) {
2126 if (!this->emitActivate(Arg))
2127 return false;
2128 }
2129
2130 if (!NonNullArgs.empty() && NonNullArgs[ArgIndex]) {
2131 PrimType ArgT = classify(Arg).value_or(PT_Ptr);
2132 if (ArgT == PT_Ptr) {
2133 if (!this->emitCheckNonNullArg(ArgT, Arg))
2134 return false;
2135 }
2136 }
2137
2138 ++ArgIndex;
2139 }
2140
2141 return true;
2142}
2143
2144template <class Emitter>
2146 return this->visitInitList(E->inits(), E->getArrayFiller(), E);
2147}
2148
2149template <class Emitter>
2154
2155template <class Emitter>
2160
2161template <class Emitter>
2163 OptPrimType T = classify(E->getType());
2164 if (T && E->hasAPValueResult()) {
2165 // Try to emit the APValue directly, without visiting the subexpr.
2166 // This will only fail if we can't emit the APValue, so won't emit any
2167 // diagnostics or any double values.
2168 if (DiscardResult)
2169 return true;
2170
2171 if (this->visitAPValue(E->getAPValueResult(), *T, E))
2172 return true;
2173 }
2174 return this->delegate(E->getSubExpr());
2175}
2176
2177template <class Emitter>
2179 auto It = E->begin();
2180 return this->visit(*It);
2181}
2182
2184 UnaryExprOrTypeTrait Kind) {
2185 bool AlignOfReturnsPreferred =
2186 ASTCtx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
2187
2188 // C++ [expr.alignof]p3:
2189 // When alignof is applied to a reference type, the result is the
2190 // alignment of the referenced type.
2191 if (const auto *Ref = T->getAs<ReferenceType>())
2192 T = Ref->getPointeeType();
2193
2194 if (T.getQualifiers().hasUnaligned())
2195 return CharUnits::One();
2196
2197 // __alignof is defined to return the preferred alignment.
2198 // Before 8, clang returned the preferred alignment for alignof and
2199 // _Alignof as well.
2200 if (Kind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
2201 return ASTCtx.toCharUnitsFromBits(ASTCtx.getPreferredTypeAlign(T));
2202
2203 return ASTCtx.getTypeAlignInChars(T);
2204}
2205
2206template <class Emitter>
2208 const UnaryExprOrTypeTraitExpr *E) {
2209 UnaryExprOrTypeTrait Kind = E->getKind();
2210 const ASTContext &ASTCtx = Ctx.getASTContext();
2211
2212 if (Kind == UETT_SizeOf || Kind == UETT_DataSizeOf) {
2214
2215 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2216 // the result is the size of the referenced type."
2217 if (const auto *Ref = ArgType->getAs<ReferenceType>())
2218 ArgType = Ref->getPointeeType();
2219
2220 CharUnits Size;
2221 if (ArgType->isVoidType() || ArgType->isFunctionType())
2222 Size = CharUnits::One();
2223 else {
2224 if (ArgType->isDependentType() || !ArgType->isConstantSizeType())
2225 return this->emitInvalid(E);
2226
2227 if (Kind == UETT_SizeOf)
2228 Size = ASTCtx.getTypeSizeInChars(ArgType);
2229 else
2231 }
2232
2233 if (DiscardResult)
2234 return true;
2235
2236 return this->emitConst(Size.getQuantity(), E);
2237 }
2238
2239 if (Kind == UETT_CountOf) {
2240 QualType Ty = E->getTypeOfArgument();
2241 assert(Ty->isArrayType());
2242
2243 // We don't need to worry about array element qualifiers, so getting the
2244 // unsafe array type is fine.
2245 if (const auto *CAT =
2246 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
2247 if (DiscardResult)
2248 return true;
2249 return this->emitConst(CAT->getSize(), E);
2250 }
2251
2252 assert(!Ty->isConstantSizeType());
2253
2254 // If it's a variable-length array type, we need to check whether it is a
2255 // multidimensional array. If so, we need to check the size expression of
2256 // the VLA to see if it's a constant size. If so, we can return that value.
2257 const auto *VAT = ASTCtx.getAsVariableArrayType(Ty);
2258 assert(VAT);
2259 if (VAT->getElementType()->isArrayType()) {
2260 std::optional<APSInt> Res =
2261 VAT->getSizeExpr()
2262 ? VAT->getSizeExpr()->getIntegerConstantExpr(ASTCtx)
2263 : std::nullopt;
2264 if (Res) {
2265 if (DiscardResult)
2266 return true;
2267 return this->emitConst(*Res, E);
2268 }
2269 }
2270 }
2271
2272 if (Kind == UETT_AlignOf || Kind == UETT_PreferredAlignOf) {
2273 CharUnits Size;
2274
2275 if (E->isArgumentType()) {
2277
2278 Size = AlignOfType(ArgType, ASTCtx, Kind);
2279 } else {
2280 // Argument is an expression, not a type.
2281 const Expr *Arg = E->getArgumentExpr()->IgnoreParens();
2282
2283 // The kinds of expressions that we have special-case logic here for
2284 // should be kept up to date with the special checks for those
2285 // expressions in Sema.
2286
2287 // alignof decl is always accepted, even if it doesn't make sense: we
2288 // default to 1 in those cases.
2289 if (const auto *DRE = dyn_cast<DeclRefExpr>(Arg))
2290 Size = ASTCtx.getDeclAlign(DRE->getDecl(),
2291 /*RefAsPointee*/ true);
2292 else if (const auto *ME = dyn_cast<MemberExpr>(Arg))
2293 Size = ASTCtx.getDeclAlign(ME->getMemberDecl(),
2294 /*RefAsPointee*/ true);
2295 else
2296 Size = AlignOfType(Arg->getType(), ASTCtx, Kind);
2297 }
2298
2299 if (DiscardResult)
2300 return true;
2301
2302 return this->emitConst(Size.getQuantity(), E);
2303 }
2304
2305 if (Kind == UETT_VectorElements) {
2306 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>())
2307 return this->emitConst(VT->getNumElements(), E);
2309 return this->emitSizelessVectorElementSize(E);
2310 }
2311
2312 if (Kind == UETT_VecStep) {
2313 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>()) {
2314 unsigned N = VT->getNumElements();
2315
2316 // The vec_step built-in functions that take a 3-component
2317 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2318 if (N == 3)
2319 N = 4;
2320
2321 return this->emitConst(N, E);
2322 }
2323 return this->emitConst(1, E);
2324 }
2325
2326 if (Kind == UETT_OpenMPRequiredSimdAlign) {
2327 assert(E->isArgumentType());
2328 unsigned Bits = ASTCtx.getOpenMPDefaultSimdAlign(E->getArgumentType());
2329
2330 return this->emitConst(ASTCtx.toCharUnitsFromBits(Bits).getQuantity(), E);
2331 }
2332
2333 if (Kind == UETT_PtrAuthTypeDiscriminator) {
2334 if (E->getArgumentType()->isDependentType())
2335 return this->emitInvalid(E);
2336
2337 return this->emitConst(
2338 const_cast<ASTContext &>(ASTCtx).getPointerAuthTypeDiscriminator(
2339 E->getArgumentType()),
2340 E);
2341 }
2342
2343 return false;
2344}
2345
2346template <class Emitter>
2348 // 'Base.Member'
2349 const Expr *Base = E->getBase();
2350 const ValueDecl *Member = E->getMemberDecl();
2351
2352 if (DiscardResult)
2353 return this->discard(Base);
2354
2355 // MemberExprs are almost always lvalues, in which case we don't need to
2356 // do the load. But sometimes they aren't.
2357 const auto maybeLoadValue = [&]() -> bool {
2358 if (E->isGLValue())
2359 return true;
2360 if (OptPrimType T = classify(E))
2361 return this->emitLoadPop(*T, E);
2362 return false;
2363 };
2364
2365 if (const auto *VD = dyn_cast<VarDecl>(Member)) {
2366 // I am almost confident in saying that a var decl must be static
2367 // and therefore registered as a global variable. But this will probably
2368 // turn out to be wrong some time in the future, as always.
2369 if (auto GlobalIndex = P.getGlobal(VD))
2370 return this->emitGetPtrGlobal(*GlobalIndex, E) && maybeLoadValue();
2371 return false;
2372 }
2373
2374 if (!isa<FieldDecl>(Member)) {
2375 if (!this->discard(Base) && !this->emitSideEffect(E))
2376 return false;
2377
2378 return this->visitDeclRef(Member, E);
2379 }
2380
2381 if (Initializing) {
2382 if (!this->delegate(Base))
2383 return false;
2384 } else {
2385 if (!this->visit(Base))
2386 return false;
2387 }
2388
2389 // Base above gives us a pointer on the stack.
2390 const auto *FD = cast<FieldDecl>(Member);
2391 const RecordDecl *RD = FD->getParent();
2392 const Record *R = getRecord(RD);
2393 if (!R)
2394 return false;
2395 const Record::Field *F = R->getField(FD);
2396 // Leave a pointer to the field on the stack.
2397 if (F->Decl->getType()->isReferenceType())
2398 return this->emitGetFieldPop(PT_Ptr, F->Offset, E) && maybeLoadValue();
2399 return this->emitGetPtrFieldPop(F->Offset, E) && maybeLoadValue();
2400}
2401
2402template <class Emitter>
2404 // ArrayIndex might not be set if a ArrayInitIndexExpr is being evaluated
2405 // stand-alone, e.g. via EvaluateAsInt().
2406 if (!ArrayIndex)
2407 return false;
2408 return this->emitConst(*ArrayIndex, E);
2409}
2410
2411template <class Emitter>
2413 assert(Initializing);
2414 assert(!DiscardResult);
2415
2416 // We visit the common opaque expression here once so we have its value
2417 // cached.
2418 if (!this->discard(E->getCommonExpr()))
2419 return false;
2420
2421 // TODO: This compiles to quite a lot of bytecode if the array is larger.
2422 // Investigate compiling this to a loop.
2423 const Expr *SubExpr = E->getSubExpr();
2424 size_t Size = E->getArraySize().getZExtValue();
2425 OptPrimType SubExprT = classify(SubExpr);
2426
2427 // So, every iteration, we execute an assignment here
2428 // where the LHS is on the stack (the target array)
2429 // and the RHS is our SubExpr.
2430 for (size_t I = 0; I != Size; ++I) {
2431 ArrayIndexScope<Emitter> IndexScope(this, I);
2432 BlockScope<Emitter> BS(this);
2433
2434 if (!this->visitArrayElemInit(I, SubExpr, SubExprT))
2435 return false;
2436 if (!BS.destroyLocals())
2437 return false;
2438 }
2439 return true;
2440}
2441
2442template <class Emitter>
2444 const Expr *SourceExpr = E->getSourceExpr();
2445 if (!SourceExpr)
2446 return false;
2447
2448 if (Initializing)
2449 return this->visitInitializer(SourceExpr);
2450
2451 PrimType SubExprT = classify(SourceExpr).value_or(PT_Ptr);
2452 if (auto It = OpaqueExprs.find(E); It != OpaqueExprs.end())
2453 return this->emitGetLocal(SubExprT, It->second, E);
2454
2455 if (!this->visit(SourceExpr))
2456 return false;
2457
2458 // At this point we either have the evaluated source expression or a pointer
2459 // to an object on the stack. We want to create a local variable that stores
2460 // this value.
2461 unsigned LocalIndex = allocateLocalPrimitive(E, SubExprT, /*IsConst=*/true);
2462 if (!this->emitSetLocal(SubExprT, LocalIndex, E))
2463 return false;
2464
2465 // Here the local variable is created but the value is removed from the stack,
2466 // so we put it back if the caller needs it.
2467 if (!DiscardResult) {
2468 if (!this->emitGetLocal(SubExprT, LocalIndex, E))
2469 return false;
2470 }
2471
2472 // This is cleaned up when the local variable is destroyed.
2473 OpaqueExprs.insert({E, LocalIndex});
2474
2475 return true;
2476}
2477
2478template <class Emitter>
2480 const AbstractConditionalOperator *E) {
2481 const Expr *Condition = E->getCond();
2482 const Expr *TrueExpr = E->getTrueExpr();
2483 const Expr *FalseExpr = E->getFalseExpr();
2484
2485 auto visitChildExpr = [&](const Expr *E) -> bool {
2486 LocalScope<Emitter> S(this);
2487 if (!this->delegate(E))
2488 return false;
2489 return S.destroyLocals();
2490 };
2491
2492 if (std::optional<bool> BoolValue = getBoolValue(Condition)) {
2493 if (BoolValue)
2494 return visitChildExpr(TrueExpr);
2495 return visitChildExpr(FalseExpr);
2496 }
2497
2498 bool IsBcpCall = false;
2499 if (const auto *CE = dyn_cast<CallExpr>(Condition->IgnoreParenCasts());
2500 CE && CE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) {
2501 IsBcpCall = true;
2502 }
2503
2504 LabelTy LabelEnd = this->getLabel(); // Label after the operator.
2505 LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
2506
2507 if (IsBcpCall) {
2508 if (!this->emitStartSpeculation(E))
2509 return false;
2510 }
2511
2512 if (!this->visitBool(Condition)) {
2513 // If the condition failed and we're checking for undefined behavior
2514 // (which only happens with EvalEmitter) check the TrueExpr and FalseExpr
2515 // as well.
2516 if (this->checkingForUndefinedBehavior()) {
2517 if (!this->discard(TrueExpr))
2518 return false;
2519 if (!this->discard(FalseExpr))
2520 return false;
2521 }
2522 return false;
2523 }
2524
2525 if (!this->jumpFalse(LabelFalse))
2526 return false;
2527 if (!visitChildExpr(TrueExpr))
2528 return false;
2529 if (!this->jump(LabelEnd))
2530 return false;
2531 this->emitLabel(LabelFalse);
2532 if (!visitChildExpr(FalseExpr))
2533 return false;
2534 this->fallthrough(LabelEnd);
2535 this->emitLabel(LabelEnd);
2536
2537 if (IsBcpCall)
2538 return this->emitEndSpeculation(E);
2539 return true;
2540}
2541
2542template <class Emitter>
2544 if (DiscardResult)
2545 return true;
2546
2547 if (!Initializing) {
2548 unsigned StringIndex = P.createGlobalString(E);
2549 return this->emitGetPtrGlobal(StringIndex, E);
2550 }
2551
2552 // We are initializing an array on the stack.
2553 const ConstantArrayType *CAT =
2554 Ctx.getASTContext().getAsConstantArrayType(E->getType());
2555 assert(CAT && "a string literal that's not a constant array?");
2556
2557 // If the initializer string is too long, a diagnostic has already been
2558 // emitted. Read only the array length from the string literal.
2559 unsigned ArraySize = CAT->getZExtSize();
2560 unsigned N = std::min(ArraySize, E->getLength());
2561 unsigned CharWidth = E->getCharByteWidth();
2562
2563 for (unsigned I = 0; I != N; ++I) {
2564 uint32_t CodeUnit = E->getCodeUnit(I);
2565
2566 if (CharWidth == 1) {
2567 this->emitConstSint8(CodeUnit, E);
2568 this->emitInitElemSint8(I, E);
2569 } else if (CharWidth == 2) {
2570 this->emitConstUint16(CodeUnit, E);
2571 this->emitInitElemUint16(I, E);
2572 } else if (CharWidth == 4) {
2573 this->emitConstUint32(CodeUnit, E);
2574 this->emitInitElemUint32(I, E);
2575 } else {
2576 llvm_unreachable("unsupported character width");
2577 }
2578 }
2579
2580 // Fill up the rest of the char array with NUL bytes.
2581 for (unsigned I = N; I != ArraySize; ++I) {
2582 if (CharWidth == 1) {
2583 this->emitConstSint8(0, E);
2584 this->emitInitElemSint8(I, E);
2585 } else if (CharWidth == 2) {
2586 this->emitConstUint16(0, E);
2587 this->emitInitElemUint16(I, E);
2588 } else if (CharWidth == 4) {
2589 this->emitConstUint32(0, E);
2590 this->emitInitElemUint32(I, E);
2591 } else {
2592 llvm_unreachable("unsupported character width");
2593 }
2594 }
2595
2596 return true;
2597}
2598
2599template <class Emitter>
2601 if (DiscardResult)
2602 return true;
2603 return this->emitDummyPtr(E, E);
2604}
2605
2606template <class Emitter>
2608 auto &A = Ctx.getASTContext();
2609 std::string Str;
2610 A.getObjCEncodingForType(E->getEncodedType(), Str);
2611 StringLiteral *SL =
2613 /*Pascal=*/false, E->getType(), E->getAtLoc());
2614 return this->delegate(SL);
2615}
2616
2617template <class Emitter>
2619 const SYCLUniqueStableNameExpr *E) {
2620 if (DiscardResult)
2621 return true;
2622
2623 assert(!Initializing);
2624
2625 auto &A = Ctx.getASTContext();
2626 std::string ResultStr = E->ComputeName(A);
2627
2628 QualType CharTy = A.CharTy.withConst();
2629 APInt Size(A.getTypeSize(A.getSizeType()), ResultStr.size() + 1);
2630 QualType ArrayTy = A.getConstantArrayType(CharTy, Size, nullptr,
2632
2633 StringLiteral *SL =
2635 /*Pascal=*/false, ArrayTy, E->getLocation());
2636
2637 unsigned StringIndex = P.createGlobalString(SL);
2638 return this->emitGetPtrGlobal(StringIndex, E);
2639}
2640
2641template <class Emitter>
2643 if (DiscardResult)
2644 return true;
2645 return this->emitConst(E->getValue(), E);
2646}
2647
2648template <class Emitter>
2650 const CompoundAssignOperator *E) {
2651
2652 const Expr *LHS = E->getLHS();
2653 const Expr *RHS = E->getRHS();
2654 QualType LHSType = LHS->getType();
2655 QualType LHSComputationType = E->getComputationLHSType();
2656 QualType ResultType = E->getComputationResultType();
2657 OptPrimType LT = classify(LHSComputationType);
2658 OptPrimType RT = classify(ResultType);
2659
2660 assert(ResultType->isFloatingType());
2661
2662 if (!LT || !RT)
2663 return false;
2664
2665 PrimType LHST = classifyPrim(LHSType);
2666
2667 // C++17 onwards require that we evaluate the RHS first.
2668 // Compute RHS and save it in a temporary variable so we can
2669 // load it again later.
2670 if (!visit(RHS))
2671 return false;
2672
2673 unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
2674 if (!this->emitSetLocal(*RT, TempOffset, E))
2675 return false;
2676
2677 // First, visit LHS.
2678 if (!visit(LHS))
2679 return false;
2680 if (!this->emitLoad(LHST, E))
2681 return false;
2682
2683 // If necessary, convert LHS to its computation type.
2684 if (!this->emitPrimCast(LHST, classifyPrim(LHSComputationType),
2685 LHSComputationType, E))
2686 return false;
2687
2688 // Now load RHS.
2689 if (!this->emitGetLocal(*RT, TempOffset, E))
2690 return false;
2691
2692 switch (E->getOpcode()) {
2693 case BO_AddAssign:
2694 if (!this->emitAddf(getFPOptions(E), E))
2695 return false;
2696 break;
2697 case BO_SubAssign:
2698 if (!this->emitSubf(getFPOptions(E), E))
2699 return false;
2700 break;
2701 case BO_MulAssign:
2702 if (!this->emitMulf(getFPOptions(E), E))
2703 return false;
2704 break;
2705 case BO_DivAssign:
2706 if (!this->emitDivf(getFPOptions(E), E))
2707 return false;
2708 break;
2709 default:
2710 return false;
2711 }
2712
2713 if (!this->emitPrimCast(classifyPrim(ResultType), LHST, LHS->getType(), E))
2714 return false;
2715
2716 if (DiscardResult)
2717 return this->emitStorePop(LHST, E);
2718 return this->emitStore(LHST, E);
2719}
2720
2721template <class Emitter>
2723 const CompoundAssignOperator *E) {
2724 BinaryOperatorKind Op = E->getOpcode();
2725 const Expr *LHS = E->getLHS();
2726 const Expr *RHS = E->getRHS();
2727 OptPrimType LT = classify(LHS->getType());
2728 OptPrimType RT = classify(RHS->getType());
2729
2730 if (Op != BO_AddAssign && Op != BO_SubAssign)
2731 return false;
2732
2733 if (!LT || !RT)
2734 return false;
2735
2736 if (!visit(LHS))
2737 return false;
2738
2739 if (!this->emitLoad(*LT, LHS))
2740 return false;
2741
2742 if (!visit(RHS))
2743 return false;
2744
2745 if (Op == BO_AddAssign) {
2746 if (!this->emitAddOffset(*RT, E))
2747 return false;
2748 } else {
2749 if (!this->emitSubOffset(*RT, E))
2750 return false;
2751 }
2752
2753 if (DiscardResult)
2754 return this->emitStorePopPtr(E);
2755 return this->emitStorePtr(E);
2756}
2757
2758template <class Emitter>
2760 const CompoundAssignOperator *E) {
2761 if (E->getType()->isVectorType())
2762 return VisitVectorBinOp(E);
2763
2764 const Expr *LHS = E->getLHS();
2765 const Expr *RHS = E->getRHS();
2766 OptPrimType LHSComputationT = classify(E->getComputationLHSType());
2767 OptPrimType LT = classify(LHS->getType());
2768 OptPrimType RT = classify(RHS->getType());
2769 OptPrimType ResultT = classify(E->getType());
2770
2771 if (!Ctx.getLangOpts().CPlusPlus14)
2772 return this->visit(RHS) && this->visit(LHS) && this->emitError(E);
2773
2774 if (!LT || !RT || !ResultT || !LHSComputationT)
2775 return false;
2776
2777 // Handle floating point operations separately here, since they
2778 // require special care.
2779
2780 if (ResultT == PT_Float || RT == PT_Float)
2782
2783 if (E->getType()->isPointerType())
2785
2786 assert(!E->getType()->isPointerType() && "Handled above");
2787 assert(!E->getType()->isFloatingType() && "Handled above");
2788
2789 // C++17 onwards require that we evaluate the RHS first.
2790 // Compute RHS and save it in a temporary variable so we can
2791 // load it again later.
2792 // FIXME: Compound assignments are unsequenced in C, so we might
2793 // have to figure out how to reject them.
2794 if (!visit(RHS))
2795 return false;
2796
2797 unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
2798
2799 if (!this->emitSetLocal(*RT, TempOffset, E))
2800 return false;
2801
2802 // Get LHS pointer, load its value and cast it to the
2803 // computation type if necessary.
2804 if (!visit(LHS))
2805 return false;
2806 if (!this->emitLoad(*LT, E))
2807 return false;
2808 if (LT != LHSComputationT) {
2809 if (!this->emitCast(*LT, *LHSComputationT, E))
2810 return false;
2811 }
2812
2813 // Get the RHS value on the stack.
2814 if (!this->emitGetLocal(*RT, TempOffset, E))
2815 return false;
2816
2817 // Perform operation.
2818 switch (E->getOpcode()) {
2819 case BO_AddAssign:
2820 if (!this->emitAdd(*LHSComputationT, E))
2821 return false;
2822 break;
2823 case BO_SubAssign:
2824 if (!this->emitSub(*LHSComputationT, E))
2825 return false;
2826 break;
2827 case BO_MulAssign:
2828 if (!this->emitMul(*LHSComputationT, E))
2829 return false;
2830 break;
2831 case BO_DivAssign:
2832 if (!this->emitDiv(*LHSComputationT, E))
2833 return false;
2834 break;
2835 case BO_RemAssign:
2836 if (!this->emitRem(*LHSComputationT, E))
2837 return false;
2838 break;
2839 case BO_ShlAssign:
2840 if (!this->emitShl(*LHSComputationT, *RT, E))
2841 return false;
2842 break;
2843 case BO_ShrAssign:
2844 if (!this->emitShr(*LHSComputationT, *RT, E))
2845 return false;
2846 break;
2847 case BO_AndAssign:
2848 if (!this->emitBitAnd(*LHSComputationT, E))
2849 return false;
2850 break;
2851 case BO_XorAssign:
2852 if (!this->emitBitXor(*LHSComputationT, E))
2853 return false;
2854 break;
2855 case BO_OrAssign:
2856 if (!this->emitBitOr(*LHSComputationT, E))
2857 return false;
2858 break;
2859 default:
2860 llvm_unreachable("Unimplemented compound assign operator");
2861 }
2862
2863 // And now cast from LHSComputationT to ResultT.
2864 if (ResultT != LHSComputationT) {
2865 if (!this->emitCast(*LHSComputationT, *ResultT, E))
2866 return false;
2867 }
2868
2869 // And store the result in LHS.
2870 if (DiscardResult) {
2871 if (LHS->refersToBitField())
2872 return this->emitStoreBitFieldPop(*ResultT, E);
2873 return this->emitStorePop(*ResultT, E);
2874 }
2875 if (LHS->refersToBitField())
2876 return this->emitStoreBitField(*ResultT, E);
2877 return this->emitStore(*ResultT, E);
2878}
2879
2880template <class Emitter>
2882 LocalScope<Emitter> ES(this);
2883 const Expr *SubExpr = E->getSubExpr();
2884
2885 return this->delegate(SubExpr) && ES.destroyLocals(E);
2886}
2887
2888template <class Emitter>
2890 const MaterializeTemporaryExpr *E) {
2891 const Expr *SubExpr = E->getSubExpr();
2892
2893 if (Initializing) {
2894 // We already have a value, just initialize that.
2895 return this->delegate(SubExpr);
2896 }
2897 // If we don't end up using the materialized temporary anyway, don't
2898 // bother creating it.
2899 if (DiscardResult)
2900 return this->discard(SubExpr);
2901
2902 // When we're initializing a global variable *or* the storage duration of
2903 // the temporary is explicitly static, create a global variable.
2904 OptPrimType SubExprT = classify(SubExpr);
2905 bool IsStatic = E->getStorageDuration() == SD_Static;
2906 if (IsStatic) {
2907
2908 UnsignedOrNone GlobalIndex = P.createGlobal(E);
2909 if (!GlobalIndex)
2910 return false;
2911
2912 const LifetimeExtendedTemporaryDecl *TempDecl =
2914 assert(TempDecl);
2915
2916 if (SubExprT) {
2917 if (!this->visit(SubExpr))
2918 return false;
2919 if (!this->emitInitGlobalTemp(*SubExprT, *GlobalIndex, TempDecl, E))
2920 return false;
2921 return this->emitGetPtrGlobal(*GlobalIndex, E);
2922 }
2923
2924 if (!this->checkLiteralType(SubExpr))
2925 return false;
2926 // Non-primitive values.
2927 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2928 return false;
2929 if (!this->visitInitializer(SubExpr))
2930 return false;
2931 return this->emitInitGlobalTempComp(TempDecl, E);
2932 }
2933
2934 // For everyhing else, use local variables.
2935 if (SubExprT) {
2936 bool IsConst = SubExpr->getType().isConstQualified();
2937 unsigned LocalIndex =
2938 allocateLocalPrimitive(E, *SubExprT, IsConst, E->getExtendingDecl());
2939 if (!this->visit(SubExpr))
2940 return false;
2941 if (!this->emitSetLocal(*SubExprT, LocalIndex, E))
2942 return false;
2943 return this->emitGetPtrLocal(LocalIndex, E);
2944 }
2945
2946 if (!this->checkLiteralType(SubExpr))
2947 return false;
2948 const Expr *Inner = E->getSubExpr()->skipRValueSubobjectAdjustments();
2949 if (UnsignedOrNone LocalIndex =
2950 allocateLocal(E, Inner->getType(), E->getExtendingDecl())) {
2951 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
2952 if (!this->emitGetPtrLocal(*LocalIndex, E))
2953 return false;
2954 return this->visitInitializer(SubExpr) && this->emitFinishInit(E);
2955 }
2956 return false;
2957}
2958
2959template <class Emitter>
2961 const CXXBindTemporaryExpr *E) {
2962 const Expr *SubExpr = E->getSubExpr();
2963
2964 if (Initializing)
2965 return this->delegate(SubExpr);
2966
2967 // Make sure we create a temporary even if we're discarding, since that will
2968 // make sure we will also call the destructor.
2969
2970 if (!this->visit(SubExpr))
2971 return false;
2972
2973 if (DiscardResult)
2974 return this->emitPopPtr(E);
2975 return true;
2976}
2977
2978template <class Emitter>
2980 const Expr *Init = E->getInitializer();
2981 if (DiscardResult)
2982 return this->discard(Init);
2983
2984 if (Initializing) {
2985 // We already have a value, just initialize that.
2986 return this->visitInitializer(Init) && this->emitFinishInit(E);
2987 }
2988
2989 OptPrimType T = classify(E->getType());
2990 if (E->isFileScope()) {
2991 // Avoid creating a variable if this is a primitive RValue anyway.
2992 if (T && !E->isLValue())
2993 return this->delegate(Init);
2994
2995 UnsignedOrNone GlobalIndex = P.createGlobal(E);
2996 if (!GlobalIndex)
2997 return false;
2998
2999 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3000 return false;
3001
3002 // Since this is a global variable, we might've already seen,
3003 // don't do it again.
3004 if (P.isGlobalInitialized(*GlobalIndex))
3005 return true;
3006
3007 if (T) {
3008 if (!this->visit(Init))
3009 return false;
3010 return this->emitInitGlobal(*T, *GlobalIndex, E);
3011 }
3012
3013 return this->visitInitializer(Init) && this->emitFinishInit(E);
3014 }
3015
3016 // Otherwise, use a local variable.
3017 if (T && !E->isLValue()) {
3018 // For primitive types, we just visit the initializer.
3019 return this->delegate(Init);
3020 }
3021
3022 unsigned LocalIndex;
3023 if (T)
3024 LocalIndex = this->allocateLocalPrimitive(Init, *T, /*IsConst=*/false);
3025 else if (UnsignedOrNone MaybeIndex = this->allocateLocal(Init))
3026 LocalIndex = *MaybeIndex;
3027 else
3028 return false;
3029
3030 if (!this->emitGetPtrLocal(LocalIndex, E))
3031 return false;
3032
3033 if (T)
3034 return this->visit(Init) && this->emitInit(*T, E);
3035 return this->visitInitializer(Init) && this->emitFinishInit(E);
3036}
3037
3038template <class Emitter>
3040 if (DiscardResult)
3041 return true;
3042 if (E->isStoredAsBoolean()) {
3043 if (E->getType()->isBooleanType())
3044 return this->emitConstBool(E->getBoolValue(), E);
3045 return this->emitConst(E->getBoolValue(), E);
3046 }
3048 return this->visitAPValue(E->getAPValue(), T, E);
3049}
3050
3051template <class Emitter>
3053 if (DiscardResult)
3054 return true;
3055 return this->emitConst(E->getValue(), E);
3056}
3057
3058template <class Emitter>
3060 if (DiscardResult)
3061 return true;
3062
3063 assert(Initializing);
3064 const Record *R = P.getOrCreateRecord(E->getLambdaClass());
3065 if (!R)
3066 return false;
3067
3068 auto *CaptureInitIt = E->capture_init_begin();
3069 // Initialize all fields (which represent lambda captures) of the
3070 // record with their initializers.
3071 for (const Record::Field &F : R->fields()) {
3072 const Expr *Init = *CaptureInitIt;
3073 if (!Init || Init->containsErrors())
3074 continue;
3075 ++CaptureInitIt;
3076
3077 if (OptPrimType T = classify(Init)) {
3078 if (!this->visit(Init))
3079 return false;
3080
3081 if (!this->emitInitField(*T, F.Offset, E))
3082 return false;
3083 } else {
3084 if (!this->emitGetPtrField(F.Offset, E))
3085 return false;
3086
3087 if (!this->visitInitializer(Init))
3088 return false;
3089
3090 if (!this->emitPopPtr(E))
3091 return false;
3092 }
3093 }
3094
3095 return true;
3096}
3097
3098template <class Emitter>
3100 if (DiscardResult)
3101 return true;
3102
3103 if (!Initializing) {
3104 unsigned StringIndex = P.createGlobalString(E->getFunctionName(), E);
3105 return this->emitGetPtrGlobal(StringIndex, E);
3106 }
3107
3108 return this->delegate(E->getFunctionName());
3109}
3110
3111template <class Emitter>
3113 if (E->getSubExpr() && !this->discard(E->getSubExpr()))
3114 return false;
3115
3116 return this->emitInvalid(E);
3117}
3118
3119template <class Emitter>
3121 const CXXReinterpretCastExpr *E) {
3122 const Expr *SubExpr = E->getSubExpr();
3123
3124 OptPrimType FromT = classify(SubExpr);
3125 OptPrimType ToT = classify(E);
3126
3127 if (!FromT || !ToT)
3128 return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, E);
3129
3130 if (FromT == PT_Ptr || ToT == PT_Ptr) {
3131 // Both types could be PT_Ptr because their expressions are glvalues.
3132 OptPrimType PointeeFromT;
3133 if (SubExpr->getType()->isPointerOrReferenceType())
3134 PointeeFromT = classify(SubExpr->getType()->getPointeeType());
3135 else
3136 PointeeFromT = classify(SubExpr->getType());
3137
3138 OptPrimType PointeeToT;
3140 PointeeToT = classify(E->getType()->getPointeeType());
3141 else
3142 PointeeToT = classify(E->getType());
3143
3144 bool Fatal = true;
3145 if (PointeeToT && PointeeFromT) {
3146 if (isIntegralType(*PointeeFromT) && isIntegralType(*PointeeToT))
3147 Fatal = false;
3148 } else {
3149 Fatal = SubExpr->getType().getTypePtr() != E->getType().getTypePtr();
3150 }
3151
3152 if (!this->emitInvalidCast(CastKind::Reinterpret, Fatal, E))
3153 return false;
3154
3155 if (E->getCastKind() == CK_LValueBitCast)
3156 return this->delegate(SubExpr);
3157 return this->VisitCastExpr(E);
3158 }
3159
3160 // Try to actually do the cast.
3161 bool Fatal = (ToT != FromT);
3162 if (!this->emitInvalidCast(CastKind::Reinterpret, Fatal, E))
3163 return false;
3164
3165 return this->VisitCastExpr(E);
3166}
3167
3168template <class Emitter>
3170
3171 if (!Ctx.getLangOpts().CPlusPlus20) {
3172 if (!this->emitInvalidCast(CastKind::Dynamic, /*Fatal=*/false, E))
3173 return false;
3174 }
3175
3176 return this->VisitCastExpr(E);
3177}
3178
3179template <class Emitter>
3181 assert(E->getType()->isBooleanType());
3182
3183 if (DiscardResult)
3184 return true;
3185 return this->emitConstBool(E->getValue(), E);
3186}
3187
3188template <class Emitter>
3190 QualType T = E->getType();
3191 assert(!canClassify(T));
3192
3193 if (T->isRecordType()) {
3194 const CXXConstructorDecl *Ctor = E->getConstructor();
3195
3196 // If we're discarding a construct expression, we still need
3197 // to allocate a variable and call the constructor and destructor.
3198 if (DiscardResult) {
3199 if (Ctor->isTrivial())
3200 return true;
3201 assert(!Initializing);
3202 UnsignedOrNone LocalIndex = allocateLocal(E);
3203
3204 if (!LocalIndex)
3205 return false;
3206
3207 if (!this->emitGetPtrLocal(*LocalIndex, E))
3208 return false;
3209 }
3210
3211 // Trivial copy/move constructor. Avoid copy.
3212 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
3213 Ctor->isTrivial() &&
3214 E->getArg(0)->isTemporaryObject(Ctx.getASTContext(),
3215 T->getAsCXXRecordDecl()))
3216 return this->visitInitializer(E->getArg(0));
3217
3218 // Zero initialization.
3219 if (E->requiresZeroInitialization()) {
3220 const Record *R = getRecord(E->getType());
3221
3222 if (!this->visitZeroRecordInitializer(R, E))
3223 return false;
3224
3225 // If the constructor is trivial anyway, we're done.
3226 if (Ctor->isTrivial())
3227 return true;
3228 }
3229
3230 const Function *Func = getFunction(Ctor);
3231
3232 if (!Func)
3233 return false;
3234
3235 assert(Func->hasThisPointer());
3236 assert(!Func->hasRVO());
3237
3238 // The This pointer is already on the stack because this is an initializer,
3239 // but we need to dup() so the call() below has its own copy.
3240 if (!this->emitDupPtr(E))
3241 return false;
3242
3243 // Constructor arguments.
3244 for (const auto *Arg : E->arguments()) {
3245 if (!this->visit(Arg))
3246 return false;
3247 }
3248
3249 if (Func->isVariadic()) {
3250 uint32_t VarArgSize = 0;
3251 unsigned NumParams = Func->getNumWrittenParams();
3252 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) {
3253 VarArgSize +=
3254 align(primSize(classify(E->getArg(I)->getType()).value_or(PT_Ptr)));
3255 }
3256 if (!this->emitCallVar(Func, VarArgSize, E))
3257 return false;
3258 } else {
3259 if (!this->emitCall(Func, 0, E)) {
3260 // When discarding, we don't need the result anyway, so clean up
3261 // the instance dup we did earlier in case surrounding code wants
3262 // to keep evaluating.
3263 if (DiscardResult)
3264 (void)this->emitPopPtr(E);
3265 return false;
3266 }
3267 }
3268
3269 if (DiscardResult)
3270 return this->emitPopPtr(E);
3271 return this->emitFinishInit(E);
3272 }
3273
3274 if (T->isArrayType()) {
3275 const ConstantArrayType *CAT =
3276 Ctx.getASTContext().getAsConstantArrayType(E->getType());
3277 if (!CAT)
3278 return false;
3279
3280 size_t NumElems = CAT->getZExtSize();
3281 const Function *Func = getFunction(E->getConstructor());
3282 if (!Func)
3283 return false;
3284
3285 // FIXME(perf): We're calling the constructor once per array element here,
3286 // in the old intepreter we had a special-case for trivial constructors.
3287 for (size_t I = 0; I != NumElems; ++I) {
3288 if (!this->emitConstUint64(I, E))
3289 return false;
3290 if (!this->emitArrayElemPtrUint64(E))
3291 return false;
3292
3293 // Constructor arguments.
3294 for (const auto *Arg : E->arguments()) {
3295 if (!this->visit(Arg))
3296 return false;
3297 }
3298
3299 if (!this->emitCall(Func, 0, E))
3300 return false;
3301 }
3302 return true;
3303 }
3304
3305 return false;
3306}
3307
3308template <class Emitter>
3310 if (DiscardResult)
3311 return true;
3312
3313 const APValue Val =
3314 E->EvaluateInContext(Ctx.getASTContext(), SourceLocDefaultExpr);
3315
3316 // Things like __builtin_LINE().
3317 if (E->getType()->isIntegerType()) {
3318 assert(Val.isInt());
3319 const APSInt &I = Val.getInt();
3320 return this->emitConst(I, E);
3321 }
3322 // Otherwise, the APValue is an LValue, with only one element.
3323 // Theoretically, we don't need the APValue at all of course.
3324 assert(E->getType()->isPointerType());
3325 assert(Val.isLValue());
3326 const APValue::LValueBase &Base = Val.getLValueBase();
3327 if (const Expr *LValueExpr = Base.dyn_cast<const Expr *>())
3328 return this->visit(LValueExpr);
3329
3330 // Otherwise, we have a decl (which is the case for
3331 // __builtin_source_location).
3332 assert(Base.is<const ValueDecl *>());
3333 assert(Val.getLValuePath().size() == 0);
3334 const auto *BaseDecl = Base.dyn_cast<const ValueDecl *>();
3335 assert(BaseDecl);
3336
3337 auto *UGCD = cast<UnnamedGlobalConstantDecl>(BaseDecl);
3338
3339 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(UGCD);
3340 if (!GlobalIndex)
3341 return false;
3342
3343 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3344 return false;
3345
3346 const Record *R = getRecord(E->getType());
3347 const APValue &V = UGCD->getValue();
3348 for (unsigned I = 0, N = R->getNumFields(); I != N; ++I) {
3349 const Record::Field *F = R->getField(I);
3350 const APValue &FieldValue = V.getStructField(I);
3351
3352 PrimType FieldT = classifyPrim(F->Decl->getType());
3353
3354 if (!this->visitAPValue(FieldValue, FieldT, E))
3355 return false;
3356 if (!this->emitInitField(FieldT, F->Offset, E))
3357 return false;
3358 }
3359
3360 // Leave the pointer to the global on the stack.
3361 return true;
3362}
3363
3364template <class Emitter>
3366 unsigned N = E->getNumComponents();
3367 if (N == 0)
3368 return false;
3369
3370 for (unsigned I = 0; I != N; ++I) {
3371 const OffsetOfNode &Node = E->getComponent(I);
3372 if (Node.getKind() == OffsetOfNode::Array) {
3373 const Expr *ArrayIndexExpr = E->getIndexExpr(Node.getArrayExprIndex());
3374 PrimType IndexT = classifyPrim(ArrayIndexExpr->getType());
3375
3376 if (DiscardResult) {
3377 if (!this->discard(ArrayIndexExpr))
3378 return false;
3379 continue;
3380 }
3381
3382 if (!this->visit(ArrayIndexExpr))
3383 return false;
3384 // Cast to Sint64.
3385 if (IndexT != PT_Sint64) {
3386 if (!this->emitCast(IndexT, PT_Sint64, E))
3387 return false;
3388 }
3389 }
3390 }
3391
3392 if (DiscardResult)
3393 return true;
3394
3396 return this->emitOffsetOf(T, E, E);
3397}
3398
3399template <class Emitter>
3401 const CXXScalarValueInitExpr *E) {
3402 QualType Ty = E->getType();
3403
3404 if (DiscardResult || Ty->isVoidType())
3405 return true;
3406
3407 if (OptPrimType T = classify(Ty))
3408 return this->visitZeroInitializer(*T, Ty, E);
3409
3410 if (const auto *CT = Ty->getAs<ComplexType>()) {
3411 if (!Initializing) {
3412 UnsignedOrNone LocalIndex = allocateLocal(E);
3413 if (!LocalIndex)
3414 return false;
3415 if (!this->emitGetPtrLocal(*LocalIndex, E))
3416 return false;
3417 }
3418
3419 // Initialize both fields to 0.
3420 QualType ElemQT = CT->getElementType();
3421 PrimType ElemT = classifyPrim(ElemQT);
3422
3423 for (unsigned I = 0; I != 2; ++I) {
3424 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
3425 return false;
3426 if (!this->emitInitElem(ElemT, I, E))
3427 return false;
3428 }
3429 return true;
3430 }
3431
3432 if (const auto *VT = Ty->getAs<VectorType>()) {
3433 // FIXME: Code duplication with the _Complex case above.
3434 if (!Initializing) {
3435 UnsignedOrNone LocalIndex = allocateLocal(E);
3436 if (!LocalIndex)
3437 return false;
3438 if (!this->emitGetPtrLocal(*LocalIndex, E))
3439 return false;
3440 }
3441
3442 // Initialize all fields to 0.
3443 QualType ElemQT = VT->getElementType();
3444 PrimType ElemT = classifyPrim(ElemQT);
3445
3446 for (unsigned I = 0, N = VT->getNumElements(); I != N; ++I) {
3447 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
3448 return false;
3449 if (!this->emitInitElem(ElemT, I, E))
3450 return false;
3451 }
3452 return true;
3453 }
3454
3455 return false;
3456}
3457
3458template <class Emitter>
3460 return this->emitConst(E->getPackLength(), E);
3461}
3462
3463template <class Emitter>
3468
3469template <class Emitter>
3471 return this->delegate(E->getChosenSubExpr());
3472}
3473
3474template <class Emitter>
3476 if (DiscardResult)
3477 return true;
3478
3479 return this->emitConst(E->getValue(), E);
3480}
3481
3482template <class Emitter>
3484 const CXXInheritedCtorInitExpr *E) {
3485 const CXXConstructorDecl *Ctor = E->getConstructor();
3486 assert(!Ctor->isTrivial() &&
3487 "Trivial CXXInheritedCtorInitExpr, implement. (possible?)");
3488 const Function *F = this->getFunction(Ctor);
3489 assert(F);
3490 assert(!F->hasRVO());
3491 assert(F->hasThisPointer());
3492
3493 if (!this->emitDupPtr(SourceInfo{}))
3494 return false;
3495
3496 // Forward all arguments of the current function (which should be a
3497 // constructor itself) to the inherited ctor.
3498 // This is necessary because the calling code has pushed the pointer
3499 // of the correct base for us already, but the arguments need
3500 // to come after.
3501 unsigned Offset = align(primSize(PT_Ptr)); // instance pointer.
3502 for (const ParmVarDecl *PD : Ctor->parameters()) {
3503 PrimType PT = this->classify(PD->getType()).value_or(PT_Ptr);
3504
3505 if (!this->emitGetParam(PT, Offset, E))
3506 return false;
3507 Offset += align(primSize(PT));
3508 }
3509
3510 return this->emitCall(F, 0, E);
3511}
3512
3513// FIXME: This function has become rather unwieldy, especially
3514// the part where we initialize an array allocation of dynamic size.
3515template <class Emitter>
3517 assert(classifyPrim(E->getType()) == PT_Ptr);
3518 const Expr *Init = E->getInitializer();
3519 QualType ElementType = E->getAllocatedType();
3520 OptPrimType ElemT = classify(ElementType);
3521 unsigned PlacementArgs = E->getNumPlacementArgs();
3522 const FunctionDecl *OperatorNew = E->getOperatorNew();
3523 const Expr *PlacementDest = nullptr;
3524 bool IsNoThrow = false;
3525
3526 if (PlacementArgs != 0) {
3527 // FIXME: There is no restriction on this, but it's not clear that any
3528 // other form makes any sense. We get here for cases such as:
3529 //
3530 // new (std::align_val_t{N}) X(int)
3531 //
3532 // (which should presumably be valid only if N is a multiple of
3533 // alignof(int), and in any case can't be deallocated unless N is
3534 // alignof(X) and X has new-extended alignment).
3535 if (PlacementArgs == 1) {
3536 const Expr *Arg1 = E->getPlacementArg(0);
3537 if (Arg1->getType()->isNothrowT()) {
3538 if (!this->discard(Arg1))
3539 return false;
3540 IsNoThrow = true;
3541 } else {
3542 // Invalid unless we have C++26 or are in a std:: function.
3543 if (!this->emitInvalidNewDeleteExpr(E, E))
3544 return false;
3545
3546 // If we have a placement-new destination, we'll later use that instead
3547 // of allocating.
3548 if (OperatorNew->isReservedGlobalPlacementOperator())
3549 PlacementDest = Arg1;
3550 }
3551 } else {
3552 // Always invalid.
3553 return this->emitInvalid(E);
3554 }
3555 } else if (!OperatorNew
3556 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
3557 return this->emitInvalidNewDeleteExpr(E, E);
3558
3559 const Descriptor *Desc;
3560 if (!PlacementDest) {
3561 if (ElemT) {
3562 if (E->isArray())
3563 Desc = nullptr; // We're not going to use it in this case.
3564 else
3565 Desc = P.createDescriptor(E, *ElemT, /*SourceTy=*/nullptr,
3567 } else {
3568 Desc = P.createDescriptor(
3569 E, ElementType.getTypePtr(),
3570 E->isArray() ? std::nullopt : Descriptor::InlineDescMD,
3571 /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false,
3572 /*IsVolatile=*/false, Init);
3573 }
3574 }
3575
3576 if (E->isArray()) {
3577 std::optional<const Expr *> ArraySizeExpr = E->getArraySize();
3578 if (!ArraySizeExpr)
3579 return false;
3580
3581 const Expr *Stripped = *ArraySizeExpr;
3582 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
3583 Stripped = ICE->getSubExpr())
3584 if (ICE->getCastKind() != CK_NoOp &&
3585 ICE->getCastKind() != CK_IntegralCast)
3586 break;
3587
3588 PrimType SizeT = classifyPrim(Stripped->getType());
3589
3590 // Save evaluated array size to a variable.
3591 unsigned ArrayLen =
3592 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
3593 if (!this->visit(Stripped))
3594 return false;
3595 if (!this->emitSetLocal(SizeT, ArrayLen, E))
3596 return false;
3597
3598 if (PlacementDest) {
3599 if (!this->visit(PlacementDest))
3600 return false;
3601 if (!this->emitStartLifetime(E))
3602 return false;
3603 if (!this->emitGetLocal(SizeT, ArrayLen, E))
3604 return false;
3605 if (!this->emitCheckNewTypeMismatchArray(SizeT, E, E))
3606 return false;
3607 } else {
3608 if (!this->emitGetLocal(SizeT, ArrayLen, E))
3609 return false;
3610
3611 if (ElemT) {
3612 // N primitive elements.
3613 if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E))
3614 return false;
3615 } else {
3616 // N Composite elements.
3617 if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
3618 return false;
3619 }
3620 }
3621
3622 if (Init) {
3623 QualType InitType = Init->getType();
3624 size_t StaticInitElems = 0;
3625 const Expr *DynamicInit = nullptr;
3626 if (const ConstantArrayType *CAT =
3627 Ctx.getASTContext().getAsConstantArrayType(InitType)) {
3628 StaticInitElems = CAT->getZExtSize();
3629 if (!this->visitInitializer(Init))
3630 return false;
3631
3632 if (const auto *ILE = dyn_cast<InitListExpr>(Init);
3633 ILE && ILE->hasArrayFiller())
3634 DynamicInit = ILE->getArrayFiller();
3635 }
3636
3637 // The initializer initializes a certain number of elements, S.
3638 // However, the complete number of elements, N, might be larger than that.
3639 // In this case, we need to get an initializer for the remaining elements.
3640 // There are to cases:
3641 // 1) For the form 'new Struct[n];', the initializer is a
3642 // CXXConstructExpr and its type is an IncompleteArrayType.
3643 // 2) For the form 'new Struct[n]{1,2,3}', the initializer is an
3644 // InitListExpr and the initializer for the remaining elements
3645 // is the array filler.
3646
3647 if (DynamicInit || InitType->isIncompleteArrayType()) {
3648 const Function *CtorFunc = nullptr;
3649 if (const auto *CE = dyn_cast<CXXConstructExpr>(Init)) {
3650 CtorFunc = getFunction(CE->getConstructor());
3651 if (!CtorFunc)
3652 return false;
3653 } else if (!DynamicInit)
3654 DynamicInit = Init;
3655
3656 LabelTy EndLabel = this->getLabel();
3657 LabelTy StartLabel = this->getLabel();
3658
3659 // In the nothrow case, the alloc above might have returned nullptr.
3660 // Don't call any constructors that case.
3661 if (IsNoThrow) {
3662 if (!this->emitDupPtr(E))
3663 return false;
3664 if (!this->emitNullPtr(0, nullptr, E))
3665 return false;
3666 if (!this->emitEQPtr(E))
3667 return false;
3668 if (!this->jumpTrue(EndLabel))
3669 return false;
3670 }
3671
3672 // Create loop variables.
3673 unsigned Iter =
3674 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
3675 if (!this->emitConst(StaticInitElems, SizeT, E))
3676 return false;
3677 if (!this->emitSetLocal(SizeT, Iter, E))
3678 return false;
3679
3680 this->fallthrough(StartLabel);
3681 this->emitLabel(StartLabel);
3682 // Condition. Iter < ArrayLen?
3683 if (!this->emitGetLocal(SizeT, Iter, E))
3684 return false;
3685 if (!this->emitGetLocal(SizeT, ArrayLen, E))
3686 return false;
3687 if (!this->emitLT(SizeT, E))
3688 return false;
3689 if (!this->jumpFalse(EndLabel))
3690 return false;
3691
3692 // Pointer to the allocated array is already on the stack.
3693 if (!this->emitGetLocal(SizeT, Iter, E))
3694 return false;
3695 if (!this->emitArrayElemPtr(SizeT, E))
3696 return false;
3697
3698 if (isa_and_nonnull<ImplicitValueInitExpr>(DynamicInit) &&
3699 DynamicInit->getType()->isArrayType()) {
3700 QualType ElemType =
3701 DynamicInit->getType()->getAsArrayTypeUnsafe()->getElementType();
3702 PrimType InitT = classifyPrim(ElemType);
3703 if (!this->visitZeroInitializer(InitT, ElemType, E))
3704 return false;
3705 if (!this->emitStorePop(InitT, E))
3706 return false;
3707 } else if (DynamicInit) {
3708 if (OptPrimType InitT = classify(DynamicInit)) {
3709 if (!this->visit(DynamicInit))
3710 return false;
3711 if (!this->emitStorePop(*InitT, E))
3712 return false;
3713 } else {
3714 if (!this->visitInitializer(DynamicInit))
3715 return false;
3716 if (!this->emitPopPtr(E))
3717 return false;
3718 }
3719 } else {
3720 assert(CtorFunc);
3721 if (!this->emitCall(CtorFunc, 0, E))
3722 return false;
3723 }
3724
3725 // ++Iter;
3726 if (!this->emitGetPtrLocal(Iter, E))
3727 return false;
3728 if (!this->emitIncPop(SizeT, false, E))
3729 return false;
3730
3731 if (!this->jump(StartLabel))
3732 return false;
3733
3734 this->fallthrough(EndLabel);
3735 this->emitLabel(EndLabel);
3736 }
3737 }
3738 } else { // Non-array.
3739 if (PlacementDest) {
3740 if (!this->visit(PlacementDest))
3741 return false;
3742 if (!this->emitStartLifetime(E))
3743 return false;
3744 if (!this->emitCheckNewTypeMismatch(E, E))
3745 return false;
3746 } else {
3747 // Allocate just one element.
3748 if (!this->emitAlloc(Desc, E))
3749 return false;
3750 }
3751
3752 if (Init) {
3753 if (ElemT) {
3754 if (!this->visit(Init))
3755 return false;
3756
3757 if (!this->emitInit(*ElemT, E))
3758 return false;
3759 } else {
3760 // Composite.
3761 if (!this->visitInitializer(Init))
3762 return false;
3763 }
3764 }
3765 }
3766
3767 if (DiscardResult)
3768 return this->emitPopPtr(E);
3769
3770 return true;
3771}
3772
3773template <class Emitter>
3775 const Expr *Arg = E->getArgument();
3776
3777 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
3778
3779 if (!OperatorDelete->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
3780 return this->emitInvalidNewDeleteExpr(E, E);
3781
3782 // Arg must be an lvalue.
3783 if (!this->visit(Arg))
3784 return false;
3785
3786 return this->emitFree(E->isArrayForm(), E->isGlobalDelete(), E);
3787}
3788
3789template <class Emitter>
3791 if (DiscardResult)
3792 return true;
3793
3794 const Function *Func = nullptr;
3795 if (const Function *F = Ctx.getOrCreateObjCBlock(E))
3796 Func = F;
3797
3798 if (!Func)
3799 return false;
3800 return this->emitGetFnPtr(Func, E);
3801}
3802
3803template <class Emitter>
3805 const Type *TypeInfoType = E->getType().getTypePtr();
3806
3807 auto canonType = [](const Type *T) {
3808 return T->getCanonicalTypeUnqualified().getTypePtr();
3809 };
3810
3811 if (!E->isPotentiallyEvaluated()) {
3812 if (DiscardResult)
3813 return true;
3814
3815 if (E->isTypeOperand())
3816 return this->emitGetTypeid(
3817 canonType(E->getTypeOperand(Ctx.getASTContext()).getTypePtr()),
3818 TypeInfoType, E);
3819
3820 return this->emitGetTypeid(
3821 canonType(E->getExprOperand()->getType().getTypePtr()), TypeInfoType,
3822 E);
3823 }
3824
3825 // Otherwise, we need to evaluate the expression operand.
3826 assert(E->getExprOperand());
3827 assert(E->getExprOperand()->isLValue());
3828
3829 if (!Ctx.getLangOpts().CPlusPlus20 && !this->emitDiagTypeid(E))
3830 return false;
3831
3832 if (!this->visit(E->getExprOperand()))
3833 return false;
3834
3835 if (!this->emitGetTypeidPtr(TypeInfoType, E))
3836 return false;
3837 if (DiscardResult)
3838 return this->emitPopPtr(E);
3839 return true;
3840}
3841
3842template <class Emitter>
3844 assert(Ctx.getLangOpts().CPlusPlus);
3845 return this->emitConstBool(E->getValue(), E);
3846}
3847
3848template <class Emitter>
3850 if (DiscardResult)
3851 return true;
3852 assert(!Initializing);
3853
3854 const MSGuidDecl *GuidDecl = E->getGuidDecl();
3855 const RecordDecl *RD = GuidDecl->getType()->getAsRecordDecl();
3856 assert(RD);
3857 // If the definiton of the result type is incomplete, just return a dummy.
3858 // If (and when) that is read from, we will fail, but not now.
3859 if (!RD->isCompleteDefinition())
3860 return this->emitDummyPtr(GuidDecl, E);
3861
3862 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(GuidDecl);
3863 if (!GlobalIndex)
3864 return false;
3865 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3866 return false;
3867
3868 assert(this->getRecord(E->getType()));
3869
3870 const APValue &V = GuidDecl->getAsAPValue();
3871 if (V.getKind() == APValue::None)
3872 return true;
3873
3874 assert(V.isStruct());
3875 assert(V.getStructNumBases() == 0);
3876 if (!this->visitAPValueInitializer(V, E, E->getType()))
3877 return false;
3878
3879 return this->emitFinishInit(E);
3880}
3881
3882template <class Emitter>
3884 assert(classifyPrim(E->getType()) == PT_Bool);
3885 if (E->isValueDependent())
3886 return false;
3887 if (DiscardResult)
3888 return true;
3889 return this->emitConstBool(E->isSatisfied(), E);
3890}
3891
3892template <class Emitter>
3894 const ConceptSpecializationExpr *E) {
3895 assert(classifyPrim(E->getType()) == PT_Bool);
3896 if (DiscardResult)
3897 return true;
3898 return this->emitConstBool(E->isSatisfied(), E);
3899}
3900
3901template <class Emitter>
3906
3907template <class Emitter>
3909
3910 for (const Expr *SemE : E->semantics()) {
3911 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
3912 if (SemE == E->getResultExpr())
3913 return false;
3914
3915 if (OVE->isUnique())
3916 continue;
3917
3918 if (!this->discard(OVE))
3919 return false;
3920 } else if (SemE == E->getResultExpr()) {
3921 if (!this->delegate(SemE))
3922 return false;
3923 } else {
3924 if (!this->discard(SemE))
3925 return false;
3926 }
3927 }
3928 return true;
3929}
3930
3931template <class Emitter>
3935
3936template <class Emitter>
3938 return this->emitError(E);
3939}
3940
3941template <class Emitter>
3943 assert(E->getType()->isVoidPointerType());
3944
3945 return this->emitDummyPtr(E, E);
3946}
3947
3948template <class Emitter>
3950 assert(Initializing);
3951 const auto *VT = E->getType()->castAs<VectorType>();
3952 QualType ElemType = VT->getElementType();
3953 PrimType ElemT = classifyPrim(ElemType);
3954 const Expr *Src = E->getSrcExpr();
3955 QualType SrcType = Src->getType();
3956 PrimType SrcElemT = classifyVectorElementType(SrcType);
3957
3958 unsigned SrcOffset =
3959 this->allocateLocalPrimitive(Src, PT_Ptr, /*IsConst=*/true);
3960 if (!this->visit(Src))
3961 return false;
3962 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
3963 return false;
3964
3965 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
3966 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
3967 return false;
3968 if (!this->emitArrayElemPop(SrcElemT, I, E))
3969 return false;
3970
3971 // Cast to the desired result element type.
3972 if (SrcElemT != ElemT) {
3973 if (!this->emitPrimCast(SrcElemT, ElemT, ElemType, E))
3974 return false;
3975 } else if (ElemType->isFloatingType() && SrcType != ElemType) {
3976 const auto *TargetSemantics = &Ctx.getFloatSemantics(ElemType);
3977 if (!this->emitCastFP(TargetSemantics, getRoundingMode(E), E))
3978 return false;
3979 }
3980 if (!this->emitInitElem(ElemT, I, E))
3981 return false;
3982 }
3983
3984 return true;
3985}
3986
3987template <class Emitter>
3989 assert(Initializing);
3990 assert(E->getNumSubExprs() > 2);
3991
3992 const Expr *Vecs[] = {E->getExpr(0), E->getExpr(1)};
3993 const VectorType *VT = Vecs[0]->getType()->castAs<VectorType>();
3994 PrimType ElemT = classifyPrim(VT->getElementType());
3995 unsigned NumInputElems = VT->getNumElements();
3996 unsigned NumOutputElems = E->getNumSubExprs() - 2;
3997 assert(NumOutputElems > 0);
3998
3999 // Save both input vectors to a local variable.
4000 unsigned VectorOffsets[2];
4001 for (unsigned I = 0; I != 2; ++I) {
4002 VectorOffsets[I] =
4003 this->allocateLocalPrimitive(Vecs[I], PT_Ptr, /*IsConst=*/true);
4004 if (!this->visit(Vecs[I]))
4005 return false;
4006 if (!this->emitSetLocal(PT_Ptr, VectorOffsets[I], E))
4007 return false;
4008 }
4009 for (unsigned I = 0; I != NumOutputElems; ++I) {
4010 APSInt ShuffleIndex = E->getShuffleMaskIdx(I);
4011 assert(ShuffleIndex >= -1);
4012 if (ShuffleIndex == -1)
4013 return this->emitInvalidShuffleVectorIndex(I, E);
4014
4015 assert(ShuffleIndex < (NumInputElems * 2));
4016 if (!this->emitGetLocal(PT_Ptr,
4017 VectorOffsets[ShuffleIndex >= NumInputElems], E))
4018 return false;
4019 unsigned InputVectorIndex = ShuffleIndex.getZExtValue() % NumInputElems;
4020 if (!this->emitArrayElemPop(ElemT, InputVectorIndex, E))
4021 return false;
4022
4023 if (!this->emitInitElem(ElemT, I, E))
4024 return false;
4025 }
4026
4027 return true;
4028}
4029
4030template <class Emitter>
4032 const ExtVectorElementExpr *E) {
4033 const Expr *Base = E->getBase();
4034 assert(
4035 Base->getType()->isVectorType() ||
4036 Base->getType()->getAs<PointerType>()->getPointeeType()->isVectorType());
4037
4039 E->getEncodedElementAccess(Indices);
4040
4041 if (Indices.size() == 1) {
4042 if (!this->visit(Base))
4043 return false;
4044
4045 if (E->isGLValue()) {
4046 if (!this->emitConstUint32(Indices[0], E))
4047 return false;
4048 return this->emitArrayElemPtrPop(PT_Uint32, E);
4049 }
4050 // Else, also load the value.
4051 return this->emitArrayElemPop(classifyPrim(E->getType()), Indices[0], E);
4052 }
4053
4054 // Create a local variable for the base.
4055 unsigned BaseOffset = allocateLocalPrimitive(Base, PT_Ptr, /*IsConst=*/true);
4056 if (!this->visit(Base))
4057 return false;
4058 if (!this->emitSetLocal(PT_Ptr, BaseOffset, E))
4059 return false;
4060
4061 // Now the vector variable for the return value.
4062 if (!Initializing) {
4063 UnsignedOrNone ResultIndex = allocateLocal(E);
4064 if (!ResultIndex)
4065 return false;
4066 if (!this->emitGetPtrLocal(*ResultIndex, E))
4067 return false;
4068 }
4069
4070 assert(Indices.size() == E->getType()->getAs<VectorType>()->getNumElements());
4071
4072 PrimType ElemT =
4074 uint32_t DstIndex = 0;
4075 for (uint32_t I : Indices) {
4076 if (!this->emitGetLocal(PT_Ptr, BaseOffset, E))
4077 return false;
4078 if (!this->emitArrayElemPop(ElemT, I, E))
4079 return false;
4080 if (!this->emitInitElem(ElemT, DstIndex, E))
4081 return false;
4082 ++DstIndex;
4083 }
4084
4085 // Leave the result pointer on the stack.
4086 assert(!DiscardResult);
4087 return true;
4088}
4089
4090template <class Emitter>
4092 const Expr *SubExpr = E->getSubExpr();
4094 return this->discard(SubExpr) && this->emitInvalid(E);
4095
4096 if (DiscardResult)
4097 return true;
4098
4099 assert(classifyPrim(E) == PT_Ptr);
4100 return this->emitDummyPtr(E, E);
4101}
4102
4103template <class Emitter>
4105 const CXXStdInitializerListExpr *E) {
4106 const Expr *SubExpr = E->getSubExpr();
4108 Ctx.getASTContext().getAsConstantArrayType(SubExpr->getType());
4109 const Record *R = getRecord(E->getType());
4110 assert(Initializing);
4111 assert(SubExpr->isGLValue());
4112
4113 if (!this->visit(SubExpr))
4114 return false;
4115 if (!this->emitConstUint8(0, E))
4116 return false;
4117 if (!this->emitArrayElemPtrPopUint8(E))
4118 return false;
4119 if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
4120 return false;
4121
4122 PrimType SecondFieldT = classifyPrim(R->getField(1u)->Decl->getType());
4123 if (isIntegralType(SecondFieldT)) {
4124 if (!this->emitConst(ArrayType->getSize(), SecondFieldT, E))
4125 return false;
4126 return this->emitInitField(SecondFieldT, R->getField(1u)->Offset, E);
4127 }
4128 assert(SecondFieldT == PT_Ptr);
4129
4130 if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
4131 return false;
4132 if (!this->emitExpandPtr(E))
4133 return false;
4134 if (!this->emitConst(ArrayType->getSize(), PT_Uint64, E))
4135 return false;
4136 if (!this->emitArrayElemPtrPop(PT_Uint64, E))
4137 return false;
4138 return this->emitInitFieldPtr(R->getField(1u)->Offset, E);
4139}
4140
4141template <class Emitter>
4143 BlockScope<Emitter> BS(this);
4144 StmtExprScope<Emitter> SS(this);
4145
4146 const CompoundStmt *CS = E->getSubStmt();
4147 const Stmt *Result = CS->getStmtExprResult();
4148 for (const Stmt *S : CS->body()) {
4149 if (S != Result) {
4150 if (!this->visitStmt(S))
4151 return false;
4152 continue;
4153 }
4154
4155 assert(S == Result);
4156 if (const Expr *ResultExpr = dyn_cast<Expr>(S))
4157 return this->delegate(ResultExpr);
4158 return this->emitUnsupported(E);
4159 }
4160
4161 return BS.destroyLocals();
4162}
4163
4164template <class Emitter> bool Compiler<Emitter>::discard(const Expr *E) {
4165 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true,
4166 /*NewInitializing=*/false, /*ToLValue=*/false);
4167 return this->Visit(E);
4168}
4169
4170template <class Emitter> bool Compiler<Emitter>::delegate(const Expr *E) {
4171 // We're basically doing:
4172 // OptionScope<Emitter> Scope(this, DicardResult, Initializing, ToLValue);
4173 // but that's unnecessary of course.
4174 return this->Visit(E);
4175}
4176
4178 if (const auto *PE = dyn_cast<ParenExpr>(E))
4179 return stripCheckedDerivedToBaseCasts(PE->getSubExpr());
4180
4181 if (const auto *CE = dyn_cast<CastExpr>(E);
4182 CE &&
4183 (CE->getCastKind() == CK_DerivedToBase || CE->getCastKind() == CK_NoOp))
4184 return stripCheckedDerivedToBaseCasts(CE->getSubExpr());
4185
4186 return E;
4187}
4188
4189static const Expr *stripDerivedToBaseCasts(const Expr *E) {
4190 if (const auto *PE = dyn_cast<ParenExpr>(E))
4191 return stripDerivedToBaseCasts(PE->getSubExpr());
4192
4193 if (const auto *CE = dyn_cast<CastExpr>(E);
4194 CE && (CE->getCastKind() == CK_DerivedToBase ||
4195 CE->getCastKind() == CK_UncheckedDerivedToBase ||
4196 CE->getCastKind() == CK_NoOp))
4197 return stripDerivedToBaseCasts(CE->getSubExpr());
4198
4199 return E;
4200}
4201
4202template <class Emitter> bool Compiler<Emitter>::visit(const Expr *E) {
4203 if (E->getType().isNull())
4204 return false;
4205
4206 if (E->getType()->isVoidType())
4207 return this->discard(E);
4208
4209 // Create local variable to hold the return value.
4210 if (!E->isGLValue() && !canClassify(E->getType())) {
4212 if (!LocalIndex)
4213 return false;
4214
4215 if (!this->emitGetPtrLocal(*LocalIndex, E))
4216 return false;
4217 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
4218 return this->visitInitializer(E);
4219 }
4220
4221 // Otherwise,we have a primitive return value, produce the value directly
4222 // and push it on the stack.
4223 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4224 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
4225 return this->Visit(E);
4226}
4227
4228template <class Emitter>
4230 assert(!canClassify(E->getType()));
4231
4232 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4233 /*NewInitializing=*/true, /*ToLValue=*/false);
4234 return this->Visit(E);
4235}
4236
4237template <class Emitter> bool Compiler<Emitter>::visitAsLValue(const Expr *E) {
4238 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4239 /*NewInitializing=*/false, /*ToLValue=*/true);
4240 return this->Visit(E);
4241}
4242
4243template <class Emitter> bool Compiler<Emitter>::visitBool(const Expr *E) {
4244 OptPrimType T = classify(E->getType());
4245 if (!T) {
4246 // Convert complex values to bool.
4247 if (E->getType()->isAnyComplexType()) {
4248 if (!this->visit(E))
4249 return false;
4250 return this->emitComplexBoolCast(E);
4251 }
4252 return false;
4253 }
4254
4255 if (!this->visit(E))
4256 return false;
4257
4258 if (T == PT_Bool)
4259 return true;
4260
4261 // Convert pointers to bool.
4262 if (T == PT_Ptr)
4263 return this->emitIsNonNullPtr(E);
4264
4265 // Or Floats.
4266 if (T == PT_Float)
4267 return this->emitCastFloatingIntegralBool(getFPOptions(E), E);
4268
4269 // Or anything else we can.
4270 return this->emitCast(*T, PT_Bool, E);
4271}
4272
4273template <class Emitter>
4274bool Compiler<Emitter>::visitZeroInitializer(PrimType T, QualType QT,
4275 const Expr *E) {
4276 if (const auto *AT = QT->getAs<AtomicType>())
4277 QT = AT->getValueType();
4278
4279 switch (T) {
4280 case PT_Bool:
4281 return this->emitZeroBool(E);
4282 case PT_Sint8:
4283 return this->emitZeroSint8(E);
4284 case PT_Uint8:
4285 return this->emitZeroUint8(E);
4286 case PT_Sint16:
4287 return this->emitZeroSint16(E);
4288 case PT_Uint16:
4289 return this->emitZeroUint16(E);
4290 case PT_Sint32:
4291 return this->emitZeroSint32(E);
4292 case PT_Uint32:
4293 return this->emitZeroUint32(E);
4294 case PT_Sint64:
4295 return this->emitZeroSint64(E);
4296 case PT_Uint64:
4297 return this->emitZeroUint64(E);
4298 case PT_IntAP:
4299 return this->emitZeroIntAP(Ctx.getBitWidth(QT), E);
4300 case PT_IntAPS:
4301 return this->emitZeroIntAPS(Ctx.getBitWidth(QT), E);
4302 case PT_Ptr:
4303 return this->emitNullPtr(Ctx.getASTContext().getTargetNullPointerValue(QT),
4304 nullptr, E);
4305 case PT_MemberPtr:
4306 return this->emitNullMemberPtr(0, nullptr, E);
4307 case PT_Float: {
4308 APFloat F = APFloat::getZero(Ctx.getFloatSemantics(QT));
4309 return this->emitFloat(F, E);
4310 }
4311 case PT_FixedPoint: {
4312 auto Sem = Ctx.getASTContext().getFixedPointSemantics(E->getType());
4313 return this->emitConstFixedPoint(FixedPoint::zero(Sem), E);
4314 }
4315 }
4316 llvm_unreachable("unknown primitive type");
4317}
4318
4319template <class Emitter>
4320bool Compiler<Emitter>::visitZeroRecordInitializer(const Record *R,
4321 const Expr *E) {
4322 assert(E);
4323 assert(R);
4324 // Fields
4325 for (const Record::Field &Field : R->fields()) {
4326 if (Field.isUnnamedBitField())
4327 continue;
4328
4329 const Descriptor *D = Field.Desc;
4330 if (D->isPrimitive()) {
4331 QualType QT = D->getType();
4332 PrimType T = classifyPrim(D->getType());
4333 if (!this->visitZeroInitializer(T, QT, E))
4334 return false;
4335 if (R->isUnion()) {
4336 if (!this->emitInitFieldActivate(T, Field.Offset, E))
4337 return false;
4338 break;
4339 }
4340 if (!this->emitInitField(T, Field.Offset, E))
4341 return false;
4342 continue;
4343 }
4344
4345 if (!this->emitGetPtrField(Field.Offset, E))
4346 return false;
4347
4348 if (D->isPrimitiveArray()) {
4349 QualType ET = D->getElemQualType();
4350 PrimType T = classifyPrim(ET);
4351 for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
4352 if (!this->visitZeroInitializer(T, ET, E))
4353 return false;
4354 if (!this->emitInitElem(T, I, E))
4355 return false;
4356 }
4357 } else if (D->isCompositeArray()) {
4358 // Can't be a vector or complex field.
4359 if (!this->visitZeroArrayInitializer(D->getType(), E))
4360 return false;
4361 } else if (D->isRecord()) {
4362 if (!this->visitZeroRecordInitializer(D->ElemRecord, E))
4363 return false;
4364 } else
4365 return false;
4366
4367 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4368 // object's first non-static named data member is zero-initialized
4369 if (R->isUnion()) {
4370 if (!this->emitFinishInitActivatePop(E))
4371 return false;
4372 break;
4373 }
4374 if (!this->emitFinishInitPop(E))
4375 return false;
4376 }
4377
4378 for (const Record::Base &B : R->bases()) {
4379 if (!this->emitGetPtrBase(B.Offset, E))
4380 return false;
4381 if (!this->visitZeroRecordInitializer(B.R, E))
4382 return false;
4383 if (!this->emitFinishInitPop(E))
4384 return false;
4385 }
4386
4387 // FIXME: Virtual bases.
4388
4389 return true;
4390}
4391
4392template <class Emitter>
4393bool Compiler<Emitter>::visitZeroArrayInitializer(QualType T, const Expr *E) {
4394 assert(T->isArrayType() || T->isAnyComplexType() || T->isVectorType());
4395 const ArrayType *AT = T->getAsArrayTypeUnsafe();
4396 QualType ElemType = AT->getElementType();
4397 size_t NumElems = cast<ConstantArrayType>(AT)->getZExtSize();
4398
4399 if (OptPrimType ElemT = classify(ElemType)) {
4400 for (size_t I = 0; I != NumElems; ++I) {
4401 if (!this->visitZeroInitializer(*ElemT, ElemType, E))
4402 return false;
4403 if (!this->emitInitElem(*ElemT, I, E))
4404 return false;
4405 }
4406 return true;
4407 }
4408 if (ElemType->isRecordType()) {
4409 const Record *R = getRecord(ElemType);
4410
4411 for (size_t I = 0; I != NumElems; ++I) {
4412 if (!this->emitConstUint32(I, E))
4413 return false;
4414 if (!this->emitArrayElemPtr(PT_Uint32, E))
4415 return false;
4416 if (!this->visitZeroRecordInitializer(R, E))
4417 return false;
4418 if (!this->emitPopPtr(E))
4419 return false;
4420 }
4421 return true;
4422 }
4423 if (ElemType->isArrayType()) {
4424 for (size_t I = 0; I != NumElems; ++I) {
4425 if (!this->emitConstUint32(I, E))
4426 return false;
4427 if (!this->emitArrayElemPtr(PT_Uint32, E))
4428 return false;
4429 if (!this->visitZeroArrayInitializer(ElemType, E))
4430 return false;
4431 if (!this->emitPopPtr(E))
4432 return false;
4433 }
4434 return true;
4435 }
4436
4437 return false;
4438}
4439
4440template <class Emitter>
4441bool Compiler<Emitter>::visitAssignment(const Expr *LHS, const Expr *RHS,
4442 const Expr *E) {
4443 if (!canClassify(E->getType()))
4444 return false;
4445
4446 if (!this->visit(RHS))
4447 return false;
4448 if (!this->visit(LHS))
4449 return false;
4450
4451 // We don't support assignments in C.
4452 if (!Ctx.getLangOpts().CPlusPlus && !this->emitInvalid(E))
4453 return false;
4454
4455 PrimType RHT = classifyPrim(RHS);
4456 bool Activates = refersToUnion(LHS);
4457 bool BitField = LHS->refersToBitField();
4458
4459 if (!this->emitFlip(PT_Ptr, RHT, E))
4460 return false;
4461
4462 if (DiscardResult) {
4463 if (BitField && Activates)
4464 return this->emitStoreBitFieldActivatePop(RHT, E);
4465 if (BitField)
4466 return this->emitStoreBitFieldPop(RHT, E);
4467 if (Activates)
4468 return this->emitStoreActivatePop(RHT, E);
4469 // Otherwise, regular non-activating store.
4470 return this->emitStorePop(RHT, E);
4471 }
4472
4473 auto maybeLoad = [&](bool Result) -> bool {
4474 if (!Result)
4475 return false;
4476 // Assignments aren't necessarily lvalues in C.
4477 // Load from them in that case.
4478 if (!E->isLValue())
4479 return this->emitLoadPop(RHT, E);
4480 return true;
4481 };
4482
4483 if (BitField && Activates)
4484 return maybeLoad(this->emitStoreBitFieldActivate(RHT, E));
4485 if (BitField)
4486 return maybeLoad(this->emitStoreBitField(RHT, E));
4487 if (Activates)
4488 return maybeLoad(this->emitStoreActivate(RHT, E));
4489 // Otherwise, regular non-activating store.
4490 return maybeLoad(this->emitStore(RHT, E));
4491}
4492
4493template <class Emitter>
4494template <typename T>
4495bool Compiler<Emitter>::emitConst(T Value, PrimType Ty, const Expr *E) {
4496 switch (Ty) {
4497 case PT_Sint8:
4498 return this->emitConstSint8(Value, E);
4499 case PT_Uint8:
4500 return this->emitConstUint8(Value, E);
4501 case PT_Sint16:
4502 return this->emitConstSint16(Value, E);
4503 case PT_Uint16:
4504 return this->emitConstUint16(Value, E);
4505 case PT_Sint32:
4506 return this->emitConstSint32(Value, E);
4507 case PT_Uint32:
4508 return this->emitConstUint32(Value, E);
4509 case PT_Sint64:
4510 return this->emitConstSint64(Value, E);
4511 case PT_Uint64:
4512 return this->emitConstUint64(Value, E);
4513 case PT_Bool:
4514 return this->emitConstBool(Value, E);
4515 case PT_Ptr:
4516 case PT_MemberPtr:
4517 case PT_Float:
4518 case PT_IntAP:
4519 case PT_IntAPS:
4520 case PT_FixedPoint:
4521 llvm_unreachable("Invalid integral type");
4522 break;
4523 }
4524 llvm_unreachable("unknown primitive type");
4525}
4526
4527template <class Emitter>
4528template <typename T>
4529bool Compiler<Emitter>::emitConst(T Value, const Expr *E) {
4530 return this->emitConst(Value, classifyPrim(E->getType()), E);
4531}
4532
4533template <class Emitter>
4534bool Compiler<Emitter>::emitConst(const APSInt &Value, PrimType Ty,
4535 const Expr *E) {
4536 return this->emitConst(static_cast<const APInt &>(Value), Ty, E);
4537}
4538
4539template <class Emitter>
4540bool Compiler<Emitter>::emitConst(const APInt &Value, PrimType Ty,
4541 const Expr *E) {
4542 if (Ty == PT_IntAPS)
4543 return this->emitConstIntAPS(Value, E);
4544 if (Ty == PT_IntAP)
4545 return this->emitConstIntAP(Value, E);
4546
4547 if (isSignedType(Ty))
4548 return this->emitConst(Value.getSExtValue(), Ty, E);
4549 return this->emitConst(Value.getZExtValue(), Ty, E);
4550}
4551
4552template <class Emitter>
4553bool Compiler<Emitter>::emitConst(const APSInt &Value, const Expr *E) {
4554 return this->emitConst(Value, classifyPrim(E->getType()), E);
4555}
4556
4557template <class Emitter>
4559 DeclTy &&Src, PrimType Ty, bool IsConst, const ValueDecl *ExtendingDecl,
4560 ScopeKind SC, bool IsConstexprUnknown) {
4561 // FIXME: There are cases where Src.is<Expr*>() is wrong, e.g.
4562 // (int){12} in C. Consider using Expr::isTemporaryObject() instead
4563 // or isa<MaterializeTemporaryExpr>().
4564 Descriptor *D = P.createDescriptor(Src, Ty, nullptr, Descriptor::InlineDescMD,
4565 IsConst, isa<const Expr *>(Src));
4566 D->IsConstexprUnknown = IsConstexprUnknown;
4567 Scope::Local Local = this->createLocal(D);
4568 if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>()))
4569 Locals.insert({VD, Local});
4570 if (ExtendingDecl)
4571 VarScope->addExtended(Local, ExtendingDecl);
4572 else
4573 VarScope->addForScopeKind(Local, SC);
4574 return Local.Offset;
4575}
4576
4577template <class Emitter>
4579 const ValueDecl *ExtendingDecl,
4580 ScopeKind SC,
4581 bool IsConstexprUnknown) {
4582 const ValueDecl *Key = nullptr;
4583 const Expr *Init = nullptr;
4584 bool IsTemporary = false;
4585 if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
4586 Key = VD;
4587
4588 if (const auto *VarD = dyn_cast<VarDecl>(VD))
4589 Init = VarD->getInit();
4590 }
4591 if (auto *E = Src.dyn_cast<const Expr *>()) {
4592 IsTemporary = true;
4593 if (Ty.isNull())
4594 Ty = E->getType();
4595 }
4596
4597 Descriptor *D = P.createDescriptor(
4599 IsTemporary, /*IsMutable=*/false, /*IsVolatile=*/false, Init);
4600 if (!D)
4601 return std::nullopt;
4602 D->IsConstexprUnknown = IsConstexprUnknown;
4603
4604 Scope::Local Local = this->createLocal(D);
4605 if (Key)
4606 Locals.insert({Key, Local});
4607 if (ExtendingDecl)
4608 VarScope->addExtended(Local, ExtendingDecl);
4609 else
4610 VarScope->addForScopeKind(Local, SC);
4611 return Local.Offset;
4612}
4613
4614template <class Emitter>
4616 QualType Ty = E->getType();
4617 assert(!Ty->isRecordType());
4618
4619 Descriptor *D = P.createDescriptor(
4621 /*IsTemporary=*/true);
4622
4623 if (!D)
4624 return std::nullopt;
4625
4626 Scope::Local Local = this->createLocal(D);
4628 assert(S);
4629 // Attach to topmost scope.
4630 while (S->getParent())
4631 S = S->getParent();
4632 assert(S && !S->getParent());
4633 S->addLocal(Local);
4634 return Local.Offset;
4635}
4636
4637template <class Emitter>
4639 if (const PointerType *PT = dyn_cast<PointerType>(Ty))
4640 return PT->getPointeeType()->getAsCanonical<RecordType>();
4641 return Ty->getAsCanonical<RecordType>();
4642}
4643
4644template <class Emitter> Record *Compiler<Emitter>::getRecord(QualType Ty) {
4645 if (const auto *RecordTy = getRecordTy(Ty))
4646 return getRecord(RecordTy->getOriginalDecl()->getDefinitionOrSelf());
4647 return nullptr;
4648}
4649
4650template <class Emitter>
4652 return P.getOrCreateRecord(RD);
4653}
4654
4655template <class Emitter>
4657 return Ctx.getOrCreateFunction(FD);
4658}
4659
4660template <class Emitter>
4661bool Compiler<Emitter>::visitExpr(const Expr *E, bool DestroyToplevelScope) {
4662 LocalScope<Emitter> RootScope(this);
4663
4664 // If we won't destroy the toplevel scope, check for memory leaks first.
4665 if (!DestroyToplevelScope) {
4666 if (!this->emitCheckAllocations(E))
4667 return false;
4668 }
4669
4670 auto maybeDestroyLocals = [&]() -> bool {
4671 if (DestroyToplevelScope)
4672 return RootScope.destroyLocals() && this->emitCheckAllocations(E);
4673 return this->emitCheckAllocations(E);
4674 };
4675
4676 // Void expressions.
4677 if (E->getType()->isVoidType()) {
4678 if (!visit(E))
4679 return false;
4680 return this->emitRetVoid(E) && maybeDestroyLocals();
4681 }
4682
4683 // Expressions with a primitive return type.
4684 if (OptPrimType T = classify(E)) {
4685 if (!visit(E))
4686 return false;
4687
4688 return this->emitRet(*T, E) && maybeDestroyLocals();
4689 }
4690
4691 // Expressions with a composite return type.
4692 // For us, that means everything we don't
4693 // have a PrimType for.
4694 if (UnsignedOrNone LocalOffset = this->allocateLocal(E)) {
4695 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalOffset));
4696 if (!this->emitGetPtrLocal(*LocalOffset, E))
4697 return false;
4698
4699 if (!visitInitializer(E))
4700 return false;
4701
4702 if (!this->emitFinishInit(E))
4703 return false;
4704 // We are destroying the locals AFTER the Ret op.
4705 // The Ret op needs to copy the (alive) values, but the
4706 // destructors may still turn the entire expression invalid.
4707 return this->emitRetValue(E) && maybeDestroyLocals();
4708 }
4709
4710 return maybeDestroyLocals() && this->emitCheckAllocations(E) && false;
4711}
4712
4713template <class Emitter>
4715 bool IsConstexprUnknown) {
4716
4717 auto R = this->visitVarDecl(VD, /*Toplevel=*/true, IsConstexprUnknown);
4718
4719 if (R.notCreated())
4720 return R;
4721
4722 if (R)
4723 return true;
4724
4725 if (!R && Context::shouldBeGloballyIndexed(VD)) {
4726 if (auto GlobalIndex = P.getGlobal(VD)) {
4727 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
4729 *reinterpret_cast<GlobalInlineDescriptor *>(GlobalBlock->rawData());
4730
4732 GlobalBlock->invokeDtor();
4733 }
4734 }
4735
4736 return R;
4737}
4738
4739/// Toplevel visitDeclAndReturn().
4740/// We get here from evaluateAsInitializer().
4741/// We need to evaluate the initializer and return its value.
4742template <class Emitter>
4744 bool ConstantContext) {
4745
4746 // We only create variables if we're evaluating in a constant context.
4747 // Otherwise, just evaluate the initializer and return it.
4748 if (!ConstantContext) {
4749 DeclScope<Emitter> LS(this, VD);
4750 const Expr *Init = VD->getInit();
4751 if (!this->visit(Init))
4752 return false;
4753 return this->emitRet(classify(Init).value_or(PT_Ptr), VD) &&
4754 LS.destroyLocals() && this->emitCheckAllocations(VD);
4755 }
4756
4757 LocalScope<Emitter> VDScope(this, VD);
4758 if (!this->visitVarDecl(VD, /*Toplevel=*/true))
4759 return false;
4760
4761 OptPrimType VarT = classify(VD->getType());
4763 auto GlobalIndex = P.getGlobal(VD);
4764 assert(GlobalIndex); // visitVarDecl() didn't return false.
4765 if (VarT) {
4766 if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
4767 return false;
4768 } else {
4769 if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
4770 return false;
4771 }
4772 } else {
4773 auto Local = Locals.find(VD);
4774 assert(Local != Locals.end()); // Same here.
4775 if (VarT) {
4776 if (!this->emitGetLocal(*VarT, Local->second.Offset, VD))
4777 return false;
4778 } else {
4779 if (!this->emitGetPtrLocal(Local->second.Offset, VD))
4780 return false;
4781 }
4782 }
4783
4784 // Return the value.
4785 if (!this->emitRet(VarT.value_or(PT_Ptr), VD)) {
4786 // If the Ret above failed and this is a global variable, mark it as
4787 // uninitialized, even everything else succeeded.
4789 auto GlobalIndex = P.getGlobal(VD);
4790 assert(GlobalIndex);
4791 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
4793 *reinterpret_cast<GlobalInlineDescriptor *>(GlobalBlock->rawData());
4794
4796 GlobalBlock->invokeDtor();
4797 }
4798 return false;
4799 }
4800
4801 return VDScope.destroyLocals() && this->emitCheckAllocations(VD);
4802}
4803
4804template <class Emitter>
4806 bool Toplevel,
4807 bool IsConstexprUnknown) {
4808 // We don't know what to do with these, so just return false.
4809 if (VD->getType().isNull())
4810 return false;
4811
4812 // This case is EvalEmitter-only. If we won't create any instructions for the
4813 // initializer anyway, don't bother creating the variable in the first place.
4814 if (!this->isActive())
4816
4817 const Expr *Init = VD->getInit();
4818 OptPrimType VarT = classify(VD->getType());
4819
4820 if (Init && Init->isValueDependent())
4821 return false;
4822
4824 auto checkDecl = [&]() -> bool {
4825 bool NeedsOp = !Toplevel && VD->isLocalVarDecl() && VD->isStaticLocal();
4826 return !NeedsOp || this->emitCheckDecl(VD, VD);
4827 };
4828
4829 auto initGlobal = [&](unsigned GlobalIndex) -> bool {
4830 assert(Init);
4831
4832 if (VarT) {
4833 if (!this->visit(Init))
4834 return checkDecl() && false;
4835
4836 return checkDecl() && this->emitInitGlobal(*VarT, GlobalIndex, VD);
4837 }
4838
4839 if (!checkDecl())
4840 return false;
4841
4842 if (!this->emitGetPtrGlobal(GlobalIndex, Init))
4843 return false;
4844
4845 if (!visitInitializer(Init))
4846 return false;
4847
4848 return this->emitFinishInitGlobal(Init);
4849 };
4850
4852
4853 // We've already seen and initialized this global.
4854 if (UnsignedOrNone GlobalIndex = P.getGlobal(VD)) {
4855 if (P.getPtrGlobal(*GlobalIndex).isInitialized())
4856 return checkDecl();
4857
4858 // The previous attempt at initialization might've been unsuccessful,
4859 // so let's try this one.
4860 return Init && checkDecl() && initGlobal(*GlobalIndex);
4861 }
4862
4863 UnsignedOrNone GlobalIndex = P.createGlobal(VD, Init);
4864
4865 if (!GlobalIndex)
4866 return false;
4867
4868 return !Init || (checkDecl() && initGlobal(*GlobalIndex));
4869 }
4870 // Local variables.
4872
4873 if (VarT) {
4874 unsigned Offset = this->allocateLocalPrimitive(
4875 VD, *VarT, VD->getType().isConstQualified(), nullptr, ScopeKind::Block,
4876 IsConstexprUnknown);
4877 if (Init) {
4878 // If this is a toplevel declaration, create a scope for the
4879 // initializer.
4880 if (Toplevel) {
4882 if (!this->visit(Init))
4883 return false;
4884 return this->emitSetLocal(*VarT, Offset, VD) && Scope.destroyLocals();
4885 }
4886 if (!this->visit(Init))
4887 return false;
4888 return this->emitSetLocal(*VarT, Offset, VD);
4889 }
4890 } else {
4891 if (UnsignedOrNone Offset = this->allocateLocal(
4892 VD, VD->getType(), nullptr, ScopeKind::Block, IsConstexprUnknown)) {
4893 if (!Init)
4894 return true;
4895
4896 if (!this->emitGetPtrLocal(*Offset, Init))
4897 return false;
4898
4899 if (!visitInitializer(Init))
4900 return false;
4901
4902 return this->emitFinishInitPop(Init);
4903 }
4904 return false;
4905 }
4906 return true;
4907}
4908
4909template <class Emitter>
4911 const Expr *E) {
4912 assert(!DiscardResult);
4913 if (Val.isInt())
4914 return this->emitConst(Val.getInt(), ValType, E);
4915 if (Val.isFloat()) {
4916 APFloat F = Val.getFloat();
4917 return this->emitFloat(F, E);
4918 }
4919
4920 if (Val.isLValue()) {
4921 if (Val.isNullPointer())
4922 return this->emitNull(ValType, 0, nullptr, E);
4924 if (const Expr *BaseExpr = Base.dyn_cast<const Expr *>())
4925 return this->visit(BaseExpr);
4926 if (const auto *VD = Base.dyn_cast<const ValueDecl *>())
4927 return this->visitDeclRef(VD, E);
4928 } else if (Val.isMemberPointer()) {
4929 if (const ValueDecl *MemberDecl = Val.getMemberPointerDecl())
4930 return this->emitGetMemberPtr(MemberDecl, E);
4931 return this->emitNullMemberPtr(0, nullptr, E);
4932 }
4933
4934 return false;
4935}
4936
4937template <class Emitter>
4939 const Expr *E, QualType T) {
4940 if (Val.isStruct()) {
4941 const Record *R = this->getRecord(T);
4942 assert(R);
4943 for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) {
4944 const APValue &F = Val.getStructField(I);
4945 const Record::Field *RF = R->getField(I);
4946 QualType FieldType = RF->Decl->getType();
4947
4948 if (OptPrimType PT = classify(FieldType)) {
4949 if (!this->visitAPValue(F, *PT, E))
4950 return false;
4951 if (!this->emitInitField(*PT, RF->Offset, E))
4952 return false;
4953 } else {
4954 if (!this->emitGetPtrField(RF->Offset, E))
4955 return false;
4956 if (!this->visitAPValueInitializer(F, E, FieldType))
4957 return false;
4958 if (!this->emitPopPtr(E))
4959 return false;
4960 }
4961 }
4962 return true;
4963 }
4964 if (Val.isUnion()) {
4965 const FieldDecl *UnionField = Val.getUnionField();
4966 const Record *R = this->getRecord(UnionField->getParent());
4967 assert(R);
4968 const APValue &F = Val.getUnionValue();
4969 const Record::Field *RF = R->getField(UnionField);
4970 PrimType T = classifyPrim(RF->Decl->getType());
4971 if (!this->visitAPValue(F, T, E))
4972 return false;
4973 return this->emitInitField(T, RF->Offset, E);
4974 }
4975 if (Val.isArray()) {
4976 const auto *ArrType = T->getAsArrayTypeUnsafe();
4977 QualType ElemType = ArrType->getElementType();
4978 for (unsigned A = 0, AN = Val.getArraySize(); A != AN; ++A) {
4979 const APValue &Elem = Val.getArrayInitializedElt(A);
4980 if (OptPrimType ElemT = classify(ElemType)) {
4981 if (!this->visitAPValue(Elem, *ElemT, E))
4982 return false;
4983 if (!this->emitInitElem(*ElemT, A, E))
4984 return false;
4985 } else {
4986 if (!this->emitConstUint32(A, E))
4987 return false;
4988 if (!this->emitArrayElemPtrUint32(E))
4989 return false;
4990 if (!this->visitAPValueInitializer(Elem, E, ElemType))
4991 return false;
4992 if (!this->emitPopPtr(E))
4993 return false;
4994 }
4995 }
4996 return true;
4997 }
4998 // TODO: Other types.
4999
5000 return false;
5001}
5002
5003template <class Emitter>
5005 unsigned BuiltinID) {
5006 if (BuiltinID == Builtin::BI__builtin_constant_p) {
5007 // Void argument is always invalid and harder to handle later.
5008 if (E->getArg(0)->getType()->isVoidType()) {
5009 if (DiscardResult)
5010 return true;
5011 return this->emitConst(0, E);
5012 }
5013
5014 if (!this->emitStartSpeculation(E))
5015 return false;
5016 LabelTy EndLabel = this->getLabel();
5017 if (!this->speculate(E, EndLabel))
5018 return false;
5019 this->fallthrough(EndLabel);
5020 if (!this->emitEndSpeculation(E))
5021 return false;
5022 if (DiscardResult)
5023 return this->emitPop(classifyPrim(E), E);
5024 return true;
5025 }
5026
5027 // For these, we're expected to ultimately return an APValue pointing
5028 // to the CallExpr. This is needed to get the correct codegen.
5029 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5030 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString ||
5031 BuiltinID == Builtin::BI__builtin_ptrauth_sign_constant ||
5032 BuiltinID == Builtin::BI__builtin_function_start) {
5033 if (DiscardResult)
5034 return true;
5035 return this->emitDummyPtr(E, E);
5036 }
5037
5039 OptPrimType ReturnT = classify(E);
5040
5041 // Non-primitive return type. Prepare storage.
5042 if (!Initializing && !ReturnT && !ReturnType->isVoidType()) {
5043 UnsignedOrNone LocalIndex = allocateLocal(E);
5044 if (!LocalIndex)
5045 return false;
5046 if (!this->emitGetPtrLocal(*LocalIndex, E))
5047 return false;
5048 }
5049
5050 // Prepare function arguments including special cases.
5051 switch (BuiltinID) {
5052 case Builtin::BI__builtin_object_size:
5053 case Builtin::BI__builtin_dynamic_object_size: {
5054 assert(E->getNumArgs() == 2);
5055 const Expr *Arg0 = E->getArg(0);
5056 if (Arg0->isGLValue()) {
5057 if (!this->visit(Arg0))
5058 return false;
5059
5060 } else {
5061 if (!this->visitAsLValue(Arg0))
5062 return false;
5063 }
5064 if (!this->visit(E->getArg(1)))
5065 return false;
5066
5067 } break;
5068 default:
5069 if (!Context::isUnevaluatedBuiltin(BuiltinID)) {
5070 // Put arguments on the stack.
5071 for (const auto *Arg : E->arguments()) {
5072 if (!this->visit(Arg))
5073 return false;
5074 }
5075 }
5076 }
5077
5078 if (!this->emitCallBI(E, BuiltinID, E))
5079 return false;
5080
5081 if (DiscardResult && !ReturnType->isVoidType()) {
5082 assert(ReturnT);
5083 return this->emitPop(*ReturnT, E);
5084 }
5085
5086 return true;
5087}
5088
5089template <class Emitter>
5091 const FunctionDecl *FuncDecl = E->getDirectCallee();
5092
5093 if (FuncDecl) {
5094 if (unsigned BuiltinID = FuncDecl->getBuiltinID())
5095 return VisitBuiltinCallExpr(E, BuiltinID);
5096
5097 // Calls to replaceable operator new/operator delete.
5099 if (FuncDecl->getDeclName().isAnyOperatorNew())
5100 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_new);
5101 assert(FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Delete);
5102 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_delete);
5103 }
5104
5105 // Explicit calls to trivial destructors
5106 if (const auto *DD = dyn_cast<CXXDestructorDecl>(FuncDecl);
5107 DD && DD->isTrivial()) {
5108 const auto *MemberCall = cast<CXXMemberCallExpr>(E);
5109 if (!this->visit(MemberCall->getImplicitObjectArgument()))
5110 return false;
5111 return this->emitCheckDestruction(E) && this->emitEndLifetime(E) &&
5112 this->emitPopPtr(E);
5113 }
5114 }
5115
5116 BlockScope<Emitter> CallScope(this, ScopeKind::Call);
5117
5118 QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
5120 bool HasRVO = !ReturnType->isVoidType() && !T;
5121
5122 if (HasRVO) {
5123 if (DiscardResult) {
5124 // If we need to discard the return value but the function returns its
5125 // value via an RVO pointer, we need to create one such pointer just
5126 // for this call.
5127 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
5128 if (!this->emitGetPtrLocal(*LocalIndex, E))
5129 return false;
5130 }
5131 } else {
5132 // We need the result. Prepare a pointer to return or
5133 // dup the current one.
5134 if (!Initializing) {
5135 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
5136 if (!this->emitGetPtrLocal(*LocalIndex, E))
5137 return false;
5138 }
5139 }
5140 if (!this->emitDupPtr(E))
5141 return false;
5142 }
5143 }
5144
5146
5147 bool IsAssignmentOperatorCall = false;
5148 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
5149 OCE && OCE->isAssignmentOp()) {
5150 // Just like with regular assignments, we need to special-case assignment
5151 // operators here and evaluate the RHS (the second arg) before the LHS (the
5152 // first arg). We fix this by using a Flip op later.
5153 assert(Args.size() == 2);
5154 IsAssignmentOperatorCall = true;
5155 std::reverse(Args.begin(), Args.end());
5156 }
5157 // Calling a static operator will still
5158 // pass the instance, but we don't need it.
5159 // Discard it here.
5160 if (isa<CXXOperatorCallExpr>(E)) {
5161 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
5162 MD && MD->isStatic()) {
5163 if (!this->discard(E->getArg(0)))
5164 return false;
5165 // Drop first arg.
5166 Args.erase(Args.begin());
5167 }
5168 }
5169
5170 bool Devirtualized = false;
5171 UnsignedOrNone CalleeOffset = std::nullopt;
5172 // Add the (optional, implicit) This pointer.
5173 if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) {
5174 if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) {
5175 // If we end up creating a CallPtr op for this, we need the base of the
5176 // member pointer as the instance pointer, and later extract the function
5177 // decl as the function pointer.
5178 const Expr *Callee = E->getCallee();
5179 CalleeOffset =
5180 this->allocateLocalPrimitive(Callee, PT_MemberPtr, /*IsConst=*/true);
5181 if (!this->visit(Callee))
5182 return false;
5183 if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E))
5184 return false;
5185 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
5186 return false;
5187 if (!this->emitGetMemberPtrBase(E))
5188 return false;
5189 } else {
5190 const auto *InstancePtr = MC->getImplicitObjectArgument();
5191 if (isa_and_nonnull<CXXDestructorDecl>(CompilingFunction) ||
5192 isa_and_nonnull<CXXConstructorDecl>(CompilingFunction)) {
5193 const auto *Stripped = stripCheckedDerivedToBaseCasts(InstancePtr);
5194 if (isa<CXXThisExpr>(Stripped)) {
5195 FuncDecl =
5196 cast<CXXMethodDecl>(FuncDecl)->getCorrespondingMethodInClass(
5197 Stripped->getType()->getPointeeType()->getAsCXXRecordDecl());
5198 Devirtualized = true;
5199 if (!this->visit(Stripped))
5200 return false;
5201 } else {
5202 if (!this->visit(InstancePtr))
5203 return false;
5204 }
5205 } else {
5206 if (!this->visit(InstancePtr))
5207 return false;
5208 }
5209 }
5210 } else if (const auto *PD =
5211 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee())) {
5212 if (!this->emitCheckPseudoDtor(E))
5213 return false;
5214 const Expr *Base = PD->getBase();
5215 // E.g. `using T = int; 0.~T();`.
5216 if (OptPrimType BaseT = classify(Base); !BaseT || BaseT != PT_Ptr)
5217 return this->discard(Base);
5218 if (!this->visit(Base))
5219 return false;
5220 return this->emitEndLifetimePop(E);
5221 } else if (!FuncDecl) {
5222 const Expr *Callee = E->getCallee();
5223 CalleeOffset =
5224 this->allocateLocalPrimitive(Callee, PT_Ptr, /*IsConst=*/true);
5225 if (!this->visit(Callee))
5226 return false;
5227 if (!this->emitSetLocal(PT_Ptr, *CalleeOffset, E))
5228 return false;
5229 }
5230
5231 if (!this->visitCallArgs(Args, FuncDecl, IsAssignmentOperatorCall,
5233 return false;
5234
5235 // Undo the argument reversal we did earlier.
5236 if (IsAssignmentOperatorCall) {
5237 assert(Args.size() == 2);
5238 PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr);
5239 PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr);
5240 if (!this->emitFlip(Arg2T, Arg1T, E))
5241 return false;
5242 }
5243
5244 if (FuncDecl) {
5245 const Function *Func = getFunction(FuncDecl);
5246 if (!Func)
5247 return false;
5248
5249 // In error cases, the function may be called with fewer arguments than
5250 // parameters.
5251 if (E->getNumArgs() < Func->getNumWrittenParams())
5252 return false;
5253
5254 assert(HasRVO == Func->hasRVO());
5255
5256 bool HasQualifier = false;
5257 if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee()))
5258 HasQualifier = ME->hasQualifier();
5259
5260 bool IsVirtual = false;
5261 if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl))
5262 IsVirtual = !Devirtualized && MD->isVirtual();
5263
5264 // In any case call the function. The return value will end up on the stack
5265 // and if the function has RVO, we already have the pointer on the stack to
5266 // write the result into.
5267 if (IsVirtual && !HasQualifier) {
5268 uint32_t VarArgSize = 0;
5269 unsigned NumParams =
5270 Func->getNumWrittenParams() + isa<CXXOperatorCallExpr>(E);
5271 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
5272 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
5273
5274 if (!this->emitCallVirt(Func, VarArgSize, E))
5275 return false;
5276 } else if (Func->isVariadic()) {
5277 uint32_t VarArgSize = 0;
5278 unsigned NumParams =
5279 Func->getNumWrittenParams() + isa<CXXOperatorCallExpr>(E);
5280 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
5281 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
5282 if (!this->emitCallVar(Func, VarArgSize, E))
5283 return false;
5284 } else {
5285 if (!this->emitCall(Func, 0, E))
5286 return false;
5287 }
5288 } else {
5289 // Indirect call. Visit the callee, which will leave a FunctionPointer on
5290 // the stack. Cleanup of the returned value if necessary will be done after
5291 // the function call completed.
5292
5293 // Sum the size of all args from the call expr.
5294 uint32_t ArgSize = 0;
5295 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
5296 ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
5297
5298 // Get the callee, either from a member pointer or function pointer saved in
5299 // CalleeOffset.
5300 if (isa<CXXMemberCallExpr>(E) && CalleeOffset) {
5301 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
5302 return false;
5303 if (!this->emitGetMemberPtrDecl(E))
5304 return false;
5305 } else {
5306 if (!this->emitGetLocal(PT_Ptr, *CalleeOffset, E))
5307 return false;
5308 }
5309 if (!this->emitCallPtr(ArgSize, E, E))
5310 return false;
5311 }
5312
5313 // Cleanup for discarded return values.
5314 if (DiscardResult && !ReturnType->isVoidType() && T)
5315 return this->emitPop(*T, E) && CallScope.destroyLocals();
5316
5317 return CallScope.destroyLocals();
5318}
5319
5320template <class Emitter>
5322 SourceLocScope<Emitter> SLS(this, E);
5323
5324 return this->delegate(E->getExpr());
5325}
5326
5327template <class Emitter>
5329 SourceLocScope<Emitter> SLS(this, E);
5330
5331 return this->delegate(E->getExpr());
5332}
5333
5334template <class Emitter>
5336 if (DiscardResult)
5337 return true;
5338
5339 return this->emitConstBool(E->getValue(), E);
5340}
5341
5342template <class Emitter>
5344 const CXXNullPtrLiteralExpr *E) {
5345 if (DiscardResult)
5346 return true;
5347
5348 uint64_t Val = Ctx.getASTContext().getTargetNullPointerValue(E->getType());
5349 return this->emitNullPtr(Val, nullptr, E);
5350}
5351
5352template <class Emitter>
5354 if (DiscardResult)
5355 return true;
5356
5357 assert(E->getType()->isIntegerType());
5358
5360 return this->emitZero(T, E);
5361}
5362
5363template <class Emitter>
5365 if (DiscardResult)
5366 return true;
5367
5368 if (this->LambdaThisCapture.Offset > 0) {
5369 if (this->LambdaThisCapture.IsPtr)
5370 return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E);
5371 return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E);
5372 }
5373
5374 // In some circumstances, the 'this' pointer does not actually refer to the
5375 // instance pointer of the current function frame, but e.g. to the declaration
5376 // currently being initialized. Here we emit the necessary instruction(s) for
5377 // this scenario.
5378 if (!InitStackActive)
5379 return this->emitThis(E);
5380
5381 if (!InitStack.empty()) {
5382 // If our init stack is, for example:
5383 // 0 Stack: 3 (decl)
5384 // 1 Stack: 6 (init list)
5385 // 2 Stack: 1 (field)
5386 // 3 Stack: 6 (init list)
5387 // 4 Stack: 1 (field)
5388 //
5389 // We want to find the LAST element in it that's an init list,
5390 // which is marked with the K_InitList marker. The index right
5391 // before that points to an init list. We need to find the
5392 // elements before the K_InitList element that point to a base
5393 // (e.g. a decl or This), optionally followed by field, elem, etc.
5394 // In the example above, we want to emit elements [0..2].
5395 unsigned StartIndex = 0;
5396 unsigned EndIndex = 0;
5397 // Find the init list.
5398 for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
5399 if (InitStack[StartIndex].Kind == InitLink::K_InitList ||
5400 InitStack[StartIndex].Kind == InitLink::K_This) {
5401 EndIndex = StartIndex;
5402 --StartIndex;
5403 break;
5404 }
5405 }
5406
5407 // Walk backwards to find the base.
5408 for (; StartIndex > 0; --StartIndex) {
5409 if (InitStack[StartIndex].Kind == InitLink::K_InitList)
5410 continue;
5411
5412 if (InitStack[StartIndex].Kind != InitLink::K_Field &&
5413 InitStack[StartIndex].Kind != InitLink::K_Elem)
5414 break;
5415 }
5416
5417 // Emit the instructions.
5418 for (unsigned I = StartIndex; I != EndIndex; ++I) {
5419 if (InitStack[I].Kind == InitLink::K_InitList)
5420 continue;
5421 if (!InitStack[I].template emit<Emitter>(this, E))
5422 return false;
5423 }
5424 return true;
5425 }
5426 return this->emitThis(E);
5427}
5428
5429template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) {
5430 switch (S->getStmtClass()) {
5431 case Stmt::CompoundStmtClass:
5433 case Stmt::DeclStmtClass:
5434 return visitDeclStmt(cast<DeclStmt>(S), /*EvaluateConditionDecl=*/true);
5435 case Stmt::ReturnStmtClass:
5437 case Stmt::IfStmtClass:
5438 return visitIfStmt(cast<IfStmt>(S));
5439 case Stmt::WhileStmtClass:
5441 case Stmt::DoStmtClass:
5442 return visitDoStmt(cast<DoStmt>(S));
5443 case Stmt::ForStmtClass:
5444 return visitForStmt(cast<ForStmt>(S));
5445 case Stmt::CXXForRangeStmtClass:
5447 case Stmt::BreakStmtClass:
5449 case Stmt::ContinueStmtClass:
5451 case Stmt::SwitchStmtClass:
5453 case Stmt::CaseStmtClass:
5454 return visitCaseStmt(cast<CaseStmt>(S));
5455 case Stmt::DefaultStmtClass:
5457 case Stmt::AttributedStmtClass:
5459 case Stmt::CXXTryStmtClass:
5461 case Stmt::NullStmtClass:
5462 return true;
5463 // Always invalid statements.
5464 case Stmt::GCCAsmStmtClass:
5465 case Stmt::MSAsmStmtClass:
5466 case Stmt::GotoStmtClass:
5467 return this->emitInvalid(S);
5468 case Stmt::LabelStmtClass:
5469 return this->visitStmt(cast<LabelStmt>(S)->getSubStmt());
5470 default: {
5471 if (const auto *E = dyn_cast<Expr>(S))
5472 return this->discard(E);
5473 return false;
5474 }
5475 }
5476}
5477
5478template <class Emitter>
5481 for (const auto *InnerStmt : S->body())
5482 if (!visitStmt(InnerStmt))
5483 return false;
5484 return Scope.destroyLocals();
5485}
5486
5487template <class Emitter>
5488bool Compiler<Emitter>::maybeEmitDeferredVarInit(const VarDecl *VD) {
5489 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5490 for (auto *BD : DD->flat_bindings())
5491 if (auto *KD = BD->getHoldingVar(); KD && !this->visitVarDecl(KD))
5492 return false;
5493 }
5494 return true;
5495}
5496
5498 assert(FD);
5499 assert(FD->getParent()->isUnion());
5500 const auto *CXXRD = dyn_cast<CXXRecordDecl>(FD->getParent());
5501 return !CXXRD || CXXRD->hasTrivialDefaultConstructor();
5502}
5503
5504template <class Emitter> bool Compiler<Emitter>::refersToUnion(const Expr *E) {
5505 for (;;) {
5506 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
5507 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5508 FD && FD->getParent()->isUnion() && hasTrivialDefaultCtorParent(FD))
5509 return true;
5510 E = ME->getBase();
5511 continue;
5512 }
5513
5514 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5515 E = ASE->getBase()->IgnoreImplicit();
5516 continue;
5517 }
5518
5519 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
5520 ICE && (ICE->getCastKind() == CK_NoOp ||
5521 ICE->getCastKind() == CK_DerivedToBase ||
5522 ICE->getCastKind() == CK_UncheckedDerivedToBase)) {
5523 E = ICE->getSubExpr();
5524 continue;
5525 }
5526
5527 if (const auto *This = dyn_cast<CXXThisExpr>(E)) {
5528 const auto *ThisRecord =
5529 This->getType()->getPointeeType()->getAsRecordDecl();
5530 if (!ThisRecord->isUnion())
5531 return false;
5532 // Otherwise, always activate if we're in the ctor.
5533 if (const auto *Ctor =
5534 dyn_cast_if_present<CXXConstructorDecl>(CompilingFunction))
5535 return Ctor->getParent() == ThisRecord;
5536 return false;
5537 }
5538
5539 break;
5540 }
5541 return false;
5542}
5543
5544template <class Emitter>
5546 bool EvaluateConditionDecl) {
5547 for (const auto *D : DS->decls()) {
5550 continue;
5551
5552 const auto *VD = dyn_cast<VarDecl>(D);
5553 if (!VD)
5554 return false;
5555 if (!this->visitVarDecl(VD))
5556 return false;
5557
5558 // Register decomposition decl holding vars.
5559 if (EvaluateConditionDecl && !this->maybeEmitDeferredVarInit(VD))
5560 return false;
5561 }
5562
5563 return true;
5564}
5565
5566template <class Emitter>
5568 if (this->InStmtExpr)
5569 return this->emitUnsupported(RS);
5570
5571 if (const Expr *RE = RS->getRetValue()) {
5572 LocalScope<Emitter> RetScope(this);
5573 if (ReturnType) {
5574 // Primitive types are simply returned.
5575 if (!this->visit(RE))
5576 return false;
5577 this->emitCleanup();
5578 return this->emitRet(*ReturnType, RS);
5579 }
5580
5581 if (RE->getType()->isVoidType()) {
5582 if (!this->visit(RE))
5583 return false;
5584 } else {
5586 // RVO - construct the value in the return location.
5587 if (!this->emitRVOPtr(RE))
5588 return false;
5589 if (!this->visitInitializer(RE))
5590 return false;
5591 if (!this->emitPopPtr(RE))
5592 return false;
5593
5594 this->emitCleanup();
5595 return this->emitRetVoid(RS);
5596 }
5597 }
5598
5599 // Void return.
5600 this->emitCleanup();
5601 return this->emitRetVoid(RS);
5602}
5603
5604template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) {
5605 auto visitChildStmt = [&](const Stmt *S) -> bool {
5606 LocalScope<Emitter> SScope(this);
5607 if (!visitStmt(S))
5608 return false;
5609 return SScope.destroyLocals();
5610 };
5611 if (auto *CondInit = IS->getInit())
5612 if (!visitStmt(CondInit))
5613 return false;
5614
5615 if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt())
5616 if (!visitDeclStmt(CondDecl))
5617 return false;
5618
5619 // Save ourselves compiling some code and the jumps, etc. if the condition is
5620 // stataically known to be either true or false. We could look at more cases
5621 // here, but I think all the ones that actually happen are using a
5622 // ConstantExpr.
5623 if (std::optional<bool> BoolValue = getBoolValue(IS->getCond())) {
5624 if (*BoolValue)
5625 return visitChildStmt(IS->getThen());
5626 if (const Stmt *Else = IS->getElse())
5627 return visitChildStmt(Else);
5628 return true;
5629 }
5630
5631 // Otherwise, compile the condition.
5632 if (IS->isNonNegatedConsteval()) {
5633 if (!this->emitIsConstantContext(IS))
5634 return false;
5635 } else if (IS->isNegatedConsteval()) {
5636 if (!this->emitIsConstantContext(IS))
5637 return false;
5638 if (!this->emitInv(IS))
5639 return false;
5640 } else {
5641 if (!this->visitBool(IS->getCond()))
5642 return false;
5643 }
5644
5645 if (!this->maybeEmitDeferredVarInit(IS->getConditionVariable()))
5646 return false;
5647
5648 if (const Stmt *Else = IS->getElse()) {
5649 LabelTy LabelElse = this->getLabel();
5650 LabelTy LabelEnd = this->getLabel();
5651 if (!this->jumpFalse(LabelElse))
5652 return false;
5653 if (!visitChildStmt(IS->getThen()))
5654 return false;
5655 if (!this->jump(LabelEnd))
5656 return false;
5657 this->emitLabel(LabelElse);
5658 if (!visitChildStmt(Else))
5659 return false;
5660 this->emitLabel(LabelEnd);
5661 } else {
5662 LabelTy LabelEnd = this->getLabel();
5663 if (!this->jumpFalse(LabelEnd))
5664 return false;
5665 if (!visitChildStmt(IS->getThen()))
5666 return false;
5667 this->emitLabel(LabelEnd);
5668 }
5669
5670 return true;
5671}
5672
5673template <class Emitter>
5675 const Expr *Cond = S->getCond();
5676 const Stmt *Body = S->getBody();
5677
5678 LabelTy CondLabel = this->getLabel(); // Label before the condition.
5679 LabelTy EndLabel = this->getLabel(); // Label after the loop.
5680 LocalScope<Emitter> WholeLoopScope(this);
5681 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
5682
5683 this->fallthrough(CondLabel);
5684 this->emitLabel(CondLabel);
5685
5686 {
5687 LocalScope<Emitter> CondScope(this);
5688 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
5689 if (!visitDeclStmt(CondDecl))
5690 return false;
5691
5692 if (!this->visitBool(Cond))
5693 return false;
5694
5695 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
5696 return false;
5697
5698 if (!this->jumpFalse(EndLabel))
5699 return false;
5700
5701 if (!this->visitStmt(Body))
5702 return false;
5703
5704 if (!CondScope.destroyLocals())
5705 return false;
5706 }
5707 if (!this->jump(CondLabel))
5708 return false;
5709 this->fallthrough(EndLabel);
5710 this->emitLabel(EndLabel);
5711 return WholeLoopScope.destroyLocals();
5712}
5713
5714template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) {
5715 const Expr *Cond = S->getCond();
5716 const Stmt *Body = S->getBody();
5717
5718 LabelTy StartLabel = this->getLabel();
5719 LabelTy EndLabel = this->getLabel();
5720 LabelTy CondLabel = this->getLabel();
5721 LocalScope<Emitter> WholeLoopScope(this);
5722 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
5723
5724 this->fallthrough(StartLabel);
5725 this->emitLabel(StartLabel);
5726
5727 {
5728 LocalScope<Emitter> CondScope(this);
5729 if (!this->visitStmt(Body))
5730 return false;
5731 this->fallthrough(CondLabel);
5732 this->emitLabel(CondLabel);
5733 if (!this->visitBool(Cond))
5734 return false;
5735
5736 if (!CondScope.destroyLocals())
5737 return false;
5738 }
5739 if (!this->jumpTrue(StartLabel))
5740 return false;
5741
5742 this->fallthrough(EndLabel);
5743 this->emitLabel(EndLabel);
5744 return WholeLoopScope.destroyLocals();
5745}
5746
5747template <class Emitter>
5749 // for (Init; Cond; Inc) { Body }
5750 const Stmt *Init = S->getInit();
5751 const Expr *Cond = S->getCond();
5752 const Expr *Inc = S->getInc();
5753 const Stmt *Body = S->getBody();
5754
5755 LabelTy EndLabel = this->getLabel();
5756 LabelTy CondLabel = this->getLabel();
5757 LabelTy IncLabel = this->getLabel();
5758
5759 LocalScope<Emitter> WholeLoopScope(this);
5760 if (Init && !this->visitStmt(Init))
5761 return false;
5762
5763 // Start of the loop body {
5764 this->fallthrough(CondLabel);
5765 this->emitLabel(CondLabel);
5766
5767 LocalScope<Emitter> CondScope(this);
5768 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
5769 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
5770 if (!visitDeclStmt(CondDecl))
5771 return false;
5772 }
5773
5774 if (Cond) {
5775 if (!this->visitBool(Cond))
5776 return false;
5777 if (!this->jumpFalse(EndLabel))
5778 return false;
5779 }
5780 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
5781 return false;
5782
5783 if (Body && !this->visitStmt(Body))
5784 return false;
5785
5786 this->fallthrough(IncLabel);
5787 this->emitLabel(IncLabel);
5788 if (Inc && !this->discard(Inc))
5789 return false;
5790
5791 if (!CondScope.destroyLocals())
5792 return false;
5793 if (!this->jump(CondLabel))
5794 return false;
5795 // } End of loop body.
5796
5797 this->emitLabel(EndLabel);
5798 // If we jumped out of the loop above, we still need to clean up the condition
5799 // scope.
5800 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
5801}
5802
5803template <class Emitter>
5805 const Stmt *Init = S->getInit();
5806 const Expr *Cond = S->getCond();
5807 const Expr *Inc = S->getInc();
5808 const Stmt *Body = S->getBody();
5809 const Stmt *BeginStmt = S->getBeginStmt();
5810 const Stmt *RangeStmt = S->getRangeStmt();
5811 const Stmt *EndStmt = S->getEndStmt();
5812
5813 LabelTy EndLabel = this->getLabel();
5814 LabelTy CondLabel = this->getLabel();
5815 LabelTy IncLabel = this->getLabel();
5816 LocalScope<Emitter> WholeLoopScope(this);
5817 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
5818
5819 // Emit declarations needed in the loop.
5820 if (Init && !this->visitStmt(Init))
5821 return false;
5822 if (!this->visitStmt(RangeStmt))
5823 return false;
5824 if (!this->visitStmt(BeginStmt))
5825 return false;
5826 if (!this->visitStmt(EndStmt))
5827 return false;
5828
5829 // Now the condition as well as the loop variable assignment.
5830 this->fallthrough(CondLabel);
5831 this->emitLabel(CondLabel);
5832 if (!this->visitBool(Cond))
5833 return false;
5834 if (!this->jumpFalse(EndLabel))
5835 return false;
5836
5837 if (!this->visitDeclStmt(S->getLoopVarStmt(), /*EvaluateConditionDecl=*/true))
5838 return false;
5839
5840 // Body.
5841 {
5842 if (!this->visitStmt(Body))
5843 return false;
5844
5845 this->fallthrough(IncLabel);
5846 this->emitLabel(IncLabel);
5847 if (!this->discard(Inc))
5848 return false;
5849 }
5850
5851 if (!this->jump(CondLabel))
5852 return false;
5853
5854 this->fallthrough(EndLabel);
5855 this->emitLabel(EndLabel);
5856 return WholeLoopScope.destroyLocals();
5857}
5858
5859template <class Emitter>
5861 if (LabelInfoStack.empty())
5862 return false;
5863
5864 OptLabelTy TargetLabel = std::nullopt;
5865 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
5866 const VariableScope<Emitter> *BreakScope = nullptr;
5867
5868 if (!TargetLoop) {
5869 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
5870 if (LI.BreakLabel) {
5871 TargetLabel = *LI.BreakLabel;
5872 BreakScope = LI.BreakOrContinueScope;
5873 break;
5874 }
5875 }
5876 } else {
5877 for (auto LI : LabelInfoStack) {
5878 if (LI.Name == TargetLoop) {
5879 TargetLabel = *LI.BreakLabel;
5880 BreakScope = LI.BreakOrContinueScope;
5881 break;
5882 }
5883 }
5884 }
5885
5886 assert(TargetLabel);
5887
5888 for (VariableScope<Emitter> *C = this->VarScope; C != BreakScope;
5889 C = C->getParent())
5890 C->emitDestruction();
5891
5892 return this->jump(*TargetLabel);
5893}
5894
5895template <class Emitter>
5897 if (LabelInfoStack.empty())
5898 return false;
5899
5900 OptLabelTy TargetLabel = std::nullopt;
5901 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
5902 const VariableScope<Emitter> *ContinueScope = nullptr;
5903
5904 if (!TargetLoop) {
5905 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
5906 if (LI.ContinueLabel) {
5907 TargetLabel = *LI.ContinueLabel;
5908 ContinueScope = LI.BreakOrContinueScope;
5909 break;
5910 }
5911 }
5912 } else {
5913 for (auto LI : LabelInfoStack) {
5914 if (LI.Name == TargetLoop) {
5915 TargetLabel = *LI.ContinueLabel;
5916 ContinueScope = LI.BreakOrContinueScope;
5917 break;
5918 }
5919 }
5920 }
5921 assert(TargetLabel);
5922
5923 for (VariableScope<Emitter> *C = VarScope; C != ContinueScope;
5924 C = C->getParent())
5925 C->emitDestruction();
5926
5927 return this->jump(*TargetLabel);
5928}
5929
5930template <class Emitter>
5932 const Expr *Cond = S->getCond();
5933 if (Cond->containsErrors())
5934 return false;
5935
5936 PrimType CondT = this->classifyPrim(Cond->getType());
5937 LocalScope<Emitter> LS(this);
5938
5939 LabelTy EndLabel = this->getLabel();
5940 UnsignedOrNone DefaultLabel = std::nullopt;
5941 unsigned CondVar =
5942 this->allocateLocalPrimitive(Cond, CondT, /*IsConst=*/true);
5943
5944 if (const auto *CondInit = S->getInit())
5945 if (!visitStmt(CondInit))
5946 return false;
5947
5948 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
5949 if (!visitDeclStmt(CondDecl))
5950 return false;
5951
5952 // Initialize condition variable.
5953 if (!this->visit(Cond))
5954 return false;
5955 if (!this->emitSetLocal(CondT, CondVar, S))
5956 return false;
5957
5958 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
5959 return false;
5960
5962 // Create labels and comparison ops for all case statements.
5963 for (const SwitchCase *SC = S->getSwitchCaseList(); SC;
5964 SC = SC->getNextSwitchCase()) {
5965 if (const auto *CS = dyn_cast<CaseStmt>(SC)) {
5966 // FIXME: Implement ranges.
5967 if (CS->caseStmtIsGNURange())
5968 return false;
5969 CaseLabels[SC] = this->getLabel();
5970
5971 const Expr *Value = CS->getLHS();
5972 PrimType ValueT = this->classifyPrim(Value->getType());
5973
5974 // Compare the case statement's value to the switch condition.
5975 if (!this->emitGetLocal(CondT, CondVar, CS))
5976 return false;
5977 if (!this->visit(Value))
5978 return false;
5979
5980 // Compare and jump to the case label.
5981 if (!this->emitEQ(ValueT, S))
5982 return false;
5983 if (!this->jumpTrue(CaseLabels[CS]))
5984 return false;
5985 } else {
5986 assert(!DefaultLabel);
5987 DefaultLabel = this->getLabel();
5988 }
5989 }
5990
5991 // If none of the conditions above were true, fall through to the default
5992 // statement or jump after the switch statement.
5993 if (DefaultLabel) {
5994 if (!this->jump(*DefaultLabel))
5995 return false;
5996 } else {
5997 if (!this->jump(EndLabel))
5998 return false;
5999 }
6000
6001 SwitchScope<Emitter> SS(this, S, std::move(CaseLabels), EndLabel,
6002 DefaultLabel);
6003 if (!this->visitStmt(S->getBody()))
6004 return false;
6005 this->emitLabel(EndLabel);
6006
6007 return LS.destroyLocals();
6008}
6009
6010template <class Emitter>
6012 this->emitLabel(CaseLabels[S]);
6013 return this->visitStmt(S->getSubStmt());
6014}
6015
6016template <class Emitter>
6018 if (LabelInfoStack.empty())
6019 return false;
6020
6021 LabelTy DefaultLabel;
6022 for (const LabelInfo &LI : llvm::reverse(LabelInfoStack)) {
6023 if (LI.DefaultLabel) {
6024 DefaultLabel = *LI.DefaultLabel;
6025 break;
6026 }
6027 }
6028
6029 this->emitLabel(DefaultLabel);
6030 return this->visitStmt(S->getSubStmt());
6031}
6032
6033template <class Emitter>
6035 if (this->Ctx.getLangOpts().CXXAssumptions &&
6036 !this->Ctx.getLangOpts().MSVCCompat) {
6037 for (const Attr *A : S->getAttrs()) {
6038 auto *AA = dyn_cast<CXXAssumeAttr>(A);
6039 if (!AA)
6040 continue;
6041
6042 assert(isa<NullStmt>(S->getSubStmt()));
6043
6044 const Expr *Assumption = AA->getAssumption();
6045 if (Assumption->isValueDependent())
6046 return false;
6047
6048 if (Assumption->HasSideEffects(this->Ctx.getASTContext()))
6049 continue;
6050
6051 // Evaluate assumption.
6052 if (!this->visitBool(Assumption))
6053 return false;
6054
6055 if (!this->emitAssume(Assumption))
6056 return false;
6057 }
6058 }
6059
6060 // Ignore other attributes.
6061 return this->visitStmt(S->getSubStmt());
6062}
6063
6064template <class Emitter>
6066 // Ignore all handlers.
6067 return this->visitStmt(S->getTryBlock());
6068}
6069
6070template <class Emitter>
6071bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) {
6072 assert(MD->isLambdaStaticInvoker());
6073 assert(MD->hasBody());
6074 assert(cast<CompoundStmt>(MD->getBody())->body_empty());
6075
6076 const CXXRecordDecl *ClosureClass = MD->getParent();
6077 const CXXMethodDecl *LambdaCallOp = ClosureClass->getLambdaCallOperator();
6078 assert(ClosureClass->captures().empty());
6079 const Function *Func = this->getFunction(LambdaCallOp);
6080 if (!Func)
6081 return false;
6082 assert(Func->hasThisPointer());
6083 assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO()));
6084
6085 if (Func->hasRVO()) {
6086 if (!this->emitRVOPtr(MD))
6087 return false;
6088 }
6089
6090 // The lambda call operator needs an instance pointer, but we don't have
6091 // one here, and we don't need one either because the lambda cannot have
6092 // any captures, as verified above. Emit a null pointer. This is then
6093 // special-cased when interpreting to not emit any misleading diagnostics.
6094 if (!this->emitNullPtr(0, nullptr, MD))
6095 return false;
6096
6097 // Forward all arguments from the static invoker to the lambda call operator.
6098 for (const ParmVarDecl *PVD : MD->parameters()) {
6099 auto It = this->Params.find(PVD);
6100 assert(It != this->Params.end());
6101
6102 // We do the lvalue-to-rvalue conversion manually here, so no need
6103 // to care about references.
6104 PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr);
6105 if (!this->emitGetParam(ParamType, It->second.Offset, MD))
6106 return false;
6107 }
6108
6109 if (!this->emitCall(Func, 0, LambdaCallOp))
6110 return false;
6111
6112 this->emitCleanup();
6113 if (ReturnType)
6114 return this->emitRet(*ReturnType, MD);
6115
6116 // Nothing to do, since we emitted the RVO pointer above.
6117 return this->emitRetVoid(MD);
6118}
6119
6120template <class Emitter>
6121bool Compiler<Emitter>::checkLiteralType(const Expr *E) {
6122 if (Ctx.getLangOpts().CPlusPlus23)
6123 return true;
6124
6125 if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext()))
6126 return true;
6127
6128 return this->emitCheckLiteralType(E->getType().getTypePtr(), E);
6129}
6130
6132 const Expr *InitExpr = Init->getInit();
6133
6134 if (!Init->isWritten() && !Init->isInClassMemberInitializer() &&
6135 !isa<CXXConstructExpr>(InitExpr))
6136 return true;
6137
6138 if (const auto *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
6139 const CXXConstructorDecl *Ctor = CE->getConstructor();
6140 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
6141 Ctor->isTrivial())
6142 return true;
6143 }
6144
6145 return false;
6146}
6147
6148template <class Emitter>
6149bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
6150 assert(!ReturnType);
6151
6152 auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset,
6153 const Expr *InitExpr,
6154 bool Activate = false) -> bool {
6155 // We don't know what to do with these, so just return false.
6156 if (InitExpr->getType().isNull())
6157 return false;
6158
6159 if (OptPrimType T = this->classify(InitExpr)) {
6160 if (Activate && !this->emitActivateThisField(FieldOffset, InitExpr))
6161 return false;
6162
6163 if (!this->visit(InitExpr))
6164 return false;
6165
6166 bool BitField = F->isBitField();
6167 if (BitField)
6168 return this->emitInitThisBitField(*T, F, FieldOffset, InitExpr);
6169 return this->emitInitThisField(*T, FieldOffset, InitExpr);
6170 }
6171 // Non-primitive case. Get a pointer to the field-to-initialize
6172 // on the stack and call visitInitialzer() for it.
6173 InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset));
6174 if (!this->emitGetPtrThisField(FieldOffset, InitExpr))
6175 return false;
6176
6177 if (Activate && !this->emitActivate(InitExpr))
6178 return false;
6179
6180 if (!this->visitInitializer(InitExpr))
6181 return false;
6182
6183 return this->emitFinishInitPop(InitExpr);
6184 };
6185
6186 const RecordDecl *RD = Ctor->getParent();
6187 const Record *R = this->getRecord(RD);
6188 if (!R)
6189 return false;
6190 bool IsUnion = R->isUnion();
6191
6192 if (IsUnion && Ctor->isCopyOrMoveConstructor()) {
6194
6195 if (R->getNumFields() == 0)
6196 return this->emitRetVoid(Ctor);
6197 // union copy and move ctors are special.
6198 assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
6199 if (!this->emitThis(Ctor))
6200 return false;
6201
6202 const ParmVarDecl *PVD = Ctor->getParamDecl(0);
6203 ParamOffset PO = this->Params[PVD]; // Must exist.
6204
6205 if (!this->emitGetParam(PT_Ptr, PO.Offset, Ctor))
6206 return false;
6207
6208 return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) &&
6209 this->emitRetVoid(Ctor);
6210 }
6211
6213 for (const auto *Init : Ctor->inits()) {
6214 // Scope needed for the initializers.
6216
6217 const Expr *InitExpr = Init->getInit();
6218 if (const FieldDecl *Member = Init->getMember()) {
6219 const Record::Field *F = R->getField(Member);
6220
6223 if (!emitFieldInitializer(F, F->Offset, InitExpr, IsUnion))
6224 return false;
6225 } else if (const Type *Base = Init->getBaseClass()) {
6226 const auto *BaseDecl = Base->getAsCXXRecordDecl();
6227 assert(BaseDecl);
6228
6229 if (Init->isBaseVirtual()) {
6230 assert(R->getVirtualBase(BaseDecl));
6231 if (!this->emitGetPtrThisVirtBase(BaseDecl, InitExpr))
6232 return false;
6233
6234 } else {
6235 // Base class initializer.
6236 // Get This Base and call initializer on it.
6237 const Record::Base *B = R->getBase(BaseDecl);
6238 assert(B);
6239 if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
6240 return false;
6241 }
6242
6243 if (IsUnion && !this->emitActivate(InitExpr))
6244 return false;
6245
6246 if (!this->visitInitializer(InitExpr))
6247 return false;
6248 if (!this->emitFinishInitPop(InitExpr))
6249 return false;
6250 } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
6253 assert(IFD->getChainingSize() >= 2);
6254
6255 unsigned NestedFieldOffset = 0;
6256 const Record::Field *NestedField = nullptr;
6257 for (const NamedDecl *ND : IFD->chain()) {
6258 const auto *FD = cast<FieldDecl>(ND);
6259 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
6260 assert(FieldRecord);
6261
6262 NestedField = FieldRecord->getField(FD);
6263 assert(NestedField);
6264 IsUnion = IsUnion || FieldRecord->isUnion();
6265
6266 NestedFieldOffset += NestedField->Offset;
6267 }
6268 assert(NestedField);
6269
6270 if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr,
6271 IsUnion))
6272 return false;
6273
6274 // Mark all chain links as initialized.
6275 unsigned InitFieldOffset = 0;
6276 for (const NamedDecl *ND : IFD->chain().drop_back()) {
6277 const auto *FD = cast<FieldDecl>(ND);
6278 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
6279 assert(FieldRecord);
6280 NestedField = FieldRecord->getField(FD);
6281 InitFieldOffset += NestedField->Offset;
6282 assert(NestedField);
6283 if (!this->emitGetPtrThisField(InitFieldOffset, InitExpr))
6284 return false;
6285 if (!this->emitFinishInitPop(InitExpr))
6286 return false;
6287 }
6288
6289 } else {
6290 assert(Init->isDelegatingInitializer());
6291 if (!this->emitThis(InitExpr))
6292 return false;
6293 if (!this->visitInitializer(Init->getInit()))
6294 return false;
6295 if (!this->emitPopPtr(InitExpr))
6296 return false;
6297 }
6298
6299 if (!Scope.destroyLocals())
6300 return false;
6301 }
6302
6303 if (const auto *Body = Ctor->getBody())
6304 if (!visitStmt(Body))
6305 return false;
6306
6307 return this->emitRetVoid(SourceInfo{});
6308}
6309
6310template <class Emitter>
6311bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) {
6312 const RecordDecl *RD = Dtor->getParent();
6313 const Record *R = this->getRecord(RD);
6314 if (!R)
6315 return false;
6316
6317 if (!Dtor->isTrivial() && Dtor->getBody()) {
6318 if (!this->visitStmt(Dtor->getBody()))
6319 return false;
6320 }
6321
6322 if (!this->emitThis(Dtor))
6323 return false;
6324
6325 if (!this->emitCheckDestruction(Dtor))
6326 return false;
6327
6328 assert(R);
6329 if (!R->isUnion()) {
6330
6332 // First, destroy all fields.
6333 for (const Record::Field &Field : llvm::reverse(R->fields())) {
6334 const Descriptor *D = Field.Desc;
6335 if (D->hasTrivialDtor())
6336 continue;
6337 if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
6338 return false;
6339 if (!this->emitDestructionPop(D, SourceInfo{}))
6340 return false;
6341 }
6342 }
6343
6344 for (const Record::Base &Base : llvm::reverse(R->bases())) {
6345 if (Base.R->hasTrivialDtor())
6346 continue;
6347 if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
6348 return false;
6349 if (!this->emitRecordDestructionPop(Base.R, {}))
6350 return false;
6351 }
6352
6353 // FIXME: Virtual bases.
6354 return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor);
6355}
6356
6357template <class Emitter>
6358bool Compiler<Emitter>::compileUnionAssignmentOperator(
6359 const CXXMethodDecl *MD) {
6360 if (!this->emitThis(MD))
6361 return false;
6362
6363 const ParmVarDecl *PVD = MD->getParamDecl(0);
6364 ParamOffset PO = this->Params[PVD]; // Must exist.
6365
6366 if (!this->emitGetParam(PT_Ptr, PO.Offset, MD))
6367 return false;
6368
6369 return this->emitMemcpy(MD) && this->emitRet(PT_Ptr, MD);
6370}
6371
6372template <class Emitter>
6374 // Classify the return type.
6375 ReturnType = this->classify(F->getReturnType());
6376
6377 this->CompilingFunction = F;
6378
6379 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F))
6380 return this->compileConstructor(Ctor);
6381 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F))
6382 return this->compileDestructor(Dtor);
6383
6384 // Emit custom code if this is a lambda static invoker.
6385 if (const auto *MD = dyn_cast<CXXMethodDecl>(F)) {
6386 const RecordDecl *RD = MD->getParent();
6387
6388 if (RD->isUnion() &&
6390 return this->compileUnionAssignmentOperator(MD);
6391
6392 if (MD->isLambdaStaticInvoker())
6393 return this->emitLambdaStaticInvokerBody(MD);
6394 }
6395
6396 // Regular functions.
6397 if (const auto *Body = F->getBody())
6398 if (!visitStmt(Body))
6399 return false;
6400
6401 // Emit a guard return to protect against a code path missing one.
6402 if (F->getReturnType()->isVoidType())
6403 return this->emitRetVoid(SourceInfo{});
6404 return this->emitNoRet(SourceInfo{});
6405}
6406
6407template <class Emitter>
6409 const Expr *SubExpr = E->getSubExpr();
6410 if (SubExpr->getType()->isAnyComplexType())
6411 return this->VisitComplexUnaryOperator(E);
6412 if (SubExpr->getType()->isVectorType())
6413 return this->VisitVectorUnaryOperator(E);
6414 if (SubExpr->getType()->isFixedPointType())
6415 return this->VisitFixedPointUnaryOperator(E);
6416 OptPrimType T = classify(SubExpr->getType());
6417
6418 switch (E->getOpcode()) {
6419 case UO_PostInc: { // x++
6420 if (!Ctx.getLangOpts().CPlusPlus14)
6421 return this->emitInvalid(E);
6422 if (!T)
6423 return this->emitError(E);
6424
6425 if (!this->visit(SubExpr))
6426 return false;
6427
6428 if (T == PT_Ptr) {
6429 if (!this->emitIncPtr(E))
6430 return false;
6431
6432 return DiscardResult ? this->emitPopPtr(E) : true;
6433 }
6434
6435 if (T == PT_Float) {
6436 return DiscardResult ? this->emitIncfPop(getFPOptions(E), E)
6437 : this->emitIncf(getFPOptions(E), E);
6438 }
6439
6440 return DiscardResult ? this->emitIncPop(*T, E->canOverflow(), E)
6441 : this->emitInc(*T, E->canOverflow(), E);
6442 }
6443 case UO_PostDec: { // x--
6444 if (!Ctx.getLangOpts().CPlusPlus14)
6445 return this->emitInvalid(E);
6446 if (!T)
6447 return this->emitError(E);
6448
6449 if (!this->visit(SubExpr))
6450 return false;
6451
6452 if (T == PT_Ptr) {
6453 if (!this->emitDecPtr(E))
6454 return false;
6455
6456 return DiscardResult ? this->emitPopPtr(E) : true;
6457 }
6458
6459 if (T == PT_Float) {
6460 return DiscardResult ? this->emitDecfPop(getFPOptions(E), E)
6461 : this->emitDecf(getFPOptions(E), E);
6462 }
6463
6464 return DiscardResult ? this->emitDecPop(*T, E->canOverflow(), E)
6465 : this->emitDec(*T, E->canOverflow(), E);
6466 }
6467 case UO_PreInc: { // ++x
6468 if (!Ctx.getLangOpts().CPlusPlus14)
6469 return this->emitInvalid(E);
6470 if (!T)
6471 return this->emitError(E);
6472
6473 if (!this->visit(SubExpr))
6474 return false;
6475
6476 if (T == PT_Ptr) {
6477 if (!this->emitLoadPtr(E))
6478 return false;
6479 if (!this->emitConstUint8(1, E))
6480 return false;
6481 if (!this->emitAddOffsetUint8(E))
6482 return false;
6483 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
6484 }
6485
6486 // Post-inc and pre-inc are the same if the value is to be discarded.
6487 if (DiscardResult) {
6488 if (T == PT_Float)
6489 return this->emitIncfPop(getFPOptions(E), E);
6490 return this->emitIncPop(*T, E->canOverflow(), E);
6491 }
6492
6493 if (T == PT_Float) {
6494 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
6495 if (!this->emitLoadFloat(E))
6496 return false;
6497 APFloat F(TargetSemantics, 1);
6498 if (!this->emitFloat(F, E))
6499 return false;
6500
6501 if (!this->emitAddf(getFPOptions(E), E))
6502 return false;
6503 if (!this->emitStoreFloat(E))
6504 return false;
6505 } else {
6506 assert(isIntegralType(*T));
6507 if (!this->emitPreInc(*T, E->canOverflow(), E))
6508 return false;
6509 }
6510 return E->isGLValue() || this->emitLoadPop(*T, E);
6511 }
6512 case UO_PreDec: { // --x
6513 if (!Ctx.getLangOpts().CPlusPlus14)
6514 return this->emitInvalid(E);
6515 if (!T)
6516 return this->emitError(E);
6517
6518 if (!this->visit(SubExpr))
6519 return false;
6520
6521 if (T == PT_Ptr) {
6522 if (!this->emitLoadPtr(E))
6523 return false;
6524 if (!this->emitConstUint8(1, E))
6525 return false;
6526 if (!this->emitSubOffsetUint8(E))
6527 return false;
6528 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
6529 }
6530
6531 // Post-dec and pre-dec are the same if the value is to be discarded.
6532 if (DiscardResult) {
6533 if (T == PT_Float)
6534 return this->emitDecfPop(getFPOptions(E), E);
6535 return this->emitDecPop(*T, E->canOverflow(), E);
6536 }
6537
6538 if (T == PT_Float) {
6539 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
6540 if (!this->emitLoadFloat(E))
6541 return false;
6542 APFloat F(TargetSemantics, 1);
6543 if (!this->emitFloat(F, E))
6544 return false;
6545
6546 if (!this->emitSubf(getFPOptions(E), E))
6547 return false;
6548 if (!this->emitStoreFloat(E))
6549 return false;
6550 } else {
6551 assert(isIntegralType(*T));
6552 if (!this->emitPreDec(*T, E->canOverflow(), E))
6553 return false;
6554 }
6555 return E->isGLValue() || this->emitLoadPop(*T, E);
6556 }
6557 case UO_LNot: // !x
6558 if (!T)
6559 return this->emitError(E);
6560
6561 if (DiscardResult)
6562 return this->discard(SubExpr);
6563
6564 if (!this->visitBool(SubExpr))
6565 return false;
6566
6567 if (!this->emitInv(E))
6568 return false;
6569
6570 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
6571 return this->emitCast(PT_Bool, ET, E);
6572 return true;
6573 case UO_Minus: // -x
6574 if (!T)
6575 return this->emitError(E);
6576
6577 if (!this->visit(SubExpr))
6578 return false;
6579 return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E);
6580 case UO_Plus: // +x
6581 if (!T)
6582 return this->emitError(E);
6583
6584 if (!this->visit(SubExpr)) // noop
6585 return false;
6586 return DiscardResult ? this->emitPop(*T, E) : true;
6587 case UO_AddrOf: // &x
6588 if (E->getType()->isMemberPointerType()) {
6589 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6590 // member can be formed.
6591 return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E);
6592 }
6593 // We should already have a pointer when we get here.
6594 return this->delegate(SubExpr);
6595 case UO_Deref: // *x
6596 if (DiscardResult)
6597 return this->discard(SubExpr);
6598
6599 if (!this->visit(SubExpr))
6600 return false;
6601
6602 if (!this->emitCheckNull(E))
6603 return false;
6604
6605 if (classifyPrim(SubExpr) == PT_Ptr)
6606 return this->emitNarrowPtr(E);
6607 return true;
6608
6609 case UO_Not: // ~x
6610 if (!T)
6611 return this->emitError(E);
6612
6613 if (!this->visit(SubExpr))
6614 return false;
6615 return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
6616 case UO_Real: // __real x
6617 assert(T);
6618 return this->delegate(SubExpr);
6619 case UO_Imag: { // __imag x
6620 assert(T);
6621 if (!this->discard(SubExpr))
6622 return false;
6623 return this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr);
6624 }
6625 case UO_Extension:
6626 return this->delegate(SubExpr);
6627 case UO_Coawait:
6628 assert(false && "Unhandled opcode");
6629 }
6630
6631 return false;
6632}
6633
6634template <class Emitter>
6636 const Expr *SubExpr = E->getSubExpr();
6637 assert(SubExpr->getType()->isAnyComplexType());
6638
6639 if (DiscardResult)
6640 return this->discard(SubExpr);
6641
6642 OptPrimType ResT = classify(E);
6643 auto prepareResult = [=]() -> bool {
6644 if (!ResT && !Initializing) {
6645 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
6646 if (!LocalIndex)
6647 return false;
6648 return this->emitGetPtrLocal(*LocalIndex, E);
6649 }
6650
6651 return true;
6652 };
6653
6654 // The offset of the temporary, if we created one.
6655 unsigned SubExprOffset = ~0u;
6656 auto createTemp = [=, &SubExprOffset]() -> bool {
6657 SubExprOffset =
6658 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
6659 if (!this->visit(SubExpr))
6660 return false;
6661 return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
6662 };
6663
6664 PrimType ElemT = classifyComplexElementType(SubExpr->getType());
6665 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
6666 if (!this->emitGetLocal(PT_Ptr, Offset, E))
6667 return false;
6668 return this->emitArrayElemPop(ElemT, Index, E);
6669 };
6670
6671 switch (E->getOpcode()) {
6672 case UO_Minus:
6673 if (!prepareResult())
6674 return false;
6675 if (!createTemp())
6676 return false;
6677 for (unsigned I = 0; I != 2; ++I) {
6678 if (!getElem(SubExprOffset, I))
6679 return false;
6680 if (!this->emitNeg(ElemT, E))
6681 return false;
6682 if (!this->emitInitElem(ElemT, I, E))
6683 return false;
6684 }
6685 break;
6686
6687 case UO_Plus: // +x
6688 case UO_AddrOf: // &x
6689 case UO_Deref: // *x
6690 return this->delegate(SubExpr);
6691
6692 case UO_LNot:
6693 if (!this->visit(SubExpr))
6694 return false;
6695 if (!this->emitComplexBoolCast(SubExpr))
6696 return false;
6697 if (!this->emitInv(E))
6698 return false;
6699 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
6700 return this->emitCast(PT_Bool, ET, E);
6701 return true;
6702
6703 case UO_Real:
6704 return this->emitComplexReal(SubExpr);
6705
6706 case UO_Imag:
6707 if (!this->visit(SubExpr))
6708 return false;
6709
6710 if (SubExpr->isLValue()) {
6711 if (!this->emitConstUint8(1, E))
6712 return false;
6713 return this->emitArrayElemPtrPopUint8(E);
6714 }
6715
6716 // Since our _Complex implementation does not map to a primitive type,
6717 // we sometimes have to do the lvalue-to-rvalue conversion here manually.
6718 return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E);
6719
6720 case UO_Not: // ~x
6721 if (!this->visit(SubExpr))
6722 return false;
6723 // Negate the imaginary component.
6724 if (!this->emitArrayElem(ElemT, 1, E))
6725 return false;
6726 if (!this->emitNeg(ElemT, E))
6727 return false;
6728 if (!this->emitInitElem(ElemT, 1, E))
6729 return false;
6730 return DiscardResult ? this->emitPopPtr(E) : true;
6731
6732 case UO_Extension:
6733 return this->delegate(SubExpr);
6734
6735 default:
6736 return this->emitInvalid(E);
6737 }
6738
6739 return true;
6740}
6741
6742template <class Emitter>
6744 const Expr *SubExpr = E->getSubExpr();
6745 assert(SubExpr->getType()->isVectorType());
6746
6747 if (DiscardResult)
6748 return this->discard(SubExpr);
6749
6750 auto UnaryOp = E->getOpcode();
6751 if (UnaryOp == UO_Extension)
6752 return this->delegate(SubExpr);
6753
6754 if (UnaryOp != UO_Plus && UnaryOp != UO_Minus && UnaryOp != UO_LNot &&
6755 UnaryOp != UO_Not && UnaryOp != UO_AddrOf)
6756 return this->emitInvalid(E);
6757
6758 // Nothing to do here.
6759 if (UnaryOp == UO_Plus || UnaryOp == UO_AddrOf)
6760 return this->delegate(SubExpr);
6761
6762 if (!Initializing) {
6763 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
6764 if (!LocalIndex)
6765 return false;
6766 if (!this->emitGetPtrLocal(*LocalIndex, E))
6767 return false;
6768 }
6769
6770 // The offset of the temporary, if we created one.
6771 unsigned SubExprOffset =
6772 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
6773 if (!this->visit(SubExpr))
6774 return false;
6775 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
6776 return false;
6777
6778 const auto *VecTy = SubExpr->getType()->getAs<VectorType>();
6779 PrimType ElemT = classifyVectorElementType(SubExpr->getType());
6780 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
6781 if (!this->emitGetLocal(PT_Ptr, Offset, E))
6782 return false;
6783 return this->emitArrayElemPop(ElemT, Index, E);
6784 };
6785
6786 switch (UnaryOp) {
6787 case UO_Minus:
6788 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
6789 if (!getElem(SubExprOffset, I))
6790 return false;
6791 if (!this->emitNeg(ElemT, E))
6792 return false;
6793 if (!this->emitInitElem(ElemT, I, E))
6794 return false;
6795 }
6796 break;
6797 case UO_LNot: { // !x
6798 // In C++, the logic operators !, &&, || are available for vectors. !v is
6799 // equivalent to v == 0.
6800 //
6801 // The result of the comparison is a vector of the same width and number of
6802 // elements as the comparison operands with a signed integral element type.
6803 //
6804 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
6805 QualType ResultVecTy = E->getType();
6806 PrimType ResultVecElemT =
6807 classifyPrim(ResultVecTy->getAs<VectorType>()->getElementType());
6808 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
6809 if (!getElem(SubExprOffset, I))
6810 return false;
6811 // operator ! on vectors returns -1 for 'truth', so negate it.
6812 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
6813 return false;
6814 if (!this->emitInv(E))
6815 return false;
6816 if (!this->emitPrimCast(PT_Bool, ElemT, VecTy->getElementType(), E))
6817 return false;
6818 if (!this->emitNeg(ElemT, E))
6819 return false;
6820 if (ElemT != ResultVecElemT &&
6821 !this->emitPrimCast(ElemT, ResultVecElemT, ResultVecTy, E))
6822 return false;
6823 if (!this->emitInitElem(ResultVecElemT, I, E))
6824 return false;
6825 }
6826 break;
6827 }
6828 case UO_Not: // ~x
6829 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
6830 if (!getElem(SubExprOffset, I))
6831 return false;
6832 if (ElemT == PT_Bool) {
6833 if (!this->emitInv(E))
6834 return false;
6835 } else {
6836 if (!this->emitComp(ElemT, E))
6837 return false;
6838 }
6839 if (!this->emitInitElem(ElemT, I, E))
6840 return false;
6841 }
6842 break;
6843 default:
6844 llvm_unreachable("Unsupported unary operators should be handled up front");
6845 }
6846 return true;
6847}
6848
6849template <class Emitter>
6851 if (DiscardResult)
6852 return true;
6853
6854 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D))
6855 return this->emitConst(ECD->getInitVal(), E);
6856 if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) {
6857 const Function *F = getFunction(FuncDecl);
6858 return F && this->emitGetFnPtr(F, E);
6859 }
6860 if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) {
6861 if (UnsignedOrNone Index = P.getOrCreateGlobal(D)) {
6862 if (!this->emitGetPtrGlobal(*Index, E))
6863 return false;
6864 if (OptPrimType T = classify(E->getType())) {
6865 if (!this->visitAPValue(TPOD->getValue(), *T, E))
6866 return false;
6867 return this->emitInitGlobal(*T, *Index, E);
6868 }
6869 return this->visitAPValueInitializer(TPOD->getValue(), E,
6870 TPOD->getType());
6871 }
6872 return false;
6873 }
6874
6875 // References are implemented via pointers, so when we see a DeclRefExpr
6876 // pointing to a reference, we need to get its value directly (i.e. the
6877 // pointer to the actual value) instead of a pointer to the pointer to the
6878 // value.
6879 bool IsReference = D->getType()->isReferenceType();
6880
6881 // Function parameters.
6882 // Note that it's important to check them first since we might have a local
6883 // variable created for a ParmVarDecl as well.
6884 if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
6885 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
6887 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
6888 /*InitializerFailed=*/false, E);
6889 }
6890 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
6891 if (IsReference || !It->second.IsPtr)
6892 return this->emitGetParam(classifyPrim(E), It->second.Offset, E);
6893
6894 return this->emitGetPtrParam(It->second.Offset, E);
6895 }
6896 }
6897 // Local variables.
6898 if (auto It = Locals.find(D); It != Locals.end()) {
6899 const unsigned Offset = It->second.Offset;
6900 if (IsReference)
6901 return this->emitGetLocal(classifyPrim(E), Offset, E);
6902 return this->emitGetPtrLocal(Offset, E);
6903 }
6904 // Global variables.
6905 if (auto GlobalIndex = P.getGlobal(D)) {
6906 if (IsReference) {
6907 if (!Ctx.getLangOpts().CPlusPlus11)
6908 return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E);
6909 return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E);
6910 }
6911
6912 return this->emitGetPtrGlobal(*GlobalIndex, E);
6913 }
6914
6915 // In case we need to re-visit a declaration.
6916 auto revisit = [&](const VarDecl *VD) -> bool {
6917 if (!this->emitPushCC(VD->hasConstantInitialization(), E))
6918 return false;
6919 auto VarState = this->visitDecl(VD, /*IsConstexprUnknown=*/true);
6920
6921 if (!this->emitPopCC(E))
6922 return false;
6923
6924 if (VarState.notCreated())
6925 return true;
6926 if (!VarState)
6927 return false;
6928 // Retry.
6929 return this->visitDeclRef(D, E);
6930 };
6931
6932 // Lambda captures.
6933 if (auto It = this->LambdaCaptures.find(D);
6934 It != this->LambdaCaptures.end()) {
6935 auto [Offset, IsPtr] = It->second;
6936
6937 if (IsPtr)
6938 return this->emitGetThisFieldPtr(Offset, E);
6939 return this->emitGetPtrThisField(Offset, E);
6940 }
6941
6942 if (const auto *DRE = dyn_cast<DeclRefExpr>(E);
6943 DRE && DRE->refersToEnclosingVariableOrCapture()) {
6944 if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture())
6945 return revisit(VD);
6946 }
6947
6948 if (const auto *BD = dyn_cast<BindingDecl>(D))
6949 return this->visit(BD->getBinding());
6950
6951 // Avoid infinite recursion.
6952 if (D == InitializingDecl)
6953 return this->emitDummyPtr(D, E);
6954
6955 // Try to lazily visit (or emit dummy pointers for) declarations
6956 // we haven't seen yet.
6957 // For C.
6958 if (!Ctx.getLangOpts().CPlusPlus) {
6959 if (const auto *VD = dyn_cast<VarDecl>(D);
6960 VD && VD->getAnyInitializer() &&
6961 VD->getType().isConstant(Ctx.getASTContext()) && !VD->isWeak())
6962 return revisit(VD);
6963 return this->emitDummyPtr(D, E);
6964 }
6965
6966 // ... and C++.
6967 const auto *VD = dyn_cast<VarDecl>(D);
6968 if (!VD)
6969 return this->emitDummyPtr(D, E);
6970
6971 const auto typeShouldBeVisited = [&](QualType T) -> bool {
6972 if (T.isConstant(Ctx.getASTContext()))
6973 return true;
6974 return T->isReferenceType();
6975 };
6976
6977 if ((VD->hasGlobalStorage() || VD->isStaticDataMember()) &&
6978 typeShouldBeVisited(VD->getType())) {
6979 if (const Expr *Init = VD->getAnyInitializer();
6980 Init && !Init->isValueDependent()) {
6981 // Whether or not the evaluation is successul doesn't really matter
6982 // here -- we will create a global variable in any case, and that
6983 // will have the state of initializer evaluation attached.
6984 APValue V;
6986 (void)Init->EvaluateAsInitializer(V, Ctx.getASTContext(), VD, Notes,
6987 true);
6988 return this->visitDeclRef(D, E);
6989 }
6990 return revisit(VD);
6991 }
6992
6993 // FIXME: The evaluateValue() check here is a little ridiculous, since
6994 // it will ultimately call into Context::evaluateAsInitializer(). In
6995 // other words, we're evaluating the initializer, just to know if we can
6996 // evaluate the initializer.
6997 if (VD->isLocalVarDecl() && typeShouldBeVisited(VD->getType()) &&
6998 VD->getInit() && !VD->getInit()->isValueDependent()) {
6999
7000 if (VD->evaluateValue())
7001 return revisit(VD);
7002
7003 if (!IsReference)
7004 return this->emitDummyPtr(D, E);
7005
7006 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
7007 /*InitializerFailed=*/true, E);
7008 }
7009
7010 return this->emitDummyPtr(D, E);
7011}
7012
7013template <class Emitter>
7015 const auto *D = E->getDecl();
7016 return this->visitDeclRef(D, E);
7017}
7018
7019template <class Emitter> void Compiler<Emitter>::emitCleanup() {
7020 for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent())
7021 C->emitDestruction();
7022}
7023
7024template <class Emitter>
7025unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType,
7026 const QualType DerivedType) {
7027 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
7028 if (const auto *R = Ty->getPointeeCXXRecordDecl())
7029 return R;
7030 return Ty->getAsCXXRecordDecl();
7031 };
7032 const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType);
7033 const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType);
7034
7035 return Ctx.collectBaseOffset(BaseDecl, DerivedDecl);
7036}
7037
7038/// Emit casts from a PrimType to another PrimType.
7039template <class Emitter>
7040bool Compiler<Emitter>::emitPrimCast(PrimType FromT, PrimType ToT,
7041 QualType ToQT, const Expr *E) {
7042
7043 if (FromT == PT_Float) {
7044 // Floating to floating.
7045 if (ToT == PT_Float) {
7046 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
7047 return this->emitCastFP(ToSem, getRoundingMode(E), E);
7048 }
7049
7050 if (ToT == PT_IntAP)
7051 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT),
7052 getFPOptions(E), E);
7053 if (ToT == PT_IntAPS)
7054 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT),
7055 getFPOptions(E), E);
7056
7057 // Float to integral.
7058 if (isIntegralType(ToT) || ToT == PT_Bool)
7059 return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E);
7060 }
7061
7062 if (isIntegralType(FromT) || FromT == PT_Bool) {
7063 if (ToT == PT_IntAP)
7064 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
7065 if (ToT == PT_IntAPS)
7066 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
7067
7068 // Integral to integral.
7069 if (isIntegralType(ToT) || ToT == PT_Bool)
7070 return FromT != ToT ? this->emitCast(FromT, ToT, E) : true;
7071
7072 if (ToT == PT_Float) {
7073 // Integral to floating.
7074 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
7075 return this->emitCastIntegralFloating(FromT, ToSem, getFPOptions(E), E);
7076 }
7077 }
7078
7079 return false;
7080}
7081
7082/// Emits __real(SubExpr)
7083template <class Emitter>
7084bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) {
7085 assert(SubExpr->getType()->isAnyComplexType());
7086
7087 if (DiscardResult)
7088 return this->discard(SubExpr);
7089
7090 if (!this->visit(SubExpr))
7091 return false;
7092 if (SubExpr->isLValue()) {
7093 if (!this->emitConstUint8(0, SubExpr))
7094 return false;
7095 return this->emitArrayElemPtrPopUint8(SubExpr);
7096 }
7097
7098 // Rvalue, load the actual element.
7099 return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()),
7100 0, SubExpr);
7101}
7102
7103template <class Emitter>
7104bool Compiler<Emitter>::emitComplexBoolCast(const Expr *E) {
7105 assert(!DiscardResult);
7106 PrimType ElemT = classifyComplexElementType(E->getType());
7107 // We emit the expression (__real(E) != 0 || __imag(E) != 0)
7108 // for us, that means (bool)E[0] || (bool)E[1]
7109 if (!this->emitArrayElem(ElemT, 0, E))
7110 return false;
7111 if (ElemT == PT_Float) {
7112 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
7113 return false;
7114 } else {
7115 if (!this->emitCast(ElemT, PT_Bool, E))
7116 return false;
7117 }
7118
7119 // We now have the bool value of E[0] on the stack.
7120 LabelTy LabelTrue = this->getLabel();
7121 if (!this->jumpTrue(LabelTrue))
7122 return false;
7123
7124 if (!this->emitArrayElemPop(ElemT, 1, E))
7125 return false;
7126 if (ElemT == PT_Float) {
7127 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
7128 return false;
7129 } else {
7130 if (!this->emitCast(ElemT, PT_Bool, E))
7131 return false;
7132 }
7133 // Leave the boolean value of E[1] on the stack.
7134 LabelTy EndLabel = this->getLabel();
7135 this->jump(EndLabel);
7136
7137 this->emitLabel(LabelTrue);
7138 if (!this->emitPopPtr(E))
7139 return false;
7140 if (!this->emitConstBool(true, E))
7141 return false;
7142
7143 this->fallthrough(EndLabel);
7144 this->emitLabel(EndLabel);
7145
7146 return true;
7147}
7148
7149template <class Emitter>
7150bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS,
7151 const BinaryOperator *E) {
7152 assert(E->isComparisonOp());
7153 assert(!Initializing);
7154 assert(!DiscardResult);
7155
7156 PrimType ElemT;
7157 bool LHSIsComplex;
7158 unsigned LHSOffset;
7159 if (LHS->getType()->isAnyComplexType()) {
7160 LHSIsComplex = true;
7161 ElemT = classifyComplexElementType(LHS->getType());
7162 LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
7163 if (!this->visit(LHS))
7164 return false;
7165 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
7166 return false;
7167 } else {
7168 LHSIsComplex = false;
7169 PrimType LHST = classifyPrim(LHS->getType());
7170 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, /*IsConst=*/true);
7171 if (!this->visit(LHS))
7172 return false;
7173 if (!this->emitSetLocal(LHST, LHSOffset, E))
7174 return false;
7175 }
7176
7177 bool RHSIsComplex;
7178 unsigned RHSOffset;
7179 if (RHS->getType()->isAnyComplexType()) {
7180 RHSIsComplex = true;
7181 ElemT = classifyComplexElementType(RHS->getType());
7182 RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
7183 if (!this->visit(RHS))
7184 return false;
7185 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
7186 return false;
7187 } else {
7188 RHSIsComplex = false;
7189 PrimType RHST = classifyPrim(RHS->getType());
7190 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, /*IsConst=*/true);
7191 if (!this->visit(RHS))
7192 return false;
7193 if (!this->emitSetLocal(RHST, RHSOffset, E))
7194 return false;
7195 }
7196
7197 auto getElem = [&](unsigned LocalOffset, unsigned Index,
7198 bool IsComplex) -> bool {
7199 if (IsComplex) {
7200 if (!this->emitGetLocal(PT_Ptr, LocalOffset, E))
7201 return false;
7202 return this->emitArrayElemPop(ElemT, Index, E);
7203 }
7204 return this->emitGetLocal(ElemT, LocalOffset, E);
7205 };
7206
7207 for (unsigned I = 0; I != 2; ++I) {
7208 // Get both values.
7209 if (!getElem(LHSOffset, I, LHSIsComplex))
7210 return false;
7211 if (!getElem(RHSOffset, I, RHSIsComplex))
7212 return false;
7213 // And compare them.
7214 if (!this->emitEQ(ElemT, E))
7215 return false;
7216
7217 if (!this->emitCastBoolUint8(E))
7218 return false;
7219 }
7220
7221 // We now have two bool values on the stack. Compare those.
7222 if (!this->emitAddUint8(E))
7223 return false;
7224 if (!this->emitConstUint8(2, E))
7225 return false;
7226
7227 if (E->getOpcode() == BO_EQ) {
7228 if (!this->emitEQUint8(E))
7229 return false;
7230 } else if (E->getOpcode() == BO_NE) {
7231 if (!this->emitNEUint8(E))
7232 return false;
7233 } else
7234 return false;
7235
7236 // In C, this returns an int.
7237 if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool)
7238 return this->emitCast(PT_Bool, ResT, E);
7239 return true;
7240}
7241
7242/// When calling this, we have a pointer of the local-to-destroy
7243/// on the stack.
7244/// Emit destruction of record types (or arrays of record types).
7245template <class Emitter>
7246bool Compiler<Emitter>::emitRecordDestructionPop(const Record *R,
7247 SourceInfo Loc) {
7248 assert(R);
7249 assert(!R->hasTrivialDtor());
7250 const CXXDestructorDecl *Dtor = R->getDestructor();
7251 assert(Dtor);
7252 const Function *DtorFunc = getFunction(Dtor);
7253 if (!DtorFunc)
7254 return false;
7255 assert(DtorFunc->hasThisPointer());
7256 assert(DtorFunc->getNumParams() == 1);
7257 return this->emitCall(DtorFunc, 0, Loc);
7258}
7259/// When calling this, we have a pointer of the local-to-destroy
7260/// on the stack.
7261/// Emit destruction of record types (or arrays of record types).
7262template <class Emitter>
7263bool Compiler<Emitter>::emitDestructionPop(const Descriptor *Desc,
7264 SourceInfo Loc) {
7265 assert(Desc);
7266 assert(!Desc->hasTrivialDtor());
7267
7268 // Arrays.
7269 if (Desc->isArray()) {
7270 const Descriptor *ElemDesc = Desc->ElemDesc;
7271 assert(ElemDesc);
7272
7273 unsigned N = Desc->getNumElems();
7274 if (N == 0)
7275 return this->emitPopPtr(Loc);
7276
7277 for (ssize_t I = N - 1; I >= 1; --I) {
7278 if (!this->emitConstUint64(I, Loc))
7279 return false;
7280 if (!this->emitArrayElemPtrUint64(Loc))
7281 return false;
7282 if (!this->emitDestructionPop(ElemDesc, Loc))
7283 return false;
7284 }
7285 // Last iteration, removes the instance pointer from the stack.
7286 if (!this->emitConstUint64(0, Loc))
7287 return false;
7288 if (!this->emitArrayElemPtrPopUint64(Loc))
7289 return false;
7290 return this->emitDestructionPop(ElemDesc, Loc);
7291 }
7292
7293 assert(Desc->ElemRecord);
7294 assert(!Desc->ElemRecord->hasTrivialDtor());
7295 return this->emitRecordDestructionPop(Desc->ElemRecord, Loc);
7296}
7297
7298/// Create a dummy pointer for the given decl (or expr) and
7299/// push a pointer to it on the stack.
7300template <class Emitter>
7301bool Compiler<Emitter>::emitDummyPtr(const DeclTy &D, const Expr *E) {
7302 assert(!DiscardResult && "Should've been checked before");
7303
7304 unsigned DummyID = P.getOrCreateDummy(D);
7305
7306 if (!this->emitGetPtrGlobal(DummyID, E))
7307 return false;
7308 if (E->getType()->isVoidType())
7309 return true;
7310
7311 // Convert the dummy pointer to another pointer type if we have to.
7312 if (PrimType PT = classifyPrim(E); PT != PT_Ptr) {
7313 if (isPtrType(PT))
7314 return this->emitDecayPtr(PT_Ptr, PT, E);
7315 return false;
7316 }
7317 return true;
7318}
7319
7320template <class Emitter>
7321bool Compiler<Emitter>::emitFloat(const APFloat &F, const Expr *E) {
7322 assert(!DiscardResult && "Should've been checked before");
7323
7324 if (Floating::singleWord(F.getSemantics()))
7325 return this->emitConstFloat(Floating(F), E);
7326
7327 APInt I = F.bitcastToAPInt();
7328 return this->emitConstFloat(
7329 Floating(const_cast<uint64_t *>(I.getRawData()),
7330 llvm::APFloatBase::SemanticsToEnum(F.getSemantics())),
7331 E);
7332}
7333
7334// This function is constexpr if and only if To, From, and the types of
7335// all subobjects of To and From are types T such that...
7336// (3.1) - is_union_v<T> is false;
7337// (3.2) - is_pointer_v<T> is false;
7338// (3.3) - is_member_pointer_v<T> is false;
7339// (3.4) - is_volatile_v<T> is false; and
7340// (3.5) - T has no non-static data members of reference type
7341template <class Emitter>
7342bool Compiler<Emitter>::emitBuiltinBitCast(const CastExpr *E) {
7343 const Expr *SubExpr = E->getSubExpr();
7344 QualType FromType = SubExpr->getType();
7345 QualType ToType = E->getType();
7346 OptPrimType ToT = classify(ToType);
7347
7348 assert(!ToType->isReferenceType());
7349
7350 // Prepare storage for the result in case we discard.
7351 if (DiscardResult && !Initializing && !ToT) {
7352 UnsignedOrNone LocalIndex = allocateLocal(E);
7353 if (!LocalIndex)
7354 return false;
7355 if (!this->emitGetPtrLocal(*LocalIndex, E))
7356 return false;
7357 }
7358
7359 // Get a pointer to the value-to-cast on the stack.
7360 // For CK_LValueToRValueBitCast, this is always an lvalue and
7361 // we later assume it to be one (i.e. a PT_Ptr). However,
7362 // we call this function for other utility methods where
7363 // a bitcast might be useful, so convert it to a PT_Ptr in that case.
7364 if (SubExpr->isGLValue() || FromType->isVectorType()) {
7365 if (!this->visit(SubExpr))
7366 return false;
7367 } else if (OptPrimType FromT = classify(SubExpr)) {
7368 unsigned TempOffset =
7369 allocateLocalPrimitive(SubExpr, *FromT, /*IsConst=*/true);
7370 if (!this->visit(SubExpr))
7371 return false;
7372 if (!this->emitSetLocal(*FromT, TempOffset, E))
7373 return false;
7374 if (!this->emitGetPtrLocal(TempOffset, E))
7375 return false;
7376 } else {
7377 return false;
7378 }
7379
7380 if (!ToT) {
7381 if (!this->emitBitCast(E))
7382 return false;
7383 return DiscardResult ? this->emitPopPtr(E) : true;
7384 }
7385 assert(ToT);
7386
7387 const llvm::fltSemantics *TargetSemantics = nullptr;
7388 if (ToT == PT_Float)
7389 TargetSemantics = &Ctx.getFloatSemantics(ToType);
7390
7391 // Conversion to a primitive type. FromType can be another
7392 // primitive type, or a record/array.
7393 bool ToTypeIsUChar = (ToType->isSpecificBuiltinType(BuiltinType::UChar) ||
7394 ToType->isSpecificBuiltinType(BuiltinType::Char_U));
7395 uint32_t ResultBitWidth = std::max(Ctx.getBitWidth(ToType), 8u);
7396
7397 if (!this->emitBitCastPrim(*ToT, ToTypeIsUChar || ToType->isStdByteType(),
7398 ResultBitWidth, TargetSemantics, E))
7399 return false;
7400
7401 if (DiscardResult)
7402 return this->emitPop(*ToT, E);
7403
7404 return true;
7405}
7406
7407namespace clang {
7408namespace interp {
7409
7410template class Compiler<ByteCodeEmitter>;
7411template class Compiler<EvalEmitter>;
7412
7413} // namespace interp
7414} // namespace clang
#define V(N, I)
static void emit(Program &P, llvm::SmallVectorImpl< std::byte > &Code, const T &Val, bool &Success)
Helper to write bytecode and bail out if 32-bit offsets become invalid.
static void emitCleanup(CIRGenFunction &cgf, EHScopeStack::Cleanup *cleanup)
#define EMIT_ARITH_OP(OP)
static CharUnits AlignOfType(QualType T, const ASTContext &ASTCtx, UnaryExprOrTypeTrait Kind)
static const Expr * stripDerivedToBaseCasts(const Expr *E)
static const Expr * stripCheckedDerivedToBaseCasts(const Expr *E)
static bool hasTrivialDefaultCtorParent(const FieldDecl *FD)
static bool initNeedsOverridenLoc(const CXXCtorInitializer *Init)
llvm::APSInt APSInt
Definition Compiler.cpp:23
a trap message and trap category.
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:576
ArrayRef< LValuePathEntry > getLValuePath() const
Definition APValue.cpp:1003
APSInt & getInt()
Definition APValue.h:489
APValue & getStructField(unsigned i)
Definition APValue.h:617
const FieldDecl * getUnionField() const
Definition APValue.h:629
unsigned getStructNumFields() const
Definition APValue.h:608
bool isArray() const
Definition APValue.h:474
bool isFloat() const
Definition APValue.h:468
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
APValue & getUnionValue()
Definition APValue.h:633
bool isLValue() const
Definition APValue.h:472
bool isMemberPointer() const
Definition APValue.h:477
bool isInt() const
Definition APValue.h:467
unsigned getArraySize() const
Definition APValue.h:599
bool isUnion() const
Definition APValue.h:476
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isStruct() const
Definition APValue.h:475
bool isNullPointer() const
Definition APValue.cpp:1019
APFloat & getFloat()
Definition APValue.h:503
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:188
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
const LangOptions & getLangOpts() const
Definition ASTContext.h:891
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4289
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4467
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4473
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4479
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition Expr.h:4486
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition Expr.h:5957
Represents a loop initializing the elements of an array.
Definition Expr.h:5904
llvm::APInt getArraySize() const
Definition Expr.h:5926
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5919
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5924
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2723
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2752
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition ExprCXX.h:2990
uint64_t getValue() const
Definition ExprCXX.h:3038
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3720
QualType getElementType() const
Definition TypeBase.h:3732
Attr - This represents one attribute.
Definition Attr.h:44
Represents an attribute applied to a statement.
Definition Stmt.h:2203
Stmt * getSubStmt()
Definition Stmt.h:2239
ArrayRef< const Attr * > getAttrs() const
Definition Stmt.h:2235
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3490
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3974
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4107
Expr * getLHS() const
Definition Expr.h:4024
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4074
static bool isShiftOp(Opcode Opc)
Definition Expr.h:4062
static bool isCommaOp(Opcode Opc)
Definition Expr.h:4077
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4121
Expr * getRHS() const
Definition Expr.h:4026
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4051
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4110
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4115
Opcode getOpcode() const
Definition Expr.h:4019
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4065
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6560
BreakStmt - This represents a break.
Definition Stmt.h:3135
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition ExprCXX.h:5470
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents binding an expression to a temporary.
Definition ExprCXX.h:1494
const Expr * getSubExpr() const
Definition ExprCXX.h:1516
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:723
bool getValue() const
Definition ExprCXX.h:740
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1692
arg_range arguments()
Definition ExprCXX.h:1673
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1651
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1689
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3019
Represents a C++ base or member initializer.
Definition DeclCXX.h:2369
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1271
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1378
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1105
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2620
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2659
bool isArrayForm() const
Definition ExprCXX.h:2646
bool isGlobalDelete() const
Definition ExprCXX.h:2645
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition ExprCXX.h:481
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:135
DeclStmt * getBeginStmt()
Definition StmtCXX.h:163
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:169
DeclStmt * getEndStmt()
Definition StmtCXX.h:166
DeclStmt * getRangeStmt()
Definition StmtCXX.h:162
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1753
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1790
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2735
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2714
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2845
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2349
bool isArray() const
Definition ExprCXX.h:2458
QualType getAllocatedType() const
Definition ExprCXX.h:2428
std::optional< Expr * > getArraySize()
This might return std::nullopt even if isArray() returns true, since there might not be an array size...
Definition ExprCXX.h:2463
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2497
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2488
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2453
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2527
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition ExprCXX.h:4303
bool getValue() const
Definition ExprCXX.h:4326
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:768
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5135
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5175
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
capture_const_range captures() const
Definition DeclCXX.h:1097
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1736
A C++ reinterpret_cast expression (C++ [expr.reinterpret.cast]).
Definition ExprCXX.h:526
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:286
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:304
An expression "T()" which creates an rvalue of a non-class type T.
Definition ExprCXX.h:2198
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition ExprCXX.h:800
Represents the this expression in C++.
Definition ExprCXX.h:1155
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1209
const Expr * getSubExpr() const
Definition ExprCXX.h:1229
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:69
CompoundStmt * getTryBlock()
Definition StmtCXX.h:100
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:848
bool isTypeOperand() const
Definition ExprCXX.h:884
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:161
Expr * getExprOperand() const
Definition ExprCXX.h:895
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:134
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1069
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1115
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2879
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3083
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3062
Expr * getCallee()
Definition Expr.h:3026
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3070
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3073
arg_range arguments()
Definition Expr.h:3131
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1599
CaseStmt - Represent a case statement.
Definition Stmt.h:1920
Stmt * getSubStmt()
Definition Stmt.h:2033
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3612
CastKind getCastKind() const
Definition Expr.h:3656
llvm::iterator_range< path_iterator > path()
Path through the class hierarchy taken by casts between base and derived classes (see implementation ...
Definition Expr.h:3699
Expr * getSubExpr()
Definition Expr.h:3662
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
unsigned getValue() const
Definition Expr.h:1631
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4784
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4820
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
QualType getElementType() const
Definition TypeBase.h:3285
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4236
QualType getComputationLHSType() const
Definition Expr.h:4270
QualType getComputationResultType() const
Definition Expr.h:4273
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3541
bool isFileScope() const
Definition Expr.h:3573
const Expr * getInitializer() const
Definition Expr.h:3569
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1720
body_range body()
Definition Stmt.h:1783
Stmt * getStmtExprResult()
Definition Stmt.h:1842
Represents the specialization of a concept - evaluates to a prvalue of type bool.
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3758
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3834
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1084
APValue getAPValueResult() const
Definition Expr.cpp:409
bool hasAPValueResult() const
Definition Expr.h:1159
ContinueStmt - This represents a continue.
Definition Stmt.h:3119
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition Expr.h:4655
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4745
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1272
ValueDecl * getDecl()
Definition Expr.h:1340
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1611
decl_range decls()
Definition Stmt.h:1659
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInvalidDecl() const
Definition DeclBase.h:588
bool hasAttr() const
Definition DeclBase.h:577
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
Stmt * getSubStmt()
Definition Stmt.h:2081
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2832
Stmt * getBody()
Definition Stmt.h:2857
Expr * getCond()
Definition Stmt.h:2850
Represents a reference to emded data.
Definition Expr.h:5062
ChildElementIter< false > begin()
Definition Expr.h:5168
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3655
This represents one expression.
Definition Expr.h:112
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:80
bool isGLValue() const
Definition Expr.h:287
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3061
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3069
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3624
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3207
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:476
QualType getType() const
Definition Expr.h:144
An expression trait intrinsic.
Definition ExprCXX.h:3063
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6500
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4403
const Expr * getBase() const
Definition Expr.h:6517
Represents a member of a struct/union/class.
Definition Decl.h:3157
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1577
llvm::APFloat getValue() const
Definition Expr.h:1668
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2888
Stmt * getInit()
Definition Stmt.h:2903
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1078
Stmt * getBody()
Definition Stmt.h:2932
Expr * getInc()
Definition Stmt.h:2931
Expr * getCond()
Definition Stmt.h:2930
DeclStmt * getConditionVariableDeclStmt()
If this ForStmt has a condition variable, return the faux DeclStmt associated with the creation of th...
Definition Stmt.h:2918
const Expr * getSubExpr() const
Definition Expr.h:1064
Represents a function declaration or definition.
Definition Decl.h:1999
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2794
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3271
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3703
QualType getReturnType() const
Definition Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2771
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2376
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
Definition Decl.cpp:3414
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2384
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3767
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3191
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4859
Represents a C11 generic selection.
Definition Expr.h:6114
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6398
IfStmt - This represents an if/then/else.
Definition Stmt.h:2259
Stmt * getThen()
Definition Stmt.h:2348
Stmt * getInit()
Definition Stmt.h:2409
bool isNonNegatedConsteval() const
Definition Stmt.h:2444
Expr * getCond()
Definition Stmt.h:2336
bool isNegatedConsteval() const
Definition Stmt.h:2448
Stmt * getElse()
Definition Stmt.h:2357
DeclStmt * getConditionVariableDeclStmt()
If this IfStmt has a condition variable, return the faux DeclStmt associated with the creation of tha...
Definition Stmt.h:2392
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1026
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1733
const Expr * getSubExpr() const
Definition Expr.h:1745
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:5993
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3464
Describes an C or C++ initializer list.
Definition Expr.h:5235
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5337
ArrayRef< Expr * > inits()
Definition Expr.h:5285
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1970
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2096
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1400
Implicit declaration of a temporary that was materialized by a MaterializeTemporaryExpr and lifetime-...
Definition DeclCXX.h:3302
const Stmt * getNamedLoopOrSwitch() const
If this is a named break/continue, get the loop or switch statement that this targets.
Definition Stmt.cpp:1493
A global _GUID constant.
Definition DeclCXX.h:4392
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
Definition DeclCXX.cpp:3745
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4914
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4939
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4931
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:4964
LifetimeExtendedTemporaryDecl * getLifetimeExtendedTemporaryDecl()
Definition ExprCXX.h:4954
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3300
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3383
Expr * getBase() const
Definition Expr.h:3377
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3651
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5457
This represents a decl that may have a name.
Definition Decl.h:273
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
Represents a C++ namespace alias.
Definition DeclCXX.h:3195
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition ExprObjC.h:88
ObjCBoxedExpr - used for generalized expression boxing.
Definition ExprObjC.h:128
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:153
ObjCEncodeExpr, used for @encode in Objective-C.
Definition ExprObjC.h:409
QualType getEncodedType() const
Definition ExprObjC.h:428
SourceLocation getAtLoc() const
Definition ExprObjC.h:423
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:52
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2529
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2588
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2576
unsigned getNumComponents() const
Definition Expr.h:2584
Helper class for OffsetOfExpr.
Definition Expr.h:2423
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2481
@ Array
An index into an array.
Definition Expr.h:2428
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2477
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1180
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1230
Expr * getSelectedExpr() const
Definition ExprCXX.h:4633
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2184
const Expr * getSubExpr() const
Definition Expr.h:2201
Represents a parameter to a function.
Definition Decl.h:1789
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2007
StringLiteral * getFunctionName()
Definition Expr.h:2051
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6692
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6740
ArrayRef< Expr * > semantics()
Definition Expr.h:6764
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8369
QualType withConst() const
Definition TypeBase.h:1159
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8285
bool isConstant(const ASTContext &Ctx) const
Definition TypeBase.h:1097
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8358
Represents a struct/union/class.
Definition Decl.h:4309
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7364
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3571
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
bool isSatisfied() const
Whether or not the requires clause is satisfied.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3160
Expr * getRetValue()
Definition Stmt.h:3187
SourceLocation getLocation() const
Definition Expr.h:2157
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:583
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4579
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4631
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4612
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4618
Represents an expression that computes the length of a parameter pack.
Definition ExprCXX.h:4435
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4509
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition Expr.h:4953
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2277
Represents a C++11 static_assert declaration.
Definition DeclCXX.h:4130
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4531
CompoundStmt * getSubStmt()
Definition Expr.h:4548
Stmt - This represents one statement.
Definition Stmt.h:85
StmtClass getStmtClass() const
Definition Stmt.h:1472
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1801
unsigned getLength() const
Definition Expr.h:1911
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1184
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1884
unsigned getCharByteWidth() const
Definition Expr.h:1912
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4658
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1893
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2509
Expr * getCond()
Definition Stmt.h:2572
Stmt * getBody()
Definition Stmt.h:2584
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1144
Stmt * getInit()
Definition Stmt.h:2589
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2640
DeclStmt * getConditionVariableDeclStmt()
If this SwitchStmt has a condition variable, return the faux DeclStmt associated with the creation of...
Definition Stmt.h:2623
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3714
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3809
bool isUnion() const
Definition Decl.h:3919
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition ExprCXX.h:2890
bool getBoolValue() const
Definition ExprCXX.h:2941
const APValue & getAPValue() const
Definition ExprCXX.h:2946
bool isStoredAsBoolean() const
Definition ExprCXX.h:2937
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isVoidType() const
Definition TypeBase.h:8878
bool isBooleanType() const
Definition TypeBase.h:9008
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:2994
bool isIncompleteArrayType() const
Definition TypeBase.h:8629
bool isNothrowT() const
Definition Type.cpp:3171
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:712
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2426
bool isArrayType() const
Definition TypeBase.h:8621
bool isFunctionPointerType() const
Definition TypeBase.h:8589
bool isPointerType() const
Definition TypeBase.h:8522
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8922
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9168
bool isReferenceType() const
Definition TypeBase.h:8546
bool isEnumeralType() const
Definition TypeBase.h:8653
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:8996
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8847
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
bool isAnyComplexType() const
Definition TypeBase.h:8657
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8934
bool isMemberPointerType() const
Definition TypeBase.h:8603
bool isAtomicType() const
Definition TypeBase.h:8704
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isStdByteType() const
Definition Type.cpp:3190
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9154
bool isPointerOrReferenceType() const
Definition TypeBase.h:8526
bool isVectorType() const
Definition TypeBase.h:8661
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
bool isFloatingType() const
Definition Type.cpp:2304
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9101
bool isRecordType() const
Definition TypeBase.h:8649
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2570
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3559
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2627
QualType getArgumentType() const
Definition Expr.h:2670
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2696
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2659
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2246
Expr * getSubExpr() const
Definition Expr.h:2287
Opcode getOpcode() const
Definition Expr.h:2282
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2300
Represents C++ using-directive.
Definition DeclCXX.h:3090
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
QualType getType() const
Definition Decl.h:722
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5449
QualType getType() const
Definition Value.cpp:237
Represents a variable declaration or definition.
Definition Decl.h:925
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1577
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2575
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1282
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1225
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2648
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1207
const Expr * getInit() const
Definition Decl.h:1367
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1252
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1357
Represents a GCC generic vector type.
Definition TypeBase.h:4173
unsigned getNumElements() const
Definition TypeBase.h:4188
QualType getElementType() const
Definition TypeBase.h:4187
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2697
Expr * getCond()
Definition Stmt.h:2749
DeclStmt * getConditionVariableDeclStmt()
If this WhileStmt has a condition variable, return the faux DeclStmt associated with the creation of ...
Definition Stmt.h:2785
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1205
Stmt * getBody()
Definition Stmt.h:2761
Scope for storage declared in a compound statement.
Definition Compiler.h:627
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:44
void invokeDtor()
Invokes the Destructor.
std::byte * rawData()
Returns a pointer to the raw data, including metadata.
Compilation context for expressions.
Definition Compiler.h:110
llvm::SmallVector< InitLink > InitStack
Definition Compiler.h:452
VarCreationState visitVarDecl(const VarDecl *VD, bool Toplevel=false, bool IsConstexprUnknown=false)
Creates and initializes a variable from the given decl.
bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E)
bool VisitCXXDeleteExpr(const CXXDeleteExpr *E)
bool VisitOffsetOfExpr(const OffsetOfExpr *E)
bool visitContinueStmt(const ContinueStmt *S)
bool VisitCharacterLiteral(const CharacterLiteral *E)
bool visitArrayElemInit(unsigned ElemIndex, const Expr *Init, OptPrimType InitT)
Pointer to the array(not the element!) must be on the stack when calling this.
bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E)
bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E)
bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
bool visitBool(const Expr *E)
Visits an expression and converts it to a boolean.
bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
bool visitDeclAndReturn(const VarDecl *VD, bool ConstantContext) override
Toplevel visitDeclAndReturn().
PrimType classifyPrim(QualType Ty) const
Classifies a known primitive type.
Definition Compiler.h:277
bool VisitTypeTraitExpr(const TypeTraitExpr *E)
bool VisitLambdaExpr(const LambdaExpr *E)
bool VisitMemberExpr(const MemberExpr *E)
llvm::DenseMap< const OpaqueValueExpr *, unsigned > OpaqueExprs
OpaqueValueExpr to location mapping.
Definition Compiler.h:430
bool VisitBinaryOperator(const BinaryOperator *E)
Definition Compiler.cpp:840
bool visitAttributedStmt(const AttributedStmt *S)
bool VisitPackIndexingExpr(const PackIndexingExpr *E)
VarCreationState visitDecl(const VarDecl *VD, bool IsConstexprUnknown=false)
bool visitAPValueInitializer(const APValue &Val, const Expr *E, QualType T)
bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
bool VisitCallExpr(const CallExpr *E)
std::optional< uint64_t > ArrayIndex
Current argument index. Needed to emit ArrayInitIndexExpr.
Definition Compiler.h:436
bool VisitPseudoObjectExpr(const PseudoObjectExpr *E)
bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E)
const Function * getFunction(const FunctionDecl *FD)
Returns a function for the given FunctionDecl.
void emitCleanup()
Emits scope cleanup instructions.
bool VisitFixedPointBinOp(const BinaryOperator *E)
bool VisitCastExpr(const CastExpr *E)
Definition Compiler.cpp:212
bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E)
bool VisitFixedPointUnaryOperator(const UnaryOperator *E)
bool VisitComplexUnaryOperator(const UnaryOperator *E)
llvm::DenseMap< const SwitchCase *, LabelTy > CaseMap
Definition Compiler.h:116
bool VisitBlockExpr(const BlockExpr *E)
bool visitAPValue(const APValue &Val, PrimType ValType, const Expr *E)
Visit an APValue.
bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E)
bool VisitLogicalBinOp(const BinaryOperator *E)
bool visitCompoundStmt(const CompoundStmt *S)
Context & Ctx
Current compilation context.
Definition Compiler.h:133
bool visitDeclRef(const ValueDecl *D, const Expr *E)
Visit the given decl as if we have a reference to it.
bool visitBreakStmt(const BreakStmt *S)
bool visitExpr(const Expr *E, bool DestroyToplevelScope) override
bool visitForStmt(const ForStmt *S)
bool VisitDeclRefExpr(const DeclRefExpr *E)
bool VisitOpaqueValueExpr(const OpaqueValueExpr *E)
bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E)
bool VisitStmtExpr(const StmtExpr *E)
bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E)
Definition Compiler.cpp:776
bool VisitFixedPointLiteral(const FixedPointLiteral *E)
Definition Compiler.cpp:822
const FunctionDecl * CompilingFunction
Definition Compiler.h:463
bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E)
VariableScope< Emitter > * VarScope
Current scope.
Definition Compiler.h:433
bool VisitCXXNewExpr(const CXXNewExpr *E)
const ValueDecl * InitializingDecl
Definition Compiler.h:450
bool VisitCompoundAssignOperator(const CompoundAssignOperator *E)
bool visit(const Expr *E) override
Evaluates an expression and places the result on the stack.
bool delegate(const Expr *E)
Just pass evaluation on to E.
bool discard(const Expr *E)
Evaluates an expression for side effects and discards the result.
bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
CaseMap CaseLabels
Switch case mapping.
Definition Compiler.h:459
Record * getRecord(QualType Ty)
Returns a record from a record or pointer type.
const RecordType * getRecordTy(QualType Ty)
Returns a record type from a record or pointer type.
bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E)
bool visitInitList(ArrayRef< const Expr * > Inits, const Expr *ArrayFiller, const Expr *E)
bool VisitSizeOfPackExpr(const SizeOfPackExpr *E)
bool VisitPredefinedExpr(const PredefinedExpr *E)
bool VisitSourceLocExpr(const SourceLocExpr *E)
bool visitDeclStmt(const DeclStmt *DS, bool EvaluateConditionDecl=false)
bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E)
bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E)
bool visitInitializer(const Expr *E)
Compiles an initializer.
const Expr * SourceLocDefaultExpr
DefaultInit- or DefaultArgExpr, needed for SourceLocExpr.
Definition Compiler.h:439
UnsignedOrNone OptLabelTy
Definition Compiler.h:115
bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E)
bool VisitPointerArithBinOp(const BinaryOperator *E)
Perform addition/subtraction of a pointer and an integer or subtraction of two pointers.
bool visitCallArgs(ArrayRef< const Expr * > Args, const FunctionDecl *FuncDecl, bool Activate, bool IsOperatorCall)
bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E)
bool visitDefaultStmt(const DefaultStmt *S)
typename Emitter::LabelTy LabelTy
Definition Compiler.h:113
bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E)
bool visitStmt(const Stmt *S)
bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E)
bool VisitVectorUnaryOperator(const UnaryOperator *E)
bool VisitCXXConstructExpr(const CXXConstructExpr *E)
bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
unsigned allocateLocalPrimitive(DeclTy &&Decl, PrimType Ty, bool IsConst, const ValueDecl *ExtendingDecl=nullptr, ScopeKind SC=ScopeKind::Block, bool IsConstexprUnknown=false)
Creates a local primitive value.
bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E)
bool VisitRecoveryExpr(const RecoveryExpr *E)
bool VisitRequiresExpr(const RequiresExpr *E)
bool Initializing
Flag inidicating if we're initializing an already created variable.
Definition Compiler.h:449
bool visitReturnStmt(const ReturnStmt *RS)
bool VisitCXXThrowExpr(const CXXThrowExpr *E)
bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
bool VisitChooseExpr(const ChooseExpr *E)
bool visitFunc(const FunctionDecl *F) override
bool visitCXXForRangeStmt(const CXXForRangeStmt *S)
bool visitCaseStmt(const CaseStmt *S)
bool VisitComplexBinOp(const BinaryOperator *E)
llvm::DenseMap< const ValueDecl *, Scope::Local > Locals
Variable to storage mapping.
Definition Compiler.h:427
bool VisitAbstractConditionalOperator(const AbstractConditionalOperator *E)
bool VisitCXXTypeidExpr(const CXXTypeidExpr *E)
UnsignedOrNone allocateTemporary(const Expr *E)
bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinID)
bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E)
OptPrimType ReturnType
Type of the expression returned by the function.
Definition Compiler.h:456
bool VisitUnaryOperator(const UnaryOperator *E)
bool VisitFloatCompoundAssignOperator(const CompoundAssignOperator *E)
OptPrimType classify(const Expr *E) const
Definition Compiler.h:271
llvm::SmallVector< LabelInfo > LabelInfoStack
Stack of label information for loops and switch statements.
Definition Compiler.h:461
bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
bool visitDoStmt(const DoStmt *S)
bool VisitIntegerLiteral(const IntegerLiteral *E)
Definition Compiler.cpp:781
bool VisitInitListExpr(const InitListExpr *E)
UnsignedOrNone allocateLocal(DeclTy &&Decl, QualType Ty=QualType(), const ValueDecl *ExtendingDecl=nullptr, ScopeKind=ScopeKind::Block, bool IsConstexprUnknown=false)
Allocates a space storing a local given its type.
bool VisitVectorBinOp(const BinaryOperator *E)
bool VisitStringLiteral(const StringLiteral *E)
bool VisitParenExpr(const ParenExpr *E)
Definition Compiler.cpp:835
bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E)
bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E)
bool VisitPointerCompoundAssignOperator(const CompoundAssignOperator *E)
bool DiscardResult
Flag indicating if return value is to be discarded.
Definition Compiler.h:442
bool VisitEmbedExpr(const EmbedExpr *E)
bool VisitConvertVectorExpr(const ConvertVectorExpr *E)
bool VisitCXXThisExpr(const CXXThisExpr *E)
bool VisitConstantExpr(const ConstantExpr *E)
bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
bool visitSwitchStmt(const SwitchStmt *S)
bool VisitCXXUuidofExpr(const CXXUuidofExpr *E)
bool VisitExprWithCleanups(const ExprWithCleanups *E)
bool visitAsLValue(const Expr *E)
bool visitWhileStmt(const WhileStmt *S)
bool visitIfStmt(const IfStmt *IS)
bool VisitAddrLabelExpr(const AddrLabelExpr *E)
bool canClassify(const Expr *E) const
Definition Compiler.h:273
bool VisitFloatingLiteral(const FloatingLiteral *E)
Definition Compiler.cpp:789
Program & P
Program to link to.
Definition Compiler.h:135
bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E)
bool VisitGNUNullExpr(const GNUNullExpr *E)
bool VisitImaginaryLiteral(const ImaginaryLiteral *E)
Definition Compiler.cpp:798
bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E)
bool visitCXXTryStmt(const CXXTryStmt *S)
static bool isUnevaluatedBuiltin(unsigned ID)
Unevaluated builtins don't get their arguments put on the stack automatically.
Definition Context.cpp:628
static bool shouldBeGloballyIndexed(const ValueDecl *VD)
Returns whether we should create a global variable for the given ValueDecl.
Definition Context.h:125
Scope used to handle temporaries in toplevel variable declarations.
Definition Compiler.cpp:39
DeclScope(Compiler< Emitter > *Ctx, const ValueDecl *VD)
Definition Compiler.cpp:41
Wrapper around fixed point types.
Definition FixedPoint.h:23
static FixedPoint zero(llvm::FixedPointSemantics Sem)
Definition FixedPoint.h:36
If a Floating is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition Floating.h:35
bool singleWord() const
Definition Floating.h:106
Bytecode function.
Definition Function.h:86
bool hasThisPointer() const
Definition Function.h:193
bool hasRVO() const
Checks if the first argument is a RVO pointer.
Definition Function.h:129
When generating code for e.g.
Definition Compiler.cpp:187
LocOverrideScope(Compiler< Emitter > *Ctx, SourceInfo NewValue, bool Enabled=true)
Definition Compiler.cpp:189
Generic scope for local variables.
Definition Compiler.h:538
bool destroyLocals(const Expr *E=nullptr) override
Explicit destruction of local variables.
Definition Compiler.h:563
LocalScope(Compiler< Emitter > *Ctx, ScopeKind Kind=ScopeKind::Block)
Definition Compiler.h:540
Sets the context for break/continue statements.
Definition Compiler.cpp:113
typename Compiler< Emitter >::LabelTy LabelTy
Definition Compiler.cpp:115
typename Compiler< Emitter >::OptLabelTy OptLabelTy
Definition Compiler.cpp:116
typename Compiler< Emitter >::LabelInfo LabelInfo
Definition Compiler.cpp:117
LoopScope(Compiler< Emitter > *Ctx, const Stmt *Name, LabelTy BreakLabel, LabelTy ContinueLabel)
Definition Compiler.cpp:119
PrimType value_or(PrimType PT) const
Definition PrimType.h:68
Scope used to handle initialization methods.
Definition Compiler.cpp:59
OptionScope(Compiler< Emitter > *Ctx, bool NewDiscardResult, bool NewInitializing, bool NewToLValue)
Root constructor, compiling or discarding primitives.
Definition Compiler.cpp:62
Context to manage declaration lifetimes.
Definition Program.h:145
Structure/Class descriptor.
Definition Record.h:25
bool isUnion() const
Checks if the record is a union.
Definition Record.h:57
const CXXDestructorDecl * getDestructor() const
Returns the destructor of the record, if any.
Definition Record.h:73
const Field * getField(const FieldDecl *FD) const
Returns a field.
Definition Record.cpp:47
bool hasTrivialDtor() const
Returns true for anonymous unions and records with no destructor or for those with a trivial destruct...
Definition Record.cpp:40
llvm::iterator_range< const_base_iter > bases() const
Definition Record.h:92
const Base * getVirtualBase(const RecordDecl *RD) const
Returns a virtual base descriptor.
Definition Record.cpp:65
unsigned getNumFields() const
Definition Record.h:88
llvm::iterator_range< const_field_iter > fields() const
Definition Record.h:84
const Base * getBase(const RecordDecl *FD) const
Returns a base descriptor.
Definition Record.cpp:53
Describes a scope block.
Definition Function.h:36
Describes the statement/declaration an opcode was generated from.
Definition Source.h:73
StmtExprScope(Compiler< Emitter > *Ctx)
Definition Compiler.cpp:172
typename Compiler< Emitter >::LabelTy LabelTy
Definition Compiler.cpp:141
typename Compiler< Emitter >::OptLabelTy OptLabelTy
Definition Compiler.cpp:142
typename Compiler< Emitter >::LabelInfo LabelInfo
Definition Compiler.cpp:144
typename Compiler< Emitter >::CaseMap CaseMap
Definition Compiler.cpp:143
SwitchScope(Compiler< Emitter > *Ctx, const Stmt *Name, CaseMap &&CaseLabels, LabelTy BreakLabel, OptLabelTy DefaultLabel)
Definition Compiler.cpp:146
Scope chain managing the variable lifetimes.
Definition Compiler.h:470
Compiler< Emitter > * Ctx
Compiler instance.
Definition Compiler.h:530
virtual void addLocal(const Scope::Local &Local)
Definition Compiler.h:480
VariableScope * getParent() const
Definition Compiler.h:525
bool Sub(InterpState &S, CodePtr OpPC)
Definition Interp.h:425
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1267
static llvm::RoundingMode getRoundingMode(FPOptions FPO)
Definition Interp.h:406
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
Definition Descriptor.h:29
constexpr bool isSignedType(PrimType T)
Definition PrimType.h:89
bool Div(InterpState &S, CodePtr OpPC)
1) Pops the RHS from the stack.
Definition Interp.h:692
static bool Activate(InterpState &S, CodePtr OpPC)
Definition Interp.h:1984
constexpr bool isPtrType(PrimType T)
Definition PrimType.h:85
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:185
bool InitScope(InterpState &S, CodePtr OpPC, uint32_t I)
Definition Interp.h:2472
llvm::APFloat APFloat
Definition Floating.h:27
static void discard(InterpStack &Stk, PrimType T)
llvm::APInt APInt
Definition FixedPoint.h:19
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1274
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
static std::optional< bool > getBoolValue(const Expr *E)
Definition Compiler.cpp:28
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2098
bool Mul(InterpState &S, CodePtr OpPC)
Definition Interp.h:445
size_t primSize(PrimType Type)
Returns the size of a primitive type in bytes.
Definition PrimType.cpp:23
bool Inc(InterpState &S, CodePtr OpPC, bool CanOverflow)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition Interp.h:865
bool Add(InterpState &S, CodePtr OpPC)
Definition Interp.h:398
llvm::BitVector collectNonNullArgs(const FunctionDecl *F, ArrayRef< const Expr * > Args)
constexpr bool isIntegralType(PrimType T)
Definition PrimType.h:124
llvm::APSInt APSInt
Definition FixedPoint.h:20
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Success
Annotation was successful.
Definition Parser.h:65
Expr * Cond
};
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
@ SD_Static
Static storage duration.
Definition Specifiers.h:343
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327
#define true
Definition stdbool.h:25
A quantity in bits.
Describes a memory block created by an allocation site.
Definition Descriptor.h:122
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 hasTrivialDtor() const
Whether variables of this descriptor need their destructor called or not.
bool isCompositeArray() const
Checks if the descriptor is of an array of composites.
Definition Descriptor.h:256
QualType getType() const
const Descriptor *const ElemDesc
Descriptor of the array element.
Definition Descriptor.h:155
static constexpr MetadataSize InlineDescMD
Definition Descriptor.h:144
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:254
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:153
bool isArray() const
Checks if the descriptor is of an array.
Definition Descriptor.h:266
Descriptor used for global variables.
Definition Descriptor.h:51
const FieldDecl * Decl
Definition Record.h:29
bool isUnnamedBitField() const
Definition Record.h:33
Information about a local's storage.
Definition Function.h:39
State encapsulating if a the variable creation has been successful, unsuccessful, or no variable has ...
Definition Compiler.h:95
static VarCreationState NotCreated()
Definition Compiler.h:99