ByteCodeEmitter.cpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. //===--- ByteCodeEmitter.cpp - Instruction emitter for the 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 "ByteCodeEmitter.h"
  9. #include "Context.h"
  10. #include "Opcode.h"
  11. #include "Program.h"
  12. #include "clang/AST/DeclCXX.h"
  13. #include <type_traits>
  14. using namespace clang;
  15. using namespace clang::interp;
  16. using APSInt = llvm::APSInt;
  17. using Error = llvm::Error;
  18. Expected<Function *>
  19. ByteCodeEmitter::compileFunc(const FunctionDecl *FuncDecl) {
  20. // Function is not defined at all or not yet. We will
  21. // create a Function instance but not compile the body. That
  22. // will (maybe) happen later.
  23. bool HasBody = FuncDecl->hasBody(FuncDecl);
  24. // Create a handle over the emitted code.
  25. Function *Func = P.getFunction(FuncDecl);
  26. if (!Func) {
  27. // Set up argument indices.
  28. unsigned ParamOffset = 0;
  29. SmallVector<PrimType, 8> ParamTypes;
  30. llvm::DenseMap<unsigned, Function::ParamDescriptor> ParamDescriptors;
  31. // If the return is not a primitive, a pointer to the storage where the
  32. // value is initialized in is passed as the first argument. See 'RVO'
  33. // elsewhere in the code.
  34. QualType Ty = FuncDecl->getReturnType();
  35. bool HasRVO = false;
  36. if (!Ty->isVoidType() && !Ctx.classify(Ty)) {
  37. HasRVO = true;
  38. ParamTypes.push_back(PT_Ptr);
  39. ParamOffset += align(primSize(PT_Ptr));
  40. }
  41. // If the function decl is a member decl, the next parameter is
  42. // the 'this' pointer. This parameter is pop()ed from the
  43. // InterpStack when calling the function.
  44. bool HasThisPointer = false;
  45. if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl);
  46. MD && MD->isInstance()) {
  47. HasThisPointer = true;
  48. ParamTypes.push_back(PT_Ptr);
  49. ParamOffset += align(primSize(PT_Ptr));
  50. }
  51. // Assign descriptors to all parameters.
  52. // Composite objects are lowered to pointers.
  53. for (const ParmVarDecl *PD : FuncDecl->parameters()) {
  54. PrimType Ty = Ctx.classify(PD->getType()).value_or(PT_Ptr);
  55. Descriptor *Desc = P.createDescriptor(PD, Ty);
  56. ParamDescriptors.insert({ParamOffset, {Ty, Desc}});
  57. Params.insert({PD, ParamOffset});
  58. ParamOffset += align(primSize(Ty));
  59. ParamTypes.push_back(Ty);
  60. }
  61. Func =
  62. P.createFunction(FuncDecl, ParamOffset, std::move(ParamTypes),
  63. std::move(ParamDescriptors), HasThisPointer, HasRVO);
  64. }
  65. assert(Func);
  66. if (!HasBody)
  67. return Func;
  68. // Compile the function body.
  69. if (!FuncDecl->isConstexpr() || !visitFunc(FuncDecl)) {
  70. // Return a dummy function if compilation failed.
  71. if (BailLocation)
  72. return llvm::make_error<ByteCodeGenError>(*BailLocation);
  73. else {
  74. Func->setIsFullyCompiled(true);
  75. return Func;
  76. }
  77. } else {
  78. // Create scopes from descriptors.
  79. llvm::SmallVector<Scope, 2> Scopes;
  80. for (auto &DS : Descriptors) {
  81. Scopes.emplace_back(std::move(DS));
  82. }
  83. // Set the function's code.
  84. Func->setCode(NextLocalOffset, std::move(Code), std::move(SrcMap),
  85. std::move(Scopes));
  86. Func->setIsFullyCompiled(true);
  87. return Func;
  88. }
  89. }
  90. Scope::Local ByteCodeEmitter::createLocal(Descriptor *D) {
  91. NextLocalOffset += sizeof(Block);
  92. unsigned Location = NextLocalOffset;
  93. NextLocalOffset += align(D->getAllocSize());
  94. return {Location, D};
  95. }
  96. void ByteCodeEmitter::emitLabel(LabelTy Label) {
  97. const size_t Target = Code.size();
  98. LabelOffsets.insert({Label, Target});
  99. auto It = LabelRelocs.find(Label);
  100. if (It != LabelRelocs.end()) {
  101. for (unsigned Reloc : It->second) {
  102. using namespace llvm::support;
  103. /// Rewrite the operand of all jumps to this label.
  104. void *Location = Code.data() + Reloc - align(sizeof(int32_t));
  105. assert(aligned(Location));
  106. const int32_t Offset = Target - static_cast<int64_t>(Reloc);
  107. endian::write<int32_t, endianness::native, 1>(Location, Offset);
  108. }
  109. LabelRelocs.erase(It);
  110. }
  111. }
  112. int32_t ByteCodeEmitter::getOffset(LabelTy Label) {
  113. // Compute the PC offset which the jump is relative to.
  114. const int64_t Position =
  115. Code.size() + align(sizeof(Opcode)) + align(sizeof(int32_t));
  116. assert(aligned(Position));
  117. // If target is known, compute jump offset.
  118. auto It = LabelOffsets.find(Label);
  119. if (It != LabelOffsets.end()) {
  120. return It->second - Position;
  121. }
  122. // Otherwise, record relocation and return dummy offset.
  123. LabelRelocs[Label].push_back(Position);
  124. return 0ull;
  125. }
  126. bool ByteCodeEmitter::bail(const SourceLocation &Loc) {
  127. if (!BailLocation)
  128. BailLocation = Loc;
  129. return false;
  130. }
  131. /// Helper to write bytecode and bail out if 32-bit offsets become invalid.
  132. /// Pointers will be automatically marshalled as 32-bit IDs.
  133. template <typename T>
  134. static void emit(Program &P, std::vector<char> &Code, const T &Val,
  135. bool &Success) {
  136. size_t Size;
  137. if constexpr (std::is_pointer_v<T>)
  138. Size = sizeof(uint32_t);
  139. else
  140. Size = sizeof(T);
  141. if (Code.size() + Size > std::numeric_limits<unsigned>::max()) {
  142. Success = false;
  143. return;
  144. }
  145. // Access must be aligned!
  146. size_t ValPos = align(Code.size());
  147. Size = align(Size);
  148. assert(aligned(ValPos + Size));
  149. Code.resize(ValPos + Size);
  150. if constexpr (!std::is_pointer_v<T>) {
  151. new (Code.data() + ValPos) T(Val);
  152. } else {
  153. uint32_t ID = P.getOrCreateNativePointer(Val);
  154. new (Code.data() + ValPos) uint32_t(ID);
  155. }
  156. }
  157. template <typename... Tys>
  158. bool ByteCodeEmitter::emitOp(Opcode Op, const Tys &... Args, const SourceInfo &SI) {
  159. bool Success = true;
  160. /// The opcode is followed by arguments. The source info is
  161. /// attached to the address after the opcode.
  162. emit(P, Code, Op, Success);
  163. if (SI)
  164. SrcMap.emplace_back(Code.size(), SI);
  165. /// The initializer list forces the expression to be evaluated
  166. /// for each argument in the variadic template, in order.
  167. (void)std::initializer_list<int>{(emit(P, Code, Args, Success), 0)...};
  168. return Success;
  169. }
  170. bool ByteCodeEmitter::jumpTrue(const LabelTy &Label) {
  171. return emitJt(getOffset(Label), SourceInfo{});
  172. }
  173. bool ByteCodeEmitter::jumpFalse(const LabelTy &Label) {
  174. return emitJf(getOffset(Label), SourceInfo{});
  175. }
  176. bool ByteCodeEmitter::jump(const LabelTy &Label) {
  177. return emitJmp(getOffset(Label), SourceInfo{});
  178. }
  179. bool ByteCodeEmitter::fallthrough(const LabelTy &Label) {
  180. emitLabel(Label);
  181. return true;
  182. }
  183. //===----------------------------------------------------------------------===//
  184. // Opcode emitters
  185. //===----------------------------------------------------------------------===//
  186. #define GET_LINK_IMPL
  187. #include "Opcodes.inc"
  188. #undef GET_LINK_IMPL