1 require 'voodoo/generators/common_code_generator'
5 # = MIPS GNU Assembler Code Generator
7 # The MIPS code generator generates assembly code for use with
10 # == Calling Convention
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.
17 # The return address for the called function is passed in $31.
19 # When performing a position-independent call, the address of the called
20 # function is passed in $25.
22 # The called function will store its return value in $2.
24 # The called function is required to preserve the values of registers
25 # $16 through $23 and register $30.
27 # This calling convention is compatible with the System V ELF ABI.
31 # Call frames have the following layout:
33 # When a function is called, it receives a stack frame that looks like
44 # empty0 <-- $sp points here
46 # The function prologue of functions generated by this code generator
47 # creates activation frames that look as follows:
57 # arg0 <-- $fp points here
59 # pointer to Global Offset Table
67 # padding <-- $sp points here
71 # The four empty slots provided by the caller are used to store
72 # arguments 0 through 3 (originally passed in $4 through $7),
75 # The stack frame created below the four slots provided by the caller
76 # contains the following data, in order:
78 # - Saved return address (originally passed in $31), if necessary.
80 # - Saved pointer to global offset table (computed from $25), if necessary.
82 # - Saved value of $fp, if necessary.
84 # - Saved values of caller's locals 0 through 7
85 # (originally in $16 through $23), if necessary.
87 # - Values of our locals > 8, if necessary.
89 # - Padding to align $sp on a multiple of 8, if necessary.
92 # In accordance with the System V ELF ABI for MIPS, the pointer to
93 # the global offset table is calculated as follows:
95 # $gp = _gp_disp + $25
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.
101 # Callee-Save Registers
103 # Registers $16 through $23 and $28 through $30 are callee-save.
105 # All other registers are caller-save.
107 class MIPSGasGenerator < CommonCodeGenerator
108 def initialize params
110 @WORDSIZE = 1 << @WORDSIZE_BITS
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
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
131 @SAVE_FRAME_REGISTERS = [:'$16', :'$17', :'$18', :'$19', :'$20',
132 :'$21', :'$22', :'$23', :'$28', :'$29',
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
142 @output_file_suffix = '.s'
143 @saved_registers = []
145 :'bits-per-word' => '32',
146 :'bytes-per-word' => '4'
149 @features[:'byte-order'] = 'big-endian'
151 @features[:'byte-order'] = 'little-endian'
153 raise ArgumentError.new("#{self.class} does not support " +
154 "architecture #{@architecture}")
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"
163 emit "lui #{target}, #{(immediate >> 16) & 0xffff}\n"
164 emit "ori #{target}, #{target}, #{immediate & 0xffff}\n"
166 addiu temporary, "$0", immediate
167 emit "addu #{target}, #{source}, #{temporary}\n"
171 # Return the offset from the frame base at which the nth argument is
177 # Returns an $fp-relative reference for the nth (0-based) argument.
179 offset_reference(arg_offset(n))
182 # Returns the register in which the nth (0-based) argument is stored, or
183 # nil if not stored in a register.
186 "$#{@REGISTER_ARG_BASE + n}"
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
198 temporary = @TEMPORARIES.pop
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"
206 @TEMPORARIES.push temporary
209 emit "move #{register}, $sp\n" unless register == "$sp"
212 def auto_words n, register
213 if n.kind_of? Integer
214 auto_bytes n * @WORDSIZE, register
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"
223 emit "sll #{register}, #{register}, #{@WORDSIZE_BITS}\n"
225 emit "sub $sp, $sp, #{register}\n"
226 emit "move #{register}, $sp\n" unless register == "$sp"
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)
236 environment = Environment.new @environment
237 @environment = environment
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"
246 environment = Environment.new @environment
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
254 # Defines a byte with the given value.
256 emit ".byte #{value}\n"
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
268 # Put arguments in the right places
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)
275 # Put other arguments on the stack
276 load_value_into_register args[n], @TEMPORARY
277 emit "sw #{@TEMPORARY}, #{n * @WORDSIZE}($sp)\n"
282 # Load function address
284 if @imports.has_key? func
285 # Load address from global offset table
286 emit "lw #{@FUNCTION}, %call16(#{func})(#{@GOT})\n"
288 # Assume label defined in this module
289 emit "lui #{@FUNCTION}, %hi(#{func})\n"
290 emit "addiu #{@FUNCTION}, %lo(#{func})\n"
294 load_value_into_register func, "#{@FUNCTION}"
298 emit "jalr #{@FUNCTION}\n"
302 # Restore original stack frame
303 grow_stack -increment
306 emit "lw #{@GOT}, #{@GP_OFFSET}($fp)\n"
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
328 emit "bne #{xreg}, #{yreg}, #{falselabel}\n"
330 emit "slt #{@TEMPORARY}, #{xreg}, #{yreg}\n"
331 emit "bne #{@TEMPORARY}, $0, #{falselabel}\n"
333 emit "slt #{@TEMPORARY}, #{yreg}, #{xreg}\n"
334 emit "beq #{@TEMPORARY}, $0, #{falselabel}\n"
336 emit "slt #{@TEMPORARY}, #{yreg}, #{xreg}\n"
337 emit "bne #{@TEMPORARY}, $0, #{falselabel}\n"
339 emit "slt #{@TEMPORARY}, #{xreg}, #{yreg}\n"
340 emit "beq #{@TEMPORARY}, $0, #{falselabel}\n"
342 emit "beq #{xreg}, #{yreg}, #{falselabel}\n"
344 raise "Unknown conditional: #{comp}"
349 # Creates an activation frame which can store nlocals local variables.
350 def create_frame nlocals
351 @frame_size = @INITIAL_FRAME_SIZE
353 @frame_size = @frame_size + (nlocals * @WORDSIZE + 7) / 8 * 8
355 grow_stack @frame_size
358 def emit_align alignment
359 emit ".align #{alignment}\n"
362 # Emits function prologue.
363 def emit_function_prologue formals = [], nlocals = 0
364 # Calculate new value for $gp
365 emit "lui #{@GOT}, %hi(_gp_disp)\n"
366 emit "addiu #{@GOT}, %lo(_gp_disp)\n"
367 emit "addu #{@GOT}, #{@GOT}, #{@FUNCTION}\n"
371 # Save return address
372 emit "sw $31, #{@frame_size - @WORDSIZE}($sp)\n"
375 emit "sw #{@GOT}, #{@frame_size - 2 * @WORDSIZE}($sp)\n"
378 emit "sw $fp, #{@frame_size - 3 * @WORDSIZE}($sp)\n"
380 # Point fp at where sp was before we created the frame
381 addiu "$fp", "$sp", @frame_size
383 # Save parameters 0 .. 3 in the stack space that the caller
384 # should have allocated for them.
385 [@NREGISTER_ARGS, formals.length].min.times do |n|
386 ref = offset_reference(@environment[formals[n]])
387 emit "sw $#{n + @REGISTER_ARG_BASE}, #{ref}\n"
391 # Loads a word into a register.
392 def emit_load_word register, base, offset
393 emit "lw #{register}, #{offset * @WORDSIZE}(#{base})\n"
396 # Stores the value of a register in memory.
397 def emit_store_word register, base, offset
398 emit "sw #{register}, #{offset * @WORDSIZE}(#{base})\n"
401 # Ends a function body.
403 if @environment == @top_level
404 raise "Cannot end function when not in a function"
407 label @function_end_label
408 # Restore saved locals
409 [@NREGISTER_LOCALS, @environment.locals].min.times do |n|
410 emit "lw #{local_register n}, #{local_reference n}\n"
412 # Load return address
413 emit "lw $31, #{@RA_OFFSET}($fp)\n"
414 # Restore stack pointer
415 emit "move $sp, $fp\n"
416 # Restore frame pointer
417 emit "lw $fp, #{@FP_OFFSET}($fp)\n"
422 @function_end_label = nil
423 @environment = @top_level
426 # Ends the current block.
428 # If we are returning to top level, restore stack pointer
429 if @environment.parent == @top_level
430 grow_stack -@frame_size
433 # Restore old value of @environment
434 @environment = @environment.parent
437 # Ends a conditional.
439 label = @if_labels.pop
443 # Evaluates the binary operation expr and store the result in register.
444 def eval_binop expr, register
445 temporaries = @TEMPORARIES.dup
446 x = load_value expr[1], temporaries[0]
448 y = load_value expr[2], temporaries[0]
453 emit "srav #{register}, #{x}, #{y}\n"
455 emit "srlv #{register}, #{x}, #{y}\n"
457 emit "div $0, #{x}, #{y}\n"
458 emit "mflo #{register}\n"
460 emit "div $0, #{x}, #{y}\n"
461 emit "mfhi #{register}\n"
463 emit "mult #{x}, #{y}\n"
464 emit "mflo #{register}\n"
466 emit "subu #{@TEMPORARY}, $0, #{y}\n"
467 emit "srlv #{@TEMPORARY}, #{x}, #{@TEMPORARY}\n"
468 emit "sllv #{register}, #{x}, #{y}\n"
469 emit "or #{register}, #{register}, #{@TEMPORARY}\n"
471 emit "subu #{@TEMPORARY}, $0, #{y}\n"
472 emit "sllv #{@TEMPORARY}, #{x}, #{@TEMPORARY}\n"
473 emit "srlv #{register}, #{x}, #{y}\n"
474 emit "or #{register}, #{register}, #{@TEMPORARY}\n"
476 emit "sllv #{register}, #{x}, #{y}\n"
478 emit "srlv #{register}, #{x}, #{y}\n"
480 emit "#{expr[0]} #{register}, #{x}, #{y}\n"
484 # Evaluates the expression expr and store the result in register.
485 def eval_expr expr, register
488 load_value_into_register expr[0], register
490 # Evaluate expression
494 auto_bytes expr[1], register
496 auto_words expr[1], register
499 emit "move #{register}, #{@RETURN}\n" if register != @RETURN
501 get_byte expr[1], expr[2], register
503 get_word expr[1], expr[2], register
505 eval_binop [:nor, 0, expr[1]], register
508 eval_binop expr, register
510 raise "Not a magic word: #{op}"
516 # Exports symbols from the current section.
518 symbols.each { |sym| emit ".globl #{sym}\n" }
521 # Loads byte from _base_ + _offset_ into _register_.
522 def get_byte base, offset, register
523 # If base is an integer, but offset isn't, swap them
524 if !integer?(offset) && integer?(base)
525 base, offset = [offset, base]
529 base_reg = load_value base
530 emit "lb #{register}, #{offset}(#{base_reg})\n"
532 eval_binop [:add, base, offset], @TEMPORARY
533 emit "lb #{register}, 0(#{@TEMPORARY})\n"
537 # Loads word from _base_ + _offset_ * _@WORDSIZE_ into _register_.
538 def get_word base, offset, register
540 base_reg = load_value base
541 emit "lw #{register}, #{offset * @WORDSIZE}(#{base_reg})\n"
543 offset_reg = @TEMPORARIES.pop
545 load_value_into_register offset, offset_reg
546 base_reg = load_value base
547 emit "sll #{offset_reg}, #{offset_reg}, 2\n" # multiply by @WORDSIZE
548 emit "add #{@TEMPORARY}, #{base_reg}, #{offset_reg}\n"
549 emit "lw #{register}, 0(#{@TEMPORARY})\n"
551 @TEMPORARIES.push offset_reg
556 # Jumps to an address.
559 emit "j #{address}\n"
561 register = load_value address, @TEMPORARY
562 emit "jr #{register}\n"
567 # Grows the stack by n bytes.
569 addiu "$sp", "$sp", -n
572 # Starts the false path of a conditional.
574 newlabel = @environment.gensym
575 emit "j #{newlabel}\n"
577 label = @if_labels.pop
579 @if_labels.push newlabel
582 # Tests if x is equal to y
584 common_if :ifeq, x, y
587 # Tests if x is greater than or equal to y
589 common_if :ifge, x, y
592 # Tests if x is strictly greater than y
594 common_if :ifgt, x, y
597 # Tests if x is less than or equal to y
599 common_if :ifle, x, y
602 # Tests if x is strictly less than y
604 common_if :iflt, x, y
607 # Tests if x different from y
609 common_if :ifne, x, y
612 # Imports labels into the current section.
614 # Record imported labels in @imports
615 symbols.each { |sym| @imports[sym] = sym }
623 # Introduces a new local variable.
624 def let symbol, *expr
625 n = @environment.locals
626 register = local_register n
627 ref = local_reference n
629 # We will use a register to store the value
630 @environment.add_local symbol, register
631 # Save current value of register
632 emit "sw #{register}, #{ref}\n"
634 eval_expr expr, register
636 # We will use the stack to store the value
637 @environment.add_local symbol, local_offset(n)
638 eval_expr expr, @TEMPORARY
639 emit "sw #{@TEMPORARY}, #{ref}\n"
643 # Loads the value at the given address.
644 def load_at address, register = @TEMPORARY
645 load_value_into_register address, register
646 emit "lw #{register}, 0(#{register})\n"
650 # Loads a value into a register.
651 # Returns the name of the register.
652 # If the value was already in a register, the name of that
653 # register is returned.
654 # Else, the value is loaded into a register and the name of
655 # that register is returned. The register to use in that case
656 # may be specified using the optional second argument.
657 def load_value x, register = @TEMPORARY
659 x = substitute_number x[1]
665 addiu register, "$0", x
668 binding = @environment[x]
670 # Value is already in a register. Return register name.
672 elsif binding.kind_of? Integer
673 # Load value from memory.
674 emit "lw #{register}, #{offset_reference binding}\n"
678 emit "lui #{register}, %hi(#{x})\n"
679 emit "addiu #{register}, %lo(#{x})\n"
683 load_at x[1], register
685 raise "Don't know how to load #{x.inspect}"
689 # Loads a value into a specific register.
690 def load_value_into_register x, register
691 reg = load_value x, register
693 emit "move #{register}, #{reg}\n"
697 # Returns the offset from the frame base at which the nth local is stored.
698 # For register locals this is the offset at which the saved
699 # value (from the calling function) is stored.
704 # Returns an $sp-relative reference for the nth (0-based) local.
705 def local_reference n
706 offset_reference(local_offset(n))
709 # Returns the register in which the nth local (0-based) is stored, or
710 # nil if not stored in a register.
715 # Computes the maximum number of locals that would fit in the current
718 # + 1, because the initial frame size has room for 1 local
719 (@frame_size - @INITIAL_FRAME_SIZE) / @WORDSIZE + 1
722 # Given an offset relative to the base of the frame, returns
723 # an reference to that memory location.
724 def offset_reference offset
728 # Returns true if the nth (0-based) local is stored in a register.
729 def register_local? n
730 n < @NREGISTER_LOCALS
733 # Returns from a function.
735 # _words_ may contain an expression to be evaluated. The result
736 # of the evaluation is returned from the function.
738 # Compute return value and store it in @RETURN
739 eval_expr(words, @RETURN) unless words.empty?
741 goto @function_end_label
744 # Saves the current frame at the given location.
745 def save_frame location
746 load_value_into_register location, @TEMPORARY
747 @SAVE_FRAME_REGISTERS.each_with_index do |register,i|
748 emit "sw #{register}, #{i * @WORDSIZE}(#{@TEMPORARY})\n"
752 # Sets a variable to the result of evaluating an expression.
753 def set symbol, *expr
755 eval_expr expr, @RETURN
756 load_value_into_register symbol.to_s[1..-1].to_sym, @TEMPORARY
757 emit "sw #{@RETURN}, 0(#{@TEMPORARY})\n"
759 x = @environment[symbol]
761 raise "Cannot change value of constant #{symbol}"
765 # Should be an integer.
766 eval_expr expr, @TEMPORARY
767 emit "sw #{@TEMPORARY}, #{offset_reference x}\n"
772 # Sets the byte at _base_ + _offset_ to _value_.
773 def set_byte base, offset, value
774 # If base is an integer, but offset isn't, swap them
775 if !integer?(offset) && integer?(base)
776 base, offset = [offset, base]
779 value_reg = @TEMPORARIES.pop
780 load_value_into_register value, value_reg
783 base_reg = load_value base
784 emit "sb #{value_reg}, #{offset}(#{base_reg})\n"
786 eval_binop [:add, base, offset], @TEMPORARY
787 emit "sb #{value_reg}, 0(#{@TEMPORARY})\n"
790 @TEMPORARIES.push value_reg
794 # Sets the word at _base_ + _offset_ * +@WORDSIZE+ to _value_.
795 def set_word base, offset, value
796 value_reg = @TEMPORARIES.pop
797 load_value_into_register value, value_reg
800 base_reg = load_value base
801 emit "sw #{value_reg}, #{offset * @WORDSIZE}(#{base_reg})\n"
803 offset_reg = @TEMPORARIES.pop
805 load_value_into_register offset, offset_reg
806 base_reg = load_value base
807 emit "sll #{offset_reg}, #{offset_reg}, 2\n"
808 emit "add #{@TEMPORARY}, #{base_reg}, #{offset_reg}\n"
809 emit "sw #{value_reg}, 0(#{@TEMPORARY})\n"
811 @TEMPORARIES.push offset_reg
815 @TEMPORARIES.push value_reg
819 # Defines a string with the given value.
822 value.each_byte do |b|
825 elsif b >= 32 && b < 127 && b != 34
828 code << sprintf("\\%03o", b)
831 emit ".ascii \"#{code}\"\n"
834 # Calls a function, re-using the current call frame if possible.
835 def tail_call func, *args
836 # Compute number of stack arguments
837 nstackargs = number_of_stack_arguments args.length
838 # If we need more stack arguments than we have now,
839 # perform a normal call and return
840 if nstackargs > number_of_stack_arguments(@environment.args)
841 emit "# Not enough space for proper tail call; using regular call\n"
842 ret :call, func, *args
845 # Back up any stack arguments we will need after we overwrite them
846 temporaries = @TEMPORARIES.dup
847 nlocals = @environment.locals
848 (@NREGISTER_ARGS...args.length).each do |i|
849 x = @environment[args[i]]
850 if integer?(x) && x < arg_offset(i)
851 # args[i] is in a location that will have been overwritten by the
852 # time we get around to passing argument i to the called function.
853 # Make a backup of the value before we overwrite it.
854 if temporaries.empty?
855 # Oh dear, we're out of temporaries.
856 # Store the value in the current stack frame, extending it
858 if nlocals >= max_locals
861 reg = load_value args[i]
862 emit "sw #{reg}, #{local_reference nlocals}\n"
863 args[i] = [:local, nlocals]
864 nlocals = nlocals + 1
866 # Load the argument into a temporary
867 reg = temporaries.shift
868 load_value_into_register args[i], reg
869 # Update args[i] so we know how to get to it later
870 args[i] = [:reg, reg]
875 # Set stack arguments
876 (@NREGISTER_ARGS...args.length).each do |i|
881 if arg.kind_of? Array
882 # Special cases, created above
887 emit "lw #{reg}, #{local_reference arg[1]}\n"
890 load_value_into_register arg, reg
893 # Store value in designated place
894 emit "sw #{reg}, #{arg_reference i}\n"
897 # Set register arguments
898 [@NREGISTER_ARGS,args.length].min.times do |i|
900 load_value_into_register args[i], reg
903 # Load function address
905 if @imports.has_key? func
906 # Load address from global offset table
907 emit "lw #{@FUNCTION}, %call16(#{func})(#{@GOT})\n"
909 # Assume label defined in this module
910 emit "lui #{@FUNCTION}, %hi(#{func})\n"
911 emit "addiu #{@FUNCTION}, %lo(#{func})\n"
915 load_value_into_register func, "#{@FUNCTION}"
918 # Restore saved registers
919 [@NREGISTER_LOCALS, @environment.locals].min.times do |n|
920 emit "lw #{local_register n}, #{local_reference n}\n"
923 # Restore return address
924 emit "lw $31, #{@RA_OFFSET}($fp)\n"
926 # Restore stack pointer
927 emit "move $sp, $fp\n"
929 # Restore frame pointer
930 emit "lw $fp, #{@FP_OFFSET}($fp)\n"
933 emit "jr #{@FUNCTION}\n"
938 # Defines a word with the given value
940 emit ".int #{value}\n"
943 # Write generated code to the given IO object.
946 @sections.each do |section,code|
948 io.puts ".section #{section.to_s}"
957 # Register class for big endian MIPS
958 Voodoo::CodeGenerator.register_generator MIPSGasGenerator,
959 :architecture => :mips,
963 # Register class for little endian MIPS
964 Voodoo::CodeGenerator.register_generator MIPSGasGenerator,
965 :architecture => :mipsel,