LlvmGenerator.py 8 KB
Newer Older
Maxime Perrotin's avatar
Maxime Perrotin committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
    OpenGEODE - A tiny SDL Editor for TASTE

    This module generates LLVM IR code from SDL process models, allowing
    generation of a binary application without an intermediate language.
    LLVM also allows for various code verification, analysis, and optimization.

    The design is based on the Ada code generator. Check it for details.

    Copyright (c) 2012-2013 European Space Agency

    Designed and implemented by Maxime Perrotin

    Contact: maxime.perrotin@esa.int
"""

import logging
Maxime Perrotin's avatar
Maxime Perrotin committed
21
from singledispatch import singledispatch
Maxime Perrotin's avatar
Maxime Perrotin committed
22
23
24
25
26
27
from llvm import core, passes, ee

import ogAST

LOG = logging.getLogger(__name__)

Maxime Perrotin's avatar
Maxime Perrotin committed
28
29
__all__ = ['generate']

Maxime Perrotin's avatar
Maxime Perrotin committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

# LLVM Global variable - Initialized when the generator is invoked
LLVM = {
    # The LLVM module, which holds all the IR code.
    'module': None,
    # Dictionary that keeps track of which values are defined in the current
    # scope and what their LLVM representation is.
    'named_values': {},
    # The function optimization passes manager.
    'pass_manager': None,
    # The LLVM execution engine.
    'executor': None
}



Maxime Perrotin's avatar
Maxime Perrotin committed
46
47
48
49
@singledispatch
def generate(ast):
    ''' Generate the code for an item of the AST '''
    raise TypeError('[Backend] Unsupported AST construct')
Maxime Perrotin's avatar
Maxime Perrotin committed
50

Maxime Perrotin's avatar
Maxime Perrotin committed
51
# Processing of the AST
Maxime Perrotin's avatar
Maxime Perrotin committed
52

Maxime Perrotin's avatar
Maxime Perrotin committed
53
54
55
56
@generate.register(ogAST.Process)
def _process(process):
    ''' Generate LLVM IR code (incomplete) '''
    process_name = process.processName
Maxime Perrotin's avatar
Maxime Perrotin committed
57
58
59
60
61
62
63
64
65
    LOG.info('Generating LLVM IR code for process ' + str(process_name))

    # Initialise LLVM global structure
    LLVM['module'] = core.Module.new(str(process_name))
    LLVM['pass_manager'] = passes.FunctionPassManager.new(LLVM['module'])
    LLVM['executor'] = ee.ExecutionEngine.new(LLVM['module'])
    # Set up the optimizer pipeline.
    # Start with registering info about how the
    # target lays out data structures.
66
67
68
69
70
71
72
73
74
75
#   LLVM['pass_manager'].add(LLVM['executor'].target_data)
#   # Do simple "peephole" optimizations and bit-twiddling optzns.
#   LLVM['pass_manager'].add(passes.PASS_INSTRUCTION_COMBINING)
#   # Reassociate expressions.
#   LLVM['pass_manager'].add(passes.PASS_REASSOCIATE)
#   # Eliminate Common SubExpressions.
#   LLVM['pass_manager'].add(passes.PASS_GVN)
#   # Simplify the control flow graph (deleting unreachable blocks, etc).
#   LLVM['pass_manager'].add(passes.PASS_CFG_SIMPLIFICATION)
#   LLVM['pass_manager'].initialize()
Maxime Perrotin's avatar
Maxime Perrotin committed
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104

    # Create the runTransition function
    run_funct_name = 'run_transition'
    run_funct_type = core.Type.function(core.Type.void(), [
        core.Type.int()])
    run_funct = core.Function.new(
            LLVM['module'], run_funct_type, run_funct_name)
    # Generate the code of the start transition:
    # Clear scope
    LLVM['named_values'].clear()
    # Create the function name and type
    funct_name = str(process_name) + '_startup' 
    funct_type = core.Type.function(core.Type.void(), [])
    # Create a function object
    function = core.Function.new(LLVM['module'], funct_type, funct_name)
    # Create a new basic block to start insertion into.
    block = function.append_basic_block('entry')
    builder = core.Builder.new(block)
    # Add the body of the function
    builder.call(run_funct, (core.Constant.int(
                                     core.Type.int(), 0),))
    # Add terminator (mandatory)
    builder.ret_void()
    # Validate the generated code, checking for consistency.
    function.verify()
    # Optimize the function (not yet).
    # LLVM['pass_manager'].run(function)
    print function

Maxime Perrotin's avatar
Maxime Perrotin committed
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295


def write_statement(param, newline):
    ''' Generate the code for the special "write" operator '''
    pass

@generate.register(ogAST.Output)
@generate.register(ogAST.ProcedureCall)
def _call_external_function(output):
    ''' Generate the code of a set of output or procedure call statement '''
    pass


@generate.register(ogAST.TaskAssign)
def _task_assign(task):
    ''' A list of assignments in a task symbol '''
    pass


@generate.register(ogAST.TaskInformalText)
def _task_informal_text(task):
    ''' Generate comments for informal text '''
    pass


@generate.register(ogAST.TaskForLoop)
def _task_forloop(task):
    '''
        Return the code corresponding to a for loop. Two forms are possible:
        for x in range ([start], stop [, step])
        for x in iterable (a SEQUENCE OF)
    '''
    pass


@generate.register(ogAST.PrimVariable)
def _primary_variable(prim):
    ''' Single variable reference '''
    pass


@generate.register(ogAST.PrimPath)
def _prim_path(primaryId):
    '''
        Return the string of an element list (path)
        cases: a => 'l_a' (reference to a variable)
        a_timer => 'a_timer'  (reference to a timer)
        a!b => a.b (field of a structure)
        a!b if a is a CHOICE => TypeOfa_b_get(a)
        a(Expression) => a(ExpressionSolver) (array index)
        Expression can be complex (if-then-else-fi..)
    '''
    pass


@generate.register(ogAST.ExprPlus)
@generate.register(ogAST.ExprMul)
@generate.register(ogAST.ExprMinus)
@generate.register(ogAST.ExprEq)
@generate.register(ogAST.ExprNeq)
@generate.register(ogAST.ExprGt)
@generate.register(ogAST.ExprGe)
@generate.register(ogAST.ExprLt)
@generate.register(ogAST.ExprLe)
@generate.register(ogAST.ExprDiv)
@generate.register(ogAST.ExprMod)
@generate.register(ogAST.ExprRem)
@generate.register(ogAST.ExprAssign)
def _basic_operators(expr):
    ''' Expressions with two sides '''
    pass


@generate.register(ogAST.ExprOr)
@generate.register(ogAST.ExprAnd)
@generate.register(ogAST.ExprXor)
def _bitwise_operators(expr):
    ''' Logical operators '''
    pass


@generate.register(ogAST.ExprAppend)
def _append(expr):
    ''' Generate code for the APPEND construct: a // b '''
    pass


@generate.register(ogAST.ExprIn)
def _expr_in(expr):
    ''' IN expressions: check if item is in a SEQUENCE OF '''
    pass


@generate.register(ogAST.PrimEnumeratedValue)
def _enumerated_value(primary):
    ''' Generate code for an enumerated value '''
    pass


@generate.register(ogAST.PrimChoiceDeterminant)
def _choice_determinant(primary):
    ''' Generate code for a choice determinant (enumerated) '''
    pass


@generate.register(ogAST.PrimInteger)
@generate.register(ogAST.PrimReal)
@generate.register(ogAST.PrimBoolean)
def _integer(primary):
    ''' Generate code for a raw integer/real/boolean value  '''
    pass


@generate.register(ogAST.PrimEmptyString)
def _empty_string(primary):
    ''' Generate code for an empty SEQUENCE OF: {} '''
    pass


@generate.register(ogAST.PrimStringLiteral)
def _string_literal(primary):
    ''' Generate code for a string (Octet String) '''
    pass


@generate.register(ogAST.PrimConstant)
def _constant(primary):
    ''' Generate code for a reference to an ASN.1 constant '''
    pass


@generate.register(ogAST.PrimMantissaBaseExp)
def _mantissa_base_exp(primary):
    ''' Generate code for a Real with Mantissa-base-Exponent representation '''
    pass


@generate.register(ogAST.PrimIfThenElse)
def _if_then_else(ifThenElse):
    ''' Return string and statements for ternary operator '''
    pass


@generate.register(ogAST.PrimSequence)
def _sequence(seq):
    ''' Return Ada string for an ASN.1 SEQUENCE '''
    pass


@generate.register(ogAST.PrimSequenceOf)
def _sequence_of(seqof):
    ''' Return Ada string for an ASN.1 SEQUENCE OF '''
    pass


@generate.register(ogAST.PrimChoiceItem)
def _choiceitem(choice):
    ''' Return the Ada code for a CHOICE expression '''
    pass


@generate.register(ogAST.Decision)
def _decision(dec):
    ''' generate the code for a decision '''
    pass


@generate.register(ogAST.Label)
def _label(tr):
    ''' Transition following labels are generated in a separate section
        for visibility reasons (see Ada scope)
    '''
    pass


@generate.register(ogAST.Transition)
def _transition(tr):
    ''' generate the code for a transition '''
    pass


@generate.register(ogAST.Floating_label)
def _floating_label(label):
    ''' Generate the code for a floating label (Ada label + transition) '''
    pass


@generate.register(ogAST.Procedure)
def _inner_procedure(proc):
    ''' Generate the code for a procedure '''
    pass