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

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

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

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

1 E-1GUIDELINES FOR WRITING SIMD FLOATING-POINT EXCEPTION HANDLERS5, “Interrupt and Exception Handling,” in the Intel® 64 and IA-32 Architectures Software Developer’s Manual, Volume 3A). Some compilers use specific run-timelibraries to assist in floating-point exception handling. If any x87 FPU floating-pointoperations are going to be performed that might raise floating-point exceptions, thenthe exception handling routine must either disable all floating-point exceptions (forexample, loading a local control word with FLDCW), or it must be implemented as reentrant (for the case of x87 FPU exceptions, refer to Example D-1 in Appendix D,“Guidelines for Writing x87 FPU Exception Handlers”). If this is not the case, theroutine has to clear the status flags for x87 FPU exceptions or to mask all x87 FPUfloating-point exceptions.

For SIMD floating-point exceptions though, the exceptionflags in MXCSR do not have to be cleared, even if they remain unmasked (but theymay still be cleared). Exceptions are in this case precise and occur immediately, anda SIMD floating-point exception status flag that is set when the corresponding exception is unmasked will not generate an exception.Typical actions performed by this low-level exception handling routine are:•••Incrementing an exception counter for later display or printing•Storing information about the exception in a data structure that will be passed toa higher level user exception handlerPrinting or displaying diagnostic information (e.g.

the MXCSR and XMM registers)Aborting further execution, or using the exception pointers to build an instructionthat will run without exception and executing itIn most cases (and this applies also to SSE/SSE2/SSE3 instructions), there will bethree main components of a low-level floating-point exception handler: a prologue, abody, and an epilogue.The prologue performs functions that must be protected from possible interruptionby higher-priority sources - typically saving registers and transferring diagnosticinformation from the processor to memory. When the critical processing has beencompleted, the prologue may re-enable interrupts to allow higher-priority interrupthandlers to preempt the exception handler (assuming that the interrupt handler wascalled through an interrupt gate, meaning that the processor cleared the interruptenable (IF) flag in the EFLAGS register - refer to Section 6.4.1, “Call and ReturnOperation for Interrupt or Exception Handling Procedures”).The body of the exception handler examines the diagnostic information and makes aresponse that is application-dependent.

It may range from halting execution, todisplaying a message, to attempting to fix the problem and then proceeding withnormal execution, to setting up a data structure, calling a higher-level user exceptionhandler and continuing execution upon return from it. This latter case will beassumed in Section E.4, “SIMD Floating-Point Exceptions and the IEEE Standard754” below.Finally, the epilogue essentially reverses the actions of the prologue, restoring theprocessor state so that normal execution can be resumed.The following example represents a typical exception handler. To link it with ExampleE-2 that will follow in Section E.4.3, “Example SIMD Floating-Point Emulation Imple-E-2 Vol. 1GUIDELINES FOR WRITING SIMD FLOATING-POINT EXCEPTION HANDLERSmentation,” assume that the body of the handler (not shown here in detail) passesthe saved state to a routine that will examine in turn all the sub-operands of theexcepting instruction, invoking a user floating-point exception handler if a particularset of sub-operands raises an unmasked (enabled) exception, or emulating theinstruction otherwise.Example E-1.

SIMD Floating-Point Exception HandlerSIMD_FP_EXC_HANDLER PROC;PROLOGUE;SAVE REGISTERS THAT MIGHT BE USED BY THE EXCEPTION HANDLERPUSH EBP;SAVE EBPPUSH EAX;SAVE EAX...MOV EBP, ESP;SAVE ESP in EBPSUB ESP, 512;ALLOCATE 512 BYTESAND ESP, 0fffffff0h;MAKE THE ADDRESS 16-BYTE ALIGNEDFXSAVE [ESP];SAVE FP, MMX, AND SIMD FP STATEPUSH [EBP+EFLAGS_OFFSET];COPY OLD EFLAGS TO STACK TOPPOPFD;RESTORE THE INTERRUPT ENABLE FLAG IF;TO VALUE BEFORE SIMD FP EXCEPTION;BODY;APPLICATION-DEPENDENT EXCEPTION HANDLING CODE GOES HERELDMXCSR LOCAL_MXCSR;LOAD LOCAL MXCSR VALUE IF NEEDED......;EPILOGUEFXRSTOR [ESP];RESTORE MODIFIED STATE IMAGEMOV ESP, EBP;DE-ALLOCATE STACK SPACE...POP EAX;RESTORE EAXPOP EBP;RESTORE EBPIRET;RETURN TO INTERRUPTED CALCULATIONSIMD_FP_EXC_HANDLER ENDPE.3EXCEPTION SYNCHRONIZATIONAn SSE/SSE2/SSE3 instruction can execute in parallel with other similar instructions,with integer instructions, and with floating-point or MMX instructions.

Unlike for x87instructions, special precaution for exception synchronization is not necessary inthis case. This is because floating-point exceptions for SSE/SSE2/SSE3 instructionsVol. 1 E-3GUIDELINES FOR WRITING SIMD FLOATING-POINT EXCEPTION HANDLERSoccur immediately and are not delayed until a subsequent floating-point instructionis executed. However, floating-point emulation may be necessary when unmaskedfloating-point exceptions are generated.E.4SIMD FLOATING-POINT EXCEPTIONS AND THE IEEESTANDARD 754SSE/SSE2/SSE3 extensions are 100% compatible with the IEEE Standard 754 forBinary Floating-Point Arithmetic, satisfying all of its mandatory requirements (whenthe flush-to-zero or denormals-are-zeros modes are not enabled). But a programming environment that includes SSE/SSE2/SSE3 instructions will comply with boththe obligatory and the strongly recommended requirements of the IEEE Standard754 regarding floating-point exception handling, only as a combination of hardwareand software (which is acceptable).

The standard states that a user should be able torequest a trap on any of the five floating-point exceptions (note that the denormalexception is an IA-32 addition), and it also specifies the values (operands or result)to be delivered to the exception handler.The main issue is that for SSE/SSE2/SSE3 instructions that raise post-computationexceptions (traps: overflow, underflow, or inexact), unlike for x87 FPU instructions,the processor does not provide the result recommended by IEEE Standard 754 to theuser handler. If a user program needs the result of an instruction that generated apost-computation exception, it is the responsibility of the software to produce thisresult by emulating the faulting SSE/SSE2/SSE3 instruction.

Another issue is that thestandard does not specify explicitly how to handle multiple floating-point exceptionsthat occur simultaneously. For packed operations, a logical OR of the flags that wouldbe set by each sub-operation is used to set the exception flags in the MXCSR. Thefollowing subsections present one possible way to solve these problems.E.4.1Floating-Point EmulationEvery operating system must provide a kernel level floating-point exception handler(a template was presented in Section E.2, “Software Exception Handling” above).

Inthe following discussion, assume that a user mode floating-point exception filter issupplied for SIMD floating-point exceptions (for example as part of a library of Cfunctions), that a user program can invoke in order to handle unmasked exceptions.The user mode floating-point exception filter (not shown here) has to be able toemulate the subset of SSE/SSE2/SSE3 instructions that can generate numericexceptions, and has to be able to invoke a user provided floating-point exceptionhandler for floating-point exceptions.

When a floating-point exception that is notmasked is raised by an SSE/SSE2/SSE3 instruction, the low-level floating-pointexception handler will be called. This low-level handler may in turn call the user modefloating-point exception filter. The filter function receives the original operands of theexcepting instruction as no results are provided by the hardware, whether a precomputation or a post-computation exception has occurred. The filter will unpack theE-4 Vol. 1GUIDELINES FOR WRITING SIMD FLOATING-POINT EXCEPTION HANDLERSoperands into up to four sets of sub-operands, and will submit them one set at a timeto an emulation function (See Example E-2 in Section E.4.3, “Example SIMDFloating-Point Emulation Implementation”).

The emulation function will examine thesub-operands, and will possibly redo the necessary calculation.Two cases are possible:•If an unmasked (enabled) exception would occur in this process, the emulationfunction will return to its caller (the filter function) with the appropriate information. The filter will invoke a (previously registered) user floating-pointexception handler for this set of sub-operands, and will record the result uponreturn from the user handler (provided the user handler allows continuation ofthe execution).•If no unmasked (enabled) exception would occur, the emulation function willdetermine and will return to its caller the result of the operation for the currentset of sub-operands (it has to be IEEE Standard 754 compliant).

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

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

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

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