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
9#include "ByteCodeEmitter.h"
10#include "Context.h"
11#include "Floating.h"
12#include "IntegralAP.h"
13#include "Opcode.h"
14#include "Program.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/DeclCXX.h"
18#include <type_traits>
19
20using namespace clang;
21using namespace clang::interp;
22
23void ByteCodeEmitter::compileFunc(const FunctionDecl *FuncDecl,
24 Function *Func) {
25 assert(FuncDecl);
26 assert(Func);
27 assert(FuncDecl->isThisDeclarationADefinition());
28
29 // Manually created functions that haven't been assigned proper
30 // parameters yet.
31 if (!FuncDecl->param_empty() && !FuncDecl->param_begin())
32 return;
33
34 // Set up lambda captures.
35 if (Func->isLambdaCallOperator()) {
36 // Set up lambda capture to closure record field mapping.
37 const CXXRecordDecl *ParentDecl = Func->getParentDecl();
38 const Record *R = P.getOrCreateRecord(RD: ParentDecl);
39 assert(R);
40 llvm::DenseMap<const ValueDecl *, FieldDecl *> LC;
41 FieldDecl *LTC;
42
43 ParentDecl->getCaptureFields(Captures&: LC, ThisCapture&: LTC);
44
45 for (const auto &Cap : LC) {
46 unsigned Offset = R->getField(FD: Cap.second)->Offset;
47 this->LambdaCaptures[Cap.first] = {
48 .Offset: Offset, .IsPtr: Cap.second->getType()->isReferenceType()};
49 }
50 if (LTC) {
51 QualType CaptureType = R->getField(FD: LTC)->Decl->getType();
52 this->LambdaThisCapture = {.Offset: R->getField(FD: LTC)->Offset,
53 .IsPtr: CaptureType->isPointerOrReferenceType()};
54 }
55 }
56
57 bool IsValid = !FuncDecl->isInvalidDecl();
58 // Register parameters and their index.
59 for (unsigned ParamIndex = 0, N = Func->getNumWrittenParams();
60 ParamIndex != N; ++ParamIndex) {
61 const ParmVarDecl *PD = FuncDecl->getParamDecl(i: ParamIndex);
62 if (PD->isInvalidDecl())
63 IsValid = false;
64 this->Params.insert(KV: {PD, {.Index: ParamIndex, .IsPtr: Ctx.canClassify(T: PD->getType())}});
65 }
66
67 Func->setDefined(true);
68
69 // Lambda static invokers are a special case that we emit custom code for.
70 bool IsEligibleForCompilation = Func->isLambdaStaticInvoker() ||
71 FuncDecl->isConstexpr() ||
72 FuncDecl->hasAttr<MSConstexprAttr>();
73
74 // Compile the function body.
75 if (!IsEligibleForCompilation || !visitFunc(E: FuncDecl)) {
76 Func->setIsFullyCompiled(true);
77 return;
78 }
79
80 // Create scopes from descriptors.
81 llvm::SmallVector<Scope, 2> Scopes;
82 for (auto &DS : Descriptors) {
83 Scopes.emplace_back(Args: std::move(DS));
84 }
85
86 // Set the function's code.
87 Func->setCode(Source: FuncDecl, NewFrameSize: NextLocalOffset, NewCode: std::move(Code), NewSrcMap: std::move(SrcMap),
88 NewScopes: std::move(Scopes), NewHasBody: FuncDecl->hasBody(), NewIsValid: IsValid);
89 Func->setIsFullyCompiled(true);
90}
91
92Scope::Local ByteCodeEmitter::createLocal(const Descriptor *D) {
93 NextLocalOffset += sizeof(Block);
94 unsigned Location = NextLocalOffset;
95 NextLocalOffset += align(Size: Block::InlineDescMD + D->getAllocSize());
96 return {.Desc: D, .Offset: Location};
97}
98
99void ByteCodeEmitter::emitLabel(LabelTy Label) {
100 const size_t Target = Code.size();
101 LabelOffsets.insert(KV: {Label, Target});
102
103 if (auto It = LabelRelocs.find(Val: Label); It != LabelRelocs.end()) {
104 for (unsigned Reloc : It->second) {
105 using namespace llvm::support;
106
107 // Rewrite the operand of all jumps to this label.
108 void *Location = Code.data() + Reloc - align(Size: sizeof(int32_t));
109 assert(aligned(Location));
110 const int32_t Offset = Target - static_cast<int64_t>(Reloc);
111 endian::write<int32_t, llvm::endianness::native>(P: Location, V: Offset);
112 }
113 LabelRelocs.erase(I: It);
114 }
115}
116
117int32_t ByteCodeEmitter::getOffset(LabelTy Label) {
118 // Compute the PC offset which the jump is relative to.
119 const int64_t Position =
120 Code.size() + align(Size: sizeof(Opcode)) + align(Size: sizeof(int32_t));
121 assert(aligned(Position));
122
123 // If target is known, compute jump offset.
124 if (auto It = LabelOffsets.find(Val: Label); It != LabelOffsets.end())
125 return It->second - Position;
126
127 // Otherwise, record relocation and return dummy offset.
128 LabelRelocs[Label].push_back(Elt: Position);
129 return 0ull;
130}
131
132/// Helper to write bytecode and bail out if 32-bit offsets become invalid.
133template <typename T>
134static void emit(Program &P, llvm::SmallVectorImpl<std::byte> &Code,
135 const T &Val, bool &Success) {
136 size_t ValPos = Code.size();
137 size_t Size;
138
139 if constexpr (std::is_pointer_v<T>)
140 Size = align(Size: sizeof(uintptr_t));
141 else
142 Size = align(Size: sizeof(T));
143
144 if (ValPos + Size > std::numeric_limits<unsigned>::max()) {
145 Success = false;
146 return;
147 }
148
149 // Access must be aligned!
150 assert(aligned(ValPos));
151 assert(aligned(ValPos + Size));
152 Code.resize_for_overwrite(N: ValPos + Size);
153
154 if constexpr (std::is_pointer_v<T>)
155 new (Code.data() + ValPos) uintptr_t(reinterpret_cast<uintptr_t>(Val));
156 else
157 new (Code.data() + ValPos) T(Val);
158}
159
160/// Emits a serializable value. These usually (potentially) contain
161/// heap-allocated memory and aren't trivially copyable.
162template <typename T>
163static void emitSerialized(llvm::SmallVectorImpl<std::byte> &Code, const T &Val,
164 bool &Success) {
165 size_t ValPos = Code.size();
166 size_t Size = align(Val.bytesToSerialize());
167
168 if (ValPos + Size > std::numeric_limits<unsigned>::max()) {
169 Success = false;
170 return;
171 }
172
173 // Access must be aligned!
174 assert(aligned(ValPos));
175 assert(aligned(ValPos + Size));
176 Code.resize_for_overwrite(N: ValPos + Size);
177
178 Val.serialize(Code.data() + ValPos);
179}
180
181template <>
182void emit(Program &P, llvm::SmallVectorImpl<std::byte> &Code,
183 const Floating &Val, bool &Success) {
184 emitSerialized(Code, Val, Success);
185}
186
187template <>
188void emit(Program &P, llvm::SmallVectorImpl<std::byte> &Code,
189 const IntegralAP<false> &Val, bool &Success) {
190 emitSerialized(Code, Val, Success);
191}
192
193template <>
194void emit(Program &P, llvm::SmallVectorImpl<std::byte> &Code,
195 const IntegralAP<true> &Val, bool &Success) {
196 emitSerialized(Code, Val, Success);
197}
198
199template <>
200void emit(Program &P, llvm::SmallVectorImpl<std::byte> &Code,
201 const FixedPoint &Val, bool &Success) {
202 emitSerialized(Code, Val, Success);
203}
204
205template <typename... Tys>
206bool ByteCodeEmitter::emitOp(Opcode Op, const Tys &...Args, SourceInfo SI) {
207 bool Success = true;
208
209 // The opcode is followed by arguments. The source info is
210 // attached to the address after the opcode.
211 emit(P, Code, Val: Op, Success);
212 if (LocOverride)
213 SrcMap.push(Offset: Code.size(), Info: *LocOverride);
214 else if (SI)
215 SrcMap.push(Offset: Code.size(), Info: SI);
216
217 (..., emit(P, Code, Args, Success));
218 return Success;
219}
220
221bool ByteCodeEmitter::jumpTrue(const LabelTy &Label, SourceInfo SI) {
222 return emitJt(getOffset(Label), SI);
223}
224
225bool ByteCodeEmitter::jumpFalse(const LabelTy &Label, SourceInfo SI) {
226 return emitJf(getOffset(Label), SI);
227}
228
229bool ByteCodeEmitter::jump(const LabelTy &Label, SourceInfo SI) {
230 return emitJmp(getOffset(Label), SI);
231}
232
233bool ByteCodeEmitter::fallthrough(const LabelTy &Label) {
234 emitLabel(Label);
235 return true;
236}
237
238bool ByteCodeEmitter::speculate(const CallExpr *E, const LabelTy &EndLabel) {
239 const Expr *Arg = E->getArg(Arg: 0);
240 PrimType T = Ctx.classify(T: Arg->getType()).value_or(PT: PT_Ptr);
241 if (!this->emitBCP(getOffset(Label: EndLabel), T, E))
242 return false;
243 if (!this->visit(E: Arg))
244 return false;
245 return true;
246}
247
248//===----------------------------------------------------------------------===//
249// Opcode emitters
250//===----------------------------------------------------------------------===//
251
252#define GET_LINK_IMPL
253#include "Opcodes.inc"
254#undef GET_LINK_IMPL
255