Home > Back-end >  What is the benefit of having a dedicated stack pointer register?
What is the benefit of having a dedicated stack pointer register?

Time:12-25

As a more specific question for assembly - Why make ISA be aware of the existence of "stack" concept? - Stack Overflow and suggested by @xiver77, what is the benefit of having a dedicated stack pointer register and instructions for each ISA such as x86 and ARM?

CodePudding user response:

In instruction encoding (like ARM Thumb), it saves bits on a register-number for the pointer.

In the architecture, it means exception/interrupt semantics can save stuff like FLAGS and return address into memory, instead of needing special registers for it. (Or general-purpose registers that can be clobbered asynchronously.) Another way to handle that is via banked registers, like switching to a special bank of registers for exception handling and maybe putting some values into some of those registers, to avoid messing up the state of the code being interrupted. But that wouldn't work with a higher-priority interrupt interrupting a lower-priority handler.

MIPS doesn't do either of those things; nothing in the ISA has any implicit use of any register-number as a stack pointer, not even its exception / interrupt handling.

CodePudding user response:

'The stack' and 'a stack' are different things. Some architecture support generic stacks like ARM32 original, 68K/Coldfire, etc. Stacks are key to deterministic finite automata and form the basis for a lot of computer language theory. In order to accomodate language theory, CPU vendors implement efficient encoding of instructions.

Some languages (Forth) and machines are entirely stack based. See: Wikipedias stack machines for examples.

Some work has been done to separate program data from control flow in tools. This can prevent a 'stack overflow' as an exploit. Return addresses, etc. are stored in a separate stack from program data.

What is the benefit of having a dedicated stack pointer register?

  • It gives an efficient encoding of an extremely common idiom, used extensively by compilers.

However, having a single stack also creates an opportunity for stack overflows as it mixes control and program data in a traditional stack slot. Other mechanics can be used to ensure data can not be over-written on the stack such as extents or 'bounded arrays'. A separate stack for control flow and data can also accomplish a lot without restricting the language.

Efficient encoding of linked lists and other data structures are also important for CPU acceptance. In some ways, this is a kin to a question, like "What is the benefit of using binary?"

  • Related