shared libraries can now export variables on MIPS
[voodoo-lang.git] / lib / voodoo / generators / mips_gas_generator.rb
blobdd6afdc08635c1abbe0dad1cdfe43b1d087833e5
1 require 'voodoo/generators/common_code_generator'
2 require 'set'
4 module Voodoo
5   # = MIPS GNU Assembler Code Generator
6   #
7   # The MIPS code generator generates assembly code for use with
8   # the GNU assembler.
9   #
10   # == Calling Convention
11   #
12   # The first four arguments are passed in the registers $4 through $7.
13   # Any additional arguments are passed on the stack, starting at
14   # $sp + 16. Words $sp through $sp + 12 will be available for the called
15   # function to use. $sp will always be a multiple of 8.
16   #
17   # The return address for the called function is passed in $31.
18   #
19   # When performing a position-independent call, the address of the called
20   # function is passed in $25.
21   #
22   # The called function will store its return value in $2.
23   #
24   # The called function is required to preserve the values of registers
25   # $16 through $23 and register $30.
26   #
27   # This calling convention is compatible with the System V ELF ABI.
28   #
29   # == Call Frames
30   #
31   # Call frames have the following layout:
32   #
33   # When a function is called, it receives a stack frame that looks like
34   # the following:
35   #
36   #   :
37   #   old frame
38   #   argn
39   #   :
40   #   arg4
41   #   empty3
42   #   empty2
43   #   empty1
44   #   empty0    <-- $sp points here
45   #
46   # The function prologue of functions generated by this code generator
47   # creates activation frames that look as follows:
48   #
49   # :
50   # old frame
51   # argn
52   # :
53   # arg4
54   # arg3
55   # arg2
56   # arg1
57   # arg0       <-- $fp points here
58   # return address
59   # pointer to Global Offset Table
60   # saved $fp
61   # local0
62   # :
63   # local7
64   # local8
65   # :
66   # localn
67   # padding    <-- $sp points here
68   #
69   # In words:
70   #
71   # The four empty slots provided by the caller are used to store
72   # arguments 0 through 3 (originally passed in $4 through $7),
73   # if necessary.
74   #
75   # The stack frame created below the four slots provided by the caller
76   # contains the following data, in order:
77   #
78   # - Saved return address (originally passed in $31), if necessary.
79   #
80   # - Saved pointer to global offset table (computed from $25), if necessary.
81   #
82   # - Saved value of $fp, if necessary.
83   #
84   # - Saved values of caller's locals 0 through 7
85   #   (originally in $16 through $23), if necessary.
86   #
87   # - Values of our locals > 8, if necessary.
88   #
89   # - Padding to align $sp on a multiple of 8, if necessary.
90   #
91   #
92   # In accordance with the System V ELF ABI for MIPS, the pointer to
93   # the global offset table is calculated as follows:
94   #
95   # $gp = _gp_disp + $25
96   #
97   # where $gp is the register to store the pointer, $25 is the register
98   # holding the address of the called function, and _gp_disp is the
99   # offset between the beginning of the function and the global offset table.
100   #
101   # Callee-Save Registers
102   #
103   # Registers $16 through $23 and $28 through $30 are callee-save.
104   #
105   # All other registers are caller-save.
106   #
107   class MIPSGasGenerator < CommonCodeGenerator
108     def initialize params
109       @WORDSIZE_BITS = 2
110       @WORDSIZE = 1 << @WORDSIZE_BITS
111       @CODE_ALIGNMENT = 0
112       @DATA_ALIGNMENT = @WORDSIZE
113       @STACK_ALIGNMENT_BITS = 3
114       @STACK_ALIGNMENT = 1 << @STACK_ALIGNMENT_BITS
115       @FP_OFFSET = -3 * @WORDSIZE
116       @FUNCTION_ALIGNMENT = @WORDSIZE
117       @GP_OFFSET = -2 * @WORDSIZE
118       @INITIAL_FRAME_SIZE = 4 * @WORDSIZE
119       @REGISTER_ARG_BASE = 4
120       @NREGISTER_ARGS = 4
121       @LOCAL_REGISTERS = [:'$16', :'$17', :'$18', :'$19',
122                           :'$20', :'$21', :'$22', :'$23']
123       @LOCAL_REGISTERS_SET = Set.new @LOCAL_REGISTERS
124       @REGISTER_LOCAL_BASE = 16
125       @NREGISTER_LOCALS = @LOCAL_REGISTERS.length
126       @RA_OFFSET = -@WORDSIZE
127       @RETURN = :'$2'
128       @TEMPORARY = :'$1'
129       @FUNCTION = :'$25'
130       @GOT = :'$28'
131       @SAVE_FRAME_REGISTERS = [:'$16', :'$17', :'$18', :'$19', :'$20',
132                                :'$21', :'$22', :'$23', :'$28', :'$29',
133                                :'$30']
134       @SAVED_FRAME_LAYOUT = {}
135       @SAVE_FRAME_REGISTERS.each_with_index { |r,i| @SAVED_FRAME_LAYOUT[r] = i }
136       @TEMPORARIES = [:'$8', :'$9', :'$10', :'$11',
137                       :'$12', :'$13', :'$14', :'$15']
138       @function_end_label = nil
139       @imports = {}
140       @if_labels = []
141       super params
142       @output_file_suffix = '.s'
143       @saved_registers = []
144       @features.merge! \
145         :'bits-per-word' => '32',
146         :'bytes-per-word' => '4'
147       case @architecture
148       when :mips
149         @features[:'byte-order'] = 'big-endian'
150       when :mipsel
151         @features[:'byte-order'] = 'little-endian'
152       else
153         raise ArgumentError.new("#{self.class} does not support " +
154                                 "architecture #{@architecture}")
155       end
156     end
158     # Adds immediate to source and stores the result in target.
159     def addiu target, source, immediate, temporary = @TEMPORARY
160       if immediate >= -32768 && immediate < 32767
161         emit "addiu #{target}, #{source}, #{immediate}\n"
162       elsif source == "$0"
163         emit "lui #{target}, #{(immediate >> 16) & 0xffff}\n"
164         emit "ori #{target}, #{target}, #{immediate & 0xffff}\n"
165       else
166         addiu temporary, "$0", immediate
167         emit "addu #{target}, #{source}, #{temporary}\n"
168       end
169     end
171     # Return the offset from the frame base at which the nth argument is
172     # stored.
173     def arg_offset n
174       n * @WORDSIZE
175     end
177     # Returns an $fp-relative reference for the nth (0-based) argument.
178     def arg_reference n
179       offset_reference(arg_offset(n))
180     end
182     # Returns the register in which the nth (0-based) argument is stored, or
183     # nil if not stored in a register.
184     def arg_register n
185       if register_arg? n
186         "$#{@REGISTER_ARG_BASE + n}"
187       else
188         nil
189       end
190     end
192     def auto_bytes n, register
193       if n.kind_of? Integer
194         # Maintain stack alignment
195         n = (n + @STACK_ALIGNMENT - 1) / @STACK_ALIGNMENT * @STACK_ALIGNMENT
196         grow_stack n
197       else
198         temporary = @TEMPORARIES.pop
199         begin
200           load_value_into_register n, register
201           emit "addi #{register}, #{@STACK_ALIGNMENT - 1}\n"
202           emit "li #{temporary}, -#{@STACK_ALIGNMENT}\n"
203           emit "and #{register}, #{register}, #{temporary}\n"
204           emit "sub $sp, #{register}\n"
205         ensure
206           @TEMPORARIES.push temporary
207         end
208       end
209       emit "move #{register}, $sp\n" unless register == "$sp"
210     end
212     def auto_words n, register
213       if n.kind_of? Integer
214         auto_bytes n * @WORDSIZE, register
215       else
216         load_value_into_register n, register
217         if @STACK_ALIGNMENT_BITS > @WORDSIZE_BITS
218           bits = @STACK_ALIGNMENT_BITS - @WORDSIZE_BITS
219           emit "addi #{register}, #{(1 << bits) - 1}\n"
220           emit "srl #{register}, #{register}, #{bits}\n"
221           emit "sll #{register}, #{register}, #{@STACK_ALIGNMENT_BITS}\n"
222         else
223           emit "sll #{register}, #{register}, #{@WORDSIZE_BITS}\n"
224         end
225         emit "sub $sp, $sp, #{register}\n"
226         emit "move #{register}, $sp\n" unless register == "$sp"
227       end
228     end
230     # Begins a new block.
231     def begin_block *code
232       # If we are at top-level, create a frame
233       if @environment == @top_level
234         create_frame count_locals(code)
235       end
236       environment = Environment.new @environment
237       @environment = environment
238     end
240     # Emits function prologue and declare _formals_ as function arguments.
241     def begin_function formals, nlocals
242       if @environment != @top_level
243         raise "Cannot begin function when already in a function"
244       end
246       environment = Environment.new @environment
247       @frame_size = 0
248       formals.each {|x| environment.add_arg x, arg_offset(environment.args)}
249       @environment = environment
250       @function_end_label = gensym
251       emit_function_prologue formals, nlocals
252     end
254     # Defines a byte with the given value.
255     def byte value
256       emit ".byte #{value}\n"
257     end
259     # Calls a function.
260     def call func, *args
261       # Grow the stack frame, subject to 3 conditions:
262       # 1. There must be enough space to hold all arguments
263       # 2. $sp must remain a multiple of 8
264       # 3. We must provide space for at least 4 words
265       increment = ([args.length, 4].max * @WORDSIZE + 7) / 8 * 8
266       grow_stack increment
268       # Put arguments in the right places
269       n = 0
270       while n < args.length
271         if n < @NREGISTER_ARGS
272           # Put arguments up to @NREGISTER_ARGS in registers
273           load_value_into_register args[n], arg_register(n)
274         else
275           # Put other arguments on the stack
276           load_value_into_register args[n], @TEMPORARY
277           emit "sw #{@TEMPORARY}, #{n * @WORDSIZE}($sp)\n"
278         end
279         n = n + 1
280       end
282       # Load function address
283       if global? func
284         if @imports.has_key? func
285           # Load address from global offset table
286           emit "lw #{@FUNCTION}, %call16(#{func})(#{@GOT})\n"
287         else
288           # Assume label defined in this module
289           emit "lui #{@FUNCTION}, %hi(#{func})\n"
290           emit "addiu #{@FUNCTION}, %lo(#{func})\n"
291         end
292       else
293         # Load address
294         load_value_into_register func, "#{@FUNCTION}"
295       end
297       # Perform call
298       emit "jalr #{@FUNCTION}\n"
299       # brach delay slot
300       emit "nop\n"
302       # Restore original stack frame
303       grow_stack -increment
305       # restore gp
306       emit "lw #{@GOT}, #{@GP_OFFSET}($fp)\n"
307     end
309     # Emits a comment.
310     def comment text
311       emit "# #{text}\n"
312     end
314     # Starts a conditional using the specified branch instruction
315     # after the comparison.
316     def common_if comp, x, y = nil
317       temporaries = @TEMPORARIES.dup
318       xreg = load_value x, temporaries[0]
319       temporaries.delete xreg
320       yreg = load_value y, temporaries[0]
321       temporaries.delete yreg
323       falselabel = @environment.gensym
324       @if_labels.push falselabel
326       case comp
327       when :ifeq
328         emit "bne #{xreg}, #{yreg}, #{falselabel}\n"
329       when :ifge
330         emit "slt #{@TEMPORARY}, #{xreg}, #{yreg}\n"
331         emit "bne #{@TEMPORARY}, $0, #{falselabel}\n"
332       when :ifgt
333         emit "slt #{@TEMPORARY}, #{yreg}, #{xreg}\n"
334         emit "beq #{@TEMPORARY}, $0, #{falselabel}\n"
335       when :ifle
336         emit "slt #{@TEMPORARY}, #{yreg}, #{xreg}\n"
337         emit "bne #{@TEMPORARY}, $0, #{falselabel}\n"
338       when :iflt
339         emit "slt #{@TEMPORARY}, #{xreg}, #{yreg}\n"
340         emit "beq #{@TEMPORARY}, $0, #{falselabel}\n"
341       when :ifne
342         emit "beq #{xreg}, #{yreg}, #{falselabel}\n"
343       else
344         raise "Unknown conditional: #{comp}"
345       end
346       emit "nop\n"
347     end
349     # Creates an activation frame which can store nlocals local variables.
350     def create_frame nlocals
351       @frame_size = @INITIAL_FRAME_SIZE
352       if nlocals > 0
353         @frame_size = @frame_size + (nlocals * @WORDSIZE + 7) / 8 * 8
354       end
355       grow_stack @frame_size
356       @saved_registers = []
357     end
359     def emit_align alignment
360       emit ".align #{alignment}\n"
361     end
363     # Exports symbols from the current section.
364     def emit_export *symbols
365       symbols.each { |sym| emit ".globl #{sym}\n" }
366     end
368     # Emits function prologue.
369     def emit_function_prologue formals = [], nlocals = 0
370       # Calculate new value for $gp
371       emit "lui #{@GOT}, %hi(_gp_disp)\n"
372       emit "addiu #{@GOT}, %lo(_gp_disp)\n"
373       emit "addu #{@GOT}, #{@GOT}, #{@FUNCTION}\n"
375       create_frame nlocals
377       # Save return address
378       emit "sw $31, #{@frame_size - @WORDSIZE}($sp)\n"
380       # Save gp
381       emit "sw #{@GOT}, #{@frame_size - 2 * @WORDSIZE}($sp)\n"
383       # Save fp
384       emit "sw $fp, #{@frame_size - 3 * @WORDSIZE}($sp)\n"
386       # Point fp at where sp was before we created the frame
387       addiu "$fp", "$sp", @frame_size
389       # Save parameters 0 .. 3 in the stack space that the caller
390       # should have allocated for them.
391       [@NREGISTER_ARGS, formals.length].min.times do |n|
392         ref = offset_reference(@environment[formals[n]])
393         emit "sw $#{n + @REGISTER_ARG_BASE}, #{ref}\n"
394       end
395     end
397     # Imports labels into the current section.
398     def emit_import *symbols
399       # Record imported labels in @imports
400       symbols.each { |sym| @imports[sym] = sym }
401     end
403     # Emits a label type annotation.
404     def emit_label_type name, type
405       type_map = {
406         :code => "@function",
407         :data => "@object",
408       }
409       emit ".type #{name}, #{type_map[type]}\n"
410     end
412     # Emits a label size annotation.
413     def emit_label_size name
414       emit ".size #{name}, .-#{name}\n"
415     end
417     # Loads a word into a register.
418     def emit_load_word register, base, offset
419       emit "lw #{register}, #{offset * @WORDSIZE}(#{base})\n"
420     end
422     # Stores the value of a register in memory.
423     def emit_store_word register, base, offset
424       emit "sw #{register}, #{offset * @WORDSIZE}(#{base})\n"
425     end
427     # Ends a function body.
428     def end_function
429       if @environment == @top_level
430         raise "Cannot end function when not in a function"
431       end
433       label @function_end_label
434       # Restore saved locals
435       [@NREGISTER_LOCALS, @environment.locals].min.times do |n|
436         emit "lw #{local_register n}, #{local_reference n}\n"
437       end
438       @saved_registers = []
439       # Load return address
440       emit "lw $31, #{@RA_OFFSET}($fp)\n"
441       # Restore stack pointer
442       emit "move $sp, $fp\n"
443       # Restore frame pointer
444       emit "lw $fp, #{@FP_OFFSET}($fp)\n"
445       # Return
446       emit "jr $31\n"
447       emit "nop\n"
449       @function_end_label = nil
450       @environment = @top_level
451     end
453     # Ends the current block.
454     def end_block
455       # If we are returning to top level, restore stack pointer
456       if @environment.parent == @top_level
457         grow_stack -@frame_size
458         @saved_registers = []
459       end
461       # Restore old value of @environment
462       @environment = @environment.parent
463     end
465     # Ends a conditional.
466     def end_if
467       label = @if_labels.pop
468       emit "#{label}:\n"
469     end
471     # Evaluates the binary operation expr and store the result in register.
472     def eval_binop expr, register
473       temporaries = @TEMPORARIES.dup
474       x = load_value expr[1], temporaries[0]
475       temporaries.delete x
476       y = load_value expr[2], temporaries[0]
477       temporaries.delete y
479       case expr[0]
480       when :asr
481         emit "srav #{register}, #{x}, #{y}\n"
482       when :bsr
483         emit "srlv #{register}, #{x}, #{y}\n"
484       when :div
485         emit "div $0, #{x}, #{y}\n"
486         emit "mflo #{register}\n"
487       when :mod
488         emit "div $0, #{x}, #{y}\n"
489         emit "mfhi #{register}\n"
490       when :mul
491         emit "mult #{x}, #{y}\n"
492         emit "mflo #{register}\n"
493       when :rol
494         emit "subu #{@TEMPORARY}, $0, #{y}\n"
495         emit "srlv #{@TEMPORARY}, #{x}, #{@TEMPORARY}\n"
496         emit "sllv #{register}, #{x}, #{y}\n"
497         emit "or #{register}, #{register}, #{@TEMPORARY}\n"
498       when :ror
499         emit "subu #{@TEMPORARY}, $0, #{y}\n"
500         emit "sllv #{@TEMPORARY}, #{x}, #{@TEMPORARY}\n"
501         emit "srlv #{register}, #{x}, #{y}\n"
502         emit "or #{register}, #{register}, #{@TEMPORARY}\n"
503       when :shl
504         emit "sllv #{register}, #{x}, #{y}\n"
505       when :shr
506         emit "srlv #{register}, #{x}, #{y}\n"
507       else
508         emit "#{expr[0]} #{register}, #{x}, #{y}\n"
509       end
510     end
512     # Evaluates the expression expr and store the result in register.
513     def eval_expr expr, register
514       if expr.length == 1
515         # Load value
516         load_value_into_register expr[0], register
517       else
518         # Evaluate expression
519         op = expr[0]
520         case op
521         when :'auto-bytes'
522           auto_bytes expr[1], register
523         when :'auto-words'
524           auto_words expr[1], register
525         when :call
526           call *expr[1..-1]
527           emit "move #{register}, #{@RETURN}\n" if register != @RETURN
528         when :'get-byte'
529           get_byte expr[1], expr[2], register
530         when :'get-word'
531           get_word expr[1], expr[2], register
532         when :not
533             eval_binop [:nor, 0, expr[1]], register
534         else
535           if binop? op
536             eval_binop expr, register
537           else
538             raise "Not a magic word: #{op}"
539           end
540         end
541       end
542     end
544     # Loads byte from _base_ + _offset_ into _register_.
545     def get_byte base, offset, register
546       # If base is an integer, but offset isn't, swap them
547       if !integer?(offset) && integer?(base)
548         base, offset = [offset, base]
549       end
551       if integer? offset
552         base_reg = load_value base
553         emit "lb #{register}, #{offset}(#{base_reg})\n"
554       else
555         eval_binop [:add, base, offset], @TEMPORARY
556         emit "lb #{register}, 0(#{@TEMPORARY})\n"
557       end
558     end
560     # Loads word from _base_ + _offset_ * _@WORDSIZE_ into _register_.
561     def get_word base, offset, register
562       if integer? offset
563         base_reg = load_value base
564         emit "lw #{register}, #{offset * @WORDSIZE}(#{base_reg})\n"
565       else
566         offset_reg = @TEMPORARIES.pop
567         begin
568           load_value_into_register offset, offset_reg
569           base_reg = load_value base
570           emit "sll #{offset_reg}, #{offset_reg}, 2\n" # multiply by @WORDSIZE
571           emit "add #{@TEMPORARY}, #{base_reg}, #{offset_reg}\n"
572           emit "lw #{register}, 0(#{@TEMPORARY})\n"
573         ensure
574           @TEMPORARIES.push offset_reg
575         end
576       end
577     end
579     # Jumps to an address.
580     def goto address
581       if global? address
582         emit "j #{address}\n"
583       else
584         register = load_value address, @TEMPORARY
585         emit "jr #{register}\n"
586       end
587       emit "nop\n"
588     end
590     # Grows the stack by n bytes.
591     def grow_stack n
592       addiu "$sp", "$sp", -n
593     end
595     # Starts the false path of a conditional.
596     def ifelse
597       newlabel = @environment.gensym
598       emit "j #{newlabel}\n"
599       emit "nop\n"
600       label = @if_labels.pop
601       emit "#{label}:\n"
602       @if_labels.push newlabel
603     end
605     # Tests if x is equal to y
606     def ifeq x, y
607       common_if :ifeq, x, y
608     end
610     # Tests if x is greater than or equal to y
611     def ifge x, y
612       common_if :ifge, x, y
613     end
615     # Tests if x is strictly greater than y
616     def ifgt x, y
617       common_if :ifgt, x, y
618     end
620     # Tests if x is less than or equal to y
621     def ifle x, y
622       common_if :ifle, x, y
623     end
625     # Tests if x is strictly less than y
626     def iflt x, y
627       common_if :iflt, x, y
628     end
630     # Tests if x different from y
631     def ifne x, y
632       common_if :ifne, x, y
633     end
635     # Introduces a new local variable.
636     def let symbol, *expr
637       n = @environment.locals
638       register = local_register n
639       ref = local_reference n
640       if register
641         # We will use a register to store the value
642         @environment.add_local symbol, register
643         # Save current value of register
644         emit "sw #{register}, #{ref}\n"
645         @saved_registers << register
646         # Set new value
647         eval_expr expr, register
648       else
649         # We will use the stack to store the value
650         @environment.add_local symbol, local_offset(n)
651         eval_expr expr, @TEMPORARY
652         emit "sw #{@TEMPORARY}, #{ref}\n"
653       end
654     end
656     # Loads the value at the given address.
657     def load_at address, register = @TEMPORARY
658       load_value_into_register address, register
659       emit "lw #{register}, 0(#{register})\n"
660       register
661     end
663     # Loads a value into a register.
664     # Returns the name of the register.
665     # If the value was already in a register, the name of that
666     # register is returned.
667     # Else, the value is loaded into a register and the name of
668     # that register is returned. The register to use in that case
669     # may be specified using the optional second argument.
670     def load_value x, register = @TEMPORARY
671       if substitution? x
672         x = substitute_number x[1]
673       end
675       if x == 0
676         return "$0"
677       elsif integer? x
678         addiu register, "$0", x
679         return register
680       elsif symbol? x
681         binding = @environment[x]
682         if register? binding
683           # Value is already in a register. Return register name.
684           return binding
685         elsif binding.kind_of? Integer
686           # Load value from memory.
687           emit "lw #{register}, #{offset_reference binding}\n"
688           return register
689         else
690           # Assume global
691           if @relocated_symbols.include? x
692             emit "lw #{register}, %got(#{x})(#{@GOT})\n"
693           else
694             emit "lui #{register}, %hi(#{x})\n"
695             emit "addiu #{register}, %lo(#{x})\n"
696           end
697           return register
698         end
699       elsif at_expr? x
700         load_at x[1], register
701       else
702         raise "Don't know how to load #{x.inspect}"
703       end
704     end
706     # Loads a value into a specific register.
707     def load_value_into_register x, register
708       reg = load_value x, register
709       if reg != register
710         emit "move #{register}, #{reg}\n"
711       end
712     end
714     # Returns the offset from the frame base at which the nth local is stored.
715     # For register locals this is the offset at which the saved
716     # value (from the calling function) is stored.
717     def local_offset n
718       -(n + 4) * @WORDSIZE
719     end
721     # Returns an $sp-relative reference for the nth (0-based) local.
722     def local_reference n
723       offset_reference(local_offset(n))
724     end
726     # Returns the register in which the nth local (0-based) is stored, or
727     # nil if not stored in a register.
728     def local_register n
729       @LOCAL_REGISTERS[n]
730     end
732     # Computes the maximum number of locals that would fit in the current
733     # frame size.
734     def max_locals
735       # + 1, because the initial frame size has room for 1 local
736       (@frame_size - @INITIAL_FRAME_SIZE) / @WORDSIZE + 1
737     end
739     # Given an offset relative to the base of the frame, returns
740     # an reference to that memory location.
741     def offset_reference offset
742       "#{offset}($fp)"
743     end
745     # Returns true if the nth (0-based) local is stored in a register.
746     def register_local? n
747       n < @NREGISTER_LOCALS
748     end
750     # Returns from a function.
751     # 
752     # _words_ may contain an expression to be evaluated. The result
753     # of the evaluation is returned from the function.
754     def ret *words
755       # Compute return value and store it in @RETURN
756       eval_expr(words, @RETURN) unless words.empty?
757       # Go to epilogue
758       goto @function_end_label
759     end
761     # Saves the current frame at the given location.
762     def save_frame location
763       load_value_into_register location, @TEMPORARY
764       @SAVE_FRAME_REGISTERS.each_with_index do |register,i|
765         emit "sw #{register}, #{i * @WORDSIZE}(#{@TEMPORARY})\n"
766       end
767     end
769     # Sets a variable to the result of evaluating an expression.
770     def set symbol, *expr
771       if at_expr? symbol
772         eval_expr expr, @RETURN
773         load_value_into_register symbol.to_s[1..-1].to_sym, @TEMPORARY
774         emit "sw #{@RETURN}, 0(#{@TEMPORARY})\n"
775       else
776         x = @environment[symbol]
777         if x == nil
778           raise "Cannot change value of constant #{symbol}"
779         elsif register? x
780           eval_expr expr, x
781         else
782           # Should be an integer.
783           eval_expr expr, @TEMPORARY
784           emit "sw #{@TEMPORARY}, #{offset_reference x}\n"
785         end
786       end
787     end
789     # Sets the byte at _base_ + _offset_ to _value_.
790     def set_byte base, offset, value
791       # If base is an integer, but offset isn't, swap them
792       if !integer?(offset) && integer?(base)
793         base, offset = [offset, base]
794       end
796       value_reg = @TEMPORARIES.pop
797       load_value_into_register value, value_reg
798       begin
799         if integer? offset
800           base_reg = load_value base
801           emit "sb #{value_reg}, #{offset}(#{base_reg})\n"
802         else
803           eval_binop [:add, base, offset], @TEMPORARY
804           emit "sb #{value_reg}, 0(#{@TEMPORARY})\n"
805         end
806       ensure
807         @TEMPORARIES.push value_reg
808       end
809     end
811     # Sets the word at _base_ + _offset_ * +@WORDSIZE+ to _value_.
812     def set_word base, offset, value
813       value_reg = @TEMPORARIES.pop
814       load_value_into_register value, value_reg
815       begin
816         if integer? offset
817           base_reg = load_value base
818           emit "sw #{value_reg}, #{offset * @WORDSIZE}(#{base_reg})\n"
819         else
820           offset_reg = @TEMPORARIES.pop
821           begin
822             load_value_into_register offset, offset_reg
823             base_reg = load_value base
824             emit "sll #{offset_reg}, #{offset_reg}, 2\n"
825             emit "add #{@TEMPORARY}, #{base_reg}, #{offset_reg}\n"
826             emit "sw #{value_reg}, 0(#{@TEMPORARY})\n"
827           ensure
828             @TEMPORARIES.push offset_reg
829           end
830         end
831       ensure
832         @TEMPORARIES.push value_reg
833       end
834     end
836     # Defines a string with the given value.
837     def string value
838       code = ''
839       value.each_byte do |b|
840         if b == 92
841           code << "\\\\"
842         elsif b >= 32 && b < 127 && b != 34
843           code << b.chr
844         else
845           code << sprintf("\\%03o", b)
846         end
847       end
848       emit ".ascii \"#{code}\"\n"
849     end
851     # Calls a function, re-using the current call frame if possible.
852     def tail_call func, *args
853       # Compute number of stack arguments
854       nstackargs = number_of_stack_arguments args.length
855       # If we need more stack arguments than we have now,
856       # perform a normal call and return
857       if nstackargs > number_of_stack_arguments(@environment.args)
858         emit "# Not enough space for proper tail call; using regular call\n"
859         ret :call, func, *args
860       end
862       # Back up any stack arguments we will need after we overwrite them
863       temporaries = @TEMPORARIES.dup
864       nlocals = @environment.locals
865       (@NREGISTER_ARGS...args.length).each do |i|
866         x = @environment[args[i]]
867         if integer?(x) && x < arg_offset(i)
868           # args[i] is in a location that will have been overwritten by the
869           # time we get around to passing argument i to the called function.
870           # Make a backup of the value before we overwrite it.
871           if temporaries.empty?
872             # Oh dear, we're out of temporaries.
873             # Store the value in the current stack frame, extending it
874             # as necessary.
875             if nlocals >= max_locals
876               grow_stack 8
877             end
878             reg = load_value args[i]
879             emit "sw #{reg}, #{local_reference nlocals}\n"
880             args[i] = [:local, nlocals]
881             nlocals = nlocals + 1
882           else
883             # Load the argument into a temporary
884             reg = temporaries.shift
885             load_value_into_register args[i], reg
886             # Update args[i] so we know how to get to it later
887             args[i] = [:reg, reg]
888           end
889         end
890       end
892       # Set stack arguments
893       (@NREGISTER_ARGS...args.length).each do |i|
894         arg = args[i]
895         reg = @TEMPORARY
897         # Load value
898         if arg.kind_of? Array
899           # Special cases, created above
900           case arg[0]
901           when :reg
902             reg = arg[1]
903           when :local
904             emit "lw #{reg}, #{local_reference arg[1]}\n"
905           end
906         else
907           load_value_into_register arg, reg
908         end
910         # Store value in designated place
911         emit "sw #{reg}, #{arg_reference i}\n"
912       end
914       # Set register arguments
915       [@NREGISTER_ARGS,args.length].min.times do |i|
916         reg = arg_register i
917         load_value_into_register args[i], reg
918       end
920       # Load function address
921       if global? func
922         if @imports.has_key? func
923           # Load address from global offset table
924           emit "lw #{@FUNCTION}, %call16(#{func})(#{@GOT})\n"
925         else
926           # Assume label defined in this module
927           emit "lui #{@FUNCTION}, %hi(#{func})\n"
928           emit "addiu #{@FUNCTION}, %lo(#{func})\n"
929         end
930       else
931         # Load address
932         load_value_into_register func, "#{@FUNCTION}"
933       end
935       # Restore saved registers
936       [@NREGISTER_LOCALS, @environment.locals].min.times do |n|
937         emit "lw #{local_register n}, #{local_reference n}\n"
938       end
940       # Restore return address
941       emit "lw $31, #{@RA_OFFSET}($fp)\n"
943       # Restore stack pointer
944       emit "move $sp, $fp\n"
946       # Restore frame pointer
947       emit "lw $fp, #{@FP_OFFSET}($fp)\n"
949       # Perform call
950       emit "jr #{@FUNCTION}\n"
951       # brach delay slot
952       emit "nop\n"
953     end
955     # Defines a word with the given value
956     def word value
957       emit ".int #{value}\n"
958     end
960     # Write generated code to the given IO object.
961     def write io
962       io.puts ".set noat"
963       @sections.each do |section,code|
964         unless code.empty?
965           io.puts ".section #{section.to_s}"
966           io.puts code
967           io.puts
968         end
969       end
970     end
972   end
974   # Register class for big endian MIPS
975   Voodoo::CodeGenerator.register_generator MIPSGasGenerator,
976                                            :architecture => :mips,
977                                            :format => :gas
980   # Register class for little endian MIPS
981   Voodoo::CodeGenerator.register_generator MIPSGasGenerator,
982                                            :architecture => :mipsel,
983                                            :format => :gas