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