GVN.cpp 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850
  1. //===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass performs global value numbering to eliminate fully redundant
  11. // instructions. It also performs simple dead load elimination.
  12. //
  13. // Note that this pass does the value numbering itself; it does not use the
  14. // ValueNumbering analysis passes.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/Transforms/Scalar.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/DepthFirstIterator.h"
  20. #include "llvm/ADT/Hashing.h"
  21. #include "llvm/ADT/MapVector.h"
  22. #include "llvm/ADT/PostOrderIterator.h"
  23. #include "llvm/ADT/SetVector.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/Statistic.h"
  26. #include "llvm/Analysis/AliasAnalysis.h"
  27. #include "llvm/Analysis/AssumptionCache.h"
  28. #include "llvm/Analysis/CFG.h"
  29. #include "llvm/Analysis/ConstantFolding.h"
  30. #include "llvm/Analysis/InstructionSimplify.h"
  31. #include "llvm/Analysis/Loads.h"
  32. #include "llvm/Analysis/MemoryBuiltins.h"
  33. #include "llvm/Analysis/MemoryDependenceAnalysis.h"
  34. #include "llvm/Analysis/PHITransAddr.h"
  35. #include "llvm/Analysis/TargetLibraryInfo.h"
  36. #include "llvm/Analysis/ValueTracking.h"
  37. #include "llvm/IR/DataLayout.h"
  38. #include "llvm/IR/Dominators.h"
  39. #include "llvm/IR/GlobalVariable.h"
  40. #include "llvm/IR/IRBuilder.h"
  41. #include "llvm/IR/IntrinsicInst.h"
  42. #include "llvm/IR/LLVMContext.h"
  43. #include "llvm/IR/Metadata.h"
  44. #include "llvm/IR/PatternMatch.h"
  45. #include "llvm/Support/Allocator.h"
  46. #include "llvm/Support/CommandLine.h"
  47. #include "llvm/Support/Debug.h"
  48. #include "llvm/Support/raw_ostream.h"
  49. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  50. #include "llvm/Transforms/Utils/Local.h"
  51. #include "llvm/Transforms/Utils/SSAUpdater.h"
  52. #include <vector>
  53. #include "dxc/HLSL/DxilConstants.h" // HLSL Change
  54. using namespace llvm;
  55. using namespace PatternMatch;
  56. #define DEBUG_TYPE "gvn"
  57. STATISTIC(NumGVNInstr, "Number of instructions deleted");
  58. STATISTIC(NumGVNLoad, "Number of loads deleted");
  59. STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
  60. STATISTIC(NumGVNBlocks, "Number of blocks merged");
  61. STATISTIC(NumGVNSimpl, "Number of instructions simplified");
  62. STATISTIC(NumGVNEqProp, "Number of equalities propagated");
  63. STATISTIC(NumPRELoad, "Number of loads PRE'd");
  64. static cl::opt<bool> EnablePRE("enable-pre",
  65. cl::init(true), cl::Hidden);
  66. static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
  67. // Maximum allowed recursion depth.
  68. static cl::opt<uint32_t>
  69. MaxRecurseDepth("max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore,
  70. cl::desc("Max recurse depth (default = 1000)"));
  71. //===----------------------------------------------------------------------===//
  72. // ValueTable Class
  73. //===----------------------------------------------------------------------===//
  74. /// This class holds the mapping between values and value numbers. It is used
  75. /// as an efficient mechanism to determine the expression-wise equivalence of
  76. /// two values.
  77. namespace {
  78. struct Expression {
  79. uint32_t opcode;
  80. Type *type;
  81. SmallVector<uint32_t, 4> varargs;
  82. Expression(uint32_t o = ~2U) : opcode(o) { }
  83. bool operator==(const Expression &other) const {
  84. if (opcode != other.opcode)
  85. return false;
  86. if (opcode == ~0U || opcode == ~1U)
  87. return true;
  88. if (type != other.type)
  89. return false;
  90. if (varargs != other.varargs)
  91. return false;
  92. return true;
  93. }
  94. friend hash_code hash_value(const Expression &Value) {
  95. return hash_combine(Value.opcode, Value.type,
  96. hash_combine_range(Value.varargs.begin(),
  97. Value.varargs.end()));
  98. }
  99. };
  100. class ValueTable {
  101. DenseMap<Value*, uint32_t> valueNumbering;
  102. DenseMap<Expression, uint32_t> expressionNumbering;
  103. AliasAnalysis *AA;
  104. MemoryDependenceAnalysis *MD;
  105. DominatorTree *DT;
  106. uint32_t nextValueNumber;
  107. Expression create_expression(Instruction* I);
  108. Expression create_cmp_expression(unsigned Opcode,
  109. CmpInst::Predicate Predicate,
  110. Value *LHS, Value *RHS);
  111. Expression create_extractvalue_expression(ExtractValueInst* EI);
  112. uint32_t lookup_or_add_call(CallInst* C);
  113. public:
  114. ValueTable() : nextValueNumber(1) { }
  115. uint32_t lookup_or_add(Value *V);
  116. uint32_t lookup(Value *V) const;
  117. uint32_t lookup_or_add_cmp(unsigned Opcode, CmpInst::Predicate Pred,
  118. Value *LHS, Value *RHS);
  119. void add(Value *V, uint32_t num);
  120. void clear();
  121. void erase(Value *v);
  122. void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
  123. AliasAnalysis *getAliasAnalysis() const { return AA; }
  124. void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
  125. void setDomTree(DominatorTree* D) { DT = D; }
  126. uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
  127. void verifyRemoved(const Value *) const;
  128. };
  129. }
  130. namespace llvm {
  131. template <> struct DenseMapInfo<Expression> {
  132. static inline Expression getEmptyKey() {
  133. return ~0U;
  134. }
  135. static inline Expression getTombstoneKey() {
  136. return ~1U;
  137. }
  138. static unsigned getHashValue(const Expression e) {
  139. using llvm::hash_value;
  140. return static_cast<unsigned>(hash_value(e));
  141. }
  142. static bool isEqual(const Expression &LHS, const Expression &RHS) {
  143. return LHS == RHS;
  144. }
  145. };
  146. }
  147. //===----------------------------------------------------------------------===//
  148. // ValueTable Internal Functions
  149. //===----------------------------------------------------------------------===//
  150. Expression ValueTable::create_expression(Instruction *I) {
  151. Expression e;
  152. e.type = I->getType();
  153. e.opcode = I->getOpcode();
  154. for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
  155. OI != OE; ++OI)
  156. e.varargs.push_back(lookup_or_add(*OI));
  157. if (I->isCommutative()) {
  158. // Ensure that commutative instructions that only differ by a permutation
  159. // of their operands get the same value number by sorting the operand value
  160. // numbers. Since all commutative instructions have two operands it is more
  161. // efficient to sort by hand rather than using, say, std::sort.
  162. assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
  163. if (e.varargs[0] > e.varargs[1])
  164. std::swap(e.varargs[0], e.varargs[1]);
  165. }
  166. if (CmpInst *C = dyn_cast<CmpInst>(I)) {
  167. // Sort the operand value numbers so x<y and y>x get the same value number.
  168. CmpInst::Predicate Predicate = C->getPredicate();
  169. if (e.varargs[0] > e.varargs[1]) {
  170. std::swap(e.varargs[0], e.varargs[1]);
  171. Predicate = CmpInst::getSwappedPredicate(Predicate);
  172. }
  173. e.opcode = (C->getOpcode() << 8) | Predicate;
  174. } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
  175. for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
  176. II != IE; ++II)
  177. e.varargs.push_back(*II);
  178. }
  179. return e;
  180. }
  181. Expression ValueTable::create_cmp_expression(unsigned Opcode,
  182. CmpInst::Predicate Predicate,
  183. Value *LHS, Value *RHS) {
  184. assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
  185. "Not a comparison!");
  186. Expression e;
  187. e.type = CmpInst::makeCmpResultType(LHS->getType());
  188. e.varargs.push_back(lookup_or_add(LHS));
  189. e.varargs.push_back(lookup_or_add(RHS));
  190. // Sort the operand value numbers so x<y and y>x get the same value number.
  191. if (e.varargs[0] > e.varargs[1]) {
  192. std::swap(e.varargs[0], e.varargs[1]);
  193. Predicate = CmpInst::getSwappedPredicate(Predicate);
  194. }
  195. e.opcode = (Opcode << 8) | Predicate;
  196. return e;
  197. }
  198. Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI) {
  199. assert(EI && "Not an ExtractValueInst?");
  200. Expression e;
  201. e.type = EI->getType();
  202. e.opcode = 0;
  203. IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
  204. if (I != nullptr && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
  205. // EI might be an extract from one of our recognised intrinsics. If it
  206. // is we'll synthesize a semantically equivalent expression instead on
  207. // an extract value expression.
  208. switch (I->getIntrinsicID()) {
  209. case Intrinsic::sadd_with_overflow:
  210. case Intrinsic::uadd_with_overflow:
  211. e.opcode = Instruction::Add;
  212. break;
  213. case Intrinsic::ssub_with_overflow:
  214. case Intrinsic::usub_with_overflow:
  215. e.opcode = Instruction::Sub;
  216. break;
  217. case Intrinsic::smul_with_overflow:
  218. case Intrinsic::umul_with_overflow:
  219. e.opcode = Instruction::Mul;
  220. break;
  221. default:
  222. break;
  223. }
  224. if (e.opcode != 0) {
  225. // Intrinsic recognized. Grab its args to finish building the expression.
  226. assert(I->getNumArgOperands() == 2 &&
  227. "Expect two args for recognised intrinsics.");
  228. e.varargs.push_back(lookup_or_add(I->getArgOperand(0)));
  229. e.varargs.push_back(lookup_or_add(I->getArgOperand(1)));
  230. return e;
  231. }
  232. }
  233. // Not a recognised intrinsic. Fall back to producing an extract value
  234. // expression.
  235. e.opcode = EI->getOpcode();
  236. for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
  237. OI != OE; ++OI)
  238. e.varargs.push_back(lookup_or_add(*OI));
  239. for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
  240. II != IE; ++II)
  241. e.varargs.push_back(*II);
  242. return e;
  243. }
  244. //===----------------------------------------------------------------------===//
  245. // ValueTable External Functions
  246. //===----------------------------------------------------------------------===//
  247. /// add - Insert a value into the table with a specified value number.
  248. void ValueTable::add(Value *V, uint32_t num) {
  249. valueNumbering.insert(std::make_pair(V, num));
  250. }
  251. uint32_t ValueTable::lookup_or_add_call(CallInst *C) {
  252. if (AA->doesNotAccessMemory(C)) {
  253. Expression exp = create_expression(C);
  254. uint32_t &e = expressionNumbering[exp];
  255. if (!e) e = nextValueNumber++;
  256. valueNumbering[C] = e;
  257. return e;
  258. } else if (AA->onlyReadsMemory(C)) {
  259. Expression exp = create_expression(C);
  260. uint32_t &e = expressionNumbering[exp];
  261. if (!e) {
  262. e = nextValueNumber++;
  263. valueNumbering[C] = e;
  264. return e;
  265. }
  266. if (!MD) {
  267. e = nextValueNumber++;
  268. valueNumbering[C] = e;
  269. return e;
  270. }
  271. MemDepResult local_dep = MD->getDependency(C);
  272. if (!local_dep.isDef() && !local_dep.isNonLocal()) {
  273. valueNumbering[C] = nextValueNumber;
  274. return nextValueNumber++;
  275. }
  276. if (local_dep.isDef()) {
  277. CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
  278. if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
  279. valueNumbering[C] = nextValueNumber;
  280. return nextValueNumber++;
  281. }
  282. for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
  283. uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
  284. uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
  285. if (c_vn != cd_vn) {
  286. valueNumbering[C] = nextValueNumber;
  287. return nextValueNumber++;
  288. }
  289. }
  290. uint32_t v = lookup_or_add(local_cdep);
  291. valueNumbering[C] = v;
  292. return v;
  293. }
  294. // Non-local case.
  295. const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
  296. MD->getNonLocalCallDependency(CallSite(C));
  297. // FIXME: Move the checking logic to MemDep!
  298. CallInst* cdep = nullptr;
  299. // Check to see if we have a single dominating call instruction that is
  300. // identical to C.
  301. for (unsigned i = 0, e = deps.size(); i != e; ++i) {
  302. const NonLocalDepEntry *I = &deps[i];
  303. if (I->getResult().isNonLocal())
  304. continue;
  305. // We don't handle non-definitions. If we already have a call, reject
  306. // instruction dependencies.
  307. if (!I->getResult().isDef() || cdep != nullptr) {
  308. cdep = nullptr;
  309. break;
  310. }
  311. CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
  312. // FIXME: All duplicated with non-local case.
  313. if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
  314. cdep = NonLocalDepCall;
  315. continue;
  316. }
  317. cdep = nullptr;
  318. break;
  319. }
  320. if (!cdep) {
  321. valueNumbering[C] = nextValueNumber;
  322. return nextValueNumber++;
  323. }
  324. if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
  325. valueNumbering[C] = nextValueNumber;
  326. return nextValueNumber++;
  327. }
  328. for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
  329. uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
  330. uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
  331. if (c_vn != cd_vn) {
  332. valueNumbering[C] = nextValueNumber;
  333. return nextValueNumber++;
  334. }
  335. }
  336. uint32_t v = lookup_or_add(cdep);
  337. valueNumbering[C] = v;
  338. return v;
  339. } else {
  340. valueNumbering[C] = nextValueNumber;
  341. return nextValueNumber++;
  342. }
  343. }
  344. /// lookup_or_add - Returns the value number for the specified value, assigning
  345. /// it a new number if it did not have one before.
  346. uint32_t ValueTable::lookup_or_add(Value *V) {
  347. DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
  348. if (VI != valueNumbering.end())
  349. return VI->second;
  350. if (!isa<Instruction>(V)) {
  351. valueNumbering[V] = nextValueNumber;
  352. return nextValueNumber++;
  353. }
  354. Instruction* I = cast<Instruction>(V);
  355. Expression exp;
  356. switch (I->getOpcode()) {
  357. case Instruction::Call:
  358. return lookup_or_add_call(cast<CallInst>(I));
  359. case Instruction::Add:
  360. case Instruction::FAdd:
  361. case Instruction::Sub:
  362. case Instruction::FSub:
  363. case Instruction::Mul:
  364. case Instruction::FMul:
  365. case Instruction::UDiv:
  366. case Instruction::SDiv:
  367. case Instruction::FDiv:
  368. case Instruction::URem:
  369. case Instruction::SRem:
  370. case Instruction::FRem:
  371. case Instruction::Shl:
  372. case Instruction::LShr:
  373. case Instruction::AShr:
  374. case Instruction::And:
  375. case Instruction::Or:
  376. case Instruction::Xor:
  377. case Instruction::ICmp:
  378. case Instruction::FCmp:
  379. case Instruction::Trunc:
  380. case Instruction::ZExt:
  381. case Instruction::SExt:
  382. case Instruction::FPToUI:
  383. case Instruction::FPToSI:
  384. case Instruction::UIToFP:
  385. case Instruction::SIToFP:
  386. case Instruction::FPTrunc:
  387. case Instruction::FPExt:
  388. case Instruction::PtrToInt:
  389. case Instruction::IntToPtr:
  390. case Instruction::BitCast:
  391. case Instruction::Select:
  392. case Instruction::ExtractElement:
  393. case Instruction::InsertElement:
  394. case Instruction::ShuffleVector:
  395. case Instruction::InsertValue:
  396. case Instruction::GetElementPtr:
  397. exp = create_expression(I);
  398. break;
  399. case Instruction::ExtractValue:
  400. exp = create_extractvalue_expression(cast<ExtractValueInst>(I));
  401. break;
  402. default:
  403. valueNumbering[V] = nextValueNumber;
  404. return nextValueNumber++;
  405. }
  406. uint32_t& e = expressionNumbering[exp];
  407. if (!e) e = nextValueNumber++;
  408. valueNumbering[V] = e;
  409. return e;
  410. }
  411. /// Returns the value number of the specified value. Fails if
  412. /// the value has not yet been numbered.
  413. uint32_t ValueTable::lookup(Value *V) const {
  414. DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
  415. assert(VI != valueNumbering.end() && "Value not numbered?");
  416. return VI->second;
  417. }
  418. /// Returns the value number of the given comparison,
  419. /// assigning it a new number if it did not have one before. Useful when
  420. /// we deduced the result of a comparison, but don't immediately have an
  421. /// instruction realizing that comparison to hand.
  422. uint32_t ValueTable::lookup_or_add_cmp(unsigned Opcode,
  423. CmpInst::Predicate Predicate,
  424. Value *LHS, Value *RHS) {
  425. Expression exp = create_cmp_expression(Opcode, Predicate, LHS, RHS);
  426. uint32_t& e = expressionNumbering[exp];
  427. if (!e) e = nextValueNumber++;
  428. return e;
  429. }
  430. /// Remove all entries from the ValueTable.
  431. void ValueTable::clear() {
  432. valueNumbering.clear();
  433. expressionNumbering.clear();
  434. nextValueNumber = 1;
  435. }
  436. /// Remove a value from the value numbering.
  437. void ValueTable::erase(Value *V) {
  438. valueNumbering.erase(V);
  439. }
  440. /// verifyRemoved - Verify that the value is removed from all internal data
  441. /// structures.
  442. void ValueTable::verifyRemoved(const Value *V) const {
  443. for (DenseMap<Value*, uint32_t>::const_iterator
  444. I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
  445. assert(I->first != V && "Inst still occurs in value numbering map!");
  446. }
  447. }
  448. //===----------------------------------------------------------------------===//
  449. // GVN Pass
  450. //===----------------------------------------------------------------------===//
  451. namespace {
  452. class GVN;
  453. struct AvailableValueInBlock {
  454. /// BB - The basic block in question.
  455. BasicBlock *BB;
  456. enum ValType {
  457. SimpleVal, // A simple offsetted value that is accessed.
  458. LoadVal, // A value produced by a load.
  459. MemIntrin, // A memory intrinsic which is loaded from.
  460. UndefVal // A UndefValue representing a value from dead block (which
  461. // is not yet physically removed from the CFG).
  462. };
  463. /// V - The value that is live out of the block.
  464. PointerIntPair<Value *, 2, ValType> Val;
  465. /// Offset - The byte offset in Val that is interesting for the load query.
  466. unsigned Offset;
  467. static AvailableValueInBlock get(BasicBlock *BB, Value *V,
  468. unsigned Offset = 0) {
  469. AvailableValueInBlock Res;
  470. Res.BB = BB;
  471. Res.Val.setPointer(V);
  472. Res.Val.setInt(SimpleVal);
  473. Res.Offset = Offset;
  474. return Res;
  475. }
  476. static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
  477. unsigned Offset = 0) {
  478. AvailableValueInBlock Res;
  479. Res.BB = BB;
  480. Res.Val.setPointer(MI);
  481. Res.Val.setInt(MemIntrin);
  482. Res.Offset = Offset;
  483. return Res;
  484. }
  485. static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
  486. unsigned Offset = 0) {
  487. AvailableValueInBlock Res;
  488. Res.BB = BB;
  489. Res.Val.setPointer(LI);
  490. Res.Val.setInt(LoadVal);
  491. Res.Offset = Offset;
  492. return Res;
  493. }
  494. static AvailableValueInBlock getUndef(BasicBlock *BB) {
  495. AvailableValueInBlock Res;
  496. Res.BB = BB;
  497. Res.Val.setPointer(nullptr);
  498. Res.Val.setInt(UndefVal);
  499. Res.Offset = 0;
  500. return Res;
  501. }
  502. bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
  503. bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
  504. bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
  505. bool isUndefValue() const { return Val.getInt() == UndefVal; }
  506. Value *getSimpleValue() const {
  507. assert(isSimpleValue() && "Wrong accessor");
  508. return Val.getPointer();
  509. }
  510. LoadInst *getCoercedLoadValue() const {
  511. assert(isCoercedLoadValue() && "Wrong accessor");
  512. return cast<LoadInst>(Val.getPointer());
  513. }
  514. MemIntrinsic *getMemIntrinValue() const {
  515. assert(isMemIntrinValue() && "Wrong accessor");
  516. return cast<MemIntrinsic>(Val.getPointer());
  517. }
  518. /// Emit code into this block to adjust the value defined here to the
  519. /// specified type. This handles various coercion cases.
  520. Value *MaterializeAdjustedValue(LoadInst *LI, GVN &gvn) const;
  521. };
  522. class GVN : public FunctionPass {
  523. bool NoLoads;
  524. MemoryDependenceAnalysis *MD;
  525. DominatorTree *DT;
  526. const TargetLibraryInfo *TLI;
  527. AssumptionCache *AC;
  528. SetVector<BasicBlock *> DeadBlocks;
  529. ValueTable VN;
  530. /// A mapping from value numbers to lists of Value*'s that
  531. /// have that value number. Use findLeader to query it.
  532. struct LeaderTableEntry {
  533. Value *Val;
  534. const BasicBlock *BB;
  535. LeaderTableEntry *Next;
  536. };
  537. DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
  538. BumpPtrAllocator TableAllocator;
  539. SmallVector<Instruction*, 8> InstrsToErase;
  540. typedef SmallVector<NonLocalDepResult, 64> LoadDepVect;
  541. typedef SmallVector<AvailableValueInBlock, 64> AvailValInBlkVect;
  542. typedef SmallVector<BasicBlock*, 64> UnavailBlkVect;
  543. public:
  544. static char ID; // Pass identification, replacement for typeid
  545. explicit GVN(bool noloads = false)
  546. : FunctionPass(ID), NoLoads(noloads), MD(nullptr) {
  547. initializeGVNPass(*PassRegistry::getPassRegistry());
  548. }
  549. bool runOnFunction(Function &F) override;
  550. /// This removes the specified instruction from
  551. /// our various maps and marks it for deletion.
  552. void markInstructionForDeletion(Instruction *I) {
  553. VN.erase(I);
  554. InstrsToErase.push_back(I);
  555. }
  556. DominatorTree &getDominatorTree() const { return *DT; }
  557. AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
  558. MemoryDependenceAnalysis &getMemDep() const { return *MD; }
  559. private:
  560. /// Push a new Value to the LeaderTable onto the list for its value number.
  561. void addToLeaderTable(uint32_t N, Value *V, const BasicBlock *BB) {
  562. LeaderTableEntry &Curr = LeaderTable[N];
  563. if (!Curr.Val) {
  564. Curr.Val = V;
  565. Curr.BB = BB;
  566. return;
  567. }
  568. LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
  569. Node->Val = V;
  570. Node->BB = BB;
  571. Node->Next = Curr.Next;
  572. Curr.Next = Node;
  573. }
  574. /// Scan the list of values corresponding to a given
  575. /// value number, and remove the given instruction if encountered.
  576. void removeFromLeaderTable(uint32_t N, Instruction *I, BasicBlock *BB) {
  577. LeaderTableEntry* Prev = nullptr;
  578. LeaderTableEntry* Curr = &LeaderTable[N];
  579. while (Curr && (Curr->Val != I || Curr->BB != BB)) {
  580. Prev = Curr;
  581. Curr = Curr->Next;
  582. }
  583. if (!Curr)
  584. return;
  585. if (Prev) {
  586. Prev->Next = Curr->Next;
  587. } else {
  588. if (!Curr->Next) {
  589. Curr->Val = nullptr;
  590. Curr->BB = nullptr;
  591. } else {
  592. LeaderTableEntry* Next = Curr->Next;
  593. Curr->Val = Next->Val;
  594. Curr->BB = Next->BB;
  595. Curr->Next = Next->Next;
  596. }
  597. }
  598. }
  599. // List of critical edges to be split between iterations.
  600. SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
  601. // This transformation requires dominator postdominator info
  602. void getAnalysisUsage(AnalysisUsage &AU) const override {
  603. AU.addRequired<AssumptionCacheTracker>();
  604. AU.addRequired<DominatorTreeWrapperPass>();
  605. AU.addRequired<TargetLibraryInfoWrapperPass>();
  606. if (!NoLoads)
  607. AU.addRequired<MemoryDependenceAnalysis>();
  608. AU.addRequired<AliasAnalysis>();
  609. AU.addPreserved<DominatorTreeWrapperPass>();
  610. AU.addPreserved<AliasAnalysis>();
  611. }
  612. // Helper fuctions of redundant load elimination
  613. bool processLoad(LoadInst *L);
  614. bool processNonLocalLoad(LoadInst *L);
  615. void AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
  616. AvailValInBlkVect &ValuesPerBlock,
  617. UnavailBlkVect &UnavailableBlocks);
  618. bool PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
  619. UnavailBlkVect &UnavailableBlocks);
  620. // Other helper routines
  621. bool processInstruction(Instruction *I);
  622. bool processBlock(BasicBlock *BB);
  623. void dump(DenseMap<uint32_t, Value*> &d);
  624. bool iterateOnFunction(Function &F);
  625. bool performPRE(Function &F);
  626. bool performScalarPRE(Instruction *I);
  627. bool performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
  628. unsigned int ValNo);
  629. Value *findLeader(const BasicBlock *BB, uint32_t num);
  630. void cleanupGlobalSets();
  631. void verifyRemoved(const Instruction *I) const;
  632. bool splitCriticalEdges();
  633. BasicBlock *splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ);
  634. bool propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root);
  635. bool processFoldableCondBr(BranchInst *BI);
  636. void addDeadBlock(BasicBlock *BB);
  637. void assignValNumForDeadCode();
  638. };
  639. char GVN::ID = 0;
  640. }
  641. // The public interface to this file...
  642. FunctionPass *llvm::createGVNPass(bool NoLoads) {
  643. return new GVN(NoLoads);
  644. }
  645. INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
  646. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  647. INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
  648. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  649. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  650. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  651. INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
  652. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  653. void GVN::dump(DenseMap<uint32_t, Value*>& d) {
  654. errs() << "{\n";
  655. for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
  656. E = d.end(); I != E; ++I) {
  657. errs() << I->first << "\n";
  658. I->second->dump();
  659. }
  660. errs() << "}\n";
  661. }
  662. #endif
  663. /// Return true if we can prove that the value
  664. /// we're analyzing is fully available in the specified block. As we go, keep
  665. /// track of which blocks we know are fully alive in FullyAvailableBlocks. This
  666. /// map is actually a tri-state map with the following values:
  667. /// 0) we know the block *is not* fully available.
  668. /// 1) we know the block *is* fully available.
  669. /// 2) we do not know whether the block is fully available or not, but we are
  670. /// currently speculating that it will be.
  671. /// 3) we are speculating for this block and have used that to speculate for
  672. /// other blocks.
  673. static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
  674. DenseMap<BasicBlock*, char> &FullyAvailableBlocks,
  675. uint32_t RecurseDepth) {
  676. if (RecurseDepth > MaxRecurseDepth)
  677. return false;
  678. // Optimistically assume that the block is fully available and check to see
  679. // if we already know about this block in one lookup.
  680. std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
  681. FullyAvailableBlocks.insert(std::make_pair(BB, 2));
  682. // If the entry already existed for this block, return the precomputed value.
  683. if (!IV.second) {
  684. // If this is a speculative "available" value, mark it as being used for
  685. // speculation of other blocks.
  686. if (IV.first->second == 2)
  687. IV.first->second = 3;
  688. return IV.first->second != 0;
  689. }
  690. // Otherwise, see if it is fully available in all predecessors.
  691. pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
  692. // If this block has no predecessors, it isn't live-in here.
  693. if (PI == PE)
  694. goto SpeculationFailure;
  695. for (; PI != PE; ++PI)
  696. // If the value isn't fully available in one of our predecessors, then it
  697. // isn't fully available in this block either. Undo our previous
  698. // optimistic assumption and bail out.
  699. if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks,RecurseDepth+1))
  700. goto SpeculationFailure;
  701. return true;
  702. // If we get here, we found out that this is not, after
  703. // all, a fully-available block. We have a problem if we speculated on this and
  704. // used the speculation to mark other blocks as available.
  705. SpeculationFailure:
  706. char &BBVal = FullyAvailableBlocks[BB];
  707. // If we didn't speculate on this, just return with it set to false.
  708. if (BBVal == 2) {
  709. BBVal = 0;
  710. return false;
  711. }
  712. // If we did speculate on this value, we could have blocks set to 1 that are
  713. // incorrect. Walk the (transitive) successors of this block and mark them as
  714. // 0 if set to one.
  715. SmallVector<BasicBlock*, 32> BBWorklist;
  716. BBWorklist.push_back(BB);
  717. do {
  718. BasicBlock *Entry = BBWorklist.pop_back_val();
  719. // Note that this sets blocks to 0 (unavailable) if they happen to not
  720. // already be in FullyAvailableBlocks. This is safe.
  721. char &EntryVal = FullyAvailableBlocks[Entry];
  722. if (EntryVal == 0) continue; // Already unavailable.
  723. // Mark as unavailable.
  724. EntryVal = 0;
  725. BBWorklist.append(succ_begin(Entry), succ_end(Entry));
  726. } while (!BBWorklist.empty());
  727. return false;
  728. }
  729. /// Return true if CoerceAvailableValueToLoadType will succeed.
  730. static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
  731. Type *LoadTy,
  732. const DataLayout &DL) {
  733. // If the loaded or stored value is an first class array or struct, don't try
  734. // to transform them. We need to be able to bitcast to integer.
  735. if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
  736. StoredVal->getType()->isStructTy() ||
  737. StoredVal->getType()->isArrayTy())
  738. return false;
  739. // The store has to be at least as big as the load.
  740. if (DL.getTypeSizeInBits(StoredVal->getType()) <
  741. DL.getTypeSizeInBits(LoadTy))
  742. return false;
  743. return true;
  744. }
  745. /// If we saw a store of a value to memory, and
  746. /// then a load from a must-aliased pointer of a different type, try to coerce
  747. /// the stored value. LoadedTy is the type of the load we want to replace.
  748. /// IRB is IRBuilder used to insert new instructions.
  749. ///
  750. /// If we can't do it, return null.
  751. static Value *CoerceAvailableValueToLoadType(Value *StoredVal, Type *LoadedTy,
  752. IRBuilder<> &IRB,
  753. const DataLayout &DL) {
  754. if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, DL))
  755. return nullptr;
  756. // If this is already the right type, just return it.
  757. Type *StoredValTy = StoredVal->getType();
  758. uint64_t StoreSize = DL.getTypeSizeInBits(StoredValTy);
  759. uint64_t LoadSize = DL.getTypeSizeInBits(LoadedTy);
  760. // If the store and reload are the same size, we can always reuse it.
  761. if (StoreSize == LoadSize) {
  762. // Pointer to Pointer -> use bitcast.
  763. if (StoredValTy->getScalarType()->isPointerTy() &&
  764. LoadedTy->getScalarType()->isPointerTy())
  765. return IRB.CreateBitCast(StoredVal, LoadedTy);
  766. // Convert source pointers to integers, which can be bitcast.
  767. if (StoredValTy->getScalarType()->isPointerTy()) {
  768. StoredValTy = DL.getIntPtrType(StoredValTy);
  769. StoredVal = IRB.CreatePtrToInt(StoredVal, StoredValTy);
  770. }
  771. Type *TypeToCastTo = LoadedTy;
  772. if (TypeToCastTo->getScalarType()->isPointerTy())
  773. TypeToCastTo = DL.getIntPtrType(TypeToCastTo);
  774. if (StoredValTy != TypeToCastTo)
  775. StoredVal = IRB.CreateBitCast(StoredVal, TypeToCastTo);
  776. // Cast to pointer if the load needs a pointer type.
  777. if (LoadedTy->getScalarType()->isPointerTy())
  778. StoredVal = IRB.CreateIntToPtr(StoredVal, LoadedTy);
  779. return StoredVal;
  780. }
  781. // If the loaded value is smaller than the available value, then we can
  782. // extract out a piece from it. If the available value is too small, then we
  783. // can't do anything.
  784. assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
  785. // Convert source pointers to integers, which can be manipulated.
  786. if (StoredValTy->getScalarType()->isPointerTy()) {
  787. StoredValTy = DL.getIntPtrType(StoredValTy);
  788. StoredVal = IRB.CreatePtrToInt(StoredVal, StoredValTy);
  789. }
  790. // Convert vectors and fp to integer, which can be manipulated.
  791. if (!StoredValTy->isIntegerTy()) {
  792. StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
  793. StoredVal = IRB.CreateBitCast(StoredVal, StoredValTy);
  794. }
  795. // If this is a big-endian system, we need to shift the value down to the low
  796. // bits so that a truncate will work.
  797. if (DL.isBigEndian()) {
  798. StoredVal = IRB.CreateLShr(StoredVal, StoreSize - LoadSize, "tmp");
  799. }
  800. // Truncate the integer to the right size now.
  801. Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
  802. StoredVal = IRB.CreateTrunc(StoredVal, NewIntTy, "trunc");
  803. if (LoadedTy == NewIntTy)
  804. return StoredVal;
  805. // If the result is a pointer, inttoptr.
  806. if (LoadedTy->getScalarType()->isPointerTy())
  807. return IRB.CreateIntToPtr(StoredVal, LoadedTy, "inttoptr");
  808. // Otherwise, bitcast.
  809. return IRB.CreateBitCast(StoredVal, LoadedTy, "bitcast");
  810. }
  811. /// This function is called when we have a
  812. /// memdep query of a load that ends up being a clobbering memory write (store,
  813. /// memset, memcpy, memmove). This means that the write *may* provide bits used
  814. /// by the load but we can't be sure because the pointers don't mustalias.
  815. ///
  816. /// Check this case to see if there is anything more we can do before we give
  817. /// up. This returns -1 if we have to give up, or a byte number in the stored
  818. /// value of the piece that feeds the load.
  819. static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
  820. Value *WritePtr,
  821. uint64_t WriteSizeInBits,
  822. const DataLayout &DL) {
  823. // If the loaded or stored value is a first class array or struct, don't try
  824. // to transform them. We need to be able to bitcast to integer.
  825. if (LoadTy->isStructTy() || LoadTy->isArrayTy())
  826. return -1;
  827. int64_t StoreOffset = 0, LoadOffset = 0;
  828. Value *StoreBase =
  829. GetPointerBaseWithConstantOffset(WritePtr, StoreOffset, DL);
  830. Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, DL);
  831. if (StoreBase != LoadBase)
  832. return -1;
  833. // If the load and store are to the exact same address, they should have been
  834. // a must alias. AA must have gotten confused.
  835. // FIXME: Study to see if/when this happens. One case is forwarding a memset
  836. // to a load from the base of the memset.
  837. #if 0
  838. if (LoadOffset == StoreOffset) {
  839. dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
  840. << "Base = " << *StoreBase << "\n"
  841. << "Store Ptr = " << *WritePtr << "\n"
  842. << "Store Offs = " << StoreOffset << "\n"
  843. << "Load Ptr = " << *LoadPtr << "\n";
  844. abort();
  845. }
  846. #endif
  847. // If the load and store don't overlap at all, the store doesn't provide
  848. // anything to the load. In this case, they really don't alias at all, AA
  849. // must have gotten confused.
  850. uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy);
  851. if ((WriteSizeInBits & 7) | (LoadSize & 7))
  852. return -1;
  853. uint64_t StoreSize = WriteSizeInBits >> 3; // Convert to bytes.
  854. LoadSize >>= 3;
  855. bool isAAFailure = false;
  856. if (StoreOffset < LoadOffset)
  857. isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
  858. else
  859. isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
  860. if (isAAFailure) {
  861. #if 0
  862. dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
  863. << "Base = " << *StoreBase << "\n"
  864. << "Store Ptr = " << *WritePtr << "\n"
  865. << "Store Offs = " << StoreOffset << "\n"
  866. << "Load Ptr = " << *LoadPtr << "\n";
  867. abort();
  868. #endif
  869. return -1;
  870. }
  871. // If the Load isn't completely contained within the stored bits, we don't
  872. // have all the bits to feed it. We could do something crazy in the future
  873. // (issue a smaller load then merge the bits in) but this seems unlikely to be
  874. // valuable.
  875. if (StoreOffset > LoadOffset ||
  876. StoreOffset+StoreSize < LoadOffset+LoadSize)
  877. return -1;
  878. // Okay, we can do this transformation. Return the number of bytes into the
  879. // store that the load is.
  880. return LoadOffset-StoreOffset;
  881. }
  882. /// This function is called when we have a
  883. /// memdep query of a load that ends up being a clobbering store.
  884. static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
  885. StoreInst *DepSI) {
  886. // Cannot handle reading from store of first-class aggregate yet.
  887. if (DepSI->getValueOperand()->getType()->isStructTy() ||
  888. DepSI->getValueOperand()->getType()->isArrayTy())
  889. return -1;
  890. const DataLayout &DL = DepSI->getModule()->getDataLayout();
  891. Value *StorePtr = DepSI->getPointerOperand();
  892. uint64_t StoreSize =DL.getTypeSizeInBits(DepSI->getValueOperand()->getType());
  893. return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
  894. StorePtr, StoreSize, DL);
  895. }
  896. /// This function is called when we have a
  897. /// memdep query of a load that ends up being clobbered by another load. See if
  898. /// the other load can feed into the second load.
  899. static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
  900. LoadInst *DepLI, const DataLayout &DL){
  901. // Cannot handle reading from store of first-class aggregate yet.
  902. if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
  903. return -1;
  904. Value *DepPtr = DepLI->getPointerOperand();
  905. uint64_t DepSize = DL.getTypeSizeInBits(DepLI->getType());
  906. int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, DL);
  907. if (R != -1) return R;
  908. // If we have a load/load clobber an DepLI can be widened to cover this load,
  909. // then we should widen it!
  910. int64_t LoadOffs = 0;
  911. const Value *LoadBase =
  912. GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, DL);
  913. unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
  914. unsigned Size = MemoryDependenceAnalysis::getLoadLoadClobberFullWidthSize(
  915. LoadBase, LoadOffs, LoadSize, DepLI);
  916. if (Size == 0) return -1;
  917. return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, DL);
  918. }
  919. static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
  920. MemIntrinsic *MI,
  921. const DataLayout &DL) {
  922. // If the mem operation is a non-constant size, we can't handle it.
  923. ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
  924. if (!SizeCst) return -1;
  925. uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
  926. // If this is memset, we just need to see if the offset is valid in the size
  927. // of the memset..
  928. if (MI->getIntrinsicID() == Intrinsic::memset)
  929. return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
  930. MemSizeInBits, DL);
  931. // If we have a memcpy/memmove, the only case we can handle is if this is a
  932. // copy from constant memory. In that case, we can read directly from the
  933. // constant memory.
  934. MemTransferInst *MTI = cast<MemTransferInst>(MI);
  935. Constant *Src = dyn_cast<Constant>(MTI->getSource());
  936. if (!Src) return -1;
  937. GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, DL));
  938. if (!GV || !GV->isConstant()) return -1;
  939. // See if the access is within the bounds of the transfer.
  940. int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
  941. MI->getDest(), MemSizeInBits, DL);
  942. if (Offset == -1)
  943. return Offset;
  944. unsigned AS = Src->getType()->getPointerAddressSpace();
  945. // Otherwise, see if we can constant fold a load from the constant with the
  946. // offset applied as appropriate.
  947. Src = ConstantExpr::getBitCast(Src,
  948. Type::getInt8PtrTy(Src->getContext(), AS));
  949. Constant *OffsetCst =
  950. ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
  951. Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()), Src,
  952. OffsetCst);
  953. Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
  954. if (ConstantFoldLoadFromConstPtr(Src, DL))
  955. return Offset;
  956. return -1;
  957. }
  958. /// This function is called when we have a
  959. /// memdep query of a load that ends up being a clobbering store. This means
  960. /// that the store provides bits used by the load but we the pointers don't
  961. /// mustalias. Check this case to see if there is anything more we can do
  962. /// before we give up.
  963. static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
  964. Type *LoadTy,
  965. Instruction *InsertPt, const DataLayout &DL){
  966. LLVMContext &Ctx = SrcVal->getType()->getContext();
  967. uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
  968. uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8;
  969. IRBuilder<> Builder(InsertPt);
  970. // Compute which bits of the stored value are being used by the load. Convert
  971. // to an integer type to start with.
  972. if (SrcVal->getType()->getScalarType()->isPointerTy())
  973. SrcVal = Builder.CreatePtrToInt(SrcVal,
  974. DL.getIntPtrType(SrcVal->getType()));
  975. if (!SrcVal->getType()->isIntegerTy())
  976. SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
  977. // Shift the bits to the least significant depending on endianness.
  978. unsigned ShiftAmt;
  979. if (DL.isLittleEndian())
  980. ShiftAmt = Offset*8;
  981. else
  982. ShiftAmt = (StoreSize-LoadSize-Offset)*8;
  983. if (ShiftAmt)
  984. SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
  985. if (LoadSize != StoreSize)
  986. SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
  987. return CoerceAvailableValueToLoadType(SrcVal, LoadTy, Builder, DL);
  988. }
  989. /// This function is called when we have a
  990. /// memdep query of a load that ends up being a clobbering load. This means
  991. /// that the load *may* provide bits used by the load but we can't be sure
  992. /// because the pointers don't mustalias. Check this case to see if there is
  993. /// anything more we can do before we give up.
  994. static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
  995. Type *LoadTy, Instruction *InsertPt,
  996. GVN &gvn) {
  997. const DataLayout &DL = SrcVal->getModule()->getDataLayout();
  998. // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
  999. // widen SrcVal out to a larger load.
  1000. unsigned SrcValSize = DL.getTypeStoreSize(SrcVal->getType());
  1001. unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
  1002. if (Offset+LoadSize > SrcValSize) {
  1003. assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
  1004. assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
  1005. // If we have a load/load clobber an DepLI can be widened to cover this
  1006. // load, then we should widen it to the next power of 2 size big enough!
  1007. unsigned NewLoadSize = Offset+LoadSize;
  1008. if (!isPowerOf2_32(NewLoadSize))
  1009. NewLoadSize = NextPowerOf2(NewLoadSize);
  1010. Value *PtrVal = SrcVal->getPointerOperand();
  1011. // Insert the new load after the old load. This ensures that subsequent
  1012. // memdep queries will find the new load. We can't easily remove the old
  1013. // load completely because it is already in the value numbering table.
  1014. IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
  1015. Type *DestPTy =
  1016. IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
  1017. DestPTy = PointerType::get(DestPTy,
  1018. PtrVal->getType()->getPointerAddressSpace());
  1019. Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
  1020. PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
  1021. LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
  1022. NewLoad->takeName(SrcVal);
  1023. NewLoad->setAlignment(SrcVal->getAlignment());
  1024. DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
  1025. DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
  1026. // Replace uses of the original load with the wider load. On a big endian
  1027. // system, we need to shift down to get the relevant bits.
  1028. Value *RV = NewLoad;
  1029. if (DL.isBigEndian())
  1030. RV = Builder.CreateLShr(RV,
  1031. NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
  1032. RV = Builder.CreateTrunc(RV, SrcVal->getType());
  1033. SrcVal->replaceAllUsesWith(RV);
  1034. // We would like to use gvn.markInstructionForDeletion here, but we can't
  1035. // because the load is already memoized into the leader map table that GVN
  1036. // tracks. It is potentially possible to remove the load from the table,
  1037. // but then there all of the operations based on it would need to be
  1038. // rehashed. Just leave the dead load around.
  1039. gvn.getMemDep().removeInstruction(SrcVal);
  1040. SrcVal = NewLoad;
  1041. }
  1042. return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, DL);
  1043. }
  1044. /// This function is called when we have a
  1045. /// memdep query of a load that ends up being a clobbering mem intrinsic.
  1046. static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
  1047. Type *LoadTy, Instruction *InsertPt,
  1048. const DataLayout &DL){
  1049. LLVMContext &Ctx = LoadTy->getContext();
  1050. uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy)/8;
  1051. IRBuilder<> Builder(InsertPt);
  1052. // We know that this method is only called when the mem transfer fully
  1053. // provides the bits for the load.
  1054. if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
  1055. // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
  1056. // independently of what the offset is.
  1057. Value *Val = MSI->getValue();
  1058. if (LoadSize != 1)
  1059. Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
  1060. Value *OneElt = Val;
  1061. // Splat the value out to the right number of bits.
  1062. for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
  1063. // If we can double the number of bytes set, do it.
  1064. if (NumBytesSet*2 <= LoadSize) {
  1065. Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
  1066. Val = Builder.CreateOr(Val, ShVal);
  1067. NumBytesSet <<= 1;
  1068. continue;
  1069. }
  1070. // Otherwise insert one byte at a time.
  1071. Value *ShVal = Builder.CreateShl(Val, 1*8);
  1072. Val = Builder.CreateOr(OneElt, ShVal);
  1073. ++NumBytesSet;
  1074. }
  1075. return CoerceAvailableValueToLoadType(Val, LoadTy, Builder, DL);
  1076. }
  1077. // Otherwise, this is a memcpy/memmove from a constant global.
  1078. MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
  1079. Constant *Src = cast<Constant>(MTI->getSource());
  1080. unsigned AS = Src->getType()->getPointerAddressSpace();
  1081. // Otherwise, see if we can constant fold a load from the constant with the
  1082. // offset applied as appropriate.
  1083. Src = ConstantExpr::getBitCast(Src,
  1084. Type::getInt8PtrTy(Src->getContext(), AS));
  1085. Constant *OffsetCst =
  1086. ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
  1087. Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()), Src,
  1088. OffsetCst);
  1089. Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
  1090. return ConstantFoldLoadFromConstPtr(Src, DL);
  1091. }
  1092. /// Given a set of loads specified by ValuesPerBlock,
  1093. /// construct SSA form, allowing us to eliminate LI. This returns the value
  1094. /// that should be used at LI's definition site.
  1095. static Value *ConstructSSAForLoadSet(LoadInst *LI,
  1096. SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
  1097. GVN &gvn) {
  1098. // Check for the fully redundant, dominating load case. In this case, we can
  1099. // just use the dominating value directly.
  1100. if (ValuesPerBlock.size() == 1 &&
  1101. gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
  1102. LI->getParent())) {
  1103. assert(!ValuesPerBlock[0].isUndefValue() && "Dead BB dominate this block");
  1104. return ValuesPerBlock[0].MaterializeAdjustedValue(LI, gvn);
  1105. }
  1106. // Otherwise, we have to construct SSA form.
  1107. SmallVector<PHINode*, 8> NewPHIs;
  1108. SSAUpdater SSAUpdate(&NewPHIs);
  1109. SSAUpdate.Initialize(LI->getType(), LI->getName());
  1110. for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
  1111. const AvailableValueInBlock &AV = ValuesPerBlock[i];
  1112. BasicBlock *BB = AV.BB;
  1113. if (SSAUpdate.HasValueForBlock(BB))
  1114. continue;
  1115. SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LI, gvn));
  1116. }
  1117. // Perform PHI construction.
  1118. Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
  1119. // If new PHI nodes were created, notify alias analysis.
  1120. if (V->getType()->getScalarType()->isPointerTy()) {
  1121. AliasAnalysis *AA = gvn.getAliasAnalysis();
  1122. // Scan the new PHIs and inform alias analysis that we've added potentially
  1123. // escaping uses to any values that are operands to these PHIs.
  1124. for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
  1125. PHINode *P = NewPHIs[i];
  1126. for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
  1127. unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
  1128. AA->addEscapingUse(P->getOperandUse(jj));
  1129. }
  1130. }
  1131. }
  1132. return V;
  1133. }
  1134. Value *AvailableValueInBlock::MaterializeAdjustedValue(LoadInst *LI,
  1135. GVN &gvn) const {
  1136. Value *Res;
  1137. Type *LoadTy = LI->getType();
  1138. const DataLayout &DL = LI->getModule()->getDataLayout();
  1139. if (isSimpleValue()) {
  1140. Res = getSimpleValue();
  1141. if (Res->getType() != LoadTy) {
  1142. Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(), DL);
  1143. DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << " "
  1144. << *getSimpleValue() << '\n'
  1145. << *Res << '\n' << "\n\n\n");
  1146. }
  1147. } else if (isCoercedLoadValue()) {
  1148. LoadInst *Load = getCoercedLoadValue();
  1149. if (Load->getType() == LoadTy && Offset == 0) {
  1150. Res = Load;
  1151. } else {
  1152. Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
  1153. gvn);
  1154. DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << " "
  1155. << *getCoercedLoadValue() << '\n'
  1156. << *Res << '\n' << "\n\n\n");
  1157. }
  1158. } else if (isMemIntrinValue()) {
  1159. Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset, LoadTy,
  1160. BB->getTerminator(), DL);
  1161. DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
  1162. << " " << *getMemIntrinValue() << '\n'
  1163. << *Res << '\n' << "\n\n\n");
  1164. } else {
  1165. assert(isUndefValue() && "Should be UndefVal");
  1166. DEBUG(dbgs() << "GVN COERCED NONLOCAL Undef:\n";);
  1167. return UndefValue::get(LoadTy);
  1168. }
  1169. return Res;
  1170. }
  1171. static bool isLifetimeStart(const Instruction *Inst) {
  1172. if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
  1173. return II->getIntrinsicID() == Intrinsic::lifetime_start;
  1174. return false;
  1175. }
  1176. void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
  1177. AvailValInBlkVect &ValuesPerBlock,
  1178. UnavailBlkVect &UnavailableBlocks) {
  1179. // Filter out useless results (non-locals, etc). Keep track of the blocks
  1180. // where we have a value available in repl, also keep track of whether we see
  1181. // dependencies that produce an unknown value for the load (such as a call
  1182. // that could potentially clobber the load).
  1183. unsigned NumDeps = Deps.size();
  1184. const DataLayout &DL = LI->getModule()->getDataLayout();
  1185. for (unsigned i = 0, e = NumDeps; i != e; ++i) {
  1186. BasicBlock *DepBB = Deps[i].getBB();
  1187. MemDepResult DepInfo = Deps[i].getResult();
  1188. if (DeadBlocks.count(DepBB)) {
  1189. // Dead dependent mem-op disguise as a load evaluating the same value
  1190. // as the load in question.
  1191. ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
  1192. continue;
  1193. }
  1194. if (!DepInfo.isDef() && !DepInfo.isClobber()) {
  1195. UnavailableBlocks.push_back(DepBB);
  1196. continue;
  1197. }
  1198. if (DepInfo.isClobber()) {
  1199. // The address being loaded in this non-local block may not be the same as
  1200. // the pointer operand of the load if PHI translation occurs. Make sure
  1201. // to consider the right address.
  1202. Value *Address = Deps[i].getAddress();
  1203. // If the dependence is to a store that writes to a superset of the bits
  1204. // read by the load, we can extract the bits we need for the load from the
  1205. // stored value.
  1206. if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
  1207. if (Address) {
  1208. int Offset =
  1209. AnalyzeLoadFromClobberingStore(LI->getType(), Address, DepSI);
  1210. if (Offset != -1) {
  1211. ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
  1212. DepSI->getValueOperand(),
  1213. Offset));
  1214. continue;
  1215. }
  1216. }
  1217. }
  1218. // Check to see if we have something like this:
  1219. // load i32* P
  1220. // load i8* (P+1)
  1221. // if we have this, replace the later with an extraction from the former.
  1222. if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
  1223. // If this is a clobber and L is the first instruction in its block, then
  1224. // we have the first instruction in the entry block.
  1225. if (DepLI != LI && Address) {
  1226. int Offset =
  1227. AnalyzeLoadFromClobberingLoad(LI->getType(), Address, DepLI, DL);
  1228. if (Offset != -1) {
  1229. ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
  1230. Offset));
  1231. continue;
  1232. }
  1233. }
  1234. }
  1235. // If the clobbering value is a memset/memcpy/memmove, see if we can
  1236. // forward a value on from it.
  1237. if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
  1238. if (Address) {
  1239. int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
  1240. DepMI, DL);
  1241. if (Offset != -1) {
  1242. ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
  1243. Offset));
  1244. continue;
  1245. }
  1246. }
  1247. }
  1248. UnavailableBlocks.push_back(DepBB);
  1249. continue;
  1250. }
  1251. // DepInfo.isDef() here
  1252. Instruction *DepInst = DepInfo.getInst();
  1253. // Loading the allocation -> undef.
  1254. if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) ||
  1255. // Loading immediately after lifetime begin -> undef.
  1256. isLifetimeStart(DepInst)) {
  1257. ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
  1258. UndefValue::get(LI->getType())));
  1259. continue;
  1260. }
  1261. // Loading from calloc (which zero initializes memory) -> zero
  1262. if (isCallocLikeFn(DepInst, TLI)) {
  1263. ValuesPerBlock.push_back(AvailableValueInBlock::get(
  1264. DepBB, Constant::getNullValue(LI->getType())));
  1265. continue;
  1266. }
  1267. if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
  1268. // Reject loads and stores that are to the same address but are of
  1269. // different types if we have to.
  1270. if (S->getValueOperand()->getType() != LI->getType()) {
  1271. // If the stored value is larger or equal to the loaded value, we can
  1272. // reuse it.
  1273. if (!CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
  1274. LI->getType(), DL)) {
  1275. UnavailableBlocks.push_back(DepBB);
  1276. continue;
  1277. }
  1278. }
  1279. ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
  1280. S->getValueOperand()));
  1281. continue;
  1282. }
  1283. if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
  1284. // If the types mismatch and we can't handle it, reject reuse of the load.
  1285. if (LD->getType() != LI->getType()) {
  1286. // If the stored value is larger or equal to the loaded value, we can
  1287. // reuse it.
  1288. if (!CanCoerceMustAliasedValueToLoad(LD, LI->getType(), DL)) {
  1289. UnavailableBlocks.push_back(DepBB);
  1290. continue;
  1291. }
  1292. }
  1293. ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
  1294. continue;
  1295. }
  1296. UnavailableBlocks.push_back(DepBB);
  1297. }
  1298. }
  1299. bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
  1300. UnavailBlkVect &UnavailableBlocks) {
  1301. // Okay, we have *some* definitions of the value. This means that the value
  1302. // is available in some of our (transitive) predecessors. Lets think about
  1303. // doing PRE of this load. This will involve inserting a new load into the
  1304. // predecessor when it's not available. We could do this in general, but
  1305. // prefer to not increase code size. As such, we only do this when we know
  1306. // that we only have to insert *one* load (which means we're basically moving
  1307. // the load, not inserting a new one).
  1308. SmallPtrSet<BasicBlock *, 4> Blockers;
  1309. for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
  1310. Blockers.insert(UnavailableBlocks[i]);
  1311. // Let's find the first basic block with more than one predecessor. Walk
  1312. // backwards through predecessors if needed.
  1313. BasicBlock *LoadBB = LI->getParent();
  1314. BasicBlock *TmpBB = LoadBB;
  1315. while (TmpBB->getSinglePredecessor()) {
  1316. TmpBB = TmpBB->getSinglePredecessor();
  1317. if (TmpBB == LoadBB) // Infinite (unreachable) loop.
  1318. return false;
  1319. if (Blockers.count(TmpBB))
  1320. return false;
  1321. // If any of these blocks has more than one successor (i.e. if the edge we
  1322. // just traversed was critical), then there are other paths through this
  1323. // block along which the load may not be anticipated. Hoisting the load
  1324. // above this block would be adding the load to execution paths along
  1325. // which it was not previously executed.
  1326. if (TmpBB->getTerminator()->getNumSuccessors() != 1)
  1327. return false;
  1328. }
  1329. assert(TmpBB);
  1330. LoadBB = TmpBB;
  1331. // Check to see how many predecessors have the loaded value fully
  1332. // available.
  1333. MapVector<BasicBlock *, Value *> PredLoads;
  1334. DenseMap<BasicBlock*, char> FullyAvailableBlocks;
  1335. for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
  1336. FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
  1337. for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
  1338. FullyAvailableBlocks[UnavailableBlocks[i]] = false;
  1339. SmallVector<BasicBlock *, 4> CriticalEdgePred;
  1340. for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
  1341. PI != E; ++PI) {
  1342. BasicBlock *Pred = *PI;
  1343. if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks, 0)) {
  1344. continue;
  1345. }
  1346. if (Pred->getTerminator()->getNumSuccessors() != 1) {
  1347. if (isa<IndirectBrInst>(Pred->getTerminator())) {
  1348. DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
  1349. << Pred->getName() << "': " << *LI << '\n');
  1350. return false;
  1351. }
  1352. if (LoadBB->isLandingPad()) {
  1353. DEBUG(dbgs()
  1354. << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
  1355. << Pred->getName() << "': " << *LI << '\n');
  1356. return false;
  1357. }
  1358. CriticalEdgePred.push_back(Pred);
  1359. } else {
  1360. // Only add the predecessors that will not be split for now.
  1361. PredLoads[Pred] = nullptr;
  1362. }
  1363. }
  1364. // Decide whether PRE is profitable for this load.
  1365. unsigned NumUnavailablePreds = PredLoads.size() + CriticalEdgePred.size();
  1366. assert(NumUnavailablePreds != 0 &&
  1367. "Fully available value should already be eliminated!");
  1368. // If this load is unavailable in multiple predecessors, reject it.
  1369. // FIXME: If we could restructure the CFG, we could make a common pred with
  1370. // all the preds that don't have an available LI and insert a new load into
  1371. // that one block.
  1372. if (NumUnavailablePreds != 1)
  1373. return false;
  1374. // Split critical edges, and update the unavailable predecessors accordingly.
  1375. for (BasicBlock *OrigPred : CriticalEdgePred) {
  1376. BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
  1377. assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!");
  1378. PredLoads[NewPred] = nullptr;
  1379. DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
  1380. << LoadBB->getName() << '\n');
  1381. }
  1382. // Check if the load can safely be moved to all the unavailable predecessors.
  1383. bool CanDoPRE = true;
  1384. const DataLayout &DL = LI->getModule()->getDataLayout();
  1385. SmallVector<Instruction*, 8> NewInsts;
  1386. for (auto &PredLoad : PredLoads) {
  1387. BasicBlock *UnavailablePred = PredLoad.first;
  1388. // Do PHI translation to get its value in the predecessor if necessary. The
  1389. // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
  1390. // If all preds have a single successor, then we know it is safe to insert
  1391. // the load on the pred (?!?), so we can insert code to materialize the
  1392. // pointer if it is not available.
  1393. PHITransAddr Address(LI->getPointerOperand(), DL, AC);
  1394. Value *LoadPtr = nullptr;
  1395. LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
  1396. *DT, NewInsts);
  1397. // If we couldn't find or insert a computation of this phi translated value,
  1398. // we fail PRE.
  1399. if (!LoadPtr) {
  1400. DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
  1401. << *LI->getPointerOperand() << "\n");
  1402. CanDoPRE = false;
  1403. break;
  1404. }
  1405. PredLoad.second = LoadPtr;
  1406. }
  1407. if (!CanDoPRE) {
  1408. while (!NewInsts.empty()) {
  1409. Instruction *I = NewInsts.pop_back_val();
  1410. if (MD) MD->removeInstruction(I);
  1411. I->eraseFromParent();
  1412. }
  1413. // HINT: Don't revert the edge-splitting as following transformation may
  1414. // also need to split these critical edges.
  1415. return !CriticalEdgePred.empty();
  1416. }
  1417. // Okay, we can eliminate this load by inserting a reload in the predecessor
  1418. // and using PHI construction to get the value in the other predecessors, do
  1419. // it.
  1420. DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
  1421. DEBUG(if (!NewInsts.empty())
  1422. dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
  1423. << *NewInsts.back() << '\n');
  1424. // Assign value numbers to the new instructions.
  1425. for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
  1426. // FIXME: We really _ought_ to insert these value numbers into their
  1427. // parent's availability map. However, in doing so, we risk getting into
  1428. // ordering issues. If a block hasn't been processed yet, we would be
  1429. // marking a value as AVAIL-IN, which isn't what we intend.
  1430. VN.lookup_or_add(NewInsts[i]);
  1431. }
  1432. for (const auto &PredLoad : PredLoads) {
  1433. BasicBlock *UnavailablePred = PredLoad.first;
  1434. Value *LoadPtr = PredLoad.second;
  1435. Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
  1436. LI->getAlignment(),
  1437. UnavailablePred->getTerminator());
  1438. // Transfer the old load's AA tags to the new load.
  1439. AAMDNodes Tags;
  1440. LI->getAAMetadata(Tags);
  1441. if (Tags)
  1442. NewLoad->setAAMetadata(Tags);
  1443. // Transfer DebugLoc.
  1444. NewLoad->setDebugLoc(LI->getDebugLoc());
  1445. // Add the newly created load.
  1446. ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
  1447. NewLoad));
  1448. MD->invalidateCachedPointerInfo(LoadPtr);
  1449. DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
  1450. }
  1451. // Perform PHI construction.
  1452. Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
  1453. LI->replaceAllUsesWith(V);
  1454. if (isa<PHINode>(V))
  1455. V->takeName(LI);
  1456. if (Instruction *I = dyn_cast<Instruction>(V))
  1457. I->setDebugLoc(LI->getDebugLoc());
  1458. if (V->getType()->getScalarType()->isPointerTy())
  1459. MD->invalidateCachedPointerInfo(V);
  1460. markInstructionForDeletion(LI);
  1461. ++NumPRELoad;
  1462. return true;
  1463. }
  1464. /// Attempt to eliminate a load whose dependencies are
  1465. /// non-local by performing PHI construction.
  1466. bool GVN::processNonLocalLoad(LoadInst *LI) {
  1467. // Step 1: Find the non-local dependencies of the load.
  1468. LoadDepVect Deps;
  1469. MD->getNonLocalPointerDependency(LI, Deps);
  1470. // If we had to process more than one hundred blocks to find the
  1471. // dependencies, this load isn't worth worrying about. Optimizing
  1472. // it will be too expensive.
  1473. unsigned NumDeps = Deps.size();
  1474. if (NumDeps > 100)
  1475. return false;
  1476. // If we had a phi translation failure, we'll have a single entry which is a
  1477. // clobber in the current block. Reject this early.
  1478. if (NumDeps == 1 &&
  1479. !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
  1480. DEBUG(
  1481. dbgs() << "GVN: non-local load ";
  1482. LI->printAsOperand(dbgs());
  1483. dbgs() << " has unknown dependencies\n";
  1484. );
  1485. return false;
  1486. }
  1487. // If this load follows a GEP, see if we can PRE the indices before analyzing.
  1488. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) {
  1489. for (GetElementPtrInst::op_iterator OI = GEP->idx_begin(),
  1490. OE = GEP->idx_end();
  1491. OI != OE; ++OI)
  1492. if (Instruction *I = dyn_cast<Instruction>(OI->get()))
  1493. performScalarPRE(I);
  1494. }
  1495. // Step 2: Analyze the availability of the load
  1496. AvailValInBlkVect ValuesPerBlock;
  1497. UnavailBlkVect UnavailableBlocks;
  1498. AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
  1499. // If we have no predecessors that produce a known value for this load, exit
  1500. // early.
  1501. if (ValuesPerBlock.empty())
  1502. return false;
  1503. // Step 3: Eliminate fully redundancy.
  1504. //
  1505. // If all of the instructions we depend on produce a known value for this
  1506. // load, then it is fully redundant and we can use PHI insertion to compute
  1507. // its value. Insert PHIs and remove the fully redundant value now.
  1508. if (UnavailableBlocks.empty()) {
  1509. DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
  1510. // Perform PHI construction.
  1511. Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
  1512. LI->replaceAllUsesWith(V);
  1513. if (isa<PHINode>(V))
  1514. V->takeName(LI);
  1515. if (Instruction *I = dyn_cast<Instruction>(V))
  1516. I->setDebugLoc(LI->getDebugLoc());
  1517. if (V->getType()->getScalarType()->isPointerTy())
  1518. MD->invalidateCachedPointerInfo(V);
  1519. markInstructionForDeletion(LI);
  1520. ++NumGVNLoad;
  1521. return true;
  1522. }
  1523. // Step 4: Eliminate partial redundancy.
  1524. if (!EnablePRE || !EnableLoadPRE)
  1525. return false;
  1526. return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
  1527. }
  1528. static void patchReplacementInstruction(Instruction *I, Value *Repl) {
  1529. // Patch the replacement so that it is not more restrictive than the value
  1530. // being replaced.
  1531. BinaryOperator *Op = dyn_cast<BinaryOperator>(I);
  1532. BinaryOperator *ReplOp = dyn_cast<BinaryOperator>(Repl);
  1533. if (Op && ReplOp)
  1534. ReplOp->andIRFlags(Op);
  1535. if (Instruction *ReplInst = dyn_cast<Instruction>(Repl)) {
  1536. // FIXME: If both the original and replacement value are part of the
  1537. // same control-flow region (meaning that the execution of one
  1538. // guarentees the executation of the other), then we can combine the
  1539. // noalias scopes here and do better than the general conservative
  1540. // answer used in combineMetadata().
  1541. // In general, GVN unifies expressions over different control-flow
  1542. // regions, and so we need a conservative combination of the noalias
  1543. // scopes.
  1544. static const unsigned KnownIDs[] = {
  1545. LLVMContext::MD_tbaa,
  1546. LLVMContext::MD_alias_scope,
  1547. LLVMContext::MD_noalias,
  1548. LLVMContext::MD_range,
  1549. LLVMContext::MD_fpmath,
  1550. LLVMContext::MD_invariant_load,
  1551. };
  1552. combineMetadata(ReplInst, I, KnownIDs);
  1553. }
  1554. }
  1555. static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
  1556. patchReplacementInstruction(I, Repl);
  1557. I->replaceAllUsesWith(Repl);
  1558. }
  1559. /// Attempt to eliminate a load, first by eliminating it
  1560. /// locally, and then attempting non-local elimination if that fails.
  1561. bool GVN::processLoad(LoadInst *L) {
  1562. if (!MD)
  1563. return false;
  1564. if (!L->isSimple())
  1565. return false;
  1566. if (L->use_empty()) {
  1567. markInstructionForDeletion(L);
  1568. return true;
  1569. }
  1570. // ... to a pointer that has been loaded from before...
  1571. MemDepResult Dep = MD->getDependency(L);
  1572. const DataLayout &DL = L->getModule()->getDataLayout();
  1573. // If we have a clobber and target data is around, see if this is a clobber
  1574. // that we can fix up through code synthesis.
  1575. if (Dep.isClobber()) {
  1576. // Check to see if we have something like this:
  1577. // store i32 123, i32* %P
  1578. // %A = bitcast i32* %P to i8*
  1579. // %B = gep i8* %A, i32 1
  1580. // %C = load i8* %B
  1581. //
  1582. // We could do that by recognizing if the clobber instructions are obviously
  1583. // a common base + constant offset, and if the previous store (or memset)
  1584. // completely covers this load. This sort of thing can happen in bitfield
  1585. // access code.
  1586. Value *AvailVal = nullptr;
  1587. if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
  1588. int Offset = AnalyzeLoadFromClobberingStore(
  1589. L->getType(), L->getPointerOperand(), DepSI);
  1590. if (Offset != -1)
  1591. AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
  1592. L->getType(), L, DL);
  1593. }
  1594. // Check to see if we have something like this:
  1595. // load i32* P
  1596. // load i8* (P+1)
  1597. // if we have this, replace the later with an extraction from the former.
  1598. if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
  1599. // If this is a clobber and L is the first instruction in its block, then
  1600. // we have the first instruction in the entry block.
  1601. if (DepLI == L)
  1602. return false;
  1603. int Offset = AnalyzeLoadFromClobberingLoad(
  1604. L->getType(), L->getPointerOperand(), DepLI, DL);
  1605. if (Offset != -1)
  1606. AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
  1607. }
  1608. // If the clobbering value is a memset/memcpy/memmove, see if we can forward
  1609. // a value on from it.
  1610. if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
  1611. int Offset = AnalyzeLoadFromClobberingMemInst(
  1612. L->getType(), L->getPointerOperand(), DepMI, DL);
  1613. if (Offset != -1)
  1614. AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, DL);
  1615. }
  1616. if (AvailVal) {
  1617. DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
  1618. << *AvailVal << '\n' << *L << "\n\n\n");
  1619. // Replace the load!
  1620. L->replaceAllUsesWith(AvailVal);
  1621. if (AvailVal->getType()->getScalarType()->isPointerTy())
  1622. MD->invalidateCachedPointerInfo(AvailVal);
  1623. markInstructionForDeletion(L);
  1624. ++NumGVNLoad;
  1625. return true;
  1626. }
  1627. }
  1628. // If the value isn't available, don't do anything!
  1629. if (Dep.isClobber()) {
  1630. DEBUG(
  1631. // fast print dep, using operator<< on instruction is too slow.
  1632. dbgs() << "GVN: load ";
  1633. L->printAsOperand(dbgs());
  1634. Instruction *I = Dep.getInst();
  1635. dbgs() << " is clobbered by " << *I << '\n';
  1636. );
  1637. return false;
  1638. }
  1639. // If it is defined in another block, try harder.
  1640. if (Dep.isNonLocal())
  1641. return processNonLocalLoad(L);
  1642. if (!Dep.isDef()) {
  1643. DEBUG(
  1644. // fast print dep, using operator<< on instruction is too slow.
  1645. dbgs() << "GVN: load ";
  1646. L->printAsOperand(dbgs());
  1647. dbgs() << " has unknown dependence\n";
  1648. );
  1649. return false;
  1650. }
  1651. Instruction *DepInst = Dep.getInst();
  1652. if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
  1653. Value *StoredVal = DepSI->getValueOperand();
  1654. // The store and load are to a must-aliased pointer, but they may not
  1655. // actually have the same type. See if we know how to reuse the stored
  1656. // value (depending on its type).
  1657. if (StoredVal->getType() != L->getType()) {
  1658. IRBuilder<> Builder(L);
  1659. StoredVal =
  1660. CoerceAvailableValueToLoadType(StoredVal, L->getType(), Builder, DL);
  1661. if (!StoredVal)
  1662. return false;
  1663. DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
  1664. << '\n' << *L << "\n\n\n");
  1665. }
  1666. // Remove it!
  1667. L->replaceAllUsesWith(StoredVal);
  1668. if (StoredVal->getType()->getScalarType()->isPointerTy())
  1669. MD->invalidateCachedPointerInfo(StoredVal);
  1670. markInstructionForDeletion(L);
  1671. ++NumGVNLoad;
  1672. return true;
  1673. }
  1674. if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
  1675. Value *AvailableVal = DepLI;
  1676. // The loads are of a must-aliased pointer, but they may not actually have
  1677. // the same type. See if we know how to reuse the previously loaded value
  1678. // (depending on its type).
  1679. if (DepLI->getType() != L->getType()) {
  1680. IRBuilder<> Builder(L);
  1681. AvailableVal =
  1682. CoerceAvailableValueToLoadType(DepLI, L->getType(), Builder, DL);
  1683. if (!AvailableVal)
  1684. return false;
  1685. DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
  1686. << "\n" << *L << "\n\n\n");
  1687. }
  1688. // Remove it!
  1689. patchAndReplaceAllUsesWith(L, AvailableVal);
  1690. if (DepLI->getType()->getScalarType()->isPointerTy())
  1691. MD->invalidateCachedPointerInfo(DepLI);
  1692. markInstructionForDeletion(L);
  1693. ++NumGVNLoad;
  1694. return true;
  1695. }
  1696. // If this load really doesn't depend on anything, then we must be loading an
  1697. // undef value. This can happen when loading for a fresh allocation with no
  1698. // intervening stores, for example.
  1699. if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
  1700. L->replaceAllUsesWith(UndefValue::get(L->getType()));
  1701. markInstructionForDeletion(L);
  1702. ++NumGVNLoad;
  1703. return true;
  1704. }
  1705. // If this load occurs either right after a lifetime begin,
  1706. // then the loaded value is undefined.
  1707. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
  1708. if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
  1709. L->replaceAllUsesWith(UndefValue::get(L->getType()));
  1710. markInstructionForDeletion(L);
  1711. ++NumGVNLoad;
  1712. return true;
  1713. }
  1714. }
  1715. // If this load follows a calloc (which zero initializes memory),
  1716. // then the loaded value is zero
  1717. if (isCallocLikeFn(DepInst, TLI)) {
  1718. L->replaceAllUsesWith(Constant::getNullValue(L->getType()));
  1719. markInstructionForDeletion(L);
  1720. ++NumGVNLoad;
  1721. return true;
  1722. }
  1723. return false;
  1724. }
  1725. // In order to find a leader for a given value number at a
  1726. // specific basic block, we first obtain the list of all Values for that number,
  1727. // and then scan the list to find one whose block dominates the block in
  1728. // question. This is fast because dominator tree queries consist of only
  1729. // a few comparisons of DFS numbers.
  1730. Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) {
  1731. LeaderTableEntry Vals = LeaderTable[num];
  1732. if (!Vals.Val) return nullptr;
  1733. Value *Val = nullptr;
  1734. if (DT->dominates(Vals.BB, BB)) {
  1735. Val = Vals.Val;
  1736. if (isa<Constant>(Val)) return Val;
  1737. }
  1738. LeaderTableEntry* Next = Vals.Next;
  1739. while (Next) {
  1740. if (DT->dominates(Next->BB, BB)) {
  1741. if (isa<Constant>(Next->Val)) return Next->Val;
  1742. if (!Val) Val = Next->Val;
  1743. }
  1744. Next = Next->Next;
  1745. }
  1746. return Val;
  1747. }
  1748. /// There is an edge from 'Src' to 'Dst'. Return
  1749. /// true if every path from the entry block to 'Dst' passes via this edge. In
  1750. /// particular 'Dst' must not be reachable via another edge from 'Src'.
  1751. static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
  1752. DominatorTree *DT) {
  1753. // While in theory it is interesting to consider the case in which Dst has
  1754. // more than one predecessor, because Dst might be part of a loop which is
  1755. // only reachable from Src, in practice it is pointless since at the time
  1756. // GVN runs all such loops have preheaders, which means that Dst will have
  1757. // been changed to have only one predecessor, namely Src.
  1758. const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
  1759. const BasicBlock *Src = E.getStart();
  1760. assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
  1761. (void)Src;
  1762. return Pred != nullptr;
  1763. }
  1764. /// The given values are known to be equal in every block
  1765. /// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
  1766. /// 'RHS' everywhere in the scope. Returns whether a change was made.
  1767. bool GVN::propagateEquality(Value *LHS, Value *RHS,
  1768. const BasicBlockEdge &Root) {
  1769. SmallVector<std::pair<Value*, Value*>, 4> Worklist;
  1770. Worklist.push_back(std::make_pair(LHS, RHS));
  1771. bool Changed = false;
  1772. // For speed, compute a conservative fast approximation to
  1773. // DT->dominates(Root, Root.getEnd());
  1774. bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
  1775. while (!Worklist.empty()) {
  1776. std::pair<Value*, Value*> Item = Worklist.pop_back_val();
  1777. LHS = Item.first; RHS = Item.second;
  1778. if (LHS == RHS) continue;
  1779. assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
  1780. // Don't try to propagate equalities between constants.
  1781. if (isa<Constant>(LHS) && isa<Constant>(RHS)) continue;
  1782. // Prefer a constant on the right-hand side, or an Argument if no constants.
  1783. if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
  1784. std::swap(LHS, RHS);
  1785. assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
  1786. // If there is no obvious reason to prefer the left-hand side over the
  1787. // right-hand side, ensure the longest lived term is on the right-hand side,
  1788. // so the shortest lived term will be replaced by the longest lived.
  1789. // This tends to expose more simplifications.
  1790. uint32_t LVN = VN.lookup_or_add(LHS);
  1791. if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
  1792. (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
  1793. // Move the 'oldest' value to the right-hand side, using the value number
  1794. // as a proxy for age.
  1795. uint32_t RVN = VN.lookup_or_add(RHS);
  1796. if (LVN < RVN) {
  1797. std::swap(LHS, RHS);
  1798. LVN = RVN;
  1799. }
  1800. }
  1801. // If value numbering later sees that an instruction in the scope is equal
  1802. // to 'LHS' then ensure it will be turned into 'RHS'. In order to preserve
  1803. // the invariant that instructions only occur in the leader table for their
  1804. // own value number (this is used by removeFromLeaderTable), do not do this
  1805. // if RHS is an instruction (if an instruction in the scope is morphed into
  1806. // LHS then it will be turned into RHS by the next GVN iteration anyway, so
  1807. // using the leader table is about compiling faster, not optimizing better).
  1808. // The leader table only tracks basic blocks, not edges. Only add to if we
  1809. // have the simple case where the edge dominates the end.
  1810. if (RootDominatesEnd && !isa<Instruction>(RHS))
  1811. addToLeaderTable(LVN, RHS, Root.getEnd());
  1812. // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
  1813. // LHS always has at least one use that is not dominated by Root, this will
  1814. // never do anything if LHS has only one use.
  1815. if (!LHS->hasOneUse()) {
  1816. unsigned NumReplacements = replaceDominatedUsesWith(LHS, RHS, *DT, Root);
  1817. Changed |= NumReplacements > 0;
  1818. NumGVNEqProp += NumReplacements;
  1819. }
  1820. // Now try to deduce additional equalities from this one. For example, if
  1821. // the known equality was "(A != B)" == "false" then it follows that A and B
  1822. // are equal in the scope. Only boolean equalities with an explicit true or
  1823. // false RHS are currently supported.
  1824. if (!RHS->getType()->isIntegerTy(1))
  1825. // Not a boolean equality - bail out.
  1826. continue;
  1827. ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
  1828. if (!CI)
  1829. // RHS neither 'true' nor 'false' - bail out.
  1830. continue;
  1831. // Whether RHS equals 'true'. Otherwise it equals 'false'.
  1832. bool isKnownTrue = CI->isAllOnesValue();
  1833. bool isKnownFalse = !isKnownTrue;
  1834. // If "A && B" is known true then both A and B are known true. If "A || B"
  1835. // is known false then both A and B are known false.
  1836. Value *A, *B;
  1837. if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
  1838. (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
  1839. Worklist.push_back(std::make_pair(A, RHS));
  1840. Worklist.push_back(std::make_pair(B, RHS));
  1841. continue;
  1842. }
  1843. // If we are propagating an equality like "(A == B)" == "true" then also
  1844. // propagate the equality A == B. When propagating a comparison such as
  1845. // "(A >= B)" == "true", replace all instances of "A < B" with "false".
  1846. if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
  1847. Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
  1848. // If "A == B" is known true, or "A != B" is known false, then replace
  1849. // A with B everywhere in the scope.
  1850. if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
  1851. (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
  1852. Worklist.push_back(std::make_pair(Op0, Op1));
  1853. // Handle the floating point versions of equality comparisons too.
  1854. if ((isKnownTrue && Cmp->getPredicate() == CmpInst::FCMP_OEQ) ||
  1855. (isKnownFalse && Cmp->getPredicate() == CmpInst::FCMP_UNE)) {
  1856. // Floating point -0.0 and 0.0 compare equal, so we can only
  1857. // propagate values if we know that we have a constant and that
  1858. // its value is non-zero.
  1859. // FIXME: We should do this optimization if 'no signed zeros' is
  1860. // applicable via an instruction-level fast-math-flag or some other
  1861. // indicator that relaxed FP semantics are being used.
  1862. if (isa<ConstantFP>(Op1) && !cast<ConstantFP>(Op1)->isZero())
  1863. Worklist.push_back(std::make_pair(Op0, Op1));
  1864. }
  1865. // If "A >= B" is known true, replace "A < B" with false everywhere.
  1866. CmpInst::Predicate NotPred = Cmp->getInversePredicate();
  1867. Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
  1868. // Since we don't have the instruction "A < B" immediately to hand, work
  1869. // out the value number that it would have and use that to find an
  1870. // appropriate instruction (if any).
  1871. uint32_t NextNum = VN.getNextUnusedValueNumber();
  1872. uint32_t Num = VN.lookup_or_add_cmp(Cmp->getOpcode(), NotPred, Op0, Op1);
  1873. // If the number we were assigned was brand new then there is no point in
  1874. // looking for an instruction realizing it: there cannot be one!
  1875. if (Num < NextNum) {
  1876. Value *NotCmp = findLeader(Root.getEnd(), Num);
  1877. if (NotCmp && isa<Instruction>(NotCmp)) {
  1878. unsigned NumReplacements =
  1879. replaceDominatedUsesWith(NotCmp, NotVal, *DT, Root);
  1880. Changed |= NumReplacements > 0;
  1881. NumGVNEqProp += NumReplacements;
  1882. }
  1883. }
  1884. // Ensure that any instruction in scope that gets the "A < B" value number
  1885. // is replaced with false.
  1886. // The leader table only tracks basic blocks, not edges. Only add to if we
  1887. // have the simple case where the edge dominates the end.
  1888. if (RootDominatesEnd)
  1889. addToLeaderTable(Num, NotVal, Root.getEnd());
  1890. continue;
  1891. }
  1892. }
  1893. return Changed;
  1894. }
  1895. /// When calculating availability, handle an instruction
  1896. /// by inserting it into the appropriate sets
  1897. bool GVN::processInstruction(Instruction *I) {
  1898. // Ignore dbg info intrinsics.
  1899. if (isa<DbgInfoIntrinsic>(I))
  1900. return false;
  1901. // If the instruction can be easily simplified then do so now in preference
  1902. // to value numbering it. Value numbering often exposes redundancies, for
  1903. // example if it determines that %y is equal to %x then the instruction
  1904. // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
  1905. const DataLayout &DL = I->getModule()->getDataLayout();
  1906. if (Value *V = SimplifyInstruction(I, DL, TLI, DT, AC)) {
  1907. I->replaceAllUsesWith(V);
  1908. if (MD && V->getType()->getScalarType()->isPointerTy())
  1909. MD->invalidateCachedPointerInfo(V);
  1910. markInstructionForDeletion(I);
  1911. ++NumGVNSimpl;
  1912. return true;
  1913. }
  1914. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  1915. if (processLoad(LI))
  1916. return true;
  1917. unsigned Num = VN.lookup_or_add(LI);
  1918. addToLeaderTable(Num, LI, LI->getParent());
  1919. return false;
  1920. }
  1921. // For conditional branches, we can perform simple conditional propagation on
  1922. // the condition value itself.
  1923. if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
  1924. if (!BI->isConditional())
  1925. return false;
  1926. if (isa<Constant>(BI->getCondition()))
  1927. return processFoldableCondBr(BI);
  1928. Value *BranchCond = BI->getCondition();
  1929. BasicBlock *TrueSucc = BI->getSuccessor(0);
  1930. BasicBlock *FalseSucc = BI->getSuccessor(1);
  1931. // Avoid multiple edges early.
  1932. if (TrueSucc == FalseSucc)
  1933. return false;
  1934. BasicBlock *Parent = BI->getParent();
  1935. bool Changed = false;
  1936. Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
  1937. BasicBlockEdge TrueE(Parent, TrueSucc);
  1938. Changed |= propagateEquality(BranchCond, TrueVal, TrueE);
  1939. Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
  1940. BasicBlockEdge FalseE(Parent, FalseSucc);
  1941. Changed |= propagateEquality(BranchCond, FalseVal, FalseE);
  1942. return Changed;
  1943. }
  1944. // For switches, propagate the case values into the case destinations.
  1945. if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
  1946. Value *SwitchCond = SI->getCondition();
  1947. BasicBlock *Parent = SI->getParent();
  1948. bool Changed = false;
  1949. // Remember how many outgoing edges there are to every successor.
  1950. SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
  1951. for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
  1952. ++SwitchEdges[SI->getSuccessor(i)];
  1953. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  1954. i != e; ++i) {
  1955. BasicBlock *Dst = i.getCaseSuccessor();
  1956. // If there is only a single edge, propagate the case value into it.
  1957. if (SwitchEdges.lookup(Dst) == 1) {
  1958. BasicBlockEdge E(Parent, Dst);
  1959. Changed |= propagateEquality(SwitchCond, i.getCaseValue(), E);
  1960. }
  1961. }
  1962. return Changed;
  1963. }
  1964. // Instructions with void type don't return a value, so there's
  1965. // no point in trying to find redundancies in them.
  1966. if (I->getType()->isVoidTy()) return false;
  1967. uint32_t NextNum = VN.getNextUnusedValueNumber();
  1968. unsigned Num = VN.lookup_or_add(I);
  1969. // Allocations are always uniquely numbered, so we can save time and memory
  1970. // by fast failing them.
  1971. if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
  1972. addToLeaderTable(Num, I, I->getParent());
  1973. return false;
  1974. }
  1975. // If the number we were assigned was a brand new VN, then we don't
  1976. // need to do a lookup to see if the number already exists
  1977. // somewhere in the domtree: it can't!
  1978. if (Num >= NextNum) {
  1979. addToLeaderTable(Num, I, I->getParent());
  1980. return false;
  1981. }
  1982. // Perform fast-path value-number based elimination of values inherited from
  1983. // dominators.
  1984. Value *repl = findLeader(I->getParent(), Num);
  1985. if (!repl) {
  1986. // Failure, just remember this instance for future use.
  1987. addToLeaderTable(Num, I, I->getParent());
  1988. return false;
  1989. }
  1990. // Remove it!
  1991. patchAndReplaceAllUsesWith(I, repl);
  1992. if (MD && repl->getType()->getScalarType()->isPointerTy())
  1993. MD->invalidateCachedPointerInfo(repl);
  1994. markInstructionForDeletion(I);
  1995. return true;
  1996. }
  1997. /// runOnFunction - This is the main transformation entry point for a function.
  1998. bool GVN::runOnFunction(Function& F) {
  1999. if (skipOptnoneFunction(F))
  2000. return false;
  2001. if (!NoLoads)
  2002. MD = &getAnalysis<MemoryDependenceAnalysis>();
  2003. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  2004. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  2005. TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  2006. VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
  2007. VN.setMemDep(MD);
  2008. VN.setDomTree(DT);
  2009. bool Changed = false;
  2010. bool ShouldContinue = true;
  2011. // Merge unconditional branches, allowing PRE to catch more
  2012. // optimization opportunities.
  2013. for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
  2014. BasicBlock *BB = FI++;
  2015. bool removedBlock = MergeBlockIntoPredecessor(
  2016. BB, DT, /* LoopInfo */ nullptr, VN.getAliasAnalysis(), MD);
  2017. if (removedBlock) ++NumGVNBlocks;
  2018. Changed |= removedBlock;
  2019. }
  2020. unsigned Iteration = 0;
  2021. while (ShouldContinue) {
  2022. DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
  2023. ShouldContinue = iterateOnFunction(F);
  2024. Changed |= ShouldContinue;
  2025. ++Iteration;
  2026. }
  2027. if (EnablePRE) {
  2028. // Fabricate val-num for dead-code in order to suppress assertion in
  2029. // performPRE().
  2030. assignValNumForDeadCode();
  2031. bool PREChanged = true;
  2032. while (PREChanged) {
  2033. PREChanged = performPRE(F);
  2034. Changed |= PREChanged;
  2035. }
  2036. }
  2037. // FIXME: Should perform GVN again after PRE does something. PRE can move
  2038. // computations into blocks where they become fully redundant. Note that
  2039. // we can't do this until PRE's critical edge splitting updates memdep.
  2040. // Actually, when this happens, we should just fully integrate PRE into GVN.
  2041. cleanupGlobalSets();
  2042. // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
  2043. // iteration.
  2044. DeadBlocks.clear();
  2045. return Changed;
  2046. }
  2047. bool GVN::processBlock(BasicBlock *BB) {
  2048. // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
  2049. // (and incrementing BI before processing an instruction).
  2050. assert(InstrsToErase.empty() &&
  2051. "We expect InstrsToErase to be empty across iterations");
  2052. if (DeadBlocks.count(BB))
  2053. return false;
  2054. bool ChangedFunction = false;
  2055. for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
  2056. BI != BE;) {
  2057. ChangedFunction |= processInstruction(BI);
  2058. if (InstrsToErase.empty()) {
  2059. ++BI;
  2060. continue;
  2061. }
  2062. // If we need some instructions deleted, do it now.
  2063. NumGVNInstr += InstrsToErase.size();
  2064. // Avoid iterator invalidation.
  2065. bool AtStart = BI == BB->begin();
  2066. if (!AtStart)
  2067. --BI;
  2068. for (SmallVectorImpl<Instruction *>::iterator I = InstrsToErase.begin(),
  2069. E = InstrsToErase.end(); I != E; ++I) {
  2070. DEBUG(dbgs() << "GVN removed: " << **I << '\n');
  2071. if (MD) MD->removeInstruction(*I);
  2072. DEBUG(verifyRemoved(*I));
  2073. (*I)->eraseFromParent();
  2074. }
  2075. InstrsToErase.clear();
  2076. if (AtStart)
  2077. BI = BB->begin();
  2078. else
  2079. ++BI;
  2080. }
  2081. return ChangedFunction;
  2082. }
  2083. // Instantiate an expression in a predecessor that lacked it.
  2084. bool GVN::performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
  2085. unsigned int ValNo) {
  2086. // Because we are going top-down through the block, all value numbers
  2087. // will be available in the predecessor by the time we need them. Any
  2088. // that weren't originally present will have been instantiated earlier
  2089. // in this loop.
  2090. bool success = true;
  2091. for (unsigned i = 0, e = Instr->getNumOperands(); i != e; ++i) {
  2092. Value *Op = Instr->getOperand(i);
  2093. if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
  2094. continue;
  2095. if (Value *V = findLeader(Pred, VN.lookup(Op))) {
  2096. Instr->setOperand(i, V);
  2097. } else {
  2098. success = false;
  2099. break;
  2100. }
  2101. }
  2102. // Fail out if we encounter an operand that is not available in
  2103. // the PRE predecessor. This is typically because of loads which
  2104. // are not value numbered precisely.
  2105. if (!success)
  2106. return false;
  2107. Instr->insertBefore(Pred->getTerminator());
  2108. Instr->setName(Instr->getName() + ".pre");
  2109. Instr->setDebugLoc(Instr->getDebugLoc());
  2110. VN.add(Instr, ValNo);
  2111. // Update the availability map to include the new instruction.
  2112. addToLeaderTable(ValNo, Instr, Pred);
  2113. return true;
  2114. }
  2115. bool GVN::performScalarPRE(Instruction *CurInst) {
  2116. SmallVector<std::pair<Value*, BasicBlock*>, 8> predMap;
  2117. if (isa<AllocaInst>(CurInst) || isa<TerminatorInst>(CurInst) ||
  2118. isa<PHINode>(CurInst) || CurInst->getType()->isVoidTy() ||
  2119. CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
  2120. isa<DbgInfoIntrinsic>(CurInst))
  2121. return false;
  2122. // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
  2123. // sinking the compare again, and it would force the code generator to
  2124. // move the i1 from processor flags or predicate registers into a general
  2125. // purpose register.
  2126. if (isa<CmpInst>(CurInst))
  2127. return false;
  2128. // HLSL Change Begin
  2129. // Don't do PRE on share memory. The PHI may merge two shader memory variable.
  2130. if (PointerType *PT = dyn_cast<PointerType>(CurInst->getType())) {
  2131. if (PT->getAddressSpace() == hlsl::DXIL::kTGSMAddrSpace)
  2132. return false;
  2133. }
  2134. // HLSL Change End
  2135. // We don't currently value number ANY inline asm calls.
  2136. if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
  2137. if (CallI->isInlineAsm())
  2138. return false;
  2139. uint32_t ValNo = VN.lookup(CurInst);
  2140. // Look for the predecessors for PRE opportunities. We're
  2141. // only trying to solve the basic diamond case, where
  2142. // a value is computed in the successor and one predecessor,
  2143. // but not the other. We also explicitly disallow cases
  2144. // where the successor is its own predecessor, because they're
  2145. // more complicated to get right.
  2146. unsigned NumWith = 0;
  2147. unsigned NumWithout = 0;
  2148. BasicBlock *PREPred = nullptr;
  2149. BasicBlock *CurrentBlock = CurInst->getParent();
  2150. predMap.clear();
  2151. for (pred_iterator PI = pred_begin(CurrentBlock), PE = pred_end(CurrentBlock);
  2152. PI != PE; ++PI) {
  2153. BasicBlock *P = *PI;
  2154. // We're not interested in PRE where the block is its
  2155. // own predecessor, or in blocks with predecessors
  2156. // that are not reachable.
  2157. if (P == CurrentBlock) {
  2158. NumWithout = 2;
  2159. break;
  2160. } else if (!DT->isReachableFromEntry(P)) {
  2161. NumWithout = 2;
  2162. break;
  2163. }
  2164. Value *predV = findLeader(P, ValNo);
  2165. if (!predV) {
  2166. predMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P));
  2167. PREPred = P;
  2168. ++NumWithout;
  2169. } else if (predV == CurInst) {
  2170. /* CurInst dominates this predecessor. */
  2171. NumWithout = 2;
  2172. break;
  2173. } else {
  2174. predMap.push_back(std::make_pair(predV, P));
  2175. ++NumWith;
  2176. }
  2177. }
  2178. // Don't do PRE when it might increase code size, i.e. when
  2179. // we would need to insert instructions in more than one pred.
  2180. if (NumWithout > 1 || NumWith == 0)
  2181. return false;
  2182. // We may have a case where all predecessors have the instruction,
  2183. // and we just need to insert a phi node. Otherwise, perform
  2184. // insertion.
  2185. Instruction *PREInstr = nullptr;
  2186. if (NumWithout != 0) {
  2187. // Don't do PRE across indirect branch.
  2188. if (isa<IndirectBrInst>(PREPred->getTerminator()))
  2189. return false;
  2190. // We can't do PRE safely on a critical edge, so instead we schedule
  2191. // the edge to be split and perform the PRE the next time we iterate
  2192. // on the function.
  2193. unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
  2194. if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
  2195. toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
  2196. return false;
  2197. }
  2198. // We need to insert somewhere, so let's give it a shot
  2199. PREInstr = CurInst->clone();
  2200. if (!performScalarPREInsertion(PREInstr, PREPred, ValNo)) {
  2201. // If we failed insertion, make sure we remove the instruction.
  2202. DEBUG(verifyRemoved(PREInstr));
  2203. delete PREInstr;
  2204. return false;
  2205. }
  2206. }
  2207. // Either we should have filled in the PRE instruction, or we should
  2208. // not have needed insertions.
  2209. assert (PREInstr != nullptr || NumWithout == 0);
  2210. ++NumGVNPRE;
  2211. // Create a PHI to make the value available in this block.
  2212. PHINode *Phi =
  2213. PHINode::Create(CurInst->getType(), predMap.size(),
  2214. CurInst->getName() + ".pre-phi", CurrentBlock->begin());
  2215. for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
  2216. if (Value *V = predMap[i].first)
  2217. Phi->addIncoming(V, predMap[i].second);
  2218. else
  2219. Phi->addIncoming(PREInstr, PREPred);
  2220. }
  2221. VN.add(Phi, ValNo);
  2222. addToLeaderTable(ValNo, Phi, CurrentBlock);
  2223. Phi->setDebugLoc(CurInst->getDebugLoc());
  2224. CurInst->replaceAllUsesWith(Phi);
  2225. if (Phi->getType()->getScalarType()->isPointerTy()) {
  2226. // Because we have added a PHI-use of the pointer value, it has now
  2227. // "escaped" from alias analysis' perspective. We need to inform
  2228. // AA of this.
  2229. for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee; ++ii) {
  2230. unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
  2231. VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
  2232. }
  2233. if (MD)
  2234. MD->invalidateCachedPointerInfo(Phi);
  2235. }
  2236. VN.erase(CurInst);
  2237. removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
  2238. DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
  2239. if (MD)
  2240. MD->removeInstruction(CurInst);
  2241. DEBUG(verifyRemoved(CurInst));
  2242. CurInst->eraseFromParent();
  2243. ++NumGVNInstr;
  2244. return true;
  2245. }
  2246. /// Perform a purely local form of PRE that looks for diamond
  2247. /// control flow patterns and attempts to perform simple PRE at the join point.
  2248. bool GVN::performPRE(Function &F) {
  2249. bool Changed = false;
  2250. for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) {
  2251. // Nothing to PRE in the entry block.
  2252. if (CurrentBlock == &F.getEntryBlock())
  2253. continue;
  2254. // Don't perform PRE on a landing pad.
  2255. if (CurrentBlock->isLandingPad())
  2256. continue;
  2257. for (BasicBlock::iterator BI = CurrentBlock->begin(),
  2258. BE = CurrentBlock->end();
  2259. BI != BE;) {
  2260. Instruction *CurInst = BI++;
  2261. Changed = performScalarPRE(CurInst);
  2262. }
  2263. }
  2264. if (splitCriticalEdges())
  2265. Changed = true;
  2266. return Changed;
  2267. }
  2268. /// Split the critical edge connecting the given two blocks, and return
  2269. /// the block inserted to the critical edge.
  2270. BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
  2271. BasicBlock *BB = SplitCriticalEdge(
  2272. Pred, Succ, CriticalEdgeSplittingOptions(getAliasAnalysis(), DT));
  2273. if (MD)
  2274. MD->invalidateCachedPredecessors();
  2275. return BB;
  2276. }
  2277. /// Split critical edges found during the previous
  2278. /// iteration that may enable further optimization.
  2279. bool GVN::splitCriticalEdges() {
  2280. if (toSplit.empty())
  2281. return false;
  2282. do {
  2283. std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
  2284. SplitCriticalEdge(Edge.first, Edge.second,
  2285. CriticalEdgeSplittingOptions(getAliasAnalysis(), DT));
  2286. } while (!toSplit.empty());
  2287. if (MD) MD->invalidateCachedPredecessors();
  2288. return true;
  2289. }
  2290. /// Executes one iteration of GVN
  2291. bool GVN::iterateOnFunction(Function &F) {
  2292. cleanupGlobalSets();
  2293. // Top-down walk of the dominator tree
  2294. bool Changed = false;
  2295. // Save the blocks this function have before transformation begins. GVN may
  2296. // split critical edge, and hence may invalidate the RPO/DT iterator.
  2297. //
  2298. std::vector<BasicBlock *> BBVect;
  2299. BBVect.reserve(256);
  2300. // Needed for value numbering with phi construction to work.
  2301. ReversePostOrderTraversal<Function *> RPOT(&F);
  2302. for (ReversePostOrderTraversal<Function *>::rpo_iterator RI = RPOT.begin(),
  2303. RE = RPOT.end();
  2304. RI != RE; ++RI)
  2305. BBVect.push_back(*RI);
  2306. for (std::vector<BasicBlock *>::iterator I = BBVect.begin(), E = BBVect.end();
  2307. I != E; I++)
  2308. Changed |= processBlock(*I);
  2309. return Changed;
  2310. }
  2311. void GVN::cleanupGlobalSets() {
  2312. VN.clear();
  2313. LeaderTable.clear();
  2314. TableAllocator.Reset();
  2315. }
  2316. /// Verify that the specified instruction does not occur in our
  2317. /// internal data structures.
  2318. void GVN::verifyRemoved(const Instruction *Inst) const {
  2319. VN.verifyRemoved(Inst);
  2320. // Walk through the value number scope to make sure the instruction isn't
  2321. // ferreted away in it.
  2322. for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
  2323. I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
  2324. const LeaderTableEntry *Node = &I->second;
  2325. assert(Node->Val != Inst && "Inst still in value numbering scope!");
  2326. while (Node->Next) {
  2327. Node = Node->Next;
  2328. assert(Node->Val != Inst && "Inst still in value numbering scope!");
  2329. }
  2330. }
  2331. }
  2332. /// BB is declared dead, which implied other blocks become dead as well. This
  2333. /// function is to add all these blocks to "DeadBlocks". For the dead blocks'
  2334. /// live successors, update their phi nodes by replacing the operands
  2335. /// corresponding to dead blocks with UndefVal.
  2336. void GVN::addDeadBlock(BasicBlock *BB) {
  2337. SmallVector<BasicBlock *, 4> NewDead;
  2338. SmallSetVector<BasicBlock *, 4> DF;
  2339. NewDead.push_back(BB);
  2340. while (!NewDead.empty()) {
  2341. BasicBlock *D = NewDead.pop_back_val();
  2342. if (DeadBlocks.count(D))
  2343. continue;
  2344. // All blocks dominated by D are dead.
  2345. SmallVector<BasicBlock *, 8> Dom;
  2346. DT->getDescendants(D, Dom);
  2347. DeadBlocks.insert(Dom.begin(), Dom.end());
  2348. // Figure out the dominance-frontier(D).
  2349. for (SmallVectorImpl<BasicBlock *>::iterator I = Dom.begin(),
  2350. E = Dom.end(); I != E; I++) {
  2351. BasicBlock *B = *I;
  2352. for (succ_iterator SI = succ_begin(B), SE = succ_end(B); SI != SE; SI++) {
  2353. BasicBlock *S = *SI;
  2354. if (DeadBlocks.count(S))
  2355. continue;
  2356. bool AllPredDead = true;
  2357. for (pred_iterator PI = pred_begin(S), PE = pred_end(S); PI != PE; PI++)
  2358. if (!DeadBlocks.count(*PI)) {
  2359. AllPredDead = false;
  2360. break;
  2361. }
  2362. if (!AllPredDead) {
  2363. // S could be proved dead later on. That is why we don't update phi
  2364. // operands at this moment.
  2365. DF.insert(S);
  2366. } else {
  2367. // While S is not dominated by D, it is dead by now. This could take
  2368. // place if S already have a dead predecessor before D is declared
  2369. // dead.
  2370. NewDead.push_back(S);
  2371. }
  2372. }
  2373. }
  2374. }
  2375. // For the dead blocks' live successors, update their phi nodes by replacing
  2376. // the operands corresponding to dead blocks with UndefVal.
  2377. for(SmallSetVector<BasicBlock *, 4>::iterator I = DF.begin(), E = DF.end();
  2378. I != E; I++) {
  2379. BasicBlock *B = *I;
  2380. if (DeadBlocks.count(B))
  2381. continue;
  2382. SmallVector<BasicBlock *, 4> Preds(pred_begin(B), pred_end(B));
  2383. for (SmallVectorImpl<BasicBlock *>::iterator PI = Preds.begin(),
  2384. PE = Preds.end(); PI != PE; PI++) {
  2385. BasicBlock *P = *PI;
  2386. if (!DeadBlocks.count(P))
  2387. continue;
  2388. if (isCriticalEdge(P->getTerminator(), GetSuccessorNumber(P, B))) {
  2389. if (BasicBlock *S = splitCriticalEdges(P, B))
  2390. DeadBlocks.insert(P = S);
  2391. }
  2392. for (BasicBlock::iterator II = B->begin(); isa<PHINode>(II); ++II) {
  2393. PHINode &Phi = cast<PHINode>(*II);
  2394. Phi.setIncomingValue(Phi.getBasicBlockIndex(P),
  2395. UndefValue::get(Phi.getType()));
  2396. }
  2397. }
  2398. }
  2399. }
  2400. // If the given branch is recognized as a foldable branch (i.e. conditional
  2401. // branch with constant condition), it will perform following analyses and
  2402. // transformation.
  2403. // 1) If the dead out-coming edge is a critical-edge, split it. Let
  2404. // R be the target of the dead out-coming edge.
  2405. // 1) Identify the set of dead blocks implied by the branch's dead outcoming
  2406. // edge. The result of this step will be {X| X is dominated by R}
  2407. // 2) Identify those blocks which haves at least one dead prodecessor. The
  2408. // result of this step will be dominance-frontier(R).
  2409. // 3) Update the PHIs in DF(R) by replacing the operands corresponding to
  2410. // dead blocks with "UndefVal" in an hope these PHIs will optimized away.
  2411. //
  2412. // Return true iff *NEW* dead code are found.
  2413. bool GVN::processFoldableCondBr(BranchInst *BI) {
  2414. if (!BI || BI->isUnconditional())
  2415. return false;
  2416. // If a branch has two identical successors, we cannot declare either dead.
  2417. if (BI->getSuccessor(0) == BI->getSuccessor(1))
  2418. return false;
  2419. ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
  2420. if (!Cond)
  2421. return false;
  2422. BasicBlock *DeadRoot = Cond->getZExtValue() ?
  2423. BI->getSuccessor(1) : BI->getSuccessor(0);
  2424. if (DeadBlocks.count(DeadRoot))
  2425. return false;
  2426. if (!DeadRoot->getSinglePredecessor())
  2427. DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
  2428. addDeadBlock(DeadRoot);
  2429. return true;
  2430. }
  2431. // performPRE() will trigger assert if it comes across an instruction without
  2432. // associated val-num. As it normally has far more live instructions than dead
  2433. // instructions, it makes more sense just to "fabricate" a val-number for the
  2434. // dead code than checking if instruction involved is dead or not.
  2435. void GVN::assignValNumForDeadCode() {
  2436. for (SetVector<BasicBlock *>::iterator I = DeadBlocks.begin(),
  2437. E = DeadBlocks.end(); I != E; I++) {
  2438. BasicBlock *BB = *I;
  2439. for (BasicBlock::iterator II = BB->begin(), EE = BB->end();
  2440. II != EE; II++) {
  2441. Instruction *Inst = &*II;
  2442. unsigned ValNum = VN.lookup_or_add(Inst);
  2443. addToLeaderTable(ValNum, Inst, BB);
  2444. }
  2445. }
  2446. }