To protect your data, the CISO officer has suggested users to enable GitLab 2FA as soon as possible.

genmu.py 30.9 KB
Newer Older
1
from rpython.flowspace.model import Constant
2
from rpython.config.translationoption import get_translation_config
John Zhang's avatar
John Zhang committed
3
4
from rpython.tool.ansi_print import AnsiLogger
from rpython.tool.ansi_mandelbrot import Driver
5
from rpython.translator.mu import mutype
6
from rpython.translator.platform import platform, CompilationError
7
from rpython.translator.platform.darwin import Darwin
8
from rpython.translator.platform import log as log_platform
John Zhang's avatar
John Zhang committed
9
import py, os, sys
John Zhang's avatar
John Zhang committed
10
11
12
13
14
15

__mdb = Driver()


def get_rmu():
    from rpython.config.translationoption import get_translation_config
16
    from rpython.rlib import rmu
John Zhang's avatar
John Zhang committed
17
    import importlib
John Zhang's avatar
John Zhang committed
18
    config = get_translation_config()
19
    mod_name = config.translation.mu.impl + ('_c' if config.translation.mu.codegen == 'c' else '')
John Zhang's avatar
John Zhang committed
20
21
    return importlib.import_module('rpython.rlib.rmu.%(mod_name)s' % locals())
    # return getattr(rmu, mod_name)
John Zhang's avatar
John Zhang committed
22
23
24
25


class MuBundleGen:
    def __init__(self, db):
26
27
28
29
        # type: (rpython.translator.mu.database.MuDatabase) -> None
        self.db = db
        self.idmap = {}
        self.rmu = get_rmu()
30
31
32
33
        
        if hasattr(self.rmu, 'get_global_apilogger'):
            self.rmu.get_global_apilogger().clear()     # clear API logger over continuous test runs

34
        self.mu_config = get_translation_config().translation.mu
35
        self.mu = self.rmu.MuVM(self.get_config_str())
36
37
38
39
        self.ctx = self.mu.new_context()
        self.bdr = self.ctx.new_ir_builder()
        self.objhdlmap = {}     # used in heap initialisation; NOTE: referent -> handle (not reference)
        self.log = AnsiLogger('MuBundleGen')
40
41
42
        self.reloc_obj_map = {}
        self.obj_hdl_map = {}
        self._hyb2stt_map = {}
43

44
    def get_config_str(self):
45
        from ctypes.util import find_library
46
47
        config_items = []
        if self.mu_config.impl == 'holstein':
48
            sep = '\n' if self.mu_config.codegen == 'api' else '\\n'
49
50
            libs = []
            for lib in self.db.merged_eci.libraries:
51
52
                if lib == 'rt':
                    if isinstance(platform, Darwin):
53
                        lib = 'System'  # HACK: libSystem.dylib should be the equivalent of librt.so
54
55
56
57
58

                if not os.path.isabs(lib):
                    lib = find_library(lib)
                    assert lib
                libs.append(lib)
59
            config_items.append('uPtrHack=True')    # turn on uptr hack (loading refs from uptr in Mu)
60
            config_items.append('extraLibs=' + ':'.join(libs))
61
            self._holstein_config_extralibs = ':'.join(libs)
62
63
64
65
            if 'vmLog' not in self.mu_config.vmargs:
                config_items.append('vmLog=' + os.environ.get('MU_LOG_LEVEL', 'ERROR'))
            if 'dumpBundle' not in self.mu_config.vmargs:
                config_items.append('dumpBundle=%s' % False)
John Zhang's avatar
John Zhang committed
66
            config_items.append('automagicReloc=False')  # use manual relocation
67
68
69
70
71
72
        else:
            sep = ' '
            if 'log-level' not in self.mu_config.vmargs:
                config_items.append('--log-level=' + os.environ.get('MU_LOG_LEVEL', 'none'))
            if 'emit-dir' not in self.mu_config.vmargs:
                config_items.append('--aot-emit-dir=' + 'emit')
73
74
75
76
77
78
79
80
81
82
83
84
85
            for lib in self.db.merged_eci.libraries:
                if lib == 'rt':
                    if isinstance(platform, Darwin):
                        lib = 'System'  # HACK: libSystem.dylib should be the equivalent of librt.so

                if os.path.isabs(lib):
                    config_items.append('--bootimage-external-libpath=%s' % os.path.dirname(lib))
                    lib = os.path.basename(lib)
                if lib.startswith(platform.so_prefixes[0]) and lib.endswith(platform.so_ext):
                    # taking only the library name to pass to linker
                    lib = lib[3:lib.index('.')]     # cut at the first '.'
                config_items.append('--bootimage-external-lib=%s' % lib)

86
87
        return sep.join([self.mu_config.vmargs] + config_items)

88
    def build_and_load_bundle(self):
89
90
        self.check_reloc_object()

John Zhang's avatar
John Zhang committed
91
        self.idmap = self.db.mu_name_map
92
93
94
95
96
97
98

        self.gen_types()
        self.gen_consts()
        self.gen_gcells()
        self.gen_graphs()
        self.bdr.load()

99
100
        self.init_heap()

101
102
        return self.db, self, self.db.tlc.entry_point_graph.name

John Zhang's avatar
John Zhang committed
103
    def gen_symbols(self):
104
        self.log.gen_symbols('generating symbols...')
105
106
        # self.idmap = self.db.mu_name_map.copy()
        self.idmap = self.db.mu_name_map
107
108
        count = 0
        total = len(self.idmap)
John Zhang's avatar
John Zhang committed
109
110
111
112
113
        for entity in self.idmap:
            _name = self.idmap[entity]
            _id = self.bdr.gen_sym(_name)
            self.idmap[entity] = _id  # drop the name

114
            count += 1
115
            if count % 500 == 0 or count == total:
116
117
118
                sys.stderr.write("\033[0F\033[K")
                self.log.gen_symbols("generating symbols... (%d/%d %d%%)" % (count, total, count * 100 / total))

119
120
121
122
        # add predefined types in idmap.
        for (MuT, (name_str, _id)) in mutype.MU_PREDEF_TYPES.items():
            self.idmap[MuT] = _id

123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
    def check_reloc_object(self):
        """
        Check heap objects that need uptr relocation.
        Create new global cells for these objects.

        When an object is hybrid (C array), it is quite a tricky case.
        Without proper support of relocation,
        a compromise needs to be made in order to fit it in global cell.
        So the current strategy is to convert the hybrid into an equivalent struct and make note of that,
        and add the struct type to the database.
        """
        for obj in self.db.objtracer.fixed_objs:
            MuT = mutype.mutypeOf(obj)
            if isinstance(MuT, mutype.MuHybrid):
                stt = hybrid2struct(obj)
                self._hyb2stt_map[obj] = stt
                MuT = mutype.mutypeOf(stt)
                self.db._add_type(MuT)
                obj = stt

            GCL = mutype.MuGlobalCell(MuT)
            gcl = mutype.new(GCL)
            gcl._store(obj)
            gcl_c = Constant(gcl, GCL)
147
            self.db._add_type(MuT)
148
149
150
151
            self.db.gcells.add(gcl_c)

            self.reloc_obj_map[obj] = gcl_c

152
153
154
155
156
157
158
        for T in filter(lambda T: T not in self.db.mu_name_map, self.db.types):
            self.db.mu_name_map[T] = self.db.nman.assign(T)
        for gcl_c in filter(lambda gcl_c: gcl_c not in self.db.mu_name_map, self.db.gcells):
            self.db.mu_name_map[gcl_c] = self.db.nman.assign(gcl_c)

        self.log.check_reloc_object('%d glocal cells created for pointer relocation objects...' %
                                    len(self.db.objtracer.fixed_objs))
John Zhang's avatar
John Zhang committed
159

160
161
162
163
164
165
166
167
168
169
170
171
    def gen_boot_image(self, targetname):
        self.build_and_load_bundle()

        if self.mu_config.testjit:
            libname = targetname + '.' + platform.so_ext
            self.mu.compile_to_sharedlib(libname, [])
        else:
            hmain = self.ctx.handle_from_func(self._id_of(self.db.tlc.entry_point_graph))
            topdefs = []
            topdefs.extend(self._ids_of(self.db.types))
            topdefs.extend(self._ids_of(self.db.consts))
            topdefs.extend(self._ids_of(self.db.extern_fncs))
John Zhang's avatar
John Zhang committed
172
            topdefs.extend(self._ids_of(self.db.gcells))
173
            topdefs.extend(self._ids_of(self.db.graphs))
John Zhang's avatar
John Zhang committed
174
175
176
177
178
179
180
181
182
183
184
185
186
187

            reloc_sym_strs = []
            reloc_hgcls = []
            reloc_hflds = []
            reloc_hflds_syms = []
            for obj, record in self.reloc_obj_map.items():
                sym_str, hgcl = record[:2]
                hflds = record[2:]
                reloc_sym_strs.append(sym_str)
                reloc_hgcls.append(hgcl)
                for hfld in hflds:
                    reloc_hflds.append(hfld)
                    reloc_hflds_syms.append(sym_str)

188
189
190
            self.ctx.make_boot_image(topdefs, hmain,
                                     self.rmu.null(self.rmu.MuStackRefValue),
                                     self.rmu.null(self.rmu.MuRefValue),
John Zhang's avatar
John Zhang committed
191
192
                                     reloc_hgcls, reloc_sym_strs, reloc_hflds, reloc_hflds_syms,
                                     targetname)
193
194
195
196

        if hasattr(self.mu, 'close'):
            self.mu.close()

197
        if self.mu_config.codegen == 'c':
198
            self.log.gen_boot_image("writing C files...")
199
            mf, exe = self.rmu.get_global_apilogger().genc(py.path.local(targetname).basename)
200
            platform.execute_makefile(mf)
201
            exec 'from rpython.rlib.rmu.%s import eci as rmu_eci' % self.mu_config.impl
202
            log_platform.execute(exe)
203
            r = platform.execute(exe, compilation_info=locals()['rmu_eci'])
204
            if r.returncode != 0:
205
                raise CompilationError(r.out, r.err)
206
207
208

        if self.mu_config.impl == 'holstein':
            if self.db.libsupport_path:
209
210
                from rpython.rlib.rmu.holstein import mu_dir
                sys.path.append(str(py.path.local(mu_dir).join('..', 'tools')))
211
                from mar import mu_meta_set
212
                mu_meta_set(str(targetname), extra_libraries=self._holstein_config_extralibs)
213

214
215
216
217
            # in conformity to the assumption of pypy interpreter that the final product is executable
            import stat
            py.path.local(targetname).chmod(stat.S_IRWXU)
            
218
219
        return self.db, self, self.db.tlc.entry_point_graph.name

220
    def gen_types(self):
John Zhang's avatar
John Zhang committed
221
        self.log.gen_types("declaring %d types..." % len(self.db.types))
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
        for T in self.db.types:
            _id = self._id_of(T)
            if isinstance(T, mutype.MuIntType):
                self.bdr.new_type_int(_id, T.BITS)
            elif T == mutype.MU_FLOAT:
                self.bdr.new_type_float(_id)
            elif T == mutype.MU_DOUBLE:
                self.bdr.new_type_double(_id)
            elif T == mutype.MU_VOID:
                self.bdr.new_type_void(_id)
            elif isinstance(T, mutype.MuStruct):
                self.bdr.new_type_struct(_id, self._ids_of(T._field_types()))
            elif isinstance(T, mutype.MuHybrid):
                self.bdr.new_type_hybrid(_id, self._ids_of(T._fixed_field_types()),
                                         self._id_of(T._var_field_type()))
            elif isinstance(T, mutype.MuArray):
                self.bdr.new_type_array(_id, self._id_of(T.OF), T.length)
            elif isinstance(T, mutype.MuFuncSig):
                self.bdr.new_funcsig(_id, self._ids_of(T.ARGS), self._ids_of(T.RESULTS))
            elif isinstance(T, mutype.MuFuncRef):
                self.bdr.new_type_funcref(_id, self._id_of(T.Sig))
            elif isinstance(T, mutype.MuUFuncPtr):
                self.bdr.new_type_ufuncptr(_id, self._id_of(T.Sig))
            elif isinstance(T, mutype.MuRef):
                self.bdr.new_type_ref(_id, self._id_of(T.TO))
            elif isinstance(T, mutype.MuIRef):
                self.bdr.new_type_iref(_id, self._id_of(T.TO))
            elif isinstance(T, mutype.MuUPtr):
                self.bdr.new_type_uptr(_id, self._id_of(T.TO))
John Zhang's avatar
John Zhang committed
251
252
            elif isinstance(T, mutype.MuWeakRef):
                self.bdr.new_type_weakref(_id, self._id_of(T.TO))
John Zhang's avatar
John Zhang committed
253
254
255
            elif isinstance(T, mutype.MuOpaqueRef):
                if T is mutype.MUTA_IRBUILDER_REF:
                    self.bdr.new_type_irbuilderref(_id)
256
257

    def gen_consts(self):
John Zhang's avatar
John Zhang committed
258
        self.log.gen_types("declaring %d constants..." % (len(self.db.consts) + len(self.db.extern_fncs)))
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
        for c in self.db.consts:
            T = c.concretetype
            v = c.value
            _id = self._id_of(c)
            _id_T = self._id_of(T)
            if isinstance(T, mutype.MuIntType):
                if not isinstance(T, mutype.MuBigIntType):
                    self.bdr.new_const_int(_id, _id_T, v)
                else:
                    self.bdr.new_const_int_ex(_id, _id_T, v.get_uint64s())
            elif T == mutype.MU_FLOAT:
                self.bdr.new_const_float(_id, _id_T, float(v))
            elif T == mutype.MU_DOUBLE:
                self.bdr.new_const_double(_id, _id_T, float(v))
            elif isinstance(T, mutype.MuReferenceType):
                assert v._is_null()
275
276
277
                if isinstance(T, mutype.MuUPtr):
                    self.bdr.new_const_int(_id, _id_T, 0)   # NULL for uptr is 0
                else:
278
279
                    if isinstance(T, mutype.MuWeakRef):
                        _id_T = self._id_of(mutype.MuRef(mutype.MU_VOID))
280
                    self.bdr.new_const_null(_id, _id_T)
281
282
283
284
285

        for c in self.db.extern_fncs:
            self.bdr.new_const_extern(self._id_of(c), self._id_of(c.concretetype), c.value._name)

    def gen_gcells(self):
John Zhang's avatar
John Zhang committed
286
        self.log.gen_gcells("declaring %d global cells..." % (len(self.db.gcells)))
287
288
289
290
291
        for gcl in self.db.gcells:
            self.bdr.new_global_cell(self._id_of(gcl), self._id_of(gcl.concretetype.TO))

    def gen_graphs(self):
        for frc in self.db.funcref_consts:
John Zhang's avatar
John Zhang committed
292
            self.idmap[frc] = self._id_of(frc.value.graph)
293

John Zhang's avatar
John Zhang committed
294
295
296
        self.log.gen_graphs("")
        count = 0
        total = len(self.db.graphs)
297
        for g in self.db.graphs:
John Zhang's avatar
John Zhang committed
298
299
            count += 1
            sys.stderr.write("\033[0F\033[K")
300
            self.log.gen_graphs("building function (%d/%d %d%%) %s" % (count, total, count * 100 / total, g))
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
            self.bdr.new_func(self._id_of(g), self._id_of(g.sig))
            self.bdr.new_func_ver(self.bdr.gen_sym('@' + g.name + '_v1'),
                                  self._id_of(g), self._ids_of(g.iterblocks()))

            for blk in g.iterblocks():
                op_ids = []
                for op in filter(lambda op: op.opname.startswith('mu_'), blk.operations):
                    _id = self.bdr.gen_sym()
                    op_ids.append(_id)
                    mtd = getattr(self, '_genop_' + op.opname)
                    mtd(op, _id)
                self.bdr.new_bb(self._id_of(blk),
                                self._ids_of(blk.inputargs),
                                self._ids_of(map(lambda a: a.concretetype, blk.inputargs)),
                                self._id_of(blk.mu_excparam) if blk.mu_excparam else self.rmu.MU_NO_ID,
                                op_ids)

    def _genop_mu_binop(self, op, op_id):
        metainfo = op.args[-1].value
John Zhang's avatar
John Zhang committed
320
        if 'status' in metainfo and not self.mu_config.no_ovf:
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
            self.bdr.new_binop_with_status(op_id, self._id_of(op.result),
                                           self._ids_of(metainfo['status'][1]),
                                           getattr(self.rmu.MuBinOptr, op.args[0].value),
                                           getattr(self.rmu.MuBinOpStatus, metainfo['status'][0]),
                                           self._id_of(op.args[1].concretetype),
                                           self._id_of(op.args[1]), self._id_of(op.args[2]))
        else:
            self.bdr.new_binop(op_id, self._id_of(op.result),
                               getattr(self.rmu.MuBinOptr, op.args[0].value),
                               self._id_of(op.args[1].concretetype),
                               self._id_of(op.args[1]), self._id_of(op.args[2]))

    def _genop_mu_cmpop(self, op, op_id):
        self.bdr.new_cmp(op_id, self._id_of(op.result),
                         getattr(self.rmu.MuCmpOptr, op.args[0].value),
                         self._id_of(op.args[1].concretetype),
                         self._id_of(op.args[1]), self._id_of(op.args[2]))

    def _genop_mu_convop(self, op, op_id):
        self.bdr.new_conv(op_id, self._id_of(op.result),
                          getattr(self.rmu.MuConvOptr, op.args[0].value),
                          self._id_of(op.args[2].concretetype),
                          self._id_of(op.args[1].value),
                          self._id_of(op.args[2]))

    def _genop_mu_select(self, op, op_id):
        self.bdr.new_select(op_id, self._id_of(op.result),
                            self._id_of(op.args[0].concretetype),
                            self._id_of(op.args[1].concretetype),
                            self._id_of(op.args[0]),
                            self._id_of(op.args[1]), self._id_of(op.args[2]))

    def _genop_mu_branch(self, op, op_id):
        dst = self.bdr.gen_sym()
        self.bdr.new_dest_clause(dst, self._id_of(op.args[0].value.target),
                                 self._ids_of(op.args[0].value.args))
        self.bdr.new_branch(op_id, dst)

    def _genop_mu_branch2(self, op, op_id):
        dst_t = self.bdr.gen_sym()
        dst_f = self.bdr.gen_sym()
        lnk_t = op.args[1].value
        lnk_f = op.args[2].value
        self.bdr.new_dest_clause(dst_t, self._id_of(lnk_t.target), self._ids_of(lnk_t.args))
        self.bdr.new_dest_clause(dst_f, self._id_of(lnk_f.target), self._ids_of(lnk_f.args))
        self.bdr.new_branch2(op_id, self._id_of(op.args[0]), dst_t, dst_f)
John Zhang's avatar
John Zhang committed
367

368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
    def _genop_mu_switch(self, op, op_id):
        dst_dfl = self.bdr.gen_sym()
        lnk_dfl = op.args[1].value
        self.bdr.new_dest_clause(dst_dfl, self._id_of(lnk_dfl.target), self._ids_of(lnk_dfl.args))
        case_lnks = op.args[2:]
        dst_ids = []
        for lnk_c in case_lnks:
            lnk = lnk_c.value
            _id = self.bdr.gen_sym()
            dst_ids.append(_id)
            self.bdr.new_dest_clause(_id, self._id_of(lnk.target), self._ids_of(lnk.args))

        self.bdr.new_switch(op_id, self._id_of(op.args[0].concretetype), self._id_of(op.args[0]),
                            dst_dfl,
                            self._ids_of(map(lambda l_c: l_c.value.exitcase, case_lnks)),
                            dst_ids)

    def _genop_mu_call(self, op, op_id):
        metainfo = op.args[-1].value
        if 'excclause' in metainfo:
            lnk_n, lnk_e = metainfo['excclause']
            dst_n = self.bdr.gen_sym()
            dst_e = self.bdr.gen_sym()
            exc = self.bdr.gen_sym()
            self.bdr.new_dest_clause(dst_n, self._id_of(lnk_n.target), self._ids_of(lnk_n.args))
            self.bdr.new_dest_clause(dst_e, self._id_of(lnk_e.target), self._ids_of(lnk_e.args))
            self.bdr.new_exc_clause(exc, dst_n, dst_e)
        else:
            exc = self.rmu.MU_NO_ID
397
398
        results = [self._id_of(op.result)] if op.args[0].concretetype.Sig.RESULTS else []
        self.bdr.new_call(op_id, results,
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
                          self._id_of(op.args[0].concretetype.Sig), self._id_of(op.args[0]),
                          self._ids_of(op.args[1:-1]), exc)

    def _genop_mu_ret(self, op, op_id):
        self.bdr.new_ret(op_id, self._ids_of(op.args))

    def _genop_mu_throw(self, op, op_id):
        self.bdr.new_throw(op_id, self._id_of(op.args[0]))

    def _genop_mu_new(self, op, op_id):
        self.bdr.new_new(op_id, self._id_of(op.result), self._id_of(op.args[0].value))

    def _genop_mu_newhybrid(self, op, op_id):
        self.bdr.new_newhybrid(op_id, self._id_of(op.result),
                               self._id_of(op.args[0].value),
                               self._id_of(op.args[1].concretetype),
                               self._id_of(op.args[1]))

    def _genop_mu_getiref(self, op, op_id):
        self.bdr.new_getiref(op_id, self._id_of(op.result),
                             self._id_of(op.args[0].concretetype.TO), self._id_of(op.args[0]))

    def _genop_mu_getfieldiref(self, op, op_id):
        self.bdr.new_getfieldiref(op_id, self._id_of(op.result),
                                  isinstance(op.args[0].concretetype, mutype.MuUPtr),
                                  self._id_of(op.args[0].concretetype.TO),
                                  op.args[0].concretetype.TO._index_of(op.args[1].value),
                                  self._id_of(op.args[0]))

    def _genop_mu_getelemiref(self, op, op_id):
        self.bdr.new_getelemiref(op_id, self._id_of(op.result),
                                 isinstance(op.args[0].concretetype, mutype.MuUPtr),
                                 self._id_of(op.args[0].concretetype.TO),
                                 self._id_of(op.args[1].concretetype),
                                 self._id_of(op.args[0]), self._id_of(op.args[1]))

    def _genop_mu_shiftiref(self, op, op_id):
        self.bdr.new_shiftiref(op_id, self._id_of(op.result),
                               isinstance(op.args[0].concretetype, mutype.MuUPtr),
                               self._id_of(op.args[0].concretetype.TO),
                               self._id_of(op.args[1].concretetype),
                               self._id_of(op.args[0]), self._id_of(op.args[1]))

    def _genop_mu_getvarpartiref(self, op, op_id):
        self.bdr.new_getvarpartiref(op_id, self._id_of(op.result),
                                    isinstance(op.args[0].concretetype, mutype.MuUPtr),
                                    self._id_of(op.args[0].concretetype.TO),
                                    self._id_of(op.args[0]))

    def _genop_mu_load(self, op, op_id):
        self.bdr.new_load(op_id, self._id_of(op.result),
                          isinstance(op.args[0].concretetype, mutype.MuUPtr),
                          getattr(self.rmu.MuMemOrd, op.args[-1].value['memord']),
                          self._id_of(op.args[0].concretetype.TO),
                          self._id_of(op.args[0]))

    def _genop_mu_store(self, op, op_id):
        self.bdr.new_store(op_id,
                           isinstance(op.args[0].concretetype, mutype.MuUPtr),
                           getattr(self.rmu.MuMemOrd, op.args[-1].value['memord']),
                           self._id_of(op.args[0].concretetype.TO),
                           self._id_of(op.args[0]),
                           self._id_of(op.args[1]))

    def _genop_mu_ccall(self, op, op_id):
464
465
        results = [self._id_of(op.result)] if op.args[0].concretetype.Sig.RESULTS else []
        self.bdr.new_ccall(op_id, results,
466
467
468
469
470
471
472
473
474
475
476
477
478
479
                           getattr(self.rmu.MuCallConv, op.args[-1].value['callconv']),
                           self._id_of(op.args[0].concretetype),
                           self._id_of(op.args[0].concretetype.Sig),
                           self._id_of(op.args[0]),
                           self._ids_of(op.args[1:-1]))

    def _genop_mu_comminst(self, op, op_id):
        metainfo = op.args[-1].value
        if 'flags' in metainfo:
            raise NotImplementedError
        else:
            flags = []
        types = self._ids_of(metainfo['types']) if 'types' in metainfo else []
        sigs = self._ids_of(metainfo['sigs']) if 'sigs' in metainfo else []
John Zhang's avatar
John Zhang committed
480
481
        results = [self._id_of(op.result)] if op.result.concretetype != mutype.MU_VOID else []
        self.bdr.new_comminst(op_id, results,
482
                              getattr(self.rmu.MuCommInst, op.args[0].value),
483
484
485
                              flags, types, sigs,
                              self._ids_of(op.args[1:-1]))

John Zhang's avatar
John Zhang committed
486
487
488
    def _genop_mu_meta_callinternal(self, op, op_id):
        pass

489
    def _id_of(self, entity):
John Zhang's avatar
John Zhang committed
490
491
492
493
494
495
496
497
        # look up id of the entity, if non-existent, call gen_sym
        _id = self.idmap[entity]
        assert _id
        if isinstance(_id, str):     # still name
            _name = _id
            _id = self.bdr.gen_sym(_name)
            self.idmap[entity] = _id  # drop the name
        return _id
498
499

    def _ids_of(self, lst_entity):
John Zhang's avatar
John Zhang committed
500
        return map(lambda e: self._id_of(e), lst_entity)
501
502

    def init_heap(self):
503
504
505
506
        count = 0
        total = len(self.db.objtracer.heap_objs) + len(self.db.objtracer.fixed_objs)
        self.log.init_heap('initialising heap objects...')

507
508
509
510
511
512
513
514
515
516
517
        # allocate memory first
        for obj in self.db.objtracer.heap_objs:
            MuT = mutype.mutypeOf(obj)
            tid = self._id_of(MuT)
            if isinstance(MuT, mutype.MuHybrid):
                hlen = self.ctx.handle_from_uint64(obj.length, mutype.mutypeOf(obj.length).BITS)
                hdl = self.ctx.new_hybrid(tid, hlen)
            else:
                hdl = self.ctx.new_fixed(tid)
            self.obj_hdl_map[obj] = hdl

John Zhang's avatar
John Zhang committed
518
        for i, obj in enumerate(self.db.objtracer.fixed_objs):
519
520
            if isinstance(mutype.mutypeOf(obj), mutype.MuHybrid):
                obj = self._hyb2stt_map[obj]
John Zhang's avatar
John Zhang committed
521
522
            # generate a symbol string
            sym_str = "mu_reloc_obj_%d" % i
523
            hdl = self.ctx.handle_from_global(self._id_of(self.reloc_obj_map[obj]))
John Zhang's avatar
John Zhang committed
524
525
            self.reloc_obj_map[obj] = (sym_str, hdl)    # sym_str, gcl handle, field handle
            # self.obj_hdl_map[obj] = hdl
526
527
528

        for obj in self.db.objtracer.heap_objs:
            self._init_heap_obj(obj)
529
530
531
532
533
534

            count += 1
            if count % 10 == 0 or count == total:
                sys.stderr.write("\033[0F\033[K")
                self.log.init_heap('initialising heap objects... (%d/%d %d%%)' % (count, total, count * 100 / total))

535
536
537
        for obj in self.db.objtracer.fixed_objs:
            self._init_fixed_obj(obj)

538
539
540
541
542
            count += 1
            if count % 10 == 0 or count == total:
                sys.stderr.write("\033[0F\033[K")
                self.log.init_heap('initialising heap objects... (%d/%d %d%%)' % (count, total, count * 100 / total))

543
544
545
546
547
        # store to global cells
        for gcl_c in self.db.gcells:
            MuT = gcl_c.concretetype.TO
            gcl_id = self._id_of(gcl_c)
            obj = gcl_c.value._obj
548
549
550
551
552
553
            if isinstance(MuT, mutype.MuObjectRef):
                hgcl = self.ctx.handle_from_global(gcl_id)
                if obj._is_null():
                    NULL_c = self.db.heap_NULL_constant_map[mutype.mutypeOf(obj)]
                    NULL_c_id = self._id_of(NULL_c)
                    hdl = self.ctx.handle_from_const(NULL_c_id)
John Zhang's avatar
John Zhang committed
554
                    self.ctx.store(self.rmu.MuMemOrd.NOT_ATOMIC, hgcl, hdl)
555
556
557
558
559
                else:
                    if isinstance(MuT, (mutype.MuRef, mutype.MuWeakRef)):
                        heap_obj = obj._obj if isinstance(MuT, mutype.MuRef) else obj._obj()
                        if isinstance(mutype.mutypeOf(heap_obj), mutype.MuStruct):
                            heap_obj = heap_obj._normalizedcontainer()
John Zhang's avatar
John Zhang committed
560
                        hdl = self.obj_hdl_map[heap_obj]
John Zhang's avatar
John Zhang committed
561
                        self.ctx.store(self.rmu.MuMemOrd.NOT_ATOMIC, hgcl, hdl)
562
563
564
565
566
567
                    elif isinstance(MuT, mutype.MuUPtr):
                        fixed_obj = obj._obj
                        if isinstance(mutype.mutypeOf(fixed_obj), mutype.MuHybrid):
                            fixed_obj = self._hyb2stt_map[fixed_obj]
                        if isinstance(mutype.mutypeOf(fixed_obj), mutype.MuStruct):
                            fixed_obj = fixed_obj._normalizedcontainer()
John Zhang's avatar
John Zhang committed
568
569
570
                        # hgcl_obj = self.reloc_obj_map[fixed_obj]
                        # hdl = self.ctx.get_addr(hgcl_obj)
                        self.reloc_obj_map[fixed_obj] += (hgcl, )
571

572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
    def _init_heap_obj(self, obj, hiref=None):
        MuT = mutype.mutypeOf(obj)
        if isinstance(MuT, mutype.MuNumber):
            if isinstance(MuT, mutype.MuIntType):
                if MuT.BITS <= 64:
                    mtd = getattr(self.ctx, 'handle_from_uint%d' % MuT.BITS)
                    return mtd(obj, MuT.BITS)
                else:
                    return self.ctx.handle_from_uint64s(obj.get_uint64s(), MuT.BITS)
            elif MuT == mutype.MU_FLOAT:
                return self.ctx.handle_from_float(float(obj))
            elif MuT == mutype.MU_DOUBLE:
                return self.ctx.handle_from_double(float(obj))

        elif isinstance(MuT, mutype.MuStruct):
            if not hiref:
                href = self.obj_hdl_map[obj]
                hiref = self.ctx.get_iref(href)
            self._init_heap_struct_like(obj, hiref)

            return

        elif isinstance(MuT, mutype.MuHybrid):
            if not hiref:
                href = self.obj_hdl_map[obj]
                hiref = self.ctx.get_iref(href)

            # fixed fields
            self._init_heap_struct_like(obj, hiref, MuT._names[:-1])

            # var fields
            memarr = getattr(obj, MuT._varfld)
            hiref_var = self.ctx.get_var_part_iref(hiref)
            self._init_heap_array_like(memarr, hiref_var)

            return

        elif isinstance(MuT, mutype.MuArray):
            if len(obj) > 0:
                if not hiref:
                    href = self.obj_hdl_map[obj]
                    hiref = self.ctx.get_iref(href)
                helm_0 = self.ctx.get_elem_iref(hiref, self.ctx.handle_from_uint64(0, 64))
                self._init_heap_array_like(obj, helm_0)

            return

        elif isinstance(MuT, mutype.MuReferenceType):
            if obj._is_null():
                const_id = self._id_of(self.db.heap_NULL_constant_map[MuT])
                return self.ctx.handle_from_const(const_id)

John Zhang's avatar
John Zhang committed
624
625
626
            if isinstance(MuT, (mutype.MuRef, mutype.MuWeakRef)):
                _obj = obj._obj if isinstance(MuT, mutype.MuRef) else obj._obj()
                refnt = _obj._normalizedcontainer() if isinstance(MuT.TO, mutype.MuStruct) else _obj
627
628
629
630
631
632
633
634
635
                return self.obj_hdl_map[refnt]

            elif isinstance(MuT, mutype.MuUPtr):
                refnt = obj._obj
                if isinstance(MuT.TO, mutype.MuStruct):
                    refnt = refnt._normalizedcontainer()
                elif isinstance(MuT.TO, mutype.MuHybrid):
                    refnt = self._hyb2stt_map[refnt]

John Zhang's avatar
John Zhang committed
636
637
638
639
640
641
642
643
                # add field iref handle to reloc record
                assert hiref
                self.reloc_obj_map[refnt] += (hiref, )

                # hgcl = self.obj_hdl_map[refnt]
                # addr = self.ctx.get_addr(hgcl)
                # return addr
                return
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672

            elif isinstance(MuT, mutype.MuFuncRef):
                return self.ctx.handle_from_func(self._id_of(obj.graph))

        raise NotImplementedError("Don't know how to initialise heap object %s of type %s" % (obj, MuT))

    def _init_heap_struct_like(self, obj, hiref, names=None):
        MuT = mutype.mutypeOf(obj)
        if names is None:
            names = MuT._names

        for idx, fld_name in enumerate(names):
            fld_hiref = self.ctx.get_field_iref(hiref, idx)
            fld_val_hdl = self._init_heap_obj(getattr(obj, fld_name), fld_hiref)
            if fld_val_hdl:
                self.ctx.store(self.rmu.MuMemOrd.NOT_ATOMIC, fld_hiref, fld_val_hdl)

    def _init_heap_array_like(self, arr, hiref):
        for i in range(len(arr)):
            elm = arr[i]
            hidx = self.ctx.handle_from_uint64(i, 64)
            elm_iref = self.ctx.shift_iref(hiref, hidx)
            elm_hdl = self._init_heap_obj(elm, elm_iref)
            if elm_hdl:
                self.ctx.store(self.rmu.MuMemOrd.NOT_ATOMIC, elm_iref, elm_hdl)

    def _init_fixed_obj(self, obj):
        if isinstance(mutype.mutypeOf(obj), mutype.MuHybrid):
            obj = self._hyb2stt_map[obj]
John Zhang's avatar
John Zhang committed
673
        self._init_heap_obj(obj, self.reloc_obj_map[obj][1])
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693


def hybrid2struct(hyb):
    # convert a hybrid with known size to struct
    Hyb = mutype.mutypeOf(hyb)
    assert isinstance(Hyb, mutype.MuHybrid)
    fixed_flds = [(n, Hyb._flds[n]) for n in Hyb._names[:-1]]
    Arr = mutype.MuArray(Hyb._var_field_type(), len(getattr(hyb, Hyb._varfld)))
    Stt = mutype.MuStruct(Hyb._name, *(fixed_flds + [(Hyb._varfld, Arr)]))

    stt = mutype._mustruct(Stt)
    for n in Hyb._names[:-1]:
        setattr(stt, n, getattr(hyb, n))

    stt_arr = getattr(stt, Hyb._varfld)
    hyb_arr = getattr(hyb, Hyb._varfld)
    for i, e in enumerate(hyb_arr):
        stt_arr[i] = e

    return stt