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

Volume 1 Basic Architecture (794100), страница 46

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

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

Bit Test and Modify InstructionsInstructionEffect on CF FlagEffect on Selected BitBT (Bit Test)CF flag ← Selected BitNo effectBTS (Bit Test and Set)CF flag ← Selected BitSelected Bit ← 1BTR (Bit Test and Reset)CF flag ← Selected BitSelected Bit ← 0BTC (Bit Test andComplement)CF flag ← Selected BitSelected Bit ← NOT (Selected Bit)7.3.7.2Bit Scan InstructionsThe BSF (bit scan forward) and BSR (bit scan reverse) instructions scan a bit string ina source operand for a set bit and store the bit index of the first set bit found in adestination register. The bit index is the offset from the least significant bit (bit 0) inthe bit string to the first set bit.

The BSF instruction scans the source operand low-tohigh (from bit 0 of the source operand toward the most significant bit); the BSRinstruction scans high-to-low (from the most significant bit toward the least significant bit).7.3.7.3Byte Set on Condition InstructionsThe SETcc (set byte on condition) instructions set a destination-operand byte to 0 or1, depending on the state of selected status flags (CF, OF, SF, ZF, and PF) in theEFLAGS register. The suffix (cc) added to the SET mnemonic determines the condition being tested for.For example, the SETO instruction tests for overflow.

If the OF flag is set, the destination byte is set to 1; if OF is clear, the destination byte is cleared to 0. Appendix B,7-20 Vol. 1PROGRAMMING WITH GENERAL-PURPOSE INSTRUCTIONS“EFLAGS Condition Codes,” lists the conditions it is possible to test for with thisinstruction.7.3.7.4Test InstructionThe TEST instruction performs a logical AND of two operands and sets the SF, ZF, andPF flags according to the results. The flags can then be tested by the conditional jumpor loop instructions or the SETcc instructions.

The TEST instruction differs from theAND instruction in that it does not alter either of the operands.7.3.8Control Transfer InstructionsThe processor provides both conditional and unconditional control transfer instructions to direct the flow of program execution. Conditional transfers are taken only forspecified states of the status flags in the EFLAGS register.

Unconditional controltransfers are always executed.For the purpose of this discussion, these instructions are further divided subordinatesubgroups that process:•••Unconditional transfersConditional transfersSoftware interrupts7.3.8.1Unconditional Transfer InstructionsThe JMP, CALL, RET, INT, and IRET instructions transfer program control to anotherlocation (destination address) in the instruction stream.

The destination can bewithin the same code segment (near transfer) or in a different code segment (fartransfer).Jump instruction — The JMP (jump) instruction unconditionally transfers programcontrol to a destination instruction. The transfer is one-way; that is, a return addressis not saved. A destination operand specifies the address (the instruction pointer) ofthe destination instruction. The address can be a relative address or an absoluteaddress.A relative address is a displacement (offset) with respect to the address in the EIPregister. The destination address (a near pointer) is formed by adding the displacement to the address in the EIP register. The displacement is specified with a signedinteger, allowing jumps either forward or backward in the instruction stream.An absolute address is a offset from address 0 of a segment. It can be specified ineither of the following ways:•An address in a general-purpose register — This address is treated as a nearpointer, which is copied into the EIP register.

Program execution then continues atthe new address within the current code segment.Vol. 1 7-21PROGRAMMING WITH GENERAL-PURPOSE INSTRUCTIONS•An address specified using the standard addressing modes of theprocessor — Here, the address can be a near pointer or a far pointer. If theaddress is for a near pointer, the address is translated into an offset and copiedinto the EIP register. If the address is for a far pointer, the address is translatedinto a segment selector (which is copied into the CS register) and an offset(which is copied into the EIP register).In protected mode, the JMP instruction also allows jumps to a call gate, a task gate,and a task-state segment.Call and return instructions — The CALL (call procedure) and RET (return fromprocedure) instructions allow a jump from one procedure (or subroutine) to anotherand a subsequent jump back (return) to the calling procedure.The CALL instruction transfers program control from the current (or calling procedure) to another procedure (the called procedure).

To allow a subsequent return tothe calling procedure, the CALL instruction saves the current contents of the EIPregister on the stack before jumping to the called procedure. The EIP register (priorto transferring program control) contains the address of the instruction following theCALL instruction. When this address is pushed on the stack, it is referred to as thereturn instruction pointer or return address.The address of the called procedure (the address of the first instruction in the procedure being jumped to) is specified in a CALL instruction the same way as it is in a JMPinstruction (see “Jump instruction” on page 7-21).

The address can be specified as arelative address or an absolute address. If an absolute address is specified, it can beeither a near or a far pointer.The RET instruction transfers program control from the procedure currently beingexecuted (the called procedure) back to the procedure that called it (the callingprocedure). Transfer of control is accomplished by copying the return instructionpointer from the stack into the EIP register. Program execution then continues withthe instruction pointed to by the EIP register.The RET instruction has an optional operand, the value of which is added to thecontents of the ESP register as part of the return operation.

This operand allows thestack pointer to be incremented to remove parameters from the stack that werepushed on the stack by the calling procedure.See Section 6.3, “Calling Procedures Using CALL and RET,” for more information onthe mechanics of making procedure calls with the CALL and RET instructions.Return from interrupt instruction — When the processor services an interrupt, itperforms an implicit call to an interrupt-handling procedure. The IRET (return frominterrupt) instruction returns program control from an interrupt handler to the interrupted procedure (that is, the procedure that was executing when the interruptoccurred). The IRET instruction performs a similar operation to the RET instruction(see “Call and return instructions” on page 7-22) except that it also restores theEFLAGS register from the stack.

The contents of the EFLAGS register are automatically stored on the stack along with the return instruction pointer when the processorservices an interrupt.7-22 Vol. 1PROGRAMMING WITH GENERAL-PURPOSE INSTRUCTIONS7.3.8.2Conditional Transfer InstructionsThe conditional transfer instructions execute jumps or loops that transfer programcontrol to another instruction in the instruction stream if specified conditions aremet. The conditions for control transfer are specified with a set of condition codesthat define various states of the status flags (CF, ZF, OF, PF, and SF) in the EFLAGSregister.Conditional jump instructions — The Jcc (conditional) jump instructions transferprogram control to a destination instruction if the conditions specified with the condition code (cc) associated with the instruction are satisfied (see Table 7-4). If thecondition is not satisfied, execution continues with the instruction following the Jccinstruction.

As with the JMP instruction, the transfer is one-way; that is, a returnaddress is not saved.Table 7-4. Conditional Jump InstructionsInstruction MnemonicCondition (Flag States)DescriptionJA/JNBE(CF or ZF) = 0Above/not below or equalJAE/JNBCF = 0Above or equal/not belowUnsigned Conditional JumpsJB/JNAECF = 1Below/not above or equalJBE/JNA(CF or ZF) = 1Below or equal/not aboveJCCF = 1CarryJE/JZZF = 1Equal/zeroJNCCF = 0Not carryJNE/JNZZF = 0Not equal/not zeroJNP/JPOPF = 0Not parity/parity oddJP/JPEPF = 1Parity/parity evenJCXZCX = 0Register CX is zeroJECXZECX = 0Register ECX is zeroJG/JNLE((SF xor OF) or ZF) = 0Greater/not less or equalJGE/JNL(SF xor OF) = 0Greater or equal/not lessJL/JNGE(SF xor OF) = 1Less/not greater or equalJLE/JNG((SF xor OF) or ZF) = 1Less or equal/not greaterJNOOF = 0Not overflowSigned Conditional JumpsJNSSF = 0Not sign (non-negative)JOOF = 1OverflowJSSF = 1Sign (negative)Vol.

1 7-23PROGRAMMING WITH GENERAL-PURPOSE INSTRUCTIONSThe destination operand specifies a relative address (a signed offset with respect tothe address in the EIP register) that points to an instruction in the current codesegment. The Jcc instructions do not support far transfers; however, far transfers canbe accomplished with a combination of a Jcc and a JMP instruction (see “Jcc—Jump ifCondition Is Met” in Chapter 3, “Instruction Set Reference, A-M,” of the Intel® 64and IA-32 Architectures Software Developer’s Manual, Volume 2A).Table 7-4 shows the mnemonics for the Jcc instructions and the conditions beingtested for each instruction. The condition code mnemonics are appended to the letter“J” to form the mnemonic for a Jcc instruction. The instructions are divided into twogroups: unsigned and signed conditional jumps.

These groups correspond to theresults of operations performed on unsigned and signed integers respectively. Thoseinstructions listed as pairs (for example, JA/JNBE) are alternate names for the sameinstruction. Assemblers provide alternate names to make it easier to read programlistings.The JCXZ and JECXZ instructions test the CX and ECX registers, respectively, insteadof one or more status flags.

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

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

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

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