v8
V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.
Loading...
Searching...
No Matches
templates.h
Go to the documentation of this file.
1// Copyright 2018 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef V8_OBJECTS_TEMPLATES_H_
6#define V8_OBJECTS_TEMPLATES_H_
7
8#include <optional>
9#include <string_view>
10
13#include "src/handles/handles.h"
15#include "src/objects/struct.h"
16#include "torque-generated/bit-fields.h"
17
18// Has to be the last include (doesn't have include guards):
20
21namespace v8 {
22
23class CFunctionInfo;
24class StructBodyDescriptor;
25
26namespace internal {
27
28#include "torque-generated/src/objects/templates-tq.inc"
29
31 : public TorqueGeneratedTemplateInfo<TemplateInfo, HeapObject> {
32 public:
34
35 // While we could grow the cache until we run out of memory, we put
36 // a limit on it anyway to not crash for embedders that re-create templates
37 // instead of caching them.
38 static constexpr int kMaxTemplateInstantiationsCacheSize = 1 * MB;
39
40 // Initial serial number value.
41 static const int kUninitializedSerialNumber = 0;
42
43 // Serial numbers less than this must not be reused.
44 static const int kFirstNonUniqueSerialNumber =
46
47 DECL_BOOLEAN_ACCESSORS(is_cacheable)
48 DECL_BOOLEAN_ACCESSORS(should_promote_to_read_only)
49 DECL_PRIMITIVE_ACCESSORS(serial_number, uint32_t)
50
51 // Initializes serial number if necessary and returns it.
52 inline uint32_t EnsureHasSerialNumber(Isolate* isolate);
53
54 inline uint32_t GetHash() const;
55
56 inline bool TryGetIsolate(Isolate** isolate) const;
57 inline Isolate* GetIsolateChecked() const;
58
60
61 // Whether or not to cache every instance: when we materialize a getter or
62 // setter from an lazy AccessorPair, we rely on this cache to be able to
63 // always return the same getter or setter. However, objects will be cloned
64 // anyways, so it's not observable if we didn't cache an instance.
65 // Furthermore, a badly behaved embedder might create an unlimited number of
66 // objects, so we limit the cache for those cases.
68
69 template <typename ReturnType>
76
79 DirectHandle<TemplateInfo> info, CachingMode caching_mode);
80
81 inline static void CacheTemplateInstantiation(
83 DirectHandle<TemplateInfo> info, CachingMode caching_mode,
85
86 inline static void UncacheTemplateInstantiation(
88 DirectHandle<TemplateInfo> info, CachingMode caching_mode);
89
90 // Bit position in the template_info_base_flags, from least significant bit
91 // position.
92 DEFINE_TORQUE_GENERATED_TEMPLATE_INFO_FLAGS()
93
95};
96
98 : public TorqueGeneratedTemplateInfoWithProperties<
100 public:
102};
103
104// Contains data members that are rarely set on a FunctionTemplateInfo.
106 : public TorqueGeneratedFunctionTemplateRareData<FunctionTemplateRareData,
107 Struct> {
108 public:
110
112
114};
115
116// See the api-exposed FunctionTemplate for more information.
118 : public TorqueGeneratedFunctionTemplateInfo<FunctionTemplateInfo,
120 public:
121#define DECL_RARE_ACCESSORS(Name, CamelName, ...) \
122 DECL_GETTER(Get##CamelName, Tagged<__VA_ARGS__>) \
123 static inline void Set##CamelName( \
124 Isolate* isolate, \
125 DirectHandle<FunctionTemplateInfo> function_template_info, \
126 DirectHandle<__VA_ARGS__> Name);
127
128 // ObjectTemplateInfo or Undefined, used for the prototype property of the
129 // resulting JSFunction instance of this FunctionTemplate.
130 DECL_RARE_ACCESSORS(prototype_template, PrototypeTemplate,
132
133 // In the case the prototype_template is Undefined we use the
134 // prototype_provider_template to retrieve the instance prototype. Either
135 // contains an FunctionTemplateInfo or Undefined.
136 DECL_RARE_ACCESSORS(prototype_provider_template, PrototypeProviderTemplate,
138
139 // Used to create prototype chains. The parent_template's prototype is set as
140 // __proto__ of this FunctionTemplate's instance prototype. Is either a
141 // FunctionTemplateInfo or Undefined.
142 DECL_RARE_ACCESSORS(parent_template, ParentTemplate,
144
145 // Returns an InterceptorInfo or Undefined for named properties.
146 DECL_RARE_ACCESSORS(named_property_handler, NamedPropertyHandler,
148 // Returns an InterceptorInfo or Undefined for indexed properties/elements.
149 DECL_RARE_ACCESSORS(indexed_property_handler, IndexedPropertyHandler,
151
152 // An ObjectTemplateInfo that is used when instantiating the JSFunction
153 // associated with this FunctionTemplateInfo. Contains either an
154 // ObjectTemplateInfo or Undefined. A default instance_template is assigned
155 // upon first instantiation if it's Undefined.
156 DECL_RARE_ACCESSORS(instance_template, InstanceTemplate,
158
159 // Either a FunctionTemplateInfo or Undefined. If an instance_call_handler is
160 // provided the instances created from the associated JSFunction are marked as
161 // callable.
162 DECL_RARE_ACCESSORS(instance_call_handler, InstanceCallHandler,
164
167
168 DECL_RARE_ACCESSORS(c_function_overloads, CFunctionOverloads, FixedArray)
169#undef DECL_RARE_ACCESSORS
170
172
173 // Begin flag bits ---------------------
174
175 // This FunctionTemplateInfo is just a storage for callback function and
176 // callback data for a callable ObjectTemplate object.
177 DECL_BOOLEAN_ACCESSORS(is_object_template_call_handler)
178
179 DECL_BOOLEAN_ACCESSORS(has_side_effects)
180
181 DECL_BOOLEAN_ACCESSORS(undetectable)
182
183 // If set, object instances created by this function requires access check.
184 DECL_BOOLEAN_ACCESSORS(needs_access_check)
185
186 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
187
188 // If set, do not create a prototype property for the associated
189 // JSFunction. This bit implies that neither the prototype_template nor the
190 // prototype_provider_template are instantiated.
191 DECL_BOOLEAN_ACCESSORS(remove_prototype)
192
193 // If not set an access may be performed on calling the associated JSFunction.
194 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
195
196 // This flag is used to check that the FunctionTemplateInfo instance is not
197 // changed after it became visible to TurboFan (either set in a
198 // SharedFunctionInfo or an accessor), because TF relies on immutability to
199 // safely read concurrently.
200 DECL_BOOLEAN_ACCESSORS(published)
201
202 // This specifies the permissible range of instance type of objects that can
203 // be allowed to be used as receivers with the given template.
204 DECL_PRIMITIVE_GETTER(allowed_receiver_instance_type_range_start,
206 DECL_PRIMITIVE_GETTER(allowed_receiver_instance_type_range_end, InstanceType)
207
208 // End flag bits ---------------------
209
210 inline InstanceType GetInstanceType() const;
211 inline void SetInstanceType(int api_instance_type);
212
213 inline void SetAllowedReceiverInstanceTypeRange(int api_instance_type_start,
214 int api_instance_type_end);
215
216 static Handle<SharedFunctionInfo> GetOrCreateSharedFunctionInfo(
218 MaybeDirectHandle<Name> maybe_name);
219
220 static Handle<SharedFunctionInfo> GetOrCreateSharedFunctionInfo(
222 DirectHandle<Name> maybe_name) {
223 // We don't support streaming compilation of scripts with natives, so we
224 // don't need an off-thread implementation of this.
225 UNREACHABLE();
226 }
227
228 // Returns parent function template or a null FunctionTemplateInfo.
229 inline Tagged<FunctionTemplateInfo> GetParent(Isolate* isolate);
230 // Returns true if |object| is an instance of this function template.
231 inline bool IsTemplateFor(Tagged<JSObject> object) const;
232 bool IsTemplateFor(Tagged<Map> map) const;
233 // Returns true if |object| is an API object and is constructed by this
234 // particular function template (skips walking up the chain of inheriting
235 // functions that is done by IsTemplateFor).
236 bool IsLeafTemplateForApiObject(Tagged<Object> object) const;
237 inline bool instantiated();
238
239 static void SealAndPrepareForPromotionToReadOnly(
241
242 bool BreakAtEntry(Isolate* isolate);
243 bool HasInstanceType();
244
245 // Helper function for cached accessors.
246 static std::optional<Tagged<Name>> TryGetCachedPropertyName(
247 Isolate* isolate, Tagged<Object> getter);
248 // Fast API overloads.
249 int GetCFunctionsCount() const;
250 Address GetCFunction(Isolate* isolate, int index) const;
251 const CFunctionInfo* GetCSignature(Isolate* isolate, int index) const;
252
253 // CFunction data for a set of overloads is stored into a FixedArray, as
254 // [address_0, signature_0, ... address_n-1, signature_n-1].
255 static const int kFunctionOverloadEntrySize = 2;
256
257 // Bit position in the flag, from least significant bit position.
258 DEFINE_TORQUE_GENERATED_FUNCTION_TEMPLATE_INFO_FLAGS()
259
260 // This is a wrapper around |maybe_redirected_callback| accessor which
261 // returns/accepts C function and converts the value from and to redirected
262 // pointer.
264 inline void init_callback_redirection(i::IsolateForSandbox isolate);
265 inline void remove_callback_redirection(i::IsolateForSandbox isolate);
266
267 template <class IsolateT>
268 inline bool has_callback(IsolateT* isolate) const;
269
271
272 class BodyDescriptor;
273
274 private:
275 // When simulator is enabled the field stores the "redirected" address of the
276 // C function (the one that's callabled from simulated compiled code), in
277 // this case the original address of the C function has to be taken from the
278 // redirection.
279 // For native builds the field contains the address of the C function.
280 // This field is initialized implicitly via respective |callback|-related
281 // methods.
283 maybe_redirected_callback, Address)
284
285 // For ease of use of the BITFIELD macro.
286 inline int32_t relaxed_flag() const;
287 inline void set_relaxed_flag(int32_t flags);
288
289 // Enforce using SetInstanceType() and SetAllowedReceiverInstanceTypeRange()
290 // instead of raw accessors.
291 using TorqueGeneratedFunctionTemplateInfo<
293 DECL_PRIMITIVE_SETTER(allowed_receiver_instance_type_range_start,
295 DECL_PRIMITIVE_SETTER(allowed_receiver_instance_type_range_end, InstanceType)
296
297 static constexpr int kNoJSApiObjectType = 0;
298 static inline Tagged<FunctionTemplateRareData> EnsureFunctionTemplateRareData(
299 Isolate* isolate,
300 DirectHandle<FunctionTemplateInfo> function_template_info);
301
302 static Tagged<FunctionTemplateRareData> AllocateFunctionTemplateRareData(
303 Isolate* isolate,
304 DirectHandle<FunctionTemplateInfo> function_template_info);
305
307};
308
310 : public TorqueGeneratedObjectTemplateInfo<ObjectTemplateInfo,
312 public:
314
315 DECL_INT_ACCESSORS(embedder_field_count)
316 DECL_BOOLEAN_ACCESSORS(immutable_proto)
317 DECL_BOOLEAN_ACCESSORS(code_like)
318
319 // Starting from given object template's constructor walk up the inheritance
320 // chain till a function template that has an instance template is found.
321 inline Tagged<ObjectTemplateInfo> GetParent(Isolate* isolate);
322
324
325 private:
326 DEFINE_TORQUE_GENERATED_OBJECT_TEMPLATE_INFO_FLAGS()
327
329};
330
332 : public TorqueGeneratedDictionaryTemplateInfo<DictionaryTemplateInfo,
333 TemplateInfo> {
334 public:
335 class BodyDescriptor;
336
338 Isolate* isolate, const v8::MemorySpan<const std::string_view>& names);
339
340 static DirectHandle<JSObject> NewInstance(
343 const MemorySpan<MaybeLocal<Value>>& property_values);
344
346
348};
349
350} // namespace internal
351} // namespace v8
352
354
355#endif // V8_OBJECTS_TEMPLATES_H_
PropertyT * getter
DECL_RARE_ACCESSORS(prototype_template, PrototypeTemplate, UnionOf< Undefined, ObjectTemplateInfo >) DECL_RARE_ACCESSORS(prototype_provider_template
static void CacheTemplateInstantiation(Isolate *isolate, DirectHandle< NativeContext > native_context, DirectHandle< TemplateInfo > info, CachingMode caching_mode, DirectHandle< Object > object)
static constexpr int kMaxTemplateInstantiationsCacheSize
Definition templates.h:38
Isolate * GetIsolateChecked() const
static void UncacheTemplateInstantiation(Isolate *isolate, DirectHandle< NativeContext > native_context, DirectHandle< TemplateInfo > info, CachingMode caching_mode)
bool TryGetIsolate(Isolate **isolate) const
static const int kUninitializedSerialNumber
Definition templates.h:41
static const int kFirstNonUniqueSerialNumber
Definition templates.h:44
static const int kFastTemplateInstantiationsCacheSize
Definition templates.h:33
uint32_t EnsureHasSerialNumber(Isolate *isolate)
static MaybeHandle< ReturnType > ProbeInstantiationsCache(Isolate *isolate, DirectHandle< NativeContext > native_context, DirectHandle< TemplateInfo > info, CachingMode caching_mode)
Definition templates.h:70
TNode< Object > callback
typename detail::FlattenUnionHelper< Union<>, Ts... >::type UnionOf
Definition union.h:123
refactor address components for immediate indexing make OptimizeMaglevOnNextCall optimize to turbofan instead of maglev filter for tracing turbofan compilation trace turbo cfg trace TurboFan s graph trimmer trace TurboFan s control equivalence trace TurboFan s register allocator trace stack load store counters for optimized code in run fuzzing &&concurrent_recompilation trace_turbo trace_turbo_scheduled trace_turbo_stack_accesses verify TurboFan machine graph of code stubs enable FixedArray bounds checks print TurboFan statistics of wasm compilations maximum cumulative size of bytecode considered for inlining scale factor of bytecode size used to calculate the inlining budget * KB
Definition flags.cc:1366
too high values may cause the compiler to set high thresholds for inlining to as much as possible avoid inlined allocation of objects that cannot escape trace load stores from virtual maglev objects use TurboFan fast string builder analyze liveness of environment slots and zap dead values trace TurboFan load elimination emit data about basic block usage in builtins to this enable builtin reordering when run mksnapshot flag for emit warnings when applying builtin profile data verify register allocation in TurboFan randomly schedule instructions to stress dependency tracking enable store store elimination in TurboFan rewrite far to near simulate GC compiler thread race related to allow float parameters to be passed in simulator mode JS Wasm Run additional turbo_optimize_inlined_js_wasm_wrappers enable experimental feedback collection in generic lowering enable Turboshaft s WasmLoadElimination enable Turboshaft s low level load elimination for JS enable Turboshaft s escape analysis for string concatenation use enable Turbolev features that we want to ship in the not too far future trace individual Turboshaft reduction steps trace intermediate Turboshaft reduction steps invocation count threshold for early optimization Enables optimizations which favor memory size over execution speed Enables sampling allocation profiler with X as a sample interval min size of a semi the new space consists of two semi spaces max size of the Collect garbage after Collect garbage after keeps maps alive for< n > old space garbage collections print one detailed trace line in allocation gc speed threshold for starting incremental marking via a task in percent of available threshold for starting incremental marking immediately in percent of available Use a single schedule for determining a marking schedule between JS and C objects schedules the minor GC task with kUserVisible priority max worker number of concurrent for NumberOfWorkerThreads start background threads that allocate memory concurrent_array_buffer_sweeping use parallel threads to clear weak refs in the atomic pause trace progress of the incremental marking trace object counts and memory usage * MB
Definition flags.cc:2197
!IsContextMap !IsContextMap native_context
Definition map-inl.h:877
Tagged< To > Cast(Tagged< From > value, const v8::SourceLocation &loc=INIT_SOURCE_LOCATION_IN_DEBUG)
Definition casting.h:150
#define DECL_VERIFIER(Name)
#define DECL_BOOLEAN_ACCESSORS(name)
#define NEVER_READ_ONLY_SPACE
#define DECL_PRIMITIVE_GETTER(name, type)
#define DECL_PRIMITIVE_ACCESSORS(name, type)
#define DECL_RELAXED_UINT32_ACCESSORS(name)
#define DECL_PRIMITIVE_SETTER(name, type)
#define DECL_PRINTER(Name)
#define DECL_INT_ACCESSORS(name)
#define TQ_OBJECT_CONSTRUCTORS(Type)
#define DECL_EXTERNAL_POINTER_ACCESSORS_MAYBE_READ_ONLY_HOST(name, type)
#define UNREACHABLE()
Definition logging.h:67
#define DECL_RARE_ACCESSORS(Name, CamelName,...)
Definition templates.h:121