Wednesday, January 31, 2007

 

inline assembly for MIPS

Here's a piece of code to prefetch data. It's useful if the compiler is use mips2, so the gcc __builtin_prefetch() may not work.

/* Prefetch Header */
#define PREF_LOAD 0 /* intended for read */
#define PREF_STORE 1 /* intended for write */

#define _PREFETCH(v,t,o) \
__asm__ __volatile__ \
( \
".set push\n" \
".set mips4\n" \
"pref %1, %2(%0)\n" \
".set mips2\n" \
".set pop\n" \
:: "r"(v), "i"(t),"i"(o) \
)

.set is a directive to the compiler and not actually assembly. It'll be translated into multiple assembly instructions, but not to be confused with synthesis instructions like li.

.set push and pop will save the required registers on the stack.
.set mips4 and mip2 set the mode of operation on the processor.
pref is the assembly instruction to prefech data. This is a mips4 instruction, which is why it's preceed by .set mips4.

"r" is a constraint says to keep the value of v in a general purpose register.
"i" says the value is a constant of the type integer

%0, %1, and %2 refers to v, t, and o respectively. The value used to reference a variable is dictated by the order the varables appear after "::".


Example: Writing a 64bit value when the compiler is using 32bits.

void write64(uint32_t addr, uint64_t val)
{
uint32_t high = val >> 32; /* we don't assume endianness */
uint32_t low = val & 0xffffffff;

__asm__ __volatile__
(
".set push\n"
".set noreorder\n"
".set noat\n"
".set mips3\n"
"dsll32 $16, %1, 0 \n"
"dsll32 $17, $0, 0 \n"
"dsrl32 $16, $16, 0 \n"
"or $17, $17, $16 \n"
"sd $17, (%2) \n"
".set mips2\n"
".set reorder\n"
".set pop\n"
:: "r" (high), "r" (low), "r" (addr)
: "$16", "$17"
}

$16 and $17 are general purpose registers. The line begining with ":" says that $16 and $17 need to be saved and restored as part of ".set push" and ".set pop".

To save time, replace $16 and $17 with $8 and$9. These are temporary registers that don't need to be protected after a subroutine call, so you can remove the line with ":" to save 4 instructions.

Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?