Debian Codegraph @

js/src/jit/GenerateMIRFiles.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 # This script generates jit/MIROpsGenerated.h (list of MIR instructions)
6 # from MIROps.yaml, as well as MIR op definitions.
7
8 import io
9
10 import buildconfig
11 import yaml
12 from mozbuild.preprocessor import Preprocessor
13
14 HEADER_TEMPLATE = """\
15 /* This Source Code Form is subject to the terms of the Mozilla Public
16 * License, v. 2.0. If a copy of the MPL was not distributed with this
17 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
18
19 #ifndef %(includeguard)s
20 #define %(includeguard)s
21
22 /* This file is generated by jit/GenerateMIRFiles.py. Do not edit! */
23
24 %(contents)s
25
26 #endif // %(includeguard)s
27 """
28
29
30 def generate_header(c_out, includeguard, contents):
31 c_out.write(
32 HEADER_TEMPLATE
33 % {
34 "includeguard": includeguard,
35 "contents": contents,
36 }
37 )
38
39
40 def load_yaml(yaml_path):
41 # First invoke preprocessor.py so that we can use #ifdef JS_SIMULATOR in
42 # the YAML file.
43 pp = Preprocessor()
44 pp.context.update(buildconfig.defines["ALLDEFINES"])
45 pp.out = io.StringIO()
46 pp.do_filter("substitution")
47 pp.do_include(yaml_path)
48 contents = pp.out.getvalue()
49 return yaml.safe_load(contents)
50
51
52 type_policies = {
53 "Object": "ObjectPolicy",
54 "Value": "BoxPolicy",
55 "Int32": "UnboxedInt32Policy",
56 "BigInt": "BigIntPolicy",
57 "IntPtr": "IntPtrPolicy",
58 "Boolean": "BooleanPolicy",
59 "Double": "DoublePolicy",
60 "String": "StringPolicy",
61 "Symbol": "SymbolPolicy",
62 }
63
64
65 def decide_type_policy(types, no_type_policy):
66 if no_type_policy:
67 return "public NoTypePolicy::Data"
68
69 if len(types) == 1:
70 return f"public {type_policies[types[0]]}<0>::Data"
71
72 type_num = 0
73 mixed_type_policies = []
74 for mir_type in types:
75 policy = type_policies[mir_type]
76 mixed_type_policies.append(f"{policy}<{type_num}>")
77 type_num += 1
78
79 return "public MixPolicy<{}>::Data".format(", ".join(mixed_type_policies))
80
81
82 mir_base_class = [
83 "MNullaryInstruction",
84 "MUnaryInstruction",
85 "MBinaryInstruction",
86 "MTernaryInstruction",
87 "MQuaternaryInstruction",
88 ]
89
90
91 gc_pointer_types = [
92 "JSObject*",
93 "NativeObject*",
94 "JSFunction*",
95 "BaseScript*",
96 "PropertyName*",
97 "Shape*",
98 "GetterSetter*",
99 "JSAtom*",
100 "ClassBodyScope*",
101 "VarScope*",
102 "NamedLambdaObject*",
103 "RegExpObject*",
104 "JSScript*",
105 "LexicalScope*",
106 ]
107
108
109 def gen_mir_class(
110 name,
111 operands,
112 arguments,
113 no_type_policy,
114 result,
115 guard,
116 movable,
117 folds_to,
118 congruent_to,
119 alias_set,
120 might_alias,
121 possibly_calls,
122 compute_range,
123 can_recover,
124 clone,
125 can_consume_float32,
126 ):
127 """Generates class definition for a single MIR opcode."""
128
129 # Generate a MIR opcode class definition.
130 # For example:
131 # class MGuardIndexIsValidUpdateOrAdd
132 # : public MBinaryInstruction,
133 # public MixPolicy<ObjectPolicy<0>, UnboxedInt32Policy<1>>::Data {
134 # explicit MGuardIndexIsValidUpdateOrAdd(MDefinition* object,
135 # MDefinition* index)
136 # : MBinaryInstruction(classOpcode, object, index) {
137 # setGuard();
138 # setMovable();
139 # setResultType(MIRType::Int32);
140 # }
141 # public:
142 # INSTRUCTION_HEADER(GetFrameArgument)
143 # TRIVIAL_NEW_WRAPPERS
144 # NAMED_OPERANDS((0, object), (1, index))
145 # AliasSet getAliasSet() const override { return AliasSet::None(); }
146 # bool congruentTo(const MDefinition* ins) const override {
147 # return congruentIfOperandsEqual(ins); }
148 # };
149 #
150
151 type_policy = ""
152 # MIR op constructor operands.
153 mir_operands = []
154 # MIR op base class constructor operands.
155 mir_base_class_operands = []
156 # Types of each constructor operand.
157 mir_types = []
158 # Items for NAMED_OPERANDS.
159 named_operands = []
160 if operands:
161 current_oper_num = 0
162 for oper_name in operands:
163 oper = "MDefinition* " + oper_name
164 mir_operands.append(oper)
165 mir_base_class_operands.append(", " + oper_name)
166 # Collect all the MIR argument types to use for determining the
167 # ops type policy.
168 mir_types.append(operands[oper_name])
169 # Collecting named operands for defining accessors.
170 named_operands.append(f"({current_oper_num}, {oper_name})")
171 current_oper_num += 1
172 type_policy = decide_type_policy(mir_types, no_type_policy)
173
174 class_name = "M" + name
175
176 assert len(mir_operands) < 5
177 base_class = mir_base_class[len(mir_operands)]
178 assert base_class
179 if base_class != "MNullaryInstruction":
180 assert type_policy
181 type_policy = ", " + type_policy
182 code = f"class {class_name} : public {base_class}{type_policy} {{\\\n"
183
184 # Arguments to class constructor that require accessors.
185 mir_args = []
186 if arguments:
187 for arg_name in arguments:
188 arg_type_sig = arguments[arg_name]
189 mir_args.append(arg_type_sig + " " + arg_name)
190 if arg_type_sig in gc_pointer_types:
191 code += " CompilerGCPointer<" + arg_type_sig + ">"
192 else:
193 code += " " + arg_type_sig
194 code += " " + arg_name + "_;\\\n"
195
196 code += " explicit {}({}) : {}(classOpcode{})".format(
197 class_name,
198 ", ".join(mir_operands + mir_args),
199 base_class,
200 "".join(mir_base_class_operands),
201 )
202 if arguments:
203 for arg_name in arguments:
204 code += ", " + arg_name + "_(" + arg_name + ")"
205 code += " {\\\n"
206 if guard:
207 code += " setGuard();\\\n"
208 if movable:
209 code += " setMovable();\\\n"
210 if result:
211 code += f" setResultType(MIRType::{result});\\\n"
212 code += " }\\\n public:\\\n"
213 if arguments:
214 for arg_name in arguments:
215 code += " " + arguments[arg_name] + " " + arg_name + "() const { "
216 code += "return " + arg_name + "_; }\\\n"
217 code += f" INSTRUCTION_HEADER({name})\\\n"
218 code += " TRIVIAL_NEW_WRAPPERS\\\n"
219 if named_operands:
220 code += " NAMED_OPERANDS({})\\\n".format(", ".join(named_operands))
221 if alias_set:
222 if alias_set == "custom":
223 code += " AliasSet getAliasSet() const override;\\\n"
224 else:
225 assert alias_set == "none"
226 code += (
227 " AliasSet getAliasSet() const override { "
228 "return AliasSet::None(); }\\\n"
229 )
230 if might_alias:
231 code += " AliasType mightAlias(const MDefinition* store) const override;\\\n"
232 if folds_to:
233 code += " MDefinition* foldsTo(TempAllocator& alloc) override;\\\n"
234 if congruent_to:
235 if congruent_to == "custom":
236 code += " bool congruentTo(const MDefinition* ins) const override;\\\n"
237 else:
238 assert congruent_to == "if_operands_equal"
239 code += (
240 " bool congruentTo(const MDefinition* ins) const override { "
241 "return congruentIfOperandsEqual(ins); }\\\n"
242 )
243 if possibly_calls:
244 if possibly_calls == "custom":
245 code += " bool possiblyCalls() const override;\\\n"
246 else:
247 code += " bool possiblyCalls() const override { return true; }\\\n"
248 if compute_range:
249 code += " void computeRange(TempAllocator& alloc) override;\\\n"
250 if can_recover:
251 code += " [[nodiscard]] bool writeRecoverData(\\\n"
252 code += " CompactBufferWriter& writer) const override;\\\n"
253 if can_recover == "custom":
254 code += " bool canRecoverOnBailout() const override;\\\n"
255 else:
256 code += " bool canRecoverOnBailout() const override { return true; }\\\n"
257 if clone:
258 code += " ALLOW_CLONE(" + class_name + ")\\\n"
259 if can_consume_float32:
260 code += (
261 " bool canConsumeFloat32(MUse* use) const override { return true; }\\\n"
262 )
263 code += "};\\\n"
264 return code
265
266
267 def gen_non_gc_pointer_type_assertions(seen_types):
268 """Generates a list of static assertions used to ensure that all argument
269 types seen are not derived from gc::Cell, ensuring that gc pointer arguments
270 are added to the gc_pointer_types list.
271 """
272 assertions = []
273
274 for seen_type in sorted(seen_types):
275 assertions.append(
276 "static_assert(!std::is_base_of_v<gc::Cell, " + seen_type.strip("*") + ">, "
277 '"Ensure that '
278 + seen_type.strip("*")
279 + ' is added to the gc_pointer_types list in GenerateMIRFiles.py."'
280 ");"
281 )
282
283 return assertions
284
285
286 def generate_mir_header(c_out, yaml_path):
287 """Generate MIROpsGenerated.h from MIROps.yaml. The generated file
288 has a list of MIR ops and boilerplate for MIR op definitions.
289 """
290
291 data = load_yaml(yaml_path)
292
293 # MIR_OPCODE_LIST items. Stores the name of each MIR op.
294 ops_items = []
295
296 # Generated MIR op class definitions.
297 mir_op_classes = []
298
299 # Unique and non gc pointer types seen for arguments to the MIR constructor.
300 seen_non_gc_pointer_argument_types = set()
301
302 for op in data:
303 name = op["name"]
304
305 ops_items.append(f"_({name})")
306
307 gen_boilerplate = op.get("gen_boilerplate", True)
308 assert isinstance(gen_boilerplate, bool)
309
310 if gen_boilerplate:
311 operands = op.get("operands", None)
312 assert operands is None or isinstance(operands, dict)
313
314 arguments = op.get("arguments", None)
315 assert arguments is None or isinstance(arguments, dict)
316
317 no_type_policy = op.get("type_policy", None)
318 assert no_type_policy in (None, "none")
319
320 result = op.get("result_type", None)
321 assert result is None or isinstance(result, str)
322
323 guard = op.get("guard", None)
324 assert guard in (None, True, False)
325
326 movable = op.get("movable", None)
327 assert movable in (None, True, False)
328
329 folds_to = op.get("folds_to", None)
330 assert folds_to in (None, "custom")
331
332 congruent_to = op.get("congruent_to", None)
333 assert congruent_to in (None, "if_operands_equal", "custom")
334
335 alias_set = op.get("alias_set", None)
336 assert alias_set in (None, "none", "custom")
337
338 might_alias = op.get("might_alias", None)
339 assert might_alias in (None, "custom")
340
341 possibly_calls = op.get("possibly_calls", None)
342 assert possibly_calls in (None, True, "custom")
343
344 compute_range = op.get("compute_range", None)
345 assert compute_range in (None, "custom")
346
347 can_recover = op.get("can_recover", None)
348 assert can_recover in (None, True, False, "custom")
349
350 clone = op.get("clone", None)
351 assert clone in (None, True, False)
352
353 can_consume_float32 = op.get("can_consume_float32", None)
354 assert can_consume_float32 in (None, True, False)
355
356 code = gen_mir_class(
357 name,
358 operands,
359 arguments,
360 no_type_policy,
361 result,
362 guard,
363 movable,
364 folds_to,
365 congruent_to,
366 alias_set,
367 might_alias,
368 possibly_calls,
369 compute_range,
370 can_recover,
371 clone,
372 can_consume_float32,
373 )
374 mir_op_classes.append(code)
375
376 if arguments:
377 for argument in arguments:
378 arg_type = arguments[argument]
379 if arg_type not in gc_pointer_types:
380 seen_non_gc_pointer_argument_types.add(arg_type)
381
382 contents = "#define MIR_OPCODE_LIST(_)\\\n"
383 contents += "\\\n".join(ops_items)
384 contents += "\n\n"
385
386 contents += "#define MIR_OPCODE_CLASS_GENERATED \\\n"
387 contents += "\\\n".join(mir_op_classes)
388 contents += "\n\n"
389
390 contents += "#define NON_GC_POINTER_TYPE_ASSERTIONS_GENERATED \\\n"
391 contents += "\\\n".join(
392 gen_non_gc_pointer_type_assertions(seen_non_gc_pointer_argument_types)
393 )
394 contents += "\n\n"
395
396 generate_header(c_out, "jit_MIROpsGenerated_h", contents)