GVN.cpp 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212
  1. //===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
  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. // This pass performs global value numbering to eliminate fully redundant
  10. // instructions. It also performs simple dead load elimination.
  11. //
  12. // Note that this pass does the value numbering itself; it does not use the
  13. // ValueNumbering analysis passes.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/Transforms/Scalar/GVN.h"
  17. #include "llvm/ADT/DenseMap.h"
  18. #include "llvm/ADT/DepthFirstIterator.h"
  19. #include "llvm/ADT/Hashing.h"
  20. #include "llvm/ADT/MapVector.h"
  21. #include "llvm/ADT/PostOrderIterator.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SetVector.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/Statistic.h"
  27. #include "llvm/Analysis/AliasAnalysis.h"
  28. #include "llvm/Analysis/AssumeBundleQueries.h"
  29. #include "llvm/Analysis/AssumptionCache.h"
  30. #include "llvm/Analysis/CFG.h"
  31. #include "llvm/Analysis/DomTreeUpdater.h"
  32. #include "llvm/Analysis/GlobalsModRef.h"
  33. #include "llvm/Analysis/InstructionPrecedenceTracking.h"
  34. #include "llvm/Analysis/InstructionSimplify.h"
  35. #include "llvm/Analysis/LoopInfo.h"
  36. #include "llvm/Analysis/MemoryBuiltins.h"
  37. #include "llvm/Analysis/MemoryDependenceAnalysis.h"
  38. #include "llvm/Analysis/MemorySSA.h"
  39. #include "llvm/Analysis/MemorySSAUpdater.h"
  40. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  41. #include "llvm/Analysis/PHITransAddr.h"
  42. #include "llvm/Analysis/TargetLibraryInfo.h"
  43. #include "llvm/Analysis/ValueTracking.h"
  44. #include "llvm/IR/Attributes.h"
  45. #include "llvm/IR/BasicBlock.h"
  46. #include "llvm/IR/Constant.h"
  47. #include "llvm/IR/Constants.h"
  48. #include "llvm/IR/DebugLoc.h"
  49. #include "llvm/IR/Dominators.h"
  50. #include "llvm/IR/Function.h"
  51. #include "llvm/IR/InstrTypes.h"
  52. #include "llvm/IR/Instruction.h"
  53. #include "llvm/IR/Instructions.h"
  54. #include "llvm/IR/IntrinsicInst.h"
  55. #include "llvm/IR/LLVMContext.h"
  56. #include "llvm/IR/Metadata.h"
  57. #include "llvm/IR/Module.h"
  58. #include "llvm/IR/PassManager.h"
  59. #include "llvm/IR/PatternMatch.h"
  60. #include "llvm/IR/Type.h"
  61. #include "llvm/IR/Use.h"
  62. #include "llvm/IR/Value.h"
  63. #include "llvm/InitializePasses.h"
  64. #include "llvm/Pass.h"
  65. #include "llvm/Support/Casting.h"
  66. #include "llvm/Support/CommandLine.h"
  67. #include "llvm/Support/Compiler.h"
  68. #include "llvm/Support/Debug.h"
  69. #include "llvm/Support/raw_ostream.h"
  70. #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
  71. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  72. #include "llvm/Transforms/Utils/Local.h"
  73. #include "llvm/Transforms/Utils/SSAUpdater.h"
  74. #include "llvm/Transforms/Utils/VNCoercion.h"
  75. #include <algorithm>
  76. #include <cassert>
  77. #include <cstdint>
  78. #include <optional>
  79. #include <utility>
  80. using namespace llvm;
  81. using namespace llvm::gvn;
  82. using namespace llvm::VNCoercion;
  83. using namespace PatternMatch;
  84. #define DEBUG_TYPE "gvn"
  85. STATISTIC(NumGVNInstr, "Number of instructions deleted");
  86. STATISTIC(NumGVNLoad, "Number of loads deleted");
  87. STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
  88. STATISTIC(NumGVNBlocks, "Number of blocks merged");
  89. STATISTIC(NumGVNSimpl, "Number of instructions simplified");
  90. STATISTIC(NumGVNEqProp, "Number of equalities propagated");
  91. STATISTIC(NumPRELoad, "Number of loads PRE'd");
  92. STATISTIC(NumPRELoopLoad, "Number of loop loads PRE'd");
  93. STATISTIC(IsValueFullyAvailableInBlockNumSpeculationsMax,
  94. "Number of blocks speculated as available in "
  95. "IsValueFullyAvailableInBlock(), max");
  96. STATISTIC(MaxBBSpeculationCutoffReachedTimes,
  97. "Number of times we we reached gvn-max-block-speculations cut-off "
  98. "preventing further exploration");
  99. static cl::opt<bool> GVNEnablePRE("enable-pre", cl::init(true), cl::Hidden);
  100. static cl::opt<bool> GVNEnableLoadPRE("enable-load-pre", cl::init(true));
  101. static cl::opt<bool> GVNEnableLoadInLoopPRE("enable-load-in-loop-pre",
  102. cl::init(true));
  103. static cl::opt<bool>
  104. GVNEnableSplitBackedgeInLoadPRE("enable-split-backedge-in-load-pre",
  105. cl::init(false));
  106. static cl::opt<bool> GVNEnableMemDep("enable-gvn-memdep", cl::init(true));
  107. static cl::opt<uint32_t> MaxNumDeps(
  108. "gvn-max-num-deps", cl::Hidden, cl::init(100),
  109. cl::desc("Max number of dependences to attempt Load PRE (default = 100)"));
  110. // This is based on IsValueFullyAvailableInBlockNumSpeculationsMax stat.
  111. static cl::opt<uint32_t> MaxBBSpeculations(
  112. "gvn-max-block-speculations", cl::Hidden, cl::init(600),
  113. cl::desc("Max number of blocks we're willing to speculate on (and recurse "
  114. "into) when deducing if a value is fully available or not in GVN "
  115. "(default = 600)"));
  116. static cl::opt<uint32_t> MaxNumVisitedInsts(
  117. "gvn-max-num-visited-insts", cl::Hidden, cl::init(100),
  118. cl::desc("Max number of visited instructions when trying to find "
  119. "dominating value of select dependency (default = 100)"));
  120. struct llvm::GVNPass::Expression {
  121. uint32_t opcode;
  122. bool commutative = false;
  123. // The type is not necessarily the result type of the expression, it may be
  124. // any additional type needed to disambiguate the expression.
  125. Type *type = nullptr;
  126. SmallVector<uint32_t, 4> varargs;
  127. Expression(uint32_t o = ~2U) : opcode(o) {}
  128. bool operator==(const Expression &other) const {
  129. if (opcode != other.opcode)
  130. return false;
  131. if (opcode == ~0U || opcode == ~1U)
  132. return true;
  133. if (type != other.type)
  134. return false;
  135. if (varargs != other.varargs)
  136. return false;
  137. return true;
  138. }
  139. friend hash_code hash_value(const Expression &Value) {
  140. return hash_combine(
  141. Value.opcode, Value.type,
  142. hash_combine_range(Value.varargs.begin(), Value.varargs.end()));
  143. }
  144. };
  145. namespace llvm {
  146. template <> struct DenseMapInfo<GVNPass::Expression> {
  147. static inline GVNPass::Expression getEmptyKey() { return ~0U; }
  148. static inline GVNPass::Expression getTombstoneKey() { return ~1U; }
  149. static unsigned getHashValue(const GVNPass::Expression &e) {
  150. using llvm::hash_value;
  151. return static_cast<unsigned>(hash_value(e));
  152. }
  153. static bool isEqual(const GVNPass::Expression &LHS,
  154. const GVNPass::Expression &RHS) {
  155. return LHS == RHS;
  156. }
  157. };
  158. } // end namespace llvm
  159. /// Represents a particular available value that we know how to materialize.
  160. /// Materialization of an AvailableValue never fails. An AvailableValue is
  161. /// implicitly associated with a rematerialization point which is the
  162. /// location of the instruction from which it was formed.
  163. struct llvm::gvn::AvailableValue {
  164. enum class ValType {
  165. SimpleVal, // A simple offsetted value that is accessed.
  166. LoadVal, // A value produced by a load.
  167. MemIntrin, // A memory intrinsic which is loaded from.
  168. UndefVal, // A UndefValue representing a value from dead block (which
  169. // is not yet physically removed from the CFG).
  170. SelectVal, // A pointer select which is loaded from and for which the load
  171. // can be replace by a value select.
  172. };
  173. /// Val - The value that is live out of the block.
  174. Value *Val;
  175. /// Kind of the live-out value.
  176. ValType Kind;
  177. /// Offset - The byte offset in Val that is interesting for the load query.
  178. unsigned Offset = 0;
  179. /// V1, V2 - The dominating non-clobbered values of SelectVal.
  180. Value *V1 = nullptr, *V2 = nullptr;
  181. static AvailableValue get(Value *V, unsigned Offset = 0) {
  182. AvailableValue Res;
  183. Res.Val = V;
  184. Res.Kind = ValType::SimpleVal;
  185. Res.Offset = Offset;
  186. return Res;
  187. }
  188. static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset = 0) {
  189. AvailableValue Res;
  190. Res.Val = MI;
  191. Res.Kind = ValType::MemIntrin;
  192. Res.Offset = Offset;
  193. return Res;
  194. }
  195. static AvailableValue getLoad(LoadInst *Load, unsigned Offset = 0) {
  196. AvailableValue Res;
  197. Res.Val = Load;
  198. Res.Kind = ValType::LoadVal;
  199. Res.Offset = Offset;
  200. return Res;
  201. }
  202. static AvailableValue getUndef() {
  203. AvailableValue Res;
  204. Res.Val = nullptr;
  205. Res.Kind = ValType::UndefVal;
  206. Res.Offset = 0;
  207. return Res;
  208. }
  209. static AvailableValue getSelect(SelectInst *Sel, Value *V1, Value *V2) {
  210. AvailableValue Res;
  211. Res.Val = Sel;
  212. Res.Kind = ValType::SelectVal;
  213. Res.Offset = 0;
  214. Res.V1 = V1;
  215. Res.V2 = V2;
  216. return Res;
  217. }
  218. bool isSimpleValue() const { return Kind == ValType::SimpleVal; }
  219. bool isCoercedLoadValue() const { return Kind == ValType::LoadVal; }
  220. bool isMemIntrinValue() const { return Kind == ValType::MemIntrin; }
  221. bool isUndefValue() const { return Kind == ValType::UndefVal; }
  222. bool isSelectValue() const { return Kind == ValType::SelectVal; }
  223. Value *getSimpleValue() const {
  224. assert(isSimpleValue() && "Wrong accessor");
  225. return Val;
  226. }
  227. LoadInst *getCoercedLoadValue() const {
  228. assert(isCoercedLoadValue() && "Wrong accessor");
  229. return cast<LoadInst>(Val);
  230. }
  231. MemIntrinsic *getMemIntrinValue() const {
  232. assert(isMemIntrinValue() && "Wrong accessor");
  233. return cast<MemIntrinsic>(Val);
  234. }
  235. SelectInst *getSelectValue() const {
  236. assert(isSelectValue() && "Wrong accessor");
  237. return cast<SelectInst>(Val);
  238. }
  239. /// Emit code at the specified insertion point to adjust the value defined
  240. /// here to the specified type. This handles various coercion cases.
  241. Value *MaterializeAdjustedValue(LoadInst *Load, Instruction *InsertPt,
  242. GVNPass &gvn) const;
  243. };
  244. /// Represents an AvailableValue which can be rematerialized at the end of
  245. /// the associated BasicBlock.
  246. struct llvm::gvn::AvailableValueInBlock {
  247. /// BB - The basic block in question.
  248. BasicBlock *BB = nullptr;
  249. /// AV - The actual available value
  250. AvailableValue AV;
  251. static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV) {
  252. AvailableValueInBlock Res;
  253. Res.BB = BB;
  254. Res.AV = std::move(AV);
  255. return Res;
  256. }
  257. static AvailableValueInBlock get(BasicBlock *BB, Value *V,
  258. unsigned Offset = 0) {
  259. return get(BB, AvailableValue::get(V, Offset));
  260. }
  261. static AvailableValueInBlock getUndef(BasicBlock *BB) {
  262. return get(BB, AvailableValue::getUndef());
  263. }
  264. static AvailableValueInBlock getSelect(BasicBlock *BB, SelectInst *Sel,
  265. Value *V1, Value *V2) {
  266. return get(BB, AvailableValue::getSelect(Sel, V1, V2));
  267. }
  268. /// Emit code at the end of this block to adjust the value defined here to
  269. /// the specified type. This handles various coercion cases.
  270. Value *MaterializeAdjustedValue(LoadInst *Load, GVNPass &gvn) const {
  271. return AV.MaterializeAdjustedValue(Load, BB->getTerminator(), gvn);
  272. }
  273. };
  274. //===----------------------------------------------------------------------===//
  275. // ValueTable Internal Functions
  276. //===----------------------------------------------------------------------===//
  277. GVNPass::Expression GVNPass::ValueTable::createExpr(Instruction *I) {
  278. Expression e;
  279. e.type = I->getType();
  280. e.opcode = I->getOpcode();
  281. if (const GCRelocateInst *GCR = dyn_cast<GCRelocateInst>(I)) {
  282. // gc.relocate is 'special' call: its second and third operands are
  283. // not real values, but indices into statepoint's argument list.
  284. // Use the refered to values for purposes of identity.
  285. e.varargs.push_back(lookupOrAdd(GCR->getOperand(0)));
  286. e.varargs.push_back(lookupOrAdd(GCR->getBasePtr()));
  287. e.varargs.push_back(lookupOrAdd(GCR->getDerivedPtr()));
  288. } else {
  289. for (Use &Op : I->operands())
  290. e.varargs.push_back(lookupOrAdd(Op));
  291. }
  292. if (I->isCommutative()) {
  293. // Ensure that commutative instructions that only differ by a permutation
  294. // of their operands get the same value number by sorting the operand value
  295. // numbers. Since commutative operands are the 1st two operands it is more
  296. // efficient to sort by hand rather than using, say, std::sort.
  297. assert(I->getNumOperands() >= 2 && "Unsupported commutative instruction!");
  298. if (e.varargs[0] > e.varargs[1])
  299. std::swap(e.varargs[0], e.varargs[1]);
  300. e.commutative = true;
  301. }
  302. if (auto *C = dyn_cast<CmpInst>(I)) {
  303. // Sort the operand value numbers so x<y and y>x get the same value number.
  304. CmpInst::Predicate Predicate = C->getPredicate();
  305. if (e.varargs[0] > e.varargs[1]) {
  306. std::swap(e.varargs[0], e.varargs[1]);
  307. Predicate = CmpInst::getSwappedPredicate(Predicate);
  308. }
  309. e.opcode = (C->getOpcode() << 8) | Predicate;
  310. e.commutative = true;
  311. } else if (auto *E = dyn_cast<InsertValueInst>(I)) {
  312. e.varargs.append(E->idx_begin(), E->idx_end());
  313. } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) {
  314. ArrayRef<int> ShuffleMask = SVI->getShuffleMask();
  315. e.varargs.append(ShuffleMask.begin(), ShuffleMask.end());
  316. }
  317. return e;
  318. }
  319. GVNPass::Expression GVNPass::ValueTable::createCmpExpr(
  320. unsigned Opcode, CmpInst::Predicate Predicate, Value *LHS, Value *RHS) {
  321. assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
  322. "Not a comparison!");
  323. Expression e;
  324. e.type = CmpInst::makeCmpResultType(LHS->getType());
  325. e.varargs.push_back(lookupOrAdd(LHS));
  326. e.varargs.push_back(lookupOrAdd(RHS));
  327. // Sort the operand value numbers so x<y and y>x get the same value number.
  328. if (e.varargs[0] > e.varargs[1]) {
  329. std::swap(e.varargs[0], e.varargs[1]);
  330. Predicate = CmpInst::getSwappedPredicate(Predicate);
  331. }
  332. e.opcode = (Opcode << 8) | Predicate;
  333. e.commutative = true;
  334. return e;
  335. }
  336. GVNPass::Expression
  337. GVNPass::ValueTable::createExtractvalueExpr(ExtractValueInst *EI) {
  338. assert(EI && "Not an ExtractValueInst?");
  339. Expression e;
  340. e.type = EI->getType();
  341. e.opcode = 0;
  342. WithOverflowInst *WO = dyn_cast<WithOverflowInst>(EI->getAggregateOperand());
  343. if (WO != nullptr && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
  344. // EI is an extract from one of our with.overflow intrinsics. Synthesize
  345. // a semantically equivalent expression instead of an extract value
  346. // expression.
  347. e.opcode = WO->getBinaryOp();
  348. e.varargs.push_back(lookupOrAdd(WO->getLHS()));
  349. e.varargs.push_back(lookupOrAdd(WO->getRHS()));
  350. return e;
  351. }
  352. // Not a recognised intrinsic. Fall back to producing an extract value
  353. // expression.
  354. e.opcode = EI->getOpcode();
  355. for (Use &Op : EI->operands())
  356. e.varargs.push_back(lookupOrAdd(Op));
  357. append_range(e.varargs, EI->indices());
  358. return e;
  359. }
  360. GVNPass::Expression GVNPass::ValueTable::createGEPExpr(GetElementPtrInst *GEP) {
  361. Expression E;
  362. Type *PtrTy = GEP->getType()->getScalarType();
  363. const DataLayout &DL = GEP->getModule()->getDataLayout();
  364. unsigned BitWidth = DL.getIndexTypeSizeInBits(PtrTy);
  365. MapVector<Value *, APInt> VariableOffsets;
  366. APInt ConstantOffset(BitWidth, 0);
  367. if (PtrTy->isOpaquePointerTy() &&
  368. GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset)) {
  369. // For opaque pointers, convert into offset representation, to recognize
  370. // equivalent address calculations that use different type encoding.
  371. LLVMContext &Context = GEP->getContext();
  372. E.opcode = GEP->getOpcode();
  373. E.type = nullptr;
  374. E.varargs.push_back(lookupOrAdd(GEP->getPointerOperand()));
  375. for (const auto &Pair : VariableOffsets) {
  376. E.varargs.push_back(lookupOrAdd(Pair.first));
  377. E.varargs.push_back(lookupOrAdd(ConstantInt::get(Context, Pair.second)));
  378. }
  379. if (!ConstantOffset.isZero())
  380. E.varargs.push_back(
  381. lookupOrAdd(ConstantInt::get(Context, ConstantOffset)));
  382. } else {
  383. // If converting to offset representation fails (for typed pointers and
  384. // scalable vectors), fall back to type-based implementation:
  385. E.opcode = GEP->getOpcode();
  386. E.type = GEP->getSourceElementType();
  387. for (Use &Op : GEP->operands())
  388. E.varargs.push_back(lookupOrAdd(Op));
  389. }
  390. return E;
  391. }
  392. //===----------------------------------------------------------------------===//
  393. // ValueTable External Functions
  394. //===----------------------------------------------------------------------===//
  395. GVNPass::ValueTable::ValueTable() = default;
  396. GVNPass::ValueTable::ValueTable(const ValueTable &) = default;
  397. GVNPass::ValueTable::ValueTable(ValueTable &&) = default;
  398. GVNPass::ValueTable::~ValueTable() = default;
  399. GVNPass::ValueTable &
  400. GVNPass::ValueTable::operator=(const GVNPass::ValueTable &Arg) = default;
  401. /// add - Insert a value into the table with a specified value number.
  402. void GVNPass::ValueTable::add(Value *V, uint32_t num) {
  403. valueNumbering.insert(std::make_pair(V, num));
  404. if (PHINode *PN = dyn_cast<PHINode>(V))
  405. NumberingPhi[num] = PN;
  406. }
  407. uint32_t GVNPass::ValueTable::lookupOrAddCall(CallInst *C) {
  408. if (AA->doesNotAccessMemory(C) &&
  409. // FIXME: Currently the calls which may access the thread id may
  410. // be considered as not accessing the memory. But this is
  411. // problematic for coroutines, since coroutines may resume in a
  412. // different thread. So we disable the optimization here for the
  413. // correctness. However, it may block many other correct
  414. // optimizations. Revert this one when we detect the memory
  415. // accessing kind more precisely.
  416. !C->getFunction()->isPresplitCoroutine()) {
  417. Expression exp = createExpr(C);
  418. uint32_t e = assignExpNewValueNum(exp).first;
  419. valueNumbering[C] = e;
  420. return e;
  421. } else if (MD && AA->onlyReadsMemory(C) &&
  422. // FIXME: Currently the calls which may access the thread id may
  423. // be considered as not accessing the memory. But this is
  424. // problematic for coroutines, since coroutines may resume in a
  425. // different thread. So we disable the optimization here for the
  426. // correctness. However, it may block many other correct
  427. // optimizations. Revert this one when we detect the memory
  428. // accessing kind more precisely.
  429. !C->getFunction()->isPresplitCoroutine()) {
  430. Expression exp = createExpr(C);
  431. auto ValNum = assignExpNewValueNum(exp);
  432. if (ValNum.second) {
  433. valueNumbering[C] = ValNum.first;
  434. return ValNum.first;
  435. }
  436. MemDepResult local_dep = MD->getDependency(C);
  437. if (!local_dep.isDef() && !local_dep.isNonLocal()) {
  438. valueNumbering[C] = nextValueNumber;
  439. return nextValueNumber++;
  440. }
  441. if (local_dep.isDef()) {
  442. // For masked load/store intrinsics, the local_dep may actually be
  443. // a normal load or store instruction.
  444. CallInst *local_cdep = dyn_cast<CallInst>(local_dep.getInst());
  445. if (!local_cdep || local_cdep->arg_size() != C->arg_size()) {
  446. valueNumbering[C] = nextValueNumber;
  447. return nextValueNumber++;
  448. }
  449. for (unsigned i = 0, e = C->arg_size(); i < e; ++i) {
  450. uint32_t c_vn = lookupOrAdd(C->getArgOperand(i));
  451. uint32_t cd_vn = lookupOrAdd(local_cdep->getArgOperand(i));
  452. if (c_vn != cd_vn) {
  453. valueNumbering[C] = nextValueNumber;
  454. return nextValueNumber++;
  455. }
  456. }
  457. uint32_t v = lookupOrAdd(local_cdep);
  458. valueNumbering[C] = v;
  459. return v;
  460. }
  461. // Non-local case.
  462. const MemoryDependenceResults::NonLocalDepInfo &deps =
  463. MD->getNonLocalCallDependency(C);
  464. // FIXME: Move the checking logic to MemDep!
  465. CallInst* cdep = nullptr;
  466. // Check to see if we have a single dominating call instruction that is
  467. // identical to C.
  468. for (const NonLocalDepEntry &I : deps) {
  469. if (I.getResult().isNonLocal())
  470. continue;
  471. // We don't handle non-definitions. If we already have a call, reject
  472. // instruction dependencies.
  473. if (!I.getResult().isDef() || cdep != nullptr) {
  474. cdep = nullptr;
  475. break;
  476. }
  477. CallInst *NonLocalDepCall = dyn_cast<CallInst>(I.getResult().getInst());
  478. // FIXME: All duplicated with non-local case.
  479. if (NonLocalDepCall && DT->properlyDominates(I.getBB(), C->getParent())) {
  480. cdep = NonLocalDepCall;
  481. continue;
  482. }
  483. cdep = nullptr;
  484. break;
  485. }
  486. if (!cdep) {
  487. valueNumbering[C] = nextValueNumber;
  488. return nextValueNumber++;
  489. }
  490. if (cdep->arg_size() != C->arg_size()) {
  491. valueNumbering[C] = nextValueNumber;
  492. return nextValueNumber++;
  493. }
  494. for (unsigned i = 0, e = C->arg_size(); i < e; ++i) {
  495. uint32_t c_vn = lookupOrAdd(C->getArgOperand(i));
  496. uint32_t cd_vn = lookupOrAdd(cdep->getArgOperand(i));
  497. if (c_vn != cd_vn) {
  498. valueNumbering[C] = nextValueNumber;
  499. return nextValueNumber++;
  500. }
  501. }
  502. uint32_t v = lookupOrAdd(cdep);
  503. valueNumbering[C] = v;
  504. return v;
  505. } else {
  506. valueNumbering[C] = nextValueNumber;
  507. return nextValueNumber++;
  508. }
  509. }
  510. /// Returns true if a value number exists for the specified value.
  511. bool GVNPass::ValueTable::exists(Value *V) const {
  512. return valueNumbering.count(V) != 0;
  513. }
  514. /// lookup_or_add - Returns the value number for the specified value, assigning
  515. /// it a new number if it did not have one before.
  516. uint32_t GVNPass::ValueTable::lookupOrAdd(Value *V) {
  517. DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
  518. if (VI != valueNumbering.end())
  519. return VI->second;
  520. auto *I = dyn_cast<Instruction>(V);
  521. if (!I) {
  522. valueNumbering[V] = nextValueNumber;
  523. return nextValueNumber++;
  524. }
  525. Expression exp;
  526. switch (I->getOpcode()) {
  527. case Instruction::Call:
  528. return lookupOrAddCall(cast<CallInst>(I));
  529. case Instruction::FNeg:
  530. case Instruction::Add:
  531. case Instruction::FAdd:
  532. case Instruction::Sub:
  533. case Instruction::FSub:
  534. case Instruction::Mul:
  535. case Instruction::FMul:
  536. case Instruction::UDiv:
  537. case Instruction::SDiv:
  538. case Instruction::FDiv:
  539. case Instruction::URem:
  540. case Instruction::SRem:
  541. case Instruction::FRem:
  542. case Instruction::Shl:
  543. case Instruction::LShr:
  544. case Instruction::AShr:
  545. case Instruction::And:
  546. case Instruction::Or:
  547. case Instruction::Xor:
  548. case Instruction::ICmp:
  549. case Instruction::FCmp:
  550. case Instruction::Trunc:
  551. case Instruction::ZExt:
  552. case Instruction::SExt:
  553. case Instruction::FPToUI:
  554. case Instruction::FPToSI:
  555. case Instruction::UIToFP:
  556. case Instruction::SIToFP:
  557. case Instruction::FPTrunc:
  558. case Instruction::FPExt:
  559. case Instruction::PtrToInt:
  560. case Instruction::IntToPtr:
  561. case Instruction::AddrSpaceCast:
  562. case Instruction::BitCast:
  563. case Instruction::Select:
  564. case Instruction::Freeze:
  565. case Instruction::ExtractElement:
  566. case Instruction::InsertElement:
  567. case Instruction::ShuffleVector:
  568. case Instruction::InsertValue:
  569. exp = createExpr(I);
  570. break;
  571. case Instruction::GetElementPtr:
  572. exp = createGEPExpr(cast<GetElementPtrInst>(I));
  573. break;
  574. case Instruction::ExtractValue:
  575. exp = createExtractvalueExpr(cast<ExtractValueInst>(I));
  576. break;
  577. case Instruction::PHI:
  578. valueNumbering[V] = nextValueNumber;
  579. NumberingPhi[nextValueNumber] = cast<PHINode>(V);
  580. return nextValueNumber++;
  581. default:
  582. valueNumbering[V] = nextValueNumber;
  583. return nextValueNumber++;
  584. }
  585. uint32_t e = assignExpNewValueNum(exp).first;
  586. valueNumbering[V] = e;
  587. return e;
  588. }
  589. /// Returns the value number of the specified value. Fails if
  590. /// the value has not yet been numbered.
  591. uint32_t GVNPass::ValueTable::lookup(Value *V, bool Verify) const {
  592. DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
  593. if (Verify) {
  594. assert(VI != valueNumbering.end() && "Value not numbered?");
  595. return VI->second;
  596. }
  597. return (VI != valueNumbering.end()) ? VI->second : 0;
  598. }
  599. /// Returns the value number of the given comparison,
  600. /// assigning it a new number if it did not have one before. Useful when
  601. /// we deduced the result of a comparison, but don't immediately have an
  602. /// instruction realizing that comparison to hand.
  603. uint32_t GVNPass::ValueTable::lookupOrAddCmp(unsigned Opcode,
  604. CmpInst::Predicate Predicate,
  605. Value *LHS, Value *RHS) {
  606. Expression exp = createCmpExpr(Opcode, Predicate, LHS, RHS);
  607. return assignExpNewValueNum(exp).first;
  608. }
  609. /// Remove all entries from the ValueTable.
  610. void GVNPass::ValueTable::clear() {
  611. valueNumbering.clear();
  612. expressionNumbering.clear();
  613. NumberingPhi.clear();
  614. PhiTranslateTable.clear();
  615. nextValueNumber = 1;
  616. Expressions.clear();
  617. ExprIdx.clear();
  618. nextExprNumber = 0;
  619. }
  620. /// Remove a value from the value numbering.
  621. void GVNPass::ValueTable::erase(Value *V) {
  622. uint32_t Num = valueNumbering.lookup(V);
  623. valueNumbering.erase(V);
  624. // If V is PHINode, V <--> value number is an one-to-one mapping.
  625. if (isa<PHINode>(V))
  626. NumberingPhi.erase(Num);
  627. }
  628. /// verifyRemoved - Verify that the value is removed from all internal data
  629. /// structures.
  630. void GVNPass::ValueTable::verifyRemoved(const Value *V) const {
  631. for (DenseMap<Value*, uint32_t>::const_iterator
  632. I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
  633. assert(I->first != V && "Inst still occurs in value numbering map!");
  634. }
  635. }
  636. //===----------------------------------------------------------------------===//
  637. // GVN Pass
  638. //===----------------------------------------------------------------------===//
  639. bool GVNPass::isPREEnabled() const {
  640. return Options.AllowPRE.value_or(GVNEnablePRE);
  641. }
  642. bool GVNPass::isLoadPREEnabled() const {
  643. return Options.AllowLoadPRE.value_or(GVNEnableLoadPRE);
  644. }
  645. bool GVNPass::isLoadInLoopPREEnabled() const {
  646. return Options.AllowLoadInLoopPRE.value_or(GVNEnableLoadInLoopPRE);
  647. }
  648. bool GVNPass::isLoadPRESplitBackedgeEnabled() const {
  649. return Options.AllowLoadPRESplitBackedge.value_or(
  650. GVNEnableSplitBackedgeInLoadPRE);
  651. }
  652. bool GVNPass::isMemDepEnabled() const {
  653. return Options.AllowMemDep.value_or(GVNEnableMemDep);
  654. }
  655. PreservedAnalyses GVNPass::run(Function &F, FunctionAnalysisManager &AM) {
  656. // FIXME: The order of evaluation of these 'getResult' calls is very
  657. // significant! Re-ordering these variables will cause GVN when run alone to
  658. // be less effective! We should fix memdep and basic-aa to not exhibit this
  659. // behavior, but until then don't change the order here.
  660. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  661. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  662. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  663. auto &AA = AM.getResult<AAManager>(F);
  664. auto *MemDep =
  665. isMemDepEnabled() ? &AM.getResult<MemoryDependenceAnalysis>(F) : nullptr;
  666. auto *LI = AM.getCachedResult<LoopAnalysis>(F);
  667. auto *MSSA = AM.getCachedResult<MemorySSAAnalysis>(F);
  668. auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  669. bool Changed = runImpl(F, AC, DT, TLI, AA, MemDep, LI, &ORE,
  670. MSSA ? &MSSA->getMSSA() : nullptr);
  671. if (!Changed)
  672. return PreservedAnalyses::all();
  673. PreservedAnalyses PA;
  674. PA.preserve<DominatorTreeAnalysis>();
  675. PA.preserve<TargetLibraryAnalysis>();
  676. if (MSSA)
  677. PA.preserve<MemorySSAAnalysis>();
  678. if (LI)
  679. PA.preserve<LoopAnalysis>();
  680. return PA;
  681. }
  682. void GVNPass::printPipeline(
  683. raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
  684. static_cast<PassInfoMixin<GVNPass> *>(this)->printPipeline(
  685. OS, MapClassName2PassName);
  686. OS << "<";
  687. if (Options.AllowPRE != std::nullopt)
  688. OS << (*Options.AllowPRE ? "" : "no-") << "pre;";
  689. if (Options.AllowLoadPRE != std::nullopt)
  690. OS << (*Options.AllowLoadPRE ? "" : "no-") << "load-pre;";
  691. if (Options.AllowLoadPRESplitBackedge != std::nullopt)
  692. OS << (*Options.AllowLoadPRESplitBackedge ? "" : "no-")
  693. << "split-backedge-load-pre;";
  694. if (Options.AllowMemDep != std::nullopt)
  695. OS << (*Options.AllowMemDep ? "" : "no-") << "memdep";
  696. OS << ">";
  697. }
  698. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  699. LLVM_DUMP_METHOD void GVNPass::dump(DenseMap<uint32_t, Value *> &d) const {
  700. errs() << "{\n";
  701. for (auto &I : d) {
  702. errs() << I.first << "\n";
  703. I.second->dump();
  704. }
  705. errs() << "}\n";
  706. }
  707. #endif
  708. enum class AvailabilityState : char {
  709. /// We know the block *is not* fully available. This is a fixpoint.
  710. Unavailable = 0,
  711. /// We know the block *is* fully available. This is a fixpoint.
  712. Available = 1,
  713. /// We do not know whether the block is fully available or not,
  714. /// but we are currently speculating that it will be.
  715. /// If it would have turned out that the block was, in fact, not fully
  716. /// available, this would have been cleaned up into an Unavailable.
  717. SpeculativelyAvailable = 2,
  718. };
  719. /// Return true if we can prove that the value
  720. /// we're analyzing is fully available in the specified block. As we go, keep
  721. /// track of which blocks we know are fully alive in FullyAvailableBlocks. This
  722. /// map is actually a tri-state map with the following values:
  723. /// 0) we know the block *is not* fully available.
  724. /// 1) we know the block *is* fully available.
  725. /// 2) we do not know whether the block is fully available or not, but we are
  726. /// currently speculating that it will be.
  727. static bool IsValueFullyAvailableInBlock(
  728. BasicBlock *BB,
  729. DenseMap<BasicBlock *, AvailabilityState> &FullyAvailableBlocks) {
  730. SmallVector<BasicBlock *, 32> Worklist;
  731. std::optional<BasicBlock *> UnavailableBB;
  732. // The number of times we didn't find an entry for a block in a map and
  733. // optimistically inserted an entry marking block as speculatively available.
  734. unsigned NumNewNewSpeculativelyAvailableBBs = 0;
  735. #ifndef NDEBUG
  736. SmallSet<BasicBlock *, 32> NewSpeculativelyAvailableBBs;
  737. SmallVector<BasicBlock *, 32> AvailableBBs;
  738. #endif
  739. Worklist.emplace_back(BB);
  740. while (!Worklist.empty()) {
  741. BasicBlock *CurrBB = Worklist.pop_back_val(); // LoadFO - depth-first!
  742. // Optimistically assume that the block is Speculatively Available and check
  743. // to see if we already know about this block in one lookup.
  744. std::pair<DenseMap<BasicBlock *, AvailabilityState>::iterator, bool> IV =
  745. FullyAvailableBlocks.try_emplace(
  746. CurrBB, AvailabilityState::SpeculativelyAvailable);
  747. AvailabilityState &State = IV.first->second;
  748. // Did the entry already exist for this block?
  749. if (!IV.second) {
  750. if (State == AvailabilityState::Unavailable) {
  751. UnavailableBB = CurrBB;
  752. break; // Backpropagate unavailability info.
  753. }
  754. #ifndef NDEBUG
  755. AvailableBBs.emplace_back(CurrBB);
  756. #endif
  757. continue; // Don't recurse further, but continue processing worklist.
  758. }
  759. // No entry found for block.
  760. ++NumNewNewSpeculativelyAvailableBBs;
  761. bool OutOfBudget = NumNewNewSpeculativelyAvailableBBs > MaxBBSpeculations;
  762. // If we have exhausted our budget, mark this block as unavailable.
  763. // Also, if this block has no predecessors, the value isn't live-in here.
  764. if (OutOfBudget || pred_empty(CurrBB)) {
  765. MaxBBSpeculationCutoffReachedTimes += (int)OutOfBudget;
  766. State = AvailabilityState::Unavailable;
  767. UnavailableBB = CurrBB;
  768. break; // Backpropagate unavailability info.
  769. }
  770. // Tentatively consider this block as speculatively available.
  771. #ifndef NDEBUG
  772. NewSpeculativelyAvailableBBs.insert(CurrBB);
  773. #endif
  774. // And further recurse into block's predecessors, in depth-first order!
  775. Worklist.append(pred_begin(CurrBB), pred_end(CurrBB));
  776. }
  777. #if LLVM_ENABLE_STATS
  778. IsValueFullyAvailableInBlockNumSpeculationsMax.updateMax(
  779. NumNewNewSpeculativelyAvailableBBs);
  780. #endif
  781. // If the block isn't marked as fixpoint yet
  782. // (the Unavailable and Available states are fixpoints)
  783. auto MarkAsFixpointAndEnqueueSuccessors =
  784. [&](BasicBlock *BB, AvailabilityState FixpointState) {
  785. auto It = FullyAvailableBlocks.find(BB);
  786. if (It == FullyAvailableBlocks.end())
  787. return; // Never queried this block, leave as-is.
  788. switch (AvailabilityState &State = It->second) {
  789. case AvailabilityState::Unavailable:
  790. case AvailabilityState::Available:
  791. return; // Don't backpropagate further, continue processing worklist.
  792. case AvailabilityState::SpeculativelyAvailable: // Fix it!
  793. State = FixpointState;
  794. #ifndef NDEBUG
  795. assert(NewSpeculativelyAvailableBBs.erase(BB) &&
  796. "Found a speculatively available successor leftover?");
  797. #endif
  798. // Queue successors for further processing.
  799. Worklist.append(succ_begin(BB), succ_end(BB));
  800. return;
  801. }
  802. };
  803. if (UnavailableBB) {
  804. // Okay, we have encountered an unavailable block.
  805. // Mark speculatively available blocks reachable from UnavailableBB as
  806. // unavailable as well. Paths are terminated when they reach blocks not in
  807. // FullyAvailableBlocks or they are not marked as speculatively available.
  808. Worklist.clear();
  809. Worklist.append(succ_begin(*UnavailableBB), succ_end(*UnavailableBB));
  810. while (!Worklist.empty())
  811. MarkAsFixpointAndEnqueueSuccessors(Worklist.pop_back_val(),
  812. AvailabilityState::Unavailable);
  813. }
  814. #ifndef NDEBUG
  815. Worklist.clear();
  816. for (BasicBlock *AvailableBB : AvailableBBs)
  817. Worklist.append(succ_begin(AvailableBB), succ_end(AvailableBB));
  818. while (!Worklist.empty())
  819. MarkAsFixpointAndEnqueueSuccessors(Worklist.pop_back_val(),
  820. AvailabilityState::Available);
  821. assert(NewSpeculativelyAvailableBBs.empty() &&
  822. "Must have fixed all the new speculatively available blocks.");
  823. #endif
  824. return !UnavailableBB;
  825. }
  826. /// Given a set of loads specified by ValuesPerBlock,
  827. /// construct SSA form, allowing us to eliminate Load. This returns the value
  828. /// that should be used at Load's definition site.
  829. static Value *
  830. ConstructSSAForLoadSet(LoadInst *Load,
  831. SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
  832. GVNPass &gvn) {
  833. // Check for the fully redundant, dominating load case. In this case, we can
  834. // just use the dominating value directly.
  835. if (ValuesPerBlock.size() == 1 &&
  836. gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
  837. Load->getParent())) {
  838. assert(!ValuesPerBlock[0].AV.isUndefValue() &&
  839. "Dead BB dominate this block");
  840. return ValuesPerBlock[0].MaterializeAdjustedValue(Load, gvn);
  841. }
  842. // Otherwise, we have to construct SSA form.
  843. SmallVector<PHINode*, 8> NewPHIs;
  844. SSAUpdater SSAUpdate(&NewPHIs);
  845. SSAUpdate.Initialize(Load->getType(), Load->getName());
  846. for (const AvailableValueInBlock &AV : ValuesPerBlock) {
  847. BasicBlock *BB = AV.BB;
  848. if (AV.AV.isUndefValue())
  849. continue;
  850. if (SSAUpdate.HasValueForBlock(BB))
  851. continue;
  852. // If the value is the load that we will be eliminating, and the block it's
  853. // available in is the block that the load is in, then don't add it as
  854. // SSAUpdater will resolve the value to the relevant phi which may let it
  855. // avoid phi construction entirely if there's actually only one value.
  856. if (BB == Load->getParent() &&
  857. ((AV.AV.isSimpleValue() && AV.AV.getSimpleValue() == Load) ||
  858. (AV.AV.isCoercedLoadValue() && AV.AV.getCoercedLoadValue() == Load)))
  859. continue;
  860. SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(Load, gvn));
  861. }
  862. // Perform PHI construction.
  863. return SSAUpdate.GetValueInMiddleOfBlock(Load->getParent());
  864. }
  865. Value *AvailableValue::MaterializeAdjustedValue(LoadInst *Load,
  866. Instruction *InsertPt,
  867. GVNPass &gvn) const {
  868. Value *Res;
  869. Type *LoadTy = Load->getType();
  870. const DataLayout &DL = Load->getModule()->getDataLayout();
  871. if (isSimpleValue()) {
  872. Res = getSimpleValue();
  873. if (Res->getType() != LoadTy) {
  874. Res = getStoreValueForLoad(Res, Offset, LoadTy, InsertPt, DL);
  875. LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset
  876. << " " << *getSimpleValue() << '\n'
  877. << *Res << '\n'
  878. << "\n\n\n");
  879. }
  880. } else if (isCoercedLoadValue()) {
  881. LoadInst *CoercedLoad = getCoercedLoadValue();
  882. if (CoercedLoad->getType() == LoadTy && Offset == 0) {
  883. Res = CoercedLoad;
  884. } else {
  885. Res = getLoadValueForLoad(CoercedLoad, Offset, LoadTy, InsertPt, DL);
  886. // We would like to use gvn.markInstructionForDeletion here, but we can't
  887. // because the load is already memoized into the leader map table that GVN
  888. // tracks. It is potentially possible to remove the load from the table,
  889. // but then there all of the operations based on it would need to be
  890. // rehashed. Just leave the dead load around.
  891. gvn.getMemDep().removeInstruction(CoercedLoad);
  892. LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset
  893. << " " << *getCoercedLoadValue() << '\n'
  894. << *Res << '\n'
  895. << "\n\n\n");
  896. }
  897. } else if (isMemIntrinValue()) {
  898. Res = getMemInstValueForLoad(getMemIntrinValue(), Offset, LoadTy,
  899. InsertPt, DL);
  900. LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
  901. << " " << *getMemIntrinValue() << '\n'
  902. << *Res << '\n'
  903. << "\n\n\n");
  904. } else if (isSelectValue()) {
  905. // Introduce a new value select for a load from an eligible pointer select.
  906. SelectInst *Sel = getSelectValue();
  907. assert(V1 && V2 && "both value operands of the select must be present");
  908. Res = SelectInst::Create(Sel->getCondition(), V1, V2, "", Sel);
  909. } else {
  910. llvm_unreachable("Should not materialize value from dead block");
  911. }
  912. assert(Res && "failed to materialize?");
  913. return Res;
  914. }
  915. static bool isLifetimeStart(const Instruction *Inst) {
  916. if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
  917. return II->getIntrinsicID() == Intrinsic::lifetime_start;
  918. return false;
  919. }
  920. /// Assuming To can be reached from both From and Between, does Between lie on
  921. /// every path from From to To?
  922. static bool liesBetween(const Instruction *From, Instruction *Between,
  923. const Instruction *To, DominatorTree *DT) {
  924. if (From->getParent() == Between->getParent())
  925. return DT->dominates(From, Between);
  926. SmallSet<BasicBlock *, 1> Exclusion;
  927. Exclusion.insert(Between->getParent());
  928. return !isPotentiallyReachable(From, To, &Exclusion, DT);
  929. }
  930. /// Try to locate the three instruction involved in a missed
  931. /// load-elimination case that is due to an intervening store.
  932. static void reportMayClobberedLoad(LoadInst *Load, MemDepResult DepInfo,
  933. DominatorTree *DT,
  934. OptimizationRemarkEmitter *ORE) {
  935. using namespace ore;
  936. Instruction *OtherAccess = nullptr;
  937. OptimizationRemarkMissed R(DEBUG_TYPE, "LoadClobbered", Load);
  938. R << "load of type " << NV("Type", Load->getType()) << " not eliminated"
  939. << setExtraArgs();
  940. for (auto *U : Load->getPointerOperand()->users()) {
  941. if (U != Load && (isa<LoadInst>(U) || isa<StoreInst>(U))) {
  942. auto *I = cast<Instruction>(U);
  943. if (I->getFunction() == Load->getFunction() && DT->dominates(I, Load)) {
  944. // Use the most immediately dominating value
  945. if (OtherAccess) {
  946. if (DT->dominates(OtherAccess, I))
  947. OtherAccess = I;
  948. else
  949. assert(U == OtherAccess || DT->dominates(I, OtherAccess));
  950. } else
  951. OtherAccess = I;
  952. }
  953. }
  954. }
  955. if (!OtherAccess) {
  956. // There is no dominating use, check if we can find a closest non-dominating
  957. // use that lies between any other potentially available use and Load.
  958. for (auto *U : Load->getPointerOperand()->users()) {
  959. if (U != Load && (isa<LoadInst>(U) || isa<StoreInst>(U))) {
  960. auto *I = cast<Instruction>(U);
  961. if (I->getFunction() == Load->getFunction() &&
  962. isPotentiallyReachable(I, Load, nullptr, DT)) {
  963. if (OtherAccess) {
  964. if (liesBetween(OtherAccess, I, Load, DT)) {
  965. OtherAccess = I;
  966. } else if (!liesBetween(I, OtherAccess, Load, DT)) {
  967. // These uses are both partially available at Load were it not for
  968. // the clobber, but neither lies strictly after the other.
  969. OtherAccess = nullptr;
  970. break;
  971. } // else: keep current OtherAccess since it lies between U and Load
  972. } else {
  973. OtherAccess = I;
  974. }
  975. }
  976. }
  977. }
  978. }
  979. if (OtherAccess)
  980. R << " in favor of " << NV("OtherAccess", OtherAccess);
  981. R << " because it is clobbered by " << NV("ClobberedBy", DepInfo.getInst());
  982. ORE->emit(R);
  983. }
  984. // Find non-clobbered value for Loc memory location in extended basic block
  985. // (chain of basic blocks with single predecessors) starting From instruction.
  986. static Value *findDominatingValue(const MemoryLocation &Loc, Type *LoadTy,
  987. Instruction *From, AAResults *AA) {
  988. uint32_t NumVisitedInsts = 0;
  989. BasicBlock *FromBB = From->getParent();
  990. BatchAAResults BatchAA(*AA);
  991. for (BasicBlock *BB = FromBB; BB; BB = BB->getSinglePredecessor())
  992. for (auto I = BB == FromBB ? From->getReverseIterator() : BB->rbegin(),
  993. E = BB->rend();
  994. I != E; ++I) {
  995. // Stop the search if limit is reached.
  996. if (++NumVisitedInsts > MaxNumVisitedInsts)
  997. return nullptr;
  998. Instruction *Inst = &*I;
  999. if (isModSet(BatchAA.getModRefInfo(Inst, Loc)))
  1000. return nullptr;
  1001. if (auto *LI = dyn_cast<LoadInst>(Inst))
  1002. if (LI->getPointerOperand() == Loc.Ptr && LI->getType() == LoadTy)
  1003. return LI;
  1004. }
  1005. return nullptr;
  1006. }
  1007. std::optional<AvailableValue>
  1008. GVNPass::AnalyzeLoadAvailability(LoadInst *Load, MemDepResult DepInfo,
  1009. Value *Address) {
  1010. assert(Load->isUnordered() && "rules below are incorrect for ordered access");
  1011. assert(DepInfo.isLocal() && "expected a local dependence");
  1012. Instruction *DepInst = DepInfo.getInst();
  1013. const DataLayout &DL = Load->getModule()->getDataLayout();
  1014. if (DepInfo.isClobber()) {
  1015. // If the dependence is to a store that writes to a superset of the bits
  1016. // read by the load, we can extract the bits we need for the load from the
  1017. // stored value.
  1018. if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
  1019. // Can't forward from non-atomic to atomic without violating memory model.
  1020. if (Address && Load->isAtomic() <= DepSI->isAtomic()) {
  1021. int Offset =
  1022. analyzeLoadFromClobberingStore(Load->getType(), Address, DepSI, DL);
  1023. if (Offset != -1)
  1024. return AvailableValue::get(DepSI->getValueOperand(), Offset);
  1025. }
  1026. }
  1027. // Check to see if we have something like this:
  1028. // load i32* P
  1029. // load i8* (P+1)
  1030. // if we have this, replace the later with an extraction from the former.
  1031. if (LoadInst *DepLoad = dyn_cast<LoadInst>(DepInst)) {
  1032. // If this is a clobber and L is the first instruction in its block, then
  1033. // we have the first instruction in the entry block.
  1034. // Can't forward from non-atomic to atomic without violating memory model.
  1035. if (DepLoad != Load && Address &&
  1036. Load->isAtomic() <= DepLoad->isAtomic()) {
  1037. Type *LoadType = Load->getType();
  1038. int Offset = -1;
  1039. // If MD reported clobber, check it was nested.
  1040. if (DepInfo.isClobber() &&
  1041. canCoerceMustAliasedValueToLoad(DepLoad, LoadType, DL)) {
  1042. const auto ClobberOff = MD->getClobberOffset(DepLoad);
  1043. // GVN has no deal with a negative offset.
  1044. Offset = (ClobberOff == std::nullopt || *ClobberOff < 0)
  1045. ? -1
  1046. : *ClobberOff;
  1047. }
  1048. if (Offset == -1)
  1049. Offset =
  1050. analyzeLoadFromClobberingLoad(LoadType, Address, DepLoad, DL);
  1051. if (Offset != -1)
  1052. return AvailableValue::getLoad(DepLoad, Offset);
  1053. }
  1054. }
  1055. // If the clobbering value is a memset/memcpy/memmove, see if we can
  1056. // forward a value on from it.
  1057. if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
  1058. if (Address && !Load->isAtomic()) {
  1059. int Offset = analyzeLoadFromClobberingMemInst(Load->getType(), Address,
  1060. DepMI, DL);
  1061. if (Offset != -1)
  1062. return AvailableValue::getMI(DepMI, Offset);
  1063. }
  1064. }
  1065. // Nothing known about this clobber, have to be conservative
  1066. LLVM_DEBUG(
  1067. // fast print dep, using operator<< on instruction is too slow.
  1068. dbgs() << "GVN: load "; Load->printAsOperand(dbgs());
  1069. dbgs() << " is clobbered by " << *DepInst << '\n';);
  1070. if (ORE->allowExtraAnalysis(DEBUG_TYPE))
  1071. reportMayClobberedLoad(Load, DepInfo, DT, ORE);
  1072. return std::nullopt;
  1073. }
  1074. assert(DepInfo.isDef() && "follows from above");
  1075. // Loading the alloca -> undef.
  1076. // Loading immediately after lifetime begin -> undef.
  1077. if (isa<AllocaInst>(DepInst) || isLifetimeStart(DepInst))
  1078. return AvailableValue::get(UndefValue::get(Load->getType()));
  1079. if (Constant *InitVal =
  1080. getInitialValueOfAllocation(DepInst, TLI, Load->getType()))
  1081. return AvailableValue::get(InitVal);
  1082. if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
  1083. // Reject loads and stores that are to the same address but are of
  1084. // different types if we have to. If the stored value is convertable to
  1085. // the loaded value, we can reuse it.
  1086. if (!canCoerceMustAliasedValueToLoad(S->getValueOperand(), Load->getType(),
  1087. DL))
  1088. return std::nullopt;
  1089. // Can't forward from non-atomic to atomic without violating memory model.
  1090. if (S->isAtomic() < Load->isAtomic())
  1091. return std::nullopt;
  1092. return AvailableValue::get(S->getValueOperand());
  1093. }
  1094. if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
  1095. // If the types mismatch and we can't handle it, reject reuse of the load.
  1096. // If the stored value is larger or equal to the loaded value, we can reuse
  1097. // it.
  1098. if (!canCoerceMustAliasedValueToLoad(LD, Load->getType(), DL))
  1099. return std::nullopt;
  1100. // Can't forward from non-atomic to atomic without violating memory model.
  1101. if (LD->isAtomic() < Load->isAtomic())
  1102. return std::nullopt;
  1103. return AvailableValue::getLoad(LD);
  1104. }
  1105. // Check if load with Addr dependent from select can be converted to select
  1106. // between load values. There must be no instructions between the found
  1107. // loads and DepInst that may clobber the loads.
  1108. if (auto *Sel = dyn_cast<SelectInst>(DepInst)) {
  1109. assert(Sel->getType() == Load->getPointerOperandType());
  1110. auto Loc = MemoryLocation::get(Load);
  1111. Value *V1 =
  1112. findDominatingValue(Loc.getWithNewPtr(Sel->getTrueValue()),
  1113. Load->getType(), DepInst, getAliasAnalysis());
  1114. if (!V1)
  1115. return std::nullopt;
  1116. Value *V2 =
  1117. findDominatingValue(Loc.getWithNewPtr(Sel->getFalseValue()),
  1118. Load->getType(), DepInst, getAliasAnalysis());
  1119. if (!V2)
  1120. return std::nullopt;
  1121. return AvailableValue::getSelect(Sel, V1, V2);
  1122. }
  1123. // Unknown def - must be conservative
  1124. LLVM_DEBUG(
  1125. // fast print dep, using operator<< on instruction is too slow.
  1126. dbgs() << "GVN: load "; Load->printAsOperand(dbgs());
  1127. dbgs() << " has unknown def " << *DepInst << '\n';);
  1128. return std::nullopt;
  1129. }
  1130. void GVNPass::AnalyzeLoadAvailability(LoadInst *Load, LoadDepVect &Deps,
  1131. AvailValInBlkVect &ValuesPerBlock,
  1132. UnavailBlkVect &UnavailableBlocks) {
  1133. // Filter out useless results (non-locals, etc). Keep track of the blocks
  1134. // where we have a value available in repl, also keep track of whether we see
  1135. // dependencies that produce an unknown value for the load (such as a call
  1136. // that could potentially clobber the load).
  1137. for (const auto &Dep : Deps) {
  1138. BasicBlock *DepBB = Dep.getBB();
  1139. MemDepResult DepInfo = Dep.getResult();
  1140. if (DeadBlocks.count(DepBB)) {
  1141. // Dead dependent mem-op disguise as a load evaluating the same value
  1142. // as the load in question.
  1143. ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
  1144. continue;
  1145. }
  1146. if (!DepInfo.isLocal()) {
  1147. UnavailableBlocks.push_back(DepBB);
  1148. continue;
  1149. }
  1150. // The address being loaded in this non-local block may not be the same as
  1151. // the pointer operand of the load if PHI translation occurs. Make sure
  1152. // to consider the right address.
  1153. if (auto AV = AnalyzeLoadAvailability(Load, DepInfo, Dep.getAddress())) {
  1154. // subtlety: because we know this was a non-local dependency, we know
  1155. // it's safe to materialize anywhere between the instruction within
  1156. // DepInfo and the end of it's block.
  1157. ValuesPerBlock.push_back(
  1158. AvailableValueInBlock::get(DepBB, std::move(*AV)));
  1159. } else {
  1160. UnavailableBlocks.push_back(DepBB);
  1161. }
  1162. }
  1163. assert(Deps.size() == ValuesPerBlock.size() + UnavailableBlocks.size() &&
  1164. "post condition violation");
  1165. }
  1166. void GVNPass::eliminatePartiallyRedundantLoad(
  1167. LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
  1168. MapVector<BasicBlock *, Value *> &AvailableLoads) {
  1169. for (const auto &AvailableLoad : AvailableLoads) {
  1170. BasicBlock *UnavailableBlock = AvailableLoad.first;
  1171. Value *LoadPtr = AvailableLoad.second;
  1172. auto *NewLoad =
  1173. new LoadInst(Load->getType(), LoadPtr, Load->getName() + ".pre",
  1174. Load->isVolatile(), Load->getAlign(), Load->getOrdering(),
  1175. Load->getSyncScopeID(), UnavailableBlock->getTerminator());
  1176. NewLoad->setDebugLoc(Load->getDebugLoc());
  1177. if (MSSAU) {
  1178. auto *MSSA = MSSAU->getMemorySSA();
  1179. // Get the defining access of the original load or use the load if it is a
  1180. // MemoryDef (e.g. because it is volatile). The inserted loads are
  1181. // guaranteed to load from the same definition.
  1182. auto *LoadAcc = MSSA->getMemoryAccess(Load);
  1183. auto *DefiningAcc =
  1184. isa<MemoryDef>(LoadAcc) ? LoadAcc : LoadAcc->getDefiningAccess();
  1185. auto *NewAccess = MSSAU->createMemoryAccessInBB(
  1186. NewLoad, DefiningAcc, NewLoad->getParent(),
  1187. MemorySSA::BeforeTerminator);
  1188. if (auto *NewDef = dyn_cast<MemoryDef>(NewAccess))
  1189. MSSAU->insertDef(NewDef, /*RenameUses=*/true);
  1190. else
  1191. MSSAU->insertUse(cast<MemoryUse>(NewAccess), /*RenameUses=*/true);
  1192. }
  1193. // Transfer the old load's AA tags to the new load.
  1194. AAMDNodes Tags = Load->getAAMetadata();
  1195. if (Tags)
  1196. NewLoad->setAAMetadata(Tags);
  1197. if (auto *MD = Load->getMetadata(LLVMContext::MD_invariant_load))
  1198. NewLoad->setMetadata(LLVMContext::MD_invariant_load, MD);
  1199. if (auto *InvGroupMD = Load->getMetadata(LLVMContext::MD_invariant_group))
  1200. NewLoad->setMetadata(LLVMContext::MD_invariant_group, InvGroupMD);
  1201. if (auto *RangeMD = Load->getMetadata(LLVMContext::MD_range))
  1202. NewLoad->setMetadata(LLVMContext::MD_range, RangeMD);
  1203. if (auto *AccessMD = Load->getMetadata(LLVMContext::MD_access_group))
  1204. if (LI &&
  1205. LI->getLoopFor(Load->getParent()) == LI->getLoopFor(UnavailableBlock))
  1206. NewLoad->setMetadata(LLVMContext::MD_access_group, AccessMD);
  1207. // We do not propagate the old load's debug location, because the new
  1208. // load now lives in a different BB, and we want to avoid a jumpy line
  1209. // table.
  1210. // FIXME: How do we retain source locations without causing poor debugging
  1211. // behavior?
  1212. // Add the newly created load.
  1213. ValuesPerBlock.push_back(
  1214. AvailableValueInBlock::get(UnavailableBlock, NewLoad));
  1215. MD->invalidateCachedPointerInfo(LoadPtr);
  1216. LLVM_DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
  1217. }
  1218. // Perform PHI construction.
  1219. Value *V = ConstructSSAForLoadSet(Load, ValuesPerBlock, *this);
  1220. Load->replaceAllUsesWith(V);
  1221. if (isa<PHINode>(V))
  1222. V->takeName(Load);
  1223. if (Instruction *I = dyn_cast<Instruction>(V))
  1224. I->setDebugLoc(Load->getDebugLoc());
  1225. if (V->getType()->isPtrOrPtrVectorTy())
  1226. MD->invalidateCachedPointerInfo(V);
  1227. markInstructionForDeletion(Load);
  1228. ORE->emit([&]() {
  1229. return OptimizationRemark(DEBUG_TYPE, "LoadPRE", Load)
  1230. << "load eliminated by PRE";
  1231. });
  1232. }
  1233. bool GVNPass::PerformLoadPRE(LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
  1234. UnavailBlkVect &UnavailableBlocks) {
  1235. // Okay, we have *some* definitions of the value. This means that the value
  1236. // is available in some of our (transitive) predecessors. Lets think about
  1237. // doing PRE of this load. This will involve inserting a new load into the
  1238. // predecessor when it's not available. We could do this in general, but
  1239. // prefer to not increase code size. As such, we only do this when we know
  1240. // that we only have to insert *one* load (which means we're basically moving
  1241. // the load, not inserting a new one).
  1242. SmallPtrSet<BasicBlock *, 4> Blockers(UnavailableBlocks.begin(),
  1243. UnavailableBlocks.end());
  1244. // Let's find the first basic block with more than one predecessor. Walk
  1245. // backwards through predecessors if needed.
  1246. BasicBlock *LoadBB = Load->getParent();
  1247. BasicBlock *TmpBB = LoadBB;
  1248. // Check that there is no implicit control flow instructions above our load in
  1249. // its block. If there is an instruction that doesn't always pass the
  1250. // execution to the following instruction, then moving through it may become
  1251. // invalid. For example:
  1252. //
  1253. // int arr[LEN];
  1254. // int index = ???;
  1255. // ...
  1256. // guard(0 <= index && index < LEN);
  1257. // use(arr[index]);
  1258. //
  1259. // It is illegal to move the array access to any point above the guard,
  1260. // because if the index is out of bounds we should deoptimize rather than
  1261. // access the array.
  1262. // Check that there is no guard in this block above our instruction.
  1263. bool MustEnsureSafetyOfSpeculativeExecution =
  1264. ICF->isDominatedByICFIFromSameBlock(Load);
  1265. while (TmpBB->getSinglePredecessor()) {
  1266. TmpBB = TmpBB->getSinglePredecessor();
  1267. if (TmpBB == LoadBB) // Infinite (unreachable) loop.
  1268. return false;
  1269. if (Blockers.count(TmpBB))
  1270. return false;
  1271. // If any of these blocks has more than one successor (i.e. if the edge we
  1272. // just traversed was critical), then there are other paths through this
  1273. // block along which the load may not be anticipated. Hoisting the load
  1274. // above this block would be adding the load to execution paths along
  1275. // which it was not previously executed.
  1276. if (TmpBB->getTerminator()->getNumSuccessors() != 1)
  1277. return false;
  1278. // Check that there is no implicit control flow in a block above.
  1279. MustEnsureSafetyOfSpeculativeExecution =
  1280. MustEnsureSafetyOfSpeculativeExecution || ICF->hasICF(TmpBB);
  1281. }
  1282. assert(TmpBB);
  1283. LoadBB = TmpBB;
  1284. // Check to see how many predecessors have the loaded value fully
  1285. // available.
  1286. MapVector<BasicBlock *, Value *> PredLoads;
  1287. DenseMap<BasicBlock *, AvailabilityState> FullyAvailableBlocks;
  1288. for (const AvailableValueInBlock &AV : ValuesPerBlock)
  1289. FullyAvailableBlocks[AV.BB] = AvailabilityState::Available;
  1290. for (BasicBlock *UnavailableBB : UnavailableBlocks)
  1291. FullyAvailableBlocks[UnavailableBB] = AvailabilityState::Unavailable;
  1292. SmallVector<BasicBlock *, 4> CriticalEdgePred;
  1293. for (BasicBlock *Pred : predecessors(LoadBB)) {
  1294. // If any predecessor block is an EH pad that does not allow non-PHI
  1295. // instructions before the terminator, we can't PRE the load.
  1296. if (Pred->getTerminator()->isEHPad()) {
  1297. LLVM_DEBUG(
  1298. dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '"
  1299. << Pred->getName() << "': " << *Load << '\n');
  1300. return false;
  1301. }
  1302. if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks)) {
  1303. continue;
  1304. }
  1305. if (Pred->getTerminator()->getNumSuccessors() != 1) {
  1306. if (isa<IndirectBrInst>(Pred->getTerminator())) {
  1307. LLVM_DEBUG(
  1308. dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
  1309. << Pred->getName() << "': " << *Load << '\n');
  1310. return false;
  1311. }
  1312. if (LoadBB->isEHPad()) {
  1313. LLVM_DEBUG(
  1314. dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '"
  1315. << Pred->getName() << "': " << *Load << '\n');
  1316. return false;
  1317. }
  1318. // Do not split backedge as it will break the canonical loop form.
  1319. if (!isLoadPRESplitBackedgeEnabled())
  1320. if (DT->dominates(LoadBB, Pred)) {
  1321. LLVM_DEBUG(
  1322. dbgs()
  1323. << "COULD NOT PRE LOAD BECAUSE OF A BACKEDGE CRITICAL EDGE '"
  1324. << Pred->getName() << "': " << *Load << '\n');
  1325. return false;
  1326. }
  1327. CriticalEdgePred.push_back(Pred);
  1328. } else {
  1329. // Only add the predecessors that will not be split for now.
  1330. PredLoads[Pred] = nullptr;
  1331. }
  1332. }
  1333. // Decide whether PRE is profitable for this load.
  1334. unsigned NumUnavailablePreds = PredLoads.size() + CriticalEdgePred.size();
  1335. assert(NumUnavailablePreds != 0 &&
  1336. "Fully available value should already be eliminated!");
  1337. // If this load is unavailable in multiple predecessors, reject it.
  1338. // FIXME: If we could restructure the CFG, we could make a common pred with
  1339. // all the preds that don't have an available Load and insert a new load into
  1340. // that one block.
  1341. if (NumUnavailablePreds != 1)
  1342. return false;
  1343. // Now we know where we will insert load. We must ensure that it is safe
  1344. // to speculatively execute the load at that points.
  1345. if (MustEnsureSafetyOfSpeculativeExecution) {
  1346. if (CriticalEdgePred.size())
  1347. if (!isSafeToSpeculativelyExecute(Load, LoadBB->getFirstNonPHI(), AC, DT))
  1348. return false;
  1349. for (auto &PL : PredLoads)
  1350. if (!isSafeToSpeculativelyExecute(Load, PL.first->getTerminator(), AC,
  1351. DT))
  1352. return false;
  1353. }
  1354. // Split critical edges, and update the unavailable predecessors accordingly.
  1355. for (BasicBlock *OrigPred : CriticalEdgePred) {
  1356. BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
  1357. assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!");
  1358. PredLoads[NewPred] = nullptr;
  1359. LLVM_DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
  1360. << LoadBB->getName() << '\n');
  1361. }
  1362. // Check if the load can safely be moved to all the unavailable predecessors.
  1363. bool CanDoPRE = true;
  1364. const DataLayout &DL = Load->getModule()->getDataLayout();
  1365. SmallVector<Instruction*, 8> NewInsts;
  1366. for (auto &PredLoad : PredLoads) {
  1367. BasicBlock *UnavailablePred = PredLoad.first;
  1368. // Do PHI translation to get its value in the predecessor if necessary. The
  1369. // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
  1370. // We do the translation for each edge we skipped by going from Load's block
  1371. // to LoadBB, otherwise we might miss pieces needing translation.
  1372. // If all preds have a single successor, then we know it is safe to insert
  1373. // the load on the pred (?!?), so we can insert code to materialize the
  1374. // pointer if it is not available.
  1375. Value *LoadPtr = Load->getPointerOperand();
  1376. BasicBlock *Cur = Load->getParent();
  1377. while (Cur != LoadBB) {
  1378. PHITransAddr Address(LoadPtr, DL, AC);
  1379. LoadPtr = Address.PHITranslateWithInsertion(
  1380. Cur, Cur->getSinglePredecessor(), *DT, NewInsts);
  1381. if (!LoadPtr) {
  1382. CanDoPRE = false;
  1383. break;
  1384. }
  1385. Cur = Cur->getSinglePredecessor();
  1386. }
  1387. if (LoadPtr) {
  1388. PHITransAddr Address(LoadPtr, DL, AC);
  1389. LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred, *DT,
  1390. NewInsts);
  1391. }
  1392. // If we couldn't find or insert a computation of this phi translated value,
  1393. // we fail PRE.
  1394. if (!LoadPtr) {
  1395. LLVM_DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
  1396. << *Load->getPointerOperand() << "\n");
  1397. CanDoPRE = false;
  1398. break;
  1399. }
  1400. PredLoad.second = LoadPtr;
  1401. }
  1402. if (!CanDoPRE) {
  1403. while (!NewInsts.empty()) {
  1404. // Erase instructions generated by the failed PHI translation before
  1405. // trying to number them. PHI translation might insert instructions
  1406. // in basic blocks other than the current one, and we delete them
  1407. // directly, as markInstructionForDeletion only allows removing from the
  1408. // current basic block.
  1409. NewInsts.pop_back_val()->eraseFromParent();
  1410. }
  1411. // HINT: Don't revert the edge-splitting as following transformation may
  1412. // also need to split these critical edges.
  1413. return !CriticalEdgePred.empty();
  1414. }
  1415. // Okay, we can eliminate this load by inserting a reload in the predecessor
  1416. // and using PHI construction to get the value in the other predecessors, do
  1417. // it.
  1418. LLVM_DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *Load << '\n');
  1419. LLVM_DEBUG(if (!NewInsts.empty()) dbgs() << "INSERTED " << NewInsts.size()
  1420. << " INSTS: " << *NewInsts.back()
  1421. << '\n');
  1422. // Assign value numbers to the new instructions.
  1423. for (Instruction *I : NewInsts) {
  1424. // Instructions that have been inserted in predecessor(s) to materialize
  1425. // the load address do not retain their original debug locations. Doing
  1426. // so could lead to confusing (but correct) source attributions.
  1427. I->updateLocationAfterHoist();
  1428. // FIXME: We really _ought_ to insert these value numbers into their
  1429. // parent's availability map. However, in doing so, we risk getting into
  1430. // ordering issues. If a block hasn't been processed yet, we would be
  1431. // marking a value as AVAIL-IN, which isn't what we intend.
  1432. VN.lookupOrAdd(I);
  1433. }
  1434. eliminatePartiallyRedundantLoad(Load, ValuesPerBlock, PredLoads);
  1435. ++NumPRELoad;
  1436. return true;
  1437. }
  1438. bool GVNPass::performLoopLoadPRE(LoadInst *Load,
  1439. AvailValInBlkVect &ValuesPerBlock,
  1440. UnavailBlkVect &UnavailableBlocks) {
  1441. if (!LI)
  1442. return false;
  1443. const Loop *L = LI->getLoopFor(Load->getParent());
  1444. // TODO: Generalize to other loop blocks that dominate the latch.
  1445. if (!L || L->getHeader() != Load->getParent())
  1446. return false;
  1447. BasicBlock *Preheader = L->getLoopPreheader();
  1448. BasicBlock *Latch = L->getLoopLatch();
  1449. if (!Preheader || !Latch)
  1450. return false;
  1451. Value *LoadPtr = Load->getPointerOperand();
  1452. // Must be available in preheader.
  1453. if (!L->isLoopInvariant(LoadPtr))
  1454. return false;
  1455. // We plan to hoist the load to preheader without introducing a new fault.
  1456. // In order to do it, we need to prove that we cannot side-exit the loop
  1457. // once loop header is first entered before execution of the load.
  1458. if (ICF->isDominatedByICFIFromSameBlock(Load))
  1459. return false;
  1460. BasicBlock *LoopBlock = nullptr;
  1461. for (auto *Blocker : UnavailableBlocks) {
  1462. // Blockers from outside the loop are handled in preheader.
  1463. if (!L->contains(Blocker))
  1464. continue;
  1465. // Only allow one loop block. Loop header is not less frequently executed
  1466. // than each loop block, and likely it is much more frequently executed. But
  1467. // in case of multiple loop blocks, we need extra information (such as block
  1468. // frequency info) to understand whether it is profitable to PRE into
  1469. // multiple loop blocks.
  1470. if (LoopBlock)
  1471. return false;
  1472. // Do not sink into inner loops. This may be non-profitable.
  1473. if (L != LI->getLoopFor(Blocker))
  1474. return false;
  1475. // Blocks that dominate the latch execute on every single iteration, maybe
  1476. // except the last one. So PREing into these blocks doesn't make much sense
  1477. // in most cases. But the blocks that do not necessarily execute on each
  1478. // iteration are sometimes much colder than the header, and this is when
  1479. // PRE is potentially profitable.
  1480. if (DT->dominates(Blocker, Latch))
  1481. return false;
  1482. // Make sure that the terminator itself doesn't clobber.
  1483. if (Blocker->getTerminator()->mayWriteToMemory())
  1484. return false;
  1485. LoopBlock = Blocker;
  1486. }
  1487. if (!LoopBlock)
  1488. return false;
  1489. // Make sure the memory at this pointer cannot be freed, therefore we can
  1490. // safely reload from it after clobber.
  1491. if (LoadPtr->canBeFreed())
  1492. return false;
  1493. // TODO: Support critical edge splitting if blocker has more than 1 successor.
  1494. MapVector<BasicBlock *, Value *> AvailableLoads;
  1495. AvailableLoads[LoopBlock] = LoadPtr;
  1496. AvailableLoads[Preheader] = LoadPtr;
  1497. LLVM_DEBUG(dbgs() << "GVN REMOVING PRE LOOP LOAD: " << *Load << '\n');
  1498. eliminatePartiallyRedundantLoad(Load, ValuesPerBlock, AvailableLoads);
  1499. ++NumPRELoopLoad;
  1500. return true;
  1501. }
  1502. static void reportLoadElim(LoadInst *Load, Value *AvailableValue,
  1503. OptimizationRemarkEmitter *ORE) {
  1504. using namespace ore;
  1505. ORE->emit([&]() {
  1506. return OptimizationRemark(DEBUG_TYPE, "LoadElim", Load)
  1507. << "load of type " << NV("Type", Load->getType()) << " eliminated"
  1508. << setExtraArgs() << " in favor of "
  1509. << NV("InfavorOfValue", AvailableValue);
  1510. });
  1511. }
  1512. /// Attempt to eliminate a load whose dependencies are
  1513. /// non-local by performing PHI construction.
  1514. bool GVNPass::processNonLocalLoad(LoadInst *Load) {
  1515. // non-local speculations are not allowed under asan.
  1516. if (Load->getParent()->getParent()->hasFnAttribute(
  1517. Attribute::SanitizeAddress) ||
  1518. Load->getParent()->getParent()->hasFnAttribute(
  1519. Attribute::SanitizeHWAddress))
  1520. return false;
  1521. // Step 1: Find the non-local dependencies of the load.
  1522. LoadDepVect Deps;
  1523. MD->getNonLocalPointerDependency(Load, Deps);
  1524. // If we had to process more than one hundred blocks to find the
  1525. // dependencies, this load isn't worth worrying about. Optimizing
  1526. // it will be too expensive.
  1527. unsigned NumDeps = Deps.size();
  1528. if (NumDeps > MaxNumDeps)
  1529. return false;
  1530. // If we had a phi translation failure, we'll have a single entry which is a
  1531. // clobber in the current block. Reject this early.
  1532. if (NumDeps == 1 &&
  1533. !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
  1534. LLVM_DEBUG(dbgs() << "GVN: non-local load "; Load->printAsOperand(dbgs());
  1535. dbgs() << " has unknown dependencies\n";);
  1536. return false;
  1537. }
  1538. bool Changed = false;
  1539. // If this load follows a GEP, see if we can PRE the indices before analyzing.
  1540. if (GetElementPtrInst *GEP =
  1541. dyn_cast<GetElementPtrInst>(Load->getOperand(0))) {
  1542. for (Use &U : GEP->indices())
  1543. if (Instruction *I = dyn_cast<Instruction>(U.get()))
  1544. Changed |= performScalarPRE(I);
  1545. }
  1546. // Step 2: Analyze the availability of the load
  1547. AvailValInBlkVect ValuesPerBlock;
  1548. UnavailBlkVect UnavailableBlocks;
  1549. AnalyzeLoadAvailability(Load, Deps, ValuesPerBlock, UnavailableBlocks);
  1550. // If we have no predecessors that produce a known value for this load, exit
  1551. // early.
  1552. if (ValuesPerBlock.empty())
  1553. return Changed;
  1554. // Step 3: Eliminate fully redundancy.
  1555. //
  1556. // If all of the instructions we depend on produce a known value for this
  1557. // load, then it is fully redundant and we can use PHI insertion to compute
  1558. // its value. Insert PHIs and remove the fully redundant value now.
  1559. if (UnavailableBlocks.empty()) {
  1560. LLVM_DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *Load << '\n');
  1561. // Perform PHI construction.
  1562. Value *V = ConstructSSAForLoadSet(Load, ValuesPerBlock, *this);
  1563. Load->replaceAllUsesWith(V);
  1564. if (isa<PHINode>(V))
  1565. V->takeName(Load);
  1566. if (Instruction *I = dyn_cast<Instruction>(V))
  1567. // If instruction I has debug info, then we should not update it.
  1568. // Also, if I has a null DebugLoc, then it is still potentially incorrect
  1569. // to propagate Load's DebugLoc because Load may not post-dominate I.
  1570. if (Load->getDebugLoc() && Load->getParent() == I->getParent())
  1571. I->setDebugLoc(Load->getDebugLoc());
  1572. if (V->getType()->isPtrOrPtrVectorTy())
  1573. MD->invalidateCachedPointerInfo(V);
  1574. markInstructionForDeletion(Load);
  1575. ++NumGVNLoad;
  1576. reportLoadElim(Load, V, ORE);
  1577. return true;
  1578. }
  1579. // Step 4: Eliminate partial redundancy.
  1580. if (!isPREEnabled() || !isLoadPREEnabled())
  1581. return Changed;
  1582. if (!isLoadInLoopPREEnabled() && LI && LI->getLoopFor(Load->getParent()))
  1583. return Changed;
  1584. if (performLoopLoadPRE(Load, ValuesPerBlock, UnavailableBlocks) ||
  1585. PerformLoadPRE(Load, ValuesPerBlock, UnavailableBlocks))
  1586. return true;
  1587. return Changed;
  1588. }
  1589. static bool impliesEquivalanceIfTrue(CmpInst* Cmp) {
  1590. if (Cmp->getPredicate() == CmpInst::Predicate::ICMP_EQ)
  1591. return true;
  1592. // Floating point comparisons can be equal, but not equivalent. Cases:
  1593. // NaNs for unordered operators
  1594. // +0.0 vs 0.0 for all operators
  1595. if (Cmp->getPredicate() == CmpInst::Predicate::FCMP_OEQ ||
  1596. (Cmp->getPredicate() == CmpInst::Predicate::FCMP_UEQ &&
  1597. Cmp->getFastMathFlags().noNaNs())) {
  1598. Value *LHS = Cmp->getOperand(0);
  1599. Value *RHS = Cmp->getOperand(1);
  1600. // If we can prove either side non-zero, then equality must imply
  1601. // equivalence.
  1602. // FIXME: We should do this optimization if 'no signed zeros' is
  1603. // applicable via an instruction-level fast-math-flag or some other
  1604. // indicator that relaxed FP semantics are being used.
  1605. if (isa<ConstantFP>(LHS) && !cast<ConstantFP>(LHS)->isZero())
  1606. return true;
  1607. if (isa<ConstantFP>(RHS) && !cast<ConstantFP>(RHS)->isZero())
  1608. return true;;
  1609. // TODO: Handle vector floating point constants
  1610. }
  1611. return false;
  1612. }
  1613. static bool impliesEquivalanceIfFalse(CmpInst* Cmp) {
  1614. if (Cmp->getPredicate() == CmpInst::Predicate::ICMP_NE)
  1615. return true;
  1616. // Floating point comparisons can be equal, but not equivelent. Cases:
  1617. // NaNs for unordered operators
  1618. // +0.0 vs 0.0 for all operators
  1619. if ((Cmp->getPredicate() == CmpInst::Predicate::FCMP_ONE &&
  1620. Cmp->getFastMathFlags().noNaNs()) ||
  1621. Cmp->getPredicate() == CmpInst::Predicate::FCMP_UNE) {
  1622. Value *LHS = Cmp->getOperand(0);
  1623. Value *RHS = Cmp->getOperand(1);
  1624. // If we can prove either side non-zero, then equality must imply
  1625. // equivalence.
  1626. // FIXME: We should do this optimization if 'no signed zeros' is
  1627. // applicable via an instruction-level fast-math-flag or some other
  1628. // indicator that relaxed FP semantics are being used.
  1629. if (isa<ConstantFP>(LHS) && !cast<ConstantFP>(LHS)->isZero())
  1630. return true;
  1631. if (isa<ConstantFP>(RHS) && !cast<ConstantFP>(RHS)->isZero())
  1632. return true;;
  1633. // TODO: Handle vector floating point constants
  1634. }
  1635. return false;
  1636. }
  1637. static bool hasUsersIn(Value *V, BasicBlock *BB) {
  1638. return llvm::any_of(V->users(), [BB](User *U) {
  1639. auto *I = dyn_cast<Instruction>(U);
  1640. return I && I->getParent() == BB;
  1641. });
  1642. }
  1643. bool GVNPass::processAssumeIntrinsic(AssumeInst *IntrinsicI) {
  1644. Value *V = IntrinsicI->getArgOperand(0);
  1645. if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) {
  1646. if (Cond->isZero()) {
  1647. Type *Int8Ty = Type::getInt8Ty(V->getContext());
  1648. // Insert a new store to null instruction before the load to indicate that
  1649. // this code is not reachable. FIXME: We could insert unreachable
  1650. // instruction directly because we can modify the CFG.
  1651. auto *NewS = new StoreInst(PoisonValue::get(Int8Ty),
  1652. Constant::getNullValue(Int8Ty->getPointerTo()),
  1653. IntrinsicI);
  1654. if (MSSAU) {
  1655. const MemoryUseOrDef *FirstNonDom = nullptr;
  1656. const auto *AL =
  1657. MSSAU->getMemorySSA()->getBlockAccesses(IntrinsicI->getParent());
  1658. // If there are accesses in the current basic block, find the first one
  1659. // that does not come before NewS. The new memory access is inserted
  1660. // after the found access or before the terminator if no such access is
  1661. // found.
  1662. if (AL) {
  1663. for (const auto &Acc : *AL) {
  1664. if (auto *Current = dyn_cast<MemoryUseOrDef>(&Acc))
  1665. if (!Current->getMemoryInst()->comesBefore(NewS)) {
  1666. FirstNonDom = Current;
  1667. break;
  1668. }
  1669. }
  1670. }
  1671. // This added store is to null, so it will never executed and we can
  1672. // just use the LiveOnEntry def as defining access.
  1673. auto *NewDef =
  1674. FirstNonDom ? MSSAU->createMemoryAccessBefore(
  1675. NewS, MSSAU->getMemorySSA()->getLiveOnEntryDef(),
  1676. const_cast<MemoryUseOrDef *>(FirstNonDom))
  1677. : MSSAU->createMemoryAccessInBB(
  1678. NewS, MSSAU->getMemorySSA()->getLiveOnEntryDef(),
  1679. NewS->getParent(), MemorySSA::BeforeTerminator);
  1680. MSSAU->insertDef(cast<MemoryDef>(NewDef), /*RenameUses=*/false);
  1681. }
  1682. }
  1683. if (isAssumeWithEmptyBundle(*IntrinsicI))
  1684. markInstructionForDeletion(IntrinsicI);
  1685. return false;
  1686. } else if (isa<Constant>(V)) {
  1687. // If it's not false, and constant, it must evaluate to true. This means our
  1688. // assume is assume(true), and thus, pointless, and we don't want to do
  1689. // anything more here.
  1690. return false;
  1691. }
  1692. Constant *True = ConstantInt::getTrue(V->getContext());
  1693. bool Changed = false;
  1694. for (BasicBlock *Successor : successors(IntrinsicI->getParent())) {
  1695. BasicBlockEdge Edge(IntrinsicI->getParent(), Successor);
  1696. // This property is only true in dominated successors, propagateEquality
  1697. // will check dominance for us.
  1698. Changed |= propagateEquality(V, True, Edge, false);
  1699. }
  1700. // We can replace assume value with true, which covers cases like this:
  1701. // call void @llvm.assume(i1 %cmp)
  1702. // br i1 %cmp, label %bb1, label %bb2 ; will change %cmp to true
  1703. ReplaceOperandsWithMap[V] = True;
  1704. // Similarly, after assume(!NotV) we know that NotV == false.
  1705. Value *NotV;
  1706. if (match(V, m_Not(m_Value(NotV))))
  1707. ReplaceOperandsWithMap[NotV] = ConstantInt::getFalse(V->getContext());
  1708. // If we find an equality fact, canonicalize all dominated uses in this block
  1709. // to one of the two values. We heuristically choice the "oldest" of the
  1710. // two where age is determined by value number. (Note that propagateEquality
  1711. // above handles the cross block case.)
  1712. //
  1713. // Key case to cover are:
  1714. // 1)
  1715. // %cmp = fcmp oeq float 3.000000e+00, %0 ; const on lhs could happen
  1716. // call void @llvm.assume(i1 %cmp)
  1717. // ret float %0 ; will change it to ret float 3.000000e+00
  1718. // 2)
  1719. // %load = load float, float* %addr
  1720. // %cmp = fcmp oeq float %load, %0
  1721. // call void @llvm.assume(i1 %cmp)
  1722. // ret float %load ; will change it to ret float %0
  1723. if (auto *CmpI = dyn_cast<CmpInst>(V)) {
  1724. if (impliesEquivalanceIfTrue(CmpI)) {
  1725. Value *CmpLHS = CmpI->getOperand(0);
  1726. Value *CmpRHS = CmpI->getOperand(1);
  1727. // Heuristically pick the better replacement -- the choice of heuristic
  1728. // isn't terribly important here, but the fact we canonicalize on some
  1729. // replacement is for exposing other simplifications.
  1730. // TODO: pull this out as a helper function and reuse w/existing
  1731. // (slightly different) logic.
  1732. if (isa<Constant>(CmpLHS) && !isa<Constant>(CmpRHS))
  1733. std::swap(CmpLHS, CmpRHS);
  1734. if (!isa<Instruction>(CmpLHS) && isa<Instruction>(CmpRHS))
  1735. std::swap(CmpLHS, CmpRHS);
  1736. if ((isa<Argument>(CmpLHS) && isa<Argument>(CmpRHS)) ||
  1737. (isa<Instruction>(CmpLHS) && isa<Instruction>(CmpRHS))) {
  1738. // Move the 'oldest' value to the right-hand side, using the value
  1739. // number as a proxy for age.
  1740. uint32_t LVN = VN.lookupOrAdd(CmpLHS);
  1741. uint32_t RVN = VN.lookupOrAdd(CmpRHS);
  1742. if (LVN < RVN)
  1743. std::swap(CmpLHS, CmpRHS);
  1744. }
  1745. // Handle degenerate case where we either haven't pruned a dead path or a
  1746. // removed a trivial assume yet.
  1747. if (isa<Constant>(CmpLHS) && isa<Constant>(CmpRHS))
  1748. return Changed;
  1749. LLVM_DEBUG(dbgs() << "Replacing dominated uses of "
  1750. << *CmpLHS << " with "
  1751. << *CmpRHS << " in block "
  1752. << IntrinsicI->getParent()->getName() << "\n");
  1753. // Setup the replacement map - this handles uses within the same block
  1754. if (hasUsersIn(CmpLHS, IntrinsicI->getParent()))
  1755. ReplaceOperandsWithMap[CmpLHS] = CmpRHS;
  1756. // NOTE: The non-block local cases are handled by the call to
  1757. // propagateEquality above; this block is just about handling the block
  1758. // local cases. TODO: There's a bunch of logic in propagateEqualiy which
  1759. // isn't duplicated for the block local case, can we share it somehow?
  1760. }
  1761. }
  1762. return Changed;
  1763. }
  1764. static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
  1765. patchReplacementInstruction(I, Repl);
  1766. I->replaceAllUsesWith(Repl);
  1767. }
  1768. /// Attempt to eliminate a load, first by eliminating it
  1769. /// locally, and then attempting non-local elimination if that fails.
  1770. bool GVNPass::processLoad(LoadInst *L) {
  1771. if (!MD)
  1772. return false;
  1773. // This code hasn't been audited for ordered or volatile memory access
  1774. if (!L->isUnordered())
  1775. return false;
  1776. if (L->use_empty()) {
  1777. markInstructionForDeletion(L);
  1778. return true;
  1779. }
  1780. // ... to a pointer that has been loaded from before...
  1781. MemDepResult Dep = MD->getDependency(L);
  1782. // If it is defined in another block, try harder.
  1783. if (Dep.isNonLocal())
  1784. return processNonLocalLoad(L);
  1785. // Only handle the local case below
  1786. if (!Dep.isLocal()) {
  1787. // This might be a NonFuncLocal or an Unknown
  1788. LLVM_DEBUG(
  1789. // fast print dep, using operator<< on instruction is too slow.
  1790. dbgs() << "GVN: load "; L->printAsOperand(dbgs());
  1791. dbgs() << " has unknown dependence\n";);
  1792. return false;
  1793. }
  1794. auto AV = AnalyzeLoadAvailability(L, Dep, L->getPointerOperand());
  1795. if (!AV)
  1796. return false;
  1797. Value *AvailableValue = AV->MaterializeAdjustedValue(L, L, *this);
  1798. // Replace the load!
  1799. patchAndReplaceAllUsesWith(L, AvailableValue);
  1800. markInstructionForDeletion(L);
  1801. if (MSSAU)
  1802. MSSAU->removeMemoryAccess(L);
  1803. ++NumGVNLoad;
  1804. reportLoadElim(L, AvailableValue, ORE);
  1805. // Tell MDA to reexamine the reused pointer since we might have more
  1806. // information after forwarding it.
  1807. if (MD && AvailableValue->getType()->isPtrOrPtrVectorTy())
  1808. MD->invalidateCachedPointerInfo(AvailableValue);
  1809. return true;
  1810. }
  1811. /// Return a pair the first field showing the value number of \p Exp and the
  1812. /// second field showing whether it is a value number newly created.
  1813. std::pair<uint32_t, bool>
  1814. GVNPass::ValueTable::assignExpNewValueNum(Expression &Exp) {
  1815. uint32_t &e = expressionNumbering[Exp];
  1816. bool CreateNewValNum = !e;
  1817. if (CreateNewValNum) {
  1818. Expressions.push_back(Exp);
  1819. if (ExprIdx.size() < nextValueNumber + 1)
  1820. ExprIdx.resize(nextValueNumber * 2);
  1821. e = nextValueNumber;
  1822. ExprIdx[nextValueNumber++] = nextExprNumber++;
  1823. }
  1824. return {e, CreateNewValNum};
  1825. }
  1826. /// Return whether all the values related with the same \p num are
  1827. /// defined in \p BB.
  1828. bool GVNPass::ValueTable::areAllValsInBB(uint32_t Num, const BasicBlock *BB,
  1829. GVNPass &Gvn) {
  1830. LeaderTableEntry *Vals = &Gvn.LeaderTable[Num];
  1831. while (Vals && Vals->BB == BB)
  1832. Vals = Vals->Next;
  1833. return !Vals;
  1834. }
  1835. /// Wrap phiTranslateImpl to provide caching functionality.
  1836. uint32_t GVNPass::ValueTable::phiTranslate(const BasicBlock *Pred,
  1837. const BasicBlock *PhiBlock,
  1838. uint32_t Num, GVNPass &Gvn) {
  1839. auto FindRes = PhiTranslateTable.find({Num, Pred});
  1840. if (FindRes != PhiTranslateTable.end())
  1841. return FindRes->second;
  1842. uint32_t NewNum = phiTranslateImpl(Pred, PhiBlock, Num, Gvn);
  1843. PhiTranslateTable.insert({{Num, Pred}, NewNum});
  1844. return NewNum;
  1845. }
  1846. // Return true if the value number \p Num and NewNum have equal value.
  1847. // Return false if the result is unknown.
  1848. bool GVNPass::ValueTable::areCallValsEqual(uint32_t Num, uint32_t NewNum,
  1849. const BasicBlock *Pred,
  1850. const BasicBlock *PhiBlock,
  1851. GVNPass &Gvn) {
  1852. CallInst *Call = nullptr;
  1853. LeaderTableEntry *Vals = &Gvn.LeaderTable[Num];
  1854. while (Vals) {
  1855. Call = dyn_cast<CallInst>(Vals->Val);
  1856. if (Call && Call->getParent() == PhiBlock)
  1857. break;
  1858. Vals = Vals->Next;
  1859. }
  1860. if (AA->doesNotAccessMemory(Call))
  1861. return true;
  1862. if (!MD || !AA->onlyReadsMemory(Call))
  1863. return false;
  1864. MemDepResult local_dep = MD->getDependency(Call);
  1865. if (!local_dep.isNonLocal())
  1866. return false;
  1867. const MemoryDependenceResults::NonLocalDepInfo &deps =
  1868. MD->getNonLocalCallDependency(Call);
  1869. // Check to see if the Call has no function local clobber.
  1870. for (const NonLocalDepEntry &D : deps) {
  1871. if (D.getResult().isNonFuncLocal())
  1872. return true;
  1873. }
  1874. return false;
  1875. }
  1876. /// Translate value number \p Num using phis, so that it has the values of
  1877. /// the phis in BB.
  1878. uint32_t GVNPass::ValueTable::phiTranslateImpl(const BasicBlock *Pred,
  1879. const BasicBlock *PhiBlock,
  1880. uint32_t Num, GVNPass &Gvn) {
  1881. if (PHINode *PN = NumberingPhi[Num]) {
  1882. for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
  1883. if (PN->getParent() == PhiBlock && PN->getIncomingBlock(i) == Pred)
  1884. if (uint32_t TransVal = lookup(PN->getIncomingValue(i), false))
  1885. return TransVal;
  1886. }
  1887. return Num;
  1888. }
  1889. // If there is any value related with Num is defined in a BB other than
  1890. // PhiBlock, it cannot depend on a phi in PhiBlock without going through
  1891. // a backedge. We can do an early exit in that case to save compile time.
  1892. if (!areAllValsInBB(Num, PhiBlock, Gvn))
  1893. return Num;
  1894. if (Num >= ExprIdx.size() || ExprIdx[Num] == 0)
  1895. return Num;
  1896. Expression Exp = Expressions[ExprIdx[Num]];
  1897. for (unsigned i = 0; i < Exp.varargs.size(); i++) {
  1898. // For InsertValue and ExtractValue, some varargs are index numbers
  1899. // instead of value numbers. Those index numbers should not be
  1900. // translated.
  1901. if ((i > 1 && Exp.opcode == Instruction::InsertValue) ||
  1902. (i > 0 && Exp.opcode == Instruction::ExtractValue) ||
  1903. (i > 1 && Exp.opcode == Instruction::ShuffleVector))
  1904. continue;
  1905. Exp.varargs[i] = phiTranslate(Pred, PhiBlock, Exp.varargs[i], Gvn);
  1906. }
  1907. if (Exp.commutative) {
  1908. assert(Exp.varargs.size() >= 2 && "Unsupported commutative instruction!");
  1909. if (Exp.varargs[0] > Exp.varargs[1]) {
  1910. std::swap(Exp.varargs[0], Exp.varargs[1]);
  1911. uint32_t Opcode = Exp.opcode >> 8;
  1912. if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp)
  1913. Exp.opcode = (Opcode << 8) |
  1914. CmpInst::getSwappedPredicate(
  1915. static_cast<CmpInst::Predicate>(Exp.opcode & 255));
  1916. }
  1917. }
  1918. if (uint32_t NewNum = expressionNumbering[Exp]) {
  1919. if (Exp.opcode == Instruction::Call && NewNum != Num)
  1920. return areCallValsEqual(Num, NewNum, Pred, PhiBlock, Gvn) ? NewNum : Num;
  1921. return NewNum;
  1922. }
  1923. return Num;
  1924. }
  1925. /// Erase stale entry from phiTranslate cache so phiTranslate can be computed
  1926. /// again.
  1927. void GVNPass::ValueTable::eraseTranslateCacheEntry(
  1928. uint32_t Num, const BasicBlock &CurrBlock) {
  1929. for (const BasicBlock *Pred : predecessors(&CurrBlock))
  1930. PhiTranslateTable.erase({Num, Pred});
  1931. }
  1932. // In order to find a leader for a given value number at a
  1933. // specific basic block, we first obtain the list of all Values for that number,
  1934. // and then scan the list to find one whose block dominates the block in
  1935. // question. This is fast because dominator tree queries consist of only
  1936. // a few comparisons of DFS numbers.
  1937. Value *GVNPass::findLeader(const BasicBlock *BB, uint32_t num) {
  1938. LeaderTableEntry Vals = LeaderTable[num];
  1939. if (!Vals.Val) return nullptr;
  1940. Value *Val = nullptr;
  1941. if (DT->dominates(Vals.BB, BB)) {
  1942. Val = Vals.Val;
  1943. if (isa<Constant>(Val)) return Val;
  1944. }
  1945. LeaderTableEntry* Next = Vals.Next;
  1946. while (Next) {
  1947. if (DT->dominates(Next->BB, BB)) {
  1948. if (isa<Constant>(Next->Val)) return Next->Val;
  1949. if (!Val) Val = Next->Val;
  1950. }
  1951. Next = Next->Next;
  1952. }
  1953. return Val;
  1954. }
  1955. /// There is an edge from 'Src' to 'Dst'. Return
  1956. /// true if every path from the entry block to 'Dst' passes via this edge. In
  1957. /// particular 'Dst' must not be reachable via another edge from 'Src'.
  1958. static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
  1959. DominatorTree *DT) {
  1960. // While in theory it is interesting to consider the case in which Dst has
  1961. // more than one predecessor, because Dst might be part of a loop which is
  1962. // only reachable from Src, in practice it is pointless since at the time
  1963. // GVN runs all such loops have preheaders, which means that Dst will have
  1964. // been changed to have only one predecessor, namely Src.
  1965. const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
  1966. assert((!Pred || Pred == E.getStart()) &&
  1967. "No edge between these basic blocks!");
  1968. return Pred != nullptr;
  1969. }
  1970. void GVNPass::assignBlockRPONumber(Function &F) {
  1971. BlockRPONumber.clear();
  1972. uint32_t NextBlockNumber = 1;
  1973. ReversePostOrderTraversal<Function *> RPOT(&F);
  1974. for (BasicBlock *BB : RPOT)
  1975. BlockRPONumber[BB] = NextBlockNumber++;
  1976. InvalidBlockRPONumbers = false;
  1977. }
  1978. bool GVNPass::replaceOperandsForInBlockEquality(Instruction *Instr) const {
  1979. bool Changed = false;
  1980. for (unsigned OpNum = 0; OpNum < Instr->getNumOperands(); ++OpNum) {
  1981. Value *Operand = Instr->getOperand(OpNum);
  1982. auto it = ReplaceOperandsWithMap.find(Operand);
  1983. if (it != ReplaceOperandsWithMap.end()) {
  1984. LLVM_DEBUG(dbgs() << "GVN replacing: " << *Operand << " with "
  1985. << *it->second << " in instruction " << *Instr << '\n');
  1986. Instr->setOperand(OpNum, it->second);
  1987. Changed = true;
  1988. }
  1989. }
  1990. return Changed;
  1991. }
  1992. /// The given values are known to be equal in every block
  1993. /// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
  1994. /// 'RHS' everywhere in the scope. Returns whether a change was made.
  1995. /// If DominatesByEdge is false, then it means that we will propagate the RHS
  1996. /// value starting from the end of Root.Start.
  1997. bool GVNPass::propagateEquality(Value *LHS, Value *RHS,
  1998. const BasicBlockEdge &Root,
  1999. bool DominatesByEdge) {
  2000. SmallVector<std::pair<Value*, Value*>, 4> Worklist;
  2001. Worklist.push_back(std::make_pair(LHS, RHS));
  2002. bool Changed = false;
  2003. // For speed, compute a conservative fast approximation to
  2004. // DT->dominates(Root, Root.getEnd());
  2005. const bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
  2006. while (!Worklist.empty()) {
  2007. std::pair<Value*, Value*> Item = Worklist.pop_back_val();
  2008. LHS = Item.first; RHS = Item.second;
  2009. if (LHS == RHS)
  2010. continue;
  2011. assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
  2012. // Don't try to propagate equalities between constants.
  2013. if (isa<Constant>(LHS) && isa<Constant>(RHS))
  2014. continue;
  2015. // Prefer a constant on the right-hand side, or an Argument if no constants.
  2016. if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
  2017. std::swap(LHS, RHS);
  2018. assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
  2019. // If there is no obvious reason to prefer the left-hand side over the
  2020. // right-hand side, ensure the longest lived term is on the right-hand side,
  2021. // so the shortest lived term will be replaced by the longest lived.
  2022. // This tends to expose more simplifications.
  2023. uint32_t LVN = VN.lookupOrAdd(LHS);
  2024. if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
  2025. (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
  2026. // Move the 'oldest' value to the right-hand side, using the value number
  2027. // as a proxy for age.
  2028. uint32_t RVN = VN.lookupOrAdd(RHS);
  2029. if (LVN < RVN) {
  2030. std::swap(LHS, RHS);
  2031. LVN = RVN;
  2032. }
  2033. }
  2034. // If value numbering later sees that an instruction in the scope is equal
  2035. // to 'LHS' then ensure it will be turned into 'RHS'. In order to preserve
  2036. // the invariant that instructions only occur in the leader table for their
  2037. // own value number (this is used by removeFromLeaderTable), do not do this
  2038. // if RHS is an instruction (if an instruction in the scope is morphed into
  2039. // LHS then it will be turned into RHS by the next GVN iteration anyway, so
  2040. // using the leader table is about compiling faster, not optimizing better).
  2041. // The leader table only tracks basic blocks, not edges. Only add to if we
  2042. // have the simple case where the edge dominates the end.
  2043. if (RootDominatesEnd && !isa<Instruction>(RHS))
  2044. addToLeaderTable(LVN, RHS, Root.getEnd());
  2045. // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
  2046. // LHS always has at least one use that is not dominated by Root, this will
  2047. // never do anything if LHS has only one use.
  2048. if (!LHS->hasOneUse()) {
  2049. unsigned NumReplacements =
  2050. DominatesByEdge
  2051. ? replaceDominatedUsesWith(LHS, RHS, *DT, Root)
  2052. : replaceDominatedUsesWith(LHS, RHS, *DT, Root.getStart());
  2053. Changed |= NumReplacements > 0;
  2054. NumGVNEqProp += NumReplacements;
  2055. // Cached information for anything that uses LHS will be invalid.
  2056. if (MD)
  2057. MD->invalidateCachedPointerInfo(LHS);
  2058. }
  2059. // Now try to deduce additional equalities from this one. For example, if
  2060. // the known equality was "(A != B)" == "false" then it follows that A and B
  2061. // are equal in the scope. Only boolean equalities with an explicit true or
  2062. // false RHS are currently supported.
  2063. if (!RHS->getType()->isIntegerTy(1))
  2064. // Not a boolean equality - bail out.
  2065. continue;
  2066. ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
  2067. if (!CI)
  2068. // RHS neither 'true' nor 'false' - bail out.
  2069. continue;
  2070. // Whether RHS equals 'true'. Otherwise it equals 'false'.
  2071. bool isKnownTrue = CI->isMinusOne();
  2072. bool isKnownFalse = !isKnownTrue;
  2073. // If "A && B" is known true then both A and B are known true. If "A || B"
  2074. // is known false then both A and B are known false.
  2075. Value *A, *B;
  2076. if ((isKnownTrue && match(LHS, m_LogicalAnd(m_Value(A), m_Value(B)))) ||
  2077. (isKnownFalse && match(LHS, m_LogicalOr(m_Value(A), m_Value(B))))) {
  2078. Worklist.push_back(std::make_pair(A, RHS));
  2079. Worklist.push_back(std::make_pair(B, RHS));
  2080. continue;
  2081. }
  2082. // If we are propagating an equality like "(A == B)" == "true" then also
  2083. // propagate the equality A == B. When propagating a comparison such as
  2084. // "(A >= B)" == "true", replace all instances of "A < B" with "false".
  2085. if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
  2086. Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
  2087. // If "A == B" is known true, or "A != B" is known false, then replace
  2088. // A with B everywhere in the scope. For floating point operations, we
  2089. // have to be careful since equality does not always imply equivalance.
  2090. if ((isKnownTrue && impliesEquivalanceIfTrue(Cmp)) ||
  2091. (isKnownFalse && impliesEquivalanceIfFalse(Cmp)))
  2092. Worklist.push_back(std::make_pair(Op0, Op1));
  2093. // If "A >= B" is known true, replace "A < B" with false everywhere.
  2094. CmpInst::Predicate NotPred = Cmp->getInversePredicate();
  2095. Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
  2096. // Since we don't have the instruction "A < B" immediately to hand, work
  2097. // out the value number that it would have and use that to find an
  2098. // appropriate instruction (if any).
  2099. uint32_t NextNum = VN.getNextUnusedValueNumber();
  2100. uint32_t Num = VN.lookupOrAddCmp(Cmp->getOpcode(), NotPred, Op0, Op1);
  2101. // If the number we were assigned was brand new then there is no point in
  2102. // looking for an instruction realizing it: there cannot be one!
  2103. if (Num < NextNum) {
  2104. Value *NotCmp = findLeader(Root.getEnd(), Num);
  2105. if (NotCmp && isa<Instruction>(NotCmp)) {
  2106. unsigned NumReplacements =
  2107. DominatesByEdge
  2108. ? replaceDominatedUsesWith(NotCmp, NotVal, *DT, Root)
  2109. : replaceDominatedUsesWith(NotCmp, NotVal, *DT,
  2110. Root.getStart());
  2111. Changed |= NumReplacements > 0;
  2112. NumGVNEqProp += NumReplacements;
  2113. // Cached information for anything that uses NotCmp will be invalid.
  2114. if (MD)
  2115. MD->invalidateCachedPointerInfo(NotCmp);
  2116. }
  2117. }
  2118. // Ensure that any instruction in scope that gets the "A < B" value number
  2119. // is replaced with false.
  2120. // The leader table only tracks basic blocks, not edges. Only add to if we
  2121. // have the simple case where the edge dominates the end.
  2122. if (RootDominatesEnd)
  2123. addToLeaderTable(Num, NotVal, Root.getEnd());
  2124. continue;
  2125. }
  2126. }
  2127. return Changed;
  2128. }
  2129. /// When calculating availability, handle an instruction
  2130. /// by inserting it into the appropriate sets
  2131. bool GVNPass::processInstruction(Instruction *I) {
  2132. // Ignore dbg info intrinsics.
  2133. if (isa<DbgInfoIntrinsic>(I))
  2134. return false;
  2135. // If the instruction can be easily simplified then do so now in preference
  2136. // to value numbering it. Value numbering often exposes redundancies, for
  2137. // example if it determines that %y is equal to %x then the instruction
  2138. // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
  2139. const DataLayout &DL = I->getModule()->getDataLayout();
  2140. if (Value *V = simplifyInstruction(I, {DL, TLI, DT, AC})) {
  2141. bool Changed = false;
  2142. if (!I->use_empty()) {
  2143. // Simplification can cause a special instruction to become not special.
  2144. // For example, devirtualization to a willreturn function.
  2145. ICF->removeUsersOf(I);
  2146. I->replaceAllUsesWith(V);
  2147. Changed = true;
  2148. }
  2149. if (isInstructionTriviallyDead(I, TLI)) {
  2150. markInstructionForDeletion(I);
  2151. Changed = true;
  2152. }
  2153. if (Changed) {
  2154. if (MD && V->getType()->isPtrOrPtrVectorTy())
  2155. MD->invalidateCachedPointerInfo(V);
  2156. ++NumGVNSimpl;
  2157. return true;
  2158. }
  2159. }
  2160. if (auto *Assume = dyn_cast<AssumeInst>(I))
  2161. return processAssumeIntrinsic(Assume);
  2162. if (LoadInst *Load = dyn_cast<LoadInst>(I)) {
  2163. if (processLoad(Load))
  2164. return true;
  2165. unsigned Num = VN.lookupOrAdd(Load);
  2166. addToLeaderTable(Num, Load, Load->getParent());
  2167. return false;
  2168. }
  2169. // For conditional branches, we can perform simple conditional propagation on
  2170. // the condition value itself.
  2171. if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
  2172. if (!BI->isConditional())
  2173. return false;
  2174. if (isa<Constant>(BI->getCondition()))
  2175. return processFoldableCondBr(BI);
  2176. Value *BranchCond = BI->getCondition();
  2177. BasicBlock *TrueSucc = BI->getSuccessor(0);
  2178. BasicBlock *FalseSucc = BI->getSuccessor(1);
  2179. // Avoid multiple edges early.
  2180. if (TrueSucc == FalseSucc)
  2181. return false;
  2182. BasicBlock *Parent = BI->getParent();
  2183. bool Changed = false;
  2184. Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
  2185. BasicBlockEdge TrueE(Parent, TrueSucc);
  2186. Changed |= propagateEquality(BranchCond, TrueVal, TrueE, true);
  2187. Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
  2188. BasicBlockEdge FalseE(Parent, FalseSucc);
  2189. Changed |= propagateEquality(BranchCond, FalseVal, FalseE, true);
  2190. return Changed;
  2191. }
  2192. // For switches, propagate the case values into the case destinations.
  2193. if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
  2194. Value *SwitchCond = SI->getCondition();
  2195. BasicBlock *Parent = SI->getParent();
  2196. bool Changed = false;
  2197. // Remember how many outgoing edges there are to every successor.
  2198. SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
  2199. for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
  2200. ++SwitchEdges[SI->getSuccessor(i)];
  2201. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  2202. i != e; ++i) {
  2203. BasicBlock *Dst = i->getCaseSuccessor();
  2204. // If there is only a single edge, propagate the case value into it.
  2205. if (SwitchEdges.lookup(Dst) == 1) {
  2206. BasicBlockEdge E(Parent, Dst);
  2207. Changed |= propagateEquality(SwitchCond, i->getCaseValue(), E, true);
  2208. }
  2209. }
  2210. return Changed;
  2211. }
  2212. // Instructions with void type don't return a value, so there's
  2213. // no point in trying to find redundancies in them.
  2214. if (I->getType()->isVoidTy())
  2215. return false;
  2216. uint32_t NextNum = VN.getNextUnusedValueNumber();
  2217. unsigned Num = VN.lookupOrAdd(I);
  2218. // Allocations are always uniquely numbered, so we can save time and memory
  2219. // by fast failing them.
  2220. if (isa<AllocaInst>(I) || I->isTerminator() || isa<PHINode>(I)) {
  2221. addToLeaderTable(Num, I, I->getParent());
  2222. return false;
  2223. }
  2224. // If the number we were assigned was a brand new VN, then we don't
  2225. // need to do a lookup to see if the number already exists
  2226. // somewhere in the domtree: it can't!
  2227. if (Num >= NextNum) {
  2228. addToLeaderTable(Num, I, I->getParent());
  2229. return false;
  2230. }
  2231. // Perform fast-path value-number based elimination of values inherited from
  2232. // dominators.
  2233. Value *Repl = findLeader(I->getParent(), Num);
  2234. if (!Repl) {
  2235. // Failure, just remember this instance for future use.
  2236. addToLeaderTable(Num, I, I->getParent());
  2237. return false;
  2238. } else if (Repl == I) {
  2239. // If I was the result of a shortcut PRE, it might already be in the table
  2240. // and the best replacement for itself. Nothing to do.
  2241. return false;
  2242. }
  2243. // Remove it!
  2244. patchAndReplaceAllUsesWith(I, Repl);
  2245. if (MD && Repl->getType()->isPtrOrPtrVectorTy())
  2246. MD->invalidateCachedPointerInfo(Repl);
  2247. markInstructionForDeletion(I);
  2248. return true;
  2249. }
  2250. /// runOnFunction - This is the main transformation entry point for a function.
  2251. bool GVNPass::runImpl(Function &F, AssumptionCache &RunAC, DominatorTree &RunDT,
  2252. const TargetLibraryInfo &RunTLI, AAResults &RunAA,
  2253. MemoryDependenceResults *RunMD, LoopInfo *LI,
  2254. OptimizationRemarkEmitter *RunORE, MemorySSA *MSSA) {
  2255. AC = &RunAC;
  2256. DT = &RunDT;
  2257. VN.setDomTree(DT);
  2258. TLI = &RunTLI;
  2259. VN.setAliasAnalysis(&RunAA);
  2260. MD = RunMD;
  2261. ImplicitControlFlowTracking ImplicitCFT;
  2262. ICF = &ImplicitCFT;
  2263. this->LI = LI;
  2264. VN.setMemDep(MD);
  2265. ORE = RunORE;
  2266. InvalidBlockRPONumbers = true;
  2267. MemorySSAUpdater Updater(MSSA);
  2268. MSSAU = MSSA ? &Updater : nullptr;
  2269. bool Changed = false;
  2270. bool ShouldContinue = true;
  2271. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  2272. // Merge unconditional branches, allowing PRE to catch more
  2273. // optimization opportunities.
  2274. for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
  2275. bool removedBlock = MergeBlockIntoPredecessor(&BB, &DTU, LI, MSSAU, MD);
  2276. if (removedBlock)
  2277. ++NumGVNBlocks;
  2278. Changed |= removedBlock;
  2279. }
  2280. unsigned Iteration = 0;
  2281. while (ShouldContinue) {
  2282. LLVM_DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
  2283. (void) Iteration;
  2284. ShouldContinue = iterateOnFunction(F);
  2285. Changed |= ShouldContinue;
  2286. ++Iteration;
  2287. }
  2288. if (isPREEnabled()) {
  2289. // Fabricate val-num for dead-code in order to suppress assertion in
  2290. // performPRE().
  2291. assignValNumForDeadCode();
  2292. bool PREChanged = true;
  2293. while (PREChanged) {
  2294. PREChanged = performPRE(F);
  2295. Changed |= PREChanged;
  2296. }
  2297. }
  2298. // FIXME: Should perform GVN again after PRE does something. PRE can move
  2299. // computations into blocks where they become fully redundant. Note that
  2300. // we can't do this until PRE's critical edge splitting updates memdep.
  2301. // Actually, when this happens, we should just fully integrate PRE into GVN.
  2302. cleanupGlobalSets();
  2303. // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
  2304. // iteration.
  2305. DeadBlocks.clear();
  2306. if (MSSA && VerifyMemorySSA)
  2307. MSSA->verifyMemorySSA();
  2308. return Changed;
  2309. }
  2310. bool GVNPass::processBlock(BasicBlock *BB) {
  2311. // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
  2312. // (and incrementing BI before processing an instruction).
  2313. assert(InstrsToErase.empty() &&
  2314. "We expect InstrsToErase to be empty across iterations");
  2315. if (DeadBlocks.count(BB))
  2316. return false;
  2317. // Clearing map before every BB because it can be used only for single BB.
  2318. ReplaceOperandsWithMap.clear();
  2319. bool ChangedFunction = false;
  2320. // Since we may not have visited the input blocks of the phis, we can't
  2321. // use our normal hash approach for phis. Instead, simply look for
  2322. // obvious duplicates. The first pass of GVN will tend to create
  2323. // identical phis, and the second or later passes can eliminate them.
  2324. ChangedFunction |= EliminateDuplicatePHINodes(BB);
  2325. for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
  2326. BI != BE;) {
  2327. if (!ReplaceOperandsWithMap.empty())
  2328. ChangedFunction |= replaceOperandsForInBlockEquality(&*BI);
  2329. ChangedFunction |= processInstruction(&*BI);
  2330. if (InstrsToErase.empty()) {
  2331. ++BI;
  2332. continue;
  2333. }
  2334. // If we need some instructions deleted, do it now.
  2335. NumGVNInstr += InstrsToErase.size();
  2336. // Avoid iterator invalidation.
  2337. bool AtStart = BI == BB->begin();
  2338. if (!AtStart)
  2339. --BI;
  2340. for (auto *I : InstrsToErase) {
  2341. assert(I->getParent() == BB && "Removing instruction from wrong block?");
  2342. LLVM_DEBUG(dbgs() << "GVN removed: " << *I << '\n');
  2343. salvageKnowledge(I, AC);
  2344. salvageDebugInfo(*I);
  2345. if (MD) MD->removeInstruction(I);
  2346. if (MSSAU)
  2347. MSSAU->removeMemoryAccess(I);
  2348. LLVM_DEBUG(verifyRemoved(I));
  2349. ICF->removeInstruction(I);
  2350. I->eraseFromParent();
  2351. }
  2352. InstrsToErase.clear();
  2353. if (AtStart)
  2354. BI = BB->begin();
  2355. else
  2356. ++BI;
  2357. }
  2358. return ChangedFunction;
  2359. }
  2360. // Instantiate an expression in a predecessor that lacked it.
  2361. bool GVNPass::performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
  2362. BasicBlock *Curr, unsigned int ValNo) {
  2363. // Because we are going top-down through the block, all value numbers
  2364. // will be available in the predecessor by the time we need them. Any
  2365. // that weren't originally present will have been instantiated earlier
  2366. // in this loop.
  2367. bool success = true;
  2368. for (unsigned i = 0, e = Instr->getNumOperands(); i != e; ++i) {
  2369. Value *Op = Instr->getOperand(i);
  2370. if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
  2371. continue;
  2372. // This could be a newly inserted instruction, in which case, we won't
  2373. // find a value number, and should give up before we hurt ourselves.
  2374. // FIXME: Rewrite the infrastructure to let it easier to value number
  2375. // and process newly inserted instructions.
  2376. if (!VN.exists(Op)) {
  2377. success = false;
  2378. break;
  2379. }
  2380. uint32_t TValNo =
  2381. VN.phiTranslate(Pred, Curr, VN.lookup(Op), *this);
  2382. if (Value *V = findLeader(Pred, TValNo)) {
  2383. Instr->setOperand(i, V);
  2384. } else {
  2385. success = false;
  2386. break;
  2387. }
  2388. }
  2389. // Fail out if we encounter an operand that is not available in
  2390. // the PRE predecessor. This is typically because of loads which
  2391. // are not value numbered precisely.
  2392. if (!success)
  2393. return false;
  2394. Instr->insertBefore(Pred->getTerminator());
  2395. Instr->setName(Instr->getName() + ".pre");
  2396. Instr->setDebugLoc(Instr->getDebugLoc());
  2397. ICF->insertInstructionTo(Instr, Pred);
  2398. unsigned Num = VN.lookupOrAdd(Instr);
  2399. VN.add(Instr, Num);
  2400. // Update the availability map to include the new instruction.
  2401. addToLeaderTable(Num, Instr, Pred);
  2402. return true;
  2403. }
  2404. bool GVNPass::performScalarPRE(Instruction *CurInst) {
  2405. if (isa<AllocaInst>(CurInst) || CurInst->isTerminator() ||
  2406. isa<PHINode>(CurInst) || CurInst->getType()->isVoidTy() ||
  2407. CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
  2408. isa<DbgInfoIntrinsic>(CurInst))
  2409. return false;
  2410. // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
  2411. // sinking the compare again, and it would force the code generator to
  2412. // move the i1 from processor flags or predicate registers into a general
  2413. // purpose register.
  2414. if (isa<CmpInst>(CurInst))
  2415. return false;
  2416. // Don't do PRE on GEPs. The inserted PHI would prevent CodeGenPrepare from
  2417. // sinking the addressing mode computation back to its uses. Extending the
  2418. // GEP's live range increases the register pressure, and therefore it can
  2419. // introduce unnecessary spills.
  2420. //
  2421. // This doesn't prevent Load PRE. PHI translation will make the GEP available
  2422. // to the load by moving it to the predecessor block if necessary.
  2423. if (isa<GetElementPtrInst>(CurInst))
  2424. return false;
  2425. if (auto *CallB = dyn_cast<CallBase>(CurInst)) {
  2426. // We don't currently value number ANY inline asm calls.
  2427. if (CallB->isInlineAsm())
  2428. return false;
  2429. // Don't do PRE on convergent calls.
  2430. if (CallB->isConvergent())
  2431. return false;
  2432. }
  2433. uint32_t ValNo = VN.lookup(CurInst);
  2434. // Look for the predecessors for PRE opportunities. We're
  2435. // only trying to solve the basic diamond case, where
  2436. // a value is computed in the successor and one predecessor,
  2437. // but not the other. We also explicitly disallow cases
  2438. // where the successor is its own predecessor, because they're
  2439. // more complicated to get right.
  2440. unsigned NumWith = 0;
  2441. unsigned NumWithout = 0;
  2442. BasicBlock *PREPred = nullptr;
  2443. BasicBlock *CurrentBlock = CurInst->getParent();
  2444. // Update the RPO numbers for this function.
  2445. if (InvalidBlockRPONumbers)
  2446. assignBlockRPONumber(*CurrentBlock->getParent());
  2447. SmallVector<std::pair<Value *, BasicBlock *>, 8> predMap;
  2448. for (BasicBlock *P : predecessors(CurrentBlock)) {
  2449. // We're not interested in PRE where blocks with predecessors that are
  2450. // not reachable.
  2451. if (!DT->isReachableFromEntry(P)) {
  2452. NumWithout = 2;
  2453. break;
  2454. }
  2455. // It is not safe to do PRE when P->CurrentBlock is a loop backedge.
  2456. assert(BlockRPONumber.count(P) && BlockRPONumber.count(CurrentBlock) &&
  2457. "Invalid BlockRPONumber map.");
  2458. if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock]) {
  2459. NumWithout = 2;
  2460. break;
  2461. }
  2462. uint32_t TValNo = VN.phiTranslate(P, CurrentBlock, ValNo, *this);
  2463. Value *predV = findLeader(P, TValNo);
  2464. if (!predV) {
  2465. predMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P));
  2466. PREPred = P;
  2467. ++NumWithout;
  2468. } else if (predV == CurInst) {
  2469. /* CurInst dominates this predecessor. */
  2470. NumWithout = 2;
  2471. break;
  2472. } else {
  2473. predMap.push_back(std::make_pair(predV, P));
  2474. ++NumWith;
  2475. }
  2476. }
  2477. // Don't do PRE when it might increase code size, i.e. when
  2478. // we would need to insert instructions in more than one pred.
  2479. if (NumWithout > 1 || NumWith == 0)
  2480. return false;
  2481. // We may have a case where all predecessors have the instruction,
  2482. // and we just need to insert a phi node. Otherwise, perform
  2483. // insertion.
  2484. Instruction *PREInstr = nullptr;
  2485. if (NumWithout != 0) {
  2486. if (!isSafeToSpeculativelyExecute(CurInst)) {
  2487. // It is only valid to insert a new instruction if the current instruction
  2488. // is always executed. An instruction with implicit control flow could
  2489. // prevent us from doing it. If we cannot speculate the execution, then
  2490. // PRE should be prohibited.
  2491. if (ICF->isDominatedByICFIFromSameBlock(CurInst))
  2492. return false;
  2493. }
  2494. // Don't do PRE across indirect branch.
  2495. if (isa<IndirectBrInst>(PREPred->getTerminator()))
  2496. return false;
  2497. // We can't do PRE safely on a critical edge, so instead we schedule
  2498. // the edge to be split and perform the PRE the next time we iterate
  2499. // on the function.
  2500. unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
  2501. if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
  2502. toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
  2503. return false;
  2504. }
  2505. // We need to insert somewhere, so let's give it a shot
  2506. PREInstr = CurInst->clone();
  2507. if (!performScalarPREInsertion(PREInstr, PREPred, CurrentBlock, ValNo)) {
  2508. // If we failed insertion, make sure we remove the instruction.
  2509. LLVM_DEBUG(verifyRemoved(PREInstr));
  2510. PREInstr->deleteValue();
  2511. return false;
  2512. }
  2513. }
  2514. // Either we should have filled in the PRE instruction, or we should
  2515. // not have needed insertions.
  2516. assert(PREInstr != nullptr || NumWithout == 0);
  2517. ++NumGVNPRE;
  2518. // Create a PHI to make the value available in this block.
  2519. PHINode *Phi =
  2520. PHINode::Create(CurInst->getType(), predMap.size(),
  2521. CurInst->getName() + ".pre-phi", &CurrentBlock->front());
  2522. for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
  2523. if (Value *V = predMap[i].first) {
  2524. // If we use an existing value in this phi, we have to patch the original
  2525. // value because the phi will be used to replace a later value.
  2526. patchReplacementInstruction(CurInst, V);
  2527. Phi->addIncoming(V, predMap[i].second);
  2528. } else
  2529. Phi->addIncoming(PREInstr, PREPred);
  2530. }
  2531. VN.add(Phi, ValNo);
  2532. // After creating a new PHI for ValNo, the phi translate result for ValNo will
  2533. // be changed, so erase the related stale entries in phi translate cache.
  2534. VN.eraseTranslateCacheEntry(ValNo, *CurrentBlock);
  2535. addToLeaderTable(ValNo, Phi, CurrentBlock);
  2536. Phi->setDebugLoc(CurInst->getDebugLoc());
  2537. CurInst->replaceAllUsesWith(Phi);
  2538. if (MD && Phi->getType()->isPtrOrPtrVectorTy())
  2539. MD->invalidateCachedPointerInfo(Phi);
  2540. VN.erase(CurInst);
  2541. removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
  2542. LLVM_DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
  2543. if (MD)
  2544. MD->removeInstruction(CurInst);
  2545. if (MSSAU)
  2546. MSSAU->removeMemoryAccess(CurInst);
  2547. LLVM_DEBUG(verifyRemoved(CurInst));
  2548. // FIXME: Intended to be markInstructionForDeletion(CurInst), but it causes
  2549. // some assertion failures.
  2550. ICF->removeInstruction(CurInst);
  2551. CurInst->eraseFromParent();
  2552. ++NumGVNInstr;
  2553. return true;
  2554. }
  2555. /// Perform a purely local form of PRE that looks for diamond
  2556. /// control flow patterns and attempts to perform simple PRE at the join point.
  2557. bool GVNPass::performPRE(Function &F) {
  2558. bool Changed = false;
  2559. for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) {
  2560. // Nothing to PRE in the entry block.
  2561. if (CurrentBlock == &F.getEntryBlock())
  2562. continue;
  2563. // Don't perform PRE on an EH pad.
  2564. if (CurrentBlock->isEHPad())
  2565. continue;
  2566. for (BasicBlock::iterator BI = CurrentBlock->begin(),
  2567. BE = CurrentBlock->end();
  2568. BI != BE;) {
  2569. Instruction *CurInst = &*BI++;
  2570. Changed |= performScalarPRE(CurInst);
  2571. }
  2572. }
  2573. if (splitCriticalEdges())
  2574. Changed = true;
  2575. return Changed;
  2576. }
  2577. /// Split the critical edge connecting the given two blocks, and return
  2578. /// the block inserted to the critical edge.
  2579. BasicBlock *GVNPass::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
  2580. // GVN does not require loop-simplify, do not try to preserve it if it is not
  2581. // possible.
  2582. BasicBlock *BB = SplitCriticalEdge(
  2583. Pred, Succ,
  2584. CriticalEdgeSplittingOptions(DT, LI, MSSAU).unsetPreserveLoopSimplify());
  2585. if (BB) {
  2586. if (MD)
  2587. MD->invalidateCachedPredecessors();
  2588. InvalidBlockRPONumbers = true;
  2589. }
  2590. return BB;
  2591. }
  2592. /// Split critical edges found during the previous
  2593. /// iteration that may enable further optimization.
  2594. bool GVNPass::splitCriticalEdges() {
  2595. if (toSplit.empty())
  2596. return false;
  2597. bool Changed = false;
  2598. do {
  2599. std::pair<Instruction *, unsigned> Edge = toSplit.pop_back_val();
  2600. Changed |= SplitCriticalEdge(Edge.first, Edge.second,
  2601. CriticalEdgeSplittingOptions(DT, LI, MSSAU)) !=
  2602. nullptr;
  2603. } while (!toSplit.empty());
  2604. if (Changed) {
  2605. if (MD)
  2606. MD->invalidateCachedPredecessors();
  2607. InvalidBlockRPONumbers = true;
  2608. }
  2609. return Changed;
  2610. }
  2611. /// Executes one iteration of GVN
  2612. bool GVNPass::iterateOnFunction(Function &F) {
  2613. cleanupGlobalSets();
  2614. // Top-down walk of the dominator tree
  2615. bool Changed = false;
  2616. // Needed for value numbering with phi construction to work.
  2617. // RPOT walks the graph in its constructor and will not be invalidated during
  2618. // processBlock.
  2619. ReversePostOrderTraversal<Function *> RPOT(&F);
  2620. for (BasicBlock *BB : RPOT)
  2621. Changed |= processBlock(BB);
  2622. return Changed;
  2623. }
  2624. void GVNPass::cleanupGlobalSets() {
  2625. VN.clear();
  2626. LeaderTable.clear();
  2627. BlockRPONumber.clear();
  2628. TableAllocator.Reset();
  2629. ICF->clear();
  2630. InvalidBlockRPONumbers = true;
  2631. }
  2632. /// Verify that the specified instruction does not occur in our
  2633. /// internal data structures.
  2634. void GVNPass::verifyRemoved(const Instruction *Inst) const {
  2635. VN.verifyRemoved(Inst);
  2636. // Walk through the value number scope to make sure the instruction isn't
  2637. // ferreted away in it.
  2638. for (const auto &I : LeaderTable) {
  2639. const LeaderTableEntry *Node = &I.second;
  2640. assert(Node->Val != Inst && "Inst still in value numbering scope!");
  2641. while (Node->Next) {
  2642. Node = Node->Next;
  2643. assert(Node->Val != Inst && "Inst still in value numbering scope!");
  2644. }
  2645. }
  2646. }
  2647. /// BB is declared dead, which implied other blocks become dead as well. This
  2648. /// function is to add all these blocks to "DeadBlocks". For the dead blocks'
  2649. /// live successors, update their phi nodes by replacing the operands
  2650. /// corresponding to dead blocks with UndefVal.
  2651. void GVNPass::addDeadBlock(BasicBlock *BB) {
  2652. SmallVector<BasicBlock *, 4> NewDead;
  2653. SmallSetVector<BasicBlock *, 4> DF;
  2654. NewDead.push_back(BB);
  2655. while (!NewDead.empty()) {
  2656. BasicBlock *D = NewDead.pop_back_val();
  2657. if (DeadBlocks.count(D))
  2658. continue;
  2659. // All blocks dominated by D are dead.
  2660. SmallVector<BasicBlock *, 8> Dom;
  2661. DT->getDescendants(D, Dom);
  2662. DeadBlocks.insert(Dom.begin(), Dom.end());
  2663. // Figure out the dominance-frontier(D).
  2664. for (BasicBlock *B : Dom) {
  2665. for (BasicBlock *S : successors(B)) {
  2666. if (DeadBlocks.count(S))
  2667. continue;
  2668. bool AllPredDead = true;
  2669. for (BasicBlock *P : predecessors(S))
  2670. if (!DeadBlocks.count(P)) {
  2671. AllPredDead = false;
  2672. break;
  2673. }
  2674. if (!AllPredDead) {
  2675. // S could be proved dead later on. That is why we don't update phi
  2676. // operands at this moment.
  2677. DF.insert(S);
  2678. } else {
  2679. // While S is not dominated by D, it is dead by now. This could take
  2680. // place if S already have a dead predecessor before D is declared
  2681. // dead.
  2682. NewDead.push_back(S);
  2683. }
  2684. }
  2685. }
  2686. }
  2687. // For the dead blocks' live successors, update their phi nodes by replacing
  2688. // the operands corresponding to dead blocks with UndefVal.
  2689. for (BasicBlock *B : DF) {
  2690. if (DeadBlocks.count(B))
  2691. continue;
  2692. // First, split the critical edges. This might also create additional blocks
  2693. // to preserve LoopSimplify form and adjust edges accordingly.
  2694. SmallVector<BasicBlock *, 4> Preds(predecessors(B));
  2695. for (BasicBlock *P : Preds) {
  2696. if (!DeadBlocks.count(P))
  2697. continue;
  2698. if (llvm::is_contained(successors(P), B) &&
  2699. isCriticalEdge(P->getTerminator(), B)) {
  2700. if (BasicBlock *S = splitCriticalEdges(P, B))
  2701. DeadBlocks.insert(P = S);
  2702. }
  2703. }
  2704. // Now poison the incoming values from the dead predecessors.
  2705. for (BasicBlock *P : predecessors(B)) {
  2706. if (!DeadBlocks.count(P))
  2707. continue;
  2708. for (PHINode &Phi : B->phis()) {
  2709. Phi.setIncomingValueForBlock(P, PoisonValue::get(Phi.getType()));
  2710. if (MD)
  2711. MD->invalidateCachedPointerInfo(&Phi);
  2712. }
  2713. }
  2714. }
  2715. }
  2716. // If the given branch is recognized as a foldable branch (i.e. conditional
  2717. // branch with constant condition), it will perform following analyses and
  2718. // transformation.
  2719. // 1) If the dead out-coming edge is a critical-edge, split it. Let
  2720. // R be the target of the dead out-coming edge.
  2721. // 1) Identify the set of dead blocks implied by the branch's dead outcoming
  2722. // edge. The result of this step will be {X| X is dominated by R}
  2723. // 2) Identify those blocks which haves at least one dead predecessor. The
  2724. // result of this step will be dominance-frontier(R).
  2725. // 3) Update the PHIs in DF(R) by replacing the operands corresponding to
  2726. // dead blocks with "UndefVal" in an hope these PHIs will optimized away.
  2727. //
  2728. // Return true iff *NEW* dead code are found.
  2729. bool GVNPass::processFoldableCondBr(BranchInst *BI) {
  2730. if (!BI || BI->isUnconditional())
  2731. return false;
  2732. // If a branch has two identical successors, we cannot declare either dead.
  2733. if (BI->getSuccessor(0) == BI->getSuccessor(1))
  2734. return false;
  2735. ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
  2736. if (!Cond)
  2737. return false;
  2738. BasicBlock *DeadRoot =
  2739. Cond->getZExtValue() ? BI->getSuccessor(1) : BI->getSuccessor(0);
  2740. if (DeadBlocks.count(DeadRoot))
  2741. return false;
  2742. if (!DeadRoot->getSinglePredecessor())
  2743. DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
  2744. addDeadBlock(DeadRoot);
  2745. return true;
  2746. }
  2747. // performPRE() will trigger assert if it comes across an instruction without
  2748. // associated val-num. As it normally has far more live instructions than dead
  2749. // instructions, it makes more sense just to "fabricate" a val-number for the
  2750. // dead code than checking if instruction involved is dead or not.
  2751. void GVNPass::assignValNumForDeadCode() {
  2752. for (BasicBlock *BB : DeadBlocks) {
  2753. for (Instruction &Inst : *BB) {
  2754. unsigned ValNum = VN.lookupOrAdd(&Inst);
  2755. addToLeaderTable(ValNum, &Inst, BB);
  2756. }
  2757. }
  2758. }
  2759. class llvm::gvn::GVNLegacyPass : public FunctionPass {
  2760. public:
  2761. static char ID; // Pass identification, replacement for typeid
  2762. explicit GVNLegacyPass(bool NoMemDepAnalysis = !GVNEnableMemDep)
  2763. : FunctionPass(ID), Impl(GVNOptions().setMemDep(!NoMemDepAnalysis)) {
  2764. initializeGVNLegacyPassPass(*PassRegistry::getPassRegistry());
  2765. }
  2766. bool runOnFunction(Function &F) override {
  2767. if (skipFunction(F))
  2768. return false;
  2769. auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
  2770. auto *MSSAWP = getAnalysisIfAvailable<MemorySSAWrapperPass>();
  2771. return Impl.runImpl(
  2772. F, getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
  2773. getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
  2774. getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
  2775. getAnalysis<AAResultsWrapperPass>().getAAResults(),
  2776. Impl.isMemDepEnabled()
  2777. ? &getAnalysis<MemoryDependenceWrapperPass>().getMemDep()
  2778. : nullptr,
  2779. LIWP ? &LIWP->getLoopInfo() : nullptr,
  2780. &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(),
  2781. MSSAWP ? &MSSAWP->getMSSA() : nullptr);
  2782. }
  2783. void getAnalysisUsage(AnalysisUsage &AU) const override {
  2784. AU.addRequired<AssumptionCacheTracker>();
  2785. AU.addRequired<DominatorTreeWrapperPass>();
  2786. AU.addRequired<TargetLibraryInfoWrapperPass>();
  2787. AU.addRequired<LoopInfoWrapperPass>();
  2788. if (Impl.isMemDepEnabled())
  2789. AU.addRequired<MemoryDependenceWrapperPass>();
  2790. AU.addRequired<AAResultsWrapperPass>();
  2791. AU.addPreserved<DominatorTreeWrapperPass>();
  2792. AU.addPreserved<GlobalsAAWrapperPass>();
  2793. AU.addPreserved<TargetLibraryInfoWrapperPass>();
  2794. AU.addPreserved<LoopInfoWrapperPass>();
  2795. AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
  2796. AU.addPreserved<MemorySSAWrapperPass>();
  2797. }
  2798. private:
  2799. GVNPass Impl;
  2800. };
  2801. char GVNLegacyPass::ID = 0;
  2802. INITIALIZE_PASS_BEGIN(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
  2803. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  2804. INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
  2805. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  2806. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  2807. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  2808. INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
  2809. INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
  2810. INITIALIZE_PASS_END(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
  2811. // The public interface to this file...
  2812. FunctionPass *llvm::createGVNPass(bool NoMemDepAnalysis) {
  2813. return new GVNLegacyPass(NoMemDepAnalysis);
  2814. }