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

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

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

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

The purpose of this instruction is to update flags for further testing.The TEST instruction is often used to test whether one or more bits in an operand are zero. In this case,one of the instruction operands would contain a mask in which all bits are cleared to zero except thebits being tested. For more advanced bit testing and bit modification, use the BTx instructions.Bit Scan• BSF—Bit Scan Forward• BSR—Bit Scan ReverseThe BSF and BSR instructions search a source operand for the least-significant (BSF) or mostsignificant (BSR) bit that is set to 1.

If a set bit is found, its bit index is loaded into the destinationoperand, and the zero flag (ZF) is set. If no set bit is found, the zero flag is cleared and the contents ofthe destination are undefined.Population and Leading Zero Counts• POPCNT—Bit Population Count• LZCNT—Count Leading ZerosThe POPCNT instruction counts the number of bits having a value of 1 in the source operand andplaces the total in the destination register, while the LZCNT instruction counts the number of leadingzero bits in a general purpose register or memory source operand.Bit Test• BT—Bit Test• BTC—Bit Test and Complement• BTR—Bit Test and Reset• BTS—Bit Test and SetThe BTx instructions copy a specified bit in the first operand to the carry flag (CF) and leave the sourcebit unchanged (BT), or complement the source bit (BTC), or clear the source bit to 0 (BTR), or set thesource bit to 1 (BTS).These instructions are useful for implementing semaphore arrays.

Unlike the XCHG instruction, theBTx instructions set the carry flag, so no additional test or compare instruction is needed. Also,54General-Purpose Programming24592—Rev. 3.13—July 2007AMD64 Technologybecause these instructions operate directly on bits rather than larger data types, the semaphore arrayscan be smaller than is possible when using XCHG. In such semaphore applications, bit-testinstructions should be preceded by the LOCK prefix.Set Byte on Condition• SETcc—Set Byte if conditionThe SETcc instructions store a 1 or 0 value to their byte operand depending on whether their condition(represented by certain rFLAGS bits) is true or false, respectively.

Table 3-5 shows the rFLAGS valuesrequired for each SETcc instruction.Table 3-5.MnemonicrFLAGS for SETcc InstructionsRequired Flag StateDescriptionSETOOF = 1Set byte if overflowSETNOOF = 0Set byte if not overflowSETBSETCSETNAECF = 1Set byte if belowSet byte if carrySet byte if not above or equal (unsigned operands)SETAESETNBSETNCCF = 0Set byte if above or equalSet byte if not belowSet byte if not carry (unsigned operands)SETESETZZF = 1Set byte if equalSet byte if zeroSETNESETNZZF = 0Set byte if not equalSet byte if not zeroSETBESETNACF = 1 or ZF = 1Set byte if below or equalSet byte if not above (unsigned operands)SETASETNBECF = 0 and ZF = 0Set byte if not below or equalSet byte if not below or equal (unsigned operands)SETSSF = 1Set byte if signSETNSSF = 0Set byte if not signSETPSETPEPF = 1Set byte if paritySet byte if parity evenSETNPSETPOPF = 0Set byte if not paritySet byte if parity oddSETLSETNGESF <> OFSet byte if lessSet byte if not greater or equal (signed operands)SETGESETNLSF = OFSet byte if greater or equalSet byte if not less (signed operands)SETLESETNGZF = 1 or SF <> OFSet byte if less or equalSet byte if not greater (signed operands)SETGSETNLEZF = 0 and SF = OFSet byte if greaterSet byte if not less or equal (signed operands)General-Purpose Programming55AMD64 Technology24592—Rev.

3.13—July 2007SETcc instructions are often used to set logical indicators. Like CMOVcc instructions (page 42),SETcc instructions can replace two instructions—a conditional jump and a move. Replacingconditional jumps with conditional sets can help avoid branch-prediction penalties that may be causedby conditional jumps.If the logical value True (logical 1) is represented in a high-level language as an integer with all bits setto 1, software can accomplish such representation by first executing the opposite SETcc instruction—for example, the opposite of SETZ is SETNZ—and then decrementing the result.Bounds• BOUND—Check Array BoundsThe BOUND instruction checks whether the value of the first operand, a signed integer index into anarray, is within the minimal and maximal bound values pointed to by the second operand.

The valuesof array bounds are often stored at the beginning of the array. If the bounds of the range are exceeded,the processor generates a bound-range exception.The primary disadvantage of using the BOUND instruction is its use of the time-consuming exceptionmechanism to signal a failure of the bounds test.3.3.9 LogicalThe logical instructions perform bitwise operations.••••AND—Logical ANDOR—Logical ORXOR—Exclusive ORNOT—One’s Complement NegationThe AND, OR, and XOR instructions perform their respective logical operations on the correspondingbits of both operands and store the result in the first operand. The CF flag and OF flag are cleared to 0,and the ZF flag, SF flag, and PF flag are set according to the resulting value of the first operand.The NOT instruction performs logical inversion of all bits of its operand.

Each zero bit becomes oneand vice versa. All flags remain unchanged.Apart from performing logical operations, AND and OR can test a register for a zero or non-zerovalue, sign (negative or positive), and parity status of its lowest byte.

To do this, both operands must bethe same register. The XOR instruction with two identical operands is an efficient way of loading thevalue 0 into a register.3.3.10 StringThe string instructions perform common string operations such as copying, moving, comparing, orsearching strings. These instructions are widely used for processing text.56General-Purpose Programming24592—Rev. 3.13—July 2007AMD64 TechnologyCompare Strings• CMPS—Compare Strings• CMPSB—Compare Strings by Byte• CMPSW—Compare Strings by Word• CMPSD—Compare Strings by Doubleword• CMPSQ—Compare Strings by QuadwordThe CMPSx instructions compare the values of two implicit operands of the same size located atseg:[rSI] and ES:[rDI]. After the copy, both the rSI and rDI registers are auto-incremented (if the DFflag is 0) or auto-decremented (if the DF flag is 1).Scan String• SCAS—Scan String••••SCASB—Scan String as BytesSCASW—Scan String as WordsSCASD—Scan String as DoublewordSCASQ—Scan String as QuadwordThe SCASx instructions compare the values of a memory operands in ES:rDI to a value of the samesize in the AL/rAX register.

Bits in rFLAGS are set to indicate the outcome of the comparison. Afterthe comparison, the rDI register is auto-incremented (if the DF flag is 0) or auto-decremented (if theDF flag is 1).Move String• MOVS—Move String• MOVSB—Move String Byte• MOVSW—Move String Word• MOVSD—Move String Doubleword• MOVSQ—Move String QuadwordThe MOVSx instructions copy an operand from the memory location seg:[rSI] to the memory locationES:[rDI]. After the copy, both the rSI and rDI registers are auto-incremented (if the DF flag is 0) orauto-decremented (if the DF flag is 1).Load String• LODS—Load String• LODSB—Load String Byte• LODSW—Load String Word• LODSD—Load String Doubleword• LODSQ—Load String QuadwordGeneral-Purpose Programming57AMD64 Technology24592—Rev.

3.13—July 2007The LODSx instructions load a value from the memory location seg:[rSI] to the accumulator register(AL or rAX). After the load, the rSI register is auto-incremented (if the DF flag is 0) or autodecremented (if the DF flag is 1).Store String• STOS—Store String• STOSB—Store String Bytes• STOSW—Store String Words• STOSD—Store String Doublewords• STOSQ—Store String QuadwordThe STOSx instructions copy the accumulator register (AL or rAX) to a memory location ES:[rDI].After the copy, the rDI register is auto-incremented (if the DF flag is 0) or auto-decremented (if the DFflag is 1).3.3.11 Control TransferControl-transfer instructions, or branches, are used to iterate through loops and move throughconditional program logic.Jump• JMP—JumpJMP performs an unconditional jump to the specified address.

There are several ways to specify thetarget address.••••Relative Short Jump and Relative Near Jump—The target address is determined by adding an 8-bit(short jump) or 16-bit or 32-bit (near jump) signed displacement to the rIP of the instructionfollowing the JMP. The jump is performed within the current code segment (CS).Register-Indirect and Memory-Indirect Near Jump—The target rIP value is contained in a registeror in a memory location.

The jump is performed within the current CS.Direct Far Jump—For all far jumps, the target address is outside the current code segment. Here,the instruction specifies the 16-bit target-address code segment and the 16-bit or 32-bit offset as animmediate value. The direct far jump form is invalid in 64-bit mode.Memory-Indirect Far Jump—For this form, the target address (CS:rIP) is in a address outside thecurrent code segment. A 32-bit or 48-bit far pointer in a specified memory location points to thetarget address.The size of the target rIP is determined by the effective operand size for the JMP instruction.For far jumps, the target selector can specify a code-segment selector, in which case it is loaded intoCS, and a 16-bit or 32-bit target offset is loaded into rIP.

The target selector can also be a call-gateselector or a task-state-segment (TSS) selector, used for performing task switches. In these cases, the58General-Purpose Programming24592—Rev. 3.13—July 2007AMD64 Technologytarget offset of the JMP instruction is ignored, and the new values loaded into CS and rIP are takenfrom the call gate or from the TSS.Conditional Jump• Jcc—Jump if conditionConditional jump instructions jump to an instruction specified by the operand, depending on the stateof flags in the rFLAGS register. The operands specifies a signed relative offset from the currentcontents of the rIP. If the state of the corresponding flags meets the condition, a conditional jumpinstruction passes control to the target instruction, otherwise control is passed to the instructionfollowing the conditional jump instruction.

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

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

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

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