ByteCodeExprGen.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  1. //===--- ByteCodeExprGen.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. #include "ByteCodeExprGen.h"
  9. #include "ByteCodeEmitter.h"
  10. #include "ByteCodeGenError.h"
  11. #include "ByteCodeStmtGen.h"
  12. #include "Context.h"
  13. #include "Function.h"
  14. #include "PrimType.h"
  15. #include "Program.h"
  16. #include "State.h"
  17. using namespace clang;
  18. using namespace clang::interp;
  19. using APSInt = llvm::APSInt;
  20. namespace clang {
  21. namespace interp {
  22. /// Scope used to handle temporaries in toplevel variable declarations.
  23. template <class Emitter> class DeclScope final : public LocalScope<Emitter> {
  24. public:
  25. DeclScope(ByteCodeExprGen<Emitter> *Ctx, const VarDecl *VD)
  26. : LocalScope<Emitter>(Ctx), Scope(Ctx->P, VD) {}
  27. void addExtended(const Scope::Local &Local) override {
  28. return this->addLocal(Local);
  29. }
  30. private:
  31. Program::DeclScope Scope;
  32. };
  33. /// Scope used to handle initialization methods.
  34. template <class Emitter> class OptionScope {
  35. public:
  36. /// Root constructor, compiling or discarding primitives.
  37. OptionScope(ByteCodeExprGen<Emitter> *Ctx, bool NewDiscardResult)
  38. : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult) {
  39. Ctx->DiscardResult = NewDiscardResult;
  40. }
  41. ~OptionScope() { Ctx->DiscardResult = OldDiscardResult; }
  42. private:
  43. /// Parent context.
  44. ByteCodeExprGen<Emitter> *Ctx;
  45. /// Old discard flag to restore.
  46. bool OldDiscardResult;
  47. };
  48. } // namespace interp
  49. } // namespace clang
  50. template <class Emitter>
  51. bool ByteCodeExprGen<Emitter>::VisitCastExpr(const CastExpr *CE) {
  52. auto *SubExpr = CE->getSubExpr();
  53. switch (CE->getCastKind()) {
  54. case CK_LValueToRValue: {
  55. return dereference(
  56. CE->getSubExpr(), DerefKind::Read,
  57. [](PrimType) {
  58. // Value loaded - nothing to do here.
  59. return true;
  60. },
  61. [this, CE](PrimType T) {
  62. // Pointer on stack - dereference it.
  63. if (!this->emitLoadPop(T, CE))
  64. return false;
  65. return DiscardResult ? this->emitPop(T, CE) : true;
  66. });
  67. }
  68. case CK_UncheckedDerivedToBase:
  69. case CK_DerivedToBase: {
  70. if (!this->visit(SubExpr))
  71. return false;
  72. const CXXRecordDecl *FromDecl = getRecordDecl(SubExpr);
  73. assert(FromDecl);
  74. const CXXRecordDecl *ToDecl = getRecordDecl(CE);
  75. assert(ToDecl);
  76. const Record *R = getRecord(FromDecl);
  77. const Record::Base *ToBase = R->getBase(ToDecl);
  78. assert(ToBase);
  79. return this->emitGetPtrBase(ToBase->Offset, CE);
  80. }
  81. case CK_ArrayToPointerDecay:
  82. case CK_AtomicToNonAtomic:
  83. case CK_ConstructorConversion:
  84. case CK_FunctionToPointerDecay:
  85. case CK_NonAtomicToAtomic:
  86. case CK_NoOp:
  87. case CK_UserDefinedConversion:
  88. case CK_NullToPointer:
  89. return this->visit(SubExpr);
  90. case CK_IntegralToBoolean:
  91. case CK_IntegralCast: {
  92. std::optional<PrimType> FromT = classify(SubExpr->getType());
  93. std::optional<PrimType> ToT = classify(CE->getType());
  94. if (!FromT || !ToT)
  95. return false;
  96. if (!this->visit(SubExpr))
  97. return false;
  98. // TODO: Emit this only if FromT != ToT.
  99. return this->emitCast(*FromT, *ToT, CE);
  100. }
  101. case CK_ToVoid:
  102. return discard(SubExpr);
  103. default:
  104. assert(false && "Cast not implemented");
  105. }
  106. llvm_unreachable("Unhandled clang::CastKind enum");
  107. }
  108. template <class Emitter>
  109. bool ByteCodeExprGen<Emitter>::VisitIntegerLiteral(const IntegerLiteral *LE) {
  110. if (DiscardResult)
  111. return true;
  112. return this->emitConst(LE->getValue(), LE);
  113. }
  114. template <class Emitter>
  115. bool ByteCodeExprGen<Emitter>::VisitParenExpr(const ParenExpr *PE) {
  116. return this->visit(PE->getSubExpr());
  117. }
  118. template <class Emitter>
  119. bool ByteCodeExprGen<Emitter>::VisitBinaryOperator(const BinaryOperator *BO) {
  120. const Expr *LHS = BO->getLHS();
  121. const Expr *RHS = BO->getRHS();
  122. // Deal with operations which have composite or void types.
  123. switch (BO->getOpcode()) {
  124. case BO_Comma:
  125. if (!discard(LHS))
  126. return false;
  127. if (!this->visit(RHS))
  128. return false;
  129. return true;
  130. default:
  131. break;
  132. }
  133. // Typecheck the args.
  134. std::optional<PrimType> LT = classify(LHS->getType());
  135. std::optional<PrimType> RT = classify(RHS->getType());
  136. std::optional<PrimType> T = classify(BO->getType());
  137. if (!LT || !RT || !T) {
  138. return this->bail(BO);
  139. }
  140. auto Discard = [this, T, BO](bool Result) {
  141. if (!Result)
  142. return false;
  143. return DiscardResult ? this->emitPop(*T, BO) : true;
  144. };
  145. // Pointer arithmetic special case.
  146. if (BO->getOpcode() == BO_Add || BO->getOpcode() == BO_Sub) {
  147. if (*T == PT_Ptr || (*LT == PT_Ptr && *RT == PT_Ptr))
  148. return this->VisitPointerArithBinOp(BO);
  149. }
  150. if (!visit(LHS) || !visit(RHS))
  151. return false;
  152. switch (BO->getOpcode()) {
  153. case BO_EQ:
  154. return Discard(this->emitEQ(*LT, BO));
  155. case BO_NE:
  156. return Discard(this->emitNE(*LT, BO));
  157. case BO_LT:
  158. return Discard(this->emitLT(*LT, BO));
  159. case BO_LE:
  160. return Discard(this->emitLE(*LT, BO));
  161. case BO_GT:
  162. return Discard(this->emitGT(*LT, BO));
  163. case BO_GE:
  164. return Discard(this->emitGE(*LT, BO));
  165. case BO_Sub:
  166. return Discard(this->emitSub(*T, BO));
  167. case BO_Add:
  168. return Discard(this->emitAdd(*T, BO));
  169. case BO_Mul:
  170. return Discard(this->emitMul(*T, BO));
  171. case BO_Rem:
  172. return Discard(this->emitRem(*T, BO));
  173. case BO_Div:
  174. return Discard(this->emitDiv(*T, BO));
  175. case BO_Assign:
  176. if (DiscardResult)
  177. return this->emitStorePop(*T, BO);
  178. return this->emitStore(*T, BO);
  179. case BO_And:
  180. return Discard(this->emitBitAnd(*T, BO));
  181. case BO_Or:
  182. return Discard(this->emitBitOr(*T, BO));
  183. case BO_Shl:
  184. return Discard(this->emitShl(*LT, *RT, BO));
  185. case BO_Shr:
  186. return Discard(this->emitShr(*LT, *RT, BO));
  187. case BO_Xor:
  188. return Discard(this->emitBitXor(*T, BO));
  189. case BO_LAnd:
  190. case BO_LOr:
  191. default:
  192. return this->bail(BO);
  193. }
  194. llvm_unreachable("Unhandled binary op");
  195. }
  196. /// Perform addition/subtraction of a pointer and an integer or
  197. /// subtraction of two pointers.
  198. template <class Emitter>
  199. bool ByteCodeExprGen<Emitter>::VisitPointerArithBinOp(const BinaryOperator *E) {
  200. BinaryOperatorKind Op = E->getOpcode();
  201. const Expr *LHS = E->getLHS();
  202. const Expr *RHS = E->getRHS();
  203. if ((Op != BO_Add && Op != BO_Sub) ||
  204. (!LHS->getType()->isPointerType() && !RHS->getType()->isPointerType()))
  205. return false;
  206. std::optional<PrimType> LT = classify(LHS);
  207. std::optional<PrimType> RT = classify(RHS);
  208. if (!LT || !RT)
  209. return false;
  210. if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) {
  211. if (Op != BO_Sub)
  212. return false;
  213. assert(E->getType()->isIntegerType());
  214. if (!visit(RHS) || !visit(LHS))
  215. return false;
  216. return this->emitSubPtr(classifyPrim(E->getType()), E);
  217. }
  218. PrimType OffsetType;
  219. if (LHS->getType()->isIntegerType()) {
  220. if (!visit(RHS) || !visit(LHS))
  221. return false;
  222. OffsetType = *LT;
  223. } else if (RHS->getType()->isIntegerType()) {
  224. if (!visit(LHS) || !visit(RHS))
  225. return false;
  226. OffsetType = *RT;
  227. } else {
  228. return false;
  229. }
  230. if (Op == BO_Add)
  231. return this->emitAddOffset(OffsetType, E);
  232. else if (Op == BO_Sub)
  233. return this->emitSubOffset(OffsetType, E);
  234. return this->bail(E);
  235. }
  236. template <class Emitter>
  237. bool ByteCodeExprGen<Emitter>::VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  238. if (std::optional<PrimType> T = classify(E))
  239. return this->emitZero(*T, E);
  240. return false;
  241. }
  242. template <class Emitter>
  243. bool ByteCodeExprGen<Emitter>::VisitArraySubscriptExpr(
  244. const ArraySubscriptExpr *E) {
  245. const Expr *Base = E->getBase();
  246. const Expr *Index = E->getIdx();
  247. PrimType IndexT = classifyPrim(Index->getType());
  248. // Take pointer of LHS, add offset from RHS, narrow result.
  249. // What's left on the stack after this is a pointer.
  250. if (!this->visit(Base))
  251. return false;
  252. if (!this->visit(Index))
  253. return false;
  254. if (!this->emitAddOffset(IndexT, E))
  255. return false;
  256. if (!this->emitNarrowPtr(E))
  257. return false;
  258. if (DiscardResult)
  259. return this->emitPopPtr(E);
  260. return true;
  261. }
  262. template <class Emitter>
  263. bool ByteCodeExprGen<Emitter>::VisitInitListExpr(const InitListExpr *E) {
  264. for (const Expr *Init : E->inits()) {
  265. if (!this->visit(Init))
  266. return false;
  267. }
  268. return true;
  269. }
  270. template <class Emitter>
  271. bool ByteCodeExprGen<Emitter>::VisitSubstNonTypeTemplateParmExpr(
  272. const SubstNonTypeTemplateParmExpr *E) {
  273. return this->visit(E->getReplacement());
  274. }
  275. template <class Emitter>
  276. bool ByteCodeExprGen<Emitter>::VisitConstantExpr(const ConstantExpr *E) {
  277. // TODO: Check if the ConstantExpr already has a value set and if so,
  278. // use that instead of evaluating it again.
  279. return this->visit(E->getSubExpr());
  280. }
  281. static CharUnits AlignOfType(QualType T, const ASTContext &ASTCtx,
  282. UnaryExprOrTypeTrait Kind) {
  283. bool AlignOfReturnsPreferred =
  284. ASTCtx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  285. // C++ [expr.alignof]p3:
  286. // When alignof is applied to a reference type, the result is the
  287. // alignment of the referenced type.
  288. if (const auto *Ref = T->getAs<ReferenceType>())
  289. T = Ref->getPointeeType();
  290. // __alignof is defined to return the preferred alignment.
  291. // Before 8, clang returned the preferred alignment for alignof and
  292. // _Alignof as well.
  293. if (Kind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  294. return ASTCtx.toCharUnitsFromBits(ASTCtx.getPreferredTypeAlign(T));
  295. return ASTCtx.getTypeAlignInChars(T);
  296. }
  297. template <class Emitter>
  298. bool ByteCodeExprGen<Emitter>::VisitUnaryExprOrTypeTraitExpr(
  299. const UnaryExprOrTypeTraitExpr *E) {
  300. UnaryExprOrTypeTrait Kind = E->getKind();
  301. ASTContext &ASTCtx = Ctx.getASTContext();
  302. if (Kind == UETT_SizeOf) {
  303. QualType ArgType = E->getTypeOfArgument();
  304. CharUnits Size;
  305. if (ArgType->isVoidType() || ArgType->isFunctionType())
  306. Size = CharUnits::One();
  307. else {
  308. if (ArgType->isDependentType() || !ArgType->isConstantSizeType())
  309. return false;
  310. Size = ASTCtx.getTypeSizeInChars(ArgType);
  311. }
  312. return this->emitConst(Size.getQuantity(), E);
  313. }
  314. if (Kind == UETT_AlignOf || Kind == UETT_PreferredAlignOf) {
  315. CharUnits Size;
  316. if (E->isArgumentType()) {
  317. QualType ArgType = E->getTypeOfArgument();
  318. Size = AlignOfType(ArgType, ASTCtx, Kind);
  319. } else {
  320. // Argument is an expression, not a type.
  321. const Expr *Arg = E->getArgumentExpr()->IgnoreParens();
  322. // The kinds of expressions that we have special-case logic here for
  323. // should be kept up to date with the special checks for those
  324. // expressions in Sema.
  325. // alignof decl is always accepted, even if it doesn't make sense: we
  326. // default to 1 in those cases.
  327. if (const auto *DRE = dyn_cast<DeclRefExpr>(Arg))
  328. Size = ASTCtx.getDeclAlign(DRE->getDecl(),
  329. /*RefAsPointee*/ true);
  330. else if (const auto *ME = dyn_cast<MemberExpr>(Arg))
  331. Size = ASTCtx.getDeclAlign(ME->getMemberDecl(),
  332. /*RefAsPointee*/ true);
  333. else
  334. Size = AlignOfType(Arg->getType(), ASTCtx, Kind);
  335. }
  336. return this->emitConst(Size.getQuantity(), E);
  337. }
  338. return false;
  339. }
  340. template <class Emitter>
  341. bool ByteCodeExprGen<Emitter>::VisitMemberExpr(const MemberExpr *E) {
  342. if (DiscardResult)
  343. return true;
  344. // 'Base.Member'
  345. const Expr *Base = E->getBase();
  346. const ValueDecl *Member = E->getMemberDecl();
  347. if (!this->visit(Base))
  348. return false;
  349. // Base above gives us a pointer on the stack.
  350. // TODO: Implement non-FieldDecl members.
  351. if (const auto *FD = dyn_cast<FieldDecl>(Member)) {
  352. const RecordDecl *RD = FD->getParent();
  353. const Record *R = getRecord(RD);
  354. const Record::Field *F = R->getField(FD);
  355. // Leave a pointer to the field on the stack.
  356. if (F->Decl->getType()->isReferenceType())
  357. return this->emitGetFieldPop(PT_Ptr, F->Offset, E);
  358. return this->emitGetPtrField(F->Offset, E);
  359. }
  360. return false;
  361. }
  362. template <class Emitter>
  363. bool ByteCodeExprGen<Emitter>::VisitArrayInitIndexExpr(
  364. const ArrayInitIndexExpr *E) {
  365. // ArrayIndex might not be set if a ArrayInitIndexExpr is being evaluated
  366. // stand-alone, e.g. via EvaluateAsInt().
  367. if (!ArrayIndex)
  368. return false;
  369. return this->emitConst(*ArrayIndex, E);
  370. }
  371. template <class Emitter>
  372. bool ByteCodeExprGen<Emitter>::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  373. return this->visit(E->getSourceExpr());
  374. }
  375. template <class Emitter>
  376. bool ByteCodeExprGen<Emitter>::VisitAbstractConditionalOperator(
  377. const AbstractConditionalOperator *E) {
  378. const Expr *Condition = E->getCond();
  379. const Expr *TrueExpr = E->getTrueExpr();
  380. const Expr *FalseExpr = E->getFalseExpr();
  381. LabelTy LabelEnd = this->getLabel(); // Label after the operator.
  382. LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
  383. if (!this->visit(Condition))
  384. return false;
  385. if (!this->jumpFalse(LabelFalse))
  386. return false;
  387. if (!this->visit(TrueExpr))
  388. return false;
  389. if (!this->jump(LabelEnd))
  390. return false;
  391. this->emitLabel(LabelFalse);
  392. if (!this->visit(FalseExpr))
  393. return false;
  394. this->fallthrough(LabelEnd);
  395. this->emitLabel(LabelEnd);
  396. return true;
  397. }
  398. template <class Emitter>
  399. bool ByteCodeExprGen<Emitter>::VisitStringLiteral(const StringLiteral *E) {
  400. unsigned StringIndex = P.createGlobalString(E);
  401. return this->emitGetPtrGlobal(StringIndex, E);
  402. }
  403. template <class Emitter>
  404. bool ByteCodeExprGen<Emitter>::VisitCharacterLiteral(
  405. const CharacterLiteral *E) {
  406. return this->emitConst(E->getValue(), E);
  407. }
  408. template <class Emitter>
  409. bool ByteCodeExprGen<Emitter>::VisitCompoundAssignOperator(
  410. const CompoundAssignOperator *E) {
  411. const Expr *LHS = E->getLHS();
  412. const Expr *RHS = E->getRHS();
  413. std::optional<PrimType> LT = classify(E->getLHS()->getType());
  414. std::optional<PrimType> RT = classify(E->getRHS()->getType());
  415. if (!LT || !RT)
  416. return false;
  417. assert(!E->getType()->isPointerType() &&
  418. "Support pointer arithmethic in compound assignment operators");
  419. // Get LHS pointer, load its value and get RHS value.
  420. if (!visit(LHS))
  421. return false;
  422. if (!this->emitLoad(*LT, E))
  423. return false;
  424. if (!visit(RHS))
  425. return false;
  426. // Perform operation.
  427. switch (E->getOpcode()) {
  428. case BO_AddAssign:
  429. if (!this->emitAdd(*LT, E))
  430. return false;
  431. break;
  432. case BO_SubAssign:
  433. if (!this->emitSub(*LT, E))
  434. return false;
  435. break;
  436. case BO_MulAssign:
  437. case BO_DivAssign:
  438. case BO_RemAssign:
  439. case BO_ShlAssign:
  440. if (!this->emitShl(*LT, *RT, E))
  441. return false;
  442. break;
  443. case BO_ShrAssign:
  444. if (!this->emitShr(*LT, *RT, E))
  445. return false;
  446. break;
  447. case BO_AndAssign:
  448. case BO_XorAssign:
  449. case BO_OrAssign:
  450. default:
  451. llvm_unreachable("Unimplemented compound assign operator");
  452. }
  453. // And store the result in LHS.
  454. if (DiscardResult)
  455. return this->emitStorePop(*LT, E);
  456. return this->emitStore(*LT, E);
  457. }
  458. template <class Emitter> bool ByteCodeExprGen<Emitter>::discard(const Expr *E) {
  459. OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true);
  460. return this->Visit(E);
  461. }
  462. template <class Emitter>
  463. bool ByteCodeExprGen<Emitter>::visit(const Expr *E) {
  464. OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false);
  465. return this->Visit(E);
  466. }
  467. template <class Emitter>
  468. bool ByteCodeExprGen<Emitter>::visitBool(const Expr *E) {
  469. if (std::optional<PrimType> T = classify(E->getType())) {
  470. return visit(E);
  471. } else {
  472. return this->bail(E);
  473. }
  474. }
  475. template <class Emitter>
  476. bool ByteCodeExprGen<Emitter>::visitZeroInitializer(PrimType T, const Expr *E) {
  477. switch (T) {
  478. case PT_Bool:
  479. return this->emitZeroBool(E);
  480. case PT_Sint8:
  481. return this->emitZeroSint8(E);
  482. case PT_Uint8:
  483. return this->emitZeroUint8(E);
  484. case PT_Sint16:
  485. return this->emitZeroSint16(E);
  486. case PT_Uint16:
  487. return this->emitZeroUint16(E);
  488. case PT_Sint32:
  489. return this->emitZeroSint32(E);
  490. case PT_Uint32:
  491. return this->emitZeroUint32(E);
  492. case PT_Sint64:
  493. return this->emitZeroSint64(E);
  494. case PT_Uint64:
  495. return this->emitZeroUint64(E);
  496. case PT_Ptr:
  497. return this->emitNullPtr(E);
  498. }
  499. llvm_unreachable("unknown primitive type");
  500. }
  501. template <class Emitter>
  502. bool ByteCodeExprGen<Emitter>::dereference(
  503. const Expr *LV, DerefKind AK, llvm::function_ref<bool(PrimType)> Direct,
  504. llvm::function_ref<bool(PrimType)> Indirect) {
  505. if (std::optional<PrimType> T = classify(LV->getType())) {
  506. if (!LV->refersToBitField()) {
  507. // Only primitive, non bit-field types can be dereferenced directly.
  508. if (auto *DE = dyn_cast<DeclRefExpr>(LV)) {
  509. if (!DE->getDecl()->getType()->isReferenceType()) {
  510. if (auto *PD = dyn_cast<ParmVarDecl>(DE->getDecl()))
  511. return dereferenceParam(LV, *T, PD, AK, Direct, Indirect);
  512. if (auto *VD = dyn_cast<VarDecl>(DE->getDecl()))
  513. return dereferenceVar(LV, *T, VD, AK, Direct, Indirect);
  514. }
  515. }
  516. }
  517. if (!visit(LV))
  518. return false;
  519. return Indirect(*T);
  520. }
  521. return false;
  522. }
  523. template <class Emitter>
  524. bool ByteCodeExprGen<Emitter>::dereferenceParam(
  525. const Expr *LV, PrimType T, const ParmVarDecl *PD, DerefKind AK,
  526. llvm::function_ref<bool(PrimType)> Direct,
  527. llvm::function_ref<bool(PrimType)> Indirect) {
  528. auto It = this->Params.find(PD);
  529. if (It != this->Params.end()) {
  530. unsigned Idx = It->second;
  531. switch (AK) {
  532. case DerefKind::Read:
  533. return DiscardResult ? true : this->emitGetParam(T, Idx, LV);
  534. case DerefKind::Write:
  535. if (!Direct(T))
  536. return false;
  537. if (!this->emitSetParam(T, Idx, LV))
  538. return false;
  539. return DiscardResult ? true : this->emitGetPtrParam(Idx, LV);
  540. case DerefKind::ReadWrite:
  541. if (!this->emitGetParam(T, Idx, LV))
  542. return false;
  543. if (!Direct(T))
  544. return false;
  545. if (!this->emitSetParam(T, Idx, LV))
  546. return false;
  547. return DiscardResult ? true : this->emitGetPtrParam(Idx, LV);
  548. }
  549. return true;
  550. }
  551. // If the param is a pointer, we can dereference a dummy value.
  552. if (!DiscardResult && T == PT_Ptr && AK == DerefKind::Read) {
  553. if (auto Idx = P.getOrCreateDummy(PD))
  554. return this->emitGetPtrGlobal(*Idx, PD);
  555. return false;
  556. }
  557. // Value cannot be produced - try to emit pointer and do stuff with it.
  558. return visit(LV) && Indirect(T);
  559. }
  560. template <class Emitter>
  561. bool ByteCodeExprGen<Emitter>::dereferenceVar(
  562. const Expr *LV, PrimType T, const VarDecl *VD, DerefKind AK,
  563. llvm::function_ref<bool(PrimType)> Direct,
  564. llvm::function_ref<bool(PrimType)> Indirect) {
  565. auto It = Locals.find(VD);
  566. if (It != Locals.end()) {
  567. const auto &L = It->second;
  568. switch (AK) {
  569. case DerefKind::Read:
  570. if (!this->emitGetLocal(T, L.Offset, LV))
  571. return false;
  572. return DiscardResult ? this->emitPop(T, LV) : true;
  573. case DerefKind::Write:
  574. if (!Direct(T))
  575. return false;
  576. if (!this->emitSetLocal(T, L.Offset, LV))
  577. return false;
  578. return DiscardResult ? true : this->emitGetPtrLocal(L.Offset, LV);
  579. case DerefKind::ReadWrite:
  580. if (!this->emitGetLocal(T, L.Offset, LV))
  581. return false;
  582. if (!Direct(T))
  583. return false;
  584. if (!this->emitSetLocal(T, L.Offset, LV))
  585. return false;
  586. return DiscardResult ? true : this->emitGetPtrLocal(L.Offset, LV);
  587. }
  588. } else if (auto Idx = P.getGlobal(VD)) {
  589. switch (AK) {
  590. case DerefKind::Read:
  591. if (!this->emitGetGlobal(T, *Idx, LV))
  592. return false;
  593. return DiscardResult ? this->emitPop(T, LV) : true;
  594. case DerefKind::Write:
  595. if (!Direct(T))
  596. return false;
  597. if (!this->emitSetGlobal(T, *Idx, LV))
  598. return false;
  599. return DiscardResult ? true : this->emitGetPtrGlobal(*Idx, LV);
  600. case DerefKind::ReadWrite:
  601. if (!this->emitGetGlobal(T, *Idx, LV))
  602. return false;
  603. if (!Direct(T))
  604. return false;
  605. if (!this->emitSetGlobal(T, *Idx, LV))
  606. return false;
  607. return DiscardResult ? true : this->emitGetPtrGlobal(*Idx, LV);
  608. }
  609. }
  610. // If the declaration is a constant value, emit it here even
  611. // though the declaration was not evaluated in the current scope.
  612. // The access mode can only be read in this case.
  613. if (!DiscardResult && AK == DerefKind::Read) {
  614. if (VD->hasLocalStorage() && VD->hasInit() && !VD->isConstexpr()) {
  615. QualType VT = VD->getType();
  616. if (VT.isConstQualified() && VT->isFundamentalType())
  617. return this->visit(VD->getInit());
  618. }
  619. }
  620. // Value cannot be produced - try to emit pointer.
  621. return visit(LV) && Indirect(T);
  622. }
  623. template <class Emitter>
  624. template <typename T>
  625. bool ByteCodeExprGen<Emitter>::emitConst(T Value, const Expr *E) {
  626. switch (classifyPrim(E->getType())) {
  627. case PT_Sint8:
  628. return this->emitConstSint8(Value, E);
  629. case PT_Uint8:
  630. return this->emitConstUint8(Value, E);
  631. case PT_Sint16:
  632. return this->emitConstSint16(Value, E);
  633. case PT_Uint16:
  634. return this->emitConstUint16(Value, E);
  635. case PT_Sint32:
  636. return this->emitConstSint32(Value, E);
  637. case PT_Uint32:
  638. return this->emitConstUint32(Value, E);
  639. case PT_Sint64:
  640. return this->emitConstSint64(Value, E);
  641. case PT_Uint64:
  642. return this->emitConstUint64(Value, E);
  643. case PT_Bool:
  644. return this->emitConstBool(Value, E);
  645. case PT_Ptr:
  646. llvm_unreachable("Invalid integral type");
  647. break;
  648. }
  649. llvm_unreachable("unknown primitive type");
  650. }
  651. template <class Emitter>
  652. bool ByteCodeExprGen<Emitter>::emitConst(const APSInt &Value, const Expr *E) {
  653. if (Value.isSigned())
  654. return this->emitConst(Value.getSExtValue(), E);
  655. return this->emitConst(Value.getZExtValue(), E);
  656. }
  657. template <class Emitter>
  658. unsigned ByteCodeExprGen<Emitter>::allocateLocalPrimitive(DeclTy &&Src,
  659. PrimType Ty,
  660. bool IsConst,
  661. bool IsExtended) {
  662. // Make sure we don't accidentally register the same decl twice.
  663. if (const auto *VD =
  664. dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
  665. assert(!P.getGlobal(VD));
  666. assert(Locals.find(VD) == Locals.end());
  667. }
  668. // FIXME: There are cases where Src.is<Expr*>() is wrong, e.g.
  669. // (int){12} in C. Consider using Expr::isTemporaryObject() instead
  670. // or isa<MaterializeTemporaryExpr>().
  671. Descriptor *D = P.createDescriptor(Src, Ty, Descriptor::InlineDescMD, IsConst,
  672. Src.is<const Expr *>());
  673. Scope::Local Local = this->createLocal(D);
  674. if (auto *VD = dyn_cast_or_null<ValueDecl>(Src.dyn_cast<const Decl *>()))
  675. Locals.insert({VD, Local});
  676. VarScope->add(Local, IsExtended);
  677. return Local.Offset;
  678. }
  679. template <class Emitter>
  680. std::optional<unsigned>
  681. ByteCodeExprGen<Emitter>::allocateLocal(DeclTy &&Src, bool IsExtended) {
  682. // Make sure we don't accidentally register the same decl twice.
  683. if (const auto *VD =
  684. dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
  685. assert(!P.getGlobal(VD));
  686. assert(Locals.find(VD) == Locals.end());
  687. }
  688. QualType Ty;
  689. const ValueDecl *Key = nullptr;
  690. const Expr *Init = nullptr;
  691. bool IsTemporary = false;
  692. if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
  693. Key = VD;
  694. Ty = VD->getType();
  695. if (const auto *VarD = dyn_cast<VarDecl>(VD))
  696. Init = VarD->getInit();
  697. }
  698. if (auto *E = Src.dyn_cast<const Expr *>()) {
  699. IsTemporary = true;
  700. Ty = E->getType();
  701. }
  702. Descriptor *D = P.createDescriptor(
  703. Src, Ty.getTypePtr(), Descriptor::InlineDescMD, Ty.isConstQualified(),
  704. IsTemporary, /*IsMutable=*/false, Init);
  705. if (!D)
  706. return {};
  707. Scope::Local Local = this->createLocal(D);
  708. if (Key)
  709. Locals.insert({Key, Local});
  710. VarScope->add(Local, IsExtended);
  711. return Local.Offset;
  712. }
  713. // NB: When calling this function, we have a pointer to the
  714. // array-to-initialize on the stack.
  715. template <class Emitter>
  716. bool ByteCodeExprGen<Emitter>::visitArrayInitializer(const Expr *Initializer) {
  717. assert(Initializer->getType()->isArrayType());
  718. // TODO: Fillers?
  719. if (const auto *InitList = dyn_cast<InitListExpr>(Initializer)) {
  720. unsigned ElementIndex = 0;
  721. for (const Expr *Init : InitList->inits()) {
  722. if (std::optional<PrimType> T = classify(Init->getType())) {
  723. // Visit the primitive element like normal.
  724. if (!this->emitDupPtr(Init))
  725. return false;
  726. if (!this->visit(Init))
  727. return false;
  728. if (!this->emitInitElem(*T, ElementIndex, Init))
  729. return false;
  730. } else {
  731. // Advance the pointer currently on the stack to the given
  732. // dimension and narrow().
  733. if (!this->emitDupPtr(Init))
  734. return false;
  735. if (!this->emitConstUint32(ElementIndex, Init))
  736. return false;
  737. if (!this->emitAddOffsetUint32(Init))
  738. return false;
  739. if (!this->emitNarrowPtr(Init))
  740. return false;
  741. if (!visitInitializer(Init))
  742. return false;
  743. }
  744. if (!this->emitPopPtr(Init))
  745. return false;
  746. ++ElementIndex;
  747. }
  748. return true;
  749. } else if (const auto *DIE = dyn_cast<CXXDefaultInitExpr>(Initializer)) {
  750. return this->visitInitializer(DIE->getExpr());
  751. } else if (const auto *AILE = dyn_cast<ArrayInitLoopExpr>(Initializer)) {
  752. // TODO: This compiles to quite a lot of bytecode if the array is larger.
  753. // Investigate compiling this to a loop, or at least try to use
  754. // the AILE's Common expr.
  755. const Expr *SubExpr = AILE->getSubExpr();
  756. size_t Size = AILE->getArraySize().getZExtValue();
  757. std::optional<PrimType> ElemT = classify(SubExpr->getType());
  758. // So, every iteration, we execute an assignment here
  759. // where the LHS is on the stack (the target array)
  760. // and the RHS is our SubExpr.
  761. for (size_t I = 0; I != Size; ++I) {
  762. ArrayIndexScope<Emitter> IndexScope(this, I);
  763. if (!this->emitDupPtr(SubExpr)) // LHS
  764. return false;
  765. if (ElemT) {
  766. if (!this->visit(SubExpr))
  767. return false;
  768. if (!this->emitInitElem(*ElemT, I, Initializer))
  769. return false;
  770. } else {
  771. // Narrow to our array element and recurse into visitInitializer()
  772. if (!this->emitConstUint64(I, SubExpr))
  773. return false;
  774. if (!this->emitAddOffsetUint64(SubExpr))
  775. return false;
  776. if (!this->emitNarrowPtr(SubExpr))
  777. return false;
  778. if (!visitInitializer(SubExpr))
  779. return false;
  780. }
  781. if (!this->emitPopPtr(Initializer))
  782. return false;
  783. }
  784. return true;
  785. } else if (const auto *IVIE = dyn_cast<ImplicitValueInitExpr>(Initializer)) {
  786. const ArrayType *AT = IVIE->getType()->getAsArrayTypeUnsafe();
  787. assert(AT);
  788. const auto *CAT = cast<ConstantArrayType>(AT);
  789. size_t NumElems = CAT->getSize().getZExtValue();
  790. if (std::optional<PrimType> ElemT = classify(CAT->getElementType())) {
  791. // TODO(perf): For int and bool types, we can probably just skip this
  792. // since we memset our Block*s to 0 and so we have the desired value
  793. // without this.
  794. for (size_t I = 0; I != NumElems; ++I) {
  795. if (!this->emitZero(*ElemT, Initializer))
  796. return false;
  797. if (!this->emitInitElem(*ElemT, I, Initializer))
  798. return false;
  799. }
  800. } else {
  801. assert(false && "default initializer for non-primitive type");
  802. }
  803. return true;
  804. } else if (const auto *Ctor = dyn_cast<CXXConstructExpr>(Initializer)) {
  805. const ConstantArrayType *CAT =
  806. Ctx.getASTContext().getAsConstantArrayType(Ctor->getType());
  807. assert(CAT);
  808. size_t NumElems = CAT->getSize().getZExtValue();
  809. const Function *Func = getFunction(Ctor->getConstructor());
  810. if (!Func || !Func->isConstexpr())
  811. return false;
  812. // FIXME(perf): We're calling the constructor once per array element here,
  813. // in the old intepreter we had a special-case for trivial constructors.
  814. for (size_t I = 0; I != NumElems; ++I) {
  815. if (!this->emitDupPtr(Initializer))
  816. return false;
  817. if (!this->emitConstUint64(I, Initializer))
  818. return false;
  819. if (!this->emitAddOffsetUint64(Initializer))
  820. return false;
  821. if (!this->emitNarrowPtr(Initializer))
  822. return false;
  823. // Constructor arguments.
  824. for (const auto *Arg : Ctor->arguments()) {
  825. if (!this->visit(Arg))
  826. return false;
  827. }
  828. if (!this->emitCall(Func, Initializer))
  829. return false;
  830. }
  831. return true;
  832. }
  833. assert(false && "Unknown expression for array initialization");
  834. return false;
  835. }
  836. template <class Emitter>
  837. bool ByteCodeExprGen<Emitter>::visitRecordInitializer(const Expr *Initializer) {
  838. Initializer = Initializer->IgnoreParenImpCasts();
  839. assert(Initializer->getType()->isRecordType());
  840. if (const auto CtorExpr = dyn_cast<CXXConstructExpr>(Initializer)) {
  841. const Function *Func = getFunction(CtorExpr->getConstructor());
  842. if (!Func || !Func->isConstexpr())
  843. return false;
  844. // The This pointer is already on the stack because this is an initializer,
  845. // but we need to dup() so the call() below has its own copy.
  846. if (!this->emitDupPtr(Initializer))
  847. return false;
  848. // Constructor arguments.
  849. for (const auto *Arg : CtorExpr->arguments()) {
  850. if (!this->visit(Arg))
  851. return false;
  852. }
  853. return this->emitCall(Func, Initializer);
  854. } else if (const auto *InitList = dyn_cast<InitListExpr>(Initializer)) {
  855. const Record *R = getRecord(InitList->getType());
  856. unsigned InitIndex = 0;
  857. for (const Expr *Init : InitList->inits()) {
  858. const Record::Field *FieldToInit = R->getField(InitIndex);
  859. if (!this->emitDupPtr(Initializer))
  860. return false;
  861. if (std::optional<PrimType> T = classify(Init)) {
  862. if (!this->visit(Init))
  863. return false;
  864. if (!this->emitInitField(*T, FieldToInit->Offset, Initializer))
  865. return false;
  866. if (!this->emitPopPtr(Initializer))
  867. return false;
  868. } else {
  869. // Non-primitive case. Get a pointer to the field-to-initialize
  870. // on the stack and recurse into visitInitializer().
  871. if (!this->emitGetPtrField(FieldToInit->Offset, Init))
  872. return false;
  873. if (!this->visitInitializer(Init))
  874. return false;
  875. if (!this->emitPopPtr(Initializer))
  876. return false;
  877. }
  878. ++InitIndex;
  879. }
  880. return true;
  881. } else if (const CallExpr *CE = dyn_cast<CallExpr>(Initializer)) {
  882. // RVO functions expect a pointer to initialize on the stack.
  883. // Dup our existing pointer so it has its own copy to use.
  884. if (!this->emitDupPtr(Initializer))
  885. return false;
  886. return this->VisitCallExpr(CE);
  887. } else if (const auto *DIE = dyn_cast<CXXDefaultInitExpr>(Initializer)) {
  888. return this->visitInitializer(DIE->getExpr());
  889. }
  890. return false;
  891. }
  892. template <class Emitter>
  893. bool ByteCodeExprGen<Emitter>::visitInitializer(const Expr *Initializer) {
  894. QualType InitializerType = Initializer->getType();
  895. if (InitializerType->isArrayType())
  896. return visitArrayInitializer(Initializer);
  897. if (InitializerType->isRecordType())
  898. return visitRecordInitializer(Initializer);
  899. // Otherwise, visit the expression like normal.
  900. return this->visit(Initializer);
  901. }
  902. template <class Emitter>
  903. const RecordType *ByteCodeExprGen<Emitter>::getRecordTy(QualType Ty) {
  904. if (const PointerType *PT = dyn_cast<PointerType>(Ty))
  905. return PT->getPointeeType()->getAs<RecordType>();
  906. else
  907. return Ty->getAs<RecordType>();
  908. }
  909. template <class Emitter>
  910. Record *ByteCodeExprGen<Emitter>::getRecord(QualType Ty) {
  911. if (auto *RecordTy = getRecordTy(Ty)) {
  912. return getRecord(RecordTy->getDecl());
  913. }
  914. return nullptr;
  915. }
  916. template <class Emitter>
  917. Record *ByteCodeExprGen<Emitter>::getRecord(const RecordDecl *RD) {
  918. return P.getOrCreateRecord(RD);
  919. }
  920. template <class Emitter>
  921. const Function *ByteCodeExprGen<Emitter>::getFunction(const FunctionDecl *FD) {
  922. assert(FD);
  923. const Function *Func = P.getFunction(FD);
  924. bool IsBeingCompiled = Func && !Func->isFullyCompiled();
  925. bool WasNotDefined = Func && !Func->hasBody();
  926. if (IsBeingCompiled)
  927. return Func;
  928. if (!Func || WasNotDefined) {
  929. if (auto R = ByteCodeStmtGen<ByteCodeEmitter>(Ctx, P).compileFunc(FD))
  930. Func = *R;
  931. else {
  932. llvm::consumeError(R.takeError());
  933. return nullptr;
  934. }
  935. }
  936. return Func;
  937. }
  938. template <class Emitter>
  939. bool ByteCodeExprGen<Emitter>::visitExpr(const Expr *Exp) {
  940. ExprScope<Emitter> RootScope(this);
  941. if (!visit(Exp))
  942. return false;
  943. if (std::optional<PrimType> T = classify(Exp))
  944. return this->emitRet(*T, Exp);
  945. else
  946. return this->emitRetValue(Exp);
  947. }
  948. /// Toplevel visitDecl().
  949. /// We get here from evaluateAsInitializer().
  950. /// We need to evaluate the initializer and return its value.
  951. template <class Emitter>
  952. bool ByteCodeExprGen<Emitter>::visitDecl(const VarDecl *VD) {
  953. std::optional<PrimType> VarT = classify(VD->getType());
  954. // Create and initialize the variable.
  955. if (!this->visitVarDecl(VD))
  956. return false;
  957. // Get a pointer to the variable
  958. if (shouldBeGloballyIndexed(VD)) {
  959. auto GlobalIndex = P.getGlobal(VD);
  960. assert(GlobalIndex); // visitVarDecl() didn't return false.
  961. if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
  962. return false;
  963. } else {
  964. auto Local = Locals.find(VD);
  965. assert(Local != Locals.end()); // Same here.
  966. if (!this->emitGetPtrLocal(Local->second.Offset, VD))
  967. return false;
  968. }
  969. // Return the value
  970. if (VarT) {
  971. if (!this->emitLoadPop(*VarT, VD))
  972. return false;
  973. return this->emitRet(*VarT, VD);
  974. }
  975. return this->emitRetValue(VD);
  976. }
  977. template <class Emitter>
  978. bool ByteCodeExprGen<Emitter>::visitVarDecl(const VarDecl *VD) {
  979. const Expr *Init = VD->getInit();
  980. std::optional<PrimType> VarT = classify(VD->getType());
  981. if (shouldBeGloballyIndexed(VD)) {
  982. std::optional<unsigned> GlobalIndex = P.getOrCreateGlobal(VD, Init);
  983. if (!GlobalIndex)
  984. return this->bail(VD);
  985. assert(Init);
  986. {
  987. DeclScope<Emitter> LocalScope(this, VD);
  988. if (VarT) {
  989. if (!this->visit(Init))
  990. return false;
  991. return this->emitInitGlobal(*VarT, *GlobalIndex, VD);
  992. }
  993. return this->visitGlobalInitializer(Init, *GlobalIndex);
  994. }
  995. } else {
  996. VariableScope<Emitter> LocalScope(this);
  997. if (VarT) {
  998. unsigned Offset = this->allocateLocalPrimitive(
  999. VD, *VarT, VD->getType().isConstQualified());
  1000. if (Init) {
  1001. // Compile the initializer in its own scope.
  1002. ExprScope<Emitter> Scope(this);
  1003. if (!this->visit(Init))
  1004. return false;
  1005. return this->emitSetLocal(*VarT, Offset, VD);
  1006. }
  1007. } else {
  1008. if (std::optional<unsigned> Offset = this->allocateLocal(VD)) {
  1009. if (Init)
  1010. return this->visitLocalInitializer(Init, *Offset);
  1011. }
  1012. }
  1013. return true;
  1014. }
  1015. return false;
  1016. }
  1017. template <class Emitter>
  1018. bool ByteCodeExprGen<Emitter>::VisitCallExpr(const CallExpr *E) {
  1019. assert(!E->getBuiltinCallee() && "Builtin functions aren't supported yet");
  1020. const Decl *Callee = E->getCalleeDecl();
  1021. if (const auto *FuncDecl = dyn_cast_or_null<FunctionDecl>(Callee)) {
  1022. const Function *Func = getFunction(FuncDecl);
  1023. if (!Func)
  1024. return false;
  1025. // If the function is being compiled right now, this is a recursive call.
  1026. // In that case, the function can't be valid yet, even though it will be
  1027. // later.
  1028. // If the function is already fully compiled but not constexpr, it was
  1029. // found to be faulty earlier on, so bail out.
  1030. if (Func->isFullyCompiled() && !Func->isConstexpr())
  1031. return false;
  1032. QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
  1033. std::optional<PrimType> T = classify(ReturnType);
  1034. if (Func->hasRVO() && DiscardResult) {
  1035. // If we need to discard the return value but the function returns its
  1036. // value via an RVO pointer, we need to create one such pointer just
  1037. // for this call.
  1038. if (std::optional<unsigned> LocalIndex = allocateLocal(E)) {
  1039. if (!this->emitGetPtrLocal(*LocalIndex, E))
  1040. return false;
  1041. }
  1042. }
  1043. // Put arguments on the stack.
  1044. for (const auto *Arg : E->arguments()) {
  1045. if (!this->visit(Arg))
  1046. return false;
  1047. }
  1048. // In any case call the function. The return value will end up on the stack and
  1049. // if the function has RVO, we already have the pointer on the stack to write
  1050. // the result into.
  1051. if (!this->emitCall(Func, E))
  1052. return false;
  1053. if (DiscardResult && !ReturnType->isVoidType() && T)
  1054. return this->emitPop(*T, E);
  1055. return true;
  1056. } else {
  1057. assert(false && "We don't support non-FunctionDecl callees right now.");
  1058. }
  1059. return false;
  1060. }
  1061. template <class Emitter>
  1062. bool ByteCodeExprGen<Emitter>::VisitCXXMemberCallExpr(
  1063. const CXXMemberCallExpr *E) {
  1064. // Get a This pointer on the stack.
  1065. if (!this->visit(E->getImplicitObjectArgument()))
  1066. return false;
  1067. return VisitCallExpr(E);
  1068. }
  1069. template <class Emitter>
  1070. bool ByteCodeExprGen<Emitter>::VisitCXXDefaultInitExpr(
  1071. const CXXDefaultInitExpr *E) {
  1072. return this->visit(E->getExpr());
  1073. }
  1074. template <class Emitter>
  1075. bool ByteCodeExprGen<Emitter>::VisitCXXDefaultArgExpr(
  1076. const CXXDefaultArgExpr *E) {
  1077. return this->visit(E->getExpr());
  1078. }
  1079. template <class Emitter>
  1080. bool ByteCodeExprGen<Emitter>::VisitCXXBoolLiteralExpr(
  1081. const CXXBoolLiteralExpr *E) {
  1082. if (DiscardResult)
  1083. return true;
  1084. return this->emitConstBool(E->getValue(), E);
  1085. }
  1086. template <class Emitter>
  1087. bool ByteCodeExprGen<Emitter>::VisitCXXNullPtrLiteralExpr(
  1088. const CXXNullPtrLiteralExpr *E) {
  1089. if (DiscardResult)
  1090. return true;
  1091. return this->emitNullPtr(E);
  1092. }
  1093. template <class Emitter>
  1094. bool ByteCodeExprGen<Emitter>::VisitCXXThisExpr(const CXXThisExpr *E) {
  1095. if (DiscardResult)
  1096. return true;
  1097. return this->emitThis(E);
  1098. }
  1099. template <class Emitter>
  1100. bool ByteCodeExprGen<Emitter>::VisitUnaryOperator(const UnaryOperator *E) {
  1101. const Expr *SubExpr = E->getSubExpr();
  1102. std::optional<PrimType> T = classify(SubExpr->getType());
  1103. // TODO: Support pointers for inc/dec operators.
  1104. switch (E->getOpcode()) {
  1105. case UO_PostInc: { // x++
  1106. if (!this->visit(SubExpr))
  1107. return false;
  1108. return DiscardResult ? this->emitIncPop(*T, E) : this->emitInc(*T, E);
  1109. }
  1110. case UO_PostDec: { // x--
  1111. if (!this->visit(SubExpr))
  1112. return false;
  1113. return DiscardResult ? this->emitDecPop(*T, E) : this->emitDec(*T, E);
  1114. }
  1115. case UO_PreInc: { // ++x
  1116. if (!this->visit(SubExpr))
  1117. return false;
  1118. // Post-inc and pre-inc are the same if the value is to be discarded.
  1119. if (DiscardResult)
  1120. return this->emitIncPop(*T, E);
  1121. this->emitLoad(*T, E);
  1122. this->emitConst(1, E);
  1123. this->emitAdd(*T, E);
  1124. return this->emitStore(*T, E);
  1125. }
  1126. case UO_PreDec: { // --x
  1127. if (!this->visit(SubExpr))
  1128. return false;
  1129. // Post-dec and pre-dec are the same if the value is to be discarded.
  1130. if (DiscardResult)
  1131. return this->emitDecPop(*T, E);
  1132. this->emitLoad(*T, E);
  1133. this->emitConst(1, E);
  1134. this->emitSub(*T, E);
  1135. return this->emitStore(*T, E);
  1136. }
  1137. case UO_LNot: // !x
  1138. if (!this->visit(SubExpr))
  1139. return false;
  1140. // The Inv doesn't change anything, so skip it if we don't need the result.
  1141. return DiscardResult ? this->emitPop(*T, E) : this->emitInvBool(E);
  1142. case UO_Minus: // -x
  1143. if (!this->visit(SubExpr))
  1144. return false;
  1145. return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E);
  1146. case UO_Plus: // +x
  1147. if (!this->visit(SubExpr)) // noop
  1148. return false;
  1149. return DiscardResult ? this->emitPop(*T, E) : true;
  1150. case UO_AddrOf: // &x
  1151. // We should already have a pointer when we get here.
  1152. if (!this->visit(SubExpr))
  1153. return false;
  1154. return DiscardResult ? this->emitPop(*T, E) : true;
  1155. case UO_Deref: // *x
  1156. return dereference(
  1157. SubExpr, DerefKind::Read,
  1158. [](PrimType) {
  1159. llvm_unreachable("Dereferencing requires a pointer");
  1160. return false;
  1161. },
  1162. [this, E](PrimType T) {
  1163. return DiscardResult ? this->emitPop(T, E) : true;
  1164. });
  1165. case UO_Not: // ~x
  1166. if (!this->visit(SubExpr))
  1167. return false;
  1168. return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
  1169. case UO_Real: // __real x
  1170. case UO_Imag: // __imag x
  1171. case UO_Extension:
  1172. case UO_Coawait:
  1173. assert(false && "Unhandled opcode");
  1174. }
  1175. return false;
  1176. }
  1177. template <class Emitter>
  1178. bool ByteCodeExprGen<Emitter>::VisitDeclRefExpr(const DeclRefExpr *E) {
  1179. const auto *Decl = E->getDecl();
  1180. // References are implemented via pointers, so when we see a DeclRefExpr
  1181. // pointing to a reference, we need to get its value directly (i.e. the
  1182. // pointer to the actual value) instead of a pointer to the pointer to the
  1183. // value.
  1184. bool IsReference = Decl->getType()->isReferenceType();
  1185. if (auto It = Locals.find(Decl); It != Locals.end()) {
  1186. const unsigned Offset = It->second.Offset;
  1187. if (IsReference)
  1188. return this->emitGetLocal(PT_Ptr, Offset, E);
  1189. return this->emitGetPtrLocal(Offset, E);
  1190. } else if (auto GlobalIndex = P.getGlobal(Decl)) {
  1191. if (IsReference)
  1192. return this->emitGetGlobal(PT_Ptr, *GlobalIndex, E);
  1193. return this->emitGetPtrGlobal(*GlobalIndex, E);
  1194. } else if (const auto *PVD = dyn_cast<ParmVarDecl>(Decl)) {
  1195. if (auto It = this->Params.find(PVD); It != this->Params.end()) {
  1196. if (IsReference)
  1197. return this->emitGetParam(PT_Ptr, It->second, E);
  1198. return this->emitGetPtrParam(It->second, E);
  1199. }
  1200. } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(Decl)) {
  1201. return this->emitConst(ECD->getInitVal(), E);
  1202. }
  1203. return false;
  1204. }
  1205. template <class Emitter>
  1206. void ByteCodeExprGen<Emitter>::emitCleanup() {
  1207. for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent())
  1208. C->emitDestruction();
  1209. }
  1210. namespace clang {
  1211. namespace interp {
  1212. template class ByteCodeExprGen<ByteCodeEmitter>;
  1213. template class ByteCodeExprGen<EvalEmitter>;
  1214. } // namespace interp
  1215. } // namespace clang