Debian Codegraph @

clang/lib/AST/ByteCode/Compiler.cpp

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