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