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