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