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