Program.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. //===--- Program.cpp - Bytecode for the constexpr VM ------------*- 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 "Program.h"
  9. #include "ByteCodeStmtGen.h"
  10. #include "Context.h"
  11. #include "Function.h"
  12. #include "Opcode.h"
  13. #include "PrimType.h"
  14. #include "clang/AST/Decl.h"
  15. #include "clang/AST/DeclCXX.h"
  16. using namespace clang;
  17. using namespace clang::interp;
  18. unsigned Program::createGlobalString(const StringLiteral *S) {
  19. const size_t CharWidth = S->getCharByteWidth();
  20. const size_t BitWidth = CharWidth * Ctx.getCharBit();
  21. PrimType CharType;
  22. switch (CharWidth) {
  23. case 1:
  24. CharType = PT_Sint8;
  25. break;
  26. case 2:
  27. CharType = PT_Uint16;
  28. break;
  29. case 4:
  30. CharType = PT_Uint32;
  31. break;
  32. default:
  33. llvm_unreachable("unsupported character width");
  34. }
  35. // Create a descriptor for the string.
  36. Descriptor *Desc = allocateDescriptor(S, CharType, S->getLength() + 1,
  37. /*isConst=*/true,
  38. /*isTemporary=*/false,
  39. /*isMutable=*/false);
  40. // Allocate storage for the string.
  41. // The byte length does not include the null terminator.
  42. unsigned I = Globals.size();
  43. unsigned Sz = Desc->getAllocSize();
  44. auto *G = new (Allocator, Sz) Global(Desc, /*isStatic=*/true,
  45. /*isExtern=*/false);
  46. Globals.push_back(G);
  47. // Construct the string in storage.
  48. const Pointer Ptr(G->block());
  49. for (unsigned I = 0, N = S->getLength(); I <= N; ++I) {
  50. Pointer Field = Ptr.atIndex(I).narrow();
  51. const uint32_t CodePoint = I == N ? 0 : S->getCodeUnit(I);
  52. switch (CharType) {
  53. case PT_Sint8: {
  54. using T = PrimConv<PT_Sint8>::T;
  55. Field.deref<T>() = T::from(CodePoint, BitWidth);
  56. break;
  57. }
  58. case PT_Uint16: {
  59. using T = PrimConv<PT_Uint16>::T;
  60. Field.deref<T>() = T::from(CodePoint, BitWidth);
  61. break;
  62. }
  63. case PT_Uint32: {
  64. using T = PrimConv<PT_Uint32>::T;
  65. Field.deref<T>() = T::from(CodePoint, BitWidth);
  66. break;
  67. }
  68. default:
  69. llvm_unreachable("unsupported character type");
  70. }
  71. }
  72. return I;
  73. }
  74. Pointer Program::getPtrGlobal(unsigned Idx) {
  75. assert(Idx < Globals.size());
  76. return Pointer(Globals[Idx]->block());
  77. }
  78. llvm::Optional<unsigned> Program::getGlobal(const ValueDecl *VD) {
  79. auto It = GlobalIndices.find(VD);
  80. if (It != GlobalIndices.end())
  81. return It->second;
  82. // Find any previous declarations which were aleady evaluated.
  83. llvm::Optional<unsigned> Index;
  84. for (const Decl *P = VD; P; P = P->getPreviousDecl()) {
  85. auto It = GlobalIndices.find(P);
  86. if (It != GlobalIndices.end()) {
  87. Index = It->second;
  88. break;
  89. }
  90. }
  91. // Map the decl to the existing index.
  92. if (Index) {
  93. GlobalIndices[VD] = *Index;
  94. return {};
  95. }
  96. return Index;
  97. }
  98. llvm::Optional<unsigned> Program::getOrCreateGlobal(const ValueDecl *VD) {
  99. if (auto Idx = getGlobal(VD))
  100. return Idx;
  101. if (auto Idx = createGlobal(VD)) {
  102. GlobalIndices[VD] = *Idx;
  103. return Idx;
  104. }
  105. return {};
  106. }
  107. llvm::Optional<unsigned> Program::getOrCreateDummy(const ParmVarDecl *PD) {
  108. auto &ASTCtx = Ctx.getASTContext();
  109. // Create a pointer to an incomplete array of the specified elements.
  110. QualType ElemTy = PD->getType()->getAs<PointerType>()->getPointeeType();
  111. QualType Ty = ASTCtx.getIncompleteArrayType(ElemTy, ArrayType::Normal, 0);
  112. // Dedup blocks since they are immutable and pointers cannot be compared.
  113. auto It = DummyParams.find(PD);
  114. if (It != DummyParams.end())
  115. return It->second;
  116. if (auto Idx = createGlobal(PD, Ty, /*isStatic=*/true, /*isExtern=*/true)) {
  117. DummyParams[PD] = *Idx;
  118. return Idx;
  119. }
  120. return {};
  121. }
  122. llvm::Optional<unsigned> Program::createGlobal(const ValueDecl *VD) {
  123. bool IsStatic, IsExtern;
  124. if (auto *Var = dyn_cast<VarDecl>(VD)) {
  125. IsStatic = !Var->hasLocalStorage();
  126. IsExtern = !Var->getAnyInitializer();
  127. } else {
  128. IsStatic = false;
  129. IsExtern = true;
  130. }
  131. if (auto Idx = createGlobal(VD, VD->getType(), IsStatic, IsExtern)) {
  132. for (const Decl *P = VD; P; P = P->getPreviousDecl())
  133. GlobalIndices[P] = *Idx;
  134. return *Idx;
  135. }
  136. return {};
  137. }
  138. llvm::Optional<unsigned> Program::createGlobal(const Expr *E) {
  139. return createGlobal(E, E->getType(), /*isStatic=*/true, /*isExtern=*/false);
  140. }
  141. llvm::Optional<unsigned> Program::createGlobal(const DeclTy &D, QualType Ty,
  142. bool IsStatic, bool IsExtern) {
  143. // Create a descriptor for the global.
  144. Descriptor *Desc;
  145. const bool IsConst = Ty.isConstQualified();
  146. const bool IsTemporary = D.dyn_cast<const Expr *>();
  147. if (auto T = Ctx.classify(Ty)) {
  148. Desc = createDescriptor(D, *T, IsConst, IsTemporary);
  149. } else {
  150. Desc = createDescriptor(D, Ty.getTypePtr(), IsConst, IsTemporary);
  151. }
  152. if (!Desc)
  153. return {};
  154. // Allocate a block for storage.
  155. unsigned I = Globals.size();
  156. auto *G = new (Allocator, Desc->getAllocSize())
  157. Global(getCurrentDecl(), Desc, IsStatic, IsExtern);
  158. G->block()->invokeCtor();
  159. Globals.push_back(G);
  160. return I;
  161. }
  162. Function *Program::getFunction(const FunctionDecl *F) {
  163. F = F->getDefinition();
  164. auto It = Funcs.find(F);
  165. return It == Funcs.end() ? nullptr : It->second.get();
  166. }
  167. llvm::Expected<Function *> Program::getOrCreateFunction(const FunctionDecl *F) {
  168. if (Function *Func = getFunction(F)) {
  169. return Func;
  170. }
  171. // Try to compile the function if it wasn't compiled yet.
  172. if (const FunctionDecl *FD = F->getDefinition())
  173. return ByteCodeStmtGen<ByteCodeEmitter>(Ctx, *this).compileFunc(FD);
  174. // A relocation which traps if not resolved.
  175. return nullptr;
  176. }
  177. Record *Program::getOrCreateRecord(const RecordDecl *RD) {
  178. // Use the actual definition as a key.
  179. RD = RD->getDefinition();
  180. if (!RD)
  181. return nullptr;
  182. // Deduplicate records.
  183. auto It = Records.find(RD);
  184. if (It != Records.end()) {
  185. return It->second;
  186. }
  187. // Number of bytes required by fields and base classes.
  188. unsigned Size = 0;
  189. // Number of bytes required by virtual base.
  190. unsigned VirtSize = 0;
  191. // Helper to get a base descriptor.
  192. auto GetBaseDesc = [this](const RecordDecl *BD, Record *BR) -> Descriptor * {
  193. if (!BR)
  194. return nullptr;
  195. return allocateDescriptor(BD, BR, /*isConst=*/false,
  196. /*isTemporary=*/false,
  197. /*isMutable=*/false);
  198. };
  199. // Reserve space for base classes.
  200. Record::BaseList Bases;
  201. Record::VirtualBaseList VirtBases;
  202. if (auto *CD = dyn_cast<CXXRecordDecl>(RD)) {
  203. for (const CXXBaseSpecifier &Spec : CD->bases()) {
  204. if (Spec.isVirtual())
  205. continue;
  206. const RecordDecl *BD = Spec.getType()->getAs<RecordType>()->getDecl();
  207. Record *BR = getOrCreateRecord(BD);
  208. if (Descriptor *Desc = GetBaseDesc(BD, BR)) {
  209. Size += align(sizeof(InlineDescriptor));
  210. Bases.push_back({BD, Size, Desc, BR});
  211. Size += align(BR->getSize());
  212. continue;
  213. }
  214. return nullptr;
  215. }
  216. for (const CXXBaseSpecifier &Spec : CD->vbases()) {
  217. const RecordDecl *BD = Spec.getType()->getAs<RecordType>()->getDecl();
  218. Record *BR = getOrCreateRecord(BD);
  219. if (Descriptor *Desc = GetBaseDesc(BD, BR)) {
  220. VirtSize += align(sizeof(InlineDescriptor));
  221. VirtBases.push_back({BD, VirtSize, Desc, BR});
  222. VirtSize += align(BR->getSize());
  223. continue;
  224. }
  225. return nullptr;
  226. }
  227. }
  228. // Reserve space for fields.
  229. Record::FieldList Fields;
  230. for (const FieldDecl *FD : RD->fields()) {
  231. // Reserve space for the field's descriptor and the offset.
  232. Size += align(sizeof(InlineDescriptor));
  233. // Classify the field and add its metadata.
  234. QualType FT = FD->getType();
  235. const bool IsConst = FT.isConstQualified();
  236. const bool IsMutable = FD->isMutable();
  237. Descriptor *Desc;
  238. if (llvm::Optional<PrimType> T = Ctx.classify(FT)) {
  239. Desc = createDescriptor(FD, *T, IsConst, /*isTemporary=*/false,
  240. IsMutable);
  241. } else {
  242. Desc = createDescriptor(FD, FT.getTypePtr(), IsConst,
  243. /*isTemporary=*/false, IsMutable);
  244. }
  245. if (!Desc)
  246. return nullptr;
  247. Fields.push_back({FD, Size, Desc});
  248. Size += align(Desc->getAllocSize());
  249. }
  250. Record *R = new (Allocator) Record(RD, std::move(Bases), std::move(Fields),
  251. std::move(VirtBases), VirtSize, Size);
  252. Records.insert({RD, R});
  253. return R;
  254. }
  255. Descriptor *Program::createDescriptor(const DeclTy &D, const Type *Ty,
  256. bool IsConst, bool IsTemporary,
  257. bool IsMutable) {
  258. // Classes and structures.
  259. if (auto *RT = Ty->getAs<RecordType>()) {
  260. if (auto *Record = getOrCreateRecord(RT->getDecl()))
  261. return allocateDescriptor(D, Record, IsConst, IsTemporary, IsMutable);
  262. }
  263. // Arrays.
  264. if (auto ArrayType = Ty->getAsArrayTypeUnsafe()) {
  265. QualType ElemTy = ArrayType->getElementType();
  266. // Array of well-known bounds.
  267. if (auto CAT = dyn_cast<ConstantArrayType>(ArrayType)) {
  268. size_t NumElems = CAT->getSize().getZExtValue();
  269. if (llvm::Optional<PrimType> T = Ctx.classify(ElemTy)) {
  270. // Arrays of primitives.
  271. unsigned ElemSize = primSize(*T);
  272. if (std::numeric_limits<unsigned>::max() / ElemSize <= NumElems) {
  273. return {};
  274. }
  275. return allocateDescriptor(D, *T, NumElems, IsConst, IsTemporary,
  276. IsMutable);
  277. } else {
  278. // Arrays of composites. In this case, the array is a list of pointers,
  279. // followed by the actual elements.
  280. Descriptor *Desc =
  281. createDescriptor(D, ElemTy.getTypePtr(), IsConst, IsTemporary);
  282. if (!Desc)
  283. return nullptr;
  284. InterpSize ElemSize = Desc->getAllocSize() + sizeof(InlineDescriptor);
  285. if (std::numeric_limits<unsigned>::max() / ElemSize <= NumElems)
  286. return {};
  287. return allocateDescriptor(D, Desc, NumElems, IsConst, IsTemporary,
  288. IsMutable);
  289. }
  290. }
  291. // Array of unknown bounds - cannot be accessed and pointer arithmetic
  292. // is forbidden on pointers to such objects.
  293. if (isa<IncompleteArrayType>(ArrayType)) {
  294. if (llvm::Optional<PrimType> T = Ctx.classify(ElemTy)) {
  295. return allocateDescriptor(D, *T, IsTemporary,
  296. Descriptor::UnknownSize{});
  297. } else {
  298. Descriptor *Desc =
  299. createDescriptor(D, ElemTy.getTypePtr(), IsConst, IsTemporary);
  300. if (!Desc)
  301. return nullptr;
  302. return allocateDescriptor(D, Desc, IsTemporary,
  303. Descriptor::UnknownSize{});
  304. }
  305. }
  306. }
  307. // Atomic types.
  308. if (auto *AT = Ty->getAs<AtomicType>()) {
  309. const Type *InnerTy = AT->getValueType().getTypePtr();
  310. return createDescriptor(D, InnerTy, IsConst, IsTemporary, IsMutable);
  311. }
  312. // Complex types - represented as arrays of elements.
  313. if (auto *CT = Ty->getAs<ComplexType>()) {
  314. PrimType ElemTy = *Ctx.classify(CT->getElementType());
  315. return allocateDescriptor(D, ElemTy, 2, IsConst, IsTemporary, IsMutable);
  316. }
  317. return nullptr;
  318. }