GVN.cpp 103 KB

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