Arm
Arm
Arm
ARM
DEFINITION
The ARM architecture (previously, the Advanced RISC Machine, and prior to that Acorn RISC Machine) is a 32-bit RISC processor architecture that is widely used in a number of embedded designs. Due to their power saving features, ARM CPUs are dominant in the mobile electronics market, where low power consumption is a critical design goal.
ARM Evolution
Evolved from the BBCs Microcomputer Developed by Acorn Computers Ltd of Cambridge, England between 1983 and 1985. First RISC processor available for commercial use. Lot of initial ideas borrowed from Berkeley RISC I and II and Stanford MIPS processors. Initially known as Acorn RISC Machine ARM Limited formed in 1990 after which the name got changed to Advanced RISC Machine
Computer Architecture
Instruction Set, Visible Registers, Memory Management Table Structure, Exception Handling Models etc
Computer Organization
What is a Processor?
Finite State Automation Executes Instructions held in Memory State depends on values hold by registers & memory
Instructions Types
Pipelines
Fetch Decode Register Access ALU Memory, if necessary Write Back Pipeline Hazards
RISC Organization
Hard Wired Instruction Decode Logic Efficiently Pipelined Single Cycle Execution
RISC Advantages
A Smaller Die Size A Shorter Development Time Higher Performance (Bit Tricky)
RISC Disadvantages
Agenda
Architectural Inheritance The ARM Programmers Model The ARM Development Tools Examples and Exercises
ARM History
ARM
ARM
ARM Limited, 1990 ARM has been licensed to many semiconductor manufacturers
A Load/Store Architecture Fixed Length 32-bit Instructions 323- Address Instruction Formats
Register Windows Large no of registers out of which 32 Regs are Visible at a time. Procedure Entry & Exit move visible window to each procedure as new regs And thereby reduce Traffic between Processor & Memory. Reason for Rejecting this feature:
Delayed Branches
Branches cause problem in Pipelines Most RISC Processor overcome this problem using delayed branches where the branch takes effect after the followin instrn is excuted
Not implemented in ARM to avoid the complexity involved during exception and interrupt handling. Not suitable for superscalar architectures
Single Memory for Instruction & Data Even a simple load/store will require at least two cycles Separate Data & Instruction was the solution but was too costly those times
1515-general purpose 32-bit registers(r0-r14) & 32- registers(r0the Program Counter (r15) & the CPSR need to be considered
The remaining registers are only for system level programming & for handling exceptions
The Registers
ARM has 37 registers in total, all of which are 32-bits long. 32 1 dedicated program counter 1 dedicated current program status register 5 dedicated saved program status registers 30 general purpose registers However these are arranged into several banks, with the accessible bank being governed by the processor mode. Each mode can access a particular set of r0-r12 registers r0 a particular r13 (the stack pointer) and r14 (link register) r15 (the program counter) cpsr (the current program status register) and privileged modes can also access a particular spsr (saved program status register)
Register Banks
Registers are divided into sets Each operating mode can access a unique set of registers containing
R0 to R12 : general purpose registers R13 : stack pointer R14 : link register R15 : Program counter
CPSR : Current Program Status Register SPSR : Saved Program Status Register (only privileged modes)
R13= stack pointer(sp) and stores the head of the stack in the current processor mode. R14= link register(lr) and is where the core puts the return address whenever it calls the subroutine R15= program counter(pc) and contains the address of the next instruction to be fetched by the processor
CPSR
In user level programs uses CPSR to store the condition code bits as a result of comparision & Arithmatic and logic opns
N, C, Z, V
I, F, T, mode[4:0]
N Z CV
I F T
Mode
Copies of the ALU status flags (latched if the instruction has the "S" bit set).
Condition Code Flags N = Negative result from ALU flag. Z = Zero result from ALU flag. C = ALU operation Carried out V = ALU operation oVerflowed Mode Bits M[4:0] define the processor mode.
Interrupt Disable bits. I = 1, disables the IRQ. F = 1, disables the FIQ. T Bit (Architecture v4T only) T = 0, Processor in ARM state T = 1, Processor in Thumb state
Non-Privileged User Normal user code Mode FIQ Processing fast interrupts IRQ Processing standard interrupts SVC Processing software interrupts (SWIs) Abort Processing memory faults Undef Handling undefined instruction traps
User mode OK
Memory may be viewed as linear array of bytes number from 0 to 2^32 1 Data Bytes may be 8-bit (B), 16-bit (HW), 816or 32-bit (W) 32Words are always aligned at 4-byte 4boundaries i.e least two bits are zero Half Words are aligned on even boundaries
bit 0
20 16 12 8 4 0
word16
byte address
LoadLoad-Store Architecture
LoadLoad-Store Architecture 3-Address Data Processing Instructions Conditional Execution of Instructions Powerful Load/Store Multiple Register General Shift Operation (Single Cycle) Extension of Instruction Set Co-processor Co1616-bit Compressed Instruction Set
I/O System
Memory Mapped with Interrupt Support Internal Registers in devices will act as addressable locations in ARM s Memory Map Peripheral may use IRQ or FIQ May have DMA Support
ARM Exceptions
ARM supports range of Interrupts, Traps, Supervisor Calls, all grouped under general heading of Exceptions
Software Development
ARM Ltd GNU Tools tools run on different architecture from one for which they produce code
CrossCross-development
C compiler .aof
as sembler
object libraries
system model
ARMsd
ARMulator
development board
Agenda
Data Processing Instructions Data Transfer Instructions Control Flow Instructions Writing Simple Assembly Language Programs Examples and Exercises
These are the only Instruction that modify the data values in ARM Typically require two operands & produce single results (though there are exceptions)
All operands are 32-bits wide & come from 32registers or are specified as literals in the instruction itself The result, if there is any, is 32-bits wide and is 32placed in a register (Exception: Long Multiplications) Each of the operand registers & the results are independently specified in the instruction (ARM 3-Address Instruction format)
Arithmetic Operations
ADD r0, r1, r2 ADC r0, r1, r2 SUB r0, r1, r2 SBC r0, r1, r2 RSB r0, r1, r2 RSC r0, r1, r2 r0 := r1 + r2 r0 := r1 + r2 + C r0 := r1 - r2 r0 := r1 - r2 + C - 1 r0 := r2 r1 r0 := r2 r1 + C - 1
AND r0, r1, r2 ORR r0, r1, r2 EOR r0, r1, r2 BIC r0, r1, r2
r0 := r2 r0 := not r2
Comparison Operations
Immediate Operands
Second register operand is subjected to shift before it is combined with first operand ADD r3, r2, r1, LSL #3 ; r3 := r2 + (r1*8)
LSLLSL- Logical Shift Left LSRLSR- Logical Shift Right ASLASL- Arithmetic Shift Left ASRASR- Arithmetic Shift Right RORROR- Rotate Right RRXRRX- Rotate Right Extended
LSL #5
31 0 0 31 1
LSR #5
0
00000 0
1 1111 1
ROR #5
RRX
It is also possible to use a register value to specify the number of bits the second operand should be shifted by: ADD r5, r5, r3, LSL r2 r5: r5 + r3 * 2^r2
All DPI can affect the condition codes For all DPI except comparisons a special request needs to be made At assembly level the request is made by adding an S to opcode Eg: ADDS r0, r0, r1 ADC r3, r3, r2
Multiplies
Immediate second operand not supported The result register must not be the same as the first source register If the S bit is set the V flag is preserved & the C flag is rendered meaningless
transfer of a data item (byte, half-word, word) halfbetween ARM registers and memory enable transfer of large quantities of data used for procedure entry and exit, to save/restore workspace registers, to copy blocks of data around memory allow exchange between a register and memory in one instruction used to implement semaphores to ensure mutual exclusion on accesses to shared data in multis
RegisterRegister-Indirect Addressing
LDR r0, [r1] STR r0, [r1] r0 := mem32[r1] mem32[r1] := r0
r0 := mem32[r1+4]
r0 := mem32[r1] r1 := r1 + 4
r0 := mem32[r1 + 4] r1 := r1 + 4
Exercise
Pointer to Table1 Pointer to Table2 Load [Table1] Store [Table2] Add 4 to Table1 Add 4 to Table2
Answer
COPY: ADR r1, TABLE1 ADR r2, TABLE2 LOOP: LDR r0, [r1] STR r0, [r2] ADD r1, r1, #4 ADD r2, r2, #4 ... TABLE1: ... TABLE2:... ; r1 points to TABLE1 ; r2 points to TABLE2
Better Answer
COPY: ADR r1, TABLE1 ADR r2, TABLE2 LOOP: LDR r0, [r1], #4 STR r0, [r2], #4 ... TABLE1: ... TABLE2:... ; r1 points to TABLE1 ; r2 points to TABLE2
When large quantity of data needs to be transferred But there is a trade off, i.e less addressing modes
LDMIA r1, {r0, r2, r5} r0:=mem32[r1] r2 := mem32[r1 + 4] r5 := mem32[r1 + 8] Base Address should be Word Aligned Order of Registers do not matter Normal practice to specify in increasing order Including r15 is also possible
Exercise
Write a code to add two numbers a & b which are at memory locations 0x80000x80002000 & 0x8000-2001? Check the question 0x8000if some thing is wrong, correct the problem & then write the code!!
Exercise
X= X= X= X= X= X=
ARM
Advanced RISC Machines
LoadLoad-Store Architecture 3-Address Data Processing Instructions Conditional Execution of Instructions Powerful Load/Store Multiple Register General Shift Operation (Single Cycle) Extension of Instruction Set CoCoprocessor 1616-bit Compressed Instruction Set
Processor Modes
User (unprivileged mode under which most tasks run) (10000) FIQ (entered when a high priority (fast) interrupt is raised) (10001) IRQ (entered when a low priority (normal) interrupt is raised) (10010) Supervisor (entered on reset and when a Software Interrupt instruction is executed) (10011) Abort (used to handle memory access violations) (10111) Undef (used to handle undefined instructions) (11011) System (privileged mode using the same registers as user mode) (11111)
The Registers
1 dedicated program counter 1 dedicated current program status register 5 dedicated saved program status registers 30 general purpose registers
However these are arranged into several banks, with the accessible bank being governed by the processor mode. Each mode can access
a particular set of r0-r12 registers r0a particular r13 (the stack pointer) and r14 (link register) r15 (the program counter) cpsr (the current program status register) a particular spsr (saved program status register)
Register Organisation
General registers and Program Counter
User32 / System r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 (sp) r14 (lr) r15 (pc) FIQ32 r0 r1 r2 r3 r4 r5 r6 r7 r8_fiq r9_fiq r10_fiq r11_fiq r12_fiq r13_fiq r14_fiq r15 (pc) Supervisor32 r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13_svc r14_svc r15 (pc) Abort32 r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13_abt r14_abt r15 (pc) IRQ32 r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13_irq r14_irq r15 (pc) Undefined32 r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13_undef r14_undef r15 (pc)
instructions can access r0-r14 directly. r0 Most instructions also allow use of the PC.
N Z CV
I F T
Mode
Copies of the ALU status flags (latched if the instruction has the "S" bit set).
Condition Code Flags N = Negative result from ALU flag. Z = Zero result from ALU flag. C = ALU operation Carried out V = ALU operation oVerflowed Mode Bits M[4:0] define the processor mode.
Interrupt Disable bits. I = 1, disables the IRQ. F = 1, disables the FIQ. T Bit (Architecture v4T only) T = 0, Processor in ARM state T = 1, Processor in Thumb state
Condition Flags
Logical Instruction Flag Negative been set (N=1) number in Zero zero (Z=1) Carry bits (C=1) oVerflow bits (V=1) corruption of No meaning Bit 31 of the result has Indicates a negative signed operations Result is all zeroes Result of operation was Arithmetic Instruction
Result was greater than 31 Indicates a possible the sign bit in signed numbers
All instructions are 32 bits in length All instructions must be word aligned Therefore the PC value is stored in bits [31:2] with bits [1:0] equal to zero (as instruction cannot be halfword or byte aligned).
R14 is used as the subroutine link register (LR) and stores the return address when Branch with Link operations are performed, calculated from the PC. Thus to return from a linked branch
or
User Mode
r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 (sp) r14 (lr) r15 (pc) cpsr r8_fiq r9_fiq r10_fiq r11_fiq r12_fiq r13_fiq r14_fiq
FIQ Mode
r0 r1 r2 r3 r4 r5 r6 r7 r8_fiq r9_fiq r10_fiq r11_fiq r12_fiq r13_fiq r14_fiq r15 (pc)
EXCEPTION
Return address calculated from User mode PC value and stored in FIQ mode LR
spsr_fiq
cpsr spsr_fiq
Disable FIQ
Exceptions
Reset: Occurs when the processor reset pin is asserted. (Signalling power-up) Undefined Instruction: Occurs if the processor, does not recognize the currently executing instruction. Software Interrupt (SWI): This is a user-defined intentional synchronous interrupt instruction. Prefetch Abort: Occurs when the processor attempts to execute an instruction that was not fetched, because the address was illegal. Data Abort: Occurs when a data transfer instruction attempts to load or store data at an illegal address. IRQ: Occurs when the processor external Interrupt ReQuest pin is asserted FIQ: Occurs when the processor external Fast Interrupt reQuest pin is asserted
Exception Entry
Changes Operating Mode Save Address of next Instruction in r14 of the new mode Saves Old value of CPSR into SPSR of new mode Disables either IRQ or FIQ if the exception is IRQ or FIQ respectively Forces PC to vector to new address
Exception Return
Any modified user registers should be restored from the Stack The CPSR should be restored from appropriate SPSR The PC must be changed to relevant User Instruction Stream
Problem: Last two cannot be carried out independently.two technics are used to carry out these steps simultaneously
Solution 1
Note how the return instruction incorporates an adjustment to the return address where necessary: IRQ and FIQ must return one instruction early in order to execute the instruction that was 'usurped' for the exception entry. Prefetch abort must return one instruction early to execute the instruction that had caused a memory fault when first requested. Data abort must return two instructions early to retry the data transfer instruction, which was the instruction before the one usurped for exception entry
SOLUTION2
If the handler has copied the return address out onto a stack (in order, for example, to allow re-entrant rebehaviour, though note that in this case the SPSR must be saved as well as the PC) the restoration of the user registers and the return may be implemented with a single multiple register transfer instruction such as: LDMFD r13!, {r0-r3,pc}" ; restore and return {r0The CPSR is restored at the same time that the PC is loaded from memory, which will always be the last item transferred from memory since the registers are loaded in increasing order.
EXCEPTION PRIORITIES
Reset Data Abort FIQ IRQ Prefetch Abort SWI, Undefined Instruction
When an exception occurs, the core: Copies CPSR into SPSR_<mode> Sets appropriate CPSR bits
Reset Undefined Instruction Software Interrupt Prefetch Abort Data Abort Reserved IRQ FIQ
Maps in appropriate banked registers Stores the return address in LR_<mode> Sets PC to vector address To return, exception handler needs to:
Quiz - Verbal
What register is used to store the program counter ? What is r13 often used to store? Which mode, or modes has the fewest available number of registers available? How many and why? Name the exceptions in the ARM? Mention their priorities. What happens on Exception Entry & Exception Exit?
Instruction type
Data processing / PSR Transfer Multiply
Cond Cond Cond Cond Cond Cond Cond Cond Cond Cond Cond Cond Cond Cond
0 0 I Opcode
Rn Rd RdHi Rn Rn Rn Rn Rn
Rd Rn RdLo Rd Rd Rs Rs
Operand2 1 0 0 1 1 0 0 1 Rm Rm Rm
0 0 0 0 0 0 A S 0 0 0 0 1 U A S 0 0 0 1 0 B 0 0 0 1 I P U B W L 1 0 0 P U S W L 0 0 0 P U 1 W L 0 0 0 P U 0 W L
(v3M / v4 only)
Load/Store Byte/Word
Load/Store Multiple Halfword transfer : Immediate offset Halfword transfer: Register offset (v4 only) Branch
Rd Rd
Offset1 1 S H 1 Offset2 0 0 0 0 1 S H 1 Rm
1 0 1 L 0 0 0 1
Offset 0 0 1 0 1 1 1 1 1 1 1 1 Rn CRn L CRn CRd CRd Rd 1 1 1 1 0 0 0 1 CPNum CPNum CPNum Op2 Op2 Offset 0 1 CRm CRm Rn
Branch Exchange
(v4T only)
1 1 0 P U N W L 1 1 1 0 1 1 1 0 1 1 1 1 Op1 Op1
SWI Number
Software interrupt
Conditional Execution
Most instruction sets only allow branches to be executed conditionally. However by reusing the condition evaluation hardware, ARM effectively increases number of instructions.
All instructions contain a condition field which determines whether the CPU will execute them. NonNon-executed instructions soak up 1 cycle.
Still have to complete cycle so as to allow fetching and decoding of following instructions.
This removes the need for many branches, which stall the pipeline (3 cycles to refill).
Cond
0000 = EQ - Z set (equal) 0001 = NE - Z clear (not equal) 0010 = HS / CS - C set (unsigned higher or same) 0011 = LO / CC - C clear (unsigned lower) 0100 = MI -N set (negative) 0101 = PL - N clear (positive or zero) 0110 = VS - V set (overflow) 0111 = VC - V clear (no overflow) 1000 = HI - C set and Z clear (unsigned higher)
1001 = LS - C clear or Z (set unsigned lower or same) 1010 = GE - N set and V set, or N clear and V clear (>or =) 1011 = LT - N set and V clear, or N clear and V set (>) 1100 = GT - Z clear, and either N set and V set, or N clear and V set (>) 1101 = LE - Z set, or N set and V clear,or N clear and V set (<, or =) 1110 = AL - always 1111 = NV - reserved.
To execute an instruction conditionally, simply postfix it with the appropriate condition: For example an add instruction takes the form: ADD r0,r1,r2 ; r0 = r1 + r2 (ADDAL) To execute this only if the zero flag is set: ADDEQ r0,r1,r2 ; If zero flag set then ; ... r0 = r1 + r2 By default, data processing operations do not affect the condition flags (apart from the comparisons where this is the only effect). To cause the condition flags to be updated, the S bit of the instruction needs to be set by postfixing the instruction (and any condition code) with an S . For example to add two numbers and set the condition flags: ADDS r0,r1,r2 ; r0 = r1 + r2 ; ... and set flags
Cond
1 0 1 L
Offset
Link bit
Condition field
The offset for branch instructions is calculated by the assembler: By taking the difference between the branch instruction and the target address minus 8 (to allow for the pipeline). This gives a 26 bit offset which is right shifted 2 bits (as the bottom two bits are always zero as instructions are word aligned) and stored into the instruction encoding. This gives a range of 32 Mbytes.
When executing the instruction, the processor: shifts the offset left two bits, sign extends it to 32 bits, and adds it to PC. Execution then continues from the new PC, once the pipeline has been refilled. The "Branch with link" instruction implements a subroutine call by writing PCPC-4 into the LR of the current bank. i.e. the address of the next instruction following the branch with link (allowing for the pipeline). To return from subroutine, simply need to restore the PC from the LR: MOV pc, lr Again, pipeline has to refill before execution continues. The "Branch" instruction does not affect LR. Note: Architecture 4T offers a further ARM branch instruction, BX See Thumb Instruction Set Module for details.
Largest family of ARM instructions, all sharing the same instruction format. Contains: Arithmetic operations Comparisons (no results - just set condition codes) Logical operations Data movement between registers Remember, this is a load / store architecture These instruction only work on registers, NOT memory. They each perform a specific operation on one or two operands. First operand always a register - Rn Second operand sent to the ALU via barrel shifter. We will examine the barrel shifter shortly.
Arithmetic Operations
Operations are:
Syntax:
Examples
ADD r0, r1, r2 SUBGT r3, r3, #1 RSBLES r4, r5, #5
Comparisons
The only effect of the comparisons is to UPDATE THE CONDITION FLAGS. Thus no need to set S bit. FLAGS. Operations are: CMP operand1 - operand2, but result not written CMN operand1 + operand2, but result not written TST operand1 AND operand2, but result not written TEQ operand1 EOR operand2, but result not written Syntax: <Operation>{<cond>} Rn, Operand2 Examples: CMP r0, r1 TSTEQ r2, #5
Logical Operations
Operations are:
AND operand2 EOR operand2 OR operand2 AND NOT operand2 [ie bit clear]
Syntax:
Examples:
Data Movement
Operations are:
MOV MVN
<Operation>{<cond>}{S} Rd, Operand2 MOV r0, r1 MOVS r2, #10 MVNEQ r1,#0
Examples:
The ARM doesn t have actual shift instructions. Instead it has a barrel shifter which provides a mechanism to carry out shifts as part of other instructions. So what operations does the barrel shifter support?
CF
Destination
Destination
CF
Destination
Sign bit shifted in
CF
Rotate Right
Destination
CF
Destination
CF
Register, optionally with shift operation applied. Shift value can be either be: 5 bit unsigned integer Specified in bottom byte of another register.
ALU
* Immediate value 8 bit number Can be rotated right through an even number of positions. Assembler will calculate rotate for you from constant.
Result
Then takes extra cycle to execute ARM doesn t have enough read ports to read 3 registers at once. Then same as on other processors where shift is separate instruction. If no shift is specified then a default shift is applied: LSL #0 i.e. barrel shifter has no effect on value in register.
Using a multiplication instruction to multiply by a constant means first loading the constant into a register and then waiting a number of internal cycles for the instruction to complete. A more optimum solution can often be found by using some combination of MOVs, ADDs, SUBs and RSBs with shifts. Multiplications by a constant equal to a ((power of 2) 1) can be done in one cycle. Example: r0 = r1 * 5 Example: r0 = r1 + (r1 * 4) ADD ADD r0, r1, r1, LSL #2 Example: r2 = r3 * 105 Example: r2 = r3 * 15 * 7 Example: r2 = r3 * (16 - 1) * (8 - 1) RSB RSB r2, r3, r3, LSL #4 ; r2 = r3 * 15 RSB RSB r2, r2, r2, LSL #3 ; r2 = r2 * 7
There is no single instruction which will load a 32 bit immediate constant into a register without performing a data load from memory. All ARM instructions are 32 bits long ARM instructions do not use the instruction stream as data. The data processing instruction format has 12 bits available for operand2 If used directly this would only give a range of 4096. Instead it is used to store 8 bit constants, giving a range of 0 - 255. These 8 bits can then be rotated right through an even number of positions (ie RORs by 0, 2, 4,..30). This gives a much larger range of constants that can be directly loaded, though some constants will still need to be loaded from memory.
This gives us: 0 - 255 [0 - 0xff] 256,260,264,..,1020 [0x100-0x3fc, step 4, 0x40-0xff ror 30] [0x1000x40 1024,1040,1056,..,4080 [0x400-0xff0, step 16, 0x40-0xff ror 28] [0x4000x40 4096,4160, 4224,..,16320 [0x1000-0x3fc0, step 64, 0x40-0xff ror [0x10000x4026] These can be loaded using, for example: MOV r0, #0x40, 26 ; => MOV r0, #0x1000 (ie 4096) To make this easier, the assembler will convert to this form for us if simply given the required constant: MOV r0, #4096 ; => MOV r0, #0x1000 (ie 0x40 ror 26) The bitwise complements can also be formed using MVN: MOV r0, #0xFFFFFFFF ; assembles to MVN r0, #0 If the required constant cannot be generated, an error will be reported.
Although the MOV/MVN mechansim will load a large range of constants into a register, sometimes this mechansim will not generate the required constant. Therefore, the assembler also provides a method which will load ANY 32 bit constant: LDR rd,=numeric constant If the constant can be constructed using either a MOV or MVN then this will be the instruction actually generated. Otherwise, the assembler will produce an LDR instruction with a PCPCrelative address to read the constant from a literal pool. LDR r0,=0x42 ; generates MOV r0,#0x42 LDR r0,=0x55555555 ; generate LDR r0,[pc, offset to lit pool] As this mechanism will always generate the best instruction for a given case, it is the recommended way of loading constants.
Multiplication Instructions
The Basic ARM provides two multiplication instructions. Multiply MUL{<cond>}{S} Rd, Rm, Rs ; Rd = Rm * Rs Multiply Accumulate - does addition for free MLA{<cond>}{S} Rd, Rm, Rs,Rn ; Rd = (Rm * Rs) + Rn Restrictions on use: Rd and Rm cannot be the same register Can be avoid by swapping Rm and Rs around. This works because multiplication is commutative. Cannot use PC. These will be picked up by the assembler if overlooked. Operands can be considered signed or unsigned Up to user to interpret correctly.
Instructions are MULL which gives RdHi,RdLo:=Rm*Rs MLAL which gives RdHi,RdLo:=(Rm*Rs)+RdHi,RdLo However the full 64 bit of the result now matter (lower precision multiply instructions simply throws top 32bits away) Need to specify whether operands are signed or unsigned Therefore syntax of new instructions are: UMULL{<cond>}{S} RdLo,RdHi,Rm,Rs UMLAL{<cond>}{S} RdLo,RdHi,Rm,Rs SMULL{<cond>}{S} RdLo, RdHi, Rm, Rs SMLAL{<cond>}{S} RdLo, RdHi, Rm, Rs Not generated by the compiler. Warning : Unpredictable on non-M ARMs. non-
Example
1. Specify instructions which will implement the following: a) r0 = 16 b) r1 = r0 * 4 c) r0 = r1 / 16 ( r1 signed 2's comp.) d) r1 = r2 * 7 2. What will the following instructions do? a) ADDS r0, r1, r1, LSL #2 b) RSB r2, r1, #0
3. What does the following instruction sequence do? ADD r0, r1, r1, LSL #1 SUB r0, r0, r1, LSL #4 ADD r0, r0, r1, LSL #7
The ARM is a Load / Store Architecture: Does not support memory to memory data processing operations. Must move data values into registers before using them. This might sound inefficient, but in practice isn t: Load data values from memory into registers. Process data in registers using a number of data processing instructions which are not slowed down by memory access. Store results from registers out to memory. The ARM has three sets of instructions which interact with main memory. These are: Single register data transfer (LDR / STR). Block data transfer (LDM/STM). Single Data Swap (SWP).
The basic load and store instructions are: Load and Store Word or Byte LDR / STR / LDRB / STRB ARM Architecture Version 4 also adds support for halfwords and signed data. Load and Store Halfword LDRH / STRH Load Signed Byte or Halfword - load value and sign extend it to 32 bits. LDRSB / LDRSH All of these instructions can be conditionally executed by inserting the appropriate condition code after STR / LDR. e.g. LDREQB Syntax: <LDR|STR>{<cond>}{<size>} Rd, <address>
The memory location to be accessed is held in a base register STR r0, [r1] ; Store contents of r0 to location pointed to ; by contents of r1. LDR r2, [r1] ; Load r2 with contents of memory location ; pointed to by contents of r1.
r0 Source Register for STR 0x5 Memory
r2 0x5 0x5
Load and Store Word or Byte: Offsets from the Base Register
As well as accessing the actual location contained in the base register, these instructions can access a location offset from the base register pointer. This offset can be An unsigned 12bit immediate value (ie 0 - 4095 bytes). A register, optionally shifted by an immediate value This can be either added or subtracted from the base register: Prefix the offset value or register with + (default) or - . This offset can be applied: before the transfer is made: Pre-indexed addressing Pre optionally auto-incrementing the base register, by postfixing the autoinstruction with an ! . after the transfer is made: Post-indexed addressing Post causing the base register to be auto-incremented. auto-incremented.
Memory
r0 0x5
0x5
Base Register
0x200
0x200
To store to location 0x1f4 instead use: STR r0, [r1,#-12] [r1,#To auto-increment base pointer to 0x20c use: STR r0, [r1, #12]! autoIf r2 contains 3, access 0x20c by multiplying this by 4: STR r0, [r1, r2, LSL #2]
Memory r0 0x5
r1 0x200
0x200
0x5
To auto-increment the base register to location 0x1f4 instead use: auto STR r0, [r1], #-12 #If r2 contains 3, auto-incremenet base register to 0x20c by automultiplying this by 4: STR r0, [r1], r2, LSL #2
Imagine an array, the first element of which is pointed to by the contents of r0. Memory If we want to access a particular element, element Offset then we can use pre-indexed addressing: pre r1 is element we want. LDR r2, [r0, r1, LSL #2] 12 3 If we want to step through every 1 element of the array, for instance 0 r0 to produce sum of elements in the array, then we can use post-indexed addressing within a loop: post r1 is address of current element (initially equal to r0). LDR r2, [r1], #4 Use a further register to store the address of final element, so that the loop can be correctly terminated.
Pointer to start of array 2 8 4 0
The Load and Store Halfword and Load Signed Byte or Halfword instructions can make use of prepre- and post-indexed addressing in much the postsame way as the basic load and store instructions. However the actual offset formats are more constrained:
The immediate value is limited to 8 bits (rather than 12 bits) giving an offset of 0-255 bytes. 0The register form cannot have a shift applied to it.
Effect of endianess
The ARM can be set up to access its data in either little or big endian format. Little endian:
Least significant byte of a word is stored in bits 0-7 of an addressed word. Least significant byte of a word is stored in bits 2424-31 of an addressed word.
Big endian:
This has no real relevance unless data is stored as words and then accessed in smaller sized quantities (halfwords or bytes).
Which byte / halfword is accessed will depend on the endianess of the system involved.
Endianess Example
r0 = 0x11223344
31 24 23 16 15 87 0
11
22
33
44
31
24 23
16 15
87
31
24 23
16 15
87
r1 = 0x100
11
22
33
44
Memory
LDRB r2, [r1]
44
33
22
11
r1 = 0x100
Little-endian
31 24 23 16 15 87 0
Big-endian
31 24 23 16 15 87 0
00
00
00
44
00
00
00
11
r2 = 0x44
r2 = 0x11
Example
Write a segment of code that add together elements x to x+(n-1) of x+(nan array, where the element x=0 is the first element of the array. Each element of the array is word sized (ie. 32 bits). The segment should use post-indexed addressing. postAt the start of your segments, you should assume that: r0 points to the start of the array. Elements r1 = x r2 = n
n elements
x + (n - 1)
x+1 x
r0
Sample Solution
ADD r0, r0, r1, LSL#2 ADD r2, r0, r2, LSL#2 n+1 MOV r1, #0 loop LDR r3, [r0], #4 next ADD r1, r1, r3 CMP r0, r2 BLT loop ; Set r0 to address of element x ; Set r2 to address of element ; Initialise counter ; Access element and move to ; Add contents to counter ; Have we reached element x+n? ; If not - repeat for ; next element
The Load and Store Multiple instructions (LDM / STM) allow betweeen 1 and 16 registers to be transferred to or from memory. The transferred registers can be either: Any subset of the current bank of registers (default). Any subset of the user mode bank of registers when in a priviledged mode (postfix instruction with a ^ ).
31 28 27 24 23 22 21 20 19 16 15 0
Cond
1 0 0 P U S W L
Rn
Register list
Condition field
Up/Down bit
0 = Down; subtract offset from base 1 = Up ; add offset to base
Base register
Load/Store bit
0 = Store to memory 1 = Load from memory
4 different addressing modes allow increment and decrement inclusive or exclusive of the base register location. Base register can be optionally updated following the transfer (by appending it with an ! . Lowest register number is always transferred to/from lowest memory location accessed.
These instructions are very efficient for Saving and restoring context For this useful to view memory as a stack. Moving large blocks of data around memory For this useful to directly represent functionality of the instructions.
Stacks
A stack is an area of memory which grows as new data is pushed onto the top of it, and shrinks as data is popped off the top. Two pointers define the current limits of the stack. A base pointer used to point to the bottom of the stack (the first location). A stack pointer used to point the current top of the stack.
PUSH {1,2,3}
SP 3 2 SP BASE 2 1 1 BASE
POP
Result of pop = 3
SP BASE
Stack Operation
Traditionally, a stack grows down in memory, with the last pushed value at the lowest address. The ARM also supports ascending stacks, where the stack structure grows up through memory. The value of the stack pointer can either: Point to the last occupied address (Full stack) and so needs pre-decrementing (ie before the push) pre Point to the next occupied address (Empty stack) and so needs post-decrementing (ie after the push) postThe stack type to be used is given by the postfix to the instruction: STMFD / LDMFD : Full Descending stack STMFA / LDMFA : Full Ascending stack. STMED / LDMED : Empty Descending stack STMEA / LDMEA : Empty Ascending stack Note: ARM Compiler will always use a Full descending stack.
Stack Examples
STMFD sp!, {r0,r1,r3-r5} STMED sp!, {r0,r1,r3-r5} STMFA sp!, {r0,r1,r3-r5} STMEA sp!, {r0,r1,r3-r5}
0x418
SP r5 r4 r3 r1 r0 SP r5 r4 r3 r1 r0
Old SP
Old SP
SP
r5 r4 r3 r1 r0
r5 r4 r3 r1 r0
Old SP
Old SP
0x400
SP
0x3e8
One use of stacks is to create temporary register workspace for subroutines. Any registers that are needed can be pushed onto the stack at the start of the subroutine and popped off again at the end so as to restore them before return to the caller : STMFD sp!,{r0-r12, lr} sp!,{r0; stack all registers ........ ; and the return address ........ LDMFD sp!,{r0-r12, pc} sp!,{r0; load all the registers ; and return automatically
When LDM / STM are not being used to implement stacks, it is clearer to specify exactly what functionality of the instruction is:
i.e. specify whether to increment / decrement the base pointer, before or after the memory access.
In order to do this, LDM / STM support a further syntax in addition to the stack one:
STMIA / LDMIA : Increment After STMIB / LDMIB : Increment Before STMDA / LDMDA : Decrement After STMDB / LDMDB : Decrement Before
Copy a block of memory, which is an exact multiple of 12 words long from the location pointed to by r12 to the location pointed to by r13. r14 points to the end of block to be copied.
; r12 points to the start of the source data ; r14 points to the end of the source data ; r13 points to the start of the destination data loop LDMIA r12!, {r0-r11} {r0; load 48 bytes STMIA r13!, {r0-r11} {r0; and store them CMP r12, r14 ; check for the end BNE loop ; and loop until done
r12
Quiz
r0 r1 r2 r3 r4 r5 r6
r3 r4 r6 r5 r0 r1 r2
Write a segment of code that uses full descending stack operations to carry this out, and hence requires no use of any other registers for temporary storage.
S P
r6 r5 r4 r3 r2 r1 r0
S P
r6 r5 r4 r3
S P
r6 r5 r4
r3 = r0 r4 = r1 r6 = r2
r5 = r3
r0 = r4 r1 = r5 r2 = r6
SWP{<cond>}{B} Rd, Atomic operation of a memory read followed by a memory write which moves byte or word Rm, [Rn]
1 temp 2 Memory Rm Rd 3
Rn
Thus to implement an actual swap of contents make Rd = Rm. The compiler cannot produce this instruction.
Cond
1 1 1 1
Condition Field
In effect, a SWI is a user-defined instruction. userIt causes an exception trap to the SWI hardware vector (thus causing a change to supervisor mode, plus the associated state saving), thus causing the SWI exception handler to be called. The handler can then examine the comment field of the instruction to decide what operation has been requested. By making use of the SWI mechansim, an operating system can implement a set of privileged operations which applications running in user mode can request. See Exception Handling Module for further details.
All instructions are 32 bits long. Most instructions execute in a single cycle. Every instruction can be conditionally executed. A load/store architecture
Three operand format Combined ALU and shifter for high speed bit manipulation
Operating States
ARM Thumb
ARM State
Able to access more large memories efficiently 32 bit integer arithmetic in a single cycle More number of instructions Better performance
Thumb ISA: 16-bit instruction, dynamically 16decompressed into ARM Instruction before execution Fewer directly accessible GPRs (Only R0-R8) R0The CPU can be switched between ARM ISA mode and Thumb ISA mode dynamically
Switching State
ARM to Thumb
Thumb to ARM
Execute the BX instruction with state bit=0 An interrupt or exception occurs
Low memory system : use thumb 16 bit memory : use thumb Performance is critical : use ARM
Performance is critical AND Memory is low : use both ARM and thumb example : in interrupt routines
ARM Thumb
T (Thumb)-extension shrinks the ARM instruction set to 16-bit word length > 35-40% saving in amount of memory compared to 32-bit instruction set Extension enables simpler and significantly cheaper realization of processor system. Instructions take only half of memory than with 32-bit instruction set without significant decrease in performance or increase in code size. Extension is made to instruction decoder at the processor pipeline Registers are preserved as 32-bit but only half of them are available
Thumb-instruction decoder is placed in pipeline Change to Thumb-mode happens by turning the state of multiplexers feeding the instruction decoders and data bus A1 selects the 16-bit half word from the 32-bit bus Example ADD Rd,# 8 bit connstsnt
THUMB ENTRY
ARM cores start up, after reset, executing ARM instructions. The normal way they switch to execute Thumb instructions is by executing a Branch and Exchange instruction BX . This instruction sets the T bit if the bottom bit of the specified register was set, and switches the program counter to the address given in the remainder of the register. Other instructions which change from ARM to Thumb code include exception returns, either using a special form of data processing instruction or a special form of load multiple register instruction.
THUMB EXIT
An explicit switch back to an ARM instruction stream can be caused by executing a Thumb BX instruction An implicit return to an ARM instruction stream takes place whenever an exception is taken, since exception entry is always handled in ARM code.
THUMB SYSTEMS
All Thumb systems include some ARM code, if only to handle initialization and exception entry. Most of the Thumb applications will make more than this minimal use of ARM code. A typical embedded system will include a small amount of fast 32-bit memory on the same chip as the ARM core and will execute speed-critical routines (such as digital signal processing algorithms) in ARM code from this memory. The bulk of the code will not be speed critical and may execute from a 16-bit off-chip ROM.
Thumb-ARM Similarities
All Thumb instructions are 16 bits long. They map onto ARM instructions so they inherit many properties of the ARM instruction set The load-store architecture with data processing, data transfer and control flow instructions. Support for 8-bit byte, 16-bit half-word and 32-bit word data types where half-words are aligned on 2-byte boundaries and words are aligned on 4-byte boundaries.
To achieve a 16-bit instruction length a number of characteristic features of the ARM instruction set have been abandoned: Most Thumb instructions are executed unconditionally. (All ARM instructions are executed conditionally.) Many Thumb data processing instructions use a 2address format (the destination register is the same as one of the source registers). (ARM data processing instructions, with the exception of the 64-bit multiplies, use a 3-address format.) Thumb instruction formats are less regular than ARM instruction formats, as a result of the dense encoding.
Thumb Exceptions
All exceptions cause the processor to switch into ARM state and are handled within the ARM programmer's model. Since the T bit resides in the CPSR, it is saved on exception entry in the appropriate SPSR, and the same return from exception instruction will restore the state of the processor and leave it executing ARM orThumb instructions according to the state when the exception arose.
The ARM uses a pipeline in order to increase the speed of the flow of instructions to the processor. Allows several operations to be undertaken simultaneously, rather than serially.
ARM PC FETCH Instruction fetched from memory
PC - 4
DECODE
PC - 8
EXECUTE
Register(s) read from Register Bank Shift and ALU operation Write register(s) back to Register Bank
Rather than pointing to the instruction being executed, the PC points to the instruction being fetched.
control flow instructions include the various forms of PC-relative branch and branch-and-link instruction and the branch-and-exchange instruction for switching between the ARM and Thumb instruction sets.
Typical uses of branch instructions include: 1. short conditional branches to control (for example) loop exit; 2. medium-range unconditional branches to 'goto' sections of code; 3. long-range subroutine calls. ARM handles all these with the same instructions but 24-bit offset in the first two cases
In the first two formats , offset is shifted left one bit (to give half-word alignment) and sign-extended to 32 bits. Third Format-The branch and link subroutine mechanism often needs to have a long range, which is difficult within a 16-bit instruction format. Therefore Thumb uses two instructions, both with this format, to give a combined 22-bit half-word offset (which is sign-extended to 32 bits). 1. (H=0) LR := PC + (sign-extended offset shifted left 12 places); 2. (H=l) PC := LR + (offset shifted left 1 place); LR := oldPC + 3. Here oldPC' is the address of the second instruction; the return address has two bytes added to point to the next instruction and the bottom bit set to indicate that the caller is a Thumb routine.
Format 3a- is available only in architecture v5T. 3aAssembler Format of Branch Instrns B<cond> <label> ; format 1 - Thumb target B <label> ; format 2 - Thumb target BL <label> ; format 3 - Thumb target BLX <label> ; format 3a - ARM target B{L}X Rm ; format 4 - ARM or Thumb targ
ARM instruction Thumb instruction MOVS Rd, #<#imm8> ; MOV Rd, #<#imm8> MVNS Rd, Rm ; MVN Rd, Rm CMP Rn, #<#imm8> ; CMP Rn, #<#imm8> CMP Rn, Rm ; CMP Rn, Rm CMN Rn, Rm ; CMN Rn, Rm TST Rn, Rm ; TST Rn, Rm ADDS Rd, Rn, #<#imm3> ; ADD Rd, Rn, #<#imm3> ADDS Rd, Rd, #<#imm8> ; ADD Rd, #<#imm8> ADDS Rd, Rn, Rm ; ADD Rd, Rn, Rm #imm3,#imm8 - 3 & 8 bit immediate field #sh - 5 bit shift amount
In all cases the offset is scaled to the size of the data type. range of the 5-bit offset is 32 bytes in a load or store byte instruction, 64 bytes in a load or store half-word instruction and 128 bytes in a load or store word instruction
<Op> Rd, [Rn, #<#off5>] ; = LDRILDRB|STRISTRB <Op> Rd, [Rn, #<#off5>] ; = LDRHISTRH <op> Rd, [Rn, Rm] ; = .. LDR/LDRH/LDRSH/LDRB/LDRSB/STR/STRH/STRB LDR Rd, [PC, #<#off8> <op> Rd, [SP, #<#off8>] ;= LDR/STR
Thumb multiple register transfer instructions are useful both for procedure entry and return and for memory block copy
Assembler format <reg list> is a list of registers and register ranges from r0 to r7. LDMIA Rn!, {<reg list>) STMIA Rn!, {<reg list>} POP {<reg list>{, pc}} PUSH {<reg list>{, lr}}
The equivalent ARM instructions have the same assembler format in the first two cases, and replace POP and PUSH with the appropriate addressing mode in the second two cases. Block copy: LDMIA Rn!, {<reg list>} STMIA Rn!, {<reg list>} Pop: LDMFD SP!, {<reg list>{, pc}} Push: STMFD SP!, {<reg list>{, lr}}
Thumb implementation
Thumb properties
The Thumb code requires 70% of the space of the ARM code. The Thumb code uses 40% more instructions than the ARM code. With 32-bit memory, the ARM code is 40% faster than the Thumb code. With 16-bit memory, the Thumb code is 45% faster than the ARM code. Thumb code uses 30% less external memory power than ARM code.
Thumb applications
A high-end 32-bit ARM system may use Thumb code for certain non-critical routines to save power or memory requirements. A low-end 16-bit system may have a small amount of on-chip 32-bit RAM for critical routines running ARM code, but use offchip Thumb code for all non-critical routines.
Mobile telephone and pager applications incorporate real-time digital signal processing (DSP) functions that may require the full power of the ARM,but these are tightly coded routines that can fit in a small amount of on-chip memory. The more complex and much larger code that controls the user interface, battery management system, and so on, is less time-critical, and the use of Thumb code will enable off-chip ROMs to give good performance on an 8- or 16-bit bus, saving cost and improving battery life.
ARM architecture
Architecture version
Version 1 (obsolete)
Basic data processing Byte, word and multi-word load/store multiSoftware interrupt 26 bit address bus No Multiply & Coprocessor Support Multiply Coprocessor support 26 bit address bus First ARM with on-chip Cache (Coprocessor CP15) onSWAP Instruction Introduced
Version 2 (obsolete)
ARM architecture
Version 3
Add Abort Mode and Undef Mode Mode Mode Was Backward Compatible with 26-bit 26MUL & MLA Half word transfer Introduce THUMB processor state Add Privileged mode for operating system mode 2 word distance of PC from current instruction
Version 4
ARM architecture
Version 5
Improve ARM/THUMB inter-working inter Add CLZ instruction for efficient integer divide Add software breakpoint Add more coprocessor support More tight definition of arithmetic flags
ARM architecture
Architecture Variants
THUMB ( symbol as a T)
THUMB instruction set: 16 bit re-encoded subset of 32 rebit ARM instruction set
Simplified design
ARM Roadmap
ARM architecture
32x32 = 64 bit. Provide full 64 bit result Carefully chosen addition to native ARM instruction for DSP application Saturation 64 bit transfer First introduced in v5
D: On-chip debug. Halt in response OnI: Embedded ICE. On-chip breakpoint On-
Processor Cores
ARM7 Two main blocks: datapath and decoder Register bank (r0 to r15) Two read ports to A- bus/ B- bus AB One write port from ALU- bus ALU Additional read/ write ports for program counter r15 Barrel shifter / ALU Address registers/ incrementer Single Memory Port holds either PC address (with increment) or operand address
control
incrementer
barrel shifter
ALU
data in register
Processor Cores
Fetch : fetch instruction code from memory into the instruction pipeline Decode : instruction decoded to obtain control signals for the datapath ready for the next stage Execute : instruction owns the datapath - register read; shifting; owns ALU results generated and write- back writefetch decode execute
PC
2
PC+4
fetch
R15
decode execute
PC+4
3 instruction
PC+8
fetch decode execute time
Processor Cores
ARM7(cont ARM7(contd)
MultiMulti-cycle operation
Single cycle throughput for almost simple data processing instruction Multi-cycle for mul, load/store Multi
fetch ADD
decode
execute
fetch STR
decode
fetch ADD
decode
execute
fetch ADD
decode
execute
5 instruction
ARM 7TDMI
Version 4 Supports
Thumb : 16 bit compressed instruction set Debug : On chip debug support Enhanced Multiply : higher performance, long multiply Embedded ICE hardware 32 bit data bus Data size can be byte , half word, or word Words : 4 byte aligned Half word : 2 byte aligned
ARM7TDMI Pipeline
ARM7
1. 2. 3. Fetch Decode Execute
ARM9
1. 2. 3. 4. 5. Fetch Decode Execute Data/Buffer Write Back
Addresses higher code density by packing common instructions into 16-bit 16
Reduces bus width and activities Datapath remain unchanged, thus still 32-bit 32-
In an typical application, performanceperformancesensitive code can be in ARM ISA, while other code in Thumb
Switch to ARM ISA mode automatically on exception Can also be switch by BX (Branch and Exchange) Instruction
BX Instruction
Note: gcc-3.X now have support for gccARM/Thumb inter-working (Unsupported inter-working in 2.9x)
Thumb/ARM differences
Summary
Thumb: Try to make higher code density Thumb use a decompressor to decode decompressor 1616-bit Thumb instruction into 32-bit ARM 32instruction in the decode stage Adding Thumb support does not change original ARM datapath (except for the Thumb decompressor) Thumb: 16-bit, non-predicated ISA 16non-
40
Branch Instruction
For example
Set up exception vectors. Initialize stacks and registers. Initialize the memory system, if using MMU. Initialize any critical I/O devices. Enable interrupts. Change processor mode and/or state. Initialize variables required by C and call the main application.
Attach itself to the Undefined Instruction vector. Examine the undefined instruction to see if it should be emulated. Otherwise the emulator must pass the exception onto the original handler using the vector stored when the emulator was installed.
If no MMU, report error. Otherwise, the related handler is executed to deal with the virtual memory fault. Depending on whether the instruction that causes abort is re-executed or not, the return readdress should be properly set.
Prefetch abort
PCPC-8 PCPC-4 PC
Thank You