xref: /llvm-project/clang/lib/AST/ByteCode/Compiler.cpp (revision c79d1fa540390f6e37e1ea326153559eeadd0de6)
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 "Floating.h"
13 #include "Function.h"
14 #include "InterpShared.h"
15 #include "PrimType.h"
16 #include "Program.h"
17 #include "clang/AST/Attr.h"
18 
19 using namespace clang;
20 using namespace clang::interp;
21 
22 using APSInt = llvm::APSInt;
23 
24 namespace clang {
25 namespace interp {
26 
27 /// Scope used to handle temporaries in toplevel variable declarations.
28 template <class Emitter> class DeclScope final : public LocalScope<Emitter> {
29 public:
30   DeclScope(Compiler<Emitter> *Ctx, const ValueDecl *VD)
31       : LocalScope<Emitter>(Ctx, VD), Scope(Ctx->P, VD),
32         OldInitializingDecl(Ctx->InitializingDecl) {
33     Ctx->InitializingDecl = VD;
34     Ctx->InitStack.push_back(InitLink::Decl(VD));
35   }
36 
37   void addExtended(const Scope::Local &Local) override {
38     return this->addLocal(Local);
39   }
40 
41   ~DeclScope() {
42     this->Ctx->InitializingDecl = OldInitializingDecl;
43     this->Ctx->InitStack.pop_back();
44   }
45 
46 private:
47   Program::DeclScope Scope;
48   const ValueDecl *OldInitializingDecl;
49 };
50 
51 /// Scope used to handle initialization methods.
52 template <class Emitter> class OptionScope final {
53 public:
54   /// Root constructor, compiling or discarding primitives.
55   OptionScope(Compiler<Emitter> *Ctx, bool NewDiscardResult,
56               bool NewInitializing)
57       : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult),
58         OldInitializing(Ctx->Initializing) {
59     Ctx->DiscardResult = NewDiscardResult;
60     Ctx->Initializing = NewInitializing;
61   }
62 
63   ~OptionScope() {
64     Ctx->DiscardResult = OldDiscardResult;
65     Ctx->Initializing = OldInitializing;
66   }
67 
68 private:
69   /// Parent context.
70   Compiler<Emitter> *Ctx;
71   /// Old discard flag to restore.
72   bool OldDiscardResult;
73   bool OldInitializing;
74 };
75 
76 template <class Emitter>
77 bool InitLink::emit(Compiler<Emitter> *Ctx, const Expr *E) const {
78   switch (Kind) {
79   case K_This:
80     return Ctx->emitThis(E);
81   case K_Field:
82     // We're assuming there's a base pointer on the stack already.
83     return Ctx->emitGetPtrFieldPop(Offset, E);
84   case K_Temp:
85     return Ctx->emitGetPtrLocal(Offset, E);
86   case K_Decl:
87     return Ctx->visitDeclRef(D, E);
88   case K_Elem:
89     if (!Ctx->emitConstUint32(Offset, E))
90       return false;
91     return Ctx->emitArrayElemPtrPopUint32(E);
92   default:
93     llvm_unreachable("Unhandled InitLink kind");
94   }
95   return true;
96 }
97 
98 /// Scope managing label targets.
99 template <class Emitter> class LabelScope {
100 public:
101   virtual ~LabelScope() {}
102 
103 protected:
104   LabelScope(Compiler<Emitter> *Ctx) : Ctx(Ctx) {}
105   /// Compiler instance.
106   Compiler<Emitter> *Ctx;
107 };
108 
109 /// Sets the context for break/continue statements.
110 template <class Emitter> class LoopScope final : public LabelScope<Emitter> {
111 public:
112   using LabelTy = typename Compiler<Emitter>::LabelTy;
113   using OptLabelTy = typename Compiler<Emitter>::OptLabelTy;
114 
115   LoopScope(Compiler<Emitter> *Ctx, LabelTy BreakLabel, LabelTy ContinueLabel)
116       : LabelScope<Emitter>(Ctx), OldBreakLabel(Ctx->BreakLabel),
117         OldContinueLabel(Ctx->ContinueLabel) {
118     this->Ctx->BreakLabel = BreakLabel;
119     this->Ctx->ContinueLabel = ContinueLabel;
120   }
121 
122   ~LoopScope() {
123     this->Ctx->BreakLabel = OldBreakLabel;
124     this->Ctx->ContinueLabel = OldContinueLabel;
125   }
126 
127 private:
128   OptLabelTy OldBreakLabel;
129   OptLabelTy OldContinueLabel;
130 };
131 
132 // Sets the context for a switch scope, mapping labels.
133 template <class Emitter> class SwitchScope final : public LabelScope<Emitter> {
134 public:
135   using LabelTy = typename Compiler<Emitter>::LabelTy;
136   using OptLabelTy = typename Compiler<Emitter>::OptLabelTy;
137   using CaseMap = typename Compiler<Emitter>::CaseMap;
138 
139   SwitchScope(Compiler<Emitter> *Ctx, CaseMap &&CaseLabels, LabelTy BreakLabel,
140               OptLabelTy DefaultLabel)
141       : LabelScope<Emitter>(Ctx), OldBreakLabel(Ctx->BreakLabel),
142         OldDefaultLabel(this->Ctx->DefaultLabel),
143         OldCaseLabels(std::move(this->Ctx->CaseLabels)) {
144     this->Ctx->BreakLabel = BreakLabel;
145     this->Ctx->DefaultLabel = DefaultLabel;
146     this->Ctx->CaseLabels = std::move(CaseLabels);
147   }
148 
149   ~SwitchScope() {
150     this->Ctx->BreakLabel = OldBreakLabel;
151     this->Ctx->DefaultLabel = OldDefaultLabel;
152     this->Ctx->CaseLabels = std::move(OldCaseLabels);
153   }
154 
155 private:
156   OptLabelTy OldBreakLabel;
157   OptLabelTy OldDefaultLabel;
158   CaseMap OldCaseLabels;
159 };
160 
161 template <class Emitter> class StmtExprScope final {
162 public:
163   StmtExprScope(Compiler<Emitter> *Ctx) : Ctx(Ctx), OldFlag(Ctx->InStmtExpr) {
164     Ctx->InStmtExpr = true;
165   }
166 
167   ~StmtExprScope() { Ctx->InStmtExpr = OldFlag; }
168 
169 private:
170   Compiler<Emitter> *Ctx;
171   bool OldFlag;
172 };
173 
174 } // namespace interp
175 } // namespace clang
176 
177 template <class Emitter>
178 bool Compiler<Emitter>::VisitCastExpr(const CastExpr *CE) {
179   const Expr *SubExpr = CE->getSubExpr();
180   switch (CE->getCastKind()) {
181 
182   case CK_LValueToRValue: {
183     if (DiscardResult)
184       return this->discard(SubExpr);
185 
186     std::optional<PrimType> SubExprT = classify(SubExpr->getType());
187     // Prepare storage for the result.
188     if (!Initializing && !SubExprT) {
189       std::optional<unsigned> LocalIndex = allocateLocal(SubExpr);
190       if (!LocalIndex)
191         return false;
192       if (!this->emitGetPtrLocal(*LocalIndex, CE))
193         return false;
194     }
195 
196     if (!this->visit(SubExpr))
197       return false;
198 
199     if (SubExprT)
200       return this->emitLoadPop(*SubExprT, CE);
201 
202     // If the subexpr type is not primitive, we need to perform a copy here.
203     // This happens for example in C when dereferencing a pointer of struct
204     // type.
205     return this->emitMemcpy(CE);
206   }
207 
208   case CK_DerivedToBaseMemberPointer: {
209     assert(classifyPrim(CE->getType()) == PT_MemberPtr);
210     assert(classifyPrim(SubExpr->getType()) == PT_MemberPtr);
211     const auto *FromMP = SubExpr->getType()->getAs<MemberPointerType>();
212     const auto *ToMP = CE->getType()->getAs<MemberPointerType>();
213 
214     unsigned DerivedOffset = collectBaseOffset(QualType(ToMP->getClass(), 0),
215                                                QualType(FromMP->getClass(), 0));
216 
217     if (!this->delegate(SubExpr))
218       return false;
219 
220     return this->emitGetMemberPtrBasePop(DerivedOffset, CE);
221   }
222 
223   case CK_BaseToDerivedMemberPointer: {
224     assert(classifyPrim(CE) == PT_MemberPtr);
225     assert(classifyPrim(SubExpr) == PT_MemberPtr);
226     const auto *FromMP = SubExpr->getType()->getAs<MemberPointerType>();
227     const auto *ToMP = CE->getType()->getAs<MemberPointerType>();
228 
229     unsigned DerivedOffset = collectBaseOffset(QualType(FromMP->getClass(), 0),
230                                                QualType(ToMP->getClass(), 0));
231 
232     if (!this->delegate(SubExpr))
233       return false;
234     return this->emitGetMemberPtrBasePop(-DerivedOffset, CE);
235   }
236 
237   case CK_UncheckedDerivedToBase:
238   case CK_DerivedToBase: {
239     if (!this->delegate(SubExpr))
240       return false;
241 
242     const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
243       if (const auto *PT = dyn_cast<PointerType>(Ty))
244         return PT->getPointeeType()->getAsCXXRecordDecl();
245       return Ty->getAsCXXRecordDecl();
246     };
247 
248     // FIXME: We can express a series of non-virtual casts as a single
249     // GetPtrBasePop op.
250     QualType CurType = SubExpr->getType();
251     for (const CXXBaseSpecifier *B : CE->path()) {
252       if (B->isVirtual()) {
253         if (!this->emitGetPtrVirtBasePop(extractRecordDecl(B->getType()), CE))
254           return false;
255         CurType = B->getType();
256       } else {
257         unsigned DerivedOffset = collectBaseOffset(B->getType(), CurType);
258         if (!this->emitGetPtrBasePop(DerivedOffset, CE))
259           return false;
260         CurType = B->getType();
261       }
262     }
263 
264     return true;
265   }
266 
267   case CK_BaseToDerived: {
268     if (!this->delegate(SubExpr))
269       return false;
270 
271     unsigned DerivedOffset =
272         collectBaseOffset(SubExpr->getType(), CE->getType());
273 
274     return this->emitGetPtrDerivedPop(DerivedOffset, CE);
275   }
276 
277   case CK_FloatingCast: {
278     // HLSL uses CK_FloatingCast to cast between vectors.
279     if (!SubExpr->getType()->isFloatingType() ||
280         !CE->getType()->isFloatingType())
281       return false;
282     if (DiscardResult)
283       return this->discard(SubExpr);
284     if (!this->visit(SubExpr))
285       return false;
286     const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
287     return this->emitCastFP(TargetSemantics, getRoundingMode(CE), CE);
288   }
289 
290   case CK_IntegralToFloating: {
291     if (DiscardResult)
292       return this->discard(SubExpr);
293     std::optional<PrimType> FromT = classify(SubExpr->getType());
294     if (!FromT)
295       return false;
296 
297     if (!this->visit(SubExpr))
298       return false;
299 
300     const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
301     llvm::RoundingMode RM = getRoundingMode(CE);
302     return this->emitCastIntegralFloating(*FromT, TargetSemantics, RM, CE);
303   }
304 
305   case CK_FloatingToBoolean:
306   case CK_FloatingToIntegral: {
307     if (DiscardResult)
308       return this->discard(SubExpr);
309 
310     std::optional<PrimType> ToT = classify(CE->getType());
311 
312     if (!ToT)
313       return false;
314 
315     if (!this->visit(SubExpr))
316       return false;
317 
318     if (ToT == PT_IntAP)
319       return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(CE->getType()),
320                                               CE);
321     if (ToT == PT_IntAPS)
322       return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(CE->getType()),
323                                                CE);
324 
325     return this->emitCastFloatingIntegral(*ToT, CE);
326   }
327 
328   case CK_NullToPointer:
329   case CK_NullToMemberPointer: {
330     if (!this->discard(SubExpr))
331       return false;
332     if (DiscardResult)
333       return true;
334 
335     const Descriptor *Desc = nullptr;
336     const QualType PointeeType = CE->getType()->getPointeeType();
337     if (!PointeeType.isNull()) {
338       if (std::optional<PrimType> T = classify(PointeeType))
339         Desc = P.createDescriptor(SubExpr, *T);
340       else
341         Desc = P.createDescriptor(SubExpr, PointeeType.getTypePtr(),
342                                   std::nullopt, true, false,
343                                   /*IsMutable=*/false, nullptr);
344     }
345     return this->emitNull(classifyPrim(CE->getType()), Desc, CE);
346   }
347 
348   case CK_PointerToIntegral: {
349     if (DiscardResult)
350       return this->discard(SubExpr);
351 
352     if (!this->visit(SubExpr))
353       return false;
354 
355     // If SubExpr doesn't result in a pointer, make it one.
356     if (PrimType FromT = classifyPrim(SubExpr->getType()); FromT != PT_Ptr) {
357       assert(isPtrType(FromT));
358       if (!this->emitDecayPtr(FromT, PT_Ptr, CE))
359         return false;
360     }
361 
362     PrimType T = classifyPrim(CE->getType());
363     if (T == PT_IntAP)
364       return this->emitCastPointerIntegralAP(Ctx.getBitWidth(CE->getType()),
365                                              CE);
366     if (T == PT_IntAPS)
367       return this->emitCastPointerIntegralAPS(Ctx.getBitWidth(CE->getType()),
368                                               CE);
369     return this->emitCastPointerIntegral(T, CE);
370   }
371 
372   case CK_ArrayToPointerDecay: {
373     if (!this->visit(SubExpr))
374       return false;
375     if (!this->emitArrayDecay(CE))
376       return false;
377     if (DiscardResult)
378       return this->emitPopPtr(CE);
379     return true;
380   }
381 
382   case CK_IntegralToPointer: {
383     QualType IntType = SubExpr->getType();
384     assert(IntType->isIntegralOrEnumerationType());
385     if (!this->visit(SubExpr))
386       return false;
387     // FIXME: I think the discard is wrong since the int->ptr cast might cause a
388     // diagnostic.
389     PrimType T = classifyPrim(IntType);
390     if (DiscardResult)
391       return this->emitPop(T, CE);
392 
393     QualType PtrType = CE->getType();
394     const Descriptor *Desc;
395     if (std::optional<PrimType> T = classify(PtrType->getPointeeType()))
396       Desc = P.createDescriptor(SubExpr, *T);
397     else if (PtrType->getPointeeType()->isVoidType())
398       Desc = nullptr;
399     else
400       Desc = P.createDescriptor(CE, PtrType->getPointeeType().getTypePtr(),
401                                 Descriptor::InlineDescMD, true, false,
402                                 /*IsMutable=*/false, nullptr);
403 
404     if (!this->emitGetIntPtr(T, Desc, CE))
405       return false;
406 
407     PrimType DestPtrT = classifyPrim(PtrType);
408     if (DestPtrT == PT_Ptr)
409       return true;
410 
411     // In case we're converting the integer to a non-Pointer.
412     return this->emitDecayPtr(PT_Ptr, DestPtrT, CE);
413   }
414 
415   case CK_AtomicToNonAtomic:
416   case CK_ConstructorConversion:
417   case CK_FunctionToPointerDecay:
418   case CK_NonAtomicToAtomic:
419   case CK_NoOp:
420   case CK_UserDefinedConversion:
421   case CK_AddressSpaceConversion:
422     return this->delegate(SubExpr);
423 
424   case CK_BitCast: {
425     // Reject bitcasts to atomic types.
426     if (CE->getType()->isAtomicType()) {
427       if (!this->discard(SubExpr))
428         return false;
429       return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, CE);
430     }
431 
432     if (DiscardResult)
433       return this->discard(SubExpr);
434 
435     QualType SubExprTy = SubExpr->getType();
436     std::optional<PrimType> FromT = classify(SubExprTy);
437     std::optional<PrimType> ToT = classify(CE->getType());
438     if (!FromT || !ToT)
439       return false;
440 
441     assert(isPtrType(*FromT));
442     assert(isPtrType(*ToT));
443     if (FromT == ToT) {
444       if (CE->getType()->isVoidPointerType())
445         return this->delegate(SubExpr);
446 
447       if (!this->visit(SubExpr))
448         return false;
449       if (FromT == PT_Ptr)
450         return this->emitPtrPtrCast(SubExprTy->isVoidPointerType(), CE);
451       return true;
452     }
453 
454     if (!this->visit(SubExpr))
455       return false;
456     return this->emitDecayPtr(*FromT, *ToT, CE);
457   }
458 
459   case CK_IntegralToBoolean:
460   case CK_BooleanToSignedIntegral:
461   case CK_IntegralCast: {
462     if (DiscardResult)
463       return this->discard(SubExpr);
464     std::optional<PrimType> FromT = classify(SubExpr->getType());
465     std::optional<PrimType> ToT = classify(CE->getType());
466 
467     if (!FromT || !ToT)
468       return false;
469 
470     if (!this->visit(SubExpr))
471       return false;
472 
473     // Possibly diagnose casts to enum types if the target type does not
474     // have a fixed size.
475     if (Ctx.getLangOpts().CPlusPlus && CE->getType()->isEnumeralType()) {
476       if (const auto *ET = CE->getType().getCanonicalType()->getAs<EnumType>();
477           ET && !ET->getDecl()->isFixed()) {
478         if (!this->emitCheckEnumValue(*FromT, ET->getDecl(), CE))
479           return false;
480       }
481     }
482 
483     auto maybeNegate = [&]() -> bool {
484       if (CE->getCastKind() == CK_BooleanToSignedIntegral)
485         return this->emitNeg(*ToT, CE);
486       return true;
487     };
488 
489     if (ToT == PT_IntAP)
490       return this->emitCastAP(*FromT, Ctx.getBitWidth(CE->getType()), CE) &&
491              maybeNegate();
492     if (ToT == PT_IntAPS)
493       return this->emitCastAPS(*FromT, Ctx.getBitWidth(CE->getType()), CE) &&
494              maybeNegate();
495 
496     if (FromT == ToT)
497       return true;
498     if (!this->emitCast(*FromT, *ToT, CE))
499       return false;
500 
501     return maybeNegate();
502   }
503 
504   case CK_PointerToBoolean:
505   case CK_MemberPointerToBoolean: {
506     PrimType PtrT = classifyPrim(SubExpr->getType());
507 
508     // Just emit p != nullptr for this.
509     if (!this->visit(SubExpr))
510       return false;
511 
512     if (!this->emitNull(PtrT, nullptr, CE))
513       return false;
514 
515     return this->emitNE(PtrT, CE);
516   }
517 
518   case CK_IntegralComplexToBoolean:
519   case CK_FloatingComplexToBoolean: {
520     if (DiscardResult)
521       return this->discard(SubExpr);
522     if (!this->visit(SubExpr))
523       return false;
524     return this->emitComplexBoolCast(SubExpr);
525   }
526 
527   case CK_IntegralComplexToReal:
528   case CK_FloatingComplexToReal:
529     return this->emitComplexReal(SubExpr);
530 
531   case CK_IntegralRealToComplex:
532   case CK_FloatingRealToComplex: {
533     // We're creating a complex value here, so we need to
534     // allocate storage for it.
535     if (!Initializing) {
536       unsigned LocalIndex = allocateTemporary(CE);
537       if (!this->emitGetPtrLocal(LocalIndex, CE))
538         return false;
539     }
540 
541     // Init the complex value to {SubExpr, 0}.
542     if (!this->visitArrayElemInit(0, SubExpr))
543       return false;
544     // Zero-init the second element.
545     PrimType T = classifyPrim(SubExpr->getType());
546     if (!this->visitZeroInitializer(T, SubExpr->getType(), SubExpr))
547       return false;
548     return this->emitInitElem(T, 1, SubExpr);
549   }
550 
551   case CK_IntegralComplexCast:
552   case CK_FloatingComplexCast:
553   case CK_IntegralComplexToFloatingComplex:
554   case CK_FloatingComplexToIntegralComplex: {
555     assert(CE->getType()->isAnyComplexType());
556     assert(SubExpr->getType()->isAnyComplexType());
557     if (DiscardResult)
558       return this->discard(SubExpr);
559 
560     if (!Initializing) {
561       std::optional<unsigned> LocalIndex = allocateLocal(CE);
562       if (!LocalIndex)
563         return false;
564       if (!this->emitGetPtrLocal(*LocalIndex, CE))
565         return false;
566     }
567 
568     // Location for the SubExpr.
569     // Since SubExpr is of complex type, visiting it results in a pointer
570     // anyway, so we just create a temporary pointer variable.
571     unsigned SubExprOffset = allocateLocalPrimitive(
572         SubExpr, PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false);
573     if (!this->visit(SubExpr))
574       return false;
575     if (!this->emitSetLocal(PT_Ptr, SubExprOffset, CE))
576       return false;
577 
578     PrimType SourceElemT = classifyComplexElementType(SubExpr->getType());
579     QualType DestElemType =
580         CE->getType()->getAs<ComplexType>()->getElementType();
581     PrimType DestElemT = classifyPrim(DestElemType);
582     // Cast both elements individually.
583     for (unsigned I = 0; I != 2; ++I) {
584       if (!this->emitGetLocal(PT_Ptr, SubExprOffset, CE))
585         return false;
586       if (!this->emitArrayElemPop(SourceElemT, I, CE))
587         return false;
588 
589       // Do the cast.
590       if (!this->emitPrimCast(SourceElemT, DestElemT, DestElemType, CE))
591         return false;
592 
593       // Save the value.
594       if (!this->emitInitElem(DestElemT, I, CE))
595         return false;
596     }
597     return true;
598   }
599 
600   case CK_VectorSplat: {
601     assert(!classify(CE->getType()));
602     assert(classify(SubExpr->getType()));
603     assert(CE->getType()->isVectorType());
604 
605     if (DiscardResult)
606       return this->discard(SubExpr);
607 
608     if (!Initializing) {
609       std::optional<unsigned> LocalIndex = allocateLocal(CE);
610       if (!LocalIndex)
611         return false;
612       if (!this->emitGetPtrLocal(*LocalIndex, CE))
613         return false;
614     }
615 
616     const auto *VT = CE->getType()->getAs<VectorType>();
617     PrimType ElemT = classifyPrim(SubExpr->getType());
618     unsigned ElemOffset = allocateLocalPrimitive(
619         SubExpr, ElemT, /*IsConst=*/true, /*IsExtended=*/false);
620 
621     // Prepare a local variable for the scalar value.
622     if (!this->visit(SubExpr))
623       return false;
624     if (classifyPrim(SubExpr) == PT_Ptr && !this->emitLoadPop(ElemT, CE))
625       return false;
626 
627     if (!this->emitSetLocal(ElemT, ElemOffset, CE))
628       return false;
629 
630     for (unsigned I = 0; I != VT->getNumElements(); ++I) {
631       if (!this->emitGetLocal(ElemT, ElemOffset, CE))
632         return false;
633       if (!this->emitInitElem(ElemT, I, CE))
634         return false;
635     }
636 
637     return true;
638   }
639 
640   case CK_ToVoid:
641     return discard(SubExpr);
642 
643   default:
644     return this->emitInvalid(CE);
645   }
646   llvm_unreachable("Unhandled clang::CastKind enum");
647 }
648 
649 template <class Emitter>
650 bool Compiler<Emitter>::VisitIntegerLiteral(const IntegerLiteral *LE) {
651   if (DiscardResult)
652     return true;
653 
654   return this->emitConst(LE->getValue(), LE);
655 }
656 
657 template <class Emitter>
658 bool Compiler<Emitter>::VisitFloatingLiteral(const FloatingLiteral *E) {
659   if (DiscardResult)
660     return true;
661 
662   return this->emitConstFloat(E->getValue(), E);
663 }
664 
665 template <class Emitter>
666 bool Compiler<Emitter>::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
667   assert(E->getType()->isAnyComplexType());
668   if (DiscardResult)
669     return true;
670 
671   if (!Initializing) {
672     unsigned LocalIndex = allocateTemporary(E);
673     if (!this->emitGetPtrLocal(LocalIndex, E))
674       return false;
675   }
676 
677   const Expr *SubExpr = E->getSubExpr();
678   PrimType SubExprT = classifyPrim(SubExpr->getType());
679 
680   if (!this->visitZeroInitializer(SubExprT, SubExpr->getType(), SubExpr))
681     return false;
682   if (!this->emitInitElem(SubExprT, 0, SubExpr))
683     return false;
684   return this->visitArrayElemInit(1, SubExpr);
685 }
686 
687 template <class Emitter>
688 bool Compiler<Emitter>::VisitParenExpr(const ParenExpr *E) {
689   return this->delegate(E->getSubExpr());
690 }
691 
692 template <class Emitter>
693 bool Compiler<Emitter>::VisitBinaryOperator(const BinaryOperator *BO) {
694   // Need short-circuiting for these.
695   if (BO->isLogicalOp())
696     return this->VisitLogicalBinOp(BO);
697 
698   const Expr *LHS = BO->getLHS();
699   const Expr *RHS = BO->getRHS();
700 
701   // Handle comma operators. Just discard the LHS
702   // and delegate to RHS.
703   if (BO->isCommaOp()) {
704     if (!this->discard(LHS))
705       return false;
706     if (RHS->getType()->isVoidType())
707       return this->discard(RHS);
708 
709     return this->delegate(RHS);
710   }
711 
712   if (BO->getType()->isAnyComplexType())
713     return this->VisitComplexBinOp(BO);
714   if ((LHS->getType()->isAnyComplexType() ||
715        RHS->getType()->isAnyComplexType()) &&
716       BO->isComparisonOp())
717     return this->emitComplexComparison(LHS, RHS, BO);
718 
719   if (BO->isPtrMemOp()) {
720     if (!this->visit(LHS))
721       return false;
722 
723     if (!this->visit(RHS))
724       return false;
725 
726     if (!this->emitToMemberPtr(BO))
727       return false;
728 
729     if (classifyPrim(BO) == PT_MemberPtr)
730       return true;
731 
732     if (!this->emitCastMemberPtrPtr(BO))
733       return false;
734     return DiscardResult ? this->emitPopPtr(BO) : true;
735   }
736 
737   // Typecheck the args.
738   std::optional<PrimType> LT = classify(LHS);
739   std::optional<PrimType> RT = classify(RHS);
740   std::optional<PrimType> T = classify(BO->getType());
741 
742   // Special case for C++'s three-way/spaceship operator <=>, which
743   // returns a std::{strong,weak,partial}_ordering (which is a class, so doesn't
744   // have a PrimType).
745   if (!T && BO->getOpcode() == BO_Cmp) {
746     if (DiscardResult)
747       return true;
748     const ComparisonCategoryInfo *CmpInfo =
749         Ctx.getASTContext().CompCategories.lookupInfoForType(BO->getType());
750     assert(CmpInfo);
751 
752     // We need a temporary variable holding our return value.
753     if (!Initializing) {
754       std::optional<unsigned> ResultIndex = this->allocateLocal(BO);
755       if (!this->emitGetPtrLocal(*ResultIndex, BO))
756         return false;
757     }
758 
759     if (!visit(LHS) || !visit(RHS))
760       return false;
761 
762     return this->emitCMP3(*LT, CmpInfo, BO);
763   }
764 
765   if (!LT || !RT || !T)
766     return false;
767 
768   // Pointer arithmetic special case.
769   if (BO->getOpcode() == BO_Add || BO->getOpcode() == BO_Sub) {
770     if (isPtrType(*T) || (isPtrType(*LT) && isPtrType(*RT)))
771       return this->VisitPointerArithBinOp(BO);
772   }
773 
774   // Assignmentes require us to evalute the RHS first.
775   if (BO->getOpcode() == BO_Assign) {
776     if (!visit(RHS) || !visit(LHS))
777       return false;
778     if (!this->emitFlip(*LT, *RT, BO))
779       return false;
780   } else {
781     if (!visit(LHS) || !visit(RHS))
782       return false;
783   }
784 
785   // For languages such as C, cast the result of one
786   // of our comparision opcodes to T (which is usually int).
787   auto MaybeCastToBool = [this, T, BO](bool Result) {
788     if (!Result)
789       return false;
790     if (DiscardResult)
791       return this->emitPop(*T, BO);
792     if (T != PT_Bool)
793       return this->emitCast(PT_Bool, *T, BO);
794     return true;
795   };
796 
797   auto Discard = [this, T, BO](bool Result) {
798     if (!Result)
799       return false;
800     return DiscardResult ? this->emitPop(*T, BO) : true;
801   };
802 
803   switch (BO->getOpcode()) {
804   case BO_EQ:
805     return MaybeCastToBool(this->emitEQ(*LT, BO));
806   case BO_NE:
807     return MaybeCastToBool(this->emitNE(*LT, BO));
808   case BO_LT:
809     return MaybeCastToBool(this->emitLT(*LT, BO));
810   case BO_LE:
811     return MaybeCastToBool(this->emitLE(*LT, BO));
812   case BO_GT:
813     return MaybeCastToBool(this->emitGT(*LT, BO));
814   case BO_GE:
815     return MaybeCastToBool(this->emitGE(*LT, BO));
816   case BO_Sub:
817     if (BO->getType()->isFloatingType())
818       return Discard(this->emitSubf(getRoundingMode(BO), BO));
819     return Discard(this->emitSub(*T, BO));
820   case BO_Add:
821     if (BO->getType()->isFloatingType())
822       return Discard(this->emitAddf(getRoundingMode(BO), BO));
823     return Discard(this->emitAdd(*T, BO));
824   case BO_Mul:
825     if (BO->getType()->isFloatingType())
826       return Discard(this->emitMulf(getRoundingMode(BO), BO));
827     return Discard(this->emitMul(*T, BO));
828   case BO_Rem:
829     return Discard(this->emitRem(*T, BO));
830   case BO_Div:
831     if (BO->getType()->isFloatingType())
832       return Discard(this->emitDivf(getRoundingMode(BO), BO));
833     return Discard(this->emitDiv(*T, BO));
834   case BO_Assign:
835     if (DiscardResult)
836       return LHS->refersToBitField() ? this->emitStoreBitFieldPop(*T, BO)
837                                      : this->emitStorePop(*T, BO);
838     if (LHS->refersToBitField()) {
839       if (!this->emitStoreBitField(*T, BO))
840         return false;
841     } else {
842       if (!this->emitStore(*T, BO))
843         return false;
844     }
845     // Assignments aren't necessarily lvalues in C.
846     // Load from them in that case.
847     if (!BO->isLValue())
848       return this->emitLoadPop(*T, BO);
849     return true;
850   case BO_And:
851     return Discard(this->emitBitAnd(*T, BO));
852   case BO_Or:
853     return Discard(this->emitBitOr(*T, BO));
854   case BO_Shl:
855     return Discard(this->emitShl(*LT, *RT, BO));
856   case BO_Shr:
857     return Discard(this->emitShr(*LT, *RT, BO));
858   case BO_Xor:
859     return Discard(this->emitBitXor(*T, BO));
860   case BO_LOr:
861   case BO_LAnd:
862     llvm_unreachable("Already handled earlier");
863   default:
864     return false;
865   }
866 
867   llvm_unreachable("Unhandled binary op");
868 }
869 
870 /// Perform addition/subtraction of a pointer and an integer or
871 /// subtraction of two pointers.
872 template <class Emitter>
873 bool Compiler<Emitter>::VisitPointerArithBinOp(const BinaryOperator *E) {
874   BinaryOperatorKind Op = E->getOpcode();
875   const Expr *LHS = E->getLHS();
876   const Expr *RHS = E->getRHS();
877 
878   if ((Op != BO_Add && Op != BO_Sub) ||
879       (!LHS->getType()->isPointerType() && !RHS->getType()->isPointerType()))
880     return false;
881 
882   std::optional<PrimType> LT = classify(LHS);
883   std::optional<PrimType> RT = classify(RHS);
884 
885   if (!LT || !RT)
886     return false;
887 
888   if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) {
889     if (Op != BO_Sub)
890       return false;
891 
892     assert(E->getType()->isIntegerType());
893     if (!visit(RHS) || !visit(LHS))
894       return false;
895 
896     return this->emitSubPtr(classifyPrim(E->getType()), E);
897   }
898 
899   PrimType OffsetType;
900   if (LHS->getType()->isIntegerType()) {
901     if (!visit(RHS) || !visit(LHS))
902       return false;
903     OffsetType = *LT;
904   } else if (RHS->getType()->isIntegerType()) {
905     if (!visit(LHS) || !visit(RHS))
906       return false;
907     OffsetType = *RT;
908   } else {
909     return false;
910   }
911 
912   if (Op == BO_Add)
913     return this->emitAddOffset(OffsetType, E);
914   else if (Op == BO_Sub)
915     return this->emitSubOffset(OffsetType, E);
916 
917   return false;
918 }
919 
920 template <class Emitter>
921 bool Compiler<Emitter>::VisitLogicalBinOp(const BinaryOperator *E) {
922   assert(E->isLogicalOp());
923   BinaryOperatorKind Op = E->getOpcode();
924   const Expr *LHS = E->getLHS();
925   const Expr *RHS = E->getRHS();
926   std::optional<PrimType> T = classify(E->getType());
927 
928   if (Op == BO_LOr) {
929     // Logical OR. Visit LHS and only evaluate RHS if LHS was FALSE.
930     LabelTy LabelTrue = this->getLabel();
931     LabelTy LabelEnd = this->getLabel();
932 
933     if (!this->visitBool(LHS))
934       return false;
935     if (!this->jumpTrue(LabelTrue))
936       return false;
937 
938     if (!this->visitBool(RHS))
939       return false;
940     if (!this->jump(LabelEnd))
941       return false;
942 
943     this->emitLabel(LabelTrue);
944     this->emitConstBool(true, E);
945     this->fallthrough(LabelEnd);
946     this->emitLabel(LabelEnd);
947 
948   } else {
949     assert(Op == BO_LAnd);
950     // Logical AND.
951     // Visit LHS. Only visit RHS if LHS was TRUE.
952     LabelTy LabelFalse = this->getLabel();
953     LabelTy LabelEnd = this->getLabel();
954 
955     if (!this->visitBool(LHS))
956       return false;
957     if (!this->jumpFalse(LabelFalse))
958       return false;
959 
960     if (!this->visitBool(RHS))
961       return false;
962     if (!this->jump(LabelEnd))
963       return false;
964 
965     this->emitLabel(LabelFalse);
966     this->emitConstBool(false, E);
967     this->fallthrough(LabelEnd);
968     this->emitLabel(LabelEnd);
969   }
970 
971   if (DiscardResult)
972     return this->emitPopBool(E);
973 
974   // For C, cast back to integer type.
975   assert(T);
976   if (T != PT_Bool)
977     return this->emitCast(PT_Bool, *T, E);
978   return true;
979 }
980 
981 template <class Emitter>
982 bool Compiler<Emitter>::VisitComplexBinOp(const BinaryOperator *E) {
983   // Prepare storage for result.
984   if (!Initializing) {
985     unsigned LocalIndex = allocateTemporary(E);
986     if (!this->emitGetPtrLocal(LocalIndex, E))
987       return false;
988   }
989 
990   // Both LHS and RHS might _not_ be of complex type, but one of them
991   // needs to be.
992   const Expr *LHS = E->getLHS();
993   const Expr *RHS = E->getRHS();
994 
995   PrimType ResultElemT = this->classifyComplexElementType(E->getType());
996   unsigned ResultOffset = ~0u;
997   if (!DiscardResult)
998     ResultOffset = this->allocateLocalPrimitive(E, PT_Ptr, true, false);
999 
1000   // Save result pointer in ResultOffset
1001   if (!this->DiscardResult) {
1002     if (!this->emitDupPtr(E))
1003       return false;
1004     if (!this->emitSetLocal(PT_Ptr, ResultOffset, E))
1005       return false;
1006   }
1007   QualType LHSType = LHS->getType();
1008   if (const auto *AT = LHSType->getAs<AtomicType>())
1009     LHSType = AT->getValueType();
1010   QualType RHSType = RHS->getType();
1011   if (const auto *AT = RHSType->getAs<AtomicType>())
1012     RHSType = AT->getValueType();
1013 
1014   bool LHSIsComplex = LHSType->isAnyComplexType();
1015   unsigned LHSOffset;
1016   bool RHSIsComplex = RHSType->isAnyComplexType();
1017 
1018   // For ComplexComplex Mul, we have special ops to make their implementation
1019   // easier.
1020   BinaryOperatorKind Op = E->getOpcode();
1021   if (Op == BO_Mul && LHSIsComplex && RHSIsComplex) {
1022     assert(classifyPrim(LHSType->getAs<ComplexType>()->getElementType()) ==
1023            classifyPrim(RHSType->getAs<ComplexType>()->getElementType()));
1024     PrimType ElemT =
1025         classifyPrim(LHSType->getAs<ComplexType>()->getElementType());
1026     if (!this->visit(LHS))
1027       return false;
1028     if (!this->visit(RHS))
1029       return false;
1030     return this->emitMulc(ElemT, E);
1031   }
1032 
1033   if (Op == BO_Div && RHSIsComplex) {
1034     QualType ElemQT = RHSType->getAs<ComplexType>()->getElementType();
1035     PrimType ElemT = classifyPrim(ElemQT);
1036     // If the LHS is not complex, we still need to do the full complex
1037     // division, so just stub create a complex value and stub it out with
1038     // the LHS and a zero.
1039 
1040     if (!LHSIsComplex) {
1041       // This is using the RHS type for the fake-complex LHS.
1042       LHSOffset = allocateTemporary(RHS);
1043 
1044       if (!this->emitGetPtrLocal(LHSOffset, E))
1045         return false;
1046 
1047       if (!this->visit(LHS))
1048         return false;
1049       // real is LHS
1050       if (!this->emitInitElem(ElemT, 0, E))
1051         return false;
1052       // imag is zero
1053       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1054         return false;
1055       if (!this->emitInitElem(ElemT, 1, E))
1056         return false;
1057     } else {
1058       if (!this->visit(LHS))
1059         return false;
1060     }
1061 
1062     if (!this->visit(RHS))
1063       return false;
1064     return this->emitDivc(ElemT, E);
1065   }
1066 
1067   // Evaluate LHS and save value to LHSOffset.
1068   if (LHSType->isAnyComplexType()) {
1069     LHSOffset = this->allocateLocalPrimitive(LHS, PT_Ptr, true, false);
1070     if (!this->visit(LHS))
1071       return false;
1072     if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
1073       return false;
1074   } else {
1075     PrimType LHST = classifyPrim(LHSType);
1076     LHSOffset = this->allocateLocalPrimitive(LHS, LHST, true, false);
1077     if (!this->visit(LHS))
1078       return false;
1079     if (!this->emitSetLocal(LHST, LHSOffset, E))
1080       return false;
1081   }
1082 
1083   // Same with RHS.
1084   unsigned RHSOffset;
1085   if (RHSType->isAnyComplexType()) {
1086     RHSOffset = this->allocateLocalPrimitive(RHS, PT_Ptr, true, false);
1087     if (!this->visit(RHS))
1088       return false;
1089     if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
1090       return false;
1091   } else {
1092     PrimType RHST = classifyPrim(RHSType);
1093     RHSOffset = this->allocateLocalPrimitive(RHS, RHST, true, false);
1094     if (!this->visit(RHS))
1095       return false;
1096     if (!this->emitSetLocal(RHST, RHSOffset, E))
1097       return false;
1098   }
1099 
1100   // For both LHS and RHS, either load the value from the complex pointer, or
1101   // directly from the local variable. For index 1 (i.e. the imaginary part),
1102   // just load 0 and do the operation anyway.
1103   auto loadComplexValue = [this](bool IsComplex, bool LoadZero,
1104                                  unsigned ElemIndex, unsigned Offset,
1105                                  const Expr *E) -> bool {
1106     if (IsComplex) {
1107       if (!this->emitGetLocal(PT_Ptr, Offset, E))
1108         return false;
1109       return this->emitArrayElemPop(classifyComplexElementType(E->getType()),
1110                                     ElemIndex, E);
1111     }
1112     if (ElemIndex == 0 || !LoadZero)
1113       return this->emitGetLocal(classifyPrim(E->getType()), Offset, E);
1114     return this->visitZeroInitializer(classifyPrim(E->getType()), E->getType(),
1115                                       E);
1116   };
1117 
1118   // Now we can get pointers to the LHS and RHS from the offsets above.
1119   for (unsigned ElemIndex = 0; ElemIndex != 2; ++ElemIndex) {
1120     // Result pointer for the store later.
1121     if (!this->DiscardResult) {
1122       if (!this->emitGetLocal(PT_Ptr, ResultOffset, E))
1123         return false;
1124     }
1125 
1126     // The actual operation.
1127     switch (Op) {
1128     case BO_Add:
1129       if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1130         return false;
1131 
1132       if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1133         return false;
1134       if (ResultElemT == PT_Float) {
1135         if (!this->emitAddf(getRoundingMode(E), E))
1136           return false;
1137       } else {
1138         if (!this->emitAdd(ResultElemT, E))
1139           return false;
1140       }
1141       break;
1142     case BO_Sub:
1143       if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1144         return false;
1145 
1146       if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1147         return false;
1148       if (ResultElemT == PT_Float) {
1149         if (!this->emitSubf(getRoundingMode(E), E))
1150           return false;
1151       } else {
1152         if (!this->emitSub(ResultElemT, E))
1153           return false;
1154       }
1155       break;
1156     case BO_Mul:
1157       if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1158         return false;
1159 
1160       if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1161         return false;
1162 
1163       if (ResultElemT == PT_Float) {
1164         if (!this->emitMulf(getRoundingMode(E), E))
1165           return false;
1166       } else {
1167         if (!this->emitMul(ResultElemT, E))
1168           return false;
1169       }
1170       break;
1171     case BO_Div:
1172       assert(!RHSIsComplex);
1173       if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1174         return false;
1175 
1176       if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1177         return false;
1178 
1179       if (ResultElemT == PT_Float) {
1180         if (!this->emitDivf(getRoundingMode(E), E))
1181           return false;
1182       } else {
1183         if (!this->emitDiv(ResultElemT, E))
1184           return false;
1185       }
1186       break;
1187 
1188     default:
1189       return false;
1190     }
1191 
1192     if (!this->DiscardResult) {
1193       // Initialize array element with the value we just computed.
1194       if (!this->emitInitElemPop(ResultElemT, ElemIndex, E))
1195         return false;
1196     } else {
1197       if (!this->emitPop(ResultElemT, E))
1198         return false;
1199     }
1200   }
1201   return true;
1202 }
1203 
1204 template <class Emitter>
1205 bool Compiler<Emitter>::VisitImplicitValueInitExpr(
1206     const ImplicitValueInitExpr *E) {
1207   QualType QT = E->getType();
1208 
1209   if (std::optional<PrimType> T = classify(QT))
1210     return this->visitZeroInitializer(*T, QT, E);
1211 
1212   if (QT->isRecordType()) {
1213     const RecordDecl *RD = QT->getAsRecordDecl();
1214     assert(RD);
1215     if (RD->isInvalidDecl())
1216       return false;
1217     if (RD->isUnion()) {
1218       // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
1219       // object's first non-static named data member is zero-initialized
1220       // FIXME
1221       return false;
1222     }
1223 
1224     if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1225         CXXRD && CXXRD->getNumVBases() > 0) {
1226       // TODO: Diagnose.
1227       return false;
1228     }
1229 
1230     const Record *R = getRecord(QT);
1231     if (!R)
1232       return false;
1233 
1234     assert(Initializing);
1235     return this->visitZeroRecordInitializer(R, E);
1236   }
1237 
1238   if (QT->isIncompleteArrayType())
1239     return true;
1240 
1241   if (QT->isArrayType()) {
1242     const ArrayType *AT = QT->getAsArrayTypeUnsafe();
1243     assert(AT);
1244     const auto *CAT = cast<ConstantArrayType>(AT);
1245     size_t NumElems = CAT->getZExtSize();
1246     PrimType ElemT = classifyPrim(CAT->getElementType());
1247 
1248     for (size_t I = 0; I != NumElems; ++I) {
1249       if (!this->visitZeroInitializer(ElemT, CAT->getElementType(), E))
1250         return false;
1251       if (!this->emitInitElem(ElemT, I, E))
1252         return false;
1253     }
1254 
1255     return true;
1256   }
1257 
1258   if (const auto *ComplexTy = E->getType()->getAs<ComplexType>()) {
1259     assert(Initializing);
1260     QualType ElemQT = ComplexTy->getElementType();
1261     PrimType ElemT = classifyPrim(ElemQT);
1262     for (unsigned I = 0; I < 2; ++I) {
1263       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1264         return false;
1265       if (!this->emitInitElem(ElemT, I, E))
1266         return false;
1267     }
1268     return true;
1269   }
1270 
1271   if (const auto *VecT = E->getType()->getAs<VectorType>()) {
1272     unsigned NumVecElements = VecT->getNumElements();
1273     QualType ElemQT = VecT->getElementType();
1274     PrimType ElemT = classifyPrim(ElemQT);
1275 
1276     for (unsigned I = 0; I < NumVecElements; ++I) {
1277       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1278         return false;
1279       if (!this->emitInitElem(ElemT, I, E))
1280         return false;
1281     }
1282     return true;
1283   }
1284 
1285   return false;
1286 }
1287 
1288 template <class Emitter>
1289 bool Compiler<Emitter>::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1290   const Expr *LHS = E->getLHS();
1291   const Expr *RHS = E->getRHS();
1292   const Expr *Index = E->getIdx();
1293 
1294   if (DiscardResult)
1295     return this->discard(LHS) && this->discard(RHS);
1296 
1297   // C++17's rules require us to evaluate the LHS first, regardless of which
1298   // side is the base.
1299   bool Success = true;
1300   for (const Expr *SubExpr : {LHS, RHS}) {
1301     if (!this->visit(SubExpr))
1302       Success = false;
1303   }
1304 
1305   if (!Success)
1306     return false;
1307 
1308   PrimType IndexT = classifyPrim(Index->getType());
1309   // If the index is first, we need to change that.
1310   if (LHS == Index) {
1311     if (!this->emitFlip(PT_Ptr, IndexT, E))
1312       return false;
1313   }
1314 
1315   return this->emitArrayElemPtrPop(IndexT, E);
1316 }
1317 
1318 template <class Emitter>
1319 bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
1320                                       const Expr *ArrayFiller, const Expr *E) {
1321   // Handle discarding first.
1322   if (DiscardResult) {
1323     for (const Expr *Init : Inits) {
1324       if (!this->discard(Init))
1325         return false;
1326     }
1327     return true;
1328   }
1329 
1330   QualType QT = E->getType();
1331   if (const auto *AT = QT->getAs<AtomicType>())
1332     QT = AT->getValueType();
1333 
1334   if (QT->isVoidType())
1335     return this->emitInvalid(E);
1336 
1337   // Primitive values.
1338   if (std::optional<PrimType> T = classify(QT)) {
1339     assert(!DiscardResult);
1340     if (Inits.size() == 0)
1341       return this->visitZeroInitializer(*T, QT, E);
1342     assert(Inits.size() == 1);
1343     return this->delegate(Inits[0]);
1344   }
1345 
1346   if (QT->isRecordType()) {
1347     const Record *R = getRecord(QT);
1348 
1349     if (Inits.size() == 1 && E->getType() == Inits[0]->getType())
1350       return this->delegate(Inits[0]);
1351 
1352     auto initPrimitiveField = [=](const Record::Field *FieldToInit,
1353                                   const Expr *Init, PrimType T) -> bool {
1354       InitStackScope<Emitter> ISS(this, isa<CXXDefaultInitExpr>(Init));
1355       if (!this->visit(Init))
1356         return false;
1357 
1358       if (FieldToInit->isBitField())
1359         return this->emitInitBitField(T, FieldToInit, E);
1360       return this->emitInitField(T, FieldToInit->Offset, E);
1361     };
1362 
1363     auto initCompositeField = [=](const Record::Field *FieldToInit,
1364                                   const Expr *Init) -> bool {
1365       InitStackScope<Emitter> ISS(this, isa<CXXDefaultInitExpr>(Init));
1366       InitLinkScope<Emitter> ILS(this, InitLink::Field(FieldToInit->Offset));
1367       // Non-primitive case. Get a pointer to the field-to-initialize
1368       // on the stack and recurse into visitInitializer().
1369       if (!this->emitGetPtrField(FieldToInit->Offset, Init))
1370         return false;
1371       if (!this->visitInitializer(Init))
1372         return false;
1373       return this->emitPopPtr(E);
1374     };
1375 
1376     if (R->isUnion()) {
1377       if (Inits.size() == 0) {
1378         if (!this->visitZeroRecordInitializer(R, E))
1379           return false;
1380       } else {
1381         const Expr *Init = Inits[0];
1382         const FieldDecl *FToInit = nullptr;
1383         if (const auto *ILE = dyn_cast<InitListExpr>(E))
1384           FToInit = ILE->getInitializedFieldInUnion();
1385         else
1386           FToInit = cast<CXXParenListInitExpr>(E)->getInitializedFieldInUnion();
1387 
1388         const Record::Field *FieldToInit = R->getField(FToInit);
1389         if (std::optional<PrimType> T = classify(Init)) {
1390           if (!initPrimitiveField(FieldToInit, Init, *T))
1391             return false;
1392         } else {
1393           if (!initCompositeField(FieldToInit, Init))
1394             return false;
1395         }
1396       }
1397       return this->emitFinishInit(E);
1398     }
1399 
1400     assert(!R->isUnion());
1401     unsigned InitIndex = 0;
1402     for (const Expr *Init : Inits) {
1403       // Skip unnamed bitfields.
1404       while (InitIndex < R->getNumFields() &&
1405              R->getField(InitIndex)->Decl->isUnnamedBitField())
1406         ++InitIndex;
1407 
1408       if (std::optional<PrimType> T = classify(Init)) {
1409         const Record::Field *FieldToInit = R->getField(InitIndex);
1410         if (!initPrimitiveField(FieldToInit, Init, *T))
1411           return false;
1412         ++InitIndex;
1413       } else {
1414         // Initializer for a direct base class.
1415         if (const Record::Base *B = R->getBase(Init->getType())) {
1416           if (!this->emitGetPtrBase(B->Offset, Init))
1417             return false;
1418 
1419           if (!this->visitInitializer(Init))
1420             return false;
1421 
1422           if (!this->emitFinishInitPop(E))
1423             return false;
1424           // Base initializers don't increase InitIndex, since they don't count
1425           // into the Record's fields.
1426         } else {
1427           const Record::Field *FieldToInit = R->getField(InitIndex);
1428           if (!initCompositeField(FieldToInit, Init))
1429             return false;
1430           ++InitIndex;
1431         }
1432       }
1433     }
1434     return this->emitFinishInit(E);
1435   }
1436 
1437   if (QT->isArrayType()) {
1438     if (Inits.size() == 1 && QT == Inits[0]->getType())
1439       return this->delegate(Inits[0]);
1440 
1441     unsigned ElementIndex = 0;
1442     for (const Expr *Init : Inits) {
1443       if (const auto *EmbedS =
1444               dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
1445         PrimType TargetT = classifyPrim(Init->getType());
1446 
1447         auto Eval = [&](const Expr *Init, unsigned ElemIndex) {
1448           PrimType InitT = classifyPrim(Init->getType());
1449           if (!this->visit(Init))
1450             return false;
1451           if (InitT != TargetT) {
1452             if (!this->emitCast(InitT, TargetT, E))
1453               return false;
1454           }
1455           return this->emitInitElem(TargetT, ElemIndex, Init);
1456         };
1457         if (!EmbedS->doForEachDataElement(Eval, ElementIndex))
1458           return false;
1459       } else {
1460         if (!this->visitArrayElemInit(ElementIndex, Init))
1461           return false;
1462         ++ElementIndex;
1463       }
1464     }
1465 
1466     // Expand the filler expression.
1467     // FIXME: This should go away.
1468     if (ArrayFiller) {
1469       const ConstantArrayType *CAT =
1470           Ctx.getASTContext().getAsConstantArrayType(QT);
1471       uint64_t NumElems = CAT->getZExtSize();
1472 
1473       for (; ElementIndex != NumElems; ++ElementIndex) {
1474         if (!this->visitArrayElemInit(ElementIndex, ArrayFiller))
1475           return false;
1476       }
1477     }
1478 
1479     return this->emitFinishInit(E);
1480   }
1481 
1482   if (const auto *ComplexTy = QT->getAs<ComplexType>()) {
1483     unsigned NumInits = Inits.size();
1484 
1485     if (NumInits == 1)
1486       return this->delegate(Inits[0]);
1487 
1488     QualType ElemQT = ComplexTy->getElementType();
1489     PrimType ElemT = classifyPrim(ElemQT);
1490     if (NumInits == 0) {
1491       // Zero-initialize both elements.
1492       for (unsigned I = 0; I < 2; ++I) {
1493         if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1494           return false;
1495         if (!this->emitInitElem(ElemT, I, E))
1496           return false;
1497       }
1498     } else if (NumInits == 2) {
1499       unsigned InitIndex = 0;
1500       for (const Expr *Init : Inits) {
1501         if (!this->visit(Init))
1502           return false;
1503 
1504         if (!this->emitInitElem(ElemT, InitIndex, E))
1505           return false;
1506         ++InitIndex;
1507       }
1508     }
1509     return true;
1510   }
1511 
1512   if (const auto *VecT = QT->getAs<VectorType>()) {
1513     unsigned NumVecElements = VecT->getNumElements();
1514     assert(NumVecElements >= Inits.size());
1515 
1516     QualType ElemQT = VecT->getElementType();
1517     PrimType ElemT = classifyPrim(ElemQT);
1518 
1519     // All initializer elements.
1520     unsigned InitIndex = 0;
1521     for (const Expr *Init : Inits) {
1522       if (!this->visit(Init))
1523         return false;
1524 
1525       // If the initializer is of vector type itself, we have to deconstruct
1526       // that and initialize all the target fields from the initializer fields.
1527       if (const auto *InitVecT = Init->getType()->getAs<VectorType>()) {
1528         if (!this->emitCopyArray(ElemT, 0, InitIndex,
1529                                  InitVecT->getNumElements(), E))
1530           return false;
1531         InitIndex += InitVecT->getNumElements();
1532       } else {
1533         if (!this->emitInitElem(ElemT, InitIndex, E))
1534           return false;
1535         ++InitIndex;
1536       }
1537     }
1538 
1539     assert(InitIndex <= NumVecElements);
1540 
1541     // Fill the rest with zeroes.
1542     for (; InitIndex != NumVecElements; ++InitIndex) {
1543       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1544         return false;
1545       if (!this->emitInitElem(ElemT, InitIndex, E))
1546         return false;
1547     }
1548     return true;
1549   }
1550 
1551   return false;
1552 }
1553 
1554 /// Pointer to the array(not the element!) must be on the stack when calling
1555 /// this.
1556 template <class Emitter>
1557 bool Compiler<Emitter>::visitArrayElemInit(unsigned ElemIndex,
1558                                            const Expr *Init) {
1559   if (std::optional<PrimType> T = classify(Init->getType())) {
1560     // Visit the primitive element like normal.
1561     if (!this->visit(Init))
1562       return false;
1563     return this->emitInitElem(*T, ElemIndex, Init);
1564   }
1565 
1566   InitLinkScope<Emitter> ILS(this, InitLink::Elem(ElemIndex));
1567   // Advance the pointer currently on the stack to the given
1568   // dimension.
1569   if (!this->emitConstUint32(ElemIndex, Init))
1570     return false;
1571   if (!this->emitArrayElemPtrUint32(Init))
1572     return false;
1573   if (!this->visitInitializer(Init))
1574     return false;
1575   return this->emitFinishInitPop(Init);
1576 }
1577 
1578 template <class Emitter>
1579 bool Compiler<Emitter>::VisitInitListExpr(const InitListExpr *E) {
1580   return this->visitInitList(E->inits(), E->getArrayFiller(), E);
1581 }
1582 
1583 template <class Emitter>
1584 bool Compiler<Emitter>::VisitCXXParenListInitExpr(
1585     const CXXParenListInitExpr *E) {
1586   return this->visitInitList(E->getInitExprs(), E->getArrayFiller(), E);
1587 }
1588 
1589 template <class Emitter>
1590 bool Compiler<Emitter>::VisitSubstNonTypeTemplateParmExpr(
1591     const SubstNonTypeTemplateParmExpr *E) {
1592   return this->delegate(E->getReplacement());
1593 }
1594 
1595 template <class Emitter>
1596 bool Compiler<Emitter>::VisitConstantExpr(const ConstantExpr *E) {
1597   std::optional<PrimType> T = classify(E->getType());
1598   if (T && E->hasAPValueResult()) {
1599     // Try to emit the APValue directly, without visiting the subexpr.
1600     // This will only fail if we can't emit the APValue, so won't emit any
1601     // diagnostics or any double values.
1602     if (DiscardResult)
1603       return true;
1604 
1605     if (this->visitAPValue(E->getAPValueResult(), *T, E))
1606       return true;
1607   }
1608   return this->delegate(E->getSubExpr());
1609 }
1610 
1611 template <class Emitter>
1612 bool Compiler<Emitter>::VisitEmbedExpr(const EmbedExpr *E) {
1613   auto It = E->begin();
1614   return this->visit(*It);
1615 }
1616 
1617 static CharUnits AlignOfType(QualType T, const ASTContext &ASTCtx,
1618                              UnaryExprOrTypeTrait Kind) {
1619   bool AlignOfReturnsPreferred =
1620       ASTCtx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
1621 
1622   // C++ [expr.alignof]p3:
1623   //     When alignof is applied to a reference type, the result is the
1624   //     alignment of the referenced type.
1625   if (const auto *Ref = T->getAs<ReferenceType>())
1626     T = Ref->getPointeeType();
1627 
1628   if (T.getQualifiers().hasUnaligned())
1629     return CharUnits::One();
1630 
1631   // __alignof is defined to return the preferred alignment.
1632   // Before 8, clang returned the preferred alignment for alignof and
1633   // _Alignof as well.
1634   if (Kind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
1635     return ASTCtx.toCharUnitsFromBits(ASTCtx.getPreferredTypeAlign(T));
1636 
1637   return ASTCtx.getTypeAlignInChars(T);
1638 }
1639 
1640 template <class Emitter>
1641 bool Compiler<Emitter>::VisitUnaryExprOrTypeTraitExpr(
1642     const UnaryExprOrTypeTraitExpr *E) {
1643   UnaryExprOrTypeTrait Kind = E->getKind();
1644   const ASTContext &ASTCtx = Ctx.getASTContext();
1645 
1646   if (Kind == UETT_SizeOf || Kind == UETT_DataSizeOf) {
1647     QualType ArgType = E->getTypeOfArgument();
1648 
1649     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1650     //   the result is the size of the referenced type."
1651     if (const auto *Ref = ArgType->getAs<ReferenceType>())
1652       ArgType = Ref->getPointeeType();
1653 
1654     CharUnits Size;
1655     if (ArgType->isVoidType() || ArgType->isFunctionType())
1656       Size = CharUnits::One();
1657     else {
1658       if (ArgType->isDependentType() || !ArgType->isConstantSizeType())
1659         return false;
1660 
1661       if (Kind == UETT_SizeOf)
1662         Size = ASTCtx.getTypeSizeInChars(ArgType);
1663       else
1664         Size = ASTCtx.getTypeInfoDataSizeInChars(ArgType).Width;
1665     }
1666 
1667     if (DiscardResult)
1668       return true;
1669 
1670     return this->emitConst(Size.getQuantity(), E);
1671   }
1672 
1673   if (Kind == UETT_AlignOf || Kind == UETT_PreferredAlignOf) {
1674     CharUnits Size;
1675 
1676     if (E->isArgumentType()) {
1677       QualType ArgType = E->getTypeOfArgument();
1678 
1679       Size = AlignOfType(ArgType, ASTCtx, Kind);
1680     } else {
1681       // Argument is an expression, not a type.
1682       const Expr *Arg = E->getArgumentExpr()->IgnoreParens();
1683 
1684       // The kinds of expressions that we have special-case logic here for
1685       // should be kept up to date with the special checks for those
1686       // expressions in Sema.
1687 
1688       // alignof decl is always accepted, even if it doesn't make sense: we
1689       // default to 1 in those cases.
1690       if (const auto *DRE = dyn_cast<DeclRefExpr>(Arg))
1691         Size = ASTCtx.getDeclAlign(DRE->getDecl(),
1692                                    /*RefAsPointee*/ true);
1693       else if (const auto *ME = dyn_cast<MemberExpr>(Arg))
1694         Size = ASTCtx.getDeclAlign(ME->getMemberDecl(),
1695                                    /*RefAsPointee*/ true);
1696       else
1697         Size = AlignOfType(Arg->getType(), ASTCtx, Kind);
1698     }
1699 
1700     if (DiscardResult)
1701       return true;
1702 
1703     return this->emitConst(Size.getQuantity(), E);
1704   }
1705 
1706   if (Kind == UETT_VectorElements) {
1707     if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>())
1708       return this->emitConst(VT->getNumElements(), E);
1709     assert(E->getTypeOfArgument()->isSizelessVectorType());
1710     return this->emitSizelessVectorElementSize(E);
1711   }
1712 
1713   if (Kind == UETT_VecStep) {
1714     if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>()) {
1715       unsigned N = VT->getNumElements();
1716 
1717       // The vec_step built-in functions that take a 3-component
1718       // vector return 4. (OpenCL 1.1 spec 6.11.12)
1719       if (N == 3)
1720         N = 4;
1721 
1722       return this->emitConst(N, E);
1723     }
1724     return this->emitConst(1, E);
1725   }
1726 
1727   return false;
1728 }
1729 
1730 template <class Emitter>
1731 bool Compiler<Emitter>::VisitMemberExpr(const MemberExpr *E) {
1732   // 'Base.Member'
1733   const Expr *Base = E->getBase();
1734   const ValueDecl *Member = E->getMemberDecl();
1735 
1736   if (DiscardResult)
1737     return this->discard(Base);
1738 
1739   // MemberExprs are almost always lvalues, in which case we don't need to
1740   // do the load. But sometimes they aren't.
1741   const auto maybeLoadValue = [&]() -> bool {
1742     if (E->isGLValue())
1743       return true;
1744     if (std::optional<PrimType> T = classify(E))
1745       return this->emitLoadPop(*T, E);
1746     return false;
1747   };
1748 
1749   if (const auto *VD = dyn_cast<VarDecl>(Member)) {
1750     // I am almost confident in saying that a var decl must be static
1751     // and therefore registered as a global variable. But this will probably
1752     // turn out to be wrong some time in the future, as always.
1753     if (auto GlobalIndex = P.getGlobal(VD))
1754       return this->emitGetPtrGlobal(*GlobalIndex, E) && maybeLoadValue();
1755     return false;
1756   }
1757 
1758   if (!isa<FieldDecl>(Member))
1759     return this->discard(Base) && this->visitDeclRef(Member, E);
1760 
1761   if (Initializing) {
1762     if (!this->delegate(Base))
1763       return false;
1764   } else {
1765     if (!this->visit(Base))
1766       return false;
1767   }
1768 
1769   // Base above gives us a pointer on the stack.
1770   const auto *FD = cast<FieldDecl>(Member);
1771   const RecordDecl *RD = FD->getParent();
1772   const Record *R = getRecord(RD);
1773   if (!R)
1774     return false;
1775   const Record::Field *F = R->getField(FD);
1776   // Leave a pointer to the field on the stack.
1777   if (F->Decl->getType()->isReferenceType())
1778     return this->emitGetFieldPop(PT_Ptr, F->Offset, E) && maybeLoadValue();
1779   return this->emitGetPtrFieldPop(F->Offset, E) && maybeLoadValue();
1780 }
1781 
1782 template <class Emitter>
1783 bool Compiler<Emitter>::VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
1784   // ArrayIndex might not be set if a ArrayInitIndexExpr is being evaluated
1785   // stand-alone, e.g. via EvaluateAsInt().
1786   if (!ArrayIndex)
1787     return false;
1788   return this->emitConst(*ArrayIndex, E);
1789 }
1790 
1791 template <class Emitter>
1792 bool Compiler<Emitter>::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
1793   assert(Initializing);
1794   assert(!DiscardResult);
1795 
1796   // We visit the common opaque expression here once so we have its value
1797   // cached.
1798   if (!this->discard(E->getCommonExpr()))
1799     return false;
1800 
1801   // TODO: This compiles to quite a lot of bytecode if the array is larger.
1802   //   Investigate compiling this to a loop.
1803   const Expr *SubExpr = E->getSubExpr();
1804   size_t Size = E->getArraySize().getZExtValue();
1805 
1806   // So, every iteration, we execute an assignment here
1807   // where the LHS is on the stack (the target array)
1808   // and the RHS is our SubExpr.
1809   for (size_t I = 0; I != Size; ++I) {
1810     ArrayIndexScope<Emitter> IndexScope(this, I);
1811     BlockScope<Emitter> BS(this);
1812 
1813     if (!this->visitArrayElemInit(I, SubExpr))
1814       return false;
1815     if (!BS.destroyLocals())
1816       return false;
1817   }
1818   return true;
1819 }
1820 
1821 template <class Emitter>
1822 bool Compiler<Emitter>::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
1823   const Expr *SourceExpr = E->getSourceExpr();
1824   if (!SourceExpr)
1825     return false;
1826 
1827   if (Initializing)
1828     return this->visitInitializer(SourceExpr);
1829 
1830   PrimType SubExprT = classify(SourceExpr).value_or(PT_Ptr);
1831   if (auto It = OpaqueExprs.find(E); It != OpaqueExprs.end())
1832     return this->emitGetLocal(SubExprT, It->second, E);
1833 
1834   if (!this->visit(SourceExpr))
1835     return false;
1836 
1837   // At this point we either have the evaluated source expression or a pointer
1838   // to an object on the stack. We want to create a local variable that stores
1839   // this value.
1840   unsigned LocalIndex = allocateLocalPrimitive(E, SubExprT, /*IsConst=*/true);
1841   if (!this->emitSetLocal(SubExprT, LocalIndex, E))
1842     return false;
1843 
1844   // Here the local variable is created but the value is removed from the stack,
1845   // so we put it back if the caller needs it.
1846   if (!DiscardResult) {
1847     if (!this->emitGetLocal(SubExprT, LocalIndex, E))
1848       return false;
1849   }
1850 
1851   // This is cleaned up when the local variable is destroyed.
1852   OpaqueExprs.insert({E, LocalIndex});
1853 
1854   return true;
1855 }
1856 
1857 template <class Emitter>
1858 bool Compiler<Emitter>::VisitAbstractConditionalOperator(
1859     const AbstractConditionalOperator *E) {
1860   const Expr *Condition = E->getCond();
1861   const Expr *TrueExpr = E->getTrueExpr();
1862   const Expr *FalseExpr = E->getFalseExpr();
1863 
1864   LabelTy LabelEnd = this->getLabel();   // Label after the operator.
1865   LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
1866 
1867   if (!this->visitBool(Condition))
1868     return false;
1869 
1870   if (!this->jumpFalse(LabelFalse))
1871     return false;
1872 
1873   {
1874     LocalScope<Emitter> S(this);
1875     if (!this->delegate(TrueExpr))
1876       return false;
1877     if (!S.destroyLocals())
1878       return false;
1879   }
1880 
1881   if (!this->jump(LabelEnd))
1882     return false;
1883 
1884   this->emitLabel(LabelFalse);
1885 
1886   {
1887     LocalScope<Emitter> S(this);
1888     if (!this->delegate(FalseExpr))
1889       return false;
1890     if (!S.destroyLocals())
1891       return false;
1892   }
1893 
1894   this->fallthrough(LabelEnd);
1895   this->emitLabel(LabelEnd);
1896 
1897   return true;
1898 }
1899 
1900 template <class Emitter>
1901 bool Compiler<Emitter>::VisitStringLiteral(const StringLiteral *E) {
1902   if (DiscardResult)
1903     return true;
1904 
1905   if (!Initializing) {
1906     unsigned StringIndex = P.createGlobalString(E);
1907     return this->emitGetPtrGlobal(StringIndex, E);
1908   }
1909 
1910   // We are initializing an array on the stack.
1911   const ConstantArrayType *CAT =
1912       Ctx.getASTContext().getAsConstantArrayType(E->getType());
1913   assert(CAT && "a string literal that's not a constant array?");
1914 
1915   // If the initializer string is too long, a diagnostic has already been
1916   // emitted. Read only the array length from the string literal.
1917   unsigned ArraySize = CAT->getZExtSize();
1918   unsigned N = std::min(ArraySize, E->getLength());
1919   size_t CharWidth = E->getCharByteWidth();
1920 
1921   for (unsigned I = 0; I != N; ++I) {
1922     uint32_t CodeUnit = E->getCodeUnit(I);
1923 
1924     if (CharWidth == 1) {
1925       this->emitConstSint8(CodeUnit, E);
1926       this->emitInitElemSint8(I, E);
1927     } else if (CharWidth == 2) {
1928       this->emitConstUint16(CodeUnit, E);
1929       this->emitInitElemUint16(I, E);
1930     } else if (CharWidth == 4) {
1931       this->emitConstUint32(CodeUnit, E);
1932       this->emitInitElemUint32(I, E);
1933     } else {
1934       llvm_unreachable("unsupported character width");
1935     }
1936   }
1937 
1938   // Fill up the rest of the char array with NUL bytes.
1939   for (unsigned I = N; I != ArraySize; ++I) {
1940     if (CharWidth == 1) {
1941       this->emitConstSint8(0, E);
1942       this->emitInitElemSint8(I, E);
1943     } else if (CharWidth == 2) {
1944       this->emitConstUint16(0, E);
1945       this->emitInitElemUint16(I, E);
1946     } else if (CharWidth == 4) {
1947       this->emitConstUint32(0, E);
1948       this->emitInitElemUint32(I, E);
1949     } else {
1950       llvm_unreachable("unsupported character width");
1951     }
1952   }
1953 
1954   return true;
1955 }
1956 
1957 template <class Emitter>
1958 bool Compiler<Emitter>::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
1959   return this->delegate(E->getString());
1960 }
1961 
1962 template <class Emitter>
1963 bool Compiler<Emitter>::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1964   auto &A = Ctx.getASTContext();
1965   std::string Str;
1966   A.getObjCEncodingForType(E->getEncodedType(), Str);
1967   StringLiteral *SL =
1968       StringLiteral::Create(A, Str, StringLiteralKind::Ordinary,
1969                             /*Pascal=*/false, E->getType(), E->getAtLoc());
1970   return this->delegate(SL);
1971 }
1972 
1973 template <class Emitter>
1974 bool Compiler<Emitter>::VisitSYCLUniqueStableNameExpr(
1975     const SYCLUniqueStableNameExpr *E) {
1976   if (DiscardResult)
1977     return true;
1978 
1979   assert(!Initializing);
1980 
1981   auto &A = Ctx.getASTContext();
1982   std::string ResultStr = E->ComputeName(A);
1983 
1984   QualType CharTy = A.CharTy.withConst();
1985   APInt Size(A.getTypeSize(A.getSizeType()), ResultStr.size() + 1);
1986   QualType ArrayTy = A.getConstantArrayType(CharTy, Size, nullptr,
1987                                             ArraySizeModifier::Normal, 0);
1988 
1989   StringLiteral *SL =
1990       StringLiteral::Create(A, ResultStr, StringLiteralKind::Ordinary,
1991                             /*Pascal=*/false, ArrayTy, E->getLocation());
1992 
1993   unsigned StringIndex = P.createGlobalString(SL);
1994   return this->emitGetPtrGlobal(StringIndex, E);
1995 }
1996 
1997 template <class Emitter>
1998 bool Compiler<Emitter>::VisitCharacterLiteral(const CharacterLiteral *E) {
1999   if (DiscardResult)
2000     return true;
2001   return this->emitConst(E->getValue(), E);
2002 }
2003 
2004 template <class Emitter>
2005 bool Compiler<Emitter>::VisitFloatCompoundAssignOperator(
2006     const CompoundAssignOperator *E) {
2007 
2008   const Expr *LHS = E->getLHS();
2009   const Expr *RHS = E->getRHS();
2010   QualType LHSType = LHS->getType();
2011   QualType LHSComputationType = E->getComputationLHSType();
2012   QualType ResultType = E->getComputationResultType();
2013   std::optional<PrimType> LT = classify(LHSComputationType);
2014   std::optional<PrimType> RT = classify(ResultType);
2015 
2016   assert(ResultType->isFloatingType());
2017 
2018   if (!LT || !RT)
2019     return false;
2020 
2021   PrimType LHST = classifyPrim(LHSType);
2022 
2023   // C++17 onwards require that we evaluate the RHS first.
2024   // Compute RHS and save it in a temporary variable so we can
2025   // load it again later.
2026   if (!visit(RHS))
2027     return false;
2028 
2029   unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
2030   if (!this->emitSetLocal(*RT, TempOffset, E))
2031     return false;
2032 
2033   // First, visit LHS.
2034   if (!visit(LHS))
2035     return false;
2036   if (!this->emitLoad(LHST, E))
2037     return false;
2038 
2039   // If necessary, convert LHS to its computation type.
2040   if (!this->emitPrimCast(LHST, classifyPrim(LHSComputationType),
2041                           LHSComputationType, E))
2042     return false;
2043 
2044   // Now load RHS.
2045   if (!this->emitGetLocal(*RT, TempOffset, E))
2046     return false;
2047 
2048   llvm::RoundingMode RM = getRoundingMode(E);
2049   switch (E->getOpcode()) {
2050   case BO_AddAssign:
2051     if (!this->emitAddf(RM, E))
2052       return false;
2053     break;
2054   case BO_SubAssign:
2055     if (!this->emitSubf(RM, E))
2056       return false;
2057     break;
2058   case BO_MulAssign:
2059     if (!this->emitMulf(RM, E))
2060       return false;
2061     break;
2062   case BO_DivAssign:
2063     if (!this->emitDivf(RM, E))
2064       return false;
2065     break;
2066   default:
2067     return false;
2068   }
2069 
2070   if (!this->emitPrimCast(classifyPrim(ResultType), LHST, LHS->getType(), E))
2071     return false;
2072 
2073   if (DiscardResult)
2074     return this->emitStorePop(LHST, E);
2075   return this->emitStore(LHST, E);
2076 }
2077 
2078 template <class Emitter>
2079 bool Compiler<Emitter>::VisitPointerCompoundAssignOperator(
2080     const CompoundAssignOperator *E) {
2081   BinaryOperatorKind Op = E->getOpcode();
2082   const Expr *LHS = E->getLHS();
2083   const Expr *RHS = E->getRHS();
2084   std::optional<PrimType> LT = classify(LHS->getType());
2085   std::optional<PrimType> RT = classify(RHS->getType());
2086 
2087   if (Op != BO_AddAssign && Op != BO_SubAssign)
2088     return false;
2089 
2090   if (!LT || !RT)
2091     return false;
2092 
2093   if (!visit(LHS))
2094     return false;
2095 
2096   if (!this->emitLoad(*LT, LHS))
2097     return false;
2098 
2099   if (!visit(RHS))
2100     return false;
2101 
2102   if (Op == BO_AddAssign) {
2103     if (!this->emitAddOffset(*RT, E))
2104       return false;
2105   } else {
2106     if (!this->emitSubOffset(*RT, E))
2107       return false;
2108   }
2109 
2110   if (DiscardResult)
2111     return this->emitStorePopPtr(E);
2112   return this->emitStorePtr(E);
2113 }
2114 
2115 template <class Emitter>
2116 bool Compiler<Emitter>::VisitCompoundAssignOperator(
2117     const CompoundAssignOperator *E) {
2118 
2119   const Expr *LHS = E->getLHS();
2120   const Expr *RHS = E->getRHS();
2121   std::optional<PrimType> LHSComputationT =
2122       classify(E->getComputationLHSType());
2123   std::optional<PrimType> LT = classify(LHS->getType());
2124   std::optional<PrimType> RT = classify(RHS->getType());
2125   std::optional<PrimType> ResultT = classify(E->getType());
2126 
2127   if (!Ctx.getLangOpts().CPlusPlus14)
2128     return this->visit(RHS) && this->visit(LHS) && this->emitError(E);
2129 
2130   if (!LT || !RT || !ResultT || !LHSComputationT)
2131     return false;
2132 
2133   // Handle floating point operations separately here, since they
2134   // require special care.
2135 
2136   if (ResultT == PT_Float || RT == PT_Float)
2137     return VisitFloatCompoundAssignOperator(E);
2138 
2139   if (E->getType()->isPointerType())
2140     return VisitPointerCompoundAssignOperator(E);
2141 
2142   assert(!E->getType()->isPointerType() && "Handled above");
2143   assert(!E->getType()->isFloatingType() && "Handled above");
2144 
2145   // C++17 onwards require that we evaluate the RHS first.
2146   // Compute RHS and save it in a temporary variable so we can
2147   // load it again later.
2148   // FIXME: Compound assignments are unsequenced in C, so we might
2149   //   have to figure out how to reject them.
2150   if (!visit(RHS))
2151     return false;
2152 
2153   unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
2154 
2155   if (!this->emitSetLocal(*RT, TempOffset, E))
2156     return false;
2157 
2158   // Get LHS pointer, load its value and cast it to the
2159   // computation type if necessary.
2160   if (!visit(LHS))
2161     return false;
2162   if (!this->emitLoad(*LT, E))
2163     return false;
2164   if (LT != LHSComputationT) {
2165     if (!this->emitCast(*LT, *LHSComputationT, E))
2166       return false;
2167   }
2168 
2169   // Get the RHS value on the stack.
2170   if (!this->emitGetLocal(*RT, TempOffset, E))
2171     return false;
2172 
2173   // Perform operation.
2174   switch (E->getOpcode()) {
2175   case BO_AddAssign:
2176     if (!this->emitAdd(*LHSComputationT, E))
2177       return false;
2178     break;
2179   case BO_SubAssign:
2180     if (!this->emitSub(*LHSComputationT, E))
2181       return false;
2182     break;
2183   case BO_MulAssign:
2184     if (!this->emitMul(*LHSComputationT, E))
2185       return false;
2186     break;
2187   case BO_DivAssign:
2188     if (!this->emitDiv(*LHSComputationT, E))
2189       return false;
2190     break;
2191   case BO_RemAssign:
2192     if (!this->emitRem(*LHSComputationT, E))
2193       return false;
2194     break;
2195   case BO_ShlAssign:
2196     if (!this->emitShl(*LHSComputationT, *RT, E))
2197       return false;
2198     break;
2199   case BO_ShrAssign:
2200     if (!this->emitShr(*LHSComputationT, *RT, E))
2201       return false;
2202     break;
2203   case BO_AndAssign:
2204     if (!this->emitBitAnd(*LHSComputationT, E))
2205       return false;
2206     break;
2207   case BO_XorAssign:
2208     if (!this->emitBitXor(*LHSComputationT, E))
2209       return false;
2210     break;
2211   case BO_OrAssign:
2212     if (!this->emitBitOr(*LHSComputationT, E))
2213       return false;
2214     break;
2215   default:
2216     llvm_unreachable("Unimplemented compound assign operator");
2217   }
2218 
2219   // And now cast from LHSComputationT to ResultT.
2220   if (ResultT != LHSComputationT) {
2221     if (!this->emitCast(*LHSComputationT, *ResultT, E))
2222       return false;
2223   }
2224 
2225   // And store the result in LHS.
2226   if (DiscardResult) {
2227     if (LHS->refersToBitField())
2228       return this->emitStoreBitFieldPop(*ResultT, E);
2229     return this->emitStorePop(*ResultT, E);
2230   }
2231   if (LHS->refersToBitField())
2232     return this->emitStoreBitField(*ResultT, E);
2233   return this->emitStore(*ResultT, E);
2234 }
2235 
2236 template <class Emitter>
2237 bool Compiler<Emitter>::VisitExprWithCleanups(const ExprWithCleanups *E) {
2238   LocalScope<Emitter> ES(this);
2239   const Expr *SubExpr = E->getSubExpr();
2240 
2241   return this->delegate(SubExpr) && ES.destroyLocals(E);
2242 }
2243 
2244 template <class Emitter>
2245 bool Compiler<Emitter>::VisitMaterializeTemporaryExpr(
2246     const MaterializeTemporaryExpr *E) {
2247   const Expr *SubExpr = E->getSubExpr();
2248 
2249   if (Initializing) {
2250     // We already have a value, just initialize that.
2251     return this->delegate(SubExpr);
2252   }
2253   // If we don't end up using the materialized temporary anyway, don't
2254   // bother creating it.
2255   if (DiscardResult)
2256     return this->discard(SubExpr);
2257 
2258   // When we're initializing a global variable *or* the storage duration of
2259   // the temporary is explicitly static, create a global variable.
2260   std::optional<PrimType> SubExprT = classify(SubExpr);
2261   bool IsStatic = E->getStorageDuration() == SD_Static;
2262   if (IsStatic) {
2263     std::optional<unsigned> GlobalIndex = P.createGlobal(E);
2264     if (!GlobalIndex)
2265       return false;
2266 
2267     const LifetimeExtendedTemporaryDecl *TempDecl =
2268         E->getLifetimeExtendedTemporaryDecl();
2269     if (IsStatic)
2270       assert(TempDecl);
2271 
2272     if (SubExprT) {
2273       if (!this->visit(SubExpr))
2274         return false;
2275       if (IsStatic) {
2276         if (!this->emitInitGlobalTemp(*SubExprT, *GlobalIndex, TempDecl, E))
2277           return false;
2278       } else {
2279         if (!this->emitInitGlobal(*SubExprT, *GlobalIndex, E))
2280           return false;
2281       }
2282       return this->emitGetPtrGlobal(*GlobalIndex, E);
2283     }
2284 
2285     // Non-primitive values.
2286     if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2287       return false;
2288     if (!this->visitInitializer(SubExpr))
2289       return false;
2290     if (IsStatic)
2291       return this->emitInitGlobalTempComp(TempDecl, E);
2292     return true;
2293   }
2294 
2295   // For everyhing else, use local variables.
2296   if (SubExprT) {
2297     unsigned LocalIndex = allocateLocalPrimitive(
2298         SubExpr, *SubExprT, /*IsConst=*/true, /*IsExtended=*/true);
2299     if (!this->visit(SubExpr))
2300       return false;
2301     if (!this->emitSetLocal(*SubExprT, LocalIndex, E))
2302       return false;
2303     return this->emitGetPtrLocal(LocalIndex, E);
2304   } else {
2305     const Expr *Inner = E->getSubExpr()->skipRValueSubobjectAdjustments();
2306     if (std::optional<unsigned> LocalIndex =
2307             allocateLocal(Inner, E->getExtendingDecl())) {
2308       InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
2309       if (!this->emitGetPtrLocal(*LocalIndex, E))
2310         return false;
2311       return this->visitInitializer(SubExpr);
2312     }
2313   }
2314   return false;
2315 }
2316 
2317 template <class Emitter>
2318 bool Compiler<Emitter>::VisitCXXBindTemporaryExpr(
2319     const CXXBindTemporaryExpr *E) {
2320   return this->delegate(E->getSubExpr());
2321 }
2322 
2323 template <class Emitter>
2324 bool Compiler<Emitter>::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2325   const Expr *Init = E->getInitializer();
2326   if (DiscardResult)
2327     return this->discard(Init);
2328 
2329   if (Initializing) {
2330     // We already have a value, just initialize that.
2331     return this->visitInitializer(Init) && this->emitFinishInit(E);
2332   }
2333 
2334   std::optional<PrimType> T = classify(E->getType());
2335   if (E->isFileScope()) {
2336     // Avoid creating a variable if this is a primitive RValue anyway.
2337     if (T && !E->isLValue())
2338       return this->delegate(Init);
2339 
2340     if (std::optional<unsigned> GlobalIndex = P.createGlobal(E)) {
2341       if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2342         return false;
2343 
2344       if (T) {
2345         if (!this->visit(Init))
2346           return false;
2347         return this->emitInitGlobal(*T, *GlobalIndex, E);
2348       }
2349 
2350       return this->visitInitializer(Init) && this->emitFinishInit(E);
2351     }
2352 
2353     return false;
2354   }
2355 
2356   // Otherwise, use a local variable.
2357   if (T && !E->isLValue()) {
2358     // For primitive types, we just visit the initializer.
2359     return this->delegate(Init);
2360   } else {
2361     unsigned LocalIndex;
2362 
2363     if (T)
2364       LocalIndex = this->allocateLocalPrimitive(Init, *T, false, false);
2365     else if (std::optional<unsigned> MaybeIndex = this->allocateLocal(Init))
2366       LocalIndex = *MaybeIndex;
2367     else
2368       return false;
2369 
2370     if (!this->emitGetPtrLocal(LocalIndex, E))
2371       return false;
2372 
2373     if (T) {
2374       if (!this->visit(Init)) {
2375         return false;
2376       }
2377       return this->emitInit(*T, E);
2378     } else {
2379       if (!this->visitInitializer(Init) || !this->emitFinishInit(E))
2380         return false;
2381     }
2382     return true;
2383   }
2384 
2385   return false;
2386 }
2387 
2388 template <class Emitter>
2389 bool Compiler<Emitter>::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2390   if (DiscardResult)
2391     return true;
2392   if (E->getType()->isBooleanType())
2393     return this->emitConstBool(E->getValue(), E);
2394   return this->emitConst(E->getValue(), E);
2395 }
2396 
2397 template <class Emitter>
2398 bool Compiler<Emitter>::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2399   if (DiscardResult)
2400     return true;
2401   return this->emitConst(E->getValue(), E);
2402 }
2403 
2404 template <class Emitter>
2405 bool Compiler<Emitter>::VisitLambdaExpr(const LambdaExpr *E) {
2406   if (DiscardResult)
2407     return true;
2408 
2409   assert(Initializing);
2410   const Record *R = P.getOrCreateRecord(E->getLambdaClass());
2411 
2412   auto *CaptureInitIt = E->capture_init_begin();
2413   // Initialize all fields (which represent lambda captures) of the
2414   // record with their initializers.
2415   for (const Record::Field &F : R->fields()) {
2416     const Expr *Init = *CaptureInitIt;
2417     ++CaptureInitIt;
2418 
2419     if (!Init)
2420       continue;
2421 
2422     if (std::optional<PrimType> T = classify(Init)) {
2423       if (!this->visit(Init))
2424         return false;
2425 
2426       if (!this->emitInitField(*T, F.Offset, E))
2427         return false;
2428     } else {
2429       if (!this->emitGetPtrField(F.Offset, E))
2430         return false;
2431 
2432       if (!this->visitInitializer(Init))
2433         return false;
2434 
2435       if (!this->emitPopPtr(E))
2436         return false;
2437     }
2438   }
2439 
2440   return true;
2441 }
2442 
2443 template <class Emitter>
2444 bool Compiler<Emitter>::VisitPredefinedExpr(const PredefinedExpr *E) {
2445   if (DiscardResult)
2446     return true;
2447 
2448   return this->delegate(E->getFunctionName());
2449 }
2450 
2451 template <class Emitter>
2452 bool Compiler<Emitter>::VisitCXXThrowExpr(const CXXThrowExpr *E) {
2453   if (E->getSubExpr() && !this->discard(E->getSubExpr()))
2454     return false;
2455 
2456   return this->emitInvalid(E);
2457 }
2458 
2459 template <class Emitter>
2460 bool Compiler<Emitter>::VisitCXXReinterpretCastExpr(
2461     const CXXReinterpretCastExpr *E) {
2462   const Expr *SubExpr = E->getSubExpr();
2463 
2464   bool TypesMatch = classify(E) == classify(SubExpr);
2465   if (!this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/!TypesMatch, E))
2466     return false;
2467 
2468   return this->delegate(SubExpr);
2469 }
2470 
2471 template <class Emitter>
2472 bool Compiler<Emitter>::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2473   assert(E->getType()->isBooleanType());
2474 
2475   if (DiscardResult)
2476     return true;
2477   return this->emitConstBool(E->getValue(), E);
2478 }
2479 
2480 template <class Emitter>
2481 bool Compiler<Emitter>::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2482   QualType T = E->getType();
2483   assert(!classify(T));
2484 
2485   if (T->isRecordType()) {
2486     const CXXConstructorDecl *Ctor = E->getConstructor();
2487 
2488     // Trivial copy/move constructor. Avoid copy.
2489     if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
2490         Ctor->isTrivial() &&
2491         E->getArg(0)->isTemporaryObject(Ctx.getASTContext(),
2492                                         T->getAsCXXRecordDecl()))
2493       return this->visitInitializer(E->getArg(0));
2494 
2495     // If we're discarding a construct expression, we still need
2496     // to allocate a variable and call the constructor and destructor.
2497     if (DiscardResult) {
2498       if (Ctor->isTrivial())
2499         return true;
2500       assert(!Initializing);
2501       std::optional<unsigned> LocalIndex = allocateLocal(E);
2502 
2503       if (!LocalIndex)
2504         return false;
2505 
2506       if (!this->emitGetPtrLocal(*LocalIndex, E))
2507         return false;
2508     }
2509 
2510     // Zero initialization.
2511     if (E->requiresZeroInitialization()) {
2512       const Record *R = getRecord(E->getType());
2513 
2514       if (!this->visitZeroRecordInitializer(R, E))
2515         return false;
2516 
2517       // If the constructor is trivial anyway, we're done.
2518       if (Ctor->isTrivial())
2519         return true;
2520     }
2521 
2522     const Function *Func = getFunction(Ctor);
2523 
2524     if (!Func)
2525       return false;
2526 
2527     assert(Func->hasThisPointer());
2528     assert(!Func->hasRVO());
2529 
2530     //  The This pointer is already on the stack because this is an initializer,
2531     //  but we need to dup() so the call() below has its own copy.
2532     if (!this->emitDupPtr(E))
2533       return false;
2534 
2535     // Constructor arguments.
2536     for (const auto *Arg : E->arguments()) {
2537       if (!this->visit(Arg))
2538         return false;
2539     }
2540 
2541     if (Func->isVariadic()) {
2542       uint32_t VarArgSize = 0;
2543       unsigned NumParams = Func->getNumWrittenParams();
2544       for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) {
2545         VarArgSize +=
2546             align(primSize(classify(E->getArg(I)->getType()).value_or(PT_Ptr)));
2547       }
2548       if (!this->emitCallVar(Func, VarArgSize, E))
2549         return false;
2550     } else {
2551       if (!this->emitCall(Func, 0, E))
2552         return false;
2553     }
2554 
2555     if (DiscardResult)
2556       return this->emitPopPtr(E);
2557     return this->emitFinishInit(E);
2558   }
2559 
2560   if (T->isArrayType()) {
2561     const ConstantArrayType *CAT =
2562         Ctx.getASTContext().getAsConstantArrayType(E->getType());
2563     if (!CAT)
2564       return false;
2565 
2566     size_t NumElems = CAT->getZExtSize();
2567     const Function *Func = getFunction(E->getConstructor());
2568     if (!Func || !Func->isConstexpr())
2569       return false;
2570 
2571     // FIXME(perf): We're calling the constructor once per array element here,
2572     //   in the old intepreter we had a special-case for trivial constructors.
2573     for (size_t I = 0; I != NumElems; ++I) {
2574       if (!this->emitConstUint64(I, E))
2575         return false;
2576       if (!this->emitArrayElemPtrUint64(E))
2577         return false;
2578 
2579       // Constructor arguments.
2580       for (const auto *Arg : E->arguments()) {
2581         if (!this->visit(Arg))
2582           return false;
2583       }
2584 
2585       if (!this->emitCall(Func, 0, E))
2586         return false;
2587     }
2588     return true;
2589   }
2590 
2591   return false;
2592 }
2593 
2594 template <class Emitter>
2595 bool Compiler<Emitter>::VisitSourceLocExpr(const SourceLocExpr *E) {
2596   if (DiscardResult)
2597     return true;
2598 
2599   const APValue Val =
2600       E->EvaluateInContext(Ctx.getASTContext(), SourceLocDefaultExpr);
2601 
2602   // Things like __builtin_LINE().
2603   if (E->getType()->isIntegerType()) {
2604     assert(Val.isInt());
2605     const APSInt &I = Val.getInt();
2606     return this->emitConst(I, E);
2607   }
2608   // Otherwise, the APValue is an LValue, with only one element.
2609   // Theoretically, we don't need the APValue at all of course.
2610   assert(E->getType()->isPointerType());
2611   assert(Val.isLValue());
2612   const APValue::LValueBase &Base = Val.getLValueBase();
2613   if (const Expr *LValueExpr = Base.dyn_cast<const Expr *>())
2614     return this->visit(LValueExpr);
2615 
2616   // Otherwise, we have a decl (which is the case for
2617   // __builtin_source_location).
2618   assert(Base.is<const ValueDecl *>());
2619   assert(Val.getLValuePath().size() == 0);
2620   const auto *BaseDecl = Base.dyn_cast<const ValueDecl *>();
2621   assert(BaseDecl);
2622 
2623   auto *UGCD = cast<UnnamedGlobalConstantDecl>(BaseDecl);
2624 
2625   std::optional<unsigned> GlobalIndex = P.getOrCreateGlobal(UGCD);
2626   if (!GlobalIndex)
2627     return false;
2628 
2629   if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2630     return false;
2631 
2632   const Record *R = getRecord(E->getType());
2633   const APValue &V = UGCD->getValue();
2634   for (unsigned I = 0, N = R->getNumFields(); I != N; ++I) {
2635     const Record::Field *F = R->getField(I);
2636     const APValue &FieldValue = V.getStructField(I);
2637 
2638     PrimType FieldT = classifyPrim(F->Decl->getType());
2639 
2640     if (!this->visitAPValue(FieldValue, FieldT, E))
2641       return false;
2642     if (!this->emitInitField(FieldT, F->Offset, E))
2643       return false;
2644   }
2645 
2646   // Leave the pointer to the global on the stack.
2647   return true;
2648 }
2649 
2650 template <class Emitter>
2651 bool Compiler<Emitter>::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2652   unsigned N = E->getNumComponents();
2653   if (N == 0)
2654     return false;
2655 
2656   for (unsigned I = 0; I != N; ++I) {
2657     const OffsetOfNode &Node = E->getComponent(I);
2658     if (Node.getKind() == OffsetOfNode::Array) {
2659       const Expr *ArrayIndexExpr = E->getIndexExpr(Node.getArrayExprIndex());
2660       PrimType IndexT = classifyPrim(ArrayIndexExpr->getType());
2661 
2662       if (DiscardResult) {
2663         if (!this->discard(ArrayIndexExpr))
2664           return false;
2665         continue;
2666       }
2667 
2668       if (!this->visit(ArrayIndexExpr))
2669         return false;
2670       // Cast to Sint64.
2671       if (IndexT != PT_Sint64) {
2672         if (!this->emitCast(IndexT, PT_Sint64, E))
2673           return false;
2674       }
2675     }
2676   }
2677 
2678   if (DiscardResult)
2679     return true;
2680 
2681   PrimType T = classifyPrim(E->getType());
2682   return this->emitOffsetOf(T, E, E);
2683 }
2684 
2685 template <class Emitter>
2686 bool Compiler<Emitter>::VisitCXXScalarValueInitExpr(
2687     const CXXScalarValueInitExpr *E) {
2688   QualType Ty = E->getType();
2689 
2690   if (DiscardResult || Ty->isVoidType())
2691     return true;
2692 
2693   if (std::optional<PrimType> T = classify(Ty))
2694     return this->visitZeroInitializer(*T, Ty, E);
2695 
2696   if (const auto *CT = Ty->getAs<ComplexType>()) {
2697     if (!Initializing) {
2698       std::optional<unsigned> LocalIndex = allocateLocal(E);
2699       if (!LocalIndex)
2700         return false;
2701       if (!this->emitGetPtrLocal(*LocalIndex, E))
2702         return false;
2703     }
2704 
2705     // Initialize both fields to 0.
2706     QualType ElemQT = CT->getElementType();
2707     PrimType ElemT = classifyPrim(ElemQT);
2708 
2709     for (unsigned I = 0; I != 2; ++I) {
2710       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2711         return false;
2712       if (!this->emitInitElem(ElemT, I, E))
2713         return false;
2714     }
2715     return true;
2716   }
2717 
2718   if (const auto *VT = Ty->getAs<VectorType>()) {
2719     // FIXME: Code duplication with the _Complex case above.
2720     if (!Initializing) {
2721       std::optional<unsigned> LocalIndex = allocateLocal(E);
2722       if (!LocalIndex)
2723         return false;
2724       if (!this->emitGetPtrLocal(*LocalIndex, E))
2725         return false;
2726     }
2727 
2728     // Initialize all fields to 0.
2729     QualType ElemQT = VT->getElementType();
2730     PrimType ElemT = classifyPrim(ElemQT);
2731 
2732     for (unsigned I = 0, N = VT->getNumElements(); I != N; ++I) {
2733       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2734         return false;
2735       if (!this->emitInitElem(ElemT, I, E))
2736         return false;
2737     }
2738     return true;
2739   }
2740 
2741   return false;
2742 }
2743 
2744 template <class Emitter>
2745 bool Compiler<Emitter>::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2746   return this->emitConst(E->getPackLength(), E);
2747 }
2748 
2749 template <class Emitter>
2750 bool Compiler<Emitter>::VisitGenericSelectionExpr(
2751     const GenericSelectionExpr *E) {
2752   return this->delegate(E->getResultExpr());
2753 }
2754 
2755 template <class Emitter>
2756 bool Compiler<Emitter>::VisitChooseExpr(const ChooseExpr *E) {
2757   return this->delegate(E->getChosenSubExpr());
2758 }
2759 
2760 template <class Emitter>
2761 bool Compiler<Emitter>::VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
2762   if (DiscardResult)
2763     return true;
2764 
2765   return this->emitConst(E->getValue(), E);
2766 }
2767 
2768 template <class Emitter>
2769 bool Compiler<Emitter>::VisitCXXInheritedCtorInitExpr(
2770     const CXXInheritedCtorInitExpr *E) {
2771   const CXXConstructorDecl *Ctor = E->getConstructor();
2772   assert(!Ctor->isTrivial() &&
2773          "Trivial CXXInheritedCtorInitExpr, implement. (possible?)");
2774   const Function *F = this->getFunction(Ctor);
2775   assert(F);
2776   assert(!F->hasRVO());
2777   assert(F->hasThisPointer());
2778 
2779   if (!this->emitDupPtr(SourceInfo{}))
2780     return false;
2781 
2782   // Forward all arguments of the current function (which should be a
2783   // constructor itself) to the inherited ctor.
2784   // This is necessary because the calling code has pushed the pointer
2785   // of the correct base for  us already, but the arguments need
2786   // to come after.
2787   unsigned Offset = align(primSize(PT_Ptr)); // instance pointer.
2788   for (const ParmVarDecl *PD : Ctor->parameters()) {
2789     PrimType PT = this->classify(PD->getType()).value_or(PT_Ptr);
2790 
2791     if (!this->emitGetParam(PT, Offset, E))
2792       return false;
2793     Offset += align(primSize(PT));
2794   }
2795 
2796   return this->emitCall(F, 0, E);
2797 }
2798 
2799 template <class Emitter>
2800 bool Compiler<Emitter>::VisitCXXNewExpr(const CXXNewExpr *E) {
2801   assert(classifyPrim(E->getType()) == PT_Ptr);
2802   const Expr *Init = E->getInitializer();
2803   QualType ElementType = E->getAllocatedType();
2804   std::optional<PrimType> ElemT = classify(ElementType);
2805   unsigned PlacementArgs = E->getNumPlacementArgs();
2806   bool IsNoThrow = false;
2807 
2808   // FIXME: Better diagnostic. diag::note_constexpr_new_placement
2809   if (PlacementArgs != 0) {
2810     // The only new-placement list we support is of the form (std::nothrow).
2811     //
2812     // FIXME: There is no restriction on this, but it's not clear that any
2813     // other form makes any sense. We get here for cases such as:
2814     //
2815     //   new (std::align_val_t{N}) X(int)
2816     //
2817     // (which should presumably be valid only if N is a multiple of
2818     // alignof(int), and in any case can't be deallocated unless N is
2819     // alignof(X) and X has new-extended alignment).
2820     if (PlacementArgs != 1 || !E->getPlacementArg(0)->getType()->isNothrowT())
2821       return this->emitInvalid(E);
2822 
2823     if (!this->discard(E->getPlacementArg(0)))
2824       return false;
2825     IsNoThrow = true;
2826   }
2827 
2828   const Descriptor *Desc;
2829   if (ElemT) {
2830     if (E->isArray())
2831       Desc = nullptr; // We're not going to use it in this case.
2832     else
2833       Desc = P.createDescriptor(E, *ElemT, Descriptor::InlineDescMD,
2834                                 /*IsConst=*/false, /*IsTemporary=*/false,
2835                                 /*IsMutable=*/false);
2836   } else {
2837     Desc = P.createDescriptor(
2838         E, ElementType.getTypePtr(),
2839         E->isArray() ? std::nullopt : Descriptor::InlineDescMD,
2840         /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false, Init);
2841   }
2842 
2843   if (E->isArray()) {
2844     std::optional<const Expr *> ArraySizeExpr = E->getArraySize();
2845     if (!ArraySizeExpr)
2846       return false;
2847 
2848     const Expr *Stripped = *ArraySizeExpr;
2849     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
2850          Stripped = ICE->getSubExpr())
2851       if (ICE->getCastKind() != CK_NoOp &&
2852           ICE->getCastKind() != CK_IntegralCast)
2853         break;
2854 
2855     PrimType SizeT = classifyPrim(Stripped->getType());
2856 
2857     if (!this->visit(Stripped))
2858       return false;
2859 
2860     if (ElemT) {
2861       // N primitive elements.
2862       if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E))
2863         return false;
2864     } else {
2865       // N Composite elements.
2866       if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
2867         return false;
2868     }
2869 
2870     if (Init && !this->visitInitializer(Init))
2871       return false;
2872 
2873   } else {
2874     // Allocate just one element.
2875     if (!this->emitAlloc(Desc, E))
2876       return false;
2877 
2878     if (Init) {
2879       if (ElemT) {
2880         if (!this->visit(Init))
2881           return false;
2882 
2883         if (!this->emitInit(*ElemT, E))
2884           return false;
2885       } else {
2886         // Composite.
2887         if (!this->visitInitializer(Init))
2888           return false;
2889       }
2890     }
2891   }
2892 
2893   if (DiscardResult)
2894     return this->emitPopPtr(E);
2895 
2896   return true;
2897 }
2898 
2899 template <class Emitter>
2900 bool Compiler<Emitter>::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
2901   const Expr *Arg = E->getArgument();
2902 
2903   // Arg must be an lvalue.
2904   if (!this->visit(Arg))
2905     return false;
2906 
2907   return this->emitFree(E->isArrayForm(), E);
2908 }
2909 
2910 template <class Emitter>
2911 bool Compiler<Emitter>::VisitBlockExpr(const BlockExpr *E) {
2912   const Function *Func = nullptr;
2913   if (auto F = Compiler<ByteCodeEmitter>(Ctx, P).compileObjCBlock(E))
2914     Func = F;
2915 
2916   if (!Func)
2917     return false;
2918   return this->emitGetFnPtr(Func, E);
2919 }
2920 
2921 template <class Emitter>
2922 bool Compiler<Emitter>::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2923   assert(Ctx.getLangOpts().CPlusPlus);
2924   return this->emitConstBool(E->getValue(), E);
2925 }
2926 
2927 template <class Emitter>
2928 bool Compiler<Emitter>::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2929   if (DiscardResult)
2930     return true;
2931   assert(!Initializing);
2932 
2933   const MSGuidDecl *GuidDecl = E->getGuidDecl();
2934   const RecordDecl *RD = GuidDecl->getType()->getAsRecordDecl();
2935   assert(RD);
2936   // If the definiton of the result type is incomplete, just return a dummy.
2937   // If (and when) that is read from, we will fail, but not now.
2938   if (!RD->isCompleteDefinition()) {
2939     if (std::optional<unsigned> I = P.getOrCreateDummy(GuidDecl))
2940       return this->emitGetPtrGlobal(*I, E);
2941     return false;
2942   }
2943 
2944   std::optional<unsigned> GlobalIndex = P.getOrCreateGlobal(GuidDecl);
2945   if (!GlobalIndex)
2946     return false;
2947   if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2948     return false;
2949 
2950   assert(this->getRecord(E->getType()));
2951 
2952   const APValue &V = GuidDecl->getAsAPValue();
2953   if (V.getKind() == APValue::None)
2954     return true;
2955 
2956   assert(V.isStruct());
2957   assert(V.getStructNumBases() == 0);
2958   if (!this->visitAPValueInitializer(V, E))
2959     return false;
2960 
2961   return this->emitFinishInit(E);
2962 }
2963 
2964 template <class Emitter>
2965 bool Compiler<Emitter>::VisitRequiresExpr(const RequiresExpr *E) {
2966   assert(classifyPrim(E->getType()) == PT_Bool);
2967   if (DiscardResult)
2968     return true;
2969   return this->emitConstBool(E->isSatisfied(), E);
2970 }
2971 
2972 template <class Emitter>
2973 bool Compiler<Emitter>::VisitConceptSpecializationExpr(
2974     const ConceptSpecializationExpr *E) {
2975   assert(classifyPrim(E->getType()) == PT_Bool);
2976   if (DiscardResult)
2977     return true;
2978   return this->emitConstBool(E->isSatisfied(), E);
2979 }
2980 
2981 template <class Emitter>
2982 bool Compiler<Emitter>::VisitCXXRewrittenBinaryOperator(
2983     const CXXRewrittenBinaryOperator *E) {
2984   return this->delegate(E->getSemanticForm());
2985 }
2986 
2987 template <class Emitter>
2988 bool Compiler<Emitter>::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2989 
2990   for (const Expr *SemE : E->semantics()) {
2991     if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
2992       if (SemE == E->getResultExpr())
2993         return false;
2994 
2995       if (OVE->isUnique())
2996         continue;
2997 
2998       if (!this->discard(OVE))
2999         return false;
3000     } else if (SemE == E->getResultExpr()) {
3001       if (!this->delegate(SemE))
3002         return false;
3003     } else {
3004       if (!this->discard(SemE))
3005         return false;
3006     }
3007   }
3008   return true;
3009 }
3010 
3011 template <class Emitter>
3012 bool Compiler<Emitter>::VisitPackIndexingExpr(const PackIndexingExpr *E) {
3013   return this->delegate(E->getSelectedExpr());
3014 }
3015 
3016 template <class Emitter>
3017 bool Compiler<Emitter>::VisitRecoveryExpr(const RecoveryExpr *E) {
3018   return this->emitError(E);
3019 }
3020 
3021 template <class Emitter>
3022 bool Compiler<Emitter>::VisitAddrLabelExpr(const AddrLabelExpr *E) {
3023   assert(E->getType()->isVoidPointerType());
3024 
3025   unsigned Offset = allocateLocalPrimitive(
3026       E->getLabel(), PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false);
3027 
3028   return this->emitGetLocal(PT_Ptr, Offset, E);
3029 }
3030 
3031 template <class Emitter>
3032 bool Compiler<Emitter>::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
3033   assert(Initializing);
3034   const auto *VT = E->getType()->castAs<VectorType>();
3035   QualType ElemType = VT->getElementType();
3036   PrimType ElemT = classifyPrim(ElemType);
3037   const Expr *Src = E->getSrcExpr();
3038   PrimType SrcElemT =
3039       classifyPrim(Src->getType()->castAs<VectorType>()->getElementType());
3040 
3041   unsigned SrcOffset = this->allocateLocalPrimitive(Src, PT_Ptr, true, false);
3042   if (!this->visit(Src))
3043     return false;
3044   if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
3045     return false;
3046 
3047   for (unsigned I = 0; I != VT->getNumElements(); ++I) {
3048     if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
3049       return false;
3050     if (!this->emitArrayElemPop(SrcElemT, I, E))
3051       return false;
3052     if (SrcElemT != ElemT) {
3053       if (!this->emitPrimCast(SrcElemT, ElemT, ElemType, E))
3054         return false;
3055     }
3056     if (!this->emitInitElem(ElemT, I, E))
3057       return false;
3058   }
3059 
3060   return true;
3061 }
3062 
3063 template <class Emitter>
3064 bool Compiler<Emitter>::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
3065   assert(Initializing);
3066   assert(E->getNumSubExprs() > 2);
3067 
3068   const Expr *Vecs[] = {E->getExpr(0), E->getExpr(1)};
3069   const VectorType *VT = Vecs[0]->getType()->castAs<VectorType>();
3070   PrimType ElemT = classifyPrim(VT->getElementType());
3071   unsigned NumInputElems = VT->getNumElements();
3072   unsigned NumOutputElems = E->getNumSubExprs() - 2;
3073   assert(NumOutputElems > 0);
3074 
3075   // Save both input vectors to a local variable.
3076   unsigned VectorOffsets[2];
3077   for (unsigned I = 0; I != 2; ++I) {
3078     VectorOffsets[I] = this->allocateLocalPrimitive(
3079         Vecs[I], PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false);
3080     if (!this->visit(Vecs[I]))
3081       return false;
3082     if (!this->emitSetLocal(PT_Ptr, VectorOffsets[I], E))
3083       return false;
3084   }
3085   for (unsigned I = 0; I != NumOutputElems; ++I) {
3086     APSInt ShuffleIndex = E->getShuffleMaskIdx(Ctx.getASTContext(), I);
3087     if (ShuffleIndex == -1)
3088       return this->emitInvalid(E); // FIXME: Better diagnostic.
3089 
3090     assert(ShuffleIndex < (NumInputElems * 2));
3091     if (!this->emitGetLocal(PT_Ptr,
3092                             VectorOffsets[ShuffleIndex >= NumInputElems], E))
3093       return false;
3094     unsigned InputVectorIndex = ShuffleIndex.getZExtValue() % NumInputElems;
3095     if (!this->emitArrayElemPop(ElemT, InputVectorIndex, E))
3096       return false;
3097 
3098     if (!this->emitInitElem(ElemT, I, E))
3099       return false;
3100   }
3101 
3102   return true;
3103 }
3104 
3105 template <class Emitter>
3106 bool Compiler<Emitter>::VisitExtVectorElementExpr(
3107     const ExtVectorElementExpr *E) {
3108   const Expr *Base = E->getBase();
3109   assert(
3110       Base->getType()->isVectorType() ||
3111       Base->getType()->getAs<PointerType>()->getPointeeType()->isVectorType());
3112 
3113   SmallVector<uint32_t, 4> Indices;
3114   E->getEncodedElementAccess(Indices);
3115 
3116   if (Indices.size() == 1) {
3117     if (!this->visit(Base))
3118       return false;
3119 
3120     if (E->isGLValue()) {
3121       if (!this->emitConstUint32(Indices[0], E))
3122         return false;
3123       return this->emitArrayElemPtrPop(PT_Uint32, E);
3124     }
3125     // Else, also load the value.
3126     return this->emitArrayElemPop(classifyPrim(E->getType()), Indices[0], E);
3127   }
3128 
3129   // Create a local variable for the base.
3130   unsigned BaseOffset = allocateLocalPrimitive(Base, PT_Ptr, /*IsConst=*/true,
3131                                                /*IsExtended=*/false);
3132   if (!this->visit(Base))
3133     return false;
3134   if (!this->emitSetLocal(PT_Ptr, BaseOffset, E))
3135     return false;
3136 
3137   // Now the vector variable for the return value.
3138   if (!Initializing) {
3139     std::optional<unsigned> ResultIndex;
3140     ResultIndex = allocateLocal(E);
3141     if (!ResultIndex)
3142       return false;
3143     if (!this->emitGetPtrLocal(*ResultIndex, E))
3144       return false;
3145   }
3146 
3147   assert(Indices.size() == E->getType()->getAs<VectorType>()->getNumElements());
3148 
3149   PrimType ElemT =
3150       classifyPrim(E->getType()->getAs<VectorType>()->getElementType());
3151   uint32_t DstIndex = 0;
3152   for (uint32_t I : Indices) {
3153     if (!this->emitGetLocal(PT_Ptr, BaseOffset, E))
3154       return false;
3155     if (!this->emitArrayElemPop(ElemT, I, E))
3156       return false;
3157     if (!this->emitInitElem(ElemT, DstIndex, E))
3158       return false;
3159     ++DstIndex;
3160   }
3161 
3162   // Leave the result pointer on the stack.
3163   assert(!DiscardResult);
3164   return true;
3165 }
3166 
3167 template <class Emitter>
3168 bool Compiler<Emitter>::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
3169   const Expr *SubExpr = E->getSubExpr();
3170   if (!E->isExpressibleAsConstantInitializer())
3171     return this->discard(SubExpr) && this->emitInvalid(E);
3172 
3173   return this->delegate(SubExpr);
3174 }
3175 
3176 template <class Emitter>
3177 bool Compiler<Emitter>::VisitCXXStdInitializerListExpr(
3178     const CXXStdInitializerListExpr *E) {
3179   const Expr *SubExpr = E->getSubExpr();
3180   const ConstantArrayType *ArrayType =
3181       Ctx.getASTContext().getAsConstantArrayType(SubExpr->getType());
3182   const Record *R = getRecord(E->getType());
3183   assert(Initializing);
3184   assert(SubExpr->isGLValue());
3185 
3186   if (!this->visit(SubExpr))
3187     return false;
3188   if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
3189     return false;
3190 
3191   PrimType SecondFieldT = classifyPrim(R->getField(1u)->Decl->getType());
3192   if (isIntegralType(SecondFieldT)) {
3193     if (!this->emitConst(static_cast<APSInt>(ArrayType->getSize()),
3194                          SecondFieldT, E))
3195       return false;
3196     return this->emitInitField(SecondFieldT, R->getField(1u)->Offset, E);
3197   }
3198   assert(SecondFieldT == PT_Ptr);
3199 
3200   if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
3201     return false;
3202   if (!this->emitConst(static_cast<APSInt>(ArrayType->getSize()), PT_Uint64, E))
3203     return false;
3204   if (!this->emitArrayElemPtrPop(PT_Uint64, E))
3205     return false;
3206   return this->emitInitFieldPtr(R->getField(1u)->Offset, E);
3207 }
3208 
3209 template <class Emitter>
3210 bool Compiler<Emitter>::VisitStmtExpr(const StmtExpr *E) {
3211   BlockScope<Emitter> BS(this);
3212   StmtExprScope<Emitter> SS(this);
3213 
3214   const CompoundStmt *CS = E->getSubStmt();
3215   const Stmt *Result = CS->getStmtExprResult();
3216   for (const Stmt *S : CS->body()) {
3217     if (S != Result) {
3218       if (!this->visitStmt(S))
3219         return false;
3220       continue;
3221     }
3222 
3223     assert(S == Result);
3224     if (const Expr *ResultExpr = dyn_cast<Expr>(S))
3225       return this->delegate(ResultExpr);
3226     return this->emitUnsupported(E);
3227   }
3228 
3229   return BS.destroyLocals();
3230 }
3231 
3232 template <class Emitter> bool Compiler<Emitter>::discard(const Expr *E) {
3233   OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true,
3234                              /*NewInitializing=*/false);
3235   return this->Visit(E);
3236 }
3237 
3238 template <class Emitter> bool Compiler<Emitter>::delegate(const Expr *E) {
3239   if (E->containsErrors())
3240     return this->emitError(E);
3241 
3242   // We're basically doing:
3243   // OptionScope<Emitter> Scope(this, DicardResult, Initializing);
3244   // but that's unnecessary of course.
3245   return this->Visit(E);
3246 }
3247 
3248 template <class Emitter> bool Compiler<Emitter>::visit(const Expr *E) {
3249   if (E->getType().isNull())
3250     return false;
3251 
3252   // Create local variable to hold the return value.
3253   if (!E->getType()->isVoidType() && !E->isGLValue() &&
3254       !E->getType()->isAnyComplexType() && !classify(E->getType())) {
3255     std::optional<unsigned> LocalIndex = allocateLocal(E);
3256     if (!LocalIndex)
3257       return false;
3258 
3259     if (!this->emitGetPtrLocal(*LocalIndex, E))
3260       return false;
3261     return this->visitInitializer(E);
3262   }
3263 
3264   //  Otherwise,we have a primitive return value, produce the value directly
3265   //  and push it on the stack.
3266   OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
3267                              /*NewInitializing=*/false);
3268   return this->Visit(E);
3269 }
3270 
3271 template <class Emitter>
3272 bool Compiler<Emitter>::visitInitializer(const Expr *E) {
3273   assert(!classify(E->getType()));
3274 
3275   if (E->containsErrors())
3276     return this->emitError(E);
3277 
3278   if (!this->checkLiteralType(E))
3279     return false;
3280 
3281   OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
3282                              /*NewInitializing=*/true);
3283   return this->Visit(E);
3284 }
3285 
3286 template <class Emitter> bool Compiler<Emitter>::visitBool(const Expr *E) {
3287   std::optional<PrimType> T = classify(E->getType());
3288   if (!T) {
3289     // Convert complex values to bool.
3290     if (E->getType()->isAnyComplexType()) {
3291       if (!this->visit(E))
3292         return false;
3293       return this->emitComplexBoolCast(E);
3294     }
3295     return false;
3296   }
3297 
3298   if (!this->visit(E))
3299     return false;
3300 
3301   if (T == PT_Bool)
3302     return true;
3303 
3304   // Convert pointers to bool.
3305   if (T == PT_Ptr || T == PT_FnPtr) {
3306     if (!this->emitNull(*T, nullptr, E))
3307       return false;
3308     return this->emitNE(*T, E);
3309   }
3310 
3311   // Or Floats.
3312   if (T == PT_Float)
3313     return this->emitCastFloatingIntegralBool(E);
3314 
3315   // Or anything else we can.
3316   return this->emitCast(*T, PT_Bool, E);
3317 }
3318 
3319 template <class Emitter>
3320 bool Compiler<Emitter>::visitZeroInitializer(PrimType T, QualType QT,
3321                                              const Expr *E) {
3322   switch (T) {
3323   case PT_Bool:
3324     return this->emitZeroBool(E);
3325   case PT_Sint8:
3326     return this->emitZeroSint8(E);
3327   case PT_Uint8:
3328     return this->emitZeroUint8(E);
3329   case PT_Sint16:
3330     return this->emitZeroSint16(E);
3331   case PT_Uint16:
3332     return this->emitZeroUint16(E);
3333   case PT_Sint32:
3334     return this->emitZeroSint32(E);
3335   case PT_Uint32:
3336     return this->emitZeroUint32(E);
3337   case PT_Sint64:
3338     return this->emitZeroSint64(E);
3339   case PT_Uint64:
3340     return this->emitZeroUint64(E);
3341   case PT_IntAP:
3342     return this->emitZeroIntAP(Ctx.getBitWidth(QT), E);
3343   case PT_IntAPS:
3344     return this->emitZeroIntAPS(Ctx.getBitWidth(QT), E);
3345   case PT_Ptr:
3346     return this->emitNullPtr(nullptr, E);
3347   case PT_FnPtr:
3348     return this->emitNullFnPtr(nullptr, E);
3349   case PT_MemberPtr:
3350     return this->emitNullMemberPtr(nullptr, E);
3351   case PT_Float: {
3352     return this->emitConstFloat(APFloat::getZero(Ctx.getFloatSemantics(QT)), E);
3353   }
3354   }
3355   llvm_unreachable("unknown primitive type");
3356 }
3357 
3358 template <class Emitter>
3359 bool Compiler<Emitter>::visitZeroRecordInitializer(const Record *R,
3360                                                    const Expr *E) {
3361   assert(E);
3362   assert(R);
3363   // Fields
3364   for (const Record::Field &Field : R->fields()) {
3365     if (Field.Decl->isUnnamedBitField())
3366       continue;
3367 
3368     const Descriptor *D = Field.Desc;
3369     if (D->isPrimitive()) {
3370       QualType QT = D->getType();
3371       PrimType T = classifyPrim(D->getType());
3372       if (!this->visitZeroInitializer(T, QT, E))
3373         return false;
3374       if (!this->emitInitField(T, Field.Offset, E))
3375         return false;
3376       if (R->isUnion())
3377         break;
3378       continue;
3379     }
3380 
3381     if (!this->emitGetPtrField(Field.Offset, E))
3382       return false;
3383 
3384     if (D->isPrimitiveArray()) {
3385       QualType ET = D->getElemQualType();
3386       PrimType T = classifyPrim(ET);
3387       for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
3388         if (!this->visitZeroInitializer(T, ET, E))
3389           return false;
3390         if (!this->emitInitElem(T, I, E))
3391           return false;
3392       }
3393     } else if (D->isCompositeArray()) {
3394       const Record *ElemRecord = D->ElemDesc->ElemRecord;
3395       assert(D->ElemDesc->ElemRecord);
3396       for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
3397         if (!this->emitConstUint32(I, E))
3398           return false;
3399         if (!this->emitArrayElemPtr(PT_Uint32, E))
3400           return false;
3401         if (!this->visitZeroRecordInitializer(ElemRecord, E))
3402           return false;
3403         if (!this->emitPopPtr(E))
3404           return false;
3405       }
3406     } else if (D->isRecord()) {
3407       if (!this->visitZeroRecordInitializer(D->ElemRecord, E))
3408         return false;
3409     } else {
3410       assert(false);
3411     }
3412 
3413     if (!this->emitFinishInitPop(E))
3414       return false;
3415 
3416     if (R->isUnion())
3417       break;
3418   }
3419 
3420   for (const Record::Base &B : R->bases()) {
3421     if (!this->emitGetPtrBase(B.Offset, E))
3422       return false;
3423     if (!this->visitZeroRecordInitializer(B.R, E))
3424       return false;
3425     if (!this->emitFinishInitPop(E))
3426       return false;
3427   }
3428 
3429   // FIXME: Virtual bases.
3430 
3431   return true;
3432 }
3433 
3434 template <class Emitter>
3435 template <typename T>
3436 bool Compiler<Emitter>::emitConst(T Value, PrimType Ty, const Expr *E) {
3437   switch (Ty) {
3438   case PT_Sint8:
3439     return this->emitConstSint8(Value, E);
3440   case PT_Uint8:
3441     return this->emitConstUint8(Value, E);
3442   case PT_Sint16:
3443     return this->emitConstSint16(Value, E);
3444   case PT_Uint16:
3445     return this->emitConstUint16(Value, E);
3446   case PT_Sint32:
3447     return this->emitConstSint32(Value, E);
3448   case PT_Uint32:
3449     return this->emitConstUint32(Value, E);
3450   case PT_Sint64:
3451     return this->emitConstSint64(Value, E);
3452   case PT_Uint64:
3453     return this->emitConstUint64(Value, E);
3454   case PT_Bool:
3455     return this->emitConstBool(Value, E);
3456   case PT_Ptr:
3457   case PT_FnPtr:
3458   case PT_MemberPtr:
3459   case PT_Float:
3460   case PT_IntAP:
3461   case PT_IntAPS:
3462     llvm_unreachable("Invalid integral type");
3463     break;
3464   }
3465   llvm_unreachable("unknown primitive type");
3466 }
3467 
3468 template <class Emitter>
3469 template <typename T>
3470 bool Compiler<Emitter>::emitConst(T Value, const Expr *E) {
3471   return this->emitConst(Value, classifyPrim(E->getType()), E);
3472 }
3473 
3474 template <class Emitter>
3475 bool Compiler<Emitter>::emitConst(const APSInt &Value, PrimType Ty,
3476                                   const Expr *E) {
3477   if (Ty == PT_IntAPS)
3478     return this->emitConstIntAPS(Value, E);
3479   if (Ty == PT_IntAP)
3480     return this->emitConstIntAP(Value, E);
3481 
3482   if (Value.isSigned())
3483     return this->emitConst(Value.getSExtValue(), Ty, E);
3484   return this->emitConst(Value.getZExtValue(), Ty, E);
3485 }
3486 
3487 template <class Emitter>
3488 bool Compiler<Emitter>::emitConst(const APSInt &Value, const Expr *E) {
3489   return this->emitConst(Value, classifyPrim(E->getType()), E);
3490 }
3491 
3492 template <class Emitter>
3493 unsigned Compiler<Emitter>::allocateLocalPrimitive(DeclTy &&Src, PrimType Ty,
3494                                                    bool IsConst,
3495                                                    bool IsExtended) {
3496   // Make sure we don't accidentally register the same decl twice.
3497   if (const auto *VD =
3498           dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
3499     assert(!P.getGlobal(VD));
3500     assert(!Locals.contains(VD));
3501     (void)VD;
3502   }
3503 
3504   // FIXME: There are cases where Src.is<Expr*>() is wrong, e.g.
3505   //   (int){12} in C. Consider using Expr::isTemporaryObject() instead
3506   //   or isa<MaterializeTemporaryExpr>().
3507   Descriptor *D = P.createDescriptor(Src, Ty, Descriptor::InlineDescMD, IsConst,
3508                                      Src.is<const Expr *>());
3509   Scope::Local Local = this->createLocal(D);
3510   if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>()))
3511     Locals.insert({VD, Local});
3512   VarScope->add(Local, IsExtended);
3513   return Local.Offset;
3514 }
3515 
3516 template <class Emitter>
3517 std::optional<unsigned>
3518 Compiler<Emitter>::allocateLocal(DeclTy &&Src, const ValueDecl *ExtendingDecl) {
3519   // Make sure we don't accidentally register the same decl twice.
3520   if ([[maybe_unused]] const auto *VD =
3521           dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
3522     assert(!P.getGlobal(VD));
3523     assert(!Locals.contains(VD));
3524   }
3525 
3526   QualType Ty;
3527   const ValueDecl *Key = nullptr;
3528   const Expr *Init = nullptr;
3529   bool IsTemporary = false;
3530   if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
3531     Key = VD;
3532     Ty = VD->getType();
3533 
3534     if (const auto *VarD = dyn_cast<VarDecl>(VD))
3535       Init = VarD->getInit();
3536   }
3537   if (auto *E = Src.dyn_cast<const Expr *>()) {
3538     IsTemporary = true;
3539     Ty = E->getType();
3540   }
3541 
3542   Descriptor *D = P.createDescriptor(
3543       Src, Ty.getTypePtr(), Descriptor::InlineDescMD, Ty.isConstQualified(),
3544       IsTemporary, /*IsMutable=*/false, Init);
3545   if (!D)
3546     return std::nullopt;
3547 
3548   Scope::Local Local = this->createLocal(D);
3549   if (Key)
3550     Locals.insert({Key, Local});
3551   if (ExtendingDecl)
3552     VarScope->addExtended(Local, ExtendingDecl);
3553   else
3554     VarScope->add(Local, false);
3555   return Local.Offset;
3556 }
3557 
3558 template <class Emitter>
3559 unsigned Compiler<Emitter>::allocateTemporary(const Expr *E) {
3560   QualType Ty = E->getType();
3561   assert(!Ty->isRecordType());
3562 
3563   Descriptor *D = P.createDescriptor(
3564       E, Ty.getTypePtr(), Descriptor::InlineDescMD, Ty.isConstQualified(),
3565       /*IsTemporary=*/true, /*IsMutable=*/false, /*Init=*/nullptr);
3566   assert(D);
3567 
3568   Scope::Local Local = this->createLocal(D);
3569   VariableScope<Emitter> *S = VarScope;
3570   assert(S);
3571   // Attach to topmost scope.
3572   while (S->getParent())
3573     S = S->getParent();
3574   assert(S && !S->getParent());
3575   S->addLocal(Local);
3576   return Local.Offset;
3577 }
3578 
3579 template <class Emitter>
3580 const RecordType *Compiler<Emitter>::getRecordTy(QualType Ty) {
3581   if (const PointerType *PT = dyn_cast<PointerType>(Ty))
3582     return PT->getPointeeType()->getAs<RecordType>();
3583   return Ty->getAs<RecordType>();
3584 }
3585 
3586 template <class Emitter> Record *Compiler<Emitter>::getRecord(QualType Ty) {
3587   if (const auto *RecordTy = getRecordTy(Ty))
3588     return getRecord(RecordTy->getDecl());
3589   return nullptr;
3590 }
3591 
3592 template <class Emitter>
3593 Record *Compiler<Emitter>::getRecord(const RecordDecl *RD) {
3594   return P.getOrCreateRecord(RD);
3595 }
3596 
3597 template <class Emitter>
3598 const Function *Compiler<Emitter>::getFunction(const FunctionDecl *FD) {
3599   return Ctx.getOrCreateFunction(FD);
3600 }
3601 
3602 template <class Emitter> bool Compiler<Emitter>::visitExpr(const Expr *E) {
3603   LocalScope<Emitter> RootScope(this);
3604   // Void expressions.
3605   if (E->getType()->isVoidType()) {
3606     if (!visit(E))
3607       return false;
3608     return this->emitRetVoid(E) && RootScope.destroyLocals();
3609   }
3610 
3611   // Expressions with a primitive return type.
3612   if (std::optional<PrimType> T = classify(E)) {
3613     if (!visit(E))
3614       return false;
3615     return this->emitRet(*T, E) && RootScope.destroyLocals();
3616   }
3617 
3618   // Expressions with a composite return type.
3619   // For us, that means everything we don't
3620   // have a PrimType for.
3621   if (std::optional<unsigned> LocalOffset = this->allocateLocal(E)) {
3622     if (!this->emitGetPtrLocal(*LocalOffset, E))
3623       return false;
3624 
3625     if (!visitInitializer(E))
3626       return false;
3627 
3628     if (!this->emitFinishInit(E))
3629       return false;
3630     // We are destroying the locals AFTER the Ret op.
3631     // The Ret op needs to copy the (alive) values, but the
3632     // destructors may still turn the entire expression invalid.
3633     return this->emitRetValue(E) && RootScope.destroyLocals();
3634   }
3635 
3636   RootScope.destroyLocals();
3637   return false;
3638 }
3639 
3640 template <class Emitter>
3641 VarCreationState Compiler<Emitter>::visitDecl(const VarDecl *VD) {
3642 
3643   auto R = this->visitVarDecl(VD, /*Toplevel=*/true);
3644 
3645   if (R.notCreated())
3646     return R;
3647 
3648   if (R)
3649     return true;
3650 
3651   if (!R && Context::shouldBeGloballyIndexed(VD)) {
3652     if (auto GlobalIndex = P.getGlobal(VD)) {
3653       Block *GlobalBlock = P.getGlobal(*GlobalIndex);
3654       GlobalInlineDescriptor &GD =
3655           *reinterpret_cast<GlobalInlineDescriptor *>(GlobalBlock->rawData());
3656 
3657       GD.InitState = GlobalInitState::InitializerFailed;
3658       GlobalBlock->invokeDtor();
3659     }
3660   }
3661 
3662   return R;
3663 }
3664 
3665 /// Toplevel visitDeclAndReturn().
3666 /// We get here from evaluateAsInitializer().
3667 /// We need to evaluate the initializer and return its value.
3668 template <class Emitter>
3669 bool Compiler<Emitter>::visitDeclAndReturn(const VarDecl *VD,
3670                                            bool ConstantContext) {
3671   std::optional<PrimType> VarT = classify(VD->getType());
3672 
3673   // We only create variables if we're evaluating in a constant context.
3674   // Otherwise, just evaluate the initializer and return it.
3675   if (!ConstantContext) {
3676     DeclScope<Emitter> LS(this, VD);
3677     if (!this->visit(VD->getAnyInitializer()))
3678       return false;
3679     return this->emitRet(VarT.value_or(PT_Ptr), VD) && LS.destroyLocals();
3680   }
3681 
3682   LocalScope<Emitter> VDScope(this, VD);
3683   if (!this->visitVarDecl(VD, /*Toplevel=*/true))
3684     return false;
3685 
3686   if (Context::shouldBeGloballyIndexed(VD)) {
3687     auto GlobalIndex = P.getGlobal(VD);
3688     assert(GlobalIndex); // visitVarDecl() didn't return false.
3689     if (VarT) {
3690       if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
3691         return false;
3692     } else {
3693       if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
3694         return false;
3695     }
3696   } else {
3697     auto Local = Locals.find(VD);
3698     assert(Local != Locals.end()); // Same here.
3699     if (VarT) {
3700       if (!this->emitGetLocal(*VarT, Local->second.Offset, VD))
3701         return false;
3702     } else {
3703       if (!this->emitGetPtrLocal(Local->second.Offset, VD))
3704         return false;
3705     }
3706   }
3707 
3708   // Return the value.
3709   if (!this->emitRet(VarT.value_or(PT_Ptr), VD)) {
3710     // If the Ret above failed and this is a global variable, mark it as
3711     // uninitialized, even everything else succeeded.
3712     if (Context::shouldBeGloballyIndexed(VD)) {
3713       auto GlobalIndex = P.getGlobal(VD);
3714       assert(GlobalIndex);
3715       Block *GlobalBlock = P.getGlobal(*GlobalIndex);
3716       GlobalInlineDescriptor &GD =
3717           *reinterpret_cast<GlobalInlineDescriptor *>(GlobalBlock->rawData());
3718 
3719       GD.InitState = GlobalInitState::InitializerFailed;
3720       GlobalBlock->invokeDtor();
3721     }
3722     return false;
3723   }
3724 
3725   return VDScope.destroyLocals();
3726 }
3727 
3728 template <class Emitter>
3729 VarCreationState Compiler<Emitter>::visitVarDecl(const VarDecl *VD,
3730                                                  bool Toplevel) {
3731   // We don't know what to do with these, so just return false.
3732   if (VD->getType().isNull())
3733     return false;
3734 
3735   // This case is EvalEmitter-only. If we won't create any instructions for the
3736   // initializer anyway, don't bother creating the variable in the first place.
3737   if (!this->isActive())
3738     return VarCreationState::NotCreated();
3739 
3740   const Expr *Init = VD->getInit();
3741   std::optional<PrimType> VarT = classify(VD->getType());
3742 
3743   if (Init && Init->isValueDependent())
3744     return false;
3745 
3746   if (Context::shouldBeGloballyIndexed(VD)) {
3747     auto checkDecl = [&]() -> bool {
3748       bool NeedsOp = !Toplevel && VD->isLocalVarDecl() && VD->isStaticLocal();
3749       return !NeedsOp || this->emitCheckDecl(VD, VD);
3750     };
3751 
3752     auto initGlobal = [&](unsigned GlobalIndex) -> bool {
3753       assert(Init);
3754       DeclScope<Emitter> LocalScope(this, VD);
3755 
3756       if (VarT) {
3757         if (!this->visit(Init))
3758           return checkDecl() && false;
3759 
3760         return checkDecl() && this->emitInitGlobal(*VarT, GlobalIndex, VD);
3761       }
3762 
3763       if (!checkDecl())
3764         return false;
3765 
3766       if (!this->emitGetPtrGlobal(GlobalIndex, Init))
3767         return false;
3768 
3769       if (!visitInitializer(Init))
3770         return false;
3771 
3772       if (!this->emitFinishInit(Init))
3773         return false;
3774 
3775       return this->emitPopPtr(Init);
3776     };
3777 
3778     // We've already seen and initialized this global.
3779     if (std::optional<unsigned> GlobalIndex = P.getGlobal(VD)) {
3780       if (P.getPtrGlobal(*GlobalIndex).isInitialized())
3781         return checkDecl();
3782 
3783       // The previous attempt at initialization might've been unsuccessful,
3784       // so let's try this one.
3785       return Init && checkDecl() && initGlobal(*GlobalIndex);
3786     }
3787 
3788     std::optional<unsigned> GlobalIndex = P.createGlobal(VD, Init);
3789 
3790     if (!GlobalIndex)
3791       return false;
3792 
3793     return !Init || (checkDecl() && initGlobal(*GlobalIndex));
3794   } else {
3795     InitLinkScope<Emitter> ILS(this, InitLink::Decl(VD));
3796 
3797     if (VarT) {
3798       unsigned Offset = this->allocateLocalPrimitive(
3799           VD, *VarT, VD->getType().isConstQualified());
3800       if (Init) {
3801         // If this is a toplevel declaration, create a scope for the
3802         // initializer.
3803         if (Toplevel) {
3804           LocalScope<Emitter> Scope(this);
3805           if (!this->visit(Init))
3806             return false;
3807           return this->emitSetLocal(*VarT, Offset, VD) && Scope.destroyLocals();
3808         } else {
3809           if (!this->visit(Init))
3810             return false;
3811           return this->emitSetLocal(*VarT, Offset, VD);
3812         }
3813       }
3814     } else {
3815       if (std::optional<unsigned> Offset = this->allocateLocal(VD)) {
3816         if (!Init)
3817           return true;
3818 
3819         if (!this->emitGetPtrLocal(*Offset, Init))
3820           return false;
3821 
3822         if (!visitInitializer(Init))
3823           return false;
3824 
3825         if (!this->emitFinishInit(Init))
3826           return false;
3827 
3828         return this->emitPopPtr(Init);
3829       }
3830       return false;
3831     }
3832     return true;
3833   }
3834 
3835   return false;
3836 }
3837 
3838 template <class Emitter>
3839 bool Compiler<Emitter>::visitAPValue(const APValue &Val, PrimType ValType,
3840                                      const Expr *E) {
3841   assert(!DiscardResult);
3842   if (Val.isInt())
3843     return this->emitConst(Val.getInt(), ValType, E);
3844   else if (Val.isFloat())
3845     return this->emitConstFloat(Val.getFloat(), E);
3846 
3847   if (Val.isLValue()) {
3848     if (Val.isNullPointer())
3849       return this->emitNull(ValType, nullptr, E);
3850     APValue::LValueBase Base = Val.getLValueBase();
3851     if (const Expr *BaseExpr = Base.dyn_cast<const Expr *>())
3852       return this->visit(BaseExpr);
3853     else if (const auto *VD = Base.dyn_cast<const ValueDecl *>()) {
3854       return this->visitDeclRef(VD, E);
3855     }
3856   } else if (Val.isMemberPointer()) {
3857     if (const ValueDecl *MemberDecl = Val.getMemberPointerDecl())
3858       return this->emitGetMemberPtr(MemberDecl, E);
3859     return this->emitNullMemberPtr(nullptr, E);
3860   }
3861 
3862   return false;
3863 }
3864 
3865 template <class Emitter>
3866 bool Compiler<Emitter>::visitAPValueInitializer(const APValue &Val,
3867                                                 const Expr *E) {
3868 
3869   if (Val.isStruct()) {
3870     const Record *R = this->getRecord(E->getType());
3871     assert(R);
3872     for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) {
3873       const APValue &F = Val.getStructField(I);
3874       const Record::Field *RF = R->getField(I);
3875 
3876       if (F.isInt() || F.isFloat() || F.isLValue() || F.isMemberPointer()) {
3877         PrimType T = classifyPrim(RF->Decl->getType());
3878         if (!this->visitAPValue(F, T, E))
3879           return false;
3880         if (!this->emitInitField(T, RF->Offset, E))
3881           return false;
3882       } else if (F.isArray()) {
3883         assert(RF->Desc->isPrimitiveArray());
3884         const auto *ArrType = RF->Decl->getType()->getAsArrayTypeUnsafe();
3885         PrimType ElemT = classifyPrim(ArrType->getElementType());
3886         assert(ArrType);
3887 
3888         if (!this->emitGetPtrField(RF->Offset, E))
3889           return false;
3890 
3891         for (unsigned A = 0, AN = F.getArraySize(); A != AN; ++A) {
3892           if (!this->visitAPValue(F.getArrayInitializedElt(A), ElemT, E))
3893             return false;
3894           if (!this->emitInitElem(ElemT, A, E))
3895             return false;
3896         }
3897 
3898         if (!this->emitPopPtr(E))
3899           return false;
3900       } else if (F.isStruct() || F.isUnion()) {
3901         if (!this->emitGetPtrField(RF->Offset, E))
3902           return false;
3903         if (!this->visitAPValueInitializer(F, E))
3904           return false;
3905         if (!this->emitPopPtr(E))
3906           return false;
3907       } else {
3908         assert(false && "I don't think this should be possible");
3909       }
3910     }
3911     return true;
3912   } else if (Val.isUnion()) {
3913     const FieldDecl *UnionField = Val.getUnionField();
3914     const Record *R = this->getRecord(UnionField->getParent());
3915     assert(R);
3916     const APValue &F = Val.getUnionValue();
3917     const Record::Field *RF = R->getField(UnionField);
3918     PrimType T = classifyPrim(RF->Decl->getType());
3919     if (!this->visitAPValue(F, T, E))
3920       return false;
3921     return this->emitInitField(T, RF->Offset, E);
3922   }
3923   // TODO: Other types.
3924 
3925   return false;
3926 }
3927 
3928 template <class Emitter>
3929 bool Compiler<Emitter>::VisitBuiltinCallExpr(const CallExpr *E) {
3930   const Function *Func = getFunction(E->getDirectCallee());
3931   if (!Func)
3932     return false;
3933 
3934   // For these, we're expected to ultimately return an APValue pointing
3935   // to the CallExpr. This is needed to get the correct codegen.
3936   unsigned Builtin = E->getBuiltinCallee();
3937   if (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
3938       Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
3939       Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
3940       Builtin == Builtin::BI__builtin_function_start) {
3941     if (std::optional<unsigned> GlobalOffset = P.createGlobal(E)) {
3942       if (!this->emitGetPtrGlobal(*GlobalOffset, E))
3943         return false;
3944 
3945       if (PrimType PT = classifyPrim(E); PT != PT_Ptr && isPtrType(PT))
3946         return this->emitDecayPtr(PT_Ptr, PT, E);
3947       return true;
3948     }
3949     return false;
3950   }
3951 
3952   QualType ReturnType = E->getType();
3953   std::optional<PrimType> ReturnT = classify(E);
3954 
3955   // Non-primitive return type. Prepare storage.
3956   if (!Initializing && !ReturnT && !ReturnType->isVoidType()) {
3957     std::optional<unsigned> LocalIndex = allocateLocal(E);
3958     if (!LocalIndex)
3959       return false;
3960     if (!this->emitGetPtrLocal(*LocalIndex, E))
3961       return false;
3962   }
3963 
3964   if (!Func->isUnevaluatedBuiltin()) {
3965     // Put arguments on the stack.
3966     for (const auto *Arg : E->arguments()) {
3967       if (!this->visit(Arg))
3968         return false;
3969     }
3970   }
3971 
3972   if (!this->emitCallBI(Func, E, E))
3973     return false;
3974 
3975   if (DiscardResult && !ReturnType->isVoidType()) {
3976     assert(ReturnT);
3977     return this->emitPop(*ReturnT, E);
3978   }
3979 
3980   return true;
3981 }
3982 
3983 template <class Emitter>
3984 bool Compiler<Emitter>::VisitCallExpr(const CallExpr *E) {
3985   if (E->getBuiltinCallee())
3986     return VisitBuiltinCallExpr(E);
3987 
3988   QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
3989   std::optional<PrimType> T = classify(ReturnType);
3990   bool HasRVO = !ReturnType->isVoidType() && !T;
3991   const FunctionDecl *FuncDecl = E->getDirectCallee();
3992 
3993   if (HasRVO) {
3994     if (DiscardResult) {
3995       // If we need to discard the return value but the function returns its
3996       // value via an RVO pointer, we need to create one such pointer just
3997       // for this call.
3998       if (std::optional<unsigned> LocalIndex = allocateLocal(E)) {
3999         if (!this->emitGetPtrLocal(*LocalIndex, E))
4000           return false;
4001       }
4002     } else {
4003       // We need the result. Prepare a pointer to return or
4004       // dup the current one.
4005       if (!Initializing) {
4006         if (std::optional<unsigned> LocalIndex = allocateLocal(E)) {
4007           if (!this->emitGetPtrLocal(*LocalIndex, E))
4008             return false;
4009         }
4010       }
4011       if (!this->emitDupPtr(E))
4012         return false;
4013     }
4014   }
4015 
4016   SmallVector<const Expr *, 8> Args(
4017       llvm::ArrayRef(E->getArgs(), E->getNumArgs()));
4018 
4019   bool IsAssignmentOperatorCall = false;
4020   if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
4021       OCE && OCE->isAssignmentOp()) {
4022     // Just like with regular assignments, we need to special-case assignment
4023     // operators here and evaluate the RHS (the second arg) before the LHS (the
4024     // first arg. We fix this by using a Flip op later.
4025     assert(Args.size() == 2);
4026     IsAssignmentOperatorCall = true;
4027     std::reverse(Args.begin(), Args.end());
4028   }
4029   // Calling a static operator will still
4030   // pass the instance, but we don't need it.
4031   // Discard it here.
4032   if (isa<CXXOperatorCallExpr>(E)) {
4033     if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
4034         MD && MD->isStatic()) {
4035       if (!this->discard(E->getArg(0)))
4036         return false;
4037       // Drop first arg.
4038       Args.erase(Args.begin());
4039     }
4040   }
4041 
4042   std::optional<unsigned> CalleeOffset;
4043   // Add the (optional, implicit) This pointer.
4044   if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) {
4045     if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) {
4046       // If we end up creating a CallPtr op for this, we need the base of the
4047       // member pointer as the instance pointer, and later extract the function
4048       // decl as the function pointer.
4049       const Expr *Callee = E->getCallee();
4050       CalleeOffset =
4051           this->allocateLocalPrimitive(Callee, PT_MemberPtr, true, false);
4052       if (!this->visit(Callee))
4053         return false;
4054       if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E))
4055         return false;
4056       if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
4057         return false;
4058       if (!this->emitGetMemberPtrBase(E))
4059         return false;
4060     } else if (!this->visit(MC->getImplicitObjectArgument())) {
4061       return false;
4062     }
4063   } else if (!FuncDecl) {
4064     const Expr *Callee = E->getCallee();
4065     CalleeOffset = this->allocateLocalPrimitive(Callee, PT_FnPtr, true, false);
4066     if (!this->visit(Callee))
4067       return false;
4068     if (!this->emitSetLocal(PT_FnPtr, *CalleeOffset, E))
4069       return false;
4070   }
4071 
4072   llvm::BitVector NonNullArgs = collectNonNullArgs(FuncDecl, Args);
4073   // Put arguments on the stack.
4074   unsigned ArgIndex = 0;
4075   for (const auto *Arg : Args) {
4076     if (!this->visit(Arg))
4077       return false;
4078 
4079     // If we know the callee already, check the known parametrs for nullability.
4080     if (FuncDecl && NonNullArgs[ArgIndex]) {
4081       PrimType ArgT = classify(Arg).value_or(PT_Ptr);
4082       if (ArgT == PT_Ptr || ArgT == PT_FnPtr) {
4083         if (!this->emitCheckNonNullArg(ArgT, Arg))
4084           return false;
4085       }
4086     }
4087     ++ArgIndex;
4088   }
4089 
4090   // Undo the argument reversal we did earlier.
4091   if (IsAssignmentOperatorCall) {
4092     assert(Args.size() == 2);
4093     PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr);
4094     PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr);
4095     if (!this->emitFlip(Arg2T, Arg1T, E))
4096       return false;
4097   }
4098 
4099   if (FuncDecl) {
4100     const Function *Func = getFunction(FuncDecl);
4101     if (!Func)
4102       return false;
4103     assert(HasRVO == Func->hasRVO());
4104 
4105     bool HasQualifier = false;
4106     if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee()))
4107       HasQualifier = ME->hasQualifier();
4108 
4109     bool IsVirtual = false;
4110     if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl))
4111       IsVirtual = MD->isVirtual();
4112 
4113     // In any case call the function. The return value will end up on the stack
4114     // and if the function has RVO, we already have the pointer on the stack to
4115     // write the result into.
4116     if (IsVirtual && !HasQualifier) {
4117       uint32_t VarArgSize = 0;
4118       unsigned NumParams =
4119           Func->getNumWrittenParams() + isa<CXXOperatorCallExpr>(E);
4120       for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
4121         VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
4122 
4123       if (!this->emitCallVirt(Func, VarArgSize, E))
4124         return false;
4125     } else if (Func->isVariadic()) {
4126       uint32_t VarArgSize = 0;
4127       unsigned NumParams =
4128           Func->getNumWrittenParams() + isa<CXXOperatorCallExpr>(E);
4129       for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
4130         VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
4131       if (!this->emitCallVar(Func, VarArgSize, E))
4132         return false;
4133     } else {
4134       if (!this->emitCall(Func, 0, E))
4135         return false;
4136     }
4137   } else {
4138     // Indirect call. Visit the callee, which will leave a FunctionPointer on
4139     // the stack. Cleanup of the returned value if necessary will be done after
4140     // the function call completed.
4141 
4142     // Sum the size of all args from the call expr.
4143     uint32_t ArgSize = 0;
4144     for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
4145       ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
4146 
4147     // Get the callee, either from a member pointer or function pointer saved in
4148     // CalleeOffset.
4149     if (isa<CXXMemberCallExpr>(E) && CalleeOffset) {
4150       if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
4151         return false;
4152       if (!this->emitGetMemberPtrDecl(E))
4153         return false;
4154     } else {
4155       if (!this->emitGetLocal(PT_FnPtr, *CalleeOffset, E))
4156         return false;
4157     }
4158     if (!this->emitCallPtr(ArgSize, E, E))
4159       return false;
4160   }
4161 
4162   // Cleanup for discarded return values.
4163   if (DiscardResult && !ReturnType->isVoidType() && T)
4164     return this->emitPop(*T, E);
4165 
4166   return true;
4167 }
4168 
4169 template <class Emitter>
4170 bool Compiler<Emitter>::VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4171   SourceLocScope<Emitter> SLS(this, E);
4172 
4173   return this->delegate(E->getExpr());
4174 }
4175 
4176 template <class Emitter>
4177 bool Compiler<Emitter>::VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4178   SourceLocScope<Emitter> SLS(this, E);
4179 
4180   const Expr *SubExpr = E->getExpr();
4181   if (std::optional<PrimType> T = classify(E->getExpr()))
4182     return this->visit(SubExpr);
4183 
4184   assert(Initializing);
4185   return this->visitInitializer(SubExpr);
4186 }
4187 
4188 template <class Emitter>
4189 bool Compiler<Emitter>::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
4190   if (DiscardResult)
4191     return true;
4192 
4193   return this->emitConstBool(E->getValue(), E);
4194 }
4195 
4196 template <class Emitter>
4197 bool Compiler<Emitter>::VisitCXXNullPtrLiteralExpr(
4198     const CXXNullPtrLiteralExpr *E) {
4199   if (DiscardResult)
4200     return true;
4201 
4202   return this->emitNullPtr(nullptr, E);
4203 }
4204 
4205 template <class Emitter>
4206 bool Compiler<Emitter>::VisitGNUNullExpr(const GNUNullExpr *E) {
4207   if (DiscardResult)
4208     return true;
4209 
4210   assert(E->getType()->isIntegerType());
4211 
4212   PrimType T = classifyPrim(E->getType());
4213   return this->emitZero(T, E);
4214 }
4215 
4216 template <class Emitter>
4217 bool Compiler<Emitter>::VisitCXXThisExpr(const CXXThisExpr *E) {
4218   if (DiscardResult)
4219     return true;
4220 
4221   if (this->LambdaThisCapture.Offset > 0) {
4222     if (this->LambdaThisCapture.IsPtr)
4223       return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E);
4224     return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E);
4225   }
4226 
4227   // In some circumstances, the 'this' pointer does not actually refer to the
4228   // instance pointer of the current function frame, but e.g. to the declaration
4229   // currently being initialized. Here we emit the necessary instruction(s) for
4230   // this scenario.
4231   if (!InitStackActive || !E->isImplicit())
4232     return this->emitThis(E);
4233 
4234   if (InitStackActive && !InitStack.empty()) {
4235     unsigned StartIndex = 0;
4236     for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
4237       if (InitStack[StartIndex].Kind != InitLink::K_Field &&
4238           InitStack[StartIndex].Kind != InitLink::K_Elem)
4239         break;
4240     }
4241 
4242     for (unsigned I = StartIndex, N = InitStack.size(); I != N; ++I) {
4243       if (!InitStack[I].template emit<Emitter>(this, E))
4244         return false;
4245     }
4246     return true;
4247   }
4248   return this->emitThis(E);
4249 }
4250 
4251 template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) {
4252   switch (S->getStmtClass()) {
4253   case Stmt::CompoundStmtClass:
4254     return visitCompoundStmt(cast<CompoundStmt>(S));
4255   case Stmt::DeclStmtClass:
4256     return visitDeclStmt(cast<DeclStmt>(S));
4257   case Stmt::ReturnStmtClass:
4258     return visitReturnStmt(cast<ReturnStmt>(S));
4259   case Stmt::IfStmtClass:
4260     return visitIfStmt(cast<IfStmt>(S));
4261   case Stmt::WhileStmtClass:
4262     return visitWhileStmt(cast<WhileStmt>(S));
4263   case Stmt::DoStmtClass:
4264     return visitDoStmt(cast<DoStmt>(S));
4265   case Stmt::ForStmtClass:
4266     return visitForStmt(cast<ForStmt>(S));
4267   case Stmt::CXXForRangeStmtClass:
4268     return visitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
4269   case Stmt::BreakStmtClass:
4270     return visitBreakStmt(cast<BreakStmt>(S));
4271   case Stmt::ContinueStmtClass:
4272     return visitContinueStmt(cast<ContinueStmt>(S));
4273   case Stmt::SwitchStmtClass:
4274     return visitSwitchStmt(cast<SwitchStmt>(S));
4275   case Stmt::CaseStmtClass:
4276     return visitCaseStmt(cast<CaseStmt>(S));
4277   case Stmt::DefaultStmtClass:
4278     return visitDefaultStmt(cast<DefaultStmt>(S));
4279   case Stmt::AttributedStmtClass:
4280     return visitAttributedStmt(cast<AttributedStmt>(S));
4281   case Stmt::CXXTryStmtClass:
4282     return visitCXXTryStmt(cast<CXXTryStmt>(S));
4283   case Stmt::NullStmtClass:
4284     return true;
4285   // Always invalid statements.
4286   case Stmt::GCCAsmStmtClass:
4287   case Stmt::MSAsmStmtClass:
4288   case Stmt::GotoStmtClass:
4289     return this->emitInvalid(S);
4290   case Stmt::LabelStmtClass:
4291     return this->visitStmt(cast<LabelStmt>(S)->getSubStmt());
4292   default: {
4293     if (const auto *E = dyn_cast<Expr>(S))
4294       return this->discard(E);
4295     return false;
4296   }
4297   }
4298 }
4299 
4300 template <class Emitter>
4301 bool Compiler<Emitter>::visitCompoundStmt(const CompoundStmt *S) {
4302   BlockScope<Emitter> Scope(this);
4303   for (const auto *InnerStmt : S->body())
4304     if (!visitStmt(InnerStmt))
4305       return false;
4306   return Scope.destroyLocals();
4307 }
4308 
4309 template <class Emitter>
4310 bool Compiler<Emitter>::visitDeclStmt(const DeclStmt *DS) {
4311   for (const auto *D : DS->decls()) {
4312     if (isa<StaticAssertDecl, TagDecl, TypedefNameDecl, UsingEnumDecl,
4313             FunctionDecl>(D))
4314       continue;
4315 
4316     const auto *VD = dyn_cast<VarDecl>(D);
4317     if (!VD)
4318       return false;
4319     if (!this->visitVarDecl(VD))
4320       return false;
4321   }
4322 
4323   return true;
4324 }
4325 
4326 template <class Emitter>
4327 bool Compiler<Emitter>::visitReturnStmt(const ReturnStmt *RS) {
4328   if (this->InStmtExpr)
4329     return this->emitUnsupported(RS);
4330 
4331   if (const Expr *RE = RS->getRetValue()) {
4332     LocalScope<Emitter> RetScope(this);
4333     if (ReturnType) {
4334       // Primitive types are simply returned.
4335       if (!this->visit(RE))
4336         return false;
4337       this->emitCleanup();
4338       return this->emitRet(*ReturnType, RS);
4339     } else if (RE->getType()->isVoidType()) {
4340       if (!this->visit(RE))
4341         return false;
4342     } else {
4343       // RVO - construct the value in the return location.
4344       if (!this->emitRVOPtr(RE))
4345         return false;
4346       if (!this->visitInitializer(RE))
4347         return false;
4348       if (!this->emitPopPtr(RE))
4349         return false;
4350 
4351       this->emitCleanup();
4352       return this->emitRetVoid(RS);
4353     }
4354   }
4355 
4356   // Void return.
4357   this->emitCleanup();
4358   return this->emitRetVoid(RS);
4359 }
4360 
4361 template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) {
4362   if (IS->isNonNegatedConsteval())
4363     return visitStmt(IS->getThen());
4364   if (IS->isNegatedConsteval())
4365     return IS->getElse() ? visitStmt(IS->getElse()) : true;
4366 
4367   if (auto *CondInit = IS->getInit())
4368     if (!visitStmt(CondInit))
4369       return false;
4370 
4371   if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt())
4372     if (!visitDeclStmt(CondDecl))
4373       return false;
4374 
4375   if (!this->visitBool(IS->getCond()))
4376     return false;
4377 
4378   if (const Stmt *Else = IS->getElse()) {
4379     LabelTy LabelElse = this->getLabel();
4380     LabelTy LabelEnd = this->getLabel();
4381     if (!this->jumpFalse(LabelElse))
4382       return false;
4383     if (!visitStmt(IS->getThen()))
4384       return false;
4385     if (!this->jump(LabelEnd))
4386       return false;
4387     this->emitLabel(LabelElse);
4388     if (!visitStmt(Else))
4389       return false;
4390     this->emitLabel(LabelEnd);
4391   } else {
4392     LabelTy LabelEnd = this->getLabel();
4393     if (!this->jumpFalse(LabelEnd))
4394       return false;
4395     if (!visitStmt(IS->getThen()))
4396       return false;
4397     this->emitLabel(LabelEnd);
4398   }
4399 
4400   return true;
4401 }
4402 
4403 template <class Emitter>
4404 bool Compiler<Emitter>::visitWhileStmt(const WhileStmt *S) {
4405   const Expr *Cond = S->getCond();
4406   const Stmt *Body = S->getBody();
4407 
4408   LabelTy CondLabel = this->getLabel(); // Label before the condition.
4409   LabelTy EndLabel = this->getLabel();  // Label after the loop.
4410   LoopScope<Emitter> LS(this, EndLabel, CondLabel);
4411 
4412   this->fallthrough(CondLabel);
4413   this->emitLabel(CondLabel);
4414 
4415   if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
4416     if (!visitDeclStmt(CondDecl))
4417       return false;
4418 
4419   if (!this->visitBool(Cond))
4420     return false;
4421   if (!this->jumpFalse(EndLabel))
4422     return false;
4423 
4424   if (!this->visitStmt(Body))
4425     return false;
4426 
4427   if (!this->jump(CondLabel))
4428     return false;
4429   this->fallthrough(EndLabel);
4430   this->emitLabel(EndLabel);
4431 
4432   return true;
4433 }
4434 
4435 template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) {
4436   const Expr *Cond = S->getCond();
4437   const Stmt *Body = S->getBody();
4438 
4439   LabelTy StartLabel = this->getLabel();
4440   LabelTy EndLabel = this->getLabel();
4441   LabelTy CondLabel = this->getLabel();
4442   LoopScope<Emitter> LS(this, EndLabel, CondLabel);
4443 
4444   this->fallthrough(StartLabel);
4445   this->emitLabel(StartLabel);
4446   {
4447     if (!this->visitStmt(Body))
4448       return false;
4449     this->fallthrough(CondLabel);
4450     this->emitLabel(CondLabel);
4451     if (!this->visitBool(Cond))
4452       return false;
4453   }
4454   if (!this->jumpTrue(StartLabel))
4455     return false;
4456 
4457   this->fallthrough(EndLabel);
4458   this->emitLabel(EndLabel);
4459   return true;
4460 }
4461 
4462 template <class Emitter>
4463 bool Compiler<Emitter>::visitForStmt(const ForStmt *S) {
4464   // for (Init; Cond; Inc) { Body }
4465   const Stmt *Init = S->getInit();
4466   const Expr *Cond = S->getCond();
4467   const Expr *Inc = S->getInc();
4468   const Stmt *Body = S->getBody();
4469 
4470   LabelTy EndLabel = this->getLabel();
4471   LabelTy CondLabel = this->getLabel();
4472   LabelTy IncLabel = this->getLabel();
4473   LoopScope<Emitter> LS(this, EndLabel, IncLabel);
4474 
4475   if (Init && !this->visitStmt(Init))
4476     return false;
4477 
4478   this->fallthrough(CondLabel);
4479   this->emitLabel(CondLabel);
4480 
4481   if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
4482     if (!visitDeclStmt(CondDecl))
4483       return false;
4484 
4485   if (Cond) {
4486     if (!this->visitBool(Cond))
4487       return false;
4488     if (!this->jumpFalse(EndLabel))
4489       return false;
4490   }
4491 
4492   {
4493     if (Body && !this->visitStmt(Body))
4494       return false;
4495 
4496     this->fallthrough(IncLabel);
4497     this->emitLabel(IncLabel);
4498     if (Inc && !this->discard(Inc))
4499       return false;
4500   }
4501 
4502   if (!this->jump(CondLabel))
4503     return false;
4504   this->fallthrough(EndLabel);
4505   this->emitLabel(EndLabel);
4506   return true;
4507 }
4508 
4509 template <class Emitter>
4510 bool Compiler<Emitter>::visitCXXForRangeStmt(const CXXForRangeStmt *S) {
4511   const Stmt *Init = S->getInit();
4512   const Expr *Cond = S->getCond();
4513   const Expr *Inc = S->getInc();
4514   const Stmt *Body = S->getBody();
4515   const Stmt *BeginStmt = S->getBeginStmt();
4516   const Stmt *RangeStmt = S->getRangeStmt();
4517   const Stmt *EndStmt = S->getEndStmt();
4518   const VarDecl *LoopVar = S->getLoopVariable();
4519 
4520   LabelTy EndLabel = this->getLabel();
4521   LabelTy CondLabel = this->getLabel();
4522   LabelTy IncLabel = this->getLabel();
4523   LoopScope<Emitter> LS(this, EndLabel, IncLabel);
4524 
4525   // Emit declarations needed in the loop.
4526   if (Init && !this->visitStmt(Init))
4527     return false;
4528   if (!this->visitStmt(RangeStmt))
4529     return false;
4530   if (!this->visitStmt(BeginStmt))
4531     return false;
4532   if (!this->visitStmt(EndStmt))
4533     return false;
4534 
4535   // Now the condition as well as the loop variable assignment.
4536   this->fallthrough(CondLabel);
4537   this->emitLabel(CondLabel);
4538   if (!this->visitBool(Cond))
4539     return false;
4540   if (!this->jumpFalse(EndLabel))
4541     return false;
4542 
4543   if (!this->visitVarDecl(LoopVar))
4544     return false;
4545 
4546   // Body.
4547   {
4548     if (!this->visitStmt(Body))
4549       return false;
4550 
4551     this->fallthrough(IncLabel);
4552     this->emitLabel(IncLabel);
4553     if (!this->discard(Inc))
4554       return false;
4555   }
4556 
4557   if (!this->jump(CondLabel))
4558     return false;
4559 
4560   this->fallthrough(EndLabel);
4561   this->emitLabel(EndLabel);
4562   return true;
4563 }
4564 
4565 template <class Emitter>
4566 bool Compiler<Emitter>::visitBreakStmt(const BreakStmt *S) {
4567   if (!BreakLabel)
4568     return false;
4569 
4570   this->emitCleanup();
4571   return this->jump(*BreakLabel);
4572 }
4573 
4574 template <class Emitter>
4575 bool Compiler<Emitter>::visitContinueStmt(const ContinueStmt *S) {
4576   if (!ContinueLabel)
4577     return false;
4578 
4579   this->emitCleanup();
4580   return this->jump(*ContinueLabel);
4581 }
4582 
4583 template <class Emitter>
4584 bool Compiler<Emitter>::visitSwitchStmt(const SwitchStmt *S) {
4585   const Expr *Cond = S->getCond();
4586   PrimType CondT = this->classifyPrim(Cond->getType());
4587 
4588   LabelTy EndLabel = this->getLabel();
4589   OptLabelTy DefaultLabel = std::nullopt;
4590   unsigned CondVar = this->allocateLocalPrimitive(Cond, CondT, true, false);
4591 
4592   if (const auto *CondInit = S->getInit())
4593     if (!visitStmt(CondInit))
4594       return false;
4595 
4596   if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
4597     if (!visitDeclStmt(CondDecl))
4598       return false;
4599 
4600   // Initialize condition variable.
4601   if (!this->visit(Cond))
4602     return false;
4603   if (!this->emitSetLocal(CondT, CondVar, S))
4604     return false;
4605 
4606   CaseMap CaseLabels;
4607   // Create labels and comparison ops for all case statements.
4608   for (const SwitchCase *SC = S->getSwitchCaseList(); SC;
4609        SC = SC->getNextSwitchCase()) {
4610     if (const auto *CS = dyn_cast<CaseStmt>(SC)) {
4611       // FIXME: Implement ranges.
4612       if (CS->caseStmtIsGNURange())
4613         return false;
4614       CaseLabels[SC] = this->getLabel();
4615 
4616       const Expr *Value = CS->getLHS();
4617       PrimType ValueT = this->classifyPrim(Value->getType());
4618 
4619       // Compare the case statement's value to the switch condition.
4620       if (!this->emitGetLocal(CondT, CondVar, CS))
4621         return false;
4622       if (!this->visit(Value))
4623         return false;
4624 
4625       // Compare and jump to the case label.
4626       if (!this->emitEQ(ValueT, S))
4627         return false;
4628       if (!this->jumpTrue(CaseLabels[CS]))
4629         return false;
4630     } else {
4631       assert(!DefaultLabel);
4632       DefaultLabel = this->getLabel();
4633     }
4634   }
4635 
4636   // If none of the conditions above were true, fall through to the default
4637   // statement or jump after the switch statement.
4638   if (DefaultLabel) {
4639     if (!this->jump(*DefaultLabel))
4640       return false;
4641   } else {
4642     if (!this->jump(EndLabel))
4643       return false;
4644   }
4645 
4646   SwitchScope<Emitter> SS(this, std::move(CaseLabels), EndLabel, DefaultLabel);
4647   if (!this->visitStmt(S->getBody()))
4648     return false;
4649   this->emitLabel(EndLabel);
4650   return true;
4651 }
4652 
4653 template <class Emitter>
4654 bool Compiler<Emitter>::visitCaseStmt(const CaseStmt *S) {
4655   this->emitLabel(CaseLabels[S]);
4656   return this->visitStmt(S->getSubStmt());
4657 }
4658 
4659 template <class Emitter>
4660 bool Compiler<Emitter>::visitDefaultStmt(const DefaultStmt *S) {
4661   this->emitLabel(*DefaultLabel);
4662   return this->visitStmt(S->getSubStmt());
4663 }
4664 
4665 template <class Emitter>
4666 bool Compiler<Emitter>::visitAttributedStmt(const AttributedStmt *S) {
4667   if (this->Ctx.getLangOpts().CXXAssumptions &&
4668       !this->Ctx.getLangOpts().MSVCCompat) {
4669     for (const Attr *A : S->getAttrs()) {
4670       auto *AA = dyn_cast<CXXAssumeAttr>(A);
4671       if (!AA)
4672         continue;
4673 
4674       assert(isa<NullStmt>(S->getSubStmt()));
4675 
4676       const Expr *Assumption = AA->getAssumption();
4677       if (Assumption->isValueDependent())
4678         return false;
4679 
4680       if (Assumption->HasSideEffects(this->Ctx.getASTContext()))
4681         continue;
4682 
4683       // Evaluate assumption.
4684       if (!this->visitBool(Assumption))
4685         return false;
4686 
4687       if (!this->emitAssume(Assumption))
4688         return false;
4689     }
4690   }
4691 
4692   // Ignore other attributes.
4693   return this->visitStmt(S->getSubStmt());
4694 }
4695 
4696 template <class Emitter>
4697 bool Compiler<Emitter>::visitCXXTryStmt(const CXXTryStmt *S) {
4698   // Ignore all handlers.
4699   return this->visitStmt(S->getTryBlock());
4700 }
4701 
4702 template <class Emitter>
4703 bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) {
4704   assert(MD->isLambdaStaticInvoker());
4705   assert(MD->hasBody());
4706   assert(cast<CompoundStmt>(MD->getBody())->body_empty());
4707 
4708   const CXXRecordDecl *ClosureClass = MD->getParent();
4709   const CXXMethodDecl *LambdaCallOp = ClosureClass->getLambdaCallOperator();
4710   assert(ClosureClass->captures_begin() == ClosureClass->captures_end());
4711   const Function *Func = this->getFunction(LambdaCallOp);
4712   if (!Func)
4713     return false;
4714   assert(Func->hasThisPointer());
4715   assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO()));
4716 
4717   if (Func->hasRVO()) {
4718     if (!this->emitRVOPtr(MD))
4719       return false;
4720   }
4721 
4722   // The lambda call operator needs an instance pointer, but we don't have
4723   // one here, and we don't need one either because the lambda cannot have
4724   // any captures, as verified above. Emit a null pointer. This is then
4725   // special-cased when interpreting to not emit any misleading diagnostics.
4726   if (!this->emitNullPtr(nullptr, MD))
4727     return false;
4728 
4729   // Forward all arguments from the static invoker to the lambda call operator.
4730   for (const ParmVarDecl *PVD : MD->parameters()) {
4731     auto It = this->Params.find(PVD);
4732     assert(It != this->Params.end());
4733 
4734     // We do the lvalue-to-rvalue conversion manually here, so no need
4735     // to care about references.
4736     PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr);
4737     if (!this->emitGetParam(ParamType, It->second.Offset, MD))
4738       return false;
4739   }
4740 
4741   if (!this->emitCall(Func, 0, LambdaCallOp))
4742     return false;
4743 
4744   this->emitCleanup();
4745   if (ReturnType)
4746     return this->emitRet(*ReturnType, MD);
4747 
4748   // Nothing to do, since we emitted the RVO pointer above.
4749   return this->emitRetVoid(MD);
4750 }
4751 
4752 template <class Emitter>
4753 bool Compiler<Emitter>::checkLiteralType(const Expr *E) {
4754   if (Ctx.getLangOpts().CPlusPlus23)
4755     return true;
4756 
4757   if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext()))
4758     return true;
4759 
4760   return this->emitCheckLiteralType(E->getType().getTypePtr(), E);
4761 }
4762 
4763 template <class Emitter>
4764 bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
4765   assert(!ReturnType);
4766 
4767   auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset,
4768                                   const Expr *InitExpr) -> bool {
4769     // We don't know what to do with these, so just return false.
4770     if (InitExpr->getType().isNull())
4771       return false;
4772 
4773     if (std::optional<PrimType> T = this->classify(InitExpr)) {
4774       if (!this->visit(InitExpr))
4775         return false;
4776 
4777       if (F->isBitField())
4778         return this->emitInitThisBitField(*T, F, FieldOffset, InitExpr);
4779       return this->emitInitThisField(*T, FieldOffset, InitExpr);
4780     }
4781     // Non-primitive case. Get a pointer to the field-to-initialize
4782     // on the stack and call visitInitialzer() for it.
4783     InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset));
4784     if (!this->emitGetPtrThisField(FieldOffset, InitExpr))
4785       return false;
4786 
4787     if (!this->visitInitializer(InitExpr))
4788       return false;
4789 
4790     return this->emitFinishInitPop(InitExpr);
4791   };
4792 
4793   const RecordDecl *RD = Ctor->getParent();
4794   const Record *R = this->getRecord(RD);
4795   if (!R)
4796     return false;
4797 
4798   if (R->isUnion() && Ctor->isCopyOrMoveConstructor()) {
4799     // union copy and move ctors are special.
4800     assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
4801     if (!this->emitThis(Ctor))
4802       return false;
4803 
4804     auto PVD = Ctor->getParamDecl(0);
4805     ParamOffset PO = this->Params[PVD]; // Must exist.
4806 
4807     if (!this->emitGetParam(PT_Ptr, PO.Offset, Ctor))
4808       return false;
4809 
4810     return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) &&
4811            this->emitRetVoid(Ctor);
4812   }
4813 
4814   InitLinkScope<Emitter> InitScope(this, InitLink::This());
4815   for (const auto *Init : Ctor->inits()) {
4816     // Scope needed for the initializers.
4817     BlockScope<Emitter> Scope(this);
4818 
4819     const Expr *InitExpr = Init->getInit();
4820     if (const FieldDecl *Member = Init->getMember()) {
4821       const Record::Field *F = R->getField(Member);
4822 
4823       if (!emitFieldInitializer(F, F->Offset, InitExpr))
4824         return false;
4825     } else if (const Type *Base = Init->getBaseClass()) {
4826       const auto *BaseDecl = Base->getAsCXXRecordDecl();
4827       assert(BaseDecl);
4828 
4829       if (Init->isBaseVirtual()) {
4830         assert(R->getVirtualBase(BaseDecl));
4831         if (!this->emitGetPtrThisVirtBase(BaseDecl, InitExpr))
4832           return false;
4833 
4834       } else {
4835         // Base class initializer.
4836         // Get This Base and call initializer on it.
4837         const Record::Base *B = R->getBase(BaseDecl);
4838         assert(B);
4839         if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
4840           return false;
4841       }
4842 
4843       if (!this->visitInitializer(InitExpr))
4844         return false;
4845       if (!this->emitFinishInitPop(InitExpr))
4846         return false;
4847     } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
4848       assert(IFD->getChainingSize() >= 2);
4849 
4850       unsigned NestedFieldOffset = 0;
4851       const Record::Field *NestedField = nullptr;
4852       for (const NamedDecl *ND : IFD->chain()) {
4853         const auto *FD = cast<FieldDecl>(ND);
4854         const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
4855         assert(FieldRecord);
4856 
4857         NestedField = FieldRecord->getField(FD);
4858         assert(NestedField);
4859 
4860         NestedFieldOffset += NestedField->Offset;
4861       }
4862       assert(NestedField);
4863 
4864       if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr))
4865         return false;
4866     } else {
4867       assert(Init->isDelegatingInitializer());
4868       if (!this->emitThis(InitExpr))
4869         return false;
4870       if (!this->visitInitializer(Init->getInit()))
4871         return false;
4872       if (!this->emitPopPtr(InitExpr))
4873         return false;
4874     }
4875 
4876     if (!Scope.destroyLocals())
4877       return false;
4878   }
4879 
4880   if (const auto *Body = Ctor->getBody())
4881     if (!visitStmt(Body))
4882       return false;
4883 
4884   return this->emitRetVoid(SourceInfo{});
4885 }
4886 
4887 template <class Emitter>
4888 bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) {
4889   const RecordDecl *RD = Dtor->getParent();
4890   const Record *R = this->getRecord(RD);
4891   if (!R)
4892     return false;
4893 
4894   if (!Dtor->isTrivial() && Dtor->getBody()) {
4895     if (!this->visitStmt(Dtor->getBody()))
4896       return false;
4897   }
4898 
4899   if (!this->emitThis(Dtor))
4900     return false;
4901 
4902   assert(R);
4903   if (!R->isUnion()) {
4904     // First, destroy all fields.
4905     for (const Record::Field &Field : llvm::reverse(R->fields())) {
4906       const Descriptor *D = Field.Desc;
4907       if (!D->isPrimitive() && !D->isPrimitiveArray()) {
4908         if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
4909           return false;
4910         if (!this->emitDestruction(D))
4911           return false;
4912         if (!this->emitPopPtr(SourceInfo{}))
4913           return false;
4914       }
4915     }
4916   }
4917 
4918   for (const Record::Base &Base : llvm::reverse(R->bases())) {
4919     if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
4920       return false;
4921     if (!this->emitRecordDestruction(Base.R))
4922       return false;
4923     if (!this->emitPopPtr(SourceInfo{}))
4924       return false;
4925   }
4926 
4927   // FIXME: Virtual bases.
4928   return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor);
4929 }
4930 
4931 template <class Emitter>
4932 bool Compiler<Emitter>::visitFunc(const FunctionDecl *F) {
4933   // Classify the return type.
4934   ReturnType = this->classify(F->getReturnType());
4935 
4936   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F))
4937     return this->compileConstructor(Ctor);
4938   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F))
4939     return this->compileDestructor(Dtor);
4940 
4941   // Emit custom code if this is a lambda static invoker.
4942   if (const auto *MD = dyn_cast<CXXMethodDecl>(F);
4943       MD && MD->isLambdaStaticInvoker())
4944     return this->emitLambdaStaticInvokerBody(MD);
4945 
4946   // Regular functions.
4947   if (const auto *Body = F->getBody())
4948     if (!visitStmt(Body))
4949       return false;
4950 
4951   // Emit a guard return to protect against a code path missing one.
4952   if (F->getReturnType()->isVoidType())
4953     return this->emitRetVoid(SourceInfo{});
4954   return this->emitNoRet(SourceInfo{});
4955 }
4956 
4957 template <class Emitter>
4958 bool Compiler<Emitter>::VisitUnaryOperator(const UnaryOperator *E) {
4959   const Expr *SubExpr = E->getSubExpr();
4960   if (SubExpr->getType()->isAnyComplexType())
4961     return this->VisitComplexUnaryOperator(E);
4962   std::optional<PrimType> T = classify(SubExpr->getType());
4963 
4964   switch (E->getOpcode()) {
4965   case UO_PostInc: { // x++
4966     if (!Ctx.getLangOpts().CPlusPlus14)
4967       return this->emitInvalid(E);
4968     if (!T)
4969       return this->emitError(E);
4970 
4971     if (!this->visit(SubExpr))
4972       return false;
4973 
4974     if (T == PT_Ptr || T == PT_FnPtr) {
4975       if (!this->emitIncPtr(E))
4976         return false;
4977 
4978       return DiscardResult ? this->emitPopPtr(E) : true;
4979     }
4980 
4981     if (T == PT_Float) {
4982       return DiscardResult ? this->emitIncfPop(getRoundingMode(E), E)
4983                            : this->emitIncf(getRoundingMode(E), E);
4984     }
4985 
4986     return DiscardResult ? this->emitIncPop(*T, E) : this->emitInc(*T, E);
4987   }
4988   case UO_PostDec: { // x--
4989     if (!Ctx.getLangOpts().CPlusPlus14)
4990       return this->emitInvalid(E);
4991     if (!T)
4992       return this->emitError(E);
4993 
4994     if (!this->visit(SubExpr))
4995       return false;
4996 
4997     if (T == PT_Ptr || T == PT_FnPtr) {
4998       if (!this->emitDecPtr(E))
4999         return false;
5000 
5001       return DiscardResult ? this->emitPopPtr(E) : true;
5002     }
5003 
5004     if (T == PT_Float) {
5005       return DiscardResult ? this->emitDecfPop(getRoundingMode(E), E)
5006                            : this->emitDecf(getRoundingMode(E), E);
5007     }
5008 
5009     return DiscardResult ? this->emitDecPop(*T, E) : this->emitDec(*T, E);
5010   }
5011   case UO_PreInc: { // ++x
5012     if (!Ctx.getLangOpts().CPlusPlus14)
5013       return this->emitInvalid(E);
5014     if (!T)
5015       return this->emitError(E);
5016 
5017     if (!this->visit(SubExpr))
5018       return false;
5019 
5020     if (T == PT_Ptr || T == PT_FnPtr) {
5021       if (!this->emitLoadPtr(E))
5022         return false;
5023       if (!this->emitConstUint8(1, E))
5024         return false;
5025       if (!this->emitAddOffsetUint8(E))
5026         return false;
5027       return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
5028     }
5029 
5030     // Post-inc and pre-inc are the same if the value is to be discarded.
5031     if (DiscardResult) {
5032       if (T == PT_Float)
5033         return this->emitIncfPop(getRoundingMode(E), E);
5034       return this->emitIncPop(*T, E);
5035     }
5036 
5037     if (T == PT_Float) {
5038       const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
5039       if (!this->emitLoadFloat(E))
5040         return false;
5041       if (!this->emitConstFloat(llvm::APFloat(TargetSemantics, 1), E))
5042         return false;
5043       if (!this->emitAddf(getRoundingMode(E), E))
5044         return false;
5045       if (!this->emitStoreFloat(E))
5046         return false;
5047     } else {
5048       assert(isIntegralType(*T));
5049       if (!this->emitLoad(*T, E))
5050         return false;
5051       if (!this->emitConst(1, E))
5052         return false;
5053       if (!this->emitAdd(*T, E))
5054         return false;
5055       if (!this->emitStore(*T, E))
5056         return false;
5057     }
5058     return E->isGLValue() || this->emitLoadPop(*T, E);
5059   }
5060   case UO_PreDec: { // --x
5061     if (!Ctx.getLangOpts().CPlusPlus14)
5062       return this->emitInvalid(E);
5063     if (!T)
5064       return this->emitError(E);
5065 
5066     if (!this->visit(SubExpr))
5067       return false;
5068 
5069     if (T == PT_Ptr || T == PT_FnPtr) {
5070       if (!this->emitLoadPtr(E))
5071         return false;
5072       if (!this->emitConstUint8(1, E))
5073         return false;
5074       if (!this->emitSubOffsetUint8(E))
5075         return false;
5076       return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
5077     }
5078 
5079     // Post-dec and pre-dec are the same if the value is to be discarded.
5080     if (DiscardResult) {
5081       if (T == PT_Float)
5082         return this->emitDecfPop(getRoundingMode(E), E);
5083       return this->emitDecPop(*T, E);
5084     }
5085 
5086     if (T == PT_Float) {
5087       const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
5088       if (!this->emitLoadFloat(E))
5089         return false;
5090       if (!this->emitConstFloat(llvm::APFloat(TargetSemantics, 1), E))
5091         return false;
5092       if (!this->emitSubf(getRoundingMode(E), E))
5093         return false;
5094       if (!this->emitStoreFloat(E))
5095         return false;
5096     } else {
5097       assert(isIntegralType(*T));
5098       if (!this->emitLoad(*T, E))
5099         return false;
5100       if (!this->emitConst(1, E))
5101         return false;
5102       if (!this->emitSub(*T, E))
5103         return false;
5104       if (!this->emitStore(*T, E))
5105         return false;
5106     }
5107     return E->isGLValue() || this->emitLoadPop(*T, E);
5108   }
5109   case UO_LNot: // !x
5110     if (!T)
5111       return this->emitError(E);
5112 
5113     if (DiscardResult)
5114       return this->discard(SubExpr);
5115 
5116     if (!this->visitBool(SubExpr))
5117       return false;
5118 
5119     if (!this->emitInv(E))
5120       return false;
5121 
5122     if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
5123       return this->emitCast(PT_Bool, ET, E);
5124     return true;
5125   case UO_Minus: // -x
5126     if (!T)
5127       return this->emitError(E);
5128 
5129     if (!this->visit(SubExpr))
5130       return false;
5131     return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E);
5132   case UO_Plus: // +x
5133     if (!T)
5134       return this->emitError(E);
5135 
5136     if (!this->visit(SubExpr)) // noop
5137       return false;
5138     return DiscardResult ? this->emitPop(*T, E) : true;
5139   case UO_AddrOf: // &x
5140     if (E->getType()->isMemberPointerType()) {
5141       // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5142       // member can be formed.
5143       return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E);
5144     }
5145     // We should already have a pointer when we get here.
5146     return this->delegate(SubExpr);
5147   case UO_Deref: // *x
5148     if (DiscardResult)
5149       return this->discard(SubExpr);
5150     return this->visit(SubExpr);
5151   case UO_Not: // ~x
5152     if (!T)
5153       return this->emitError(E);
5154 
5155     if (!this->visit(SubExpr))
5156       return false;
5157     return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
5158   case UO_Real: // __real x
5159     assert(T);
5160     return this->delegate(SubExpr);
5161   case UO_Imag: { // __imag x
5162     assert(T);
5163     if (!this->discard(SubExpr))
5164       return false;
5165     return this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr);
5166   }
5167   case UO_Extension:
5168     return this->delegate(SubExpr);
5169   case UO_Coawait:
5170     assert(false && "Unhandled opcode");
5171   }
5172 
5173   return false;
5174 }
5175 
5176 template <class Emitter>
5177 bool Compiler<Emitter>::VisitComplexUnaryOperator(const UnaryOperator *E) {
5178   const Expr *SubExpr = E->getSubExpr();
5179   assert(SubExpr->getType()->isAnyComplexType());
5180 
5181   if (DiscardResult)
5182     return this->discard(SubExpr);
5183 
5184   std::optional<PrimType> ResT = classify(E);
5185   auto prepareResult = [=]() -> bool {
5186     if (!ResT && !Initializing) {
5187       std::optional<unsigned> LocalIndex = allocateLocal(SubExpr);
5188       if (!LocalIndex)
5189         return false;
5190       return this->emitGetPtrLocal(*LocalIndex, E);
5191     }
5192 
5193     return true;
5194   };
5195 
5196   // The offset of the temporary, if we created one.
5197   unsigned SubExprOffset = ~0u;
5198   auto createTemp = [=, &SubExprOffset]() -> bool {
5199     SubExprOffset = this->allocateLocalPrimitive(SubExpr, PT_Ptr, true, false);
5200     if (!this->visit(SubExpr))
5201       return false;
5202     return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
5203   };
5204 
5205   PrimType ElemT = classifyComplexElementType(SubExpr->getType());
5206   auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
5207     if (!this->emitGetLocal(PT_Ptr, Offset, E))
5208       return false;
5209     return this->emitArrayElemPop(ElemT, Index, E);
5210   };
5211 
5212   switch (E->getOpcode()) {
5213   case UO_Minus:
5214     if (!prepareResult())
5215       return false;
5216     if (!createTemp())
5217       return false;
5218     for (unsigned I = 0; I != 2; ++I) {
5219       if (!getElem(SubExprOffset, I))
5220         return false;
5221       if (!this->emitNeg(ElemT, E))
5222         return false;
5223       if (!this->emitInitElem(ElemT, I, E))
5224         return false;
5225     }
5226     break;
5227 
5228   case UO_Plus:   // +x
5229   case UO_AddrOf: // &x
5230   case UO_Deref:  // *x
5231     return this->delegate(SubExpr);
5232 
5233   case UO_LNot:
5234     if (!this->visit(SubExpr))
5235       return false;
5236     if (!this->emitComplexBoolCast(SubExpr))
5237       return false;
5238     if (!this->emitInv(E))
5239       return false;
5240     if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
5241       return this->emitCast(PT_Bool, ET, E);
5242     return true;
5243 
5244   case UO_Real:
5245     return this->emitComplexReal(SubExpr);
5246 
5247   case UO_Imag:
5248     if (!this->visit(SubExpr))
5249       return false;
5250 
5251     if (SubExpr->isLValue()) {
5252       if (!this->emitConstUint8(1, E))
5253         return false;
5254       return this->emitArrayElemPtrPopUint8(E);
5255     }
5256 
5257     // Since our _Complex implementation does not map to a primitive type,
5258     // we sometimes have to do the lvalue-to-rvalue conversion here manually.
5259     return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E);
5260 
5261   case UO_Not: // ~x
5262     if (!this->visit(SubExpr))
5263       return false;
5264     // Negate the imaginary component.
5265     if (!this->emitArrayElem(ElemT, 1, E))
5266       return false;
5267     if (!this->emitNeg(ElemT, E))
5268       return false;
5269     if (!this->emitInitElem(ElemT, 1, E))
5270       return false;
5271     return DiscardResult ? this->emitPopPtr(E) : true;
5272 
5273   case UO_Extension:
5274     return this->delegate(SubExpr);
5275 
5276   default:
5277     return this->emitInvalid(E);
5278   }
5279 
5280   return true;
5281 }
5282 
5283 template <class Emitter>
5284 bool Compiler<Emitter>::visitDeclRef(const ValueDecl *D, const Expr *E) {
5285   if (DiscardResult)
5286     return true;
5287 
5288   if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
5289     return this->emitConst(ECD->getInitVal(), E);
5290   } else if (const auto *BD = dyn_cast<BindingDecl>(D)) {
5291     return this->visit(BD->getBinding());
5292   } else if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) {
5293     const Function *F = getFunction(FuncDecl);
5294     return F && this->emitGetFnPtr(F, E);
5295   } else if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) {
5296     if (std::optional<unsigned> Index = P.getOrCreateGlobal(D)) {
5297       if (!this->emitGetPtrGlobal(*Index, E))
5298         return false;
5299       if (std::optional<PrimType> T = classify(E->getType())) {
5300         if (!this->visitAPValue(TPOD->getValue(), *T, E))
5301           return false;
5302         return this->emitInitGlobal(*T, *Index, E);
5303       }
5304       return this->visitAPValueInitializer(TPOD->getValue(), E);
5305     }
5306     return false;
5307   }
5308 
5309   // References are implemented via pointers, so when we see a DeclRefExpr
5310   // pointing to a reference, we need to get its value directly (i.e. the
5311   // pointer to the actual value) instead of a pointer to the pointer to the
5312   // value.
5313   bool IsReference = D->getType()->isReferenceType();
5314 
5315   // Check for local/global variables and parameters.
5316   if (auto It = Locals.find(D); It != Locals.end()) {
5317     const unsigned Offset = It->second.Offset;
5318     if (IsReference)
5319       return this->emitGetLocal(PT_Ptr, Offset, E);
5320     return this->emitGetPtrLocal(Offset, E);
5321   } else if (auto GlobalIndex = P.getGlobal(D)) {
5322     if (IsReference) {
5323       if (!Ctx.getLangOpts().CPlusPlus11)
5324         return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E);
5325       return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E);
5326     }
5327 
5328     return this->emitGetPtrGlobal(*GlobalIndex, E);
5329   } else if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
5330     if (auto It = this->Params.find(PVD); It != this->Params.end()) {
5331       if (IsReference || !It->second.IsPtr)
5332         return this->emitGetParam(classifyPrim(E), It->second.Offset, E);
5333 
5334       return this->emitGetPtrParam(It->second.Offset, E);
5335     }
5336   }
5337 
5338   // In case we need to re-visit a declaration.
5339   auto revisit = [&](const VarDecl *VD) -> bool {
5340     auto VarState = this->visitDecl(VD);
5341 
5342     if (VarState.notCreated())
5343       return true;
5344     if (!VarState)
5345       return false;
5346     // Retry.
5347     return this->visitDeclRef(D, E);
5348   };
5349 
5350   // Handle lambda captures.
5351   if (auto It = this->LambdaCaptures.find(D);
5352       It != this->LambdaCaptures.end()) {
5353     auto [Offset, IsPtr] = It->second;
5354 
5355     if (IsPtr)
5356       return this->emitGetThisFieldPtr(Offset, E);
5357     return this->emitGetPtrThisField(Offset, E);
5358   } else if (const auto *DRE = dyn_cast<DeclRefExpr>(E);
5359              DRE && DRE->refersToEnclosingVariableOrCapture()) {
5360     if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture())
5361       return revisit(VD);
5362   }
5363 
5364   if (D != InitializingDecl) {
5365     // Try to lazily visit (or emit dummy pointers for) declarations
5366     // we haven't seen yet.
5367     if (Ctx.getLangOpts().CPlusPlus) {
5368       if (const auto *VD = dyn_cast<VarDecl>(D)) {
5369         const auto typeShouldBeVisited = [&](QualType T) -> bool {
5370           if (T.isConstant(Ctx.getASTContext()))
5371             return true;
5372           if (const auto *RT = T->getAs<ReferenceType>())
5373             return RT->getPointeeType().isConstQualified();
5374           return false;
5375         };
5376 
5377         // DecompositionDecls are just proxies for us.
5378         if (isa<DecompositionDecl>(VD))
5379           return revisit(VD);
5380 
5381         // Visit local const variables like normal.
5382         if ((VD->hasGlobalStorage() || VD->isLocalVarDecl() ||
5383              VD->isStaticDataMember()) &&
5384             typeShouldBeVisited(VD->getType()))
5385           return revisit(VD);
5386       }
5387     } else {
5388       if (const auto *VD = dyn_cast<VarDecl>(D);
5389           VD && VD->getAnyInitializer() &&
5390           VD->getType().isConstant(Ctx.getASTContext()) && !VD->isWeak())
5391         return revisit(VD);
5392     }
5393   }
5394 
5395   if (std::optional<unsigned> I = P.getOrCreateDummy(D)) {
5396     if (!this->emitGetPtrGlobal(*I, E))
5397       return false;
5398     if (E->getType()->isVoidType())
5399       return true;
5400     // Convert the dummy pointer to another pointer type if we have to.
5401     if (PrimType PT = classifyPrim(E); PT != PT_Ptr) {
5402       if (isPtrType(PT))
5403         return this->emitDecayPtr(PT_Ptr, PT, E);
5404       return false;
5405     }
5406     return true;
5407   }
5408 
5409   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5410     return this->emitInvalidDeclRef(DRE, E);
5411   return false;
5412 }
5413 
5414 template <class Emitter>
5415 bool Compiler<Emitter>::VisitDeclRefExpr(const DeclRefExpr *E) {
5416   const auto *D = E->getDecl();
5417   return this->visitDeclRef(D, E);
5418 }
5419 
5420 template <class Emitter> void Compiler<Emitter>::emitCleanup() {
5421   for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent())
5422     C->emitDestruction();
5423 }
5424 
5425 template <class Emitter>
5426 unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType,
5427                                               const QualType DerivedType) {
5428   const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
5429     if (const auto *R = Ty->getPointeeCXXRecordDecl())
5430       return R;
5431     return Ty->getAsCXXRecordDecl();
5432   };
5433   const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType);
5434   const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType);
5435 
5436   return Ctx.collectBaseOffset(BaseDecl, DerivedDecl);
5437 }
5438 
5439 /// Emit casts from a PrimType to another PrimType.
5440 template <class Emitter>
5441 bool Compiler<Emitter>::emitPrimCast(PrimType FromT, PrimType ToT,
5442                                      QualType ToQT, const Expr *E) {
5443 
5444   if (FromT == PT_Float) {
5445     // Floating to floating.
5446     if (ToT == PT_Float) {
5447       const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
5448       return this->emitCastFP(ToSem, getRoundingMode(E), E);
5449     }
5450 
5451     if (ToT == PT_IntAP)
5452       return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT), E);
5453     if (ToT == PT_IntAPS)
5454       return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT), E);
5455 
5456     // Float to integral.
5457     if (isIntegralType(ToT) || ToT == PT_Bool)
5458       return this->emitCastFloatingIntegral(ToT, E);
5459   }
5460 
5461   if (isIntegralType(FromT) || FromT == PT_Bool) {
5462     if (ToT == PT_IntAP)
5463       return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
5464     if (ToT == PT_IntAPS)
5465       return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
5466 
5467     // Integral to integral.
5468     if (isIntegralType(ToT) || ToT == PT_Bool)
5469       return FromT != ToT ? this->emitCast(FromT, ToT, E) : true;
5470 
5471     if (ToT == PT_Float) {
5472       // Integral to floating.
5473       const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
5474       return this->emitCastIntegralFloating(FromT, ToSem, getRoundingMode(E),
5475                                             E);
5476     }
5477   }
5478 
5479   return false;
5480 }
5481 
5482 /// Emits __real(SubExpr)
5483 template <class Emitter>
5484 bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) {
5485   assert(SubExpr->getType()->isAnyComplexType());
5486 
5487   if (DiscardResult)
5488     return this->discard(SubExpr);
5489 
5490   if (!this->visit(SubExpr))
5491     return false;
5492   if (SubExpr->isLValue()) {
5493     if (!this->emitConstUint8(0, SubExpr))
5494       return false;
5495     return this->emitArrayElemPtrPopUint8(SubExpr);
5496   }
5497 
5498   // Rvalue, load the actual element.
5499   return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()),
5500                                 0, SubExpr);
5501 }
5502 
5503 template <class Emitter>
5504 bool Compiler<Emitter>::emitComplexBoolCast(const Expr *E) {
5505   assert(!DiscardResult);
5506   PrimType ElemT = classifyComplexElementType(E->getType());
5507   // We emit the expression (__real(E) != 0 || __imag(E) != 0)
5508   // for us, that means (bool)E[0] || (bool)E[1]
5509   if (!this->emitArrayElem(ElemT, 0, E))
5510     return false;
5511   if (ElemT == PT_Float) {
5512     if (!this->emitCastFloatingIntegral(PT_Bool, E))
5513       return false;
5514   } else {
5515     if (!this->emitCast(ElemT, PT_Bool, E))
5516       return false;
5517   }
5518 
5519   // We now have the bool value of E[0] on the stack.
5520   LabelTy LabelTrue = this->getLabel();
5521   if (!this->jumpTrue(LabelTrue))
5522     return false;
5523 
5524   if (!this->emitArrayElemPop(ElemT, 1, E))
5525     return false;
5526   if (ElemT == PT_Float) {
5527     if (!this->emitCastFloatingIntegral(PT_Bool, E))
5528       return false;
5529   } else {
5530     if (!this->emitCast(ElemT, PT_Bool, E))
5531       return false;
5532   }
5533   // Leave the boolean value of E[1] on the stack.
5534   LabelTy EndLabel = this->getLabel();
5535   this->jump(EndLabel);
5536 
5537   this->emitLabel(LabelTrue);
5538   if (!this->emitPopPtr(E))
5539     return false;
5540   if (!this->emitConstBool(true, E))
5541     return false;
5542 
5543   this->fallthrough(EndLabel);
5544   this->emitLabel(EndLabel);
5545 
5546   return true;
5547 }
5548 
5549 template <class Emitter>
5550 bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS,
5551                                               const BinaryOperator *E) {
5552   assert(E->isComparisonOp());
5553   assert(!Initializing);
5554   assert(!DiscardResult);
5555 
5556   PrimType ElemT;
5557   bool LHSIsComplex;
5558   unsigned LHSOffset;
5559   if (LHS->getType()->isAnyComplexType()) {
5560     LHSIsComplex = true;
5561     ElemT = classifyComplexElementType(LHS->getType());
5562     LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true,
5563                                        /*IsExtended=*/false);
5564     if (!this->visit(LHS))
5565       return false;
5566     if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
5567       return false;
5568   } else {
5569     LHSIsComplex = false;
5570     PrimType LHST = classifyPrim(LHS->getType());
5571     LHSOffset = this->allocateLocalPrimitive(LHS, LHST, true, false);
5572     if (!this->visit(LHS))
5573       return false;
5574     if (!this->emitSetLocal(LHST, LHSOffset, E))
5575       return false;
5576   }
5577 
5578   bool RHSIsComplex;
5579   unsigned RHSOffset;
5580   if (RHS->getType()->isAnyComplexType()) {
5581     RHSIsComplex = true;
5582     ElemT = classifyComplexElementType(RHS->getType());
5583     RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true,
5584                                        /*IsExtended=*/false);
5585     if (!this->visit(RHS))
5586       return false;
5587     if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
5588       return false;
5589   } else {
5590     RHSIsComplex = false;
5591     PrimType RHST = classifyPrim(RHS->getType());
5592     RHSOffset = this->allocateLocalPrimitive(RHS, RHST, true, false);
5593     if (!this->visit(RHS))
5594       return false;
5595     if (!this->emitSetLocal(RHST, RHSOffset, E))
5596       return false;
5597   }
5598 
5599   auto getElem = [&](unsigned LocalOffset, unsigned Index,
5600                      bool IsComplex) -> bool {
5601     if (IsComplex) {
5602       if (!this->emitGetLocal(PT_Ptr, LocalOffset, E))
5603         return false;
5604       return this->emitArrayElemPop(ElemT, Index, E);
5605     }
5606     return this->emitGetLocal(ElemT, LocalOffset, E);
5607   };
5608 
5609   for (unsigned I = 0; I != 2; ++I) {
5610     // Get both values.
5611     if (!getElem(LHSOffset, I, LHSIsComplex))
5612       return false;
5613     if (!getElem(RHSOffset, I, RHSIsComplex))
5614       return false;
5615     // And compare them.
5616     if (!this->emitEQ(ElemT, E))
5617       return false;
5618 
5619     if (!this->emitCastBoolUint8(E))
5620       return false;
5621   }
5622 
5623   // We now have two bool values on the stack. Compare those.
5624   if (!this->emitAddUint8(E))
5625     return false;
5626   if (!this->emitConstUint8(2, E))
5627     return false;
5628 
5629   if (E->getOpcode() == BO_EQ) {
5630     if (!this->emitEQUint8(E))
5631       return false;
5632   } else if (E->getOpcode() == BO_NE) {
5633     if (!this->emitNEUint8(E))
5634       return false;
5635   } else
5636     return false;
5637 
5638   // In C, this returns an int.
5639   if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool)
5640     return this->emitCast(PT_Bool, ResT, E);
5641   return true;
5642 }
5643 
5644 /// When calling this, we have a pointer of the local-to-destroy
5645 /// on the stack.
5646 /// Emit destruction of record types (or arrays of record types).
5647 template <class Emitter>
5648 bool Compiler<Emitter>::emitRecordDestruction(const Record *R) {
5649   assert(R);
5650   const CXXDestructorDecl *Dtor = R->getDestructor();
5651   if (!Dtor || Dtor->isTrivial())
5652     return true;
5653 
5654   assert(Dtor);
5655   const Function *DtorFunc = getFunction(Dtor);
5656   if (!DtorFunc)
5657     return false;
5658   assert(DtorFunc->hasThisPointer());
5659   assert(DtorFunc->getNumParams() == 1);
5660   if (!this->emitDupPtr(SourceInfo{}))
5661     return false;
5662   return this->emitCall(DtorFunc, 0, SourceInfo{});
5663 }
5664 /// When calling this, we have a pointer of the local-to-destroy
5665 /// on the stack.
5666 /// Emit destruction of record types (or arrays of record types).
5667 template <class Emitter>
5668 bool Compiler<Emitter>::emitDestruction(const Descriptor *Desc) {
5669   assert(Desc);
5670   assert(!Desc->isPrimitive());
5671   assert(!Desc->isPrimitiveArray());
5672 
5673   // Arrays.
5674   if (Desc->isArray()) {
5675     const Descriptor *ElemDesc = Desc->ElemDesc;
5676     assert(ElemDesc);
5677 
5678     // Don't need to do anything for these.
5679     if (ElemDesc->isPrimitiveArray())
5680       return true;
5681 
5682     // If this is an array of record types, check if we need
5683     // to call the element destructors at all. If not, try
5684     // to save the work.
5685     if (const Record *ElemRecord = ElemDesc->ElemRecord) {
5686       if (const CXXDestructorDecl *Dtor = ElemRecord->getDestructor();
5687           !Dtor || Dtor->isTrivial())
5688         return true;
5689     }
5690 
5691     for (ssize_t I = Desc->getNumElems() - 1; I >= 0; --I) {
5692       if (!this->emitConstUint64(I, SourceInfo{}))
5693         return false;
5694       if (!this->emitArrayElemPtrUint64(SourceInfo{}))
5695         return false;
5696       if (!this->emitDestruction(ElemDesc))
5697         return false;
5698       if (!this->emitPopPtr(SourceInfo{}))
5699         return false;
5700     }
5701     return true;
5702   }
5703 
5704   assert(Desc->ElemRecord);
5705   return this->emitRecordDestruction(Desc->ElemRecord);
5706 }
5707 
5708 namespace clang {
5709 namespace interp {
5710 
5711 template class Compiler<ByteCodeEmitter>;
5712 template class Compiler<EvalEmitter>;
5713 
5714 } // namespace interp
5715 } // namespace clang
5716