Главная » Просмотр файлов » Volume 1 Application Programming

Volume 1 Application Programming (794095), страница 15

Файл №794095 Volume 1 Application Programming (Intel and AMD manuals) 15 страницаVolume 1 Application Programming (794095) страница 152019-04-28СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 15)

Gray-shaded bits are not modified in 64-bit mode.General-Purpose Programming27AMD64 Technology24592—Rev. 3.13—July 2007Figure 3-4. GPRs in 64-Bit Mode28General-Purpose Programming24592—Rev. 3.13—July 2007AMD64 TechnologyDefault Operand Size. For most instructions, the default operand size in 64-bit mode is 32 bits. Toaccess 16-bit operand sizes, an instruction must contain an operand-size prefix (66h), as described inSection 3.2.2, “Operand Sizes and Overrides,” on page 39. To access the full 64-bit operand size, mostinstructions must contain a REX prefix.For details on operand size, see Section 3.2.2, “Operand Sizes and Overrides,” on page 39.Byte Registers. 64-bit mode provides a uniform set of low-byte, low-word, low-doubleword, andquadword registers that is well-suited for register allocation by compilers.

Access to the four new lowbyte registers in the legacy-GPR range (SIL, DIL, BPL, SPL), or any of the low-byte registers in theextended registers (R8B–R15B), requires a REX instruction prefix. However, the legacy high-byteregisters (AH, BH, CH, DH) are not accessible when a REX prefix is used.Zero-Extension of 32-Bit Results. As Figure 3-3 on page 27 and Figure 3-4 on page 28 show, whenperforming 32-bit operations with a GPR destination in 64-bit mode, the processor zero-extends the32-bit result into the full 64-bit destination.

8-bit and 16-bit operations on GPRs preserve all unwrittenupper bits of the destination GPR. This is consistent with legacy 16-bit and 32-bit semantics forpartial-width results.Software should explicitly sign-extend the results of 8-bit, 16-bit, and 32-bit operations to the full 64bit width before using the results in 64-bit address calculations.The following four code examples show how 64-bit, 32-bit, 16-bit, and 8-bit ADDs work. In theseexamples, “48” is a REX prefix specifying 64-bit operand size, and “01C3” and “00C3” are the opcodeand ModRM bytes of each instruction (see “Opcode Syntax” in Volume 3 for details on the opcode andModRM encoding).Example 1: 64-bit Add:Before:RAX =0002_0001_8000_2201RBX =0002_0002_0123_330148 01C3 ADD RBX,RAX ;48 is a REX prefix for size.Result:RBX = 0004_0003_8123_5502Example 2: 32-bit Add:Before:RAX = 0002_0001_8000_2201RBX = 0002_0002_0123_330101C3 ADD EBX,EAX ;32-bit addResult:RBX = 0000_0000_8123_5502(32-bit result is zero extended)Example 3: 16-bit Add:Before:RAX = 0002_0001_8000_2201RBX = 0002_0002_0123_3301General-Purpose Programming29AMD64 Technology24592—Rev.

3.13—July 200766 01C3 ADD BX,AX ;66 is 16-bit size overrideResult:RBX = 0002_0002_0123_5502(bits 63:16 are preserved)Example 4: 8-bit Add:Before:RAX = 0002_0001_8000_2201RBX = 0002_0002_0123_330100C3 ADD BL,AL ;8-bit addResult:RBX = 0002_0002_0123_3302(bits 63:08 are preserved)GPR High 32 Bits Across Mode Switches. The processor does not preserve the upper 32 bits of the64-bit GPRs across switches from 64-bit mode to compatibility or legacy modes. When using 32-bitoperands in compatibility or legacy mode, the high 32 bits of GPRs are undefined. Software must notrely on these undefined bits, because they can change from one implementation to the next or even ona cycle-to-cycle basis within a given implementation.

The undefined bits are not a function of the dataleft by any previously running process.3.1.3 Implicit Uses of GPRsMost instructions can use any of the GPRs for operands. However, as Figure 3-1 on page 31 shows,some instructions use some GPRs implicitly. Details about implicit use of GPRs are described in“General-Purpose Instruction Reference” in Volume 3.Table 3-1 on page 31 shows implicit register uses only for application instructions.

Certain systeminstructions also make implicit use of registers. These system instructions are described in “SystemInstruction Reference” in Volume 3.30General-Purpose Programming24592—Rev. 3.13—July 2007Table 3-1.AMD64 TechnologyImplicit Uses of GPRsRegisters1Low 8-BitALBLCLDLSIL216-BitAXBXCXDXSIName32-BitEAXEBXECXEDXESIImplicit Uses64-BitRAX2RBX2RCX2• Operand for decimalarithmetic, multiply, divide,string, compare-andexchange, table-translation,and I/O instructions.• Special accumulator encodingAccumulatorfor ADD, XOR, and MOVinstructions.• Used with EDX to hold doubleprecision operands.• CPUID processor-featureinformation.Base• Address generation in 16-bitcode.• Memory address for XLATinstruction.• CPUID processor-featureinformation.Count• Bit index for shift and rotateinstructions.• Iteration count for loop andrepeated string instructions.• Jump conditional if zero.• CPUID processor-featureinformation.RDX2• Operand for multiply and divideinstructions.• Port number for I/Oinstructions.I/O Address• Used with EAX to hold doubleprecision operands.• CPUID processor-featureinformation.RSI2• Memory address of sourceoperand for string instructions.Source Index• Memory index for 16-bitaddresses.Note:1.

Gray-shaded registers have no implicit uses.2. Accessible only in 64-bit mode.General-Purpose Programming31AMD64 TechnologyTable 3-1.24592—Rev. 3.13—July 2007Implicit Uses of GPRs (continued)Registers1Low 8-Bit16-Bit32-BitNameImplicit Uses• Memory address of destinationoperand for string instructions.• Memory index for 16-bitaddresses.64-BitDIL2DIEDIRDI2DestinationIndexBPL2BPEBPRBP2Base Pointer• Memory address of stackframe base pointer.SPL2SPESPRSP2Stack Pointer• Memory address of last stackentry (top of stack).R8–R102NoneNo implicit usesR8B–R10B2R8W–R10W2 R8D–R10D2R11B2R11W2R11D2R112None• Holds the value of RFLAGS onSYSCALL/SYSRET.R12B–R15B2R12W–R15WR12D–R15D2R12–R152NoneNo implicit uses2Note:1. Gray-shaded registers have no implicit uses.2.

Accessible only in 64-bit mode.Arithmetic Operations. Several forms of the add, subtract, multiply, and divide instructions use ALor rAX implicitly. The multiply and divide instructions also use the concatenation of rDX:rAX fordouble-sized results (multiplies) or quotient and remainder (divides).Sign-Extensions. The instructions that double the size of operands by sign extension (for example,CBW, CWDE, CDQE, CWD, CDQ, CQO) use rAX register implicitly for the operand.

The CWD,CDQ, and CQO instructions also uses the rDX register.Special MOVs. The MOV instruction has several opcodes that implicitly use the AL or rAX registerfor one operand.String Operations. Many types of string instructions use the accumulators implicitly. Load string,store string, and scan string instructions use AL or rAX for data and rDI or rSI for the offset of amemory address.I/O-Address-Space Operations. The I/O and string I/O instructions use rAX to hold data that isreceived from or sent to a device located in the I/O-address space. DX holds the device I/O-address(the port number).Table Translations.

The table translate instruction (XLATB) uses AL for an memory index and rBXfor memory base address.Compares and Exchanges. Compare and exchange instructions (CMPXCHG) use the AL or rAXregister for one operand.32General-Purpose Programming24592—Rev. 3.13—July 2007AMD64 TechnologyDecimal Arithmetic. The decimal arithmetic instructions (AAA, AAD, AAM, AAS, DAA, DAS)that adjust binary-coded decimal (BCD) operands implicitly use the AL and AH register for theiroperations.Shifts and Rotates. Shift and rotate instructions can use the CL register to specify the number of bitsan operand is to be shifted or rotated.Conditional Jumps. Special conditional-jump instructions use the rCX register instead of flags. TheJCXZ and JrCXZ instructions check the value of the rCX register and pass control to the targetinstruction when the value of rCX register reaches 0.Repeated String Operations.

With the exception of I/O string instructions, all string operations userSI as the source-operand pointer and rDI as the destination-operand pointer. I/O string instructionsuse rDX to specify the input-port or output-port number. For repeated string operations (thosepreceded with a repeat-instruction prefix), the rSI and rDI registers are incremented or decremented asthe string elements are moved from the source location to the destination. Repeat-string operationsalso use rCX to hold the string length, and decrement it as data is moved from one location to the other.Stack Operations.

Stack operations make implicit use of the rSP register, and in some cases, the rBPregister. The rSP register is used to hold the top-of-stack pointer (or simply, stack pointer). rSP isdecremented when items are pushed onto the stack, and incremented when they are popped off thestack. The ENTER and LEAVE instructions use rBP as a stack-frame base pointer. Here, rBP points tothe last entry in a data structure that is passed from one block-structured procedure to another.The use of rSP or rBP as a base register in an address calculation implies the use of SS (stack segment)as the default segment.

Using any other GPR as a base register without a segment-override prefiximplies the use of the DS data segment as the default segment.The push all and pop all instructions (PUSHA, PUSHAD, POPA, POPAD) implicitly use all of theGPRs.CPUID Information. The CPUID instruction makes implicit use of the EAX, EBX, ECX, and EDXregisters.

Характеристики

Тип файла
PDF-файл
Размер
2,24 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6363
Авторов
на СтудИзбе
310
Средний доход
с одного платного файла
Обучение Подробнее