NewGVN.cpp 172 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283
  1. //===- NewGVN.cpp - Global Value Numbering Pass ---------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. /// \file
  10. /// This file implements the new LLVM's Global Value Numbering pass.
  11. /// GVN partitions values computed by a function into congruence classes.
  12. /// Values ending up in the same congruence class are guaranteed to be the same
  13. /// for every execution of the program. In that respect, congruency is a
  14. /// compile-time approximation of equivalence of values at runtime.
  15. /// The algorithm implemented here uses a sparse formulation and it's based
  16. /// on the ideas described in the paper:
  17. /// "A Sparse Algorithm for Predicated Global Value Numbering" from
  18. /// Karthik Gargi.
  19. ///
  20. /// A brief overview of the algorithm: The algorithm is essentially the same as
  21. /// the standard RPO value numbering algorithm (a good reference is the paper
  22. /// "SCC based value numbering" by L. Taylor Simpson) with one major difference:
  23. /// The RPO algorithm proceeds, on every iteration, to process every reachable
  24. /// block and every instruction in that block. This is because the standard RPO
  25. /// algorithm does not track what things have the same value number, it only
  26. /// tracks what the value number of a given operation is (the mapping is
  27. /// operation -> value number). Thus, when a value number of an operation
  28. /// changes, it must reprocess everything to ensure all uses of a value number
  29. /// get updated properly. In constrast, the sparse algorithm we use *also*
  30. /// tracks what operations have a given value number (IE it also tracks the
  31. /// reverse mapping from value number -> operations with that value number), so
  32. /// that it only needs to reprocess the instructions that are affected when
  33. /// something's value number changes. The vast majority of complexity and code
  34. /// in this file is devoted to tracking what value numbers could change for what
  35. /// instructions when various things happen. The rest of the algorithm is
  36. /// devoted to performing symbolic evaluation, forward propagation, and
  37. /// simplification of operations based on the value numbers deduced so far
  38. ///
  39. /// In order to make the GVN mostly-complete, we use a technique derived from
  40. /// "Detection of Redundant Expressions: A Complete and Polynomial-time
  41. /// Algorithm in SSA" by R.R. Pai. The source of incompleteness in most SSA
  42. /// based GVN algorithms is related to their inability to detect equivalence
  43. /// between phi of ops (IE phi(a+b, c+d)) and op of phis (phi(a,c) + phi(b, d)).
  44. /// We resolve this issue by generating the equivalent "phi of ops" form for
  45. /// each op of phis we see, in a way that only takes polynomial time to resolve.
  46. ///
  47. /// We also do not perform elimination by using any published algorithm. All
  48. /// published algorithms are O(Instructions). Instead, we use a technique that
  49. /// is O(number of operations with the same value number), enabling us to skip
  50. /// trying to eliminate things that have unique value numbers.
  51. //
  52. //===----------------------------------------------------------------------===//
  53. #include "llvm/Transforms/Scalar/NewGVN.h"
  54. #include "llvm/ADT/ArrayRef.h"
  55. #include "llvm/ADT/BitVector.h"
  56. #include "llvm/ADT/DenseMap.h"
  57. #include "llvm/ADT/DenseMapInfo.h"
  58. #include "llvm/ADT/DenseSet.h"
  59. #include "llvm/ADT/DepthFirstIterator.h"
  60. #include "llvm/ADT/GraphTraits.h"
  61. #include "llvm/ADT/Hashing.h"
  62. #include "llvm/ADT/PointerIntPair.h"
  63. #include "llvm/ADT/PostOrderIterator.h"
  64. #include "llvm/ADT/SetOperations.h"
  65. #include "llvm/ADT/SmallPtrSet.h"
  66. #include "llvm/ADT/SmallVector.h"
  67. #include "llvm/ADT/SparseBitVector.h"
  68. #include "llvm/ADT/Statistic.h"
  69. #include "llvm/ADT/iterator_range.h"
  70. #include "llvm/Analysis/AliasAnalysis.h"
  71. #include "llvm/Analysis/AssumptionCache.h"
  72. #include "llvm/Analysis/CFGPrinter.h"
  73. #include "llvm/Analysis/ConstantFolding.h"
  74. #include "llvm/Analysis/GlobalsModRef.h"
  75. #include "llvm/Analysis/InstructionSimplify.h"
  76. #include "llvm/Analysis/MemoryBuiltins.h"
  77. #include "llvm/Analysis/MemorySSA.h"
  78. #include "llvm/Analysis/TargetLibraryInfo.h"
  79. #include "llvm/Analysis/ValueTracking.h"
  80. #include "llvm/IR/Argument.h"
  81. #include "llvm/IR/BasicBlock.h"
  82. #include "llvm/IR/Constant.h"
  83. #include "llvm/IR/Constants.h"
  84. #include "llvm/IR/Dominators.h"
  85. #include "llvm/IR/Function.h"
  86. #include "llvm/IR/InstrTypes.h"
  87. #include "llvm/IR/Instruction.h"
  88. #include "llvm/IR/Instructions.h"
  89. #include "llvm/IR/IntrinsicInst.h"
  90. #include "llvm/IR/PatternMatch.h"
  91. #include "llvm/IR/Type.h"
  92. #include "llvm/IR/Use.h"
  93. #include "llvm/IR/User.h"
  94. #include "llvm/IR/Value.h"
  95. #include "llvm/InitializePasses.h"
  96. #include "llvm/Pass.h"
  97. #include "llvm/Support/Allocator.h"
  98. #include "llvm/Support/ArrayRecycler.h"
  99. #include "llvm/Support/Casting.h"
  100. #include "llvm/Support/CommandLine.h"
  101. #include "llvm/Support/Debug.h"
  102. #include "llvm/Support/DebugCounter.h"
  103. #include "llvm/Support/ErrorHandling.h"
  104. #include "llvm/Support/PointerLikeTypeTraits.h"
  105. #include "llvm/Support/raw_ostream.h"
  106. #include "llvm/Transforms/Scalar.h"
  107. #include "llvm/Transforms/Scalar/GVNExpression.h"
  108. #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
  109. #include "llvm/Transforms/Utils/Local.h"
  110. #include "llvm/Transforms/Utils/PredicateInfo.h"
  111. #include "llvm/Transforms/Utils/VNCoercion.h"
  112. #include <algorithm>
  113. #include <cassert>
  114. #include <cstdint>
  115. #include <iterator>
  116. #include <map>
  117. #include <memory>
  118. #include <set>
  119. #include <string>
  120. #include <tuple>
  121. #include <utility>
  122. #include <vector>
  123. using namespace llvm;
  124. using namespace llvm::GVNExpression;
  125. using namespace llvm::VNCoercion;
  126. using namespace llvm::PatternMatch;
  127. #define DEBUG_TYPE "newgvn"
  128. STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
  129. STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
  130. STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
  131. STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
  132. STATISTIC(NumGVNMaxIterations,
  133. "Maximum Number of iterations it took to converge GVN");
  134. STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
  135. STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
  136. STATISTIC(NumGVNAvoidedSortedLeaderChanges,
  137. "Number of avoided sorted leader changes");
  138. STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
  139. STATISTIC(NumGVNPHIOfOpsCreated, "Number of PHI of ops created");
  140. STATISTIC(NumGVNPHIOfOpsEliminations,
  141. "Number of things eliminated using PHI of ops");
  142. DEBUG_COUNTER(VNCounter, "newgvn-vn",
  143. "Controls which instructions are value numbered");
  144. DEBUG_COUNTER(PHIOfOpsCounter, "newgvn-phi",
  145. "Controls which instructions we create phi of ops for");
  146. // Currently store defining access refinement is too slow due to basicaa being
  147. // egregiously slow. This flag lets us keep it working while we work on this
  148. // issue.
  149. static cl::opt<bool> EnableStoreRefinement("enable-store-refinement",
  150. cl::init(false), cl::Hidden);
  151. /// Currently, the generation "phi of ops" can result in correctness issues.
  152. static cl::opt<bool> EnablePhiOfOps("enable-phi-of-ops", cl::init(true),
  153. cl::Hidden);
  154. //===----------------------------------------------------------------------===//
  155. // GVN Pass
  156. //===----------------------------------------------------------------------===//
  157. // Anchor methods.
  158. namespace llvm {
  159. namespace GVNExpression {
  160. Expression::~Expression() = default;
  161. BasicExpression::~BasicExpression() = default;
  162. CallExpression::~CallExpression() = default;
  163. LoadExpression::~LoadExpression() = default;
  164. StoreExpression::~StoreExpression() = default;
  165. AggregateValueExpression::~AggregateValueExpression() = default;
  166. PHIExpression::~PHIExpression() = default;
  167. } // end namespace GVNExpression
  168. } // end namespace llvm
  169. namespace {
  170. // Tarjan's SCC finding algorithm with Nuutila's improvements
  171. // SCCIterator is actually fairly complex for the simple thing we want.
  172. // It also wants to hand us SCC's that are unrelated to the phi node we ask
  173. // about, and have us process them there or risk redoing work.
  174. // Graph traits over a filter iterator also doesn't work that well here.
  175. // This SCC finder is specialized to walk use-def chains, and only follows
  176. // instructions,
  177. // not generic values (arguments, etc).
  178. struct TarjanSCC {
  179. TarjanSCC() : Components(1) {}
  180. void Start(const Instruction *Start) {
  181. if (Root.lookup(Start) == 0)
  182. FindSCC(Start);
  183. }
  184. const SmallPtrSetImpl<const Value *> &getComponentFor(const Value *V) const {
  185. unsigned ComponentID = ValueToComponent.lookup(V);
  186. assert(ComponentID > 0 &&
  187. "Asking for a component for a value we never processed");
  188. return Components[ComponentID];
  189. }
  190. private:
  191. void FindSCC(const Instruction *I) {
  192. Root[I] = ++DFSNum;
  193. // Store the DFS Number we had before it possibly gets incremented.
  194. unsigned int OurDFS = DFSNum;
  195. for (const auto &Op : I->operands()) {
  196. if (auto *InstOp = dyn_cast<Instruction>(Op)) {
  197. if (Root.lookup(Op) == 0)
  198. FindSCC(InstOp);
  199. if (!InComponent.count(Op))
  200. Root[I] = std::min(Root.lookup(I), Root.lookup(Op));
  201. }
  202. }
  203. // See if we really were the root of a component, by seeing if we still have
  204. // our DFSNumber. If we do, we are the root of the component, and we have
  205. // completed a component. If we do not, we are not the root of a component,
  206. // and belong on the component stack.
  207. if (Root.lookup(I) == OurDFS) {
  208. unsigned ComponentID = Components.size();
  209. Components.resize(Components.size() + 1);
  210. auto &Component = Components.back();
  211. Component.insert(I);
  212. LLVM_DEBUG(dbgs() << "Component root is " << *I << "\n");
  213. InComponent.insert(I);
  214. ValueToComponent[I] = ComponentID;
  215. // Pop a component off the stack and label it.
  216. while (!Stack.empty() && Root.lookup(Stack.back()) >= OurDFS) {
  217. auto *Member = Stack.back();
  218. LLVM_DEBUG(dbgs() << "Component member is " << *Member << "\n");
  219. Component.insert(Member);
  220. InComponent.insert(Member);
  221. ValueToComponent[Member] = ComponentID;
  222. Stack.pop_back();
  223. }
  224. } else {
  225. // Part of a component, push to stack
  226. Stack.push_back(I);
  227. }
  228. }
  229. unsigned int DFSNum = 1;
  230. SmallPtrSet<const Value *, 8> InComponent;
  231. DenseMap<const Value *, unsigned int> Root;
  232. SmallVector<const Value *, 8> Stack;
  233. // Store the components as vector of ptr sets, because we need the topo order
  234. // of SCC's, but not individual member order
  235. SmallVector<SmallPtrSet<const Value *, 8>, 8> Components;
  236. DenseMap<const Value *, unsigned> ValueToComponent;
  237. };
  238. // Congruence classes represent the set of expressions/instructions
  239. // that are all the same *during some scope in the function*.
  240. // That is, because of the way we perform equality propagation, and
  241. // because of memory value numbering, it is not correct to assume
  242. // you can willy-nilly replace any member with any other at any
  243. // point in the function.
  244. //
  245. // For any Value in the Member set, it is valid to replace any dominated member
  246. // with that Value.
  247. //
  248. // Every congruence class has a leader, and the leader is used to symbolize
  249. // instructions in a canonical way (IE every operand of an instruction that is a
  250. // member of the same congruence class will always be replaced with leader
  251. // during symbolization). To simplify symbolization, we keep the leader as a
  252. // constant if class can be proved to be a constant value. Otherwise, the
  253. // leader is the member of the value set with the smallest DFS number. Each
  254. // congruence class also has a defining expression, though the expression may be
  255. // null. If it exists, it can be used for forward propagation and reassociation
  256. // of values.
  257. // For memory, we also track a representative MemoryAccess, and a set of memory
  258. // members for MemoryPhis (which have no real instructions). Note that for
  259. // memory, it seems tempting to try to split the memory members into a
  260. // MemoryCongruenceClass or something. Unfortunately, this does not work
  261. // easily. The value numbering of a given memory expression depends on the
  262. // leader of the memory congruence class, and the leader of memory congruence
  263. // class depends on the value numbering of a given memory expression. This
  264. // leads to wasted propagation, and in some cases, missed optimization. For
  265. // example: If we had value numbered two stores together before, but now do not,
  266. // we move them to a new value congruence class. This in turn will move at one
  267. // of the memorydefs to a new memory congruence class. Which in turn, affects
  268. // the value numbering of the stores we just value numbered (because the memory
  269. // congruence class is part of the value number). So while theoretically
  270. // possible to split them up, it turns out to be *incredibly* complicated to get
  271. // it to work right, because of the interdependency. While structurally
  272. // slightly messier, it is algorithmically much simpler and faster to do what we
  273. // do here, and track them both at once in the same class.
  274. // Note: The default iterators for this class iterate over values
  275. class CongruenceClass {
  276. public:
  277. using MemberType = Value;
  278. using MemberSet = SmallPtrSet<MemberType *, 4>;
  279. using MemoryMemberType = MemoryPhi;
  280. using MemoryMemberSet = SmallPtrSet<const MemoryMemberType *, 2>;
  281. explicit CongruenceClass(unsigned ID) : ID(ID) {}
  282. CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
  283. : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
  284. unsigned getID() const { return ID; }
  285. // True if this class has no members left. This is mainly used for assertion
  286. // purposes, and for skipping empty classes.
  287. bool isDead() const {
  288. // If it's both dead from a value perspective, and dead from a memory
  289. // perspective, it's really dead.
  290. return empty() && memory_empty();
  291. }
  292. // Leader functions
  293. Value *getLeader() const { return RepLeader; }
  294. void setLeader(Value *Leader) { RepLeader = Leader; }
  295. const std::pair<Value *, unsigned int> &getNextLeader() const {
  296. return NextLeader;
  297. }
  298. void resetNextLeader() { NextLeader = {nullptr, ~0}; }
  299. void addPossibleNextLeader(std::pair<Value *, unsigned int> LeaderPair) {
  300. if (LeaderPair.second < NextLeader.second)
  301. NextLeader = LeaderPair;
  302. }
  303. Value *getStoredValue() const { return RepStoredValue; }
  304. void setStoredValue(Value *Leader) { RepStoredValue = Leader; }
  305. const MemoryAccess *getMemoryLeader() const { return RepMemoryAccess; }
  306. void setMemoryLeader(const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
  307. // Forward propagation info
  308. const Expression *getDefiningExpr() const { return DefiningExpr; }
  309. // Value member set
  310. bool empty() const { return Members.empty(); }
  311. unsigned size() const { return Members.size(); }
  312. MemberSet::const_iterator begin() const { return Members.begin(); }
  313. MemberSet::const_iterator end() const { return Members.end(); }
  314. void insert(MemberType *M) { Members.insert(M); }
  315. void erase(MemberType *M) { Members.erase(M); }
  316. void swap(MemberSet &Other) { Members.swap(Other); }
  317. // Memory member set
  318. bool memory_empty() const { return MemoryMembers.empty(); }
  319. unsigned memory_size() const { return MemoryMembers.size(); }
  320. MemoryMemberSet::const_iterator memory_begin() const {
  321. return MemoryMembers.begin();
  322. }
  323. MemoryMemberSet::const_iterator memory_end() const {
  324. return MemoryMembers.end();
  325. }
  326. iterator_range<MemoryMemberSet::const_iterator> memory() const {
  327. return make_range(memory_begin(), memory_end());
  328. }
  329. void memory_insert(const MemoryMemberType *M) { MemoryMembers.insert(M); }
  330. void memory_erase(const MemoryMemberType *M) { MemoryMembers.erase(M); }
  331. // Store count
  332. unsigned getStoreCount() const { return StoreCount; }
  333. void incStoreCount() { ++StoreCount; }
  334. void decStoreCount() {
  335. assert(StoreCount != 0 && "Store count went negative");
  336. --StoreCount;
  337. }
  338. // True if this class has no memory members.
  339. bool definesNoMemory() const { return StoreCount == 0 && memory_empty(); }
  340. // Return true if two congruence classes are equivalent to each other. This
  341. // means that every field but the ID number and the dead field are equivalent.
  342. bool isEquivalentTo(const CongruenceClass *Other) const {
  343. if (!Other)
  344. return false;
  345. if (this == Other)
  346. return true;
  347. if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
  348. std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
  349. Other->RepMemoryAccess))
  350. return false;
  351. if (DefiningExpr != Other->DefiningExpr)
  352. if (!DefiningExpr || !Other->DefiningExpr ||
  353. *DefiningExpr != *Other->DefiningExpr)
  354. return false;
  355. if (Members.size() != Other->Members.size())
  356. return false;
  357. return llvm::set_is_subset(Members, Other->Members);
  358. }
  359. private:
  360. unsigned ID;
  361. // Representative leader.
  362. Value *RepLeader = nullptr;
  363. // The most dominating leader after our current leader, because the member set
  364. // is not sorted and is expensive to keep sorted all the time.
  365. std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
  366. // If this is represented by a store, the value of the store.
  367. Value *RepStoredValue = nullptr;
  368. // If this class contains MemoryDefs or MemoryPhis, this is the leading memory
  369. // access.
  370. const MemoryAccess *RepMemoryAccess = nullptr;
  371. // Defining Expression.
  372. const Expression *DefiningExpr = nullptr;
  373. // Actual members of this class.
  374. MemberSet Members;
  375. // This is the set of MemoryPhis that exist in the class. MemoryDefs and
  376. // MemoryUses have real instructions representing them, so we only need to
  377. // track MemoryPhis here.
  378. MemoryMemberSet MemoryMembers;
  379. // Number of stores in this congruence class.
  380. // This is used so we can detect store equivalence changes properly.
  381. int StoreCount = 0;
  382. };
  383. } // end anonymous namespace
  384. namespace llvm {
  385. struct ExactEqualsExpression {
  386. const Expression &E;
  387. explicit ExactEqualsExpression(const Expression &E) : E(E) {}
  388. hash_code getComputedHash() const { return E.getComputedHash(); }
  389. bool operator==(const Expression &Other) const {
  390. return E.exactlyEquals(Other);
  391. }
  392. };
  393. template <> struct DenseMapInfo<const Expression *> {
  394. static const Expression *getEmptyKey() {
  395. auto Val = static_cast<uintptr_t>(-1);
  396. Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
  397. return reinterpret_cast<const Expression *>(Val);
  398. }
  399. static const Expression *getTombstoneKey() {
  400. auto Val = static_cast<uintptr_t>(~1U);
  401. Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
  402. return reinterpret_cast<const Expression *>(Val);
  403. }
  404. static unsigned getHashValue(const Expression *E) {
  405. return E->getComputedHash();
  406. }
  407. static unsigned getHashValue(const ExactEqualsExpression &E) {
  408. return E.getComputedHash();
  409. }
  410. static bool isEqual(const ExactEqualsExpression &LHS, const Expression *RHS) {
  411. if (RHS == getTombstoneKey() || RHS == getEmptyKey())
  412. return false;
  413. return LHS == *RHS;
  414. }
  415. static bool isEqual(const Expression *LHS, const Expression *RHS) {
  416. if (LHS == RHS)
  417. return true;
  418. if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
  419. LHS == getEmptyKey() || RHS == getEmptyKey())
  420. return false;
  421. // Compare hashes before equality. This is *not* what the hashtable does,
  422. // since it is computing it modulo the number of buckets, whereas we are
  423. // using the full hash keyspace. Since the hashes are precomputed, this
  424. // check is *much* faster than equality.
  425. if (LHS->getComputedHash() != RHS->getComputedHash())
  426. return false;
  427. return *LHS == *RHS;
  428. }
  429. };
  430. } // end namespace llvm
  431. namespace {
  432. class NewGVN {
  433. Function &F;
  434. DominatorTree *DT = nullptr;
  435. const TargetLibraryInfo *TLI = nullptr;
  436. AliasAnalysis *AA = nullptr;
  437. MemorySSA *MSSA = nullptr;
  438. MemorySSAWalker *MSSAWalker = nullptr;
  439. AssumptionCache *AC = nullptr;
  440. const DataLayout &DL;
  441. std::unique_ptr<PredicateInfo> PredInfo;
  442. // These are the only two things the create* functions should have
  443. // side-effects on due to allocating memory.
  444. mutable BumpPtrAllocator ExpressionAllocator;
  445. mutable ArrayRecycler<Value *> ArgRecycler;
  446. mutable TarjanSCC SCCFinder;
  447. const SimplifyQuery SQ;
  448. // Number of function arguments, used by ranking
  449. unsigned int NumFuncArgs = 0;
  450. // RPOOrdering of basic blocks
  451. DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
  452. // Congruence class info.
  453. // This class is called INITIAL in the paper. It is the class everything
  454. // startsout in, and represents any value. Being an optimistic analysis,
  455. // anything in the TOP class has the value TOP, which is indeterminate and
  456. // equivalent to everything.
  457. CongruenceClass *TOPClass = nullptr;
  458. std::vector<CongruenceClass *> CongruenceClasses;
  459. unsigned NextCongruenceNum = 0;
  460. // Value Mappings.
  461. DenseMap<Value *, CongruenceClass *> ValueToClass;
  462. DenseMap<Value *, const Expression *> ValueToExpression;
  463. // Value PHI handling, used to make equivalence between phi(op, op) and
  464. // op(phi, phi).
  465. // These mappings just store various data that would normally be part of the
  466. // IR.
  467. SmallPtrSet<const Instruction *, 8> PHINodeUses;
  468. DenseMap<const Value *, bool> OpSafeForPHIOfOps;
  469. // Map a temporary instruction we created to a parent block.
  470. DenseMap<const Value *, BasicBlock *> TempToBlock;
  471. // Map between the already in-program instructions and the temporary phis we
  472. // created that they are known equivalent to.
  473. DenseMap<const Value *, PHINode *> RealToTemp;
  474. // In order to know when we should re-process instructions that have
  475. // phi-of-ops, we track the set of expressions that they needed as
  476. // leaders. When we discover new leaders for those expressions, we process the
  477. // associated phi-of-op instructions again in case they have changed. The
  478. // other way they may change is if they had leaders, and those leaders
  479. // disappear. However, at the point they have leaders, there are uses of the
  480. // relevant operands in the created phi node, and so they will get reprocessed
  481. // through the normal user marking we perform.
  482. mutable DenseMap<const Value *, SmallPtrSet<Value *, 2>> AdditionalUsers;
  483. DenseMap<const Expression *, SmallPtrSet<Instruction *, 2>>
  484. ExpressionToPhiOfOps;
  485. // Map from temporary operation to MemoryAccess.
  486. DenseMap<const Instruction *, MemoryUseOrDef *> TempToMemory;
  487. // Set of all temporary instructions we created.
  488. // Note: This will include instructions that were just created during value
  489. // numbering. The way to test if something is using them is to check
  490. // RealToTemp.
  491. DenseSet<Instruction *> AllTempInstructions;
  492. // This is the set of instructions to revisit on a reachability change. At
  493. // the end of the main iteration loop it will contain at least all the phi of
  494. // ops instructions that will be changed to phis, as well as regular phis.
  495. // During the iteration loop, it may contain other things, such as phi of ops
  496. // instructions that used edge reachability to reach a result, and so need to
  497. // be revisited when the edge changes, independent of whether the phi they
  498. // depended on changes.
  499. DenseMap<BasicBlock *, SparseBitVector<>> RevisitOnReachabilityChange;
  500. // Mapping from predicate info we used to the instructions we used it with.
  501. // In order to correctly ensure propagation, we must keep track of what
  502. // comparisons we used, so that when the values of the comparisons change, we
  503. // propagate the information to the places we used the comparison.
  504. mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>>
  505. PredicateToUsers;
  506. // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for
  507. // stores, we no longer can rely solely on the def-use chains of MemorySSA.
  508. mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>>
  509. MemoryToUsers;
  510. // A table storing which memorydefs/phis represent a memory state provably
  511. // equivalent to another memory state.
  512. // We could use the congruence class machinery, but the MemoryAccess's are
  513. // abstract memory states, so they can only ever be equivalent to each other,
  514. // and not to constants, etc.
  515. DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
  516. // We could, if we wanted, build MemoryPhiExpressions and
  517. // MemoryVariableExpressions, etc, and value number them the same way we value
  518. // number phi expressions. For the moment, this seems like overkill. They
  519. // can only exist in one of three states: they can be TOP (equal to
  520. // everything), Equivalent to something else, or unique. Because we do not
  521. // create expressions for them, we need to simulate leader change not just
  522. // when they change class, but when they change state. Note: We can do the
  523. // same thing for phis, and avoid having phi expressions if we wanted, We
  524. // should eventually unify in one direction or the other, so this is a little
  525. // bit of an experiment in which turns out easier to maintain.
  526. enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
  527. DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
  528. enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
  529. mutable DenseMap<const Instruction *, InstCycleState> InstCycleState;
  530. // Expression to class mapping.
  531. using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
  532. ExpressionClassMap ExpressionToClass;
  533. // We have a single expression that represents currently DeadExpressions.
  534. // For dead expressions we can prove will stay dead, we mark them with
  535. // DFS number zero. However, it's possible in the case of phi nodes
  536. // for us to assume/prove all arguments are dead during fixpointing.
  537. // We use DeadExpression for that case.
  538. DeadExpression *SingletonDeadExpression = nullptr;
  539. // Which values have changed as a result of leader changes.
  540. SmallPtrSet<Value *, 8> LeaderChanges;
  541. // Reachability info.
  542. using BlockEdge = BasicBlockEdge;
  543. DenseSet<BlockEdge> ReachableEdges;
  544. SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
  545. // This is a bitvector because, on larger functions, we may have
  546. // thousands of touched instructions at once (entire blocks,
  547. // instructions with hundreds of uses, etc). Even with optimization
  548. // for when we mark whole blocks as touched, when this was a
  549. // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
  550. // the time in GVN just managing this list. The bitvector, on the
  551. // other hand, efficiently supports test/set/clear of both
  552. // individual and ranges, as well as "find next element" This
  553. // enables us to use it as a worklist with essentially 0 cost.
  554. BitVector TouchedInstructions;
  555. DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
  556. mutable DenseMap<const IntrinsicInst *, const Value *> IntrinsicInstPred;
  557. #ifndef NDEBUG
  558. // Debugging for how many times each block and instruction got processed.
  559. DenseMap<const Value *, unsigned> ProcessedCount;
  560. #endif
  561. // DFS info.
  562. // This contains a mapping from Instructions to DFS numbers.
  563. // The numbering starts at 1. An instruction with DFS number zero
  564. // means that the instruction is dead.
  565. DenseMap<const Value *, unsigned> InstrDFS;
  566. // This contains the mapping DFS numbers to instructions.
  567. SmallVector<Value *, 32> DFSToInstr;
  568. // Deletion info.
  569. SmallPtrSet<Instruction *, 8> InstructionsToErase;
  570. public:
  571. NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
  572. TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
  573. const DataLayout &DL)
  574. : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), AC(AC), DL(DL),
  575. PredInfo(std::make_unique<PredicateInfo>(F, *DT, *AC)),
  576. SQ(DL, TLI, DT, AC, /*CtxI=*/nullptr, /*UseInstrInfo=*/false,
  577. /*CanUseUndef=*/false) {}
  578. bool runGVN();
  579. private:
  580. /// Helper struct return a Expression with an optional extra dependency.
  581. struct ExprResult {
  582. const Expression *Expr;
  583. Value *ExtraDep;
  584. const PredicateBase *PredDep;
  585. ExprResult(const Expression *Expr, Value *ExtraDep = nullptr,
  586. const PredicateBase *PredDep = nullptr)
  587. : Expr(Expr), ExtraDep(ExtraDep), PredDep(PredDep) {}
  588. ExprResult(const ExprResult &) = delete;
  589. ExprResult(ExprResult &&Other)
  590. : Expr(Other.Expr), ExtraDep(Other.ExtraDep), PredDep(Other.PredDep) {
  591. Other.Expr = nullptr;
  592. Other.ExtraDep = nullptr;
  593. Other.PredDep = nullptr;
  594. }
  595. ExprResult &operator=(const ExprResult &Other) = delete;
  596. ExprResult &operator=(ExprResult &&Other) = delete;
  597. ~ExprResult() { assert(!ExtraDep && "unhandled ExtraDep"); }
  598. operator bool() const { return Expr; }
  599. static ExprResult none() { return {nullptr, nullptr, nullptr}; }
  600. static ExprResult some(const Expression *Expr, Value *ExtraDep = nullptr) {
  601. return {Expr, ExtraDep, nullptr};
  602. }
  603. static ExprResult some(const Expression *Expr,
  604. const PredicateBase *PredDep) {
  605. return {Expr, nullptr, PredDep};
  606. }
  607. static ExprResult some(const Expression *Expr, Value *ExtraDep,
  608. const PredicateBase *PredDep) {
  609. return {Expr, ExtraDep, PredDep};
  610. }
  611. };
  612. // Expression handling.
  613. ExprResult createExpression(Instruction *) const;
  614. const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
  615. Instruction *) const;
  616. // Our canonical form for phi arguments is a pair of incoming value, incoming
  617. // basic block.
  618. using ValPair = std::pair<Value *, BasicBlock *>;
  619. PHIExpression *createPHIExpression(ArrayRef<ValPair>, const Instruction *,
  620. BasicBlock *, bool &HasBackEdge,
  621. bool &OriginalOpsConstant) const;
  622. const DeadExpression *createDeadExpression() const;
  623. const VariableExpression *createVariableExpression(Value *) const;
  624. const ConstantExpression *createConstantExpression(Constant *) const;
  625. const Expression *createVariableOrConstant(Value *V) const;
  626. const UnknownExpression *createUnknownExpression(Instruction *) const;
  627. const StoreExpression *createStoreExpression(StoreInst *,
  628. const MemoryAccess *) const;
  629. LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
  630. const MemoryAccess *) const;
  631. const CallExpression *createCallExpression(CallInst *,
  632. const MemoryAccess *) const;
  633. const AggregateValueExpression *
  634. createAggregateValueExpression(Instruction *) const;
  635. bool setBasicExpressionInfo(Instruction *, BasicExpression *) const;
  636. // Congruence class handling.
  637. CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
  638. auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
  639. CongruenceClasses.emplace_back(result);
  640. return result;
  641. }
  642. CongruenceClass *createMemoryClass(MemoryAccess *MA) {
  643. auto *CC = createCongruenceClass(nullptr, nullptr);
  644. CC->setMemoryLeader(MA);
  645. return CC;
  646. }
  647. CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
  648. auto *CC = getMemoryClass(MA);
  649. if (CC->getMemoryLeader() != MA)
  650. CC = createMemoryClass(MA);
  651. return CC;
  652. }
  653. CongruenceClass *createSingletonCongruenceClass(Value *Member) {
  654. CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
  655. CClass->insert(Member);
  656. ValueToClass[Member] = CClass;
  657. return CClass;
  658. }
  659. void initializeCongruenceClasses(Function &F);
  660. const Expression *makePossiblePHIOfOps(Instruction *,
  661. SmallPtrSetImpl<Value *> &);
  662. Value *findLeaderForInst(Instruction *ValueOp,
  663. SmallPtrSetImpl<Value *> &Visited,
  664. MemoryAccess *MemAccess, Instruction *OrigInst,
  665. BasicBlock *PredBB);
  666. bool OpIsSafeForPHIOfOps(Value *Op, const BasicBlock *PHIBlock,
  667. SmallPtrSetImpl<const Value *> &);
  668. void addPhiOfOps(PHINode *Op, BasicBlock *BB, Instruction *ExistingValue);
  669. void removePhiOfOps(Instruction *I, PHINode *PHITemp);
  670. // Value number an Instruction or MemoryPhi.
  671. void valueNumberMemoryPhi(MemoryPhi *);
  672. void valueNumberInstruction(Instruction *);
  673. // Symbolic evaluation.
  674. ExprResult checkExprResults(Expression *, Instruction *, Value *) const;
  675. ExprResult performSymbolicEvaluation(Value *,
  676. SmallPtrSetImpl<Value *> &) const;
  677. const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
  678. Instruction *,
  679. MemoryAccess *) const;
  680. const Expression *performSymbolicLoadEvaluation(Instruction *) const;
  681. const Expression *performSymbolicStoreEvaluation(Instruction *) const;
  682. ExprResult performSymbolicCallEvaluation(Instruction *) const;
  683. void sortPHIOps(MutableArrayRef<ValPair> Ops) const;
  684. const Expression *performSymbolicPHIEvaluation(ArrayRef<ValPair>,
  685. Instruction *I,
  686. BasicBlock *PHIBlock) const;
  687. const Expression *performSymbolicAggrValueEvaluation(Instruction *) const;
  688. ExprResult performSymbolicCmpEvaluation(Instruction *) const;
  689. ExprResult performSymbolicPredicateInfoEvaluation(IntrinsicInst *) const;
  690. // Congruence finding.
  691. bool someEquivalentDominates(const Instruction *, const Instruction *) const;
  692. Value *lookupOperandLeader(Value *) const;
  693. CongruenceClass *getClassForExpression(const Expression *E) const;
  694. void performCongruenceFinding(Instruction *, const Expression *);
  695. void moveValueToNewCongruenceClass(Instruction *, const Expression *,
  696. CongruenceClass *, CongruenceClass *);
  697. void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
  698. CongruenceClass *, CongruenceClass *);
  699. Value *getNextValueLeader(CongruenceClass *) const;
  700. const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
  701. bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
  702. CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
  703. const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
  704. bool isMemoryAccessTOP(const MemoryAccess *) const;
  705. // Ranking
  706. unsigned int getRank(const Value *) const;
  707. bool shouldSwapOperands(const Value *, const Value *) const;
  708. bool shouldSwapOperandsForIntrinsic(const Value *, const Value *,
  709. const IntrinsicInst *I) const;
  710. // Reachability handling.
  711. void updateReachableEdge(BasicBlock *, BasicBlock *);
  712. void processOutgoingEdges(Instruction *, BasicBlock *);
  713. Value *findConditionEquivalence(Value *) const;
  714. // Elimination.
  715. struct ValueDFS;
  716. void convertClassToDFSOrdered(const CongruenceClass &,
  717. SmallVectorImpl<ValueDFS> &,
  718. DenseMap<const Value *, unsigned int> &,
  719. SmallPtrSetImpl<Instruction *> &) const;
  720. void convertClassToLoadsAndStores(const CongruenceClass &,
  721. SmallVectorImpl<ValueDFS> &) const;
  722. bool eliminateInstructions(Function &);
  723. void replaceInstruction(Instruction *, Value *);
  724. void markInstructionForDeletion(Instruction *);
  725. void deleteInstructionsInBlock(BasicBlock *);
  726. Value *findPHIOfOpsLeader(const Expression *, const Instruction *,
  727. const BasicBlock *) const;
  728. // Various instruction touch utilities
  729. template <typename Map, typename KeyType>
  730. void touchAndErase(Map &, const KeyType &);
  731. void markUsersTouched(Value *);
  732. void markMemoryUsersTouched(const MemoryAccess *);
  733. void markMemoryDefTouched(const MemoryAccess *);
  734. void markPredicateUsersTouched(Instruction *);
  735. void markValueLeaderChangeTouched(CongruenceClass *CC);
  736. void markMemoryLeaderChangeTouched(CongruenceClass *CC);
  737. void markPhiOfOpsChanged(const Expression *E);
  738. void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const;
  739. void addAdditionalUsers(Value *To, Value *User) const;
  740. void addAdditionalUsers(ExprResult &Res, Instruction *User) const;
  741. // Main loop of value numbering
  742. void iterateTouchedInstructions();
  743. // Utilities.
  744. void cleanupTables();
  745. std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
  746. void updateProcessedCount(const Value *V);
  747. void verifyMemoryCongruency() const;
  748. void verifyIterationSettled(Function &F);
  749. void verifyStoreExpressions() const;
  750. bool singleReachablePHIPath(SmallPtrSet<const MemoryAccess *, 8> &,
  751. const MemoryAccess *, const MemoryAccess *) const;
  752. BasicBlock *getBlockForValue(Value *V) const;
  753. void deleteExpression(const Expression *E) const;
  754. MemoryUseOrDef *getMemoryAccess(const Instruction *) const;
  755. MemoryPhi *getMemoryAccess(const BasicBlock *) const;
  756. template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
  757. unsigned InstrToDFSNum(const Value *V) const {
  758. assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
  759. return InstrDFS.lookup(V);
  760. }
  761. unsigned InstrToDFSNum(const MemoryAccess *MA) const {
  762. return MemoryToDFSNum(MA);
  763. }
  764. Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
  765. // Given a MemoryAccess, return the relevant instruction DFS number. Note:
  766. // This deliberately takes a value so it can be used with Use's, which will
  767. // auto-convert to Value's but not to MemoryAccess's.
  768. unsigned MemoryToDFSNum(const Value *MA) const {
  769. assert(isa<MemoryAccess>(MA) &&
  770. "This should not be used with instructions");
  771. return isa<MemoryUseOrDef>(MA)
  772. ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
  773. : InstrDFS.lookup(MA);
  774. }
  775. bool isCycleFree(const Instruction *) const;
  776. bool isBackedge(BasicBlock *From, BasicBlock *To) const;
  777. // Debug counter info. When verifying, we have to reset the value numbering
  778. // debug counter to the same state it started in to get the same results.
  779. int64_t StartingVNCounter = 0;
  780. };
  781. } // end anonymous namespace
  782. template <typename T>
  783. static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
  784. if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
  785. return false;
  786. return LHS.MemoryExpression::equals(RHS);
  787. }
  788. bool LoadExpression::equals(const Expression &Other) const {
  789. return equalsLoadStoreHelper(*this, Other);
  790. }
  791. bool StoreExpression::equals(const Expression &Other) const {
  792. if (!equalsLoadStoreHelper(*this, Other))
  793. return false;
  794. // Make sure that store vs store includes the value operand.
  795. if (const auto *S = dyn_cast<StoreExpression>(&Other))
  796. if (getStoredValue() != S->getStoredValue())
  797. return false;
  798. return true;
  799. }
  800. // Determine if the edge From->To is a backedge
  801. bool NewGVN::isBackedge(BasicBlock *From, BasicBlock *To) const {
  802. return From == To ||
  803. RPOOrdering.lookup(DT->getNode(From)) >=
  804. RPOOrdering.lookup(DT->getNode(To));
  805. }
  806. #ifndef NDEBUG
  807. static std::string getBlockName(const BasicBlock *B) {
  808. return DOTGraphTraits<DOTFuncInfo *>::getSimpleNodeLabel(B, nullptr);
  809. }
  810. #endif
  811. // Get a MemoryAccess for an instruction, fake or real.
  812. MemoryUseOrDef *NewGVN::getMemoryAccess(const Instruction *I) const {
  813. auto *Result = MSSA->getMemoryAccess(I);
  814. return Result ? Result : TempToMemory.lookup(I);
  815. }
  816. // Get a MemoryPhi for a basic block. These are all real.
  817. MemoryPhi *NewGVN::getMemoryAccess(const BasicBlock *BB) const {
  818. return MSSA->getMemoryAccess(BB);
  819. }
  820. // Get the basic block from an instruction/memory value.
  821. BasicBlock *NewGVN::getBlockForValue(Value *V) const {
  822. if (auto *I = dyn_cast<Instruction>(V)) {
  823. auto *Parent = I->getParent();
  824. if (Parent)
  825. return Parent;
  826. Parent = TempToBlock.lookup(V);
  827. assert(Parent && "Every fake instruction should have a block");
  828. return Parent;
  829. }
  830. auto *MP = dyn_cast<MemoryPhi>(V);
  831. assert(MP && "Should have been an instruction or a MemoryPhi");
  832. return MP->getBlock();
  833. }
  834. // Delete a definitely dead expression, so it can be reused by the expression
  835. // allocator. Some of these are not in creation functions, so we have to accept
  836. // const versions.
  837. void NewGVN::deleteExpression(const Expression *E) const {
  838. assert(isa<BasicExpression>(E));
  839. auto *BE = cast<BasicExpression>(E);
  840. const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
  841. ExpressionAllocator.Deallocate(E);
  842. }
  843. // If V is a predicateinfo copy, get the thing it is a copy of.
  844. static Value *getCopyOf(const Value *V) {
  845. if (auto *II = dyn_cast<IntrinsicInst>(V))
  846. if (II->getIntrinsicID() == Intrinsic::ssa_copy)
  847. return II->getOperand(0);
  848. return nullptr;
  849. }
  850. // Return true if V is really PN, even accounting for predicateinfo copies.
  851. static bool isCopyOfPHI(const Value *V, const PHINode *PN) {
  852. return V == PN || getCopyOf(V) == PN;
  853. }
  854. static bool isCopyOfAPHI(const Value *V) {
  855. auto *CO = getCopyOf(V);
  856. return CO && isa<PHINode>(CO);
  857. }
  858. // Sort PHI Operands into a canonical order. What we use here is an RPO
  859. // order. The BlockInstRange numbers are generated in an RPO walk of the basic
  860. // blocks.
  861. void NewGVN::sortPHIOps(MutableArrayRef<ValPair> Ops) const {
  862. llvm::sort(Ops, [&](const ValPair &P1, const ValPair &P2) {
  863. return BlockInstRange.lookup(P1.second).first <
  864. BlockInstRange.lookup(P2.second).first;
  865. });
  866. }
  867. // Return true if V is a value that will always be available (IE can
  868. // be placed anywhere) in the function. We don't do globals here
  869. // because they are often worse to put in place.
  870. static bool alwaysAvailable(Value *V) {
  871. return isa<Constant>(V) || isa<Argument>(V);
  872. }
  873. // Create a PHIExpression from an array of {incoming edge, value} pairs. I is
  874. // the original instruction we are creating a PHIExpression for (but may not be
  875. // a phi node). We require, as an invariant, that all the PHIOperands in the
  876. // same block are sorted the same way. sortPHIOps will sort them into a
  877. // canonical order.
  878. PHIExpression *NewGVN::createPHIExpression(ArrayRef<ValPair> PHIOperands,
  879. const Instruction *I,
  880. BasicBlock *PHIBlock,
  881. bool &HasBackedge,
  882. bool &OriginalOpsConstant) const {
  883. unsigned NumOps = PHIOperands.size();
  884. auto *E = new (ExpressionAllocator) PHIExpression(NumOps, PHIBlock);
  885. E->allocateOperands(ArgRecycler, ExpressionAllocator);
  886. E->setType(PHIOperands.begin()->first->getType());
  887. E->setOpcode(Instruction::PHI);
  888. // Filter out unreachable phi operands.
  889. auto Filtered = make_filter_range(PHIOperands, [&](const ValPair &P) {
  890. auto *BB = P.second;
  891. if (auto *PHIOp = dyn_cast<PHINode>(I))
  892. if (isCopyOfPHI(P.first, PHIOp))
  893. return false;
  894. if (!ReachableEdges.count({BB, PHIBlock}))
  895. return false;
  896. // Things in TOPClass are equivalent to everything.
  897. if (ValueToClass.lookup(P.first) == TOPClass)
  898. return false;
  899. OriginalOpsConstant = OriginalOpsConstant && isa<Constant>(P.first);
  900. HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
  901. return lookupOperandLeader(P.first) != I;
  902. });
  903. std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
  904. [&](const ValPair &P) -> Value * {
  905. return lookupOperandLeader(P.first);
  906. });
  907. return E;
  908. }
  909. // Set basic expression info (Arguments, type, opcode) for Expression
  910. // E from Instruction I in block B.
  911. bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
  912. bool AllConstant = true;
  913. if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
  914. E->setType(GEP->getSourceElementType());
  915. else
  916. E->setType(I->getType());
  917. E->setOpcode(I->getOpcode());
  918. E->allocateOperands(ArgRecycler, ExpressionAllocator);
  919. // Transform the operand array into an operand leader array, and keep track of
  920. // whether all members are constant.
  921. std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
  922. auto Operand = lookupOperandLeader(O);
  923. AllConstant = AllConstant && isa<Constant>(Operand);
  924. return Operand;
  925. });
  926. return AllConstant;
  927. }
  928. const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
  929. Value *Arg1, Value *Arg2,
  930. Instruction *I) const {
  931. auto *E = new (ExpressionAllocator) BasicExpression(2);
  932. // TODO: we need to remove context instruction after Value Tracking
  933. // can run without context instruction
  934. const SimplifyQuery Q = SQ.getWithInstruction(I);
  935. E->setType(T);
  936. E->setOpcode(Opcode);
  937. E->allocateOperands(ArgRecycler, ExpressionAllocator);
  938. if (Instruction::isCommutative(Opcode)) {
  939. // Ensure that commutative instructions that only differ by a permutation
  940. // of their operands get the same value number by sorting the operand value
  941. // numbers. Since all commutative instructions have two operands it is more
  942. // efficient to sort by hand rather than using, say, std::sort.
  943. if (shouldSwapOperands(Arg1, Arg2))
  944. std::swap(Arg1, Arg2);
  945. }
  946. E->op_push_back(lookupOperandLeader(Arg1));
  947. E->op_push_back(lookupOperandLeader(Arg2));
  948. Value *V = simplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), Q);
  949. if (auto Simplified = checkExprResults(E, I, V)) {
  950. addAdditionalUsers(Simplified, I);
  951. return Simplified.Expr;
  952. }
  953. return E;
  954. }
  955. // Take a Value returned by simplification of Expression E/Instruction
  956. // I, and see if it resulted in a simpler expression. If so, return
  957. // that expression.
  958. NewGVN::ExprResult NewGVN::checkExprResults(Expression *E, Instruction *I,
  959. Value *V) const {
  960. if (!V)
  961. return ExprResult::none();
  962. if (auto *C = dyn_cast<Constant>(V)) {
  963. if (I)
  964. LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
  965. << " constant " << *C << "\n");
  966. NumGVNOpsSimplified++;
  967. assert(isa<BasicExpression>(E) &&
  968. "We should always have had a basic expression here");
  969. deleteExpression(E);
  970. return ExprResult::some(createConstantExpression(C));
  971. } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
  972. if (I)
  973. LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
  974. << " variable " << *V << "\n");
  975. deleteExpression(E);
  976. return ExprResult::some(createVariableExpression(V));
  977. }
  978. CongruenceClass *CC = ValueToClass.lookup(V);
  979. if (CC) {
  980. if (CC->getLeader() && CC->getLeader() != I) {
  981. return ExprResult::some(createVariableOrConstant(CC->getLeader()), V);
  982. }
  983. if (CC->getDefiningExpr()) {
  984. if (I)
  985. LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
  986. << " expression " << *CC->getDefiningExpr() << "\n");
  987. NumGVNOpsSimplified++;
  988. deleteExpression(E);
  989. return ExprResult::some(CC->getDefiningExpr(), V);
  990. }
  991. }
  992. return ExprResult::none();
  993. }
  994. // Create a value expression from the instruction I, replacing operands with
  995. // their leaders.
  996. NewGVN::ExprResult NewGVN::createExpression(Instruction *I) const {
  997. auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
  998. // TODO: we need to remove context instruction after Value Tracking
  999. // can run without context instruction
  1000. const SimplifyQuery Q = SQ.getWithInstruction(I);
  1001. bool AllConstant = setBasicExpressionInfo(I, E);
  1002. if (I->isCommutative()) {
  1003. // Ensure that commutative instructions that only differ by a permutation
  1004. // of their operands get the same value number by sorting the operand value
  1005. // numbers. Since all commutative instructions have two operands it is more
  1006. // efficient to sort by hand rather than using, say, std::sort.
  1007. assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
  1008. if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
  1009. E->swapOperands(0, 1);
  1010. }
  1011. // Perform simplification.
  1012. if (auto *CI = dyn_cast<CmpInst>(I)) {
  1013. // Sort the operand value numbers so x<y and y>x get the same value
  1014. // number.
  1015. CmpInst::Predicate Predicate = CI->getPredicate();
  1016. if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
  1017. E->swapOperands(0, 1);
  1018. Predicate = CmpInst::getSwappedPredicate(Predicate);
  1019. }
  1020. E->setOpcode((CI->getOpcode() << 8) | Predicate);
  1021. // TODO: 25% of our time is spent in simplifyCmpInst with pointer operands
  1022. assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
  1023. "Wrong types on cmp instruction");
  1024. assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
  1025. E->getOperand(1)->getType() == I->getOperand(1)->getType()));
  1026. Value *V =
  1027. simplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), Q);
  1028. if (auto Simplified = checkExprResults(E, I, V))
  1029. return Simplified;
  1030. } else if (isa<SelectInst>(I)) {
  1031. if (isa<Constant>(E->getOperand(0)) ||
  1032. E->getOperand(1) == E->getOperand(2)) {
  1033. assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
  1034. E->getOperand(2)->getType() == I->getOperand(2)->getType());
  1035. Value *V = simplifySelectInst(E->getOperand(0), E->getOperand(1),
  1036. E->getOperand(2), Q);
  1037. if (auto Simplified = checkExprResults(E, I, V))
  1038. return Simplified;
  1039. }
  1040. } else if (I->isBinaryOp()) {
  1041. Value *V =
  1042. simplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), Q);
  1043. if (auto Simplified = checkExprResults(E, I, V))
  1044. return Simplified;
  1045. } else if (auto *CI = dyn_cast<CastInst>(I)) {
  1046. Value *V =
  1047. simplifyCastInst(CI->getOpcode(), E->getOperand(0), CI->getType(), Q);
  1048. if (auto Simplified = checkExprResults(E, I, V))
  1049. return Simplified;
  1050. } else if (auto *GEPI = dyn_cast<GetElementPtrInst>(I)) {
  1051. Value *V = simplifyGEPInst(GEPI->getSourceElementType(), *E->op_begin(),
  1052. ArrayRef(std::next(E->op_begin()), E->op_end()),
  1053. GEPI->isInBounds(), Q);
  1054. if (auto Simplified = checkExprResults(E, I, V))
  1055. return Simplified;
  1056. } else if (AllConstant) {
  1057. // We don't bother trying to simplify unless all of the operands
  1058. // were constant.
  1059. // TODO: There are a lot of Simplify*'s we could call here, if we
  1060. // wanted to. The original motivating case for this code was a
  1061. // zext i1 false to i8, which we don't have an interface to
  1062. // simplify (IE there is no SimplifyZExt).
  1063. SmallVector<Constant *, 8> C;
  1064. for (Value *Arg : E->operands())
  1065. C.emplace_back(cast<Constant>(Arg));
  1066. if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
  1067. if (auto Simplified = checkExprResults(E, I, V))
  1068. return Simplified;
  1069. }
  1070. return ExprResult::some(E);
  1071. }
  1072. const AggregateValueExpression *
  1073. NewGVN::createAggregateValueExpression(Instruction *I) const {
  1074. if (auto *II = dyn_cast<InsertValueInst>(I)) {
  1075. auto *E = new (ExpressionAllocator)
  1076. AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
  1077. setBasicExpressionInfo(I, E);
  1078. E->allocateIntOperands(ExpressionAllocator);
  1079. std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
  1080. return E;
  1081. } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
  1082. auto *E = new (ExpressionAllocator)
  1083. AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
  1084. setBasicExpressionInfo(EI, E);
  1085. E->allocateIntOperands(ExpressionAllocator);
  1086. std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
  1087. return E;
  1088. }
  1089. llvm_unreachable("Unhandled type of aggregate value operation");
  1090. }
  1091. const DeadExpression *NewGVN::createDeadExpression() const {
  1092. // DeadExpression has no arguments and all DeadExpression's are the same,
  1093. // so we only need one of them.
  1094. return SingletonDeadExpression;
  1095. }
  1096. const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
  1097. auto *E = new (ExpressionAllocator) VariableExpression(V);
  1098. E->setOpcode(V->getValueID());
  1099. return E;
  1100. }
  1101. const Expression *NewGVN::createVariableOrConstant(Value *V) const {
  1102. if (auto *C = dyn_cast<Constant>(V))
  1103. return createConstantExpression(C);
  1104. return createVariableExpression(V);
  1105. }
  1106. const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
  1107. auto *E = new (ExpressionAllocator) ConstantExpression(C);
  1108. E->setOpcode(C->getValueID());
  1109. return E;
  1110. }
  1111. const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
  1112. auto *E = new (ExpressionAllocator) UnknownExpression(I);
  1113. E->setOpcode(I->getOpcode());
  1114. return E;
  1115. }
  1116. const CallExpression *
  1117. NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
  1118. // FIXME: Add operand bundles for calls.
  1119. // FIXME: Allow commutative matching for intrinsics.
  1120. auto *E =
  1121. new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
  1122. setBasicExpressionInfo(CI, E);
  1123. return E;
  1124. }
  1125. // Return true if some equivalent of instruction Inst dominates instruction U.
  1126. bool NewGVN::someEquivalentDominates(const Instruction *Inst,
  1127. const Instruction *U) const {
  1128. auto *CC = ValueToClass.lookup(Inst);
  1129. // This must be an instruction because we are only called from phi nodes
  1130. // in the case that the value it needs to check against is an instruction.
  1131. // The most likely candidates for dominance are the leader and the next leader.
  1132. // The leader or nextleader will dominate in all cases where there is an
  1133. // equivalent that is higher up in the dom tree.
  1134. // We can't *only* check them, however, because the
  1135. // dominator tree could have an infinite number of non-dominating siblings
  1136. // with instructions that are in the right congruence class.
  1137. // A
  1138. // B C D E F G
  1139. // |
  1140. // H
  1141. // Instruction U could be in H, with equivalents in every other sibling.
  1142. // Depending on the rpo order picked, the leader could be the equivalent in
  1143. // any of these siblings.
  1144. if (!CC)
  1145. return false;
  1146. if (alwaysAvailable(CC->getLeader()))
  1147. return true;
  1148. if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
  1149. return true;
  1150. if (CC->getNextLeader().first &&
  1151. DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
  1152. return true;
  1153. return llvm::any_of(*CC, [&](const Value *Member) {
  1154. return Member != CC->getLeader() &&
  1155. DT->dominates(cast<Instruction>(Member), U);
  1156. });
  1157. }
  1158. // See if we have a congruence class and leader for this operand, and if so,
  1159. // return it. Otherwise, return the operand itself.
  1160. Value *NewGVN::lookupOperandLeader(Value *V) const {
  1161. CongruenceClass *CC = ValueToClass.lookup(V);
  1162. if (CC) {
  1163. // Everything in TOP is represented by poison, as it can be any value.
  1164. // We do have to make sure we get the type right though, so we can't set the
  1165. // RepLeader to poison.
  1166. if (CC == TOPClass)
  1167. return PoisonValue::get(V->getType());
  1168. return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
  1169. }
  1170. return V;
  1171. }
  1172. const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
  1173. auto *CC = getMemoryClass(MA);
  1174. assert(CC->getMemoryLeader() &&
  1175. "Every MemoryAccess should be mapped to a congruence class with a "
  1176. "representative memory access");
  1177. return CC->getMemoryLeader();
  1178. }
  1179. // Return true if the MemoryAccess is really equivalent to everything. This is
  1180. // equivalent to the lattice value "TOP" in most lattices. This is the initial
  1181. // state of all MemoryAccesses.
  1182. bool NewGVN::isMemoryAccessTOP(const MemoryAccess *MA) const {
  1183. return getMemoryClass(MA) == TOPClass;
  1184. }
  1185. LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
  1186. LoadInst *LI,
  1187. const MemoryAccess *MA) const {
  1188. auto *E =
  1189. new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
  1190. E->allocateOperands(ArgRecycler, ExpressionAllocator);
  1191. E->setType(LoadType);
  1192. // Give store and loads same opcode so they value number together.
  1193. E->setOpcode(0);
  1194. E->op_push_back(PointerOp);
  1195. // TODO: Value number heap versions. We may be able to discover
  1196. // things alias analysis can't on it's own (IE that a store and a
  1197. // load have the same value, and thus, it isn't clobbering the load).
  1198. return E;
  1199. }
  1200. const StoreExpression *
  1201. NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
  1202. auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
  1203. auto *E = new (ExpressionAllocator)
  1204. StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
  1205. E->allocateOperands(ArgRecycler, ExpressionAllocator);
  1206. E->setType(SI->getValueOperand()->getType());
  1207. // Give store and loads same opcode so they value number together.
  1208. E->setOpcode(0);
  1209. E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
  1210. // TODO: Value number heap versions. We may be able to discover
  1211. // things alias analysis can't on it's own (IE that a store and a
  1212. // load have the same value, and thus, it isn't clobbering the load).
  1213. return E;
  1214. }
  1215. const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
  1216. // Unlike loads, we never try to eliminate stores, so we do not check if they
  1217. // are simple and avoid value numbering them.
  1218. auto *SI = cast<StoreInst>(I);
  1219. auto *StoreAccess = getMemoryAccess(SI);
  1220. // Get the expression, if any, for the RHS of the MemoryDef.
  1221. const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
  1222. if (EnableStoreRefinement)
  1223. StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
  1224. // If we bypassed the use-def chains, make sure we add a use.
  1225. StoreRHS = lookupMemoryLeader(StoreRHS);
  1226. if (StoreRHS != StoreAccess->getDefiningAccess())
  1227. addMemoryUsers(StoreRHS, StoreAccess);
  1228. // If we are defined by ourselves, use the live on entry def.
  1229. if (StoreRHS == StoreAccess)
  1230. StoreRHS = MSSA->getLiveOnEntryDef();
  1231. if (SI->isSimple()) {
  1232. // See if we are defined by a previous store expression, it already has a
  1233. // value, and it's the same value as our current store. FIXME: Right now, we
  1234. // only do this for simple stores, we should expand to cover memcpys, etc.
  1235. const auto *LastStore = createStoreExpression(SI, StoreRHS);
  1236. const auto *LastCC = ExpressionToClass.lookup(LastStore);
  1237. // We really want to check whether the expression we matched was a store. No
  1238. // easy way to do that. However, we can check that the class we found has a
  1239. // store, which, assuming the value numbering state is not corrupt, is
  1240. // sufficient, because we must also be equivalent to that store's expression
  1241. // for it to be in the same class as the load.
  1242. if (LastCC && LastCC->getStoredValue() == LastStore->getStoredValue())
  1243. return LastStore;
  1244. // Also check if our value operand is defined by a load of the same memory
  1245. // location, and the memory state is the same as it was then (otherwise, it
  1246. // could have been overwritten later. See test32 in
  1247. // transforms/DeadStoreElimination/simple.ll).
  1248. if (auto *LI = dyn_cast<LoadInst>(LastStore->getStoredValue()))
  1249. if ((lookupOperandLeader(LI->getPointerOperand()) ==
  1250. LastStore->getOperand(0)) &&
  1251. (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
  1252. StoreRHS))
  1253. return LastStore;
  1254. deleteExpression(LastStore);
  1255. }
  1256. // If the store is not equivalent to anything, value number it as a store that
  1257. // produces a unique memory state (instead of using it's MemoryUse, we use
  1258. // it's MemoryDef).
  1259. return createStoreExpression(SI, StoreAccess);
  1260. }
  1261. // See if we can extract the value of a loaded pointer from a load, a store, or
  1262. // a memory instruction.
  1263. const Expression *
  1264. NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
  1265. LoadInst *LI, Instruction *DepInst,
  1266. MemoryAccess *DefiningAccess) const {
  1267. assert((!LI || LI->isSimple()) && "Not a simple load");
  1268. if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
  1269. // Can't forward from non-atomic to atomic without violating memory model.
  1270. // Also don't need to coerce if they are the same type, we will just
  1271. // propagate.
  1272. if (LI->isAtomic() > DepSI->isAtomic() ||
  1273. LoadType == DepSI->getValueOperand()->getType())
  1274. return nullptr;
  1275. int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
  1276. if (Offset >= 0) {
  1277. if (auto *C = dyn_cast<Constant>(
  1278. lookupOperandLeader(DepSI->getValueOperand()))) {
  1279. if (Constant *Res =
  1280. getConstantStoreValueForLoad(C, Offset, LoadType, DL)) {
  1281. LLVM_DEBUG(dbgs() << "Coercing load from store " << *DepSI
  1282. << " to constant " << *Res << "\n");
  1283. return createConstantExpression(Res);
  1284. }
  1285. }
  1286. }
  1287. } else if (auto *DepLI = dyn_cast<LoadInst>(DepInst)) {
  1288. // Can't forward from non-atomic to atomic without violating memory model.
  1289. if (LI->isAtomic() > DepLI->isAtomic())
  1290. return nullptr;
  1291. int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
  1292. if (Offset >= 0) {
  1293. // We can coerce a constant load into a load.
  1294. if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
  1295. if (auto *PossibleConstant =
  1296. getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
  1297. LLVM_DEBUG(dbgs() << "Coercing load from load " << *LI
  1298. << " to constant " << *PossibleConstant << "\n");
  1299. return createConstantExpression(PossibleConstant);
  1300. }
  1301. }
  1302. } else if (auto *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
  1303. int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
  1304. if (Offset >= 0) {
  1305. if (auto *PossibleConstant =
  1306. getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
  1307. LLVM_DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
  1308. << " to constant " << *PossibleConstant << "\n");
  1309. return createConstantExpression(PossibleConstant);
  1310. }
  1311. }
  1312. }
  1313. // All of the below are only true if the loaded pointer is produced
  1314. // by the dependent instruction.
  1315. if (LoadPtr != lookupOperandLeader(DepInst) &&
  1316. !AA->isMustAlias(LoadPtr, DepInst))
  1317. return nullptr;
  1318. // If this load really doesn't depend on anything, then we must be loading an
  1319. // undef value. This can happen when loading for a fresh allocation with no
  1320. // intervening stores, for example. Note that this is only true in the case
  1321. // that the result of the allocation is pointer equal to the load ptr.
  1322. if (isa<AllocaInst>(DepInst)) {
  1323. return createConstantExpression(UndefValue::get(LoadType));
  1324. }
  1325. // If this load occurs either right after a lifetime begin,
  1326. // then the loaded value is undefined.
  1327. else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
  1328. if (II->getIntrinsicID() == Intrinsic::lifetime_start)
  1329. return createConstantExpression(UndefValue::get(LoadType));
  1330. } else if (auto *InitVal =
  1331. getInitialValueOfAllocation(DepInst, TLI, LoadType))
  1332. return createConstantExpression(InitVal);
  1333. return nullptr;
  1334. }
  1335. const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
  1336. auto *LI = cast<LoadInst>(I);
  1337. // We can eliminate in favor of non-simple loads, but we won't be able to
  1338. // eliminate the loads themselves.
  1339. if (!LI->isSimple())
  1340. return nullptr;
  1341. Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
  1342. // Load of undef is UB.
  1343. if (isa<UndefValue>(LoadAddressLeader))
  1344. return createConstantExpression(PoisonValue::get(LI->getType()));
  1345. MemoryAccess *OriginalAccess = getMemoryAccess(I);
  1346. MemoryAccess *DefiningAccess =
  1347. MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
  1348. if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
  1349. if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
  1350. Instruction *DefiningInst = MD->getMemoryInst();
  1351. // If the defining instruction is not reachable, replace with poison.
  1352. if (!ReachableBlocks.count(DefiningInst->getParent()))
  1353. return createConstantExpression(PoisonValue::get(LI->getType()));
  1354. // This will handle stores and memory insts. We only do if it the
  1355. // defining access has a different type, or it is a pointer produced by
  1356. // certain memory operations that cause the memory to have a fixed value
  1357. // (IE things like calloc).
  1358. if (const auto *CoercionResult =
  1359. performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
  1360. DefiningInst, DefiningAccess))
  1361. return CoercionResult;
  1362. }
  1363. }
  1364. const auto *LE = createLoadExpression(LI->getType(), LoadAddressLeader, LI,
  1365. DefiningAccess);
  1366. // If our MemoryLeader is not our defining access, add a use to the
  1367. // MemoryLeader, so that we get reprocessed when it changes.
  1368. if (LE->getMemoryLeader() != DefiningAccess)
  1369. addMemoryUsers(LE->getMemoryLeader(), OriginalAccess);
  1370. return LE;
  1371. }
  1372. NewGVN::ExprResult
  1373. NewGVN::performSymbolicPredicateInfoEvaluation(IntrinsicInst *I) const {
  1374. auto *PI = PredInfo->getPredicateInfoFor(I);
  1375. if (!PI)
  1376. return ExprResult::none();
  1377. LLVM_DEBUG(dbgs() << "Found predicate info from instruction !\n");
  1378. const std::optional<PredicateConstraint> &Constraint = PI->getConstraint();
  1379. if (!Constraint)
  1380. return ExprResult::none();
  1381. CmpInst::Predicate Predicate = Constraint->Predicate;
  1382. Value *CmpOp0 = I->getOperand(0);
  1383. Value *CmpOp1 = Constraint->OtherOp;
  1384. Value *FirstOp = lookupOperandLeader(CmpOp0);
  1385. Value *SecondOp = lookupOperandLeader(CmpOp1);
  1386. Value *AdditionallyUsedValue = CmpOp0;
  1387. // Sort the ops.
  1388. if (shouldSwapOperandsForIntrinsic(FirstOp, SecondOp, I)) {
  1389. std::swap(FirstOp, SecondOp);
  1390. Predicate = CmpInst::getSwappedPredicate(Predicate);
  1391. AdditionallyUsedValue = CmpOp1;
  1392. }
  1393. if (Predicate == CmpInst::ICMP_EQ)
  1394. return ExprResult::some(createVariableOrConstant(FirstOp),
  1395. AdditionallyUsedValue, PI);
  1396. // Handle the special case of floating point.
  1397. if (Predicate == CmpInst::FCMP_OEQ && isa<ConstantFP>(FirstOp) &&
  1398. !cast<ConstantFP>(FirstOp)->isZero())
  1399. return ExprResult::some(createConstantExpression(cast<Constant>(FirstOp)),
  1400. AdditionallyUsedValue, PI);
  1401. return ExprResult::none();
  1402. }
  1403. // Evaluate read only and pure calls, and create an expression result.
  1404. NewGVN::ExprResult NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
  1405. auto *CI = cast<CallInst>(I);
  1406. if (auto *II = dyn_cast<IntrinsicInst>(I)) {
  1407. // Intrinsics with the returned attribute are copies of arguments.
  1408. if (auto *ReturnedValue = II->getReturnedArgOperand()) {
  1409. if (II->getIntrinsicID() == Intrinsic::ssa_copy)
  1410. if (auto Res = performSymbolicPredicateInfoEvaluation(II))
  1411. return Res;
  1412. return ExprResult::some(createVariableOrConstant(ReturnedValue));
  1413. }
  1414. }
  1415. // FIXME: Currently the calls which may access the thread id may
  1416. // be considered as not accessing the memory. But this is
  1417. // problematic for coroutines, since coroutines may resume in a
  1418. // different thread. So we disable the optimization here for the
  1419. // correctness. However, it may block many other correct
  1420. // optimizations. Revert this one when we detect the memory
  1421. // accessing kind more precisely.
  1422. if (CI->getFunction()->isPresplitCoroutine())
  1423. return ExprResult::none();
  1424. if (AA->doesNotAccessMemory(CI)) {
  1425. return ExprResult::some(
  1426. createCallExpression(CI, TOPClass->getMemoryLeader()));
  1427. } else if (AA->onlyReadsMemory(CI)) {
  1428. if (auto *MA = MSSA->getMemoryAccess(CI)) {
  1429. auto *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(MA);
  1430. return ExprResult::some(createCallExpression(CI, DefiningAccess));
  1431. } else // MSSA determined that CI does not access memory.
  1432. return ExprResult::some(
  1433. createCallExpression(CI, TOPClass->getMemoryLeader()));
  1434. }
  1435. return ExprResult::none();
  1436. }
  1437. // Retrieve the memory class for a given MemoryAccess.
  1438. CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
  1439. auto *Result = MemoryAccessToClass.lookup(MA);
  1440. assert(Result && "Should have found memory class");
  1441. return Result;
  1442. }
  1443. // Update the MemoryAccess equivalence table to say that From is equal to To,
  1444. // and return true if this is different from what already existed in the table.
  1445. bool NewGVN::setMemoryClass(const MemoryAccess *From,
  1446. CongruenceClass *NewClass) {
  1447. assert(NewClass &&
  1448. "Every MemoryAccess should be getting mapped to a non-null class");
  1449. LLVM_DEBUG(dbgs() << "Setting " << *From);
  1450. LLVM_DEBUG(dbgs() << " equivalent to congruence class ");
  1451. LLVM_DEBUG(dbgs() << NewClass->getID()
  1452. << " with current MemoryAccess leader ");
  1453. LLVM_DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n");
  1454. auto LookupResult = MemoryAccessToClass.find(From);
  1455. bool Changed = false;
  1456. // If it's already in the table, see if the value changed.
  1457. if (LookupResult != MemoryAccessToClass.end()) {
  1458. auto *OldClass = LookupResult->second;
  1459. if (OldClass != NewClass) {
  1460. // If this is a phi, we have to handle memory member updates.
  1461. if (auto *MP = dyn_cast<MemoryPhi>(From)) {
  1462. OldClass->memory_erase(MP);
  1463. NewClass->memory_insert(MP);
  1464. // This may have killed the class if it had no non-memory members
  1465. if (OldClass->getMemoryLeader() == From) {
  1466. if (OldClass->definesNoMemory()) {
  1467. OldClass->setMemoryLeader(nullptr);
  1468. } else {
  1469. OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
  1470. LLVM_DEBUG(dbgs() << "Memory class leader change for class "
  1471. << OldClass->getID() << " to "
  1472. << *OldClass->getMemoryLeader()
  1473. << " due to removal of a memory member " << *From
  1474. << "\n");
  1475. markMemoryLeaderChangeTouched(OldClass);
  1476. }
  1477. }
  1478. }
  1479. // It wasn't equivalent before, and now it is.
  1480. LookupResult->second = NewClass;
  1481. Changed = true;
  1482. }
  1483. }
  1484. return Changed;
  1485. }
  1486. // Determine if a instruction is cycle-free. That means the values in the
  1487. // instruction don't depend on any expressions that can change value as a result
  1488. // of the instruction. For example, a non-cycle free instruction would be v =
  1489. // phi(0, v+1).
  1490. bool NewGVN::isCycleFree(const Instruction *I) const {
  1491. // In order to compute cycle-freeness, we do SCC finding on the instruction,
  1492. // and see what kind of SCC it ends up in. If it is a singleton, it is
  1493. // cycle-free. If it is not in a singleton, it is only cycle free if the
  1494. // other members are all phi nodes (as they do not compute anything, they are
  1495. // copies).
  1496. auto ICS = InstCycleState.lookup(I);
  1497. if (ICS == ICS_Unknown) {
  1498. SCCFinder.Start(I);
  1499. auto &SCC = SCCFinder.getComponentFor(I);
  1500. // It's cycle free if it's size 1 or the SCC is *only* phi nodes.
  1501. if (SCC.size() == 1)
  1502. InstCycleState.insert({I, ICS_CycleFree});
  1503. else {
  1504. bool AllPhis = llvm::all_of(SCC, [](const Value *V) {
  1505. return isa<PHINode>(V) || isCopyOfAPHI(V);
  1506. });
  1507. ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
  1508. for (const auto *Member : SCC)
  1509. if (auto *MemberPhi = dyn_cast<PHINode>(Member))
  1510. InstCycleState.insert({MemberPhi, ICS});
  1511. }
  1512. }
  1513. if (ICS == ICS_Cycle)
  1514. return false;
  1515. return true;
  1516. }
  1517. // Evaluate PHI nodes symbolically and create an expression result.
  1518. const Expression *
  1519. NewGVN::performSymbolicPHIEvaluation(ArrayRef<ValPair> PHIOps,
  1520. Instruction *I,
  1521. BasicBlock *PHIBlock) const {
  1522. // True if one of the incoming phi edges is a backedge.
  1523. bool HasBackedge = false;
  1524. // All constant tracks the state of whether all the *original* phi operands
  1525. // This is really shorthand for "this phi cannot cycle due to forward
  1526. // change in value of the phi is guaranteed not to later change the value of
  1527. // the phi. IE it can't be v = phi(undef, v+1)
  1528. bool OriginalOpsConstant = true;
  1529. auto *E = cast<PHIExpression>(createPHIExpression(
  1530. PHIOps, I, PHIBlock, HasBackedge, OriginalOpsConstant));
  1531. // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
  1532. // See if all arguments are the same.
  1533. // We track if any were undef because they need special handling.
  1534. bool HasUndef = false, HasPoison = false;
  1535. auto Filtered = make_filter_range(E->operands(), [&](Value *Arg) {
  1536. if (isa<PoisonValue>(Arg)) {
  1537. HasPoison = true;
  1538. return false;
  1539. }
  1540. if (isa<UndefValue>(Arg)) {
  1541. HasUndef = true;
  1542. return false;
  1543. }
  1544. return true;
  1545. });
  1546. // If we are left with no operands, it's dead.
  1547. if (Filtered.empty()) {
  1548. // If it has undef or poison at this point, it means there are no-non-undef
  1549. // arguments, and thus, the value of the phi node must be undef.
  1550. if (HasUndef) {
  1551. LLVM_DEBUG(
  1552. dbgs() << "PHI Node " << *I
  1553. << " has no non-undef arguments, valuing it as undef\n");
  1554. return createConstantExpression(UndefValue::get(I->getType()));
  1555. }
  1556. if (HasPoison) {
  1557. LLVM_DEBUG(
  1558. dbgs() << "PHI Node " << *I
  1559. << " has no non-poison arguments, valuing it as poison\n");
  1560. return createConstantExpression(PoisonValue::get(I->getType()));
  1561. }
  1562. LLVM_DEBUG(dbgs() << "No arguments of PHI node " << *I << " are live\n");
  1563. deleteExpression(E);
  1564. return createDeadExpression();
  1565. }
  1566. Value *AllSameValue = *(Filtered.begin());
  1567. ++Filtered.begin();
  1568. // Can't use std::equal here, sadly, because filter.begin moves.
  1569. if (llvm::all_of(Filtered, [&](Value *Arg) { return Arg == AllSameValue; })) {
  1570. // Can't fold phi(undef, X) -> X unless X can't be poison (thus X is undef
  1571. // in the worst case).
  1572. if (HasUndef && !isGuaranteedNotToBePoison(AllSameValue, AC, nullptr, DT))
  1573. return E;
  1574. // In LLVM's non-standard representation of phi nodes, it's possible to have
  1575. // phi nodes with cycles (IE dependent on other phis that are .... dependent
  1576. // on the original phi node), especially in weird CFG's where some arguments
  1577. // are unreachable, or uninitialized along certain paths. This can cause
  1578. // infinite loops during evaluation. We work around this by not trying to
  1579. // really evaluate them independently, but instead using a variable
  1580. // expression to say if one is equivalent to the other.
  1581. // We also special case undef/poison, so that if we have an undef, we can't
  1582. // use the common value unless it dominates the phi block.
  1583. if (HasPoison || HasUndef) {
  1584. // If we have undef and at least one other value, this is really a
  1585. // multivalued phi, and we need to know if it's cycle free in order to
  1586. // evaluate whether we can ignore the undef. The other parts of this are
  1587. // just shortcuts. If there is no backedge, or all operands are
  1588. // constants, it also must be cycle free.
  1589. if (HasBackedge && !OriginalOpsConstant &&
  1590. !isa<UndefValue>(AllSameValue) && !isCycleFree(I))
  1591. return E;
  1592. // Only have to check for instructions
  1593. if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
  1594. if (!someEquivalentDominates(AllSameInst, I))
  1595. return E;
  1596. }
  1597. // Can't simplify to something that comes later in the iteration.
  1598. // Otherwise, when and if it changes congruence class, we will never catch
  1599. // up. We will always be a class behind it.
  1600. if (isa<Instruction>(AllSameValue) &&
  1601. InstrToDFSNum(AllSameValue) > InstrToDFSNum(I))
  1602. return E;
  1603. NumGVNPhisAllSame++;
  1604. LLVM_DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
  1605. << "\n");
  1606. deleteExpression(E);
  1607. return createVariableOrConstant(AllSameValue);
  1608. }
  1609. return E;
  1610. }
  1611. const Expression *
  1612. NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
  1613. if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
  1614. auto *WO = dyn_cast<WithOverflowInst>(EI->getAggregateOperand());
  1615. if (WO && EI->getNumIndices() == 1 && *EI->idx_begin() == 0)
  1616. // EI is an extract from one of our with.overflow intrinsics. Synthesize
  1617. // a semantically equivalent expression instead of an extract value
  1618. // expression.
  1619. return createBinaryExpression(WO->getBinaryOp(), EI->getType(),
  1620. WO->getLHS(), WO->getRHS(), I);
  1621. }
  1622. return createAggregateValueExpression(I);
  1623. }
  1624. NewGVN::ExprResult NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
  1625. assert(isa<CmpInst>(I) && "Expected a cmp instruction.");
  1626. auto *CI = cast<CmpInst>(I);
  1627. // See if our operands are equal to those of a previous predicate, and if so,
  1628. // if it implies true or false.
  1629. auto Op0 = lookupOperandLeader(CI->getOperand(0));
  1630. auto Op1 = lookupOperandLeader(CI->getOperand(1));
  1631. auto OurPredicate = CI->getPredicate();
  1632. if (shouldSwapOperands(Op0, Op1)) {
  1633. std::swap(Op0, Op1);
  1634. OurPredicate = CI->getSwappedPredicate();
  1635. }
  1636. // Avoid processing the same info twice.
  1637. const PredicateBase *LastPredInfo = nullptr;
  1638. // See if we know something about the comparison itself, like it is the target
  1639. // of an assume.
  1640. auto *CmpPI = PredInfo->getPredicateInfoFor(I);
  1641. if (isa_and_nonnull<PredicateAssume>(CmpPI))
  1642. return ExprResult::some(
  1643. createConstantExpression(ConstantInt::getTrue(CI->getType())));
  1644. if (Op0 == Op1) {
  1645. // This condition does not depend on predicates, no need to add users
  1646. if (CI->isTrueWhenEqual())
  1647. return ExprResult::some(
  1648. createConstantExpression(ConstantInt::getTrue(CI->getType())));
  1649. else if (CI->isFalseWhenEqual())
  1650. return ExprResult::some(
  1651. createConstantExpression(ConstantInt::getFalse(CI->getType())));
  1652. }
  1653. // NOTE: Because we are comparing both operands here and below, and using
  1654. // previous comparisons, we rely on fact that predicateinfo knows to mark
  1655. // comparisons that use renamed operands as users of the earlier comparisons.
  1656. // It is *not* enough to just mark predicateinfo renamed operands as users of
  1657. // the earlier comparisons, because the *other* operand may have changed in a
  1658. // previous iteration.
  1659. // Example:
  1660. // icmp slt %a, %b
  1661. // %b.0 = ssa.copy(%b)
  1662. // false branch:
  1663. // icmp slt %c, %b.0
  1664. // %c and %a may start out equal, and thus, the code below will say the second
  1665. // %icmp is false. c may become equal to something else, and in that case the
  1666. // %second icmp *must* be reexamined, but would not if only the renamed
  1667. // %operands are considered users of the icmp.
  1668. // *Currently* we only check one level of comparisons back, and only mark one
  1669. // level back as touched when changes happen. If you modify this code to look
  1670. // back farther through comparisons, you *must* mark the appropriate
  1671. // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
  1672. // we know something just from the operands themselves
  1673. // See if our operands have predicate info, so that we may be able to derive
  1674. // something from a previous comparison.
  1675. for (const auto &Op : CI->operands()) {
  1676. auto *PI = PredInfo->getPredicateInfoFor(Op);
  1677. if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
  1678. if (PI == LastPredInfo)
  1679. continue;
  1680. LastPredInfo = PI;
  1681. // In phi of ops cases, we may have predicate info that we are evaluating
  1682. // in a different context.
  1683. if (!DT->dominates(PBranch->To, getBlockForValue(I)))
  1684. continue;
  1685. // TODO: Along the false edge, we may know more things too, like
  1686. // icmp of
  1687. // same operands is false.
  1688. // TODO: We only handle actual comparison conditions below, not
  1689. // and/or.
  1690. auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
  1691. if (!BranchCond)
  1692. continue;
  1693. auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
  1694. auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
  1695. auto BranchPredicate = BranchCond->getPredicate();
  1696. if (shouldSwapOperands(BranchOp0, BranchOp1)) {
  1697. std::swap(BranchOp0, BranchOp1);
  1698. BranchPredicate = BranchCond->getSwappedPredicate();
  1699. }
  1700. if (BranchOp0 == Op0 && BranchOp1 == Op1) {
  1701. if (PBranch->TrueEdge) {
  1702. // If we know the previous predicate is true and we are in the true
  1703. // edge then we may be implied true or false.
  1704. if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
  1705. OurPredicate)) {
  1706. return ExprResult::some(
  1707. createConstantExpression(ConstantInt::getTrue(CI->getType())),
  1708. PI);
  1709. }
  1710. if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
  1711. OurPredicate)) {
  1712. return ExprResult::some(
  1713. createConstantExpression(ConstantInt::getFalse(CI->getType())),
  1714. PI);
  1715. }
  1716. } else {
  1717. // Just handle the ne and eq cases, where if we have the same
  1718. // operands, we may know something.
  1719. if (BranchPredicate == OurPredicate) {
  1720. // Same predicate, same ops,we know it was false, so this is false.
  1721. return ExprResult::some(
  1722. createConstantExpression(ConstantInt::getFalse(CI->getType())),
  1723. PI);
  1724. } else if (BranchPredicate ==
  1725. CmpInst::getInversePredicate(OurPredicate)) {
  1726. // Inverse predicate, we know the other was false, so this is true.
  1727. return ExprResult::some(
  1728. createConstantExpression(ConstantInt::getTrue(CI->getType())),
  1729. PI);
  1730. }
  1731. }
  1732. }
  1733. }
  1734. }
  1735. // Create expression will take care of simplifyCmpInst
  1736. return createExpression(I);
  1737. }
  1738. // Substitute and symbolize the value before value numbering.
  1739. NewGVN::ExprResult
  1740. NewGVN::performSymbolicEvaluation(Value *V,
  1741. SmallPtrSetImpl<Value *> &Visited) const {
  1742. const Expression *E = nullptr;
  1743. if (auto *C = dyn_cast<Constant>(V))
  1744. E = createConstantExpression(C);
  1745. else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
  1746. E = createVariableExpression(V);
  1747. } else {
  1748. // TODO: memory intrinsics.
  1749. // TODO: Some day, we should do the forward propagation and reassociation
  1750. // parts of the algorithm.
  1751. auto *I = cast<Instruction>(V);
  1752. switch (I->getOpcode()) {
  1753. case Instruction::ExtractValue:
  1754. case Instruction::InsertValue:
  1755. E = performSymbolicAggrValueEvaluation(I);
  1756. break;
  1757. case Instruction::PHI: {
  1758. SmallVector<ValPair, 3> Ops;
  1759. auto *PN = cast<PHINode>(I);
  1760. for (unsigned i = 0; i < PN->getNumOperands(); ++i)
  1761. Ops.push_back({PN->getIncomingValue(i), PN->getIncomingBlock(i)});
  1762. // Sort to ensure the invariant createPHIExpression requires is met.
  1763. sortPHIOps(Ops);
  1764. E = performSymbolicPHIEvaluation(Ops, I, getBlockForValue(I));
  1765. } break;
  1766. case Instruction::Call:
  1767. return performSymbolicCallEvaluation(I);
  1768. break;
  1769. case Instruction::Store:
  1770. E = performSymbolicStoreEvaluation(I);
  1771. break;
  1772. case Instruction::Load:
  1773. E = performSymbolicLoadEvaluation(I);
  1774. break;
  1775. case Instruction::BitCast:
  1776. case Instruction::AddrSpaceCast:
  1777. return createExpression(I);
  1778. break;
  1779. case Instruction::ICmp:
  1780. case Instruction::FCmp:
  1781. return performSymbolicCmpEvaluation(I);
  1782. break;
  1783. case Instruction::FNeg:
  1784. case Instruction::Add:
  1785. case Instruction::FAdd:
  1786. case Instruction::Sub:
  1787. case Instruction::FSub:
  1788. case Instruction::Mul:
  1789. case Instruction::FMul:
  1790. case Instruction::UDiv:
  1791. case Instruction::SDiv:
  1792. case Instruction::FDiv:
  1793. case Instruction::URem:
  1794. case Instruction::SRem:
  1795. case Instruction::FRem:
  1796. case Instruction::Shl:
  1797. case Instruction::LShr:
  1798. case Instruction::AShr:
  1799. case Instruction::And:
  1800. case Instruction::Or:
  1801. case Instruction::Xor:
  1802. case Instruction::Trunc:
  1803. case Instruction::ZExt:
  1804. case Instruction::SExt:
  1805. case Instruction::FPToUI:
  1806. case Instruction::FPToSI:
  1807. case Instruction::UIToFP:
  1808. case Instruction::SIToFP:
  1809. case Instruction::FPTrunc:
  1810. case Instruction::FPExt:
  1811. case Instruction::PtrToInt:
  1812. case Instruction::IntToPtr:
  1813. case Instruction::Select:
  1814. case Instruction::ExtractElement:
  1815. case Instruction::InsertElement:
  1816. case Instruction::GetElementPtr:
  1817. return createExpression(I);
  1818. break;
  1819. case Instruction::ShuffleVector:
  1820. // FIXME: Add support for shufflevector to createExpression.
  1821. return ExprResult::none();
  1822. default:
  1823. return ExprResult::none();
  1824. }
  1825. }
  1826. return ExprResult::some(E);
  1827. }
  1828. // Look up a container of values/instructions in a map, and touch all the
  1829. // instructions in the container. Then erase value from the map.
  1830. template <typename Map, typename KeyType>
  1831. void NewGVN::touchAndErase(Map &M, const KeyType &Key) {
  1832. const auto Result = M.find_as(Key);
  1833. if (Result != M.end()) {
  1834. for (const typename Map::mapped_type::value_type Mapped : Result->second)
  1835. TouchedInstructions.set(InstrToDFSNum(Mapped));
  1836. M.erase(Result);
  1837. }
  1838. }
  1839. void NewGVN::addAdditionalUsers(Value *To, Value *User) const {
  1840. assert(User && To != User);
  1841. if (isa<Instruction>(To))
  1842. AdditionalUsers[To].insert(User);
  1843. }
  1844. void NewGVN::addAdditionalUsers(ExprResult &Res, Instruction *User) const {
  1845. if (Res.ExtraDep && Res.ExtraDep != User)
  1846. addAdditionalUsers(Res.ExtraDep, User);
  1847. Res.ExtraDep = nullptr;
  1848. if (Res.PredDep) {
  1849. if (const auto *PBranch = dyn_cast<PredicateBranch>(Res.PredDep))
  1850. PredicateToUsers[PBranch->Condition].insert(User);
  1851. else if (const auto *PAssume = dyn_cast<PredicateAssume>(Res.PredDep))
  1852. PredicateToUsers[PAssume->Condition].insert(User);
  1853. }
  1854. Res.PredDep = nullptr;
  1855. }
  1856. void NewGVN::markUsersTouched(Value *V) {
  1857. // Now mark the users as touched.
  1858. for (auto *User : V->users()) {
  1859. assert(isa<Instruction>(User) && "Use of value not within an instruction?");
  1860. TouchedInstructions.set(InstrToDFSNum(User));
  1861. }
  1862. touchAndErase(AdditionalUsers, V);
  1863. }
  1864. void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
  1865. LLVM_DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
  1866. MemoryToUsers[To].insert(U);
  1867. }
  1868. void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
  1869. TouchedInstructions.set(MemoryToDFSNum(MA));
  1870. }
  1871. void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
  1872. if (isa<MemoryUse>(MA))
  1873. return;
  1874. for (const auto *U : MA->users())
  1875. TouchedInstructions.set(MemoryToDFSNum(U));
  1876. touchAndErase(MemoryToUsers, MA);
  1877. }
  1878. // Touch all the predicates that depend on this instruction.
  1879. void NewGVN::markPredicateUsersTouched(Instruction *I) {
  1880. touchAndErase(PredicateToUsers, I);
  1881. }
  1882. // Mark users affected by a memory leader change.
  1883. void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
  1884. for (const auto *M : CC->memory())
  1885. markMemoryDefTouched(M);
  1886. }
  1887. // Touch the instructions that need to be updated after a congruence class has a
  1888. // leader change, and mark changed values.
  1889. void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
  1890. for (auto *M : *CC) {
  1891. if (auto *I = dyn_cast<Instruction>(M))
  1892. TouchedInstructions.set(InstrToDFSNum(I));
  1893. LeaderChanges.insert(M);
  1894. }
  1895. }
  1896. // Give a range of things that have instruction DFS numbers, this will return
  1897. // the member of the range with the smallest dfs number.
  1898. template <class T, class Range>
  1899. T *NewGVN::getMinDFSOfRange(const Range &R) const {
  1900. std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
  1901. for (const auto X : R) {
  1902. auto DFSNum = InstrToDFSNum(X);
  1903. if (DFSNum < MinDFS.second)
  1904. MinDFS = {X, DFSNum};
  1905. }
  1906. return MinDFS.first;
  1907. }
  1908. // This function returns the MemoryAccess that should be the next leader of
  1909. // congruence class CC, under the assumption that the current leader is going to
  1910. // disappear.
  1911. const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
  1912. // TODO: If this ends up to slow, we can maintain a next memory leader like we
  1913. // do for regular leaders.
  1914. // Make sure there will be a leader to find.
  1915. assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
  1916. if (CC->getStoreCount() > 0) {
  1917. if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
  1918. return getMemoryAccess(NL);
  1919. // Find the store with the minimum DFS number.
  1920. auto *V = getMinDFSOfRange<Value>(make_filter_range(
  1921. *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
  1922. return getMemoryAccess(cast<StoreInst>(V));
  1923. }
  1924. assert(CC->getStoreCount() == 0);
  1925. // Given our assertion, hitting this part must mean
  1926. // !OldClass->memory_empty()
  1927. if (CC->memory_size() == 1)
  1928. return *CC->memory_begin();
  1929. return getMinDFSOfRange<const MemoryPhi>(CC->memory());
  1930. }
  1931. // This function returns the next value leader of a congruence class, under the
  1932. // assumption that the current leader is going away. This should end up being
  1933. // the next most dominating member.
  1934. Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
  1935. // We don't need to sort members if there is only 1, and we don't care about
  1936. // sorting the TOP class because everything either gets out of it or is
  1937. // unreachable.
  1938. if (CC->size() == 1 || CC == TOPClass) {
  1939. return *(CC->begin());
  1940. } else if (CC->getNextLeader().first) {
  1941. ++NumGVNAvoidedSortedLeaderChanges;
  1942. return CC->getNextLeader().first;
  1943. } else {
  1944. ++NumGVNSortedLeaderChanges;
  1945. // NOTE: If this ends up to slow, we can maintain a dual structure for
  1946. // member testing/insertion, or keep things mostly sorted, and sort only
  1947. // here, or use SparseBitVector or ....
  1948. return getMinDFSOfRange<Value>(*CC);
  1949. }
  1950. }
  1951. // Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
  1952. // the memory members, etc for the move.
  1953. //
  1954. // The invariants of this function are:
  1955. //
  1956. // - I must be moving to NewClass from OldClass
  1957. // - The StoreCount of OldClass and NewClass is expected to have been updated
  1958. // for I already if it is a store.
  1959. // - The OldClass memory leader has not been updated yet if I was the leader.
  1960. void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
  1961. MemoryAccess *InstMA,
  1962. CongruenceClass *OldClass,
  1963. CongruenceClass *NewClass) {
  1964. // If the leader is I, and we had a representative MemoryAccess, it should
  1965. // be the MemoryAccess of OldClass.
  1966. assert((!InstMA || !OldClass->getMemoryLeader() ||
  1967. OldClass->getLeader() != I ||
  1968. MemoryAccessToClass.lookup(OldClass->getMemoryLeader()) ==
  1969. MemoryAccessToClass.lookup(InstMA)) &&
  1970. "Representative MemoryAccess mismatch");
  1971. // First, see what happens to the new class
  1972. if (!NewClass->getMemoryLeader()) {
  1973. // Should be a new class, or a store becoming a leader of a new class.
  1974. assert(NewClass->size() == 1 ||
  1975. (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
  1976. NewClass->setMemoryLeader(InstMA);
  1977. // Mark it touched if we didn't just create a singleton
  1978. LLVM_DEBUG(dbgs() << "Memory class leader change for class "
  1979. << NewClass->getID()
  1980. << " due to new memory instruction becoming leader\n");
  1981. markMemoryLeaderChangeTouched(NewClass);
  1982. }
  1983. setMemoryClass(InstMA, NewClass);
  1984. // Now, fixup the old class if necessary
  1985. if (OldClass->getMemoryLeader() == InstMA) {
  1986. if (!OldClass->definesNoMemory()) {
  1987. OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
  1988. LLVM_DEBUG(dbgs() << "Memory class leader change for class "
  1989. << OldClass->getID() << " to "
  1990. << *OldClass->getMemoryLeader()
  1991. << " due to removal of old leader " << *InstMA << "\n");
  1992. markMemoryLeaderChangeTouched(OldClass);
  1993. } else
  1994. OldClass->setMemoryLeader(nullptr);
  1995. }
  1996. }
  1997. // Move a value, currently in OldClass, to be part of NewClass
  1998. // Update OldClass and NewClass for the move (including changing leaders, etc).
  1999. void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
  2000. CongruenceClass *OldClass,
  2001. CongruenceClass *NewClass) {
  2002. if (I == OldClass->getNextLeader().first)
  2003. OldClass->resetNextLeader();
  2004. OldClass->erase(I);
  2005. NewClass->insert(I);
  2006. if (NewClass->getLeader() != I)
  2007. NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
  2008. // Handle our special casing of stores.
  2009. if (auto *SI = dyn_cast<StoreInst>(I)) {
  2010. OldClass->decStoreCount();
  2011. // Okay, so when do we want to make a store a leader of a class?
  2012. // If we have a store defined by an earlier load, we want the earlier load
  2013. // to lead the class.
  2014. // If we have a store defined by something else, we want the store to lead
  2015. // the class so everything else gets the "something else" as a value.
  2016. // If we have a store as the single member of the class, we want the store
  2017. // as the leader
  2018. if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
  2019. // If it's a store expression we are using, it means we are not equivalent
  2020. // to something earlier.
  2021. if (auto *SE = dyn_cast<StoreExpression>(E)) {
  2022. NewClass->setStoredValue(SE->getStoredValue());
  2023. markValueLeaderChangeTouched(NewClass);
  2024. // Shift the new class leader to be the store
  2025. LLVM_DEBUG(dbgs() << "Changing leader of congruence class "
  2026. << NewClass->getID() << " from "
  2027. << *NewClass->getLeader() << " to " << *SI
  2028. << " because store joined class\n");
  2029. // If we changed the leader, we have to mark it changed because we don't
  2030. // know what it will do to symbolic evaluation.
  2031. NewClass->setLeader(SI);
  2032. }
  2033. // We rely on the code below handling the MemoryAccess change.
  2034. }
  2035. NewClass->incStoreCount();
  2036. }
  2037. // True if there is no memory instructions left in a class that had memory
  2038. // instructions before.
  2039. // If it's not a memory use, set the MemoryAccess equivalence
  2040. auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
  2041. if (InstMA)
  2042. moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
  2043. ValueToClass[I] = NewClass;
  2044. // See if we destroyed the class or need to swap leaders.
  2045. if (OldClass->empty() && OldClass != TOPClass) {
  2046. if (OldClass->getDefiningExpr()) {
  2047. LLVM_DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr()
  2048. << " from table\n");
  2049. // We erase it as an exact expression to make sure we don't just erase an
  2050. // equivalent one.
  2051. auto Iter = ExpressionToClass.find_as(
  2052. ExactEqualsExpression(*OldClass->getDefiningExpr()));
  2053. if (Iter != ExpressionToClass.end())
  2054. ExpressionToClass.erase(Iter);
  2055. #ifdef EXPENSIVE_CHECKS
  2056. assert(
  2057. (*OldClass->getDefiningExpr() != *E || ExpressionToClass.lookup(E)) &&
  2058. "We erased the expression we just inserted, which should not happen");
  2059. #endif
  2060. }
  2061. } else if (OldClass->getLeader() == I) {
  2062. // When the leader changes, the value numbering of
  2063. // everything may change due to symbolization changes, so we need to
  2064. // reprocess.
  2065. LLVM_DEBUG(dbgs() << "Value class leader change for class "
  2066. << OldClass->getID() << "\n");
  2067. ++NumGVNLeaderChanges;
  2068. // Destroy the stored value if there are no more stores to represent it.
  2069. // Note that this is basically clean up for the expression removal that
  2070. // happens below. If we remove stores from a class, we may leave it as a
  2071. // class of equivalent memory phis.
  2072. if (OldClass->getStoreCount() == 0) {
  2073. if (OldClass->getStoredValue())
  2074. OldClass->setStoredValue(nullptr);
  2075. }
  2076. OldClass->setLeader(getNextValueLeader(OldClass));
  2077. OldClass->resetNextLeader();
  2078. markValueLeaderChangeTouched(OldClass);
  2079. }
  2080. }
  2081. // For a given expression, mark the phi of ops instructions that could have
  2082. // changed as a result.
  2083. void NewGVN::markPhiOfOpsChanged(const Expression *E) {
  2084. touchAndErase(ExpressionToPhiOfOps, E);
  2085. }
  2086. // Perform congruence finding on a given value numbering expression.
  2087. void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
  2088. // This is guaranteed to return something, since it will at least find
  2089. // TOP.
  2090. CongruenceClass *IClass = ValueToClass.lookup(I);
  2091. assert(IClass && "Should have found a IClass");
  2092. // Dead classes should have been eliminated from the mapping.
  2093. assert(!IClass->isDead() && "Found a dead class");
  2094. CongruenceClass *EClass = nullptr;
  2095. if (const auto *VE = dyn_cast<VariableExpression>(E)) {
  2096. EClass = ValueToClass.lookup(VE->getVariableValue());
  2097. } else if (isa<DeadExpression>(E)) {
  2098. EClass = TOPClass;
  2099. }
  2100. if (!EClass) {
  2101. auto lookupResult = ExpressionToClass.insert({E, nullptr});
  2102. // If it's not in the value table, create a new congruence class.
  2103. if (lookupResult.second) {
  2104. CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
  2105. auto place = lookupResult.first;
  2106. place->second = NewClass;
  2107. // Constants and variables should always be made the leader.
  2108. if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
  2109. NewClass->setLeader(CE->getConstantValue());
  2110. } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
  2111. StoreInst *SI = SE->getStoreInst();
  2112. NewClass->setLeader(SI);
  2113. NewClass->setStoredValue(SE->getStoredValue());
  2114. // The RepMemoryAccess field will be filled in properly by the
  2115. // moveValueToNewCongruenceClass call.
  2116. } else {
  2117. NewClass->setLeader(I);
  2118. }
  2119. assert(!isa<VariableExpression>(E) &&
  2120. "VariableExpression should have been handled already");
  2121. EClass = NewClass;
  2122. LLVM_DEBUG(dbgs() << "Created new congruence class for " << *I
  2123. << " using expression " << *E << " at "
  2124. << NewClass->getID() << " and leader "
  2125. << *(NewClass->getLeader()));
  2126. if (NewClass->getStoredValue())
  2127. LLVM_DEBUG(dbgs() << " and stored value "
  2128. << *(NewClass->getStoredValue()));
  2129. LLVM_DEBUG(dbgs() << "\n");
  2130. } else {
  2131. EClass = lookupResult.first->second;
  2132. if (isa<ConstantExpression>(E))
  2133. assert((isa<Constant>(EClass->getLeader()) ||
  2134. (EClass->getStoredValue() &&
  2135. isa<Constant>(EClass->getStoredValue()))) &&
  2136. "Any class with a constant expression should have a "
  2137. "constant leader");
  2138. assert(EClass && "Somehow don't have an eclass");
  2139. assert(!EClass->isDead() && "We accidentally looked up a dead class");
  2140. }
  2141. }
  2142. bool ClassChanged = IClass != EClass;
  2143. bool LeaderChanged = LeaderChanges.erase(I);
  2144. if (ClassChanged || LeaderChanged) {
  2145. LLVM_DEBUG(dbgs() << "New class " << EClass->getID() << " for expression "
  2146. << *E << "\n");
  2147. if (ClassChanged) {
  2148. moveValueToNewCongruenceClass(I, E, IClass, EClass);
  2149. markPhiOfOpsChanged(E);
  2150. }
  2151. markUsersTouched(I);
  2152. if (MemoryAccess *MA = getMemoryAccess(I))
  2153. markMemoryUsersTouched(MA);
  2154. if (auto *CI = dyn_cast<CmpInst>(I))
  2155. markPredicateUsersTouched(CI);
  2156. }
  2157. // If we changed the class of the store, we want to ensure nothing finds the
  2158. // old store expression. In particular, loads do not compare against stored
  2159. // value, so they will find old store expressions (and associated class
  2160. // mappings) if we leave them in the table.
  2161. if (ClassChanged && isa<StoreInst>(I)) {
  2162. auto *OldE = ValueToExpression.lookup(I);
  2163. // It could just be that the old class died. We don't want to erase it if we
  2164. // just moved classes.
  2165. if (OldE && isa<StoreExpression>(OldE) && *E != *OldE) {
  2166. // Erase this as an exact expression to ensure we don't erase expressions
  2167. // equivalent to it.
  2168. auto Iter = ExpressionToClass.find_as(ExactEqualsExpression(*OldE));
  2169. if (Iter != ExpressionToClass.end())
  2170. ExpressionToClass.erase(Iter);
  2171. }
  2172. }
  2173. ValueToExpression[I] = E;
  2174. }
  2175. // Process the fact that Edge (from, to) is reachable, including marking
  2176. // any newly reachable blocks and instructions for processing.
  2177. void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
  2178. // Check if the Edge was reachable before.
  2179. if (ReachableEdges.insert({From, To}).second) {
  2180. // If this block wasn't reachable before, all instructions are touched.
  2181. if (ReachableBlocks.insert(To).second) {
  2182. LLVM_DEBUG(dbgs() << "Block " << getBlockName(To)
  2183. << " marked reachable\n");
  2184. const auto &InstRange = BlockInstRange.lookup(To);
  2185. TouchedInstructions.set(InstRange.first, InstRange.second);
  2186. } else {
  2187. LLVM_DEBUG(dbgs() << "Block " << getBlockName(To)
  2188. << " was reachable, but new edge {"
  2189. << getBlockName(From) << "," << getBlockName(To)
  2190. << "} to it found\n");
  2191. // We've made an edge reachable to an existing block, which may
  2192. // impact predicates. Otherwise, only mark the phi nodes as touched, as
  2193. // they are the only thing that depend on new edges. Anything using their
  2194. // values will get propagated to if necessary.
  2195. if (MemoryAccess *MemPhi = getMemoryAccess(To))
  2196. TouchedInstructions.set(InstrToDFSNum(MemPhi));
  2197. // FIXME: We should just add a union op on a Bitvector and
  2198. // SparseBitVector. We can do it word by word faster than we are doing it
  2199. // here.
  2200. for (auto InstNum : RevisitOnReachabilityChange[To])
  2201. TouchedInstructions.set(InstNum);
  2202. }
  2203. }
  2204. }
  2205. // Given a predicate condition (from a switch, cmp, or whatever) and a block,
  2206. // see if we know some constant value for it already.
  2207. Value *NewGVN::findConditionEquivalence(Value *Cond) const {
  2208. auto Result = lookupOperandLeader(Cond);
  2209. return isa<Constant>(Result) ? Result : nullptr;
  2210. }
  2211. // Process the outgoing edges of a block for reachability.
  2212. void NewGVN::processOutgoingEdges(Instruction *TI, BasicBlock *B) {
  2213. // Evaluate reachability of terminator instruction.
  2214. Value *Cond;
  2215. BasicBlock *TrueSucc, *FalseSucc;
  2216. if (match(TI, m_Br(m_Value(Cond), TrueSucc, FalseSucc))) {
  2217. Value *CondEvaluated = findConditionEquivalence(Cond);
  2218. if (!CondEvaluated) {
  2219. if (auto *I = dyn_cast<Instruction>(Cond)) {
  2220. SmallPtrSet<Value *, 4> Visited;
  2221. auto Res = performSymbolicEvaluation(I, Visited);
  2222. if (const auto *CE = dyn_cast_or_null<ConstantExpression>(Res.Expr)) {
  2223. CondEvaluated = CE->getConstantValue();
  2224. addAdditionalUsers(Res, I);
  2225. } else {
  2226. // Did not use simplification result, no need to add the extra
  2227. // dependency.
  2228. Res.ExtraDep = nullptr;
  2229. }
  2230. } else if (isa<ConstantInt>(Cond)) {
  2231. CondEvaluated = Cond;
  2232. }
  2233. }
  2234. ConstantInt *CI;
  2235. if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
  2236. if (CI->isOne()) {
  2237. LLVM_DEBUG(dbgs() << "Condition for Terminator " << *TI
  2238. << " evaluated to true\n");
  2239. updateReachableEdge(B, TrueSucc);
  2240. } else if (CI->isZero()) {
  2241. LLVM_DEBUG(dbgs() << "Condition for Terminator " << *TI
  2242. << " evaluated to false\n");
  2243. updateReachableEdge(B, FalseSucc);
  2244. }
  2245. } else {
  2246. updateReachableEdge(B, TrueSucc);
  2247. updateReachableEdge(B, FalseSucc);
  2248. }
  2249. } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
  2250. // For switches, propagate the case values into the case
  2251. // destinations.
  2252. Value *SwitchCond = SI->getCondition();
  2253. Value *CondEvaluated = findConditionEquivalence(SwitchCond);
  2254. // See if we were able to turn this switch statement into a constant.
  2255. if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
  2256. auto *CondVal = cast<ConstantInt>(CondEvaluated);
  2257. // We should be able to get case value for this.
  2258. auto Case = *SI->findCaseValue(CondVal);
  2259. if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
  2260. // We proved the value is outside of the range of the case.
  2261. // We can't do anything other than mark the default dest as reachable,
  2262. // and go home.
  2263. updateReachableEdge(B, SI->getDefaultDest());
  2264. return;
  2265. }
  2266. // Now get where it goes and mark it reachable.
  2267. BasicBlock *TargetBlock = Case.getCaseSuccessor();
  2268. updateReachableEdge(B, TargetBlock);
  2269. } else {
  2270. for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
  2271. BasicBlock *TargetBlock = SI->getSuccessor(i);
  2272. updateReachableEdge(B, TargetBlock);
  2273. }
  2274. }
  2275. } else {
  2276. // Otherwise this is either unconditional, or a type we have no
  2277. // idea about. Just mark successors as reachable.
  2278. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
  2279. BasicBlock *TargetBlock = TI->getSuccessor(i);
  2280. updateReachableEdge(B, TargetBlock);
  2281. }
  2282. // This also may be a memory defining terminator, in which case, set it
  2283. // equivalent only to itself.
  2284. //
  2285. auto *MA = getMemoryAccess(TI);
  2286. if (MA && !isa<MemoryUse>(MA)) {
  2287. auto *CC = ensureLeaderOfMemoryClass(MA);
  2288. if (setMemoryClass(MA, CC))
  2289. markMemoryUsersTouched(MA);
  2290. }
  2291. }
  2292. }
  2293. // Remove the PHI of Ops PHI for I
  2294. void NewGVN::removePhiOfOps(Instruction *I, PHINode *PHITemp) {
  2295. InstrDFS.erase(PHITemp);
  2296. // It's still a temp instruction. We keep it in the array so it gets erased.
  2297. // However, it's no longer used by I, or in the block
  2298. TempToBlock.erase(PHITemp);
  2299. RealToTemp.erase(I);
  2300. // We don't remove the users from the phi node uses. This wastes a little
  2301. // time, but such is life. We could use two sets to track which were there
  2302. // are the start of NewGVN, and which were added, but right nowt he cost of
  2303. // tracking is more than the cost of checking for more phi of ops.
  2304. }
  2305. // Add PHI Op in BB as a PHI of operations version of ExistingValue.
  2306. void NewGVN::addPhiOfOps(PHINode *Op, BasicBlock *BB,
  2307. Instruction *ExistingValue) {
  2308. InstrDFS[Op] = InstrToDFSNum(ExistingValue);
  2309. AllTempInstructions.insert(Op);
  2310. TempToBlock[Op] = BB;
  2311. RealToTemp[ExistingValue] = Op;
  2312. // Add all users to phi node use, as they are now uses of the phi of ops phis
  2313. // and may themselves be phi of ops.
  2314. for (auto *U : ExistingValue->users())
  2315. if (auto *UI = dyn_cast<Instruction>(U))
  2316. PHINodeUses.insert(UI);
  2317. }
  2318. static bool okayForPHIOfOps(const Instruction *I) {
  2319. if (!EnablePhiOfOps)
  2320. return false;
  2321. return isa<BinaryOperator>(I) || isa<SelectInst>(I) || isa<CmpInst>(I) ||
  2322. isa<LoadInst>(I);
  2323. }
  2324. // Return true if this operand will be safe to use for phi of ops.
  2325. //
  2326. // The reason some operands are unsafe is that we are not trying to recursively
  2327. // translate everything back through phi nodes. We actually expect some lookups
  2328. // of expressions to fail. In particular, a lookup where the expression cannot
  2329. // exist in the predecessor. This is true even if the expression, as shown, can
  2330. // be determined to be constant.
  2331. bool NewGVN::OpIsSafeForPHIOfOps(Value *V, const BasicBlock *PHIBlock,
  2332. SmallPtrSetImpl<const Value *> &Visited) {
  2333. SmallVector<Value *, 4> Worklist;
  2334. Worklist.push_back(V);
  2335. while (!Worklist.empty()) {
  2336. auto *I = Worklist.pop_back_val();
  2337. if (!isa<Instruction>(I))
  2338. continue;
  2339. auto OISIt = OpSafeForPHIOfOps.find(I);
  2340. if (OISIt != OpSafeForPHIOfOps.end())
  2341. return OISIt->second;
  2342. // Keep walking until we either dominate the phi block, or hit a phi, or run
  2343. // out of things to check.
  2344. if (DT->properlyDominates(getBlockForValue(I), PHIBlock)) {
  2345. OpSafeForPHIOfOps.insert({I, true});
  2346. continue;
  2347. }
  2348. // PHI in the same block.
  2349. if (isa<PHINode>(I) && getBlockForValue(I) == PHIBlock) {
  2350. OpSafeForPHIOfOps.insert({I, false});
  2351. return false;
  2352. }
  2353. auto *OrigI = cast<Instruction>(I);
  2354. // When we hit an instruction that reads memory (load, call, etc), we must
  2355. // consider any store that may happen in the loop. For now, we assume the
  2356. // worst: there is a store in the loop that alias with this read.
  2357. // The case where the load is outside the loop is already covered by the
  2358. // dominator check above.
  2359. // TODO: relax this condition
  2360. if (OrigI->mayReadFromMemory())
  2361. return false;
  2362. // Check the operands of the current instruction.
  2363. for (auto *Op : OrigI->operand_values()) {
  2364. if (!isa<Instruction>(Op))
  2365. continue;
  2366. // Stop now if we find an unsafe operand.
  2367. auto OISIt = OpSafeForPHIOfOps.find(OrigI);
  2368. if (OISIt != OpSafeForPHIOfOps.end()) {
  2369. if (!OISIt->second) {
  2370. OpSafeForPHIOfOps.insert({I, false});
  2371. return false;
  2372. }
  2373. continue;
  2374. }
  2375. if (!Visited.insert(Op).second)
  2376. continue;
  2377. Worklist.push_back(cast<Instruction>(Op));
  2378. }
  2379. }
  2380. OpSafeForPHIOfOps.insert({V, true});
  2381. return true;
  2382. }
  2383. // Try to find a leader for instruction TransInst, which is a phi translated
  2384. // version of something in our original program. Visited is used to ensure we
  2385. // don't infinite loop during translations of cycles. OrigInst is the
  2386. // instruction in the original program, and PredBB is the predecessor we
  2387. // translated it through.
  2388. Value *NewGVN::findLeaderForInst(Instruction *TransInst,
  2389. SmallPtrSetImpl<Value *> &Visited,
  2390. MemoryAccess *MemAccess, Instruction *OrigInst,
  2391. BasicBlock *PredBB) {
  2392. unsigned IDFSNum = InstrToDFSNum(OrigInst);
  2393. // Make sure it's marked as a temporary instruction.
  2394. AllTempInstructions.insert(TransInst);
  2395. // and make sure anything that tries to add it's DFS number is
  2396. // redirected to the instruction we are making a phi of ops
  2397. // for.
  2398. TempToBlock.insert({TransInst, PredBB});
  2399. InstrDFS.insert({TransInst, IDFSNum});
  2400. auto Res = performSymbolicEvaluation(TransInst, Visited);
  2401. const Expression *E = Res.Expr;
  2402. addAdditionalUsers(Res, OrigInst);
  2403. InstrDFS.erase(TransInst);
  2404. AllTempInstructions.erase(TransInst);
  2405. TempToBlock.erase(TransInst);
  2406. if (MemAccess)
  2407. TempToMemory.erase(TransInst);
  2408. if (!E)
  2409. return nullptr;
  2410. auto *FoundVal = findPHIOfOpsLeader(E, OrigInst, PredBB);
  2411. if (!FoundVal) {
  2412. ExpressionToPhiOfOps[E].insert(OrigInst);
  2413. LLVM_DEBUG(dbgs() << "Cannot find phi of ops operand for " << *TransInst
  2414. << " in block " << getBlockName(PredBB) << "\n");
  2415. return nullptr;
  2416. }
  2417. if (auto *SI = dyn_cast<StoreInst>(FoundVal))
  2418. FoundVal = SI->getValueOperand();
  2419. return FoundVal;
  2420. }
  2421. // When we see an instruction that is an op of phis, generate the equivalent phi
  2422. // of ops form.
  2423. const Expression *
  2424. NewGVN::makePossiblePHIOfOps(Instruction *I,
  2425. SmallPtrSetImpl<Value *> &Visited) {
  2426. if (!okayForPHIOfOps(I))
  2427. return nullptr;
  2428. if (!Visited.insert(I).second)
  2429. return nullptr;
  2430. // For now, we require the instruction be cycle free because we don't
  2431. // *always* create a phi of ops for instructions that could be done as phi
  2432. // of ops, we only do it if we think it is useful. If we did do it all the
  2433. // time, we could remove the cycle free check.
  2434. if (!isCycleFree(I))
  2435. return nullptr;
  2436. SmallPtrSet<const Value *, 8> ProcessedPHIs;
  2437. // TODO: We don't do phi translation on memory accesses because it's
  2438. // complicated. For a load, we'd need to be able to simulate a new memoryuse,
  2439. // which we don't have a good way of doing ATM.
  2440. auto *MemAccess = getMemoryAccess(I);
  2441. // If the memory operation is defined by a memory operation this block that
  2442. // isn't a MemoryPhi, transforming the pointer backwards through a scalar phi
  2443. // can't help, as it would still be killed by that memory operation.
  2444. if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
  2445. MemAccess->getDefiningAccess()->getBlock() == I->getParent())
  2446. return nullptr;
  2447. // Convert op of phis to phi of ops
  2448. SmallPtrSet<const Value *, 10> VisitedOps;
  2449. SmallVector<Value *, 4> Ops(I->operand_values());
  2450. BasicBlock *SamePHIBlock = nullptr;
  2451. PHINode *OpPHI = nullptr;
  2452. if (!DebugCounter::shouldExecute(PHIOfOpsCounter))
  2453. return nullptr;
  2454. for (auto *Op : Ops) {
  2455. if (!isa<PHINode>(Op)) {
  2456. auto *ValuePHI = RealToTemp.lookup(Op);
  2457. if (!ValuePHI)
  2458. continue;
  2459. LLVM_DEBUG(dbgs() << "Found possible dependent phi of ops\n");
  2460. Op = ValuePHI;
  2461. }
  2462. OpPHI = cast<PHINode>(Op);
  2463. if (!SamePHIBlock) {
  2464. SamePHIBlock = getBlockForValue(OpPHI);
  2465. } else if (SamePHIBlock != getBlockForValue(OpPHI)) {
  2466. LLVM_DEBUG(
  2467. dbgs()
  2468. << "PHIs for operands are not all in the same block, aborting\n");
  2469. return nullptr;
  2470. }
  2471. // No point in doing this for one-operand phis.
  2472. if (OpPHI->getNumOperands() == 1) {
  2473. OpPHI = nullptr;
  2474. continue;
  2475. }
  2476. }
  2477. if (!OpPHI)
  2478. return nullptr;
  2479. SmallVector<ValPair, 4> PHIOps;
  2480. SmallPtrSet<Value *, 4> Deps;
  2481. auto *PHIBlock = getBlockForValue(OpPHI);
  2482. RevisitOnReachabilityChange[PHIBlock].reset(InstrToDFSNum(I));
  2483. for (unsigned PredNum = 0; PredNum < OpPHI->getNumOperands(); ++PredNum) {
  2484. auto *PredBB = OpPHI->getIncomingBlock(PredNum);
  2485. Value *FoundVal = nullptr;
  2486. SmallPtrSet<Value *, 4> CurrentDeps;
  2487. // We could just skip unreachable edges entirely but it's tricky to do
  2488. // with rewriting existing phi nodes.
  2489. if (ReachableEdges.count({PredBB, PHIBlock})) {
  2490. // Clone the instruction, create an expression from it that is
  2491. // translated back into the predecessor, and see if we have a leader.
  2492. Instruction *ValueOp = I->clone();
  2493. if (MemAccess)
  2494. TempToMemory.insert({ValueOp, MemAccess});
  2495. bool SafeForPHIOfOps = true;
  2496. VisitedOps.clear();
  2497. for (auto &Op : ValueOp->operands()) {
  2498. auto *OrigOp = &*Op;
  2499. // When these operand changes, it could change whether there is a
  2500. // leader for us or not, so we have to add additional users.
  2501. if (isa<PHINode>(Op)) {
  2502. Op = Op->DoPHITranslation(PHIBlock, PredBB);
  2503. if (Op != OrigOp && Op != I)
  2504. CurrentDeps.insert(Op);
  2505. } else if (auto *ValuePHI = RealToTemp.lookup(Op)) {
  2506. if (getBlockForValue(ValuePHI) == PHIBlock)
  2507. Op = ValuePHI->getIncomingValueForBlock(PredBB);
  2508. }
  2509. // If we phi-translated the op, it must be safe.
  2510. SafeForPHIOfOps =
  2511. SafeForPHIOfOps &&
  2512. (Op != OrigOp || OpIsSafeForPHIOfOps(Op, PHIBlock, VisitedOps));
  2513. }
  2514. // FIXME: For those things that are not safe we could generate
  2515. // expressions all the way down, and see if this comes out to a
  2516. // constant. For anything where that is true, and unsafe, we should
  2517. // have made a phi-of-ops (or value numbered it equivalent to something)
  2518. // for the pieces already.
  2519. FoundVal = !SafeForPHIOfOps ? nullptr
  2520. : findLeaderForInst(ValueOp, Visited,
  2521. MemAccess, I, PredBB);
  2522. ValueOp->deleteValue();
  2523. if (!FoundVal) {
  2524. // We failed to find a leader for the current ValueOp, but this might
  2525. // change in case of the translated operands change.
  2526. if (SafeForPHIOfOps)
  2527. for (auto *Dep : CurrentDeps)
  2528. addAdditionalUsers(Dep, I);
  2529. return nullptr;
  2530. }
  2531. Deps.insert(CurrentDeps.begin(), CurrentDeps.end());
  2532. } else {
  2533. LLVM_DEBUG(dbgs() << "Skipping phi of ops operand for incoming block "
  2534. << getBlockName(PredBB)
  2535. << " because the block is unreachable\n");
  2536. FoundVal = PoisonValue::get(I->getType());
  2537. RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(I));
  2538. }
  2539. PHIOps.push_back({FoundVal, PredBB});
  2540. LLVM_DEBUG(dbgs() << "Found phi of ops operand " << *FoundVal << " in "
  2541. << getBlockName(PredBB) << "\n");
  2542. }
  2543. for (auto *Dep : Deps)
  2544. addAdditionalUsers(Dep, I);
  2545. sortPHIOps(PHIOps);
  2546. auto *E = performSymbolicPHIEvaluation(PHIOps, I, PHIBlock);
  2547. if (isa<ConstantExpression>(E) || isa<VariableExpression>(E)) {
  2548. LLVM_DEBUG(
  2549. dbgs()
  2550. << "Not creating real PHI of ops because it simplified to existing "
  2551. "value or constant\n");
  2552. // We have leaders for all operands, but do not create a real PHI node with
  2553. // those leaders as operands, so the link between the operands and the
  2554. // PHI-of-ops is not materialized in the IR. If any of those leaders
  2555. // changes, the PHI-of-op may change also, so we need to add the operands as
  2556. // additional users.
  2557. for (auto &O : PHIOps)
  2558. addAdditionalUsers(O.first, I);
  2559. return E;
  2560. }
  2561. auto *ValuePHI = RealToTemp.lookup(I);
  2562. bool NewPHI = false;
  2563. if (!ValuePHI) {
  2564. ValuePHI =
  2565. PHINode::Create(I->getType(), OpPHI->getNumOperands(), "phiofops");
  2566. addPhiOfOps(ValuePHI, PHIBlock, I);
  2567. NewPHI = true;
  2568. NumGVNPHIOfOpsCreated++;
  2569. }
  2570. if (NewPHI) {
  2571. for (auto PHIOp : PHIOps)
  2572. ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
  2573. } else {
  2574. TempToBlock[ValuePHI] = PHIBlock;
  2575. unsigned int i = 0;
  2576. for (auto PHIOp : PHIOps) {
  2577. ValuePHI->setIncomingValue(i, PHIOp.first);
  2578. ValuePHI->setIncomingBlock(i, PHIOp.second);
  2579. ++i;
  2580. }
  2581. }
  2582. RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(I));
  2583. LLVM_DEBUG(dbgs() << "Created phi of ops " << *ValuePHI << " for " << *I
  2584. << "\n");
  2585. return E;
  2586. }
  2587. // The algorithm initially places the values of the routine in the TOP
  2588. // congruence class. The leader of TOP is the undetermined value `poison`.
  2589. // When the algorithm has finished, values still in TOP are unreachable.
  2590. void NewGVN::initializeCongruenceClasses(Function &F) {
  2591. NextCongruenceNum = 0;
  2592. // Note that even though we use the live on entry def as a representative
  2593. // MemoryAccess, it is *not* the same as the actual live on entry def. We
  2594. // have no real equivalent to poison for MemoryAccesses, and so we really
  2595. // should be checking whether the MemoryAccess is top if we want to know if it
  2596. // is equivalent to everything. Otherwise, what this really signifies is that
  2597. // the access "it reaches all the way back to the beginning of the function"
  2598. // Initialize all other instructions to be in TOP class.
  2599. TOPClass = createCongruenceClass(nullptr, nullptr);
  2600. TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
  2601. // The live on entry def gets put into it's own class
  2602. MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
  2603. createMemoryClass(MSSA->getLiveOnEntryDef());
  2604. for (auto *DTN : nodes(DT)) {
  2605. BasicBlock *BB = DTN->getBlock();
  2606. // All MemoryAccesses are equivalent to live on entry to start. They must
  2607. // be initialized to something so that initial changes are noticed. For
  2608. // the maximal answer, we initialize them all to be the same as
  2609. // liveOnEntry.
  2610. auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
  2611. if (MemoryBlockDefs)
  2612. for (const auto &Def : *MemoryBlockDefs) {
  2613. MemoryAccessToClass[&Def] = TOPClass;
  2614. auto *MD = dyn_cast<MemoryDef>(&Def);
  2615. // Insert the memory phis into the member list.
  2616. if (!MD) {
  2617. const MemoryPhi *MP = cast<MemoryPhi>(&Def);
  2618. TOPClass->memory_insert(MP);
  2619. MemoryPhiState.insert({MP, MPS_TOP});
  2620. }
  2621. if (MD && isa<StoreInst>(MD->getMemoryInst()))
  2622. TOPClass->incStoreCount();
  2623. }
  2624. // FIXME: This is trying to discover which instructions are uses of phi
  2625. // nodes. We should move this into one of the myriad of places that walk
  2626. // all the operands already.
  2627. for (auto &I : *BB) {
  2628. if (isa<PHINode>(&I))
  2629. for (auto *U : I.users())
  2630. if (auto *UInst = dyn_cast<Instruction>(U))
  2631. if (InstrToDFSNum(UInst) != 0 && okayForPHIOfOps(UInst))
  2632. PHINodeUses.insert(UInst);
  2633. // Don't insert void terminators into the class. We don't value number
  2634. // them, and they just end up sitting in TOP.
  2635. if (I.isTerminator() && I.getType()->isVoidTy())
  2636. continue;
  2637. TOPClass->insert(&I);
  2638. ValueToClass[&I] = TOPClass;
  2639. }
  2640. }
  2641. // Initialize arguments to be in their own unique congruence classes
  2642. for (auto &FA : F.args())
  2643. createSingletonCongruenceClass(&FA);
  2644. }
  2645. void NewGVN::cleanupTables() {
  2646. for (CongruenceClass *&CC : CongruenceClasses) {
  2647. LLVM_DEBUG(dbgs() << "Congruence class " << CC->getID() << " has "
  2648. << CC->size() << " members\n");
  2649. // Make sure we delete the congruence class (probably worth switching to
  2650. // a unique_ptr at some point.
  2651. delete CC;
  2652. CC = nullptr;
  2653. }
  2654. // Destroy the value expressions
  2655. SmallVector<Instruction *, 8> TempInst(AllTempInstructions.begin(),
  2656. AllTempInstructions.end());
  2657. AllTempInstructions.clear();
  2658. // We have to drop all references for everything first, so there are no uses
  2659. // left as we delete them.
  2660. for (auto *I : TempInst) {
  2661. I->dropAllReferences();
  2662. }
  2663. while (!TempInst.empty()) {
  2664. auto *I = TempInst.pop_back_val();
  2665. I->deleteValue();
  2666. }
  2667. ValueToClass.clear();
  2668. ArgRecycler.clear(ExpressionAllocator);
  2669. ExpressionAllocator.Reset();
  2670. CongruenceClasses.clear();
  2671. ExpressionToClass.clear();
  2672. ValueToExpression.clear();
  2673. RealToTemp.clear();
  2674. AdditionalUsers.clear();
  2675. ExpressionToPhiOfOps.clear();
  2676. TempToBlock.clear();
  2677. TempToMemory.clear();
  2678. PHINodeUses.clear();
  2679. OpSafeForPHIOfOps.clear();
  2680. ReachableBlocks.clear();
  2681. ReachableEdges.clear();
  2682. #ifndef NDEBUG
  2683. ProcessedCount.clear();
  2684. #endif
  2685. InstrDFS.clear();
  2686. InstructionsToErase.clear();
  2687. DFSToInstr.clear();
  2688. BlockInstRange.clear();
  2689. TouchedInstructions.clear();
  2690. MemoryAccessToClass.clear();
  2691. PredicateToUsers.clear();
  2692. MemoryToUsers.clear();
  2693. RevisitOnReachabilityChange.clear();
  2694. IntrinsicInstPred.clear();
  2695. }
  2696. // Assign local DFS number mapping to instructions, and leave space for Value
  2697. // PHI's.
  2698. std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
  2699. unsigned Start) {
  2700. unsigned End = Start;
  2701. if (MemoryAccess *MemPhi = getMemoryAccess(B)) {
  2702. InstrDFS[MemPhi] = End++;
  2703. DFSToInstr.emplace_back(MemPhi);
  2704. }
  2705. // Then the real block goes next.
  2706. for (auto &I : *B) {
  2707. // There's no need to call isInstructionTriviallyDead more than once on
  2708. // an instruction. Therefore, once we know that an instruction is dead
  2709. // we change its DFS number so that it doesn't get value numbered.
  2710. if (isInstructionTriviallyDead(&I, TLI)) {
  2711. InstrDFS[&I] = 0;
  2712. LLVM_DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
  2713. markInstructionForDeletion(&I);
  2714. continue;
  2715. }
  2716. if (isa<PHINode>(&I))
  2717. RevisitOnReachabilityChange[B].set(End);
  2718. InstrDFS[&I] = End++;
  2719. DFSToInstr.emplace_back(&I);
  2720. }
  2721. // All of the range functions taken half-open ranges (open on the end side).
  2722. // So we do not subtract one from count, because at this point it is one
  2723. // greater than the last instruction.
  2724. return std::make_pair(Start, End);
  2725. }
  2726. void NewGVN::updateProcessedCount(const Value *V) {
  2727. #ifndef NDEBUG
  2728. if (ProcessedCount.count(V) == 0) {
  2729. ProcessedCount.insert({V, 1});
  2730. } else {
  2731. ++ProcessedCount[V];
  2732. assert(ProcessedCount[V] < 100 &&
  2733. "Seem to have processed the same Value a lot");
  2734. }
  2735. #endif
  2736. }
  2737. // Evaluate MemoryPhi nodes symbolically, just like PHI nodes
  2738. void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
  2739. // If all the arguments are the same, the MemoryPhi has the same value as the
  2740. // argument. Filter out unreachable blocks and self phis from our operands.
  2741. // TODO: We could do cycle-checking on the memory phis to allow valueizing for
  2742. // self-phi checking.
  2743. const BasicBlock *PHIBlock = MP->getBlock();
  2744. auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
  2745. return cast<MemoryAccess>(U) != MP &&
  2746. !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
  2747. ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
  2748. });
  2749. // If all that is left is nothing, our memoryphi is poison. We keep it as
  2750. // InitialClass. Note: The only case this should happen is if we have at
  2751. // least one self-argument.
  2752. if (Filtered.begin() == Filtered.end()) {
  2753. if (setMemoryClass(MP, TOPClass))
  2754. markMemoryUsersTouched(MP);
  2755. return;
  2756. }
  2757. // Transform the remaining operands into operand leaders.
  2758. // FIXME: mapped_iterator should have a range version.
  2759. auto LookupFunc = [&](const Use &U) {
  2760. return lookupMemoryLeader(cast<MemoryAccess>(U));
  2761. };
  2762. auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
  2763. auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
  2764. // and now check if all the elements are equal.
  2765. // Sadly, we can't use std::equals since these are random access iterators.
  2766. const auto *AllSameValue = *MappedBegin;
  2767. ++MappedBegin;
  2768. bool AllEqual = std::all_of(
  2769. MappedBegin, MappedEnd,
  2770. [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
  2771. if (AllEqual)
  2772. LLVM_DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue
  2773. << "\n");
  2774. else
  2775. LLVM_DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
  2776. // If it's equal to something, it's in that class. Otherwise, it has to be in
  2777. // a class where it is the leader (other things may be equivalent to it, but
  2778. // it needs to start off in its own class, which means it must have been the
  2779. // leader, and it can't have stopped being the leader because it was never
  2780. // removed).
  2781. CongruenceClass *CC =
  2782. AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
  2783. auto OldState = MemoryPhiState.lookup(MP);
  2784. assert(OldState != MPS_Invalid && "Invalid memory phi state");
  2785. auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
  2786. MemoryPhiState[MP] = NewState;
  2787. if (setMemoryClass(MP, CC) || OldState != NewState)
  2788. markMemoryUsersTouched(MP);
  2789. }
  2790. // Value number a single instruction, symbolically evaluating, performing
  2791. // congruence finding, and updating mappings.
  2792. void NewGVN::valueNumberInstruction(Instruction *I) {
  2793. LLVM_DEBUG(dbgs() << "Processing instruction " << *I << "\n");
  2794. if (!I->isTerminator()) {
  2795. const Expression *Symbolized = nullptr;
  2796. SmallPtrSet<Value *, 2> Visited;
  2797. if (DebugCounter::shouldExecute(VNCounter)) {
  2798. auto Res = performSymbolicEvaluation(I, Visited);
  2799. Symbolized = Res.Expr;
  2800. addAdditionalUsers(Res, I);
  2801. // Make a phi of ops if necessary
  2802. if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
  2803. !isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
  2804. auto *PHIE = makePossiblePHIOfOps(I, Visited);
  2805. // If we created a phi of ops, use it.
  2806. // If we couldn't create one, make sure we don't leave one lying around
  2807. if (PHIE) {
  2808. Symbolized = PHIE;
  2809. } else if (auto *Op = RealToTemp.lookup(I)) {
  2810. removePhiOfOps(I, Op);
  2811. }
  2812. }
  2813. } else {
  2814. // Mark the instruction as unused so we don't value number it again.
  2815. InstrDFS[I] = 0;
  2816. }
  2817. // If we couldn't come up with a symbolic expression, use the unknown
  2818. // expression
  2819. if (Symbolized == nullptr)
  2820. Symbolized = createUnknownExpression(I);
  2821. performCongruenceFinding(I, Symbolized);
  2822. } else {
  2823. // Handle terminators that return values. All of them produce values we
  2824. // don't currently understand. We don't place non-value producing
  2825. // terminators in a class.
  2826. if (!I->getType()->isVoidTy()) {
  2827. auto *Symbolized = createUnknownExpression(I);
  2828. performCongruenceFinding(I, Symbolized);
  2829. }
  2830. processOutgoingEdges(I, I->getParent());
  2831. }
  2832. }
  2833. // Check if there is a path, using single or equal argument phi nodes, from
  2834. // First to Second.
  2835. bool NewGVN::singleReachablePHIPath(
  2836. SmallPtrSet<const MemoryAccess *, 8> &Visited, const MemoryAccess *First,
  2837. const MemoryAccess *Second) const {
  2838. if (First == Second)
  2839. return true;
  2840. if (MSSA->isLiveOnEntryDef(First))
  2841. return false;
  2842. // This is not perfect, but as we're just verifying here, we can live with
  2843. // the loss of precision. The real solution would be that of doing strongly
  2844. // connected component finding in this routine, and it's probably not worth
  2845. // the complexity for the time being. So, we just keep a set of visited
  2846. // MemoryAccess and return true when we hit a cycle.
  2847. if (!Visited.insert(First).second)
  2848. return true;
  2849. const auto *EndDef = First;
  2850. for (const auto *ChainDef : optimized_def_chain(First)) {
  2851. if (ChainDef == Second)
  2852. return true;
  2853. if (MSSA->isLiveOnEntryDef(ChainDef))
  2854. return false;
  2855. EndDef = ChainDef;
  2856. }
  2857. auto *MP = cast<MemoryPhi>(EndDef);
  2858. auto ReachableOperandPred = [&](const Use &U) {
  2859. return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
  2860. };
  2861. auto FilteredPhiArgs =
  2862. make_filter_range(MP->operands(), ReachableOperandPred);
  2863. SmallVector<const Value *, 32> OperandList;
  2864. llvm::copy(FilteredPhiArgs, std::back_inserter(OperandList));
  2865. bool Okay = all_equal(OperandList);
  2866. if (Okay)
  2867. return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
  2868. Second);
  2869. return false;
  2870. }
  2871. // Verify the that the memory equivalence table makes sense relative to the
  2872. // congruence classes. Note that this checking is not perfect, and is currently
  2873. // subject to very rare false negatives. It is only useful for
  2874. // testing/debugging.
  2875. void NewGVN::verifyMemoryCongruency() const {
  2876. #ifndef NDEBUG
  2877. // Verify that the memory table equivalence and memory member set match
  2878. for (const auto *CC : CongruenceClasses) {
  2879. if (CC == TOPClass || CC->isDead())
  2880. continue;
  2881. if (CC->getStoreCount() != 0) {
  2882. assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
  2883. "Any class with a store as a leader should have a "
  2884. "representative stored value");
  2885. assert(CC->getMemoryLeader() &&
  2886. "Any congruence class with a store should have a "
  2887. "representative access");
  2888. }
  2889. if (CC->getMemoryLeader())
  2890. assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
  2891. "Representative MemoryAccess does not appear to be reverse "
  2892. "mapped properly");
  2893. for (const auto *M : CC->memory())
  2894. assert(MemoryAccessToClass.lookup(M) == CC &&
  2895. "Memory member does not appear to be reverse mapped properly");
  2896. }
  2897. // Anything equivalent in the MemoryAccess table should be in the same
  2898. // congruence class.
  2899. // Filter out the unreachable and trivially dead entries, because they may
  2900. // never have been updated if the instructions were not processed.
  2901. auto ReachableAccessPred =
  2902. [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
  2903. bool Result = ReachableBlocks.count(Pair.first->getBlock());
  2904. if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
  2905. MemoryToDFSNum(Pair.first) == 0)
  2906. return false;
  2907. if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
  2908. return !isInstructionTriviallyDead(MemDef->getMemoryInst());
  2909. // We could have phi nodes which operands are all trivially dead,
  2910. // so we don't process them.
  2911. if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
  2912. for (const auto &U : MemPHI->incoming_values()) {
  2913. if (auto *I = dyn_cast<Instruction>(&*U)) {
  2914. if (!isInstructionTriviallyDead(I))
  2915. return true;
  2916. }
  2917. }
  2918. return false;
  2919. }
  2920. return true;
  2921. };
  2922. auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
  2923. for (auto KV : Filtered) {
  2924. if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
  2925. auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
  2926. if (FirstMUD && SecondMUD) {
  2927. SmallPtrSet<const MemoryAccess *, 8> VisitedMAS;
  2928. assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
  2929. ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
  2930. ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
  2931. "The instructions for these memory operations should have "
  2932. "been in the same congruence class or reachable through"
  2933. "a single argument phi");
  2934. }
  2935. } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
  2936. // We can only sanely verify that MemoryDefs in the operand list all have
  2937. // the same class.
  2938. auto ReachableOperandPred = [&](const Use &U) {
  2939. return ReachableEdges.count(
  2940. {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
  2941. isa<MemoryDef>(U);
  2942. };
  2943. // All arguments should in the same class, ignoring unreachable arguments
  2944. auto FilteredPhiArgs =
  2945. make_filter_range(FirstMP->operands(), ReachableOperandPred);
  2946. SmallVector<const CongruenceClass *, 16> PhiOpClasses;
  2947. std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
  2948. std::back_inserter(PhiOpClasses), [&](const Use &U) {
  2949. const MemoryDef *MD = cast<MemoryDef>(U);
  2950. return ValueToClass.lookup(MD->getMemoryInst());
  2951. });
  2952. assert(all_equal(PhiOpClasses) &&
  2953. "All MemoryPhi arguments should be in the same class");
  2954. }
  2955. }
  2956. #endif
  2957. }
  2958. // Verify that the sparse propagation we did actually found the maximal fixpoint
  2959. // We do this by storing the value to class mapping, touching all instructions,
  2960. // and redoing the iteration to see if anything changed.
  2961. void NewGVN::verifyIterationSettled(Function &F) {
  2962. #ifndef NDEBUG
  2963. LLVM_DEBUG(dbgs() << "Beginning iteration verification\n");
  2964. if (DebugCounter::isCounterSet(VNCounter))
  2965. DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
  2966. // Note that we have to store the actual classes, as we may change existing
  2967. // classes during iteration. This is because our memory iteration propagation
  2968. // is not perfect, and so may waste a little work. But it should generate
  2969. // exactly the same congruence classes we have now, with different IDs.
  2970. std::map<const Value *, CongruenceClass> BeforeIteration;
  2971. for (auto &KV : ValueToClass) {
  2972. if (auto *I = dyn_cast<Instruction>(KV.first))
  2973. // Skip unused/dead instructions.
  2974. if (InstrToDFSNum(I) == 0)
  2975. continue;
  2976. BeforeIteration.insert({KV.first, *KV.second});
  2977. }
  2978. TouchedInstructions.set();
  2979. TouchedInstructions.reset(0);
  2980. OpSafeForPHIOfOps.clear();
  2981. iterateTouchedInstructions();
  2982. DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
  2983. EqualClasses;
  2984. for (const auto &KV : ValueToClass) {
  2985. if (auto *I = dyn_cast<Instruction>(KV.first))
  2986. // Skip unused/dead instructions.
  2987. if (InstrToDFSNum(I) == 0)
  2988. continue;
  2989. // We could sink these uses, but i think this adds a bit of clarity here as
  2990. // to what we are comparing.
  2991. auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
  2992. auto *AfterCC = KV.second;
  2993. // Note that the classes can't change at this point, so we memoize the set
  2994. // that are equal.
  2995. if (!EqualClasses.count({BeforeCC, AfterCC})) {
  2996. assert(BeforeCC->isEquivalentTo(AfterCC) &&
  2997. "Value number changed after main loop completed!");
  2998. EqualClasses.insert({BeforeCC, AfterCC});
  2999. }
  3000. }
  3001. #endif
  3002. }
  3003. // Verify that for each store expression in the expression to class mapping,
  3004. // only the latest appears, and multiple ones do not appear.
  3005. // Because loads do not use the stored value when doing equality with stores,
  3006. // if we don't erase the old store expressions from the table, a load can find
  3007. // a no-longer valid StoreExpression.
  3008. void NewGVN::verifyStoreExpressions() const {
  3009. #ifndef NDEBUG
  3010. // This is the only use of this, and it's not worth defining a complicated
  3011. // densemapinfo hash/equality function for it.
  3012. std::set<
  3013. std::pair<const Value *,
  3014. std::tuple<const Value *, const CongruenceClass *, Value *>>>
  3015. StoreExpressionSet;
  3016. for (const auto &KV : ExpressionToClass) {
  3017. if (auto *SE = dyn_cast<StoreExpression>(KV.first)) {
  3018. // Make sure a version that will conflict with loads is not already there
  3019. auto Res = StoreExpressionSet.insert(
  3020. {SE->getOperand(0), std::make_tuple(SE->getMemoryLeader(), KV.second,
  3021. SE->getStoredValue())});
  3022. bool Okay = Res.second;
  3023. // It's okay to have the same expression already in there if it is
  3024. // identical in nature.
  3025. // This can happen when the leader of the stored value changes over time.
  3026. if (!Okay)
  3027. Okay = (std::get<1>(Res.first->second) == KV.second) &&
  3028. (lookupOperandLeader(std::get<2>(Res.first->second)) ==
  3029. lookupOperandLeader(SE->getStoredValue()));
  3030. assert(Okay && "Stored expression conflict exists in expression table");
  3031. auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
  3032. assert(ValueExpr && ValueExpr->equals(*SE) &&
  3033. "StoreExpression in ExpressionToClass is not latest "
  3034. "StoreExpression for value");
  3035. }
  3036. }
  3037. #endif
  3038. }
  3039. // This is the main value numbering loop, it iterates over the initial touched
  3040. // instruction set, propagating value numbers, marking things touched, etc,
  3041. // until the set of touched instructions is completely empty.
  3042. void NewGVN::iterateTouchedInstructions() {
  3043. uint64_t Iterations = 0;
  3044. // Figure out where touchedinstructions starts
  3045. int FirstInstr = TouchedInstructions.find_first();
  3046. // Nothing set, nothing to iterate, just return.
  3047. if (FirstInstr == -1)
  3048. return;
  3049. const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
  3050. while (TouchedInstructions.any()) {
  3051. ++Iterations;
  3052. // Walk through all the instructions in all the blocks in RPO.
  3053. // TODO: As we hit a new block, we should push and pop equalities into a
  3054. // table lookupOperandLeader can use, to catch things PredicateInfo
  3055. // might miss, like edge-only equivalences.
  3056. for (unsigned InstrNum : TouchedInstructions.set_bits()) {
  3057. // This instruction was found to be dead. We don't bother looking
  3058. // at it again.
  3059. if (InstrNum == 0) {
  3060. TouchedInstructions.reset(InstrNum);
  3061. continue;
  3062. }
  3063. Value *V = InstrFromDFSNum(InstrNum);
  3064. const BasicBlock *CurrBlock = getBlockForValue(V);
  3065. // If we hit a new block, do reachability processing.
  3066. if (CurrBlock != LastBlock) {
  3067. LastBlock = CurrBlock;
  3068. bool BlockReachable = ReachableBlocks.count(CurrBlock);
  3069. const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
  3070. // If it's not reachable, erase any touched instructions and move on.
  3071. if (!BlockReachable) {
  3072. TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
  3073. LLVM_DEBUG(dbgs() << "Skipping instructions in block "
  3074. << getBlockName(CurrBlock)
  3075. << " because it is unreachable\n");
  3076. continue;
  3077. }
  3078. updateProcessedCount(CurrBlock);
  3079. }
  3080. // Reset after processing (because we may mark ourselves as touched when
  3081. // we propagate equalities).
  3082. TouchedInstructions.reset(InstrNum);
  3083. if (auto *MP = dyn_cast<MemoryPhi>(V)) {
  3084. LLVM_DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
  3085. valueNumberMemoryPhi(MP);
  3086. } else if (auto *I = dyn_cast<Instruction>(V)) {
  3087. valueNumberInstruction(I);
  3088. } else {
  3089. llvm_unreachable("Should have been a MemoryPhi or Instruction");
  3090. }
  3091. updateProcessedCount(V);
  3092. }
  3093. }
  3094. NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
  3095. }
  3096. // This is the main transformation entry point.
  3097. bool NewGVN::runGVN() {
  3098. if (DebugCounter::isCounterSet(VNCounter))
  3099. StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
  3100. bool Changed = false;
  3101. NumFuncArgs = F.arg_size();
  3102. MSSAWalker = MSSA->getWalker();
  3103. SingletonDeadExpression = new (ExpressionAllocator) DeadExpression();
  3104. // Count number of instructions for sizing of hash tables, and come
  3105. // up with a global dfs numbering for instructions.
  3106. unsigned ICount = 1;
  3107. // Add an empty instruction to account for the fact that we start at 1
  3108. DFSToInstr.emplace_back(nullptr);
  3109. // Note: We want ideal RPO traversal of the blocks, which is not quite the
  3110. // same as dominator tree order, particularly with regard whether backedges
  3111. // get visited first or second, given a block with multiple successors.
  3112. // If we visit in the wrong order, we will end up performing N times as many
  3113. // iterations.
  3114. // The dominator tree does guarantee that, for a given dom tree node, it's
  3115. // parent must occur before it in the RPO ordering. Thus, we only need to sort
  3116. // the siblings.
  3117. ReversePostOrderTraversal<Function *> RPOT(&F);
  3118. unsigned Counter = 0;
  3119. for (auto &B : RPOT) {
  3120. auto *Node = DT->getNode(B);
  3121. assert(Node && "RPO and Dominator tree should have same reachability");
  3122. RPOOrdering[Node] = ++Counter;
  3123. }
  3124. // Sort dominator tree children arrays into RPO.
  3125. for (auto &B : RPOT) {
  3126. auto *Node = DT->getNode(B);
  3127. if (Node->getNumChildren() > 1)
  3128. llvm::sort(*Node, [&](const DomTreeNode *A, const DomTreeNode *B) {
  3129. return RPOOrdering[A] < RPOOrdering[B];
  3130. });
  3131. }
  3132. // Now a standard depth first ordering of the domtree is equivalent to RPO.
  3133. for (auto *DTN : depth_first(DT->getRootNode())) {
  3134. BasicBlock *B = DTN->getBlock();
  3135. const auto &BlockRange = assignDFSNumbers(B, ICount);
  3136. BlockInstRange.insert({B, BlockRange});
  3137. ICount += BlockRange.second - BlockRange.first;
  3138. }
  3139. initializeCongruenceClasses(F);
  3140. TouchedInstructions.resize(ICount);
  3141. // Ensure we don't end up resizing the expressionToClass map, as
  3142. // that can be quite expensive. At most, we have one expression per
  3143. // instruction.
  3144. ExpressionToClass.reserve(ICount);
  3145. // Initialize the touched instructions to include the entry block.
  3146. const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
  3147. TouchedInstructions.set(InstRange.first, InstRange.second);
  3148. LLVM_DEBUG(dbgs() << "Block " << getBlockName(&F.getEntryBlock())
  3149. << " marked reachable\n");
  3150. ReachableBlocks.insert(&F.getEntryBlock());
  3151. iterateTouchedInstructions();
  3152. verifyMemoryCongruency();
  3153. verifyIterationSettled(F);
  3154. verifyStoreExpressions();
  3155. Changed |= eliminateInstructions(F);
  3156. // Delete all instructions marked for deletion.
  3157. for (Instruction *ToErase : InstructionsToErase) {
  3158. if (!ToErase->use_empty())
  3159. ToErase->replaceAllUsesWith(PoisonValue::get(ToErase->getType()));
  3160. assert(ToErase->getParent() &&
  3161. "BB containing ToErase deleted unexpectedly!");
  3162. ToErase->eraseFromParent();
  3163. }
  3164. Changed |= !InstructionsToErase.empty();
  3165. // Delete all unreachable blocks.
  3166. auto UnreachableBlockPred = [&](const BasicBlock &BB) {
  3167. return !ReachableBlocks.count(&BB);
  3168. };
  3169. for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
  3170. LLVM_DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
  3171. << " is unreachable\n");
  3172. deleteInstructionsInBlock(&BB);
  3173. Changed = true;
  3174. }
  3175. cleanupTables();
  3176. return Changed;
  3177. }
  3178. struct NewGVN::ValueDFS {
  3179. int DFSIn = 0;
  3180. int DFSOut = 0;
  3181. int LocalNum = 0;
  3182. // Only one of Def and U will be set.
  3183. // The bool in the Def tells us whether the Def is the stored value of a
  3184. // store.
  3185. PointerIntPair<Value *, 1, bool> Def;
  3186. Use *U = nullptr;
  3187. bool operator<(const ValueDFS &Other) const {
  3188. // It's not enough that any given field be less than - we have sets
  3189. // of fields that need to be evaluated together to give a proper ordering.
  3190. // For example, if you have;
  3191. // DFS (1, 3)
  3192. // Val 0
  3193. // DFS (1, 2)
  3194. // Val 50
  3195. // We want the second to be less than the first, but if we just go field
  3196. // by field, we will get to Val 0 < Val 50 and say the first is less than
  3197. // the second. We only want it to be less than if the DFS orders are equal.
  3198. //
  3199. // Each LLVM instruction only produces one value, and thus the lowest-level
  3200. // differentiator that really matters for the stack (and what we use as as a
  3201. // replacement) is the local dfs number.
  3202. // Everything else in the structure is instruction level, and only affects
  3203. // the order in which we will replace operands of a given instruction.
  3204. //
  3205. // For a given instruction (IE things with equal dfsin, dfsout, localnum),
  3206. // the order of replacement of uses does not matter.
  3207. // IE given,
  3208. // a = 5
  3209. // b = a + a
  3210. // When you hit b, you will have two valuedfs with the same dfsin, out, and
  3211. // localnum.
  3212. // The .val will be the same as well.
  3213. // The .u's will be different.
  3214. // You will replace both, and it does not matter what order you replace them
  3215. // in (IE whether you replace operand 2, then operand 1, or operand 1, then
  3216. // operand 2).
  3217. // Similarly for the case of same dfsin, dfsout, localnum, but different
  3218. // .val's
  3219. // a = 5
  3220. // b = 6
  3221. // c = a + b
  3222. // in c, we will a valuedfs for a, and one for b,with everything the same
  3223. // but .val and .u.
  3224. // It does not matter what order we replace these operands in.
  3225. // You will always end up with the same IR, and this is guaranteed.
  3226. return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
  3227. std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
  3228. Other.U);
  3229. }
  3230. };
  3231. // This function converts the set of members for a congruence class from values,
  3232. // to sets of defs and uses with associated DFS info. The total number of
  3233. // reachable uses for each value is stored in UseCount, and instructions that
  3234. // seem
  3235. // dead (have no non-dead uses) are stored in ProbablyDead.
  3236. void NewGVN::convertClassToDFSOrdered(
  3237. const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
  3238. DenseMap<const Value *, unsigned int> &UseCounts,
  3239. SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
  3240. for (auto *D : Dense) {
  3241. // First add the value.
  3242. BasicBlock *BB = getBlockForValue(D);
  3243. // Constants are handled prior to ever calling this function, so
  3244. // we should only be left with instructions as members.
  3245. assert(BB && "Should have figured out a basic block for value");
  3246. ValueDFS VDDef;
  3247. DomTreeNode *DomNode = DT->getNode(BB);
  3248. VDDef.DFSIn = DomNode->getDFSNumIn();
  3249. VDDef.DFSOut = DomNode->getDFSNumOut();
  3250. // If it's a store, use the leader of the value operand, if it's always
  3251. // available, or the value operand. TODO: We could do dominance checks to
  3252. // find a dominating leader, but not worth it ATM.
  3253. if (auto *SI = dyn_cast<StoreInst>(D)) {
  3254. auto Leader = lookupOperandLeader(SI->getValueOperand());
  3255. if (alwaysAvailable(Leader)) {
  3256. VDDef.Def.setPointer(Leader);
  3257. } else {
  3258. VDDef.Def.setPointer(SI->getValueOperand());
  3259. VDDef.Def.setInt(true);
  3260. }
  3261. } else {
  3262. VDDef.Def.setPointer(D);
  3263. }
  3264. assert(isa<Instruction>(D) &&
  3265. "The dense set member should always be an instruction");
  3266. Instruction *Def = cast<Instruction>(D);
  3267. VDDef.LocalNum = InstrToDFSNum(D);
  3268. DFSOrderedSet.push_back(VDDef);
  3269. // If there is a phi node equivalent, add it
  3270. if (auto *PN = RealToTemp.lookup(Def)) {
  3271. auto *PHIE =
  3272. dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
  3273. if (PHIE) {
  3274. VDDef.Def.setInt(false);
  3275. VDDef.Def.setPointer(PN);
  3276. VDDef.LocalNum = 0;
  3277. DFSOrderedSet.push_back(VDDef);
  3278. }
  3279. }
  3280. unsigned int UseCount = 0;
  3281. // Now add the uses.
  3282. for (auto &U : Def->uses()) {
  3283. if (auto *I = dyn_cast<Instruction>(U.getUser())) {
  3284. // Don't try to replace into dead uses
  3285. if (InstructionsToErase.count(I))
  3286. continue;
  3287. ValueDFS VDUse;
  3288. // Put the phi node uses in the incoming block.
  3289. BasicBlock *IBlock;
  3290. if (auto *P = dyn_cast<PHINode>(I)) {
  3291. IBlock = P->getIncomingBlock(U);
  3292. // Make phi node users appear last in the incoming block
  3293. // they are from.
  3294. VDUse.LocalNum = InstrDFS.size() + 1;
  3295. } else {
  3296. IBlock = getBlockForValue(I);
  3297. VDUse.LocalNum = InstrToDFSNum(I);
  3298. }
  3299. // Skip uses in unreachable blocks, as we're going
  3300. // to delete them.
  3301. if (!ReachableBlocks.contains(IBlock))
  3302. continue;
  3303. DomTreeNode *DomNode = DT->getNode(IBlock);
  3304. VDUse.DFSIn = DomNode->getDFSNumIn();
  3305. VDUse.DFSOut = DomNode->getDFSNumOut();
  3306. VDUse.U = &U;
  3307. ++UseCount;
  3308. DFSOrderedSet.emplace_back(VDUse);
  3309. }
  3310. }
  3311. // If there are no uses, it's probably dead (but it may have side-effects,
  3312. // so not definitely dead. Otherwise, store the number of uses so we can
  3313. // track if it becomes dead later).
  3314. if (UseCount == 0)
  3315. ProbablyDead.insert(Def);
  3316. else
  3317. UseCounts[Def] = UseCount;
  3318. }
  3319. }
  3320. // This function converts the set of members for a congruence class from values,
  3321. // to the set of defs for loads and stores, with associated DFS info.
  3322. void NewGVN::convertClassToLoadsAndStores(
  3323. const CongruenceClass &Dense,
  3324. SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
  3325. for (auto *D : Dense) {
  3326. if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
  3327. continue;
  3328. BasicBlock *BB = getBlockForValue(D);
  3329. ValueDFS VD;
  3330. DomTreeNode *DomNode = DT->getNode(BB);
  3331. VD.DFSIn = DomNode->getDFSNumIn();
  3332. VD.DFSOut = DomNode->getDFSNumOut();
  3333. VD.Def.setPointer(D);
  3334. // If it's an instruction, use the real local dfs number.
  3335. if (auto *I = dyn_cast<Instruction>(D))
  3336. VD.LocalNum = InstrToDFSNum(I);
  3337. else
  3338. llvm_unreachable("Should have been an instruction");
  3339. LoadsAndStores.emplace_back(VD);
  3340. }
  3341. }
  3342. static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
  3343. patchReplacementInstruction(I, Repl);
  3344. I->replaceAllUsesWith(Repl);
  3345. }
  3346. void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
  3347. LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
  3348. ++NumGVNBlocksDeleted;
  3349. // Delete the instructions backwards, as it has a reduced likelihood of having
  3350. // to update as many def-use and use-def chains. Start after the terminator.
  3351. auto StartPoint = BB->rbegin();
  3352. ++StartPoint;
  3353. // Note that we explicitly recalculate BB->rend() on each iteration,
  3354. // as it may change when we remove the first instruction.
  3355. for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
  3356. Instruction &Inst = *I++;
  3357. if (!Inst.use_empty())
  3358. Inst.replaceAllUsesWith(PoisonValue::get(Inst.getType()));
  3359. if (isa<LandingPadInst>(Inst))
  3360. continue;
  3361. salvageKnowledge(&Inst, AC);
  3362. Inst.eraseFromParent();
  3363. ++NumGVNInstrDeleted;
  3364. }
  3365. // Now insert something that simplifycfg will turn into an unreachable.
  3366. Type *Int8Ty = Type::getInt8Ty(BB->getContext());
  3367. new StoreInst(PoisonValue::get(Int8Ty),
  3368. Constant::getNullValue(Int8Ty->getPointerTo()),
  3369. BB->getTerminator());
  3370. }
  3371. void NewGVN::markInstructionForDeletion(Instruction *I) {
  3372. LLVM_DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
  3373. InstructionsToErase.insert(I);
  3374. }
  3375. void NewGVN::replaceInstruction(Instruction *I, Value *V) {
  3376. LLVM_DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
  3377. patchAndReplaceAllUsesWith(I, V);
  3378. // We save the actual erasing to avoid invalidating memory
  3379. // dependencies until we are done with everything.
  3380. markInstructionForDeletion(I);
  3381. }
  3382. namespace {
  3383. // This is a stack that contains both the value and dfs info of where
  3384. // that value is valid.
  3385. class ValueDFSStack {
  3386. public:
  3387. Value *back() const { return ValueStack.back(); }
  3388. std::pair<int, int> dfs_back() const { return DFSStack.back(); }
  3389. void push_back(Value *V, int DFSIn, int DFSOut) {
  3390. ValueStack.emplace_back(V);
  3391. DFSStack.emplace_back(DFSIn, DFSOut);
  3392. }
  3393. bool empty() const { return DFSStack.empty(); }
  3394. bool isInScope(int DFSIn, int DFSOut) const {
  3395. if (empty())
  3396. return false;
  3397. return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
  3398. }
  3399. void popUntilDFSScope(int DFSIn, int DFSOut) {
  3400. // These two should always be in sync at this point.
  3401. assert(ValueStack.size() == DFSStack.size() &&
  3402. "Mismatch between ValueStack and DFSStack");
  3403. while (
  3404. !DFSStack.empty() &&
  3405. !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
  3406. DFSStack.pop_back();
  3407. ValueStack.pop_back();
  3408. }
  3409. }
  3410. private:
  3411. SmallVector<Value *, 8> ValueStack;
  3412. SmallVector<std::pair<int, int>, 8> DFSStack;
  3413. };
  3414. } // end anonymous namespace
  3415. // Given an expression, get the congruence class for it.
  3416. CongruenceClass *NewGVN::getClassForExpression(const Expression *E) const {
  3417. if (auto *VE = dyn_cast<VariableExpression>(E))
  3418. return ValueToClass.lookup(VE->getVariableValue());
  3419. else if (isa<DeadExpression>(E))
  3420. return TOPClass;
  3421. return ExpressionToClass.lookup(E);
  3422. }
  3423. // Given a value and a basic block we are trying to see if it is available in,
  3424. // see if the value has a leader available in that block.
  3425. Value *NewGVN::findPHIOfOpsLeader(const Expression *E,
  3426. const Instruction *OrigInst,
  3427. const BasicBlock *BB) const {
  3428. // It would already be constant if we could make it constant
  3429. if (auto *CE = dyn_cast<ConstantExpression>(E))
  3430. return CE->getConstantValue();
  3431. if (auto *VE = dyn_cast<VariableExpression>(E)) {
  3432. auto *V = VE->getVariableValue();
  3433. if (alwaysAvailable(V) || DT->dominates(getBlockForValue(V), BB))
  3434. return VE->getVariableValue();
  3435. }
  3436. auto *CC = getClassForExpression(E);
  3437. if (!CC)
  3438. return nullptr;
  3439. if (alwaysAvailable(CC->getLeader()))
  3440. return CC->getLeader();
  3441. for (auto *Member : *CC) {
  3442. auto *MemberInst = dyn_cast<Instruction>(Member);
  3443. if (MemberInst == OrigInst)
  3444. continue;
  3445. // Anything that isn't an instruction is always available.
  3446. if (!MemberInst)
  3447. return Member;
  3448. if (DT->dominates(getBlockForValue(MemberInst), BB))
  3449. return Member;
  3450. }
  3451. return nullptr;
  3452. }
  3453. bool NewGVN::eliminateInstructions(Function &F) {
  3454. // This is a non-standard eliminator. The normal way to eliminate is
  3455. // to walk the dominator tree in order, keeping track of available
  3456. // values, and eliminating them. However, this is mildly
  3457. // pointless. It requires doing lookups on every instruction,
  3458. // regardless of whether we will ever eliminate it. For
  3459. // instructions part of most singleton congruence classes, we know we
  3460. // will never eliminate them.
  3461. // Instead, this eliminator looks at the congruence classes directly, sorts
  3462. // them into a DFS ordering of the dominator tree, and then we just
  3463. // perform elimination straight on the sets by walking the congruence
  3464. // class member uses in order, and eliminate the ones dominated by the
  3465. // last member. This is worst case O(E log E) where E = number of
  3466. // instructions in a single congruence class. In theory, this is all
  3467. // instructions. In practice, it is much faster, as most instructions are
  3468. // either in singleton congruence classes or can't possibly be eliminated
  3469. // anyway (if there are no overlapping DFS ranges in class).
  3470. // When we find something not dominated, it becomes the new leader
  3471. // for elimination purposes.
  3472. // TODO: If we wanted to be faster, We could remove any members with no
  3473. // overlapping ranges while sorting, as we will never eliminate anything
  3474. // with those members, as they don't dominate anything else in our set.
  3475. bool AnythingReplaced = false;
  3476. // Since we are going to walk the domtree anyway, and we can't guarantee the
  3477. // DFS numbers are updated, we compute some ourselves.
  3478. DT->updateDFSNumbers();
  3479. // Go through all of our phi nodes, and kill the arguments associated with
  3480. // unreachable edges.
  3481. auto ReplaceUnreachablePHIArgs = [&](PHINode *PHI, BasicBlock *BB) {
  3482. for (auto &Operand : PHI->incoming_values())
  3483. if (!ReachableEdges.count({PHI->getIncomingBlock(Operand), BB})) {
  3484. LLVM_DEBUG(dbgs() << "Replacing incoming value of " << PHI
  3485. << " for block "
  3486. << getBlockName(PHI->getIncomingBlock(Operand))
  3487. << " with poison due to it being unreachable\n");
  3488. Operand.set(PoisonValue::get(PHI->getType()));
  3489. }
  3490. };
  3491. // Replace unreachable phi arguments.
  3492. // At this point, RevisitOnReachabilityChange only contains:
  3493. //
  3494. // 1. PHIs
  3495. // 2. Temporaries that will convert to PHIs
  3496. // 3. Operations that are affected by an unreachable edge but do not fit into
  3497. // 1 or 2 (rare).
  3498. // So it is a slight overshoot of what we want. We could make it exact by
  3499. // using two SparseBitVectors per block.
  3500. DenseMap<const BasicBlock *, unsigned> ReachablePredCount;
  3501. for (auto &KV : ReachableEdges)
  3502. ReachablePredCount[KV.getEnd()]++;
  3503. for (auto &BBPair : RevisitOnReachabilityChange) {
  3504. for (auto InstNum : BBPair.second) {
  3505. auto *Inst = InstrFromDFSNum(InstNum);
  3506. auto *PHI = dyn_cast<PHINode>(Inst);
  3507. PHI = PHI ? PHI : dyn_cast_or_null<PHINode>(RealToTemp.lookup(Inst));
  3508. if (!PHI)
  3509. continue;
  3510. auto *BB = BBPair.first;
  3511. if (ReachablePredCount.lookup(BB) != PHI->getNumIncomingValues())
  3512. ReplaceUnreachablePHIArgs(PHI, BB);
  3513. }
  3514. }
  3515. // Map to store the use counts
  3516. DenseMap<const Value *, unsigned int> UseCounts;
  3517. for (auto *CC : reverse(CongruenceClasses)) {
  3518. LLVM_DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID()
  3519. << "\n");
  3520. // Track the equivalent store info so we can decide whether to try
  3521. // dead store elimination.
  3522. SmallVector<ValueDFS, 8> PossibleDeadStores;
  3523. SmallPtrSet<Instruction *, 8> ProbablyDead;
  3524. if (CC->isDead() || CC->empty())
  3525. continue;
  3526. // Everything still in the TOP class is unreachable or dead.
  3527. if (CC == TOPClass) {
  3528. for (auto *M : *CC) {
  3529. auto *VTE = ValueToExpression.lookup(M);
  3530. if (VTE && isa<DeadExpression>(VTE))
  3531. markInstructionForDeletion(cast<Instruction>(M));
  3532. assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
  3533. InstructionsToErase.count(cast<Instruction>(M))) &&
  3534. "Everything in TOP should be unreachable or dead at this "
  3535. "point");
  3536. }
  3537. continue;
  3538. }
  3539. assert(CC->getLeader() && "We should have had a leader");
  3540. // If this is a leader that is always available, and it's a
  3541. // constant or has no equivalences, just replace everything with
  3542. // it. We then update the congruence class with whatever members
  3543. // are left.
  3544. Value *Leader =
  3545. CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
  3546. if (alwaysAvailable(Leader)) {
  3547. CongruenceClass::MemberSet MembersLeft;
  3548. for (auto *M : *CC) {
  3549. Value *Member = M;
  3550. // Void things have no uses we can replace.
  3551. if (Member == Leader || !isa<Instruction>(Member) ||
  3552. Member->getType()->isVoidTy()) {
  3553. MembersLeft.insert(Member);
  3554. continue;
  3555. }
  3556. LLVM_DEBUG(dbgs() << "Found replacement " << *(Leader) << " for "
  3557. << *Member << "\n");
  3558. auto *I = cast<Instruction>(Member);
  3559. assert(Leader != I && "About to accidentally remove our leader");
  3560. replaceInstruction(I, Leader);
  3561. AnythingReplaced = true;
  3562. }
  3563. CC->swap(MembersLeft);
  3564. } else {
  3565. // If this is a singleton, we can skip it.
  3566. if (CC->size() != 1 || RealToTemp.count(Leader)) {
  3567. // This is a stack because equality replacement/etc may place
  3568. // constants in the middle of the member list, and we want to use
  3569. // those constant values in preference to the current leader, over
  3570. // the scope of those constants.
  3571. ValueDFSStack EliminationStack;
  3572. // Convert the members to DFS ordered sets and then merge them.
  3573. SmallVector<ValueDFS, 8> DFSOrderedSet;
  3574. convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
  3575. // Sort the whole thing.
  3576. llvm::sort(DFSOrderedSet);
  3577. for (auto &VD : DFSOrderedSet) {
  3578. int MemberDFSIn = VD.DFSIn;
  3579. int MemberDFSOut = VD.DFSOut;
  3580. Value *Def = VD.Def.getPointer();
  3581. bool FromStore = VD.Def.getInt();
  3582. Use *U = VD.U;
  3583. // We ignore void things because we can't get a value from them.
  3584. if (Def && Def->getType()->isVoidTy())
  3585. continue;
  3586. auto *DefInst = dyn_cast_or_null<Instruction>(Def);
  3587. if (DefInst && AllTempInstructions.count(DefInst)) {
  3588. auto *PN = cast<PHINode>(DefInst);
  3589. // If this is a value phi and that's the expression we used, insert
  3590. // it into the program
  3591. // remove from temp instruction list.
  3592. AllTempInstructions.erase(PN);
  3593. auto *DefBlock = getBlockForValue(Def);
  3594. LLVM_DEBUG(dbgs() << "Inserting fully real phi of ops" << *Def
  3595. << " into block "
  3596. << getBlockName(getBlockForValue(Def)) << "\n");
  3597. PN->insertBefore(&DefBlock->front());
  3598. Def = PN;
  3599. NumGVNPHIOfOpsEliminations++;
  3600. }
  3601. if (EliminationStack.empty()) {
  3602. LLVM_DEBUG(dbgs() << "Elimination Stack is empty\n");
  3603. } else {
  3604. LLVM_DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
  3605. << EliminationStack.dfs_back().first << ","
  3606. << EliminationStack.dfs_back().second << ")\n");
  3607. }
  3608. LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
  3609. << MemberDFSOut << ")\n");
  3610. // First, we see if we are out of scope or empty. If so,
  3611. // and there equivalences, we try to replace the top of
  3612. // stack with equivalences (if it's on the stack, it must
  3613. // not have been eliminated yet).
  3614. // Then we synchronize to our current scope, by
  3615. // popping until we are back within a DFS scope that
  3616. // dominates the current member.
  3617. // Then, what happens depends on a few factors
  3618. // If the stack is now empty, we need to push
  3619. // If we have a constant or a local equivalence we want to
  3620. // start using, we also push.
  3621. // Otherwise, we walk along, processing members who are
  3622. // dominated by this scope, and eliminate them.
  3623. bool ShouldPush = Def && EliminationStack.empty();
  3624. bool OutOfScope =
  3625. !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
  3626. if (OutOfScope || ShouldPush) {
  3627. // Sync to our current scope.
  3628. EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
  3629. bool ShouldPush = Def && EliminationStack.empty();
  3630. if (ShouldPush) {
  3631. EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
  3632. }
  3633. }
  3634. // Skip the Def's, we only want to eliminate on their uses. But mark
  3635. // dominated defs as dead.
  3636. if (Def) {
  3637. // For anything in this case, what and how we value number
  3638. // guarantees that any side-effets that would have occurred (ie
  3639. // throwing, etc) can be proven to either still occur (because it's
  3640. // dominated by something that has the same side-effects), or never
  3641. // occur. Otherwise, we would not have been able to prove it value
  3642. // equivalent to something else. For these things, we can just mark
  3643. // it all dead. Note that this is different from the "ProbablyDead"
  3644. // set, which may not be dominated by anything, and thus, are only
  3645. // easy to prove dead if they are also side-effect free. Note that
  3646. // because stores are put in terms of the stored value, we skip
  3647. // stored values here. If the stored value is really dead, it will
  3648. // still be marked for deletion when we process it in its own class.
  3649. if (!EliminationStack.empty() && Def != EliminationStack.back() &&
  3650. isa<Instruction>(Def) && !FromStore)
  3651. markInstructionForDeletion(cast<Instruction>(Def));
  3652. continue;
  3653. }
  3654. // At this point, we know it is a Use we are trying to possibly
  3655. // replace.
  3656. assert(isa<Instruction>(U->get()) &&
  3657. "Current def should have been an instruction");
  3658. assert(isa<Instruction>(U->getUser()) &&
  3659. "Current user should have been an instruction");
  3660. // If the thing we are replacing into is already marked to be dead,
  3661. // this use is dead. Note that this is true regardless of whether
  3662. // we have anything dominating the use or not. We do this here
  3663. // because we are already walking all the uses anyway.
  3664. Instruction *InstUse = cast<Instruction>(U->getUser());
  3665. if (InstructionsToErase.count(InstUse)) {
  3666. auto &UseCount = UseCounts[U->get()];
  3667. if (--UseCount == 0) {
  3668. ProbablyDead.insert(cast<Instruction>(U->get()));
  3669. }
  3670. }
  3671. // If we get to this point, and the stack is empty we must have a use
  3672. // with nothing we can use to eliminate this use, so just skip it.
  3673. if (EliminationStack.empty())
  3674. continue;
  3675. Value *DominatingLeader = EliminationStack.back();
  3676. auto *II = dyn_cast<IntrinsicInst>(DominatingLeader);
  3677. bool isSSACopy = II && II->getIntrinsicID() == Intrinsic::ssa_copy;
  3678. if (isSSACopy)
  3679. DominatingLeader = II->getOperand(0);
  3680. // Don't replace our existing users with ourselves.
  3681. if (U->get() == DominatingLeader)
  3682. continue;
  3683. LLVM_DEBUG(dbgs()
  3684. << "Found replacement " << *DominatingLeader << " for "
  3685. << *U->get() << " in " << *(U->getUser()) << "\n");
  3686. // If we replaced something in an instruction, handle the patching of
  3687. // metadata. Skip this if we are replacing predicateinfo with its
  3688. // original operand, as we already know we can just drop it.
  3689. auto *ReplacedInst = cast<Instruction>(U->get());
  3690. auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
  3691. if (!PI || DominatingLeader != PI->OriginalOp)
  3692. patchReplacementInstruction(ReplacedInst, DominatingLeader);
  3693. U->set(DominatingLeader);
  3694. // This is now a use of the dominating leader, which means if the
  3695. // dominating leader was dead, it's now live!
  3696. auto &LeaderUseCount = UseCounts[DominatingLeader];
  3697. // It's about to be alive again.
  3698. if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
  3699. ProbablyDead.erase(cast<Instruction>(DominatingLeader));
  3700. // For copy instructions, we use their operand as a leader,
  3701. // which means we remove a user of the copy and it may become dead.
  3702. if (isSSACopy) {
  3703. unsigned &IIUseCount = UseCounts[II];
  3704. if (--IIUseCount == 0)
  3705. ProbablyDead.insert(II);
  3706. }
  3707. ++LeaderUseCount;
  3708. AnythingReplaced = true;
  3709. }
  3710. }
  3711. }
  3712. // At this point, anything still in the ProbablyDead set is actually dead if
  3713. // would be trivially dead.
  3714. for (auto *I : ProbablyDead)
  3715. if (wouldInstructionBeTriviallyDead(I))
  3716. markInstructionForDeletion(I);
  3717. // Cleanup the congruence class.
  3718. CongruenceClass::MemberSet MembersLeft;
  3719. for (auto *Member : *CC)
  3720. if (!isa<Instruction>(Member) ||
  3721. !InstructionsToErase.count(cast<Instruction>(Member)))
  3722. MembersLeft.insert(Member);
  3723. CC->swap(MembersLeft);
  3724. // If we have possible dead stores to look at, try to eliminate them.
  3725. if (CC->getStoreCount() > 0) {
  3726. convertClassToLoadsAndStores(*CC, PossibleDeadStores);
  3727. llvm::sort(PossibleDeadStores);
  3728. ValueDFSStack EliminationStack;
  3729. for (auto &VD : PossibleDeadStores) {
  3730. int MemberDFSIn = VD.DFSIn;
  3731. int MemberDFSOut = VD.DFSOut;
  3732. Instruction *Member = cast<Instruction>(VD.Def.getPointer());
  3733. if (EliminationStack.empty() ||
  3734. !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
  3735. // Sync to our current scope.
  3736. EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
  3737. if (EliminationStack.empty()) {
  3738. EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
  3739. continue;
  3740. }
  3741. }
  3742. // We already did load elimination, so nothing to do here.
  3743. if (isa<LoadInst>(Member))
  3744. continue;
  3745. assert(!EliminationStack.empty());
  3746. Instruction *Leader = cast<Instruction>(EliminationStack.back());
  3747. (void)Leader;
  3748. assert(DT->dominates(Leader->getParent(), Member->getParent()));
  3749. // Member is dominater by Leader, and thus dead
  3750. LLVM_DEBUG(dbgs() << "Marking dead store " << *Member
  3751. << " that is dominated by " << *Leader << "\n");
  3752. markInstructionForDeletion(Member);
  3753. CC->erase(Member);
  3754. ++NumGVNDeadStores;
  3755. }
  3756. }
  3757. }
  3758. return AnythingReplaced;
  3759. }
  3760. // This function provides global ranking of operations so that we can place them
  3761. // in a canonical order. Note that rank alone is not necessarily enough for a
  3762. // complete ordering, as constants all have the same rank. However, generally,
  3763. // we will simplify an operation with all constants so that it doesn't matter
  3764. // what order they appear in.
  3765. unsigned int NewGVN::getRank(const Value *V) const {
  3766. // Prefer constants to undef to anything else
  3767. // Undef is a constant, have to check it first.
  3768. // Prefer poison to undef as it's less defined.
  3769. // Prefer smaller constants to constantexprs
  3770. // Note that the order here matters because of class inheritance
  3771. if (isa<ConstantExpr>(V))
  3772. return 3;
  3773. if (isa<PoisonValue>(V))
  3774. return 1;
  3775. if (isa<UndefValue>(V))
  3776. return 2;
  3777. if (isa<Constant>(V))
  3778. return 0;
  3779. if (auto *A = dyn_cast<Argument>(V))
  3780. return 4 + A->getArgNo();
  3781. // Need to shift the instruction DFS by number of arguments + 5 to account for
  3782. // the constant and argument ranking above.
  3783. unsigned Result = InstrToDFSNum(V);
  3784. if (Result > 0)
  3785. return 5 + NumFuncArgs + Result;
  3786. // Unreachable or something else, just return a really large number.
  3787. return ~0;
  3788. }
  3789. // This is a function that says whether two commutative operations should
  3790. // have their order swapped when canonicalizing.
  3791. bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
  3792. // Because we only care about a total ordering, and don't rewrite expressions
  3793. // in this order, we order by rank, which will give a strict weak ordering to
  3794. // everything but constants, and then we order by pointer address.
  3795. return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
  3796. }
  3797. bool NewGVN::shouldSwapOperandsForIntrinsic(const Value *A, const Value *B,
  3798. const IntrinsicInst *I) const {
  3799. auto LookupResult = IntrinsicInstPred.find(I);
  3800. if (shouldSwapOperands(A, B)) {
  3801. if (LookupResult == IntrinsicInstPred.end())
  3802. IntrinsicInstPred.insert({I, B});
  3803. else
  3804. LookupResult->second = B;
  3805. return true;
  3806. }
  3807. if (LookupResult != IntrinsicInstPred.end()) {
  3808. auto *SeenPredicate = LookupResult->second;
  3809. if (SeenPredicate) {
  3810. if (SeenPredicate == B)
  3811. return true;
  3812. else
  3813. LookupResult->second = nullptr;
  3814. }
  3815. }
  3816. return false;
  3817. }
  3818. namespace {
  3819. class NewGVNLegacyPass : public FunctionPass {
  3820. public:
  3821. // Pass identification, replacement for typeid.
  3822. static char ID;
  3823. NewGVNLegacyPass() : FunctionPass(ID) {
  3824. initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
  3825. }
  3826. bool runOnFunction(Function &F) override;
  3827. private:
  3828. void getAnalysisUsage(AnalysisUsage &AU) const override {
  3829. AU.addRequired<AssumptionCacheTracker>();
  3830. AU.addRequired<DominatorTreeWrapperPass>();
  3831. AU.addRequired<TargetLibraryInfoWrapperPass>();
  3832. AU.addRequired<MemorySSAWrapperPass>();
  3833. AU.addRequired<AAResultsWrapperPass>();
  3834. AU.addPreserved<DominatorTreeWrapperPass>();
  3835. AU.addPreserved<GlobalsAAWrapperPass>();
  3836. }
  3837. };
  3838. } // end anonymous namespace
  3839. bool NewGVNLegacyPass::runOnFunction(Function &F) {
  3840. if (skipFunction(F))
  3841. return false;
  3842. return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
  3843. &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
  3844. &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
  3845. &getAnalysis<AAResultsWrapperPass>().getAAResults(),
  3846. &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
  3847. F.getParent()->getDataLayout())
  3848. .runGVN();
  3849. }
  3850. char NewGVNLegacyPass::ID = 0;
  3851. INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
  3852. false, false)
  3853. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  3854. INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
  3855. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  3856. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  3857. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  3858. INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
  3859. INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
  3860. false)
  3861. // createGVNPass - The public interface to this file.
  3862. FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
  3863. PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
  3864. // Apparently the order in which we get these results matter for
  3865. // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
  3866. // the same order here, just in case.
  3867. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  3868. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  3869. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  3870. auto &AA = AM.getResult<AAManager>(F);
  3871. auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
  3872. bool Changed =
  3873. NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
  3874. .runGVN();
  3875. if (!Changed)
  3876. return PreservedAnalyses::all();
  3877. PreservedAnalyses PA;
  3878. PA.preserve<DominatorTreeAnalysis>();
  3879. return PA;
  3880. }