Главная » Просмотр файлов » K. Cooper, L. Torczon - Engineering a Compiler (2011 - 2nd edition)

K. Cooper, L. Torczon - Engineering a Compiler (2011 - 2nd edition) (798440), страница 104

Файл №798440 K. Cooper, L. Torczon - Engineering a Compiler (2011 - 2nd edition) (K. Cooper, L. Torczon - Engineering a Compiler (2011 - 2nd edition)) 104 страницаK. Cooper, L. Torczon - Engineering a Compiler (2011 - 2nd edition) (798440) страница 1042019-09-18СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

An expression, such as b + c or a - d, is redundant inB if and only if it has been previously computed in B and no intervening8.4 Local Optimization 421operation redefines one of its constituent arguments. In B, the occurrence ofb + c in the third operation is not redundant because the second operationredefines b.

The occurrence of a - d in the fourth operation is redundantbecause B does not redefine a or d between the second and fourth operations.The compiler can rewrite this block so that it computes a - d once, as shownin the margin. The second evaluation of a - d is replaced with a copy from b.An alternative strategy would replace subsequent uses of d with uses of b.However, that approach requires analysis to determine whether or not b isredefined before some use of d.

In practice, it is simpler to have the optimizerinsert a copy and let a subsequent pass determine which copy operationsare, in fact, necessary and which ones can have their source and destinationnames combined.In general, replacing redundant evaluations with references to previouslycomputed values is profitable—that is, the resulting code runs more quicklythan the original. However, profitability is not guaranteed.

Replacingd ← a - d with d ← b has the potential to extend the lifetime of b and toshorten the lifetimes of either a or d or both—depending, in each case, onwhere the last use of the value lies. Depending on the precise details, eachrewrite can increase demand for registers, decrease demand for registers, orleave it unchanged. Replacing a redundant computation with a reference islikely to be unprofitable if the rewrite causes the register allocator to spill avalue in the block.abcd←←←←baba+++cdcdOriginal Blockabcd←←←←b + ca - db + cbRewritten BlockLifetimeThe lifetime of a name is the region of codebetween its definitions and its uses. Here,definition means assignment.In practice, the optimizer cannot consistently predict the behavior of the register allocator, in part because the code will be further transformed before itreaches the allocator.

Therefore, most algorithms for removing redundancyassume that rewriting to avoid redundancy is profitable.In the previous example, the redundant expression was textually identical tothe earlier instance. Assignment can, of course, produce a redundant expression that differs textually from its predecessor. Consider the block shown inthe margin. The assignment of b to d makes the expression d × c producethe same value as b × c. To recognize this case, the compiler must track theflow of values through names. Techniques that rely on textual identity donot detect such cases.Programmers will protest that they do not write code that contains redundantexpressions like those in the example.

In practice, redundancy elimination finds many opportunities. Translation from source code to ir elaborates many details, such as address calculations, and introduces redundantexpressions.Many techniques that find and eliminate redundancies have been developed. Local value numbering is one of the oldest and most powerful ofa ← b × cd ← be ← d × cEffect of Assignment422 CHAPTER 8 Introduction to Optimizationthese transformations. It discovers such redundancies within a basic blockand rewrites the block to avoid them. It provides a simple and efficientframework for other local optimizations, such as constant folding andsimplification using algebraic identities.The AlgorithmThe idea behind value numbering is simple.

The algorithm traverses a basicblock and assigns a distinct number to each value that the block computes. Itchooses the numbers so that two expressions, ei and e j , have the same valuenumber if and only ei and e j have provably equal values for all possibleoperands of the expressions.Figure 8.2 shows the basic local value numbering algorithm (lvn). lvn takesas input a block with n binary operations, each of the form Ti ← Li Opi Ri .lvn examines each operation, in order.

lvn uses a hash table to map names,constants, and expressions into distinct value numbers. The hash table isinitially empty.To process the i th operation, lvn obtains value numbers for Li and Ri bylooking for them in the hash table. If it finds an entry, lvn uses the valuenumber of that entry. If not, it creates one and assigns a new value number.Given value numbers for Li and Ri , called VN(Li) and VN(Ri), lvn constructs a hash key from hVN(Li), Opi , VN(Ri)i and looks up that key in thetable.

If an entry exists, the expression is redundant and can be replacedby a reference to the previously computed value. If not, operation i is thefirst computation of the expression in this block, so lvn creates an entryfor its hash key and assigns that entry a new value number. It also assignsthe hash key’s value number, whether new or pre-existing, to the table entryfor Ti .

Because lvn uses value numbers to construct the expression’s hashfor i ← 0 to n - 1, where the block has n operations‘‘Ti ← Li Opi Ri ’’1. get the value numbers for Li and Ri2. construct a hash key from Opi and the value numbers for Li and Ri3. if the hash key is already present in the table thenreplace operation i with a copy of the value into Ti andassociate the value number with Tielseinsert a new value number into the table at the hash key locationrecord that new value number for Tin FIGURE 8.2 Value Numbering a Single Block.8.4 Local Optimization 423THE IMPORTANCE OF ORDERThe specific order in which expressions are written has a direct impact onthe ability of optimizations to analyze and transform them.

Consider thefollowing distinct encodings of v ← a × b × c:t0 ← a × bv ← t0 × ct0 ← b × cv ← a × t0The encoding on the left assigns value numbers to a × b, to (a × b) × cand to v, while the encoding on the right assigns value numbers to b × c,to a × (b × c) and to v. Depending on the surrounding context, one orthe other encoding may be preferable. For example, if b × c occurs laterin the block but a × b does not, then the right-hand encoding producesredundancy while the left does not.In general, using commutativity, associativity, and distributivity to reorderexpressions can change the results of optimization. Similar effects can beseen with constant folding; if we replace a with 3 and c with 5, neitherordering produces the constant operation 3 × 5, which can be folded.Because the number of ways to reorder expressions is prohibitively large,compilers use heuristic techniques to find good orderings for expressions.For example, the IBM FORTRAN H compiler generated array-address computations in an order that tended to improve other optimizations.

Othercompilers have sorted the operands of commutative and associative operations into an order that corresponds to the loop nesting level at which theyare defined. Because so many solutions are possible, heuristic solutions forthis problem often require experimentation and tuning to discover what isappropriate for a specific language, compiler, and coding style.key, rather than names, it can effectively track the flow of values throughcopy and assignment operations, such as the small example labelled “Effectof Assignment” on the previous page. Extending lvn to expressions ofarbitrary arity is straightforward.To see how lvn works, consider our original example block, shown onpage 421.

The version in the margin shows the value numbers that lvnassigns as superscripts. In the first operation, with an empty value table, band c get new value numbers, 0 and 1 respectively. lvn constructs the textualstring “0 + 1” as a hash key for the expression a + b and performs a lookup.

Itdoes not find an entry for that key, so the lookup fails. Accordingly, lvn creates a new entry for “0 + 1” and assigns it value number 2. lvn then createsan entry for a and assigns it the value number of the expression, namely 2.Repeating this process for each operation, in sequential order, produces therest of the value numbers shown in the margin.a2b4c5d4←←←←b0a2b4a2++-c1d3c1d3424 CHAPTER 8 Introduction to Optimizationabcd←←←←b + ca - db + cbThe value numbers reveal, correctly, that the two occurrences of b + c produce different values, due to the intervening redefinition of b.

On the otherhand, the two occurrences of a - d produce the same value, since they havethe same input value numbers and the same operator. lvn discovers thisand records it by assigning b and d the same value number, namely 4. Thatknowledge lets lvn rewrite the fourth operation with a d ← b as shown inthe margin. Subsequent passes may eliminate the copy.Extending the Algorithmlvn provides a natural framework to perform several other localoptimizations.nnnCommutative operations Commutative operations that differ only inthe order of their operands, such as a × b and b × a, should receive thesame value numbers. As lvn constructs a hash key for the right-handside of the current operation, it can sort the operands using someconvenient scheme, such as ordering them by value number.

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

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

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

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