arm

203
ARM PROCESSOR ARM PROCESSOR N.ARUMUGAM, N.ARUMUGAM, ASST.PROF / ECE DEPT, ASST.PROF / ECE DEPT, NATIONAL ENGINEERING COLLEGE NATIONAL ENGINEERING COLLEGE KOVILPATTI KOVILPATTI

Upload: jannathul-firdous-mohamed

Post on 15-Oct-2014

83 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Arm

ARM PROCESSORARM PROCESSOR

N.ARUMUGAM,N.ARUMUGAM,

ASST.PROF / ECE DEPT, ASST.PROF / ECE DEPT,

NATIONAL ENGINEERING COLLEGENATIONAL ENGINEERING COLLEGE

KOVILPATTI KOVILPATTI

Page 2: Arm

ARMARM

DEFINITIONDEFINITION

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.

Page 3: Arm

ARM EvolutionARM Evolution Evolved from the BBCs’ MicrocomputerEvolved from the BBCs’ Microcomputer Developed by Acorn Computers Ltd of Developed by Acorn Computers Ltd of

Cambridge, England between 1983 and Cambridge, England between 1983 and 1985. 1985.

First RISC processor available for First RISC processor available for commercial use. commercial use.

Lot of initial ideas borrowed from Berkeley Lot of initial ideas borrowed from Berkeley RISC I and II and Stanford MIPS processors.RISC I and II and Stanford MIPS processors.

Initially known as Initially known as AAcorn corn RRISC ISC MMachineachine ARM Limited formed in 1990 after which the ARM Limited formed in 1990 after which the

name got changed to name got changed to AAdvanced dvanced RRISCISC MMachineachine

Page 4: Arm

Steve furber Father of ARM

Page 5: Arm

Computer ArchitectureComputer Architecture

Describes Users view of the Describes Users view of the ComputerComputer

Eg. Eg. Instruction Set, Instruction Set, Visible Registers, Visible Registers, Memory Management Table Structure,Memory Management Table Structure, Exception Handling Models etcException Handling Models etc

Page 6: Arm

Computer OrganizationComputer Organization

Describes User Invisible Describes User Invisible Implementation of the ArchitectureImplementation of the Architecture

Eg.Eg. Pipeline Structure, Pipeline Structure, Transparent Cache, Transparent Cache, Translation Look Aside Buffers etcTranslation Look Aside Buffers etc

Page 7: Arm

What is a Processor?What is a Processor?

Finite State AutomationFinite State Automation Executes Instructions held in MemoryExecutes Instructions held in Memory State depends on values hold by State depends on values hold by

registers & memory registers & memory

Page 8: Arm

Instructions TypesInstructions Types

Data ProcessingData Processing Data MovementData Movement Control FlowControl Flow Special Instructions Special Instructions

Eg. Switching to privileged modeEg. Switching to privileged mode

Page 9: Arm

How will u improve the How will u improve the Processor Performance?Processor Performance?

Instruction Type Dynamic RangeData Movement 43%Control Flow 23%Arithmetic 15%Comparisons 13%Logical 5%Other 1%

Page 10: Arm

PipelinesPipelines

FetchFetch DecodeDecode Register AccessRegister Access ALUALU Memory, if necessaryMemory, if necessary Write BackWrite Back

Pipeline HazardsPipeline Hazards

Page 11: Arm

RISC OrganizationRISC Organization

Hard Wired Instruction Decode LogicHard Wired Instruction Decode Logic Efficiently PipelinedEfficiently Pipelined Single Cycle ExecutionSingle Cycle Execution

Page 12: Arm

RISC AdvantagesRISC Advantages

A Smaller Die SizeA Smaller Die Size A Shorter Development TimeA Shorter Development Time Higher Performance (Bit Tricky)Higher Performance (Bit Tricky)

Page 13: Arm

RISC DisadvantagesRISC Disadvantages

Generally poor code density (Fixed Generally poor code density (Fixed Length Instruction)Length Instruction)

Page 14: Arm

AgendaAgenda

Architectural InheritanceArchitectural InheritanceThe ARM Programmers ModelThe ARM Programmers ModelThe ARM Development ToolsThe ARM Development ToolsExamples and ExercisesExamples and Exercises

Page 15: Arm

ARM HistoryARM History

ARM – Acorn RISC Machine(1983–ARM – Acorn RISC Machine(1983–1985)1985) Acorn Computers Limited, Cambridge, Acorn Computers Limited, Cambridge,

EnglandEngland ARM – Advanced RISC Machine 1990 ARM – Advanced RISC Machine 1990

ARM Limited, 1990ARM Limited, 1990 ARM has been licensed to many ARM has been licensed to many

semiconductor manufacturerssemiconductor manufacturers

Page 16: Arm

Features Used from Berkeley Features Used from Berkeley RISCRISC

A Load/Store ArchitectureA Load/Store Architecture Fixed Length 32-bit InstructionsFixed Length 32-bit Instructions 3- Address Instruction Formats3- Address Instruction Formats

Page 17: Arm

Features Rejected from Berkeley Features Rejected from Berkeley RISCRISC

Register WindowsRegister Windows Large no of registers out of which 32 Regs are Large no of registers out of which 32 Regs are Visible at a time. Procedure Entry & Exit move Visible at a time. Procedure Entry & Exit move visible window to each procedure as new regsvisible window to each procedure as new regsAnd thereby reduce Traffic between Processor & And thereby reduce Traffic between Processor & Memory.Memory. Reason for Rejecting this feature: Reason for Rejecting this feature:

Large Chip Area due to large no of regs. Large Chip Area due to large no of regs.

In ARM Shadow Registers used to handle In ARM Shadow Registers used to handle Exceptions are of similar conceptsExceptions are of similar concepts

Page 18: Arm

Features Rejected from Features Rejected from Berkeley RISCBerkeley RISC

Delayed BranchesDelayed Branches Branches cause problem in PipelinesBranches cause problem in Pipelines Most RISC Processor overcome this problemMost RISC Processor overcome this problem using delayed branches where the branch using delayed branches where the branch

takes effect after the followin instrn is takes effect after the followin instrn is excuted excuted

Not implemented in ARM to avoid the Not implemented in ARM to avoid the complexity involved during exception complexity involved during exception and interrupt handling.and interrupt handling.

Not suitable for superscalar architecturesNot suitable for superscalar architectures

Page 19: Arm

Features Rejected from Features Rejected from Berkeley RISCBerkeley RISC

Single Cycle Execution of Single Cycle Execution of ALLALL InstructionsInstructions Single Memory for Instruction & DataSingle Memory for Instruction & Data Even a simple load/store will require at Even a simple load/store will require at

least two cyclesleast two cycles Separate Data & Instruction was the Separate Data & Instruction was the

solution but was too costly those timessolution but was too costly those times

Page 20: Arm

The ARM Programmers ModelThe ARM Programmers Model

When writing user level programs When writing user level programs only only 15-general purpose 32-bit registers(r0-15-general purpose 32-bit registers(r0-

r14) &r14) & the Program Counter (r15) &the Program Counter (r15) & the CPSR need to be consideredthe CPSR need to be considered

The remaining registers are only for The remaining registers are only for system level programming & for system level programming & for handling exceptionshandling exceptions

Page 21: Arm

ARM has 37 registers in total, all of which are 32-bits long.ARM has 37 registers in total, all of which are 32-bits long. 1 dedicated program counter1 dedicated program counter 1 dedicated current program status register1 dedicated current program status register 5 dedicated saved program status registers5 dedicated saved program status registers 30 general purpose registers30 general purpose registers

However these are arranged into several banks, with the However these are arranged into several banks, with the accessible bank being governed by the processor mode. accessible bank being governed by the processor mode. Each mode can access Each mode can access

a particular set of r0-r12 registersa particular set of r0-r12 registers a particular r13 (the stack pointer) and r14 (link a particular r13 (the stack pointer) and r14 (link

register)register) r15 (the program counter)r15 (the program counter) cpsr (the current program status register)cpsr (the current program status register)

and privileged modes can also accessand privileged modes can also access a particular spsr (saved program status register)a particular spsr (saved program status register)

The RegistersThe Registers

Page 22: Arm

General registers and Program Counter

Program Status Registers

r15 (pc)

r14 (lr)

r13 (sp)

r14_svc

r13_svc

r14_irq

r13_irq

r14_abt

r13_abt

r14_undef

r13_undef

User32 / System FIQ32 Supervisor32 Abort32 IRQ32 Undefined32

cpsr

sprsr_fiqsprsr_fiqsprsr_fiq spsr_abtspsr_svcsprsr_fiqsprsr_fiqspsr_fiq sprsr_fiqsprsr_fiqsprsr_fiqsprsr_fiqsprsr_fiqspsr_irq

r12

r10

r11

r9

r8

r7

r4

r5

r2

r1

r0

r3

r6

r7

r4

r5

r2

r1

r0

r3

r6

r12

r10

r11

r9

r8

r7

r4

r5

r2

r1

r0

r3

r6

r12

r10

r11

r9

r8

r7

r4

r5

r2

r1

r0

r3

r6

r12

r10

r11

r9

r8

r7

r4

r5

r2

r1

r0

r3

r6

r12

r10

r11

r9

r8

r7

r4

r5

r2

r1

r0

r3

r6

r15 (pc) r15 (pc) r15 (pc) r15 (pc) r15 (pc)

cpsrcpsrcpsrcpsrcpsr

r14_fiq

r13_fiq

r12_fiq

r10_fiq

r11_fiq

r9_fiq

r8_fiq

sprsr_fiqsprsr_fiqsprsr_fiqsprsr_fiqsprsr_fiqspsr_undef

Page 23: Arm

Register BanksRegister Banks Registers are divided into setsRegisters are divided into sets Each Each operating mode operating mode can access a can access a

unique set of registers containingunique set of registers containing R0 to R12R0 to R12 : general purpose registers : general purpose registers R13R13 : stack pointer : stack pointer R14R14 : link register : link register R15 R15 : Program counter: Program counter

Each Each operating mode operating mode can access a can access a unique set of status registersunique set of status registers CPSRCPSR : Current Program Status Register : Current Program Status Register SPSRSPSR : Saved Program Status Register : Saved Program Status Register

(only privileged modes)(only privileged modes)

Page 24: Arm

Special purpose registersSpecial purpose registers

R13= stack pointer(sp) and stores R13= stack pointer(sp) and stores the head of the stack in the current the head of the stack in the current processor mode.processor mode.

R14= link register(lr) and is where R14= link register(lr) and is where the core puts the return address the core puts the return address whenever it calls the subroutinewhenever it calls the subroutine

R15= program counter(pc) and R15= program counter(pc) and contains the address of the next contains the address of the next instruction to be fetched by the instruction to be fetched by the processorprocessor

Page 25: Arm

CPSRCPSR

In user level programs uses CPSR to In user level programs uses CPSR to store the condition code bits as a store the condition code bits as a result of comparision & Arithmatic result of comparision & Arithmatic and logic opnsand logic opns N, C, Z, VN, C, Z, V

The bottom bits are protected by the The bottom bits are protected by the user level programuser level program I, F, T, mode[4:0]I, F, T, mode[4:0]

Page 26: Arm
Page 27: Arm

Program Status RegistersProgram Status Registers (CPSR and SPSRs) (CPSR and SPSRs)

Copies of the ALU status flags (latched if theinstruction has the "S" bit set).

N = Negative result from ALU flag.Z = Zero result from ALU flag.C = ALU operation Carried outV = ALU operation oVerflowed

* 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 Code Flags

ModeN Z C V

2831 8 4 0

I F T

* Mode Bits M[4:0] define the processor mode.

Page 28: Arm

ARM Modes of Operations° 10000 10000 UserUser Normal user codeNormal user code

° 10001 10001 FIQFIQ Processing fast interruptsProcessing fast interrupts

° 10010 10010 IRQIRQ Processing standard interruptsProcessing standard interrupts

° 10011 10011 SVCSVC Processing software interrupts Processing software interrupts (SWIs)(SWIs)

° 10111 10111 AbortAbort Processing memory faults Processing memory faults

° 11011 11011 UndefUndef Handling undefined instruction Handling undefined instruction trapstraps

° 11111 11111 System System Running privileged operating Running privileged operating system tasks system tasksPrivileged Modes

Non-Privileged Mode

Page 29: Arm

User Mode vs Privileged Modes • User Applications run in User Mode

• Privileged modes, used to – service interrupts – exceptions – access protected resources (via SWI Instruction)

• Privileged modes User mode OK

• User mode Privileged modes NOT OK– Only possible through Controlled mechanisms:

SWI, Exceptions, Interrupts

Page 30: Arm

The Memory SystemThe Memory System

Memory may be viewed as linear array Memory may be viewed as linear array of bytes number from 0 to 2^32 –1of bytes number from 0 to 2^32 –1

Data Bytes may be 8-bit (B), 16-bit Data Bytes may be 8-bit (B), 16-bit (HW), or 32-bit (W)(HW), or 32-bit (W)

Words are always aligned at 4-byte Words are always aligned at 4-byte boundaries i.e least two bits are zeroboundaries i.e least two bits are zero

Half Words are aligned on even Half Words are aligned on even boundariesboundaries

Page 31: Arm

ARM Memory OrganizationARM Memory Organization

half-word4

word16

0123

4567

891011

byte0

byte

12131415

16171819

20212223

byte1byte2

half-word14

byte3

byte6

address

bit 31 bit 0

half-word12

word8

Page 32: Arm

Load-Store ArchitectureLoad-Store Architecture

Data Processing InstructionsData Processing Instructions Data Transfer InstructionsData Transfer Instructions Control Flow InstructionControl Flow Instruction

Page 33: Arm

ARM Instruction SetARM Instruction Set

Load-Store ArchitectureLoad-Store Architecture 3-Address Data Processing Instructions3-Address Data Processing Instructions Conditional Execution of InstructionsConditional Execution of Instructions Powerful Load/Store Multiple RegisterPowerful Load/Store Multiple Register General Shift Operation (Single Cycle)General Shift Operation (Single Cycle) Extension of Instruction Set Co-processor Extension of Instruction Set Co-processor 16-bit Compressed Instruction Set16-bit Compressed Instruction Set

Page 34: Arm

I/O SystemI/O System

Memory Mapped with Interrupt Memory Mapped with Interrupt SupportSupport

Internal Registers in devices will act Internal Registers in devices will act as addressable locations in ARM’s as addressable locations in ARM’s Memory MapMemory Map

Peripheral may use IRQ or FIQPeripheral may use IRQ or FIQ May have DMA SupportMay have DMA Support

Page 35: Arm

ARM ExceptionsARM Exceptions

ARM supports range of Interrupts, ARM supports range of Interrupts, Traps, Supervisor Calls, all grouped Traps, Supervisor Calls, all grouped under general heading of under general heading of ExceptionsExceptions

Page 36: Arm

ARM Development ToolsARM Development Tools

Software DevelopmentSoftware Development ARM LtdARM Ltd GNU ToolsGNU Tools

Cross-developmentCross-development tools run on different architecture from tools run on different architecture from

one for which they produce codeone for which they produce code

Page 37: Arm

ARM Development ToolsARM Development Tools

as semblerC compiler

C source asm source

.aof

C libraries

linker

.axf

ARMsd

debug

ARMulatordevelopment

system model

board

objectlibraries

Page 38: Arm

ARM ASSEMBLY LANGUAGEARM ASSEMBLY LANGUAGEPROGRAMMINGPROGRAMMING

Page 39: Arm

AgendaAgenda

Data Processing InstructionsData Processing Instructions Data Transfer InstructionsData Transfer Instructions Control Flow InstructionsControl Flow Instructions Writing Simple Assembly Language Writing Simple Assembly Language

ProgramsPrograms Examples and ExercisesExamples and Exercises

Page 40: Arm

Data Processing InstructionsData Processing Instructions

These are the only Instruction that These are the only Instruction that modify the data values in ARMmodify the data values in ARM

Typically require two operands & Typically require two operands & produce single results (though there produce single results (though there are exceptions)are exceptions)

Page 41: Arm

Rules for Data Processing Rules for Data Processing InstructionsInstructions

All operands are 32-bits wide & come from All operands are 32-bits wide & come from registers or are specified as literals in the registers or are specified as literals in the instruction itselfinstruction itself

The result, if there is any, is 32-bits wide The result, if there is any, is 32-bits wide and is placed in a register (Exception: and is placed in a register (Exception: Long Multiplications)Long Multiplications)

Each of the operand registers & the results Each of the operand registers & the results are independently specified in the are independently specified in the instruction (ARM 3-Address Instruction instruction (ARM 3-Address Instruction format)format)

Page 42: Arm

Operands in Data ProcessingOperands in Data Processing

Simple Register OperandsSimple Register Operands Immediate OperandsImmediate Operands Shifted Register OperandsShifted Register Operands

Page 43: Arm

Data Processing OperationsData Processing Operations

Arithmetic OperationsArithmetic Operations Bit-wise OperationsBit-wise Operations Register MovementRegister Movement OperationsOperations Comparison OperationsComparison Operations

Page 44: Arm

Arithmetic OperationsArithmetic Operations

ADD r0, r1, r2ADD r0, r1, r2 r0 := r1 + r2r0 := r1 + r2

ADC r0, r1, r2ADC r0, r1, r2 r0 := r1 + r2 + Cr0 := r1 + r2 + C

SUB r0, r1, r2SUB r0, r1, r2 r0 := r1 - r2r0 := r1 - r2

SBC r0, r1, r2SBC r0, r1, r2 r0 := r1 - r2 + C - 1r0 := r1 - r2 + C - 1

RSB r0, r1, r2RSB r0, r1, r2 r0 := r2 – r1r0 := r2 – r1

RSC r0, r1, r2RSC r0, r1, r2 r0 := r2 – r1 + C - 1r0 := r2 – r1 + C - 1

Page 45: Arm

Bit-wise Logical OperationsBit-wise Logical Operations

AND r0, r1, r2AND r0, r1, r2 r0 := r1 and r2r0 := r1 and r2

ORR r0, r1, r2ORR r0, r1, r2 r0 := r1 or r2r0 := r1 or r2

EOR r0, r1, r2EOR r0, r1, r2 r0 := r1 xor r2r0 := r1 xor r2

BIC r0, r1, r2BIC r0, r1, r2 r0 := r1 and (not) r0 := r1 and (not) r2r2

Page 46: Arm

Register Movement OperationsRegister Movement Operations

MOV r0, r2MOV r0, r2 r0 := r2r0 := r2

MVN r0, r2MVN r0, r2 r0 := not r2r0 := not r2

Page 47: Arm

Comparison OperationsComparison Operations

CMP r1, r2CMP r1, r2 set cc on r1 - r2set cc on r1 - r2

CMN r1, r2CMN r1, r2 set cc on r1 + r2set cc on r1 + r2

TST r1, r2TST r1, r2 set cc on r1 and r2set cc on r1 and r2

TEQ r1, r2TEQ r1, r2 set cc on r1 xor r2set cc on r1 xor r2

Page 48: Arm

Immediate OperandsImmediate Operands

If we need to add constant If we need to add constant ADD r3, r3, #1ADD r3, r3, #1 ; r3 := r3 + 1 ; r3 := r3 + 1 AND r8, r7, #&ffAND r8, r7, #&ff ; r8 := r7[7:0]; r8 := r7[7:0]

Immediate OperandsImmediate Operands

imm = (0->255) * 2^n (0<=n<=12)imm = (0->255) * 2^n (0<=n<=12)

Page 49: Arm

Shift Register OperandsShift Register Operands

Second register operand is Second register operand is subjected to shift before it is subjected to shift before it is combined with first operandcombined with first operand

ADD r3, r2, r1, LSL #3ADD r3, r2, r1, LSL #3 ; r3 := r2 + ; r3 := r2 + (r1*8)(r1*8)

Page 50: Arm

ARM Shift OperationsARM Shift Operations

LSL- Logical Shift LeftLSL- Logical Shift Left LSR- Logical Shift RightLSR- Logical Shift Right ASL- Arithmetic Shift LeftASL- Arithmetic Shift Left ASR- Arithmetic Shift RightASR- Arithmetic Shift Right ROR- Rotate RightROR- Rotate Right RRX- Rotate Right ExtendedRRX- Rotate Right Extended

Page 51: Arm

LSL, LSR, ASL, ASR, ROR, LSL, LSR, ASL, ASR, ROR, RRXRRX

031

00000

LSL #5

031

00000

LSR #5

031

1 1111 1

ASR #5 , negative operand

031

00000 0

ASR #5 , positive operand

0 1

031

ROR #5

031

RRX

C

C C

Page 52: Arm

Shift Value in RegisterShift Value in Register

It is also possible to use a register It is also possible to use a register value to specify the number of bits value to specify the number of bits the second operand should be shifted the second operand should be shifted by:by:

ADD r5, r5, r3, LSL r2ADD r5, r5, r3, LSL r2

r5: r5 + r3 * 2^r2r5: r5 + r3 * 2^r2

Page 53: Arm

Setting the Condition CodesSetting the Condition Codes

All DPI can affect the condition codesAll DPI can affect the condition codes For all DPI except comparisons a For all DPI except comparisons a

special request needs to be madespecial request needs to be made At assembly level the request is At assembly level the request is

made by adding an ‘S’ to opcodemade by adding an ‘S’ to opcode Eg:Eg:

ADDS r0, r0, r1ADDS r0, r0, r1ADC r3, r3, r2ADC r3, r3, r2

Page 54: Arm

MultipliesMultiplies

MUL r4, r3, r2MUL r4, r3, r2 Some RulesSome Rules

Immediate second operand not Immediate second operand not supportedsupported

The result register must not be the same The result register must not be the same as the first source registeras the first source register

If the ‘S’ bit is set the V flag is preserved If the ‘S’ bit is set the V flag is preserved & the C flag is rendered meaningless& the C flag is rendered meaningless

Page 55: Arm

Data Transfer InstructionsData Transfer Instructions Single Register Load & StoreSingle Register Load & Store

transfer of a data item (byte, half-word, word) transfer of a data item (byte, half-word, word) between ARM registers and memorybetween ARM registers and memory

Multiple Register Load & StoreMultiple Register Load & Store enable transfer of large quantities of dataenable transfer of large quantities of data used for procedure entry and exit, to save/restore used for procedure entry and exit, to save/restore

workspace registers, to copy blocks of data around workspace registers, to copy blocks of data around memorymemory

Single Register Swap InstructionsSingle Register Swap Instructions allow exchange between a register and memory allow exchange between a register and memory

in one instructionin one instruction used to implement semaphores to ensure mutual used to implement semaphores to ensure mutual

exclusion on accesses to shared data in multisexclusion on accesses to shared data in multis

Page 56: Arm

Register-Indirect AddressingRegister-Indirect Addressing

LDR r0, [r1]LDR r0, [r1] r0 := memr0 := mem3232[r1][r1]

STR r0, [r1]STR r0, [r1] memmem3232[r1] := r0[r1] := r0

r1 =baase register containing address of memory location

Page 57: Arm

Pre Indexed AddressingPre Indexed Addressing

LDR r0, [r1, #4]LDR r0, [r1, #4] r0 := r0 := memmem3232[r1+4][r1+4]

Page 58: Arm

Post Indexed AddressingPost Indexed Addressing

LDR r0, [r1], #4LDR r0, [r1], #4 r0 := memr0 := mem3232[r1][r1]r1 := r1 + 4r1 := r1 + 4

Page 59: Arm

Auto Indexing AddressingAuto Indexing Addressing

LDR r0, [r1, LDR r0, [r1, #4]!#4]!

r0 := memr0 := mem3232[r1 + [r1 + 4]4]r1 := r1 + 4r1 := r1 + 4

Where do I use this?

Page 60: Arm

ExerciseExercise

Copy Data from Table1 to Table2Copy Data from Table1 to Table2 Algorithm:Algorithm:

Pointer to Table1Pointer to Table1 Pointer to Table2Pointer to Table2 Load [Table1]Load [Table1] Store [Table2]Store [Table2] Add 4 to Table1Add 4 to Table1 Add 4 to Table2Add 4 to Table2

Page 61: Arm

AnswerAnswer

COPY:COPY: ADR r1, TABLE1ADR r1, TABLE1 ; r1 points to TABLE1; r1 points to TABLE1

ADR r2, TABLE2ADR r2, TABLE2 ; r2 points to TABLE2; r2 points to TABLE2

LOOP:LOOP: LDR r0, [r1]LDR r0, [r1]

STR r0, [r2]STR r0, [r2]

ADD r1, r1, #4ADD r1, r1, #4

ADD r2, r2, #4ADD r2, r2, #4

......

TABLE1:TABLE1: ......

TABLE2:...TABLE2:...

Page 62: Arm

Better AnswerBetter Answer

COPY:COPY: ADR r1, TABLE1ADR r1, TABLE1 ; r1 points to TABLE1; r1 points to TABLE1

ADR r2, TABLE2ADR r2, TABLE2 ; r2 points to TABLE2; r2 points to TABLE2

LOOP:LOOP: LDR r0, [r1], #4LDR r0, [r1], #4

STR r0, [r2], #4STR r0, [r2], #4

......

TABLE1:TABLE1: ......

TABLE2:...TABLE2:...

Page 63: Arm

Multiple Register TransferMultiple Register Transfer

When large quantity of data needs When large quantity of data needs to be transferredto be transferred

But there is a trade off, i.e less But there is a trade off, i.e less addressing modesaddressing modes

Page 64: Arm

Example Multiple TransferExample Multiple Transfer

LDMIA r1, {r0, r2, LDMIA r1, {r0, r2, r5}r5}

r0:=memr0:=mem3232[r1][r1]r2 := memr2 := mem3232[r1 + [r1 + 4]4]r5 := memr5 := mem3232[r1 + [r1 + 8]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

Page 65: Arm

ExerciseExercise

Write a code to add two numbers a & Write a code to add two numbers a & b which are at memory locations b which are at memory locations 0x8000-2000 & 0x8000-2001? Check 0x8000-2000 & 0x8000-2001? Check the question if some thing is wrong, the question if some thing is wrong, correct the problem & then write the correct the problem & then write the code!!code!!

Page 66: Arm

ExerciseExercise

Write a code to covert the following C Write a code to covert the following C StatementsStatements X = A + BX = A + B X = A – B X = A – B X = B – A X = B – A X = A + B*4X = A + B*4 X = A + (B*5)X = A + (B*5) X = A + (B*5) + (C*8)X = A + (B*5) + (C*8)

Page 67: Arm

The ARM Instruction SetThe ARM Instruction Set

ARMAdvanced RISC Machines

Page 68: Arm

ARM Instruction SetARM Instruction Set Load-Store ArchitectureLoad-Store Architecture

3-Address Data Processing 3-Address Data Processing InstructionsInstructions

Conditional Execution of Conditional Execution of InstructionsInstructions

Powerful Load/Store Multiple Powerful Load/Store Multiple RegisterRegister

General Shift Operation (Single General Shift Operation (Single Cycle)Cycle)

Extension of Instruction Set Co-Extension of Instruction Set Co-processor processor

16-bit Compressed Instruction Set16-bit Compressed Instruction Set

Page 69: Arm

Processor ModesProcessor Modes

The ARM has six operating modes:The ARM has six operating modes: UserUser (unprivileged mode under which most tasks run) (unprivileged mode under which most tasks run)

(10000)(10000) FIQFIQ (entered when a high priority (fast) interrupt is raised) (entered when a high priority (fast) interrupt is raised)

(10001)(10001) IRQIRQ (entered when a low priority (normal) interrupt is (entered when a low priority (normal) interrupt is

raised) (10010)raised) (10010) SupervisorSupervisor (entered on reset and when a Software (entered on reset and when a Software

Interrupt instruction is executed) (10011)Interrupt instruction is executed) (10011) AbortAbort (used to handle memory access violations) (10111) (used to handle memory access violations) (10111) UndefUndef (used to handle undefined instructions) (11011) (used to handle undefined instructions) (11011)

ARM Architecture Version 4 adds a seventh mode:ARM Architecture Version 4 adds a seventh mode: SystemSystem (privileged mode using the same registers as user (privileged mode using the same registers as user

mode) (11111)mode) (11111)

Page 70: Arm

ARM has 37 registers in total, all of which are 32-bits long.ARM has 37 registers in total, all of which are 32-bits long. 1 dedicated program counter 1 dedicated program counter 1 dedicated current program status register1 dedicated current program status register 5 dedicated saved program status registers5 dedicated saved program status registers 30 general purpose registers30 general purpose registers

However these are arranged into several banks, with the However these are arranged into several banks, with the accessible bank being governed by the processor mode. accessible bank being governed by the processor mode. Each mode can access Each mode can access

a particular set of r0-r12 registersa particular set of r0-r12 registers a particular r13 (the stack pointer) and r14 (link register)a particular r13 (the stack pointer) and r14 (link register) r15 (the program counter)r15 (the program counter) cpsr (the current program status register)cpsr (the current program status register)

and privileged modes can also accessand privileged modes can also access a particular spsr (saved program status register)a particular spsr (saved program status register)

The RegistersThe Registers

Page 71: Arm

Register OrganisationRegister Organisation

General registers and Program Counter

Program Status Registers

r15 (pc)

r14 (lr)

r13 (sp)

r14_svc

r13_svc

r14_irq

r13_irq

r14_abt

r13_abt

r14_undef

r13_undef

User32 / System FIQ32 Supervisor32 Abort32 IRQ32 Undefined32

cpsr

sprsr_fiqsprsr_fiqsprsr_fiq spsr_abtspsr_svcsprsr_fiqsprsr_fiqspsr_fiq sprsr_fiqsprsr_fiqsprsr_fiqsprsr_fiqsprsr_fiqspsr_irq

r12

r10

r11

r9

r8

r7

r4

r5

r2

r1

r0

r3

r6

r7

r4

r5

r2

r1

r0

r3

r6

r12

r10

r11

r9

r8

r7

r4

r5

r2

r1

r0

r3

r6

r12

r10

r11

r9

r8

r7

r4

r5

r2

r1

r0

r3

r6

r12

r10

r11

r9

r8

r7

r4

r5

r2

r1

r0

r3

r6

r12

r10

r11

r9

r8

r7

r4

r5

r2

r1

r0

r3

r6

r15 (pc) r15 (pc) r15 (pc) r15 (pc) r15 (pc)

cpsrcpsrcpsrcpsrcpsr

r14_fiq

r13_fiq

r12_fiq

r10_fiq

r11_fiq

r9_fiq

r8_fiq

sprsr_fiqsprsr_fiqsprsr_fiqsprsr_fiqsprsr_fiqspsr_undef

Page 72: Arm

Accessing Registers using Accessing Registers using ARM InstructionsARM Instructions

No breakdown of currently accessible No breakdown of currently accessible registers.registers. All instructions can access r0-r14 All instructions can access r0-r14

directly.directly. Most instructions also allow use of the Most instructions also allow use of the

PC.PC. Specific instructions to allow access Specific instructions to allow access

to CPSR and SPSR.to CPSR and SPSR.

Page 73: Arm

The Program Status RegistersThe Program Status Registers (CPSR and SPSRs) (CPSR and SPSRs)

Copies of the ALU status flags (latched if theinstruction has the "S" bit set).

N = Negative result from ALU flag.Z = Zero result from ALU flag.C = ALU operation Carried outV = ALU operation oVerflowed

* 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 Code Flags

ModeN Z C V

2831 8 4 0

I F T

* Mode Bits M[4:0] define the processor mode.

Page 74: Arm

Logical Instruction Arithmetic Instruction

Flag

Negative No meaning Bit 31 of the result has been set(N=‘1’) Indicates a negative number in

signed operations

Zero Result is all zeroes Result of operation was zero(Z=‘1’)

Carry After Shift operation Result was greater than 32 bits(C=‘1’) ‘1’ was left in carry flag

oVerflow No meaning Result was greater than 31 bits(V=‘1’) Indicates a possible corruption of

the sign bit in signed numbers

Condition FlagsCondition Flags

Page 75: Arm

When the processor is executing in ARM state:When the processor is executing in ARM state: All instructions are 32 bits in lengthAll instructions are 32 bits in length All instructions must be word alignedAll instructions must be word aligned Therefore the PC value is stored in bits [31:2] with bits Therefore the PC value is stored in bits [31:2] with bits

[1:0] equal to zero (as instruction cannot be halfword or [1:0] equal to zero (as instruction cannot be halfword or byte aligned).byte aligned).

R14 is used as the subroutine link register (LR) and R14 is used as the subroutine link register (LR) and stores the return address when Branch with Link stores the return address when Branch with Link operations are performed, operations are performed, calculated from the PC.calculated from the PC.

Thus to return from a linked branchThus to return from a linked branch MOV r15,r14MOV r15,r14

oror MOV pc,lrMOV pc,lr

The Program Counter (R15)The Program Counter (R15)

Page 76: Arm

Register Example:Register Example:User to FIQ ModeUser to FIQ Mode

spsr_fiq

cpsr

r7

r4

r5

r2

r1

r0

r3

r6

r15 (pc)

r14_fiq

r13_fiq

r12_fiq

r10_fiq

r11_fiq

r9_fiq

r8_fiq

r14 (lr)

r13 (sp)

r12

r10

r11

r9

r8

User mode CPSR copied to FIQ mode SPSR

cpsr

r15 (pc)

r14 (lr)

r13 (sp)

r12

r10

r11

r9

r8

r7

r4

r5

r2

r1

r0

r3

r6

r14_fiq

r13_fiq

r12_fiq

r10_fiq

r11_fiq

r9_fiq

r8_fiq

Return address calculated from User mode PC value and stored in FIQ mode LR

Registers in use Registers in use

EXCEPTION

User Mode

FIQ Mode

spsr_fiq

Disable FIQ

Page 77: Arm

ExceptionsExceptions

Exceptions generated as the direct effect Exceptions generated as the direct effect of executing an instructionof executing an instruction Software Interrupts, Undefined Instructions & Software Interrupts, Undefined Instructions &

Prefetch AbortsPrefetch Aborts Exceptions generated as a side effect of Exceptions generated as a side effect of

an Instructionan Instruction Data Aborts (Caused by Load/Store Data Aborts (Caused by Load/Store

Instructions)Instructions) Exceptions generated externally, Exceptions generated externally,

unrelated to Instruction flowunrelated to Instruction flow Reset, IRQ, FIQReset, IRQ, FIQ

Page 78: Arm

Exception Sources in ARM ° 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

Page 79: Arm

Exception EntryException Entry

Changes Operating ModeChanges Operating Mode Save Address of next Instruction in Save Address of next Instruction in

r14 of the new moder14 of the new mode Saves Old value of CPSR into SPSR of Saves Old value of CPSR into SPSR of

new modenew mode Disables either IRQ or FIQ if the Disables either IRQ or FIQ if the

exception is IRQ or FIQ respectivelyexception is IRQ or FIQ respectively Forces PC to vector to new addressForces PC to vector to new address

Page 80: Arm

Exception ReturnException Return

Any modified user registers should Any modified user registers should be restored from the Stackbe restored from the Stack

The CPSR should be restored from The CPSR should be restored from appropriate SPSRappropriate SPSR

The PC must be changed to relevant The PC must be changed to relevant User Instruction StreamUser Instruction Stream

Problem: Last two cannot be carried out independently.two technics are used to carry out these steps simultaneously

Page 81: Arm

Solution 1Solution 1

To return from SWITo return from SWI MOVSMOVS pc, r14pc, r14

To return from IRQ, FIQ or Prefetch To return from IRQ, FIQ or Prefetch AbortAbort SUBSSUBS pc, r14, #4pc, r14, #4

To return from Data AbortsTo return from Data Aborts SUBSSUBS pc, r14, #8pc, r14, #8

The S modifier signifies special form of Instruction when the destination is PC

Page 82: Arm

Note how the return instruction incorporates an Note how the return instruction incorporates an adjustment to the return address where adjustment to the return address where necessary: necessary:

IRQ and FIQ must return one instruction early in IRQ and FIQ must return one instruction early in order to execute the instructionorder to execute the instruction

that was 'usurped' for the exception entry.that was 'usurped' for the exception entry. Prefetch abort must return one instruction early to Prefetch abort must return one instruction early to

execute the instruction that had caused a execute the instruction that had caused a memory fault when first requested.memory fault when first requested.

• • Data abort must return two instructions early to Data abort must return two instructions early to retry the data transfer instruction, which was the retry the data transfer instruction, which was the instruction before the one usurped for exception instruction before the one usurped for exception entryentry

Page 83: Arm

SOLUTION2SOLUTION2

If the handler has copied the return address out If the handler has copied the return address out onto a stack (in order, for example, to allow re-onto a stack (in order, for example, to allow re-entrant behaviour, though note that in this case entrant behaviour, though note that in this case the SPSR must be saved as well as the PC) the the SPSR must be saved as well as the PC) the restoration of the user registers and the return restoration of the user registers and the return may be implemented with a single multiple may be implemented with a single multiple register transfer instruction such as:register transfer instruction such as:

LDMFD r13!, {r0-r3,pc}" ; restore and return LDMFD r13!, {r0-r3,pc}" ; restore and return The CPSR is restored at the same time that the The CPSR is restored at the same time that the

PC is loaded from memory, which will always be PC is loaded from memory, which will always be the last item transferred from memory since the the last item transferred from memory since the registers are loaded in increasing order.registers are loaded in increasing order.

Page 84: Arm

EXCEPTION PRIORITIESEXCEPTION PRIORITIES

ResetReset Data AbortData Abort FIQFIQ IRQIRQ Prefetch AbortPrefetch Abort SWI, Undefined Instruction SWI, Undefined Instruction

Page 85: Arm

When an exception occurs, When an exception occurs, the core:the core:Copies CPSR into SPSR_<mode>Copies CPSR into SPSR_<mode>Sets appropriate CPSR bits Sets appropriate CPSR bits

If core implements ARM Architecture 4T and is If core implements ARM Architecture 4T and is currently in Thumb state, thencurrently in Thumb state, then

ARM state is entered.ARM state is entered. Mode field bits Mode field bits Interrupt disable flags if appropriate.Interrupt disable flags if appropriate.

Maps in appropriate banked registersMaps in appropriate banked registersStores the “Stores the “return addressreturn address” in LR_<mode>” in LR_<mode>Sets PC to vector addressSets PC to vector address

To return, exception handler needs To return, exception handler needs to:to:

Restore CPSR from SPSR_<mode>Restore CPSR from SPSR_<mode> Restore PC from LR_<mode>Restore PC from LR_<mode>

Exception HandlingException Handlingand the Vector Tableand the Vector Table

0x00000000

0x0000001C

0x00000018

0x00000014

0x00000010

0x0000000C

0x00000008

0x00000004

Reset

Undefined Instruction

FIQ

IRQ

Reserved

Data Abort

Prefetch Abort

Software Interrupt

Page 86: Arm

Quiz - VerbalQuiz - Verbal

What register is used to store the program What register is used to store the program counter ?counter ?

What is r13 often used to store?What is r13 often used to store? Which mode, or modes has the fewest Which mode, or modes has the fewest

available number of registers available? available number of registers available? How many and why?How many and why?

Name the exceptions in the ARM?Name the exceptions in the ARM? Mention their priorities.Mention their priorities. What happens on Exception Entry & What happens on Exception Entry &

Exception Exit?Exception Exit?

Page 87: Arm

ARM Instruction Set FormatARM Instruction Set FormatInstruction typeInstruction type

Data processing / PSR TransferData processing / PSR Transfer

MultiplyMultiply

Long MultiplyLong Multiply (v3M / v4 only) (v3M / v4 only)

SwapSwap

Load/Store Byte/WordLoad/Store Byte/Word

Load/Store MultipleLoad/Store Multiple

Halfword transfer : Immediate Halfword transfer : Immediate

offset offset

Halfword transfer: Register offset Halfword transfer: Register offset

(v4 only)(v4 only)

BranchBranch

Branch Exchange Branch Exchange (v4T only)(v4T only)

Coprocessor data transferCoprocessor data transfer

Coprocessor data operationCoprocessor data operation

Coprocessor register transferCoprocessor register transfer

Software interruptSoftware interrupt

Cond 0 0 I Opcode S Rn Rd Operand2 Cond 0 0 0 0 0 0 A S Rd Rn Rs 1 0 0 1 Rm

Cond 0 0 0 1 0 B 0 0 Rn Rd 0 0 0 0 1 0 0 1 Rm

Cond 0 1 I P U B W L Rn Rd Offset

Cond 1 0 0 P U S W L Rn Register List

Cond 0 0 0 0 1 U A S RdHi RdLo Rs 1 0 0 1 Rm

Cond 0 0 0 P U 1 W L Rn Rd Offset1 1 S H 1 Offset2

Cond 1 0 1 L Offset

Cond 1 1 0 P U N W L Rn CRd CPNum Offset

Cond 1 1 1 0 Op1 CRn CRd CPNum Op2 0 CRm

Cond 1 1 1 0 Op1 L CRn Rd CPNum Op2 1 CRm

Cond 1 1 1 1 SWI Number

Cond 0 0 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 Rn

Cond 0 0 0 P U 0 W L Rn Rd 0 0 0 0 1 S H 1 Rm

31 2827 1615 87 0

Page 88: Arm

Conditional ExecutionConditional Execution

Most instruction sets only allow branches to Most instruction sets only allow branches to be executed conditionally.be executed conditionally.

However by reusing the condition evaluation However by reusing the condition evaluation hardware, ARM effectively increases hardware, ARM effectively increases number of instructions.number of instructions. All instructions contain a condition field which All instructions contain a condition field which

determines whether the CPU will execute them. determines whether the CPU will execute them. Non-executed instructions soak up 1 cycle.Non-executed instructions soak up 1 cycle.

Still have to complete cycle so as to allow fetching and Still have to complete cycle so as to allow fetching and decoding of following instructions.decoding of following instructions.

This removes the need for many branches, This removes the need for many branches, which stall the pipeline (3 cycles to refill).which stall the pipeline (3 cycles to refill).

Page 89: Arm

The Condition FieldThe Condition Field

2831 24 20 16 12 8 4 0

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 1001 = LS - C clear or Z (set unsigned lower or unsigned lower or same) same)

1010 = GE - N set and V set, 1010 = GE - N set and V set, or N clear and V clear or N clear and V clear (>or =)(>or =)

1011 = LT - N set and V clear, 1011 = LT - N set and V clear, or N clear and V set (>)or N clear and V set (>)

1100 = GT - Z clear, and 1100 = GT - Z clear, and either N set and V set, either N set and V set, or N clear and V set (>)or N clear and V set (>)

1101 = LE - Z set, or N set 1101 = LE - Z set, or N set and V clear,or N clear and V clear,or N clear and V set (<, or =)and V set (<, or =)

1110 = AL - always1110 = AL - always

1111 = NV - reserved1111 = NV - reserved..

Page 90: Arm

Using and updating the Using and updating the Condition FieldCondition Field

To execute an instruction conditionally, simply postfix it with the To execute an instruction conditionally, simply postfix it with the appropriate condition:appropriate condition: For example an add instruction takes the form:For example an add instruction takes the form:

ADD r0,r1,r2ADD r0,r1,r2 ; r0 = r1 + r2 (ADDAL); r0 = r1 + r2 (ADDAL) To execute this only if the zero flag is set:To execute this only if the zero flag is set:

ADDEQ r0,r1,r2ADDEQ r0,r1,r2 ; If zero flag set then…; If zero flag set then…; ... r0 = r1 + r2; ... r0 = r1 + r2

By default, data processing operations do not affect the condition By default, data processing operations do not affect the condition flags (apart from the comparisons where this is the only effect). To flags (apart from the comparisons where this is the only effect). To cause the condition flags to be updated, the S bit of the cause the condition flags to be updated, the S bit of the instruction needs to be set by postfixing the instruction (and any instruction needs to be set by postfixing the instruction (and any condition code) with an “S”.condition code) with an “S”. For example to add two numbers and set the condition flags:For example to add two numbers and set the condition flags:

ADDS r0,r1,r2ADDS r0,r1,r2 ; r0 = r1 + r2 ; r0 = r1 + r2 ; ... and set flags; ... and set flags

Page 91: Arm

Branch :Branch : B{<cond>} labelB{<cond>} label Branch with Link :Branch with Link : BL{<cond>} sub_routine_labelBL{<cond>} sub_routine_label

The offset for branch instructions is calculated by the assembler:The offset for branch instructions is calculated by the assembler: By taking the difference between the branch instruction and By taking the difference between the branch instruction and

the target address minus 8 (to allow for the pipeline).the target address minus 8 (to allow for the pipeline). This gives a 26 bit offset which is right shifted 2 bits (as the This gives a 26 bit offset which is right shifted 2 bits (as the

bottom two bits are always zero as instructions are word – bottom two bits are always zero as instructions are word – aligned) and stored into the instruction encoding.aligned) and stored into the instruction encoding.

This gives a range of ± 32 Mbytes.This gives a range of ± 32 Mbytes.

Branch instructions (1)Branch instructions (1)

2831 24 0

Cond 1 0 1 L Offset

Condition field

Link bit 0 = Branch1 = Branch with link

232527

Page 92: Arm

Branch instructions (2)Branch instructions (2) When executing the instruction, the processor:When executing the instruction, the processor:

shifts the offset left two bits, sign extends it to 32 bits, and shifts the offset left two bits, sign extends it to 32 bits, and adds it to PC.adds it to PC.

Execution then continues from the new PC, once the pipeline has Execution then continues from the new PC, once the pipeline has been refilled.been refilled.

The "Branch with link" instruction implements a subroutine call by The "Branch with link" instruction implements a subroutine call by writing PC-4 into the LR of the current bank. writing PC-4 into the LR of the current bank.

i.e. the address of the next instruction following the branch i.e. the address of the next instruction following the branch with link (allowing for the pipeline).with link (allowing for the pipeline).

To return from subroutine, simply need to restore the PC from the To return from subroutine, simply need to restore the PC from the LR:LR:

MOV pc, lrMOV pc, lr Again, pipeline has to refill before execution continues.Again, pipeline has to refill before execution continues.

The "Branch" instruction does not affect LR.The "Branch" instruction does not affect LR. Note: Architecture 4T offers a further ARM branch instruction, BXNote: Architecture 4T offers a further ARM branch instruction, BX

See Thumb Instruction Set Module for details.See Thumb Instruction Set Module for details.

Page 93: Arm

Data processing InstructionsData processing Instructions Largest family of ARM instructions, all sharing the same Largest family of ARM instructions, all sharing the same

instruction format.instruction format. Contains:Contains:

Arithmetic operationsArithmetic operations Comparisons (no results - just set condition codes) Comparisons (no results - just set condition codes) Logical operationsLogical operations Data movement between registersData movement between registers

Remember, this is a load / store architectureRemember, this is a load / store architecture These instruction only work on registers, These instruction only work on registers, NOTNOT memory. memory.

They each perform a specific operation on one or two They each perform a specific operation on one or two operands.operands. First operand always a register - RnFirst operand always a register - Rn Second operand sent to the ALU via barrel shifter.Second operand sent to the ALU via barrel shifter.

We will examine the barrel shifter shortly.We will examine the barrel shifter shortly.

Page 94: Arm
Page 95: Arm

Arithmetic OperationsArithmetic Operations Operations are:Operations are:

ADDADD operand1 + operand2operand1 + operand2 ADCADC operand1 + operand2 + carryoperand1 + operand2 + carry SUBSUB operand1 - operand2operand1 - operand2 SBCSBC operand1 - operand2 + carry -1 operand1 - operand2 + carry -1 RSBRSB operand2 - operand1operand2 - operand1 RSCRSC operand2 - operand1 + carry - 1operand2 - operand1 + carry - 1

Syntax:Syntax: <Operation>{<cond>}{S} Rd, Rn, Operand2<Operation>{<cond>}{S} Rd, Rn, Operand2

ExamplesExamples ADD r0, r1, r2ADD r0, r1, r2 SUBGT r3, r3, #1SUBGT r3, r3, #1 RSBLES r4, r5, #5RSBLES r4, r5, #5

Page 96: Arm

ComparisonsComparisons The only effect of the comparisons is toThe only effect of the comparisons is to

UPDATE THE CONDITION FLAGSUPDATE THE CONDITION FLAGS. . Thus no need to set Thus no need to set S bit.S bit.

Operations are:Operations are: CMPCMP operand1 - operand2, but result not writtenoperand1 - operand2, but result not written CMNCMN operand1 + operand2, but result not writtenoperand1 + operand2, but result not written TSTTST operand1 AND operand2, but result not writtenoperand1 AND operand2, but result not written TEQTEQ operand1 EOR operand2, but result not writtenoperand1 EOR operand2, but result not written

Syntax:Syntax: <Operation>{<cond>} Rn, Operand2<Operation>{<cond>} Rn, Operand2

Examples:Examples: CMPCMP r0, r1r0, r1 TSTEQTSTEQ r2, #5r2, #5

Page 97: Arm

Logical OperationsLogical Operations

Operations are:Operations are: ANDAND operand1 AND operand2operand1 AND operand2 EOREOR operand1 EOR operand2operand1 EOR operand2 ORRORR operand1 OR operand2operand1 OR operand2 BICBIC operand1 AND NOT operand2 [ie bit operand1 AND NOT operand2 [ie bit

clear]clear] Syntax:Syntax:

<Operation>{<cond>}{S} Rd, Rn, Operand2<Operation>{<cond>}{S} Rd, Rn, Operand2 Examples:Examples:

ANDAND r0, r1, r2r0, r1, r2 EORSEORS r1,r3,r0r1,r3,r0

Page 98: Arm

Data MovementData Movement

Operations are:Operations are: MOVMOV operand2operand2 MVNMVN NOT operand2NOT operand2

Note that these make no use of operand1.Note that these make no use of operand1. Syntax:Syntax:

<Operation>{<cond>}{S} Rd, Operand2<Operation>{<cond>}{S} Rd, Operand2 Examples:Examples:

MOVMOV r0, r1r0, r1 MOVSMOVSr2, #10r2, #10 MVNEQMVNEQ r1,#0r1,#0

Page 99: Arm

The Barrel ShifterThe Barrel Shifter

The ARM doesn’t have actual shift The ARM doesn’t have actual shift instructions.instructions.

Instead it has a barrel shifter which Instead it has a barrel shifter which provides a mechanism to carry out shifts provides a mechanism to carry out shifts as part of other instructions.as part of other instructions.

So what operations does the barrel shifter So what operations does the barrel shifter support?support?

Page 100: Arm

Shifts left by the specified amount Shifts left by the specified amount (multiplies by powers of two) e.g. (multiplies by powers of two) e.g.

LSL #5 = multiply by 32LSL #5 = multiply by 32

Barrel Shifter - Left ShiftBarrel Shifter - Left Shift

Logical Shift Left (LSL)

DestinationCF 0

Page 101: Arm

Logical Shift Right Logical Shift Right • Shifts right by the Shifts right by the specified amount specified amount (divides by powers (divides by powers of two) e.g. of two) e.g.

LSR #5 = divide by LSR #5 = divide by 3232

Arithmetic Shift RightArithmetic Shift Right

• Shifts right (divides Shifts right (divides by powers of two) by powers of two) and preserves the and preserves the sign bit, for 2's sign bit, for 2's complement complement operations. e.g. operations. e.g.

ASR #5 = divide by ASR #5 = divide by 3232

Barrel Shifter - Right ShiftsBarrel Shifter - Right Shifts

Destination CF

Destination CF

Logical Shift Right

Arithmetic Shift Right

...0

Sign bit shifted in

Page 102: Arm

Barrel Shifter - Rotations Barrel Shifter - Rotations Rotate Right (ROR)Rotate Right (ROR)

•• Similar to an ASR Similar to an ASR but the bits wrap around but the bits wrap around as they leave the LSB and as they leave the LSB and appear as the MSB.appear as the MSB.

e.g. ROR #5e.g. ROR #5• Note the last bit rotated is Note the last bit rotated is also used as the Carry also used as the Carry Out.Out.

Rotate Right Extended Rotate Right Extended (RRX)(RRX)

• • This operation uses the This operation uses the CPSR C flag as a 33rd bit. CPSR C flag as a 33rd bit.

• Rotates right by 1 bit. Rotates right by 1 bit. Encoded as ROR #0.Encoded as ROR #0.

Destination CF

Rotate Right

Destination CF

Rotate Right through Carry

Page 103: Arm

Using the Barrel Shifter:Using the Barrel Shifter:The Second OperandThe Second Operand

* Immediate value

• 8 bit number

• Can be rotated right through an even number of positions.

• Assembler will calculate rotate for you from constant.

Register, optionally with Register, optionally with shift operation applied.shift operation applied.

Shift value can be either be:Shift value can be either be: 5 bit unsigned integer5 bit unsigned integer Specified in bottom byte Specified in bottom byte

of another register.of another register.

Operand 1

Result

ALU

Barrel Shifter

Operand 2

Page 104: Arm

Second Operand :Second Operand :Shifted RegisterShifted Register

The amount by which the register is to be The amount by which the register is to be shifted is contained in either: shifted is contained in either: the immediate 5-bit field in the instruction the immediate 5-bit field in the instruction

NO OVERHEAD NO OVERHEAD Shift is done for free - executes in single cycle.Shift is done for free - executes in single cycle.

the bottom byte of a register (not PC)the bottom byte of a register (not PC) Then takes extra cycle to executeThen takes extra cycle to execute ARM doesn’t have enough read ports to read 3 ARM doesn’t have enough read ports to read 3

registers at once.registers at once. Then same as on other processors where shift isThen same as on other processors where shift is

separate instruction.separate instruction. If no shift is specified then a default shift is applied: LSL #0If no shift is specified then a default shift is applied: LSL #0

i.e. barrel shifter has no effect on value in register.i.e. barrel shifter has no effect on value in register.

Page 105: Arm

Second Operand :Second Operand :Using a Shifted RegisterUsing a Shifted Register

Using a multiplication instruction to multiply by a constant Using a multiplication instruction to multiply by a constant means first loading the constant into a register and then means first loading the constant into a register and then waiting a number of internal cycles for the instruction to waiting a number of internal cycles for the instruction to complete.complete.

A more optimum solution can often be found by using some A more optimum solution can often be found by using some combination of MOVs, ADDs, SUBs and RSBs with shifts.combination of MOVs, ADDs, SUBs and RSBs with shifts. Multiplications by a constant equal to a ((power of 2) ± 1) Multiplications by a constant equal to a ((power of 2) ± 1)

can be done in one cycle.can be done in one cycle. Example: r0 = r1 * 5Example: r0 = r1 * 5

Example: r0 Example: r0 = r1 + (r1 * 4) = r1 + (r1 * 4) ADD r0, r1, r1, LSL #2ADD r0, r1, r1, LSL #2 Example: r2 = r3 * 105Example: r2 = r3 * 105

Example: r2 Example: r2 = r3 * 15 * 7= r3 * 15 * 7Example: r2Example: r2 = r3 * (16 - 1) * (8 - 1)= r3 * (16 - 1) * (8 - 1) RSB r2, r3, r3, LSL #4RSB r2, r3, r3, LSL #4 ; r2 = r3 * 15; r2 = r3 * 15

RSB r2, r2, r2, LSL #3RSB r2, r2, r2, LSL #3 ; r2 = r2 * 7; r2 = r2 * 7

Page 106: Arm

Second Operand :Second Operand :Immediate Value (1)Immediate Value (1)

There is no single instruction which will load a 32 bit immediate There is no single instruction which will load a 32 bit immediate constant into a register without performing a data load from constant into a register without performing a data load from memory.memory. All ARM instructions are 32 bits longAll ARM instructions are 32 bits long ARM instructions do not use the instruction stream as data.ARM instructions do not use the instruction stream as data.

The data processing instruction format has 12 bits available for The data processing instruction format has 12 bits available for operand2operand2 If used directly this would only give a range of 4096.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 - Instead it is used to store 8 bit constants, giving a range of 0 - 255.255.

These 8 bits can then be rotated right through an even number These 8 bits can then be rotated right through an even number of positions (ie RORs by 0, 2, 4,..30).of positions (ie RORs by 0, 2, 4,..30). This gives a much larger range of constants that can be This gives a much larger range of constants that can be

directly loaded, though some constants will still need to be directly loaded, though some constants will still need to be loaded loaded from memory.from memory.

Page 107: Arm

Second Operand :Second Operand :Immediate Value (2)Immediate Value (2)

This gives us:This gives us: 0 - 2550 - 255 [0 - 0xff][0 - 0xff] 256,260,264,..,1020256,260,264,..,1020 [0x100-0x3fc, step 4, 0x40-0xff [0x100-0x3fc, step 4, 0x40-0xff

ror 30]ror 30] 1024,1040,1056,..,40801024,1040,1056,..,4080 [0x400-0xff0, step 16, 0x40-0xff ror 28][0x400-0xff0, step 16, 0x40-0xff ror 28] 4096,4160, 4224,..,163204096,4160, 4224,..,16320 [0x1000-0x3fc0, step 64, 0x40-[0x1000-0x3fc0, step 64, 0x40-

0xff ror 26]0xff ror 26] These can be loaded using, for example:These can be loaded using, for example:

MOV r0, #0x40, 26MOV r0, #0x40, 26 ; => MOV r0, #0x1000 (ie ; => MOV r0, #0x1000 (ie 4096)4096)

To make this easier, the assembler will convert to this form for us if To make this easier, the assembler will convert to this form for us if simply given the required constant:simply given the required constant:

MOV r0, #4096MOV r0, #4096 ; => MOV r0, #0x1000 (ie 0x40 ror 26); => MOV r0, #0x1000 (ie 0x40 ror 26) The bitwise complements can also be formed using MVN:The bitwise complements can also be formed using MVN:

MOV r0, #0xFFFFFFFF MOV r0, #0xFFFFFFFF ; assembles to MVN r0, #0; assembles to MVN r0, #0 If the required constant cannot be generated, an error will If the required constant cannot be generated, an error will

be reported.be reported.

Page 108: Arm

Loading full 32 bit constantsLoading full 32 bit constants Although the MOV/MVN mechansim will load a large range of Although the MOV/MVN mechansim will load a large range of

constants into a register, sometimes this mechansim will not constants into a register, sometimes this mechansim will not generate the required constant.generate the required constant.

Therefore, the assembler also provides a method which will Therefore, the assembler also provides a method which will load load ANYANY 32 bit constant: 32 bit constant: LDR rd,=numeric constantLDR rd,=numeric constant

If the constant can be constructed using either a MOV or MVN If the constant can be constructed using either a MOV or MVN then this will be the instruction actually generated.then this will be the instruction actually generated.

Otherwise, the assembler will produce an LDR instruction with Otherwise, the assembler will produce an LDR instruction with a PC-relative address to read the constant from a literal pool.a PC-relative address to read the constant from a literal pool. LDR r0,=0x42LDR r0,=0x42; generates MOV r0,#0x42; generates MOV r0,#0x42 LDR r0,=0x55555555LDR r0,=0x55555555; generate LDR r0,[pc, offset to ; generate LDR r0,[pc, offset to lit pool]lit pool]

As this mechanism will always generate the best instruction for As this mechanism will always generate the best instruction for a given case, it is the recommended way of loading constants.a given case, it is the recommended way of loading constants.

Page 109: Arm

Multiplication InstructionsMultiplication Instructions The Basic ARM provides two multiplication instructions.The Basic ARM provides two multiplication instructions. MultiplyMultiply

MUL{<cond>}{S} Rd, Rm, RsMUL{<cond>}{S} Rd, Rm, Rs ; Rd = Rm * Rs; Rd = Rm * Rs Multiply AccumulateMultiply Accumulate - does addition for free- does addition for free

MLA{<cond>}{S} Rd, Rm, Rs,RnMLA{<cond>}{S} Rd, Rm, Rs,Rn ; Rd = (Rm * Rs) + ; Rd = (Rm * Rs) + RnRn

Restrictions on use:Restrictions on use: Rd and Rm cannot be the same registerRd and Rm cannot be the same register

Can be avoid by swapping Rm and Rs around. This Can be avoid by swapping Rm and Rs around. This works because multiplication is commutative.works because multiplication is commutative.

Cannot use PC.Cannot use PC.These will be picked up by the assembler if overlooked.These will be picked up by the assembler if overlooked.

Operands can be considered signed or unsignedOperands can be considered signed or unsigned Up to user to interpret correctly.Up to user to interpret correctly.

Page 110: Arm

Multiply-Long andMultiply-Long andMultiply-Accumulate LongMultiply-Accumulate Long

Instructions areInstructions are MULL which gives RdHi,RdLo:=Rm*Rs MULL which gives RdHi,RdLo:=Rm*Rs MLAL which gives RdHi,RdLo:=(Rm*Rs)+RdHi,RdLoMLAL which gives RdHi,RdLo:=(Rm*Rs)+RdHi,RdLo

However the full 64 bit of the result now matter (lower However the full 64 bit of the result now matter (lower precision multiply instructions simply throws top 32bits away)precision multiply instructions simply throws top 32bits away)

Need to specify whether operands are signed or unsignedNeed to specify whether operands are signed or unsigned Therefore syntax of new instructions are:Therefore syntax of new instructions are:

UMULL{<cond>}{S} RdLo,RdHi,Rm,RsUMULL{<cond>}{S} RdLo,RdHi,Rm,Rs UMLAL{<cond>}{S} RdLo,RdHi,Rm,RsUMLAL{<cond>}{S} RdLo,RdHi,Rm,Rs SMULL{<cond>}{S} RdLo, RdHi, Rm, RsSMULL{<cond>}{S} RdLo, RdHi, Rm, Rs SMLAL{<cond>}{S} RdLo, RdHi, Rm, RsSMLAL{<cond>}{S} RdLo, RdHi, Rm, Rs

Not generated by the compiler.Not generated by the compiler.Warning : Unpredictable on non-M ARMs.Warning : Unpredictable on non-M ARMs.

Page 111: Arm

ExampleExample1. Specify instructions which will implement the following:1. Specify instructions which will implement the following:

a) r0 = 16a) r0 = 16 b) r1 = r0 * 4 b) r1 = r0 * 4

c) r0 = r1 / 16 ( r1 signed 2's comp.)c) r0 = r1 / 16 ( r1 signed 2's comp.) d) r1 = r2 * 7d) r1 = r2 * 7

2. What will the following instructions do?2. What will the following instructions do?

a) ADDS r0, r1, r1, LSL #2a) ADDS r0, r1, r1, LSL #2 b) RSB r2, r1, #0b) RSB r2, r1, #0

3. What does the following instruction sequence do?3. What does the following instruction sequence do?ADD r0, r1, r1, LSL #1ADD r0, r1, r1, LSL #1SUB r0, r0, r1, LSL #4SUB r0, r0, r1, LSL #4ADD r0, r0, r1, LSL #7ADD r0, r0, r1, LSL #7

Page 112: Arm

Load / Store InstructionsLoad / Store Instructions The ARM is a Load / Store Architecture:The ARM is a Load / Store Architecture:

Does not support memory to memory data processing Does not support memory to memory data processing operations.operations.

Must move data values into registers before using them.Must move data values into registers before using them. This might sound inefficient, but in practice isn’t:This might sound inefficient, but in practice isn’t:

Load data values from memory into registers.Load data values from memory into registers. Process data in registers using a number of data Process data in registers using a number of data

processing instructions which are not slowed down by processing instructions which are not slowed down by memory access.memory access.

Store results from registers out to memory.Store results from registers out to memory. The ARM has three sets of instructions which interact with The ARM has three sets of instructions which interact with

main memory. These are:main memory. These are: Single register data transfer (LDR / STR).Single register data transfer (LDR / STR). Block data transfer (LDM/STM).Block data transfer (LDM/STM). Single Data Swap (SWP).Single Data Swap (SWP).

Page 113: Arm

Single register data transferSingle register data transfer The basic load and store instructions are:The basic load and store instructions are:

Load and Store Word or ByteLoad and Store Word or Byte LDR / STR / LDRB / STRBLDR / STR / LDRB / STRB

ARM Architecture Version 4 also adds support for halfwords ARM Architecture Version 4 also adds support for halfwords and signed data.and signed data.

Load and Store HalfwordLoad and Store Halfword LDRH / STRHLDRH / STRH

Load Signed Byte or Halfword - load value and sign extend Load Signed Byte or Halfword - load value and sign extend it to 32 bits.it to 32 bits.

LDRSB / LDRSHLDRSB / LDRSH All of these instructions can be conditionally executed by All of these instructions can be conditionally executed by

inserting the appropriate condition code after STR / LDR.inserting the appropriate condition code after STR / LDR. e.g. LDREQBe.g. LDREQB

Syntax:Syntax: <LDR|STR>{<cond>}{<size>} Rd, <address><LDR|STR>{<cond>}{<size>} Rd, <address>

Page 114: Arm

Load and Store Word or Byte:Load and Store Word or Byte: Base Register Base Register

The memory location to be accessed is held in a base The memory location to be accessed is held in a base registerregister STR r0, [r1]STR r0, [r1] ; Store contents of r0 to location pointed ; Store contents of r0 to location pointed

toto; by contents of r1.; by contents of r1.

LDR r2, [r1]LDR r2, [r1] ; Load r2 with contents of memory ; Load r2 with contents of memory locationlocation

; pointed to by contents of r1.; pointed to by contents of r1.

r1

0x200Base

Register

Memory

0x50x200

r0

0x5Source

Registerfor STR

r2

0x5Destination

Registerfor LDR

Page 115: Arm

Load and Store Word or Byte:Load and Store Word or Byte: Offsets from the Base Register Offsets from the Base Register

As well as accessing the actual location contained in the base As well as accessing the actual location contained in the base register, these instructions can access a location offset from the register, these instructions can access a location offset from the base register pointer.base register pointer.

This offset can beThis offset can be An unsigned 12bit immediate value (ie 0 - 4095 bytes).An unsigned 12bit immediate value (ie 0 - 4095 bytes). A register, optionally shifted by an immediate valueA register, optionally shifted by an immediate value

This can be either added or subtracted from the base register:This can be either added or subtracted from the base register: Prefix the offset value or register with ‘Prefix the offset value or register with ‘++’ (default) or ‘’ (default) or ‘--’.’.

This offset can be applied:This offset can be applied: before the transfer is made: before the transfer is made: Pre-indexed addressingPre-indexed addressing

optionallyoptionally auto-incrementingauto-incrementing the base register, by the base register, by postfixing the instruction with an ‘postfixing the instruction with an ‘!!’.’.

after the transfer is made: after the transfer is made: Post-indexed addressingPost-indexed addressing causing the base register to be causing the base register to be auto-incrementedauto-incremented..

Page 116: Arm

Load and Store Word or Byte:Load and Store Word or Byte:Pre-indexed AddressingPre-indexed Addressing

Example: Example: STR r0, [r1,#12]STR r0, [r1,#12]

To store to location 0x1f4 instead use: To store to location 0x1f4 instead use: STR r0, [r1,#-12]STR r0, [r1,#-12] To auto-increment base pointer to 0x20c use: To auto-increment base pointer to 0x20c use: STR r0, [r1, STR r0, [r1,

#12]!#12]! If r2 contains 3, access 0x20c by multiplying this by 4:If r2 contains 3, access 0x20c by multiplying this by 4:

STR r0, [r1, r2, LSL #2]STR r0, [r1, r2, LSL #2]

r1

0x200Base

Register

Memory

0x5

0x200

r0

0x5Source

Registerfor STR

Offset

12 0x20c

Page 117: Arm

Load and Store Word or Byte:Load and Store Word or Byte:Post-indexed AddressingPost-indexed Addressing

Example: Example: STR r0, [r1], #12STR r0, [r1], #12

To auto-increment the base register to location 0x1f4 instead To auto-increment the base register to location 0x1f4 instead use:use:

STR r0, [r1], #-12STR r0, [r1], #-12 If r2 contains 3, auto-incremenet base register to 0x20c by If r2 contains 3, auto-incremenet base register to 0x20c by

multiplying this by 4:multiplying this by 4: STR r0, [r1], r2, LSL #2STR r0, [r1], r2, LSL #2

r1

0x200Original

BaseRegister

Memory

0x50x200

r0

0x5Source

Registerfor STR

Offset

12 0x20c

r1

0x20cUpdatedBaseRegister

Page 118: Arm

Example Usage ofExample Usage ofAddressing ModesAddressing Modes

Imagine an array, the first element of which is pointed to by Imagine an array, the first element of which is pointed to by the contents of r0.the contents of r0.

If we want to access a particular element,If we want to access a particular element,then we can use pre-indexed addressing:then we can use pre-indexed addressing:

r1 is element we want.r1 is element we want. LDR r2, [r0, r1, LSL #2]LDR r2, [r0, r1, LSL #2]

If we want to step through everyIf we want to step through everyelement of the array, for instanceelement of the array, for instanceto produce sum of elements in theto produce sum of elements in thearray, then we can use post-indexed addressing within a loop:array, then we can use post-indexed addressing within a loop:

r1 is address of current element (initially equal to r0).r1 is address of current element (initially equal to r0). LDR r2, [r1], #4LDR r2, [r1], #4

Use a further register to store the address of final element,Use a further register to store the address of final element,so that the loop can be correctly terminated.so that the loop can be correctly terminated.

0

1

2

3

element

0

4

8

12

Memory Offset

r0

Pointer to start of array

Page 119: Arm

Offsets for Halfword and Signed Offsets for Halfword and Signed Halfword / Byte AccessHalfword / Byte Access

The Load and Store Halfword and Load The Load and Store Halfword and Load Signed Byte or Halfword instructions can Signed Byte or Halfword instructions can make use of pre- and post-indexed make use of pre- and post-indexed addressing in much the same way as the addressing in much the same way as the basic load and store instructions.basic load and store instructions.

However the actual offset formats are more However the actual offset formats are more constrained:constrained: The immediate value is limited to 8 bits (rather The immediate value is limited to 8 bits (rather

than 12 bits) giving an offset of 0-255 bytes.than 12 bits) giving an offset of 0-255 bytes. The register form cannot have a shift applied to The register form cannot have a shift applied to

it.it.

Page 120: Arm

Effect of endianessEffect of endianess

The ARM can be set up to access its data in The ARM can be set up to access its data in either little or big endian format. either little or big endian format.

Little endian:Little endian: Least significant byte of a word is stored in Least significant byte of a word is stored in bits 0-7 bits 0-7

of an addressed word.of an addressed word. Big endian:Big endian:

Least significant byte of a word is stored in Least significant byte of a word is stored in bits 24-bits 24-31 31 of an addressed word.of an addressed word.

This has no real relevance unless data is This has no real relevance unless data is stored as words and then accessed in smaller stored as words and then accessed in smaller sized quantities (halfwords or bytes).sized quantities (halfwords or bytes). Which byte / halfword is accessed will depend on Which byte / halfword is accessed will depend on

the endianess of the system involved.the endianess of the system involved.

Page 121: Arm

Endianess ExampleEndianess Example

Big-endianLittle-endian

r1 = 0x100

r0 = 0x1122334431 24 23 16 15 8 7 0

11 22 33 44

31 24 23 16 15 8 7 0

11 22 33 44

31 24 23 16 15 8 7 0

44 33 22 11

31 24 23 16 15 8 7 0

00 00 00 44

31 24 23 16 15 8 7 0

00 00 00 11

r2 = 0x44 r2 = 0x11

STR r0, [r1]

LDRB r2, [r1]

r1 = 0x100Memory

Page 122: Arm

ExampleExample Write a segment of code that add together elements x to Write a segment of code that add together elements x to

x+(n-1) of an array, where the element x=0 is the first x+(n-1) of an array, where the element x=0 is the first element of the array.element of the array.

Each element of the array is word sized (ie. 32 bits).Each element of the array is word sized (ie. 32 bits). The segment should use post-indexed addressing.The segment should use post-indexed addressing. At the start of your segments, you should assume that:At the start of your segments, you should assume that:

r0 points to the start of the array.r0 points to the start of the array. r1 = xr1 = x r2 = nr2 = n

r0

x

x + 1

x + (n - 1)

Elements

{n elements

0

Page 123: Arm

Sample SolutionSample Solution

ADD r0, r0, r1, LSL#2ADD r0, r0, r1, LSL#2 ; Set r0 to address of element x; Set r0 to address of element x

ADD r2, r0, r2, LSL#2ADD r2, r0, r2, LSL#2 ; Set r2 to address of element ; Set r2 to address of element n+1n+1

MOV r1, #0MOV r1, #0 ; Initialise counter; Initialise counter

looploop

LDR r3, [r0], #4LDR r3, [r0], #4 ; Access element and move to ; Access element and move to nextnext

ADD r1, r1, r3ADD r1, r1, r3 ; Add contents to counter; Add contents to counter

CMP r0, r2CMP r0, r2 ; Have we reached element x+n?; Have we reached element x+n?

BLT loopBLT loop ; If not - repeat for ; If not - repeat for ; ; next element next element

; on exit sum contained; on exit sum contained in r1 in r1

Page 124: Arm

Block Data Transfer (1)Block Data Transfer (1)

Cond 1 0 0 P U S W L Rn Register list

Condition field Base register

Load/Store bit0 = Store to memory1 = Load from memory

Write- back bit0 = no write-back1 = write address into base

PSR and force user bit0 = don’t load PSR or force user mode1 = load PSR or force user mode

Up/Down bit0 = Down; subtract offset from base1 = Up ; add offset to base

Pre/Post indexing bit0 = Post; add offset after transfer,1 = Pre ; add offset before transfer

2831 22 16 023 21 1527 20 1924

Each bit corresponds to a particular register. For example:• Bit 0 set causes r0 to be transferred.• Bit 0 unset causes r0 not to be transferred.At least one register must be transferred as the list cannot be empty.

The Load and Store Multiple instructions (LDM / STM) allow The Load and Store Multiple instructions (LDM / STM) allow betweeen 1 and 16 registers to be transferred to or from betweeen 1 and 16 registers to be transferred to or from memory.memory.

The transferred registers can be either:The transferred registers can be either: Any subset of the current bank of registers (default).Any subset of the current bank of registers (default). Any subset of the user mode bank of registers when in a Any subset of the user mode bank of registers when in a

priviledged mode (postfix instruction with a ‘priviledged mode (postfix instruction with a ‘^̂’).’).

Page 125: Arm

Block Data Transfer (2)Block Data Transfer (2) Base register used to determine where Base register used to determine where

memory access should occur.memory access should occur. 4 different addressing modes allow increment and 4 different addressing modes allow increment and

decrement inclusive or exclusive of the base register decrement inclusive or exclusive of the base register location.location.

Base register can be optionally updated following Base register can be optionally updated following the transfer (by appending it with an ‘the transfer (by appending it with an ‘!!’.’.

Lowest register number is always transferred Lowest register number is always transferred to/from lowest memory location accessed.to/from lowest memory location accessed.

These instructions are very efficient forThese instructions are very efficient for Saving and restoring contextSaving and restoring context

For this useful to view memory as a stack.For this useful to view memory as a stack. Moving large blocks of data around memoryMoving large blocks of data around memory

For this useful to directly represent functionality of the For this useful to directly represent functionality of the instructions.instructions.

Page 126: Arm

StacksStacks A stack is an area of memory which grows as new data is 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 “pushed” onto the “top” of it, and shrinks as data is “popped” off the top.the top.

Two pointers define the current limits of the stack.Two pointers define the current limits of the stack. A base pointer A base pointer

used to point to the “bottom” of the stack (the first used to point to the “bottom” of the stack (the first location).location).

A stack pointerA stack pointer used to point the current “top” of the stack. used to point the current “top” of the stack.

SPBASE

PUSH {1,2,3}

1

2

3

BASE

SP

POP

1

2Result of pop = 3

BASE

SP

Page 127: Arm

Stack OperationStack Operation Traditionally, a stack grows down in memory, with the last Traditionally, a stack grows down in memory, with the last

“pushed” value at the lowest address. The ARM also supports “pushed” value at the lowest address. The ARM also supports ascending stacks, where the stack structure grows up through ascending stacks, where the stack structure grows up through memory. memory.

The value of the stack pointer can either:The value of the stack pointer can either: Point to the last occupied address (Full stack)Point to the last occupied address (Full stack)

and so needs pre-decrementing (ie before the push)and so needs pre-decrementing (ie before the push) Point to the next occupied address (Empty stack)Point to the next occupied address (Empty stack)

and so needs post-decrementing (ie after the push)and so needs post-decrementing (ie after the push) The stack type to be used is given by the postfix to the instruction:The stack type to be used is given by the postfix to the instruction:

STMFD / LDMFD : Full Descending stackSTMFD / LDMFD : Full Descending stack STMFA / LDMFA : Full Ascending stack.STMFA / LDMFA : Full Ascending stack. STMED / LDMED : Empty Descending stackSTMED / LDMED : Empty Descending stack STMEA / LDMEA : Empty Ascending stackSTMEA / LDMEA : Empty Ascending stack

Note: ARM Compiler will always use a Full descending stack.Note: ARM Compiler will always use a Full descending stack.

Page 128: Arm

Stack ExamplesStack ExamplesSTMFD sp!,

{r0,r1,r3-r5}

r5

r4

r3r1

r0SP

Old SP

STMED sp!,{r0,r1,r3-r5}

r5

r4r3r1

r0SP

Old SP

r5

r4r3r1

r0

STMFA sp!,{r0,r1,r3-r5}

SP

Old SP 0x400

0x418

0x3e8

STMEA sp!,{r0,r1,r3-r5}

r5

r4r3r1

r0

SP

Old SP

Page 129: Arm

Stacks and SubroutinesStacks and Subroutines One use of stacks is to create temporary register One use of stacks is to create temporary register

workspace for subroutines. Any registers that are workspace for subroutines. Any registers that are needed can be pushed onto the stack at the start of needed can be pushed onto the stack at the start of the subroutine and popped off again at the end so the subroutine and popped off again at the end so as to restore them before return to the caller :as to restore them before return to the caller :

STMFD sp!,{r0-r12, lr}STMFD sp!,{r0-r12, lr} ; stack all ; stack all registersregisters

................ ; and the return address; and the return address

................LDMFD sp!,{r0-r12, pc}LDMFD sp!,{r0-r12, pc} ; load all the ; load all the registersregisters

; and return ; and return automaticallyautomatically

Page 130: Arm

Direct functionality ofDirect functionality ofBlock Data TransferBlock Data Transfer

When LDM / STM are not being used to When LDM / STM are not being used to implement stacks, it is clearer to specify implement stacks, it is clearer to specify exactly what functionality of the instruction exactly what functionality of the instruction is:is: i.e. specify whether to increment / decrement the i.e. specify whether to increment / decrement the

base pointer, before or after the memory access.base pointer, before or after the memory access. In order to do this, LDM / STM support a In order to do this, LDM / STM support a

further syntax in addition to the stack one: further syntax in addition to the stack one: STMIA / LDMIA : Increment AfterSTMIA / LDMIA : Increment After STMIB / LDMIB : Increment BeforeSTMIB / LDMIB : Increment Before STMDA / LDMDA : Decrement AfterSTMDA / LDMDA : Decrement After STMDB / LDMDB : Decrement BeforeSTMDB / LDMDB : Decrement Before

Page 131: Arm

Example: Block CopyExample: Block Copy

Copy a block of memory, which is an exact multiple of 12 Copy a block of memory, which is an exact multiple of 12 words long from the location pointed to by r12 to the location 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.pointed to by r13. r14 points to the end of block to be copied.

; r12 points to the start of the source data; r12 points to the start of the source data; r14 points to the end of the source data; r14 points to the end of the source data; r13 points to the start of the destination data; r13 points to the start of the destination datalooploop LDMIALDMIA r12!, {r0-r11}r12!, {r0-r11} ; load 48 bytes; load 48 bytes

STMIASTMIA r13!, {r0-r11}r13!, {r0-r11} ; and store them; and store themCMPCMP r12, r14r12, r14 ; check for the end; check for the endBNEBNE looploop ; and loop until done; and loop until done

This loop transfers 48 bytes in 31 cyclesThis loop transfers 48 bytes in 31 cycles Over 50 Mbytes/sec at 33 MHzOver 50 Mbytes/sec at 33 MHz

r13

r14

r12

IncreasingMemory

Page 132: Arm

Quiz Quiz The contents of registers r0 to r6 need to be The contents of registers r0 to r6 need to be

swapped around thus:swapped around thus: r0 moved into r3r0 moved into r3 r1 moved into r4r1 moved into r4 r2 moved into r6r2 moved into r6 r3 moved into r5r3 moved into r5 r4 moved into r0r4 moved into r0 r5 moved into r1r5 moved into r1 r6 moved into r2r6 moved into r2

Write a segment of code that uses full Write a segment of code that uses full descending stack operations to carry this out, descending stack operations to carry this out, and hence requires no use of any other registers and hence requires no use of any other registers for temporary storage.for temporary storage.

Page 133: Arm

Quiz - Sample SolutionQuiz - Sample Solution

STMFD sp!,{r0-r6}

LDMFD sp!,{r3,r4,r6}

r3 = r0r4 = r1r6 = r2

LDMFD sp!,{r5}

r5 = r3

LDMFD sp!,{r0-r2}

r0 = r4r1 = r5r2 = r6

Old SP

r5

r4

r3r2

r1SP

r6

r0

r5

r4SP

r6

r3

r5SP

r6

r4

SP

Page 134: Arm

quantities between registers and memory. quantities between registers and memory. Syntax:Syntax:

SWP{<cond>}{B} Rd, Atomic operation of a memory read SWP{<cond>}{B} Rd, Atomic operation of a memory read followed by a memory write which moves byte or word Rm, followed by a memory write which moves byte or word Rm, [Rn][Rn]

Thus to implement an actual swap of contents make Rd Thus to implement an actual swap of contents make Rd = Rm.= Rm.

The compiler cannot produce this instruction.The compiler cannot produce this instruction.

Swap and Swap Byte Swap and Swap Byte InstructionsInstructions

Rm Rd

Rn

32

1temp

Memory

Page 135: Arm

Software Interrupt (SWI)Software Interrupt (SWI)

In effect, a SWI is a user-defined instruction.In effect, a SWI is a user-defined instruction. It causes an exception trap to the SWI hardware vector (thus It causes an exception trap to the SWI hardware vector (thus

causing a change to supervisor mode, plus the associated state causing a change to supervisor mode, plus the associated state saving), thus causing the SWI exception handler to be called.saving), thus causing the SWI exception handler to be called.

The handler can then examine the comment field of the The handler can then examine the comment field of the instruction to decide what operation has been requested.instruction to decide what operation has been requested.

By making use of the SWI mechansim, an operating system By making use of the SWI mechansim, an operating system can implement a set of privileged operations which can implement a set of privileged operations which applications running in user mode can request.applications running in user mode can request.

See Exception Handling Module for further details.See Exception Handling Module for further details.

2831 2427 0

Cond 1 1 1 1 Comment field (ignored by Processor)

Condition Field

23

Page 136: Arm

Main features of theMain features of theARM Instruction SetARM Instruction Set

All instructions are 32 bits long.All instructions are 32 bits long. Most instructions execute in a single cycle.Most instructions execute in a single cycle. Every instruction can be conditionally executed.Every instruction can be conditionally executed. A load/store architecture A load/store architecture

Data processing instructions act only on registersData processing instructions act only on registers Three operand formatThree operand format Combined ALU and shifter for high speed bit manipulationCombined ALU and shifter for high speed bit manipulation

Specific memory access instructions with powerful Specific memory access instructions with powerful auto-indexing addressing modes.auto-indexing addressing modes.

32 bit and 8 bit data types32 bit and 8 bit data types and also 16 bit data types on ARM Architecture v4.and also 16 bit data types on ARM Architecture v4.

Flexible multiple register load and store instructionsFlexible multiple register load and store instructions Instruction set extension via coprocessorsInstruction set extension via coprocessors

Page 137: Arm

Operating StatesOperating States

Supports 2 instruction setsSupports 2 instruction sets

ARM – 32 bit instruction setARM – 32 bit instruction set

Thumb – 16 bit instruction setThumb – 16 bit instruction set

Page 138: Arm

ARM StateARM State

Able to access more large Able to access more large memories efficientlymemories efficiently

32 bit integer arithmetic in a single 32 bit integer arithmetic in a single cyclecycle

More number of instructionsMore number of instructions Better performanceBetter performance

Page 139: Arm

Thumb Mode: What is Thumb?Thumb Mode: What is Thumb?

大拇指大拇指 Thumb ISA: 16-bit instruction, dynamically Thumb ISA: 16-bit instruction, dynamically

decompressed into ARM Instruction before decompressed into ARM Instruction before executionexecution

Fewer directly accessible GPRs (Only R0-Fewer directly accessible GPRs (Only R0-R8)R8)

The CPU can be switched between ARM The CPU can be switched between ARM ISA mode and Thumb ISA mode ISA mode and Thumb ISA mode dynamicallydynamically

Page 140: Arm

Switching StateSwitching State

ARM to ThumbARM to Thumb Execute the Execute the BX BX instruction with state instruction with state

bit=1bit=1

Thumb to ARMThumb to ARM

Execute the Execute the BX BX instruction with state instruction with state bit=0bit=0

An interrupt or exception occursAn interrupt or exception occurs

Page 141: Arm

Which state to useWhich state to use

Low memory systemLow memory system : use thumb : use thumb 16 bit memory16 bit memory : use thumb : use thumb Performance is criticalPerformance is critical : use ARM : use ARM

Example : in execution of interrupt Example : in execution of interrupt routinesroutines

Performance is critical Performance is critical AND AND Memory is lowMemory is low : use both ARM and : use both ARM and thumbthumb

exampleexample : in interrupt routines : in interrupt routines

Page 142: Arm

Thumb Decode StageThumb Decode Stage

Page 143: Arm

ARM ThumbARM 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 ofprocessor system. Instructions take only half of memory than with 32-bitinstruction set without significant decrease in performance or increase incode size.• Extension is made to instruction decoder at the processor pipeline• Registers are preserved as 32-bit but only half of them are available

Page 144: Arm

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 wordfrom the 32-bit bus•

Example ADD Rd,# 8 bit connstsnt

Page 145: Arm

Thumb State RegistersThumb State Registers

Page 146: Arm
Page 147: Arm

THUMB ENTRYTHUMB 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.

Page 148: Arm

THUMB EXITTHUMB 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.

Page 149: Arm

THUMB SYSTEMSTHUMB 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.

Page 150: Arm

Thumb-ARMSimilarities

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.

Page 151: Arm

Thumb – Arm DifferencesThumb – Arm Differences 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

2-address 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.

Page 152: Arm

Thumb ExceptionsThumb 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.

Page 153: Arm

The Instruction PipelineThe Instruction Pipeline The ARM uses a pipeline in order to increase the speed of the The ARM uses a pipeline in order to increase the speed of the

flow of instructions to the processor.flow of instructions to the processor. Allows several operations to be undertaken simultaneously, Allows several operations to be undertaken simultaneously,

rather than serially.rather than serially.

Rather than pointing to the instruction being Rather than pointing to the instruction being executed, the executed, the PC points to the instruction being fetched.PC points to the instruction being fetched.

FETCH

DECODE

EXECUTE

Instruction fetched from memory

Decoding of registers used in instruction

Register(s) read from Register BankShift and ALU operationWrite register(s) back to Register Bank

PC

PC - 4

PC - 8

ARM

Page 154: Arm
Page 155: Arm

Thumb branch instructions

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.

Page 156: Arm

Thumb Branch Instruction Binary Thumb Branch Instruction Binary CodingCoding

Page 157: Arm

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

Page 158: Arm

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.

Page 159: Arm

Format 3a- is available only in Format 3a- is available only in architecture v5T.architecture v5T.

Assembler Format of Branch InstrnsAssembler 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

Page 160: Arm

Thumb data processing instructions

Page 161: Arm

Description of Data processing InstnDescription of Data processing Instn

Page 162: Arm

Examples of Eq.Arm D.P.I. Examples of Eq.Arm D.P.I. 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

Page 163: Arm

Thumb single register data transfer instructions

Page 164: Arm
Page 165: Arm

Description & Assembler Description & Assembler FormatFormat

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

Page 166: Arm

Thumb multiple register data transfer instructions

Thumb multiple register transfer instructions are useful both for procedure entry and return and for memory block copy

Page 167: Arm

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}}

Page 168: Arm

Equivalent ARMInstruction

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}}

Page 169: Arm

Thumb implementation

Page 170: Arm

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.

Page 171: Arm

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 off-chip Thumb code for all non-critical routines.

Page 172: Arm

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.

Page 173: Arm

ARM architectureARM architecture

Architecture versionArchitecture version Version 1 (obsolete)Version 1 (obsolete)

Basic data processingBasic data processing Byte, word and multi-word load/storeByte, word and multi-word load/store Software interruptSoftware interrupt 26 bit address bus26 bit address bus No Multiply & Coprocessor SupportNo Multiply & Coprocessor Support

Version 2 (obsolete)Version 2 (obsolete) MultiplyMultiply Coprocessor supportCoprocessor support 26 bit address bus26 bit address bus First ARM with on-chip Cache (Coprocessor CP15)First ARM with on-chip Cache (Coprocessor CP15) SWAP Instruction IntroducedSWAP Instruction Introduced

Page 174: Arm

ARM architectureARM architecture Architecture version (cont’d)Architecture version (cont’d)

Version 3Version 3 32 bit address bus32 bit address bus Separate CPSR, SPSRSeparate CPSR, SPSR

Add MRS, MSR. Modify exception handlerAdd MRS, MSR. Modify exception handler Add ‘Abort Mode’ and ‘Undef Mode’Add ‘Abort Mode’ and ‘Undef Mode’ Was Backward Compatible with 26-bitWas Backward Compatible with 26-bit MUL & MLAMUL & MLA

Version 4Version 4 Half word transferHalf word transfer Introduce THUMB processor stateIntroduce THUMB processor state Add ‘Privileged mode’ for operating systemAdd ‘Privileged mode’ for operating system 2 word distance of PC from current instruction2 word distance of PC from current instruction

‘‘PC+8’ behavior (at ARM state)PC+8’ behavior (at ARM state) First fully formalized architectureFirst fully formalized architecture

Page 175: Arm

ARM architectureARM architecture

Architecture version (cont’d)Architecture version (cont’d) Version 5Version 5

Improve ARM/THUMB inter-workingImprove ARM/THUMB inter-working Add CLZ instruction for efficient integer Add CLZ instruction for efficient integer

dividedivide Add software breakpointAdd software breakpoint Add more coprocessor supportAdd more coprocessor support More tight definition of arithmetic flagsMore tight definition of arithmetic flags

Page 176: Arm

ARM architectureARM architecture

Architecture VariantsArchitecture Variants THUMB ( symbol as a ‘T’)THUMB ( symbol as a ‘T’)

THUMB instruction set: 16 bit re-encoded subset of 32 bit THUMB instruction set: 16 bit re-encoded subset of 32 bit ARM instruction setARM instruction set

Small code size ( up to 40 % compression)Small code size ( up to 40 % compression) Simplified designSimplified design

Page 177: Arm

ARM RoadmapARM Roadmap

Page 178: Arm

ARM architectureARM architecture

Architecture Variants (cont’d)Architecture Variants (cont’d) Long Multiply Instruction (‘M’ variant)Long Multiply Instruction (‘M’ variant)

32x32 = 64 bit. Provide full 64 bit result32x32 = 64 bit. Provide full 64 bit result Enhanced DSP instructions (‘E’ variant)Enhanced DSP instructions (‘E’ variant)

Carefully chosen addition to native ARM instruction Carefully chosen addition to native ARM instruction for DSP applicationfor DSP application

SaturationSaturation 64 bit transfer64 bit transfer First introduced in v5First introduced in v5

Variants in Processor coreVariants in Processor core D: On-chip debug. Halt in responseD: On-chip debug. Halt in response I: Embedded ICE. On-chip breakpointI: Embedded ICE. On-chip breakpoint

Page 179: Arm

Processor CoresProcessor Cores ARM7ARM7

Two main blocks: datapath and Two main blocks: datapath and decoderdecoder

Register bank (r0 to r15)Register bank (r0 to r15) Two read ports to A- bus/ B- Two read ports to A- bus/ B-

busbus One write port from ALU- busOne write port from ALU- bus Additional read/ write ports for Additional read/ write ports for

program counter r15program counter r15 Barrel shifter / ALUBarrel shifter / ALU Address registers/ incrementerAddress registers/ incrementer

Single Memory PortSingle Memory Port holds either PC address holds either PC address

(with increment) or operand (with increment) or operand addressaddress

multiply

data out register

instruction

decode

&

control

incrementer

registerbank

address register

barrelshifter

A[31:0]

D[31:0]

data in register

ALU

control

PC

PC

ALU bus

A bus

B bus

register

Page 180: Arm

Processor CoresProcessor Cores ARM7 (cont’d)ARM7 (cont’d)

Pipeline: 3 Stage pipelinePipeline: 3 Stage pipeline Fetch : fetch instruction code from memory into the Fetch : fetch instruction code from memory into the

instruction pipelineinstruction pipeline Decode : instruction decoded to obtain control signals for Decode : instruction decoded to obtain control signals for

the datapath ready for the next stagethe datapath ready for the next stage Execute : instruction “owns” the datapath - register read; Execute : instruction “owns” the datapath - register read;

shifting; ALU results generated and write- backshifting; ALU results generated and write- back

fetch decode execute

time

1

fetch decode execute

fetch decode execute

2

3instruction

PC PC+4

PC+4 PC+8

R15

Page 181: Arm

Processor CoresProcessor Cores ARM7(cont’d)ARM7(cont’d)

Multi-cycle operationMulti-cycle operation Single cycle throughput for almost simple Single cycle throughput for almost simple

data processing instructiondata processing instruction Multi-cycle for mul, load/storeMulti-cycle for mul, load/store

fetch ADD decode execute

time

1

fetch STR decode calc. addr.

fetch ADD decode execute

2

3

data xfer

fetch ADD decode execute4

5 fetch ADD decode execute

instruction

ADDSTR

ADDADD

ADD

Page 182: Arm
Page 183: Arm

ARM Processor Cores

• The main ARM cores used today are:

ARM7TDMI – small, cheap

ARM9TDMI – moderate performance

ARM10TDMI – high performance

Page 184: Arm

ARM 7TDMIARM 7TDMI Version 4Version 4 SupportsSupports

TThumb : 16 bit compressed instruction sethumb : 16 bit compressed instruction set DDebug : On chip debug supportebug : On chip debug support Enhanced Enhanced MMultiply : higher performance, ultiply : higher performance,

long multiplylong multiply Embedded Embedded IICE hardwareCE hardware

Von neumann ArchitectureVon neumann Architecture 32 bit data bus32 bit data bus Data size can be byte , half word, or wordData size can be byte , half word, or word Words : 4 byte alignedWords : 4 byte aligned Half word : 2 byte alignedHalf word : 2 byte aligned

Page 185: Arm

ARM7TDMI PipelineARM7TDMI Pipeline

1. Fetch

2. Decode

3. Execute

ARM7

1. Fetch

2. Decode

3. Execute

4. Data/Buffer

5. Write Back

ARM9

Page 186: Arm
Page 187: Arm
Page 188: Arm

The Thumb Mode: Why The Thumb Mode: Why Thumb?Thumb?

Addresses higher code density by Addresses higher code density by packing common instructions into packing common instructions into 16-bit16-bit Reduces bus width and activitiesReduces bus width and activities Datapath remain unchanged, thus still Datapath remain unchanged, thus still

32-bit32-bit In an typical application, In an typical application,

performance-sensitive code can be in performance-sensitive code can be in ARM ISA, while other code in ThumbARM ISA, while other code in Thumb Denser code, less performance impactDenser code, less performance impact

Page 189: Arm

ARM/THUMB Mode switchARM/THUMB Mode switch

Switch to ARM ISA mode automatically Switch to ARM ISA mode automatically on exceptionon exception

Can also be switch by BX (Branch and Can also be switch by BX (Branch and Exchange) InstructionExchange) Instruction

Note: gcc-3.X now have support for Note: gcc-3.X now have support for “ARM/Thumb inter-working” “ARM/Thumb inter-working” (Unsupported in 2.9x)(Unsupported in 2.9x)

ARM ISA Mode

THUMB ISA Mode

BX Instruction

Exception/Interrupt/Software Interrupt

Page 190: Arm

Thumb/ARM differencesThumb/ARM differences

Most Thumb instructions are unconditionalMost Thumb instructions are unconditional ALL ARM instructions are conditionalALL ARM instructions are conditional

Many Thumb data processing instructions Many Thumb data processing instructions use a 2-address formatuse a 2-address format ARM data processing instructions use a 3-ARM data processing instructions use a 3-

address formataddress format Thumb Instructions are less regular than Thumb Instructions are less regular than

ARM Instructions ARM Instructions For higher code densityFor higher code density

Page 191: Arm

SummarySummary

Thumb: Try to make higher code densityThumb: Try to make higher code density Thumb use a “decompressor” to decode Thumb use a “decompressor” to decode

16-bit Thumb instruction into 32-bit ARM 16-bit Thumb instruction into 32-bit ARM instruction in the decode stageinstruction in the decode stage

Adding Thumb support does not change Adding Thumb support does not change original ARM datapath (except for the original ARM datapath (except for the Thumb decompressor)Thumb decompressor)

Thumb: 16-bit, non-predicated ISAThumb: 16-bit, non-predicated ISA

Page 192: Arm

The History of ARM The History of ARM

ARM8,810

ARM7D,7DM

ARM2,3

1985 - 90 1991 1992 1993 1994 1995 1996 1997

ARM7TDMI

ARM6,60,610

ARM7,710

MIPS

20

40

60

80

100

0

StrongARM ARM9,920

Page 193: Arm
Page 194: Arm
Page 195: Arm
Page 196: Arm
Page 197: Arm
Page 198: Arm

Branch Instruction Branch Instruction

Page 199: Arm

Data Processing Instruction Data Processing Instruction

Page 200: Arm

Operations Done by Reset Operations Done by Reset HandlersHandlers

For exampleFor example Set up exception vectors.Set up exception vectors. Initialize stacks and registers.Initialize stacks and registers. Initialize the memory system, if using MMU.Initialize the memory system, if using MMU. Initialize any critical I/O devices.Initialize any critical I/O devices. Enable interrupts.Enable interrupts. Change processor mode and/or state.Change processor mode and/or state. Initialize variables required by C and call the Initialize variables required by C and call the

main application.main application.

Page 201: Arm

Undefined Instruction HandlersUndefined Instruction Handlers

It often used to emulate a It often used to emulate a coprocessor. Such an emulator must:coprocessor. Such an emulator must: Attach itself to the Undefined Instruction Attach itself to the Undefined Instruction

vector.vector. Examine the undefined instruction to Examine the undefined instruction to

see if it should be emulated.see if it should be emulated. Otherwise the emulator must pass the Otherwise the emulator must pass the

exception onto the original handler exception onto the original handler using the vector stored when the using the vector stored when the emulator was installed.emulator was installed.

Page 202: Arm

Prefetch Abort Handler or Data Prefetch Abort Handler or Data AbortAbort

If no MMU, report error. Otherwise, the If no MMU, report error. Otherwise, the related handler is executed to deal with related handler is executed to deal with the virtual memory fault.the virtual memory fault.

Depending on whether the instruction that Depending on whether the instruction that causes abort is re-executed or not, the causes abort is re-executed or not, the return address should be properly set. return address should be properly set. Prefetch abortPrefetch abort

INST-aborted INST-aborted executed executed PC-8 PC-8 INST-1INST-1 decoded decoded PC-4 PC-4 INST-2INST-2 fetched fetched PC PC

Page 203: Arm

Thank YouThank You