Loop-invariant code motion

In computer programming, loop-invariant code consists of statements or expressions (in an imperative programming language) that can be moved outside the body of a loop without affecting the semantics of the program. Loop-invariant code motion (also called hoisting or scalar promotion) is a compiler optimization that performs this movement automatically.

Example

In the following code sample, two optimizations can be applied.

int i = 0;
while (i < n) {
    x = y + z;
    a[i] = 6 * i + x * x;
    ++i;
}

Although the calculation x = y + z and x * x is loop-invariant, precautions must be taken before moving the code outside the loop. It is possible that the loop condition is false (for example, if n holds a negative value), and in such case, the loop body should not be executed at all. One way of guaranteeing correct behaviour is using a conditional branch outside of the loop. Evaluating the loop condition can have side effects, so an additional evaluation by the if construct should be compensated by replacing the while loop with a do {} while. If the code used do {} while in the first place, the whole guarding process is not needed, as the loop body is guaranteed to execute at least once.

int i = 0;
if (i < n) {
    x = y + z;
    int const t1 = x * x;
    do {
        a[i] = 6 * i + t1;
        ++i;
    } while (i < n);
}

This code can be optimized further. For example, strength reduction could remove the two multiplications inside the loop (6*i and a[i]), and induction variable elimination could then elide i completely. Since 6 * i must be in lock step with i itself, there is no need to have both.

Invariant code detection

Usually, a reaching definitions analysis is used to detect whether a statement or expression is loop invariant.

For example, if all reaching definitions for the operands of some simple expression are outside of the loop, the expression can be moved out of the loop.

Recent work by Moyen, Rubiano and Seiller uses data-flow dependence analysis [1] to detect not only invariant commands but larger code fragments such as an inner loop. The analysis also detects quasi-invariants of arbitrary degrees, that is commands or code fragments that become invariant after a fixed number of iterations of the loop body. This technique was later used by Aubert, Rubiano, Rusch, and Seiller to automatically parallelise loops.[2]

Benefits

Loop-invariant code which has been hoisted out of a loop is executed less often, providing a speedup. Another effect of this transformation is allowing constants to be stored in registers and not having to calculate the address and access the memory (or cache line) at each iteration.

However, if too many variables are created, there will be high register pressure, especially on processors with few registers, like the 32-bit x86. If the compiler runs out of registers, some variables will be spilled. To counteract this, the inverse optimization can be performed, rematerialization.

See also

Further reading

  • Aho, Alfred V.; Sethi, Ravi; & Ullman, Jeffrey D. (1986). Compilers: Principles, Techniques, and Tools. Addison Wesley. ISBN 0-201-10088-6.

References

  1. ^ Moyen, Jean-Yves; Rubiano, Thomas; Seiller, Thomas (2017). "Loop Quasi-Invariant Chunk Detection". Automated Technology for Verification and Analysis. Lecture Notes in Computer Science. Vol. 10482. pp. 91–108. doi:10.1007/978-3-319-68167-2_7. ISBN 978-3-319-68166-5.
  2. ^ Aubert, Clément; Rubiano, Thomas; Rusch, Neea; Seiller, Thomas (2023). "Distributing and Parallelizing Non-canonical Loops". Verification, Model Checking, and Abstract Interpretation. Lecture Notes in Computer Science. Vol. 13881. pp. 91–108. doi:10.1007/978-3-031-24950-1_1.

Read other articles:

Extinct Indo-European language of northeast Italy This article is about the extinct Venetic language. For the modern day Romance language, see Venetian language. For the anti-crime operation, see Operation Venetic. For other uses, see Veneti (disambiguation). VeneticNative toItalyRegionVenetoEthnicityAdriatic VenetiEraattested 6th–1st century BCE[1]Language familyIndo-European Italic (?) orpara-Celtic (?)[2]VeneticWriting systemOld Italic (Venetic alphabet)Language code...

 

جُزء من سلسلة مقالات حولإنكار الإبادة الجماعية إنكار الإبادات والمجازر الإبادة الجماعية للأرمن Holodomor محرقة اليهود trivialization inversion حرب دولة الكونغو الحرة الإعلامية مذبحة نانجنغ Genocide of Serbs الإبادة الجماعية الإندونيسية لعام 1965-1966 الإبادة الجماعية في بنغلاديش 1971 الإبادة الجماع

 

جوشوا هارتو معلومات شخصية الميلاد 9 يناير 1979 (العمر 44 سنة)فيرجينيا الغربية، الولايات المتحدة مواطنة الولايات المتحدة  الزوجة ليز دبليو. غارسيا (2008–)  الحياة العملية المهنة ممثل اللغة الأم الإنجليزية  اللغات الإنجليزية  سنوات النشاط 1996-الآن المواقع IMDB صفحته على IMD...

Celeste Ciudad CelesteUbicación en el condado de Hunt en Texas Ubicación de Texas en EE. UU.Coordenadas 33°17′37″N 96°11′44″O / 33.2936, -96.1956Entidad Ciudad • País  Estados Unidos • Estado  Texas • Condado HuntSuperficie   • Total 2.86 km² • Tierra 2.86 km² • Agua (0%) 0 km²Altitud   • Media 204 m s. n. m.Población (2010)   • Total 814 hab. • Densidad 284,...

 

For the 2003 movie, see Black Cadillac (film). 2006 studio album by Rosanne CashBlack CadillacStudio album by Rosanne CashReleasedJanuary 23, 2006[1]RecordedNovember 2004–July 2005GenreCountry Folk, AmericanaLength46:38LabelCapitolProducerBill Bottrell, John LeventhalRosanne Cash chronology The Very Best of Rosanne Cash(2005) Black Cadillac(2006) The List(2009) Professional ratingsReview scoresSourceRatingAllMusic[2]Rolling Stone[3] Black Cadillac is Rosanne ...

 

1968 film Matthew's DaysFilm posterDirected byWitold LeszczyńskiWritten byWitold LeszczyńskiWojciech SolarzTarjei VesaasStarringFranciszek PieczkaCinematographyAndrzej KostenkoEdited byZenon PióreckiRelease date 16 February 1968 (1968-02-16) Running time80 minutesCountryPolandLanguagePolish Matthew's Days (Polish: Żywot Mateusza) is a 1968 Polish drama film directed by Witold Leszczyński. It was listed to compete at the 1968 Cannes Film Festival,[1] but the festiva...

Naruto (musim 2)Musim 2Berkas:2ndstagenaruto.jpgGambar sampul musim 2Negara asalJepangJumlah episode43RilisSaluran asliTV TokyoTanggal tayang12 November 2003 (2003-11-12) –8 September 2004 (2004-9-8)Kronologi Musim← SebelumnyaMusim 1 Selanjutnya →Musim 3 Daftar episode Naruto Musim kedua dari serial anime Naruto yang disutradarai oleh Hayato Date, dan diproduksi oleh Studio Pierrot dan TV Tokyo. Berdasarkan pada serial manga Masashi Kishimoto,[1] musim t...

 

ChurchSt. Mary's Church, Moseley52°26′47″N 1°53′12″W / 52.4464°N 1.8866°W / 52.4464; -1.8866DenominationChurch of EnglandChurchmanshipBroad ChurchWebsiteBenefice websiteHistoryDedicationSt. MaryAdministrationProvinceProvince of CanterburyDioceseDiocese of BirminghamParishMoseleyClergyVicar(s)Currently searching for a new vicarPriest(s)The Revd Magdalen SmithHonorary priest(s)Revd Prof Frank Berry and Revd Caroline GeorgeLaityOrganist/Director of musicMick P...

 

シクストゥス4世Sixtus IV 第212代ローマ教皇 教皇就任 1471年8月9日教皇離任 1484年8月12日先代 パウルス2世次代 インノケンティウス8世個人情報出生 1414年7月21日 ジェノヴァ共和国、チェッレ・リーグレ死去 (1484-08-12) 1484年8月12日(70歳没) 教皇領、ローマその他のシクストゥステンプレートを表示 シクストゥス4世(シクストゥス4せい、Sixtus Ⅳ、1414年7月21日 - 1484年8月12日&...

In a vascular plant, the stele is the central part of the root or stem[1] containing the tissues derived from the procambium. These include vascular tissue, in some cases ground tissue (pith) and a pericycle, which, if present, defines the outermost boundary of the stele. Outside the stele lies the endodermis, which is the innermost cell layer of the cortex. The concept of the stele was developed in the late 19th century by French botanists P. E. L. van Tieghem and H. Doultion as a mo...

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (أكتوبر 2016) إيمانويل ديفيد تاننباوم معلومات شخصية الميلاد 28 يونيو 1978(1978-06-28)القدس  تاريخ الوفاة 28 مايو 2012 (33 سنة) [1] مواطنة إسرائيل  الحياة العملية المدرسة الأم ...

 

This article includes a list of general references, but it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (May 2011) (Learn how and when to remove this template message) 2011 promotional single by Thirty Seconds to MarsNight of the HunterPromotional single by Thirty Seconds to Marsfrom the album This Is War ReleasedApril 8, 2011Recorded2008–2009The International Centre for the Advancement of the Arts and Sciences o...

ɸ beralih ke halaman ini. Untuk Huruf Yunani, lihat Phi. Untuk Huruf Kiril, lihat Ef (Kiril). Untuk huruf Armenia, lihat Piwr (huruf). Konsonan geser dwibibir nirsuaraɸNomor IPA126Pengkodean karakterEntitas (desimal)&#632;Unikode (heks)U+0278X-SAMPAp\KirshenbaumPBraille Gambar Sampel suaranoicon sumber · bantuan Konsonan geser dwibibir nirsuara adalah jenis dari suara konsonan dwibibir yang digunakan dalam berbagai bahasa. Simbol IPAnya adalah ⟨ɸ⟩. Dalam bahasa Indone...

 

Japanese manga series by Ryo Ikuemi Kiyoku YawakuCover of the last volume of Kiyoku Yawaku潔く柔く MangaWritten byRyo IkuemiPublished byShueishaMagazineCookieDemographicShōjoOriginal runNovember 25, 2004 – 2010Volumes13 Live-action filmDirected byTakehiko ShinjōWritten bySatomi OshimaSachiko TanakaRyo IkuemiMusic byYoshihiro IkeStudioC&I EntertainmentReleased2013 (2013)Runtime127 minutes Kiyoku Yawaku (潔(きよ)く柔く, Innocently, Softly), al...

 

Rail link between Thuringia and Saxony The Mid-Germany Railway (German: Mitte-Deutschland-Verbindung) is a rail link between German states of Thuringia and Saxony. The central element of this link connects Chemnitz and Glauchau in the east via Gera and Jena to Weimar in the west. It includes the Dresden–Werdau line (between Chemnitz and Glauchau), the Glauchau–Gößnitz line, the Gera–Gößnitz line and the Weimar–Gera line. It is part of a possible direct rail connection from the Ruh...

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Februari 2023. Trichonius atlanticus Klasifikasi ilmiah Kerajaan: Animalia Filum: Arthropoda Kelas: Insecta Ordo: Coleoptera Famili: Cerambycidae Genus: Trichonius Spesies: Trichonius atlanticus Trichonius atlanticus adalah spesies kumbang tanduk panjang yang tergol...

 

Paolo De Ceglie De Ceglie nel 2009 Nazionalità  Italia Altezza 184[1] cm Peso 75[1] kg Calcio Ruolo Allenatore (ex difensore) Squadra  Juventus Coll. Tec. Giovanili Termine carriera 1º settembre 2021 - giocatore Carriera Giovanili 1996-2006 Juventus Squadre di club1 2006-2007 Juventus8 (1)2007-2008 Siena29 (2)2008-2014 Juventus90 (1)2014→  Genoa12 (1)2014-2015→  Parma11 (3)2015 Juventus2 (0)2015-2016→  Olympique Marsigl...

 

1996 Individual Ice Speedway World Championship Previous 1995 Next 1997 The 1996 Individual Ice Speedway World Championship was the 31st edition of the World Championship [1] The Championship was held as a Grand Prix series over ten rounds.[2] [3] Alexander Balashov of Russia won his second World title. Classification Pos Rider Pts 1 Alexander Balashov 2 Juri Polikarpov 3 Vyacheslav Nikulin 4 Vladimir Fadeev 5 Vladimir Lumpov 6 Per-Olof Serenius 7 Stefan Svensson 8 Mi...

У этого термина существуют и другие значения, см. Импрессионизм (значения). Импрессионизм Дата основания / создания / возникновения 1860-е Названо в честь Впечатление. Восходящее солнце Следующее по порядку постимпрессионизм и экспрессионизм Первооткрыватель или изоб...

 

Suratan puniki Wikipédia:Ubuh, suksmanipun nénten wénten suratan liyanan sané madué pranala balik ring suratan puniki. Ngiring dagingin pranala ka suratan puniki saking suratan sané gelah hubungan utawi coba piranti pangrereh pranala. I Lelipi tekén Sang GarudaSatuaAranI Lelipi tekén Sang GarudaTasih kasub maarann.nDataMitologin.nNegaraIndonésiaWewidanganBaliPinanggal asaln.n Satua I Lelipi tekén Sang Garuda inggih punika silih tunggil satua beburonan ring satua Bali.[1 ...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!