EarlyCSE.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809
  1. //===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass performs a simple dominator tree walk that eliminates trivially
  10. // redundant instructions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Scalar/EarlyCSE.h"
  14. #include "llvm/ADT/DenseMapInfo.h"
  15. #include "llvm/ADT/Hashing.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/ScopedHashTable.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Analysis/AssumptionCache.h"
  21. #include "llvm/Analysis/GlobalsModRef.h"
  22. #include "llvm/Analysis/GuardUtils.h"
  23. #include "llvm/Analysis/InstructionSimplify.h"
  24. #include "llvm/Analysis/MemorySSA.h"
  25. #include "llvm/Analysis/MemorySSAUpdater.h"
  26. #include "llvm/Analysis/TargetLibraryInfo.h"
  27. #include "llvm/Analysis/TargetTransformInfo.h"
  28. #include "llvm/Analysis/ValueTracking.h"
  29. #include "llvm/IR/BasicBlock.h"
  30. #include "llvm/IR/Constants.h"
  31. #include "llvm/IR/Dominators.h"
  32. #include "llvm/IR/Function.h"
  33. #include "llvm/IR/InstrTypes.h"
  34. #include "llvm/IR/Instruction.h"
  35. #include "llvm/IR/Instructions.h"
  36. #include "llvm/IR/IntrinsicInst.h"
  37. #include "llvm/IR/LLVMContext.h"
  38. #include "llvm/IR/PassManager.h"
  39. #include "llvm/IR/PatternMatch.h"
  40. #include "llvm/IR/Type.h"
  41. #include "llvm/IR/Value.h"
  42. #include "llvm/InitializePasses.h"
  43. #include "llvm/Pass.h"
  44. #include "llvm/Support/Allocator.h"
  45. #include "llvm/Support/AtomicOrdering.h"
  46. #include "llvm/Support/Casting.h"
  47. #include "llvm/Support/Debug.h"
  48. #include "llvm/Support/DebugCounter.h"
  49. #include "llvm/Support/RecyclingAllocator.h"
  50. #include "llvm/Support/raw_ostream.h"
  51. #include "llvm/Transforms/Scalar.h"
  52. #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
  53. #include "llvm/Transforms/Utils/Local.h"
  54. #include <cassert>
  55. #include <deque>
  56. #include <memory>
  57. #include <utility>
  58. using namespace llvm;
  59. using namespace llvm::PatternMatch;
  60. #define DEBUG_TYPE "early-cse"
  61. STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
  62. STATISTIC(NumCSE, "Number of instructions CSE'd");
  63. STATISTIC(NumCSECVP, "Number of compare instructions CVP'd");
  64. STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
  65. STATISTIC(NumCSECall, "Number of call instructions CSE'd");
  66. STATISTIC(NumDSE, "Number of trivial dead stores removed");
  67. DEBUG_COUNTER(CSECounter, "early-cse",
  68. "Controls which instructions are removed");
  69. static cl::opt<unsigned> EarlyCSEMssaOptCap(
  70. "earlycse-mssa-optimization-cap", cl::init(500), cl::Hidden,
  71. cl::desc("Enable imprecision in EarlyCSE in pathological cases, in exchange "
  72. "for faster compile. Caps the MemorySSA clobbering calls."));
  73. static cl::opt<bool> EarlyCSEDebugHash(
  74. "earlycse-debug-hash", cl::init(false), cl::Hidden,
  75. cl::desc("Perform extra assertion checking to verify that SimpleValue's hash "
  76. "function is well-behaved w.r.t. its isEqual predicate"));
  77. //===----------------------------------------------------------------------===//
  78. // SimpleValue
  79. //===----------------------------------------------------------------------===//
  80. namespace {
  81. /// Struct representing the available values in the scoped hash table.
  82. struct SimpleValue {
  83. Instruction *Inst;
  84. SimpleValue(Instruction *I) : Inst(I) {
  85. assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
  86. }
  87. bool isSentinel() const {
  88. return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
  89. Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
  90. }
  91. static bool canHandle(Instruction *Inst) {
  92. // This can only handle non-void readnone functions.
  93. // Also handled are constrained intrinsic that look like the types
  94. // of instruction handled below (UnaryOperator, etc.).
  95. if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
  96. if (Function *F = CI->getCalledFunction()) {
  97. switch ((Intrinsic::ID)F->getIntrinsicID()) {
  98. case Intrinsic::experimental_constrained_fadd:
  99. case Intrinsic::experimental_constrained_fsub:
  100. case Intrinsic::experimental_constrained_fmul:
  101. case Intrinsic::experimental_constrained_fdiv:
  102. case Intrinsic::experimental_constrained_frem:
  103. case Intrinsic::experimental_constrained_fptosi:
  104. case Intrinsic::experimental_constrained_sitofp:
  105. case Intrinsic::experimental_constrained_fptoui:
  106. case Intrinsic::experimental_constrained_uitofp:
  107. case Intrinsic::experimental_constrained_fcmp:
  108. case Intrinsic::experimental_constrained_fcmps: {
  109. auto *CFP = cast<ConstrainedFPIntrinsic>(CI);
  110. if (CFP->getExceptionBehavior() &&
  111. CFP->getExceptionBehavior() == fp::ebStrict)
  112. return false;
  113. // Since we CSE across function calls we must not allow
  114. // the rounding mode to change.
  115. if (CFP->getRoundingMode() &&
  116. CFP->getRoundingMode() == RoundingMode::Dynamic)
  117. return false;
  118. return true;
  119. }
  120. }
  121. }
  122. return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy() &&
  123. // FIXME: Currently the calls which may access the thread id may
  124. // be considered as not accessing the memory. But this is
  125. // problematic for coroutines, since coroutines may resume in a
  126. // different thread. So we disable the optimization here for the
  127. // correctness. However, it may block many other correct
  128. // optimizations. Revert this one when we detect the memory
  129. // accessing kind more precisely.
  130. !CI->getFunction()->isPresplitCoroutine();
  131. }
  132. return isa<CastInst>(Inst) || isa<UnaryOperator>(Inst) ||
  133. isa<BinaryOperator>(Inst) || isa<GetElementPtrInst>(Inst) ||
  134. isa<CmpInst>(Inst) || isa<SelectInst>(Inst) ||
  135. isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
  136. isa<ShuffleVectorInst>(Inst) || isa<ExtractValueInst>(Inst) ||
  137. isa<InsertValueInst>(Inst) || isa<FreezeInst>(Inst);
  138. }
  139. };
  140. } // end anonymous namespace
  141. namespace llvm {
  142. template <> struct DenseMapInfo<SimpleValue> {
  143. static inline SimpleValue getEmptyKey() {
  144. return DenseMapInfo<Instruction *>::getEmptyKey();
  145. }
  146. static inline SimpleValue getTombstoneKey() {
  147. return DenseMapInfo<Instruction *>::getTombstoneKey();
  148. }
  149. static unsigned getHashValue(SimpleValue Val);
  150. static bool isEqual(SimpleValue LHS, SimpleValue RHS);
  151. };
  152. } // end namespace llvm
  153. /// Match a 'select' including an optional 'not's of the condition.
  154. static bool matchSelectWithOptionalNotCond(Value *V, Value *&Cond, Value *&A,
  155. Value *&B,
  156. SelectPatternFlavor &Flavor) {
  157. // Return false if V is not even a select.
  158. if (!match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B))))
  159. return false;
  160. // Look through a 'not' of the condition operand by swapping A/B.
  161. Value *CondNot;
  162. if (match(Cond, m_Not(m_Value(CondNot)))) {
  163. Cond = CondNot;
  164. std::swap(A, B);
  165. }
  166. // Match canonical forms of min/max. We are not using ValueTracking's
  167. // more powerful matchSelectPattern() because it may rely on instruction flags
  168. // such as "nsw". That would be incompatible with the current hashing
  169. // mechanism that may remove flags to increase the likelihood of CSE.
  170. Flavor = SPF_UNKNOWN;
  171. CmpInst::Predicate Pred;
  172. if (!match(Cond, m_ICmp(Pred, m_Specific(A), m_Specific(B)))) {
  173. // Check for commuted variants of min/max by swapping predicate.
  174. // If we do not match the standard or commuted patterns, this is not a
  175. // recognized form of min/max, but it is still a select, so return true.
  176. if (!match(Cond, m_ICmp(Pred, m_Specific(B), m_Specific(A))))
  177. return true;
  178. Pred = ICmpInst::getSwappedPredicate(Pred);
  179. }
  180. switch (Pred) {
  181. case CmpInst::ICMP_UGT: Flavor = SPF_UMAX; break;
  182. case CmpInst::ICMP_ULT: Flavor = SPF_UMIN; break;
  183. case CmpInst::ICMP_SGT: Flavor = SPF_SMAX; break;
  184. case CmpInst::ICMP_SLT: Flavor = SPF_SMIN; break;
  185. // Non-strict inequalities.
  186. case CmpInst::ICMP_ULE: Flavor = SPF_UMIN; break;
  187. case CmpInst::ICMP_UGE: Flavor = SPF_UMAX; break;
  188. case CmpInst::ICMP_SLE: Flavor = SPF_SMIN; break;
  189. case CmpInst::ICMP_SGE: Flavor = SPF_SMAX; break;
  190. default: break;
  191. }
  192. return true;
  193. }
  194. static unsigned getHashValueImpl(SimpleValue Val) {
  195. Instruction *Inst = Val.Inst;
  196. // Hash in all of the operands as pointers.
  197. if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
  198. Value *LHS = BinOp->getOperand(0);
  199. Value *RHS = BinOp->getOperand(1);
  200. if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
  201. std::swap(LHS, RHS);
  202. return hash_combine(BinOp->getOpcode(), LHS, RHS);
  203. }
  204. if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
  205. // Compares can be commuted by swapping the comparands and
  206. // updating the predicate. Choose the form that has the
  207. // comparands in sorted order, or in the case of a tie, the
  208. // one with the lower predicate.
  209. Value *LHS = CI->getOperand(0);
  210. Value *RHS = CI->getOperand(1);
  211. CmpInst::Predicate Pred = CI->getPredicate();
  212. CmpInst::Predicate SwappedPred = CI->getSwappedPredicate();
  213. if (std::tie(LHS, Pred) > std::tie(RHS, SwappedPred)) {
  214. std::swap(LHS, RHS);
  215. Pred = SwappedPred;
  216. }
  217. return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
  218. }
  219. // Hash general selects to allow matching commuted true/false operands.
  220. SelectPatternFlavor SPF;
  221. Value *Cond, *A, *B;
  222. if (matchSelectWithOptionalNotCond(Inst, Cond, A, B, SPF)) {
  223. // Hash min/max (cmp + select) to allow for commuted operands.
  224. // Min/max may also have non-canonical compare predicate (eg, the compare for
  225. // smin may use 'sgt' rather than 'slt'), and non-canonical operands in the
  226. // compare.
  227. // TODO: We should also detect FP min/max.
  228. if (SPF == SPF_SMIN || SPF == SPF_SMAX ||
  229. SPF == SPF_UMIN || SPF == SPF_UMAX) {
  230. if (A > B)
  231. std::swap(A, B);
  232. return hash_combine(Inst->getOpcode(), SPF, A, B);
  233. }
  234. // Hash general selects to allow matching commuted true/false operands.
  235. // If we do not have a compare as the condition, just hash in the condition.
  236. CmpInst::Predicate Pred;
  237. Value *X, *Y;
  238. if (!match(Cond, m_Cmp(Pred, m_Value(X), m_Value(Y))))
  239. return hash_combine(Inst->getOpcode(), Cond, A, B);
  240. // Similar to cmp normalization (above) - canonicalize the predicate value:
  241. // select (icmp Pred, X, Y), A, B --> select (icmp InvPred, X, Y), B, A
  242. if (CmpInst::getInversePredicate(Pred) < Pred) {
  243. Pred = CmpInst::getInversePredicate(Pred);
  244. std::swap(A, B);
  245. }
  246. return hash_combine(Inst->getOpcode(), Pred, X, Y, A, B);
  247. }
  248. if (CastInst *CI = dyn_cast<CastInst>(Inst))
  249. return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
  250. if (FreezeInst *FI = dyn_cast<FreezeInst>(Inst))
  251. return hash_combine(FI->getOpcode(), FI->getOperand(0));
  252. if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
  253. return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
  254. hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
  255. if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
  256. return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
  257. IVI->getOperand(1),
  258. hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
  259. assert((isa<CallInst>(Inst) || isa<GetElementPtrInst>(Inst) ||
  260. isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
  261. isa<ShuffleVectorInst>(Inst) || isa<UnaryOperator>(Inst) ||
  262. isa<FreezeInst>(Inst)) &&
  263. "Invalid/unknown instruction");
  264. // Handle intrinsics with commutative operands.
  265. // TODO: Extend this to handle intrinsics with >2 operands where the 1st
  266. // 2 operands are commutative.
  267. auto *II = dyn_cast<IntrinsicInst>(Inst);
  268. if (II && II->isCommutative() && II->arg_size() == 2) {
  269. Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
  270. if (LHS > RHS)
  271. std::swap(LHS, RHS);
  272. return hash_combine(II->getOpcode(), LHS, RHS);
  273. }
  274. // gc.relocate is 'special' call: its second and third operands are
  275. // not real values, but indices into statepoint's argument list.
  276. // Get values they point to.
  277. if (const GCRelocateInst *GCR = dyn_cast<GCRelocateInst>(Inst))
  278. return hash_combine(GCR->getOpcode(), GCR->getOperand(0),
  279. GCR->getBasePtr(), GCR->getDerivedPtr());
  280. // Mix in the opcode.
  281. return hash_combine(
  282. Inst->getOpcode(),
  283. hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
  284. }
  285. unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
  286. #ifndef NDEBUG
  287. // If -earlycse-debug-hash was specified, return a constant -- this
  288. // will force all hashing to collide, so we'll exhaustively search
  289. // the table for a match, and the assertion in isEqual will fire if
  290. // there's a bug causing equal keys to hash differently.
  291. if (EarlyCSEDebugHash)
  292. return 0;
  293. #endif
  294. return getHashValueImpl(Val);
  295. }
  296. static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS) {
  297. Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
  298. if (LHS.isSentinel() || RHS.isSentinel())
  299. return LHSI == RHSI;
  300. if (LHSI->getOpcode() != RHSI->getOpcode())
  301. return false;
  302. if (LHSI->isIdenticalToWhenDefined(RHSI))
  303. return true;
  304. // If we're not strictly identical, we still might be a commutable instruction
  305. if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
  306. if (!LHSBinOp->isCommutative())
  307. return false;
  308. assert(isa<BinaryOperator>(RHSI) &&
  309. "same opcode, but different instruction type?");
  310. BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
  311. // Commuted equality
  312. return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
  313. LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
  314. }
  315. if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
  316. assert(isa<CmpInst>(RHSI) &&
  317. "same opcode, but different instruction type?");
  318. CmpInst *RHSCmp = cast<CmpInst>(RHSI);
  319. // Commuted equality
  320. return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
  321. LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
  322. LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
  323. }
  324. // TODO: Extend this for >2 args by matching the trailing N-2 args.
  325. auto *LII = dyn_cast<IntrinsicInst>(LHSI);
  326. auto *RII = dyn_cast<IntrinsicInst>(RHSI);
  327. if (LII && RII && LII->getIntrinsicID() == RII->getIntrinsicID() &&
  328. LII->isCommutative() && LII->arg_size() == 2) {
  329. return LII->getArgOperand(0) == RII->getArgOperand(1) &&
  330. LII->getArgOperand(1) == RII->getArgOperand(0);
  331. }
  332. // See comment above in `getHashValue()`.
  333. if (const GCRelocateInst *GCR1 = dyn_cast<GCRelocateInst>(LHSI))
  334. if (const GCRelocateInst *GCR2 = dyn_cast<GCRelocateInst>(RHSI))
  335. return GCR1->getOperand(0) == GCR2->getOperand(0) &&
  336. GCR1->getBasePtr() == GCR2->getBasePtr() &&
  337. GCR1->getDerivedPtr() == GCR2->getDerivedPtr();
  338. // Min/max can occur with commuted operands, non-canonical predicates,
  339. // and/or non-canonical operands.
  340. // Selects can be non-trivially equivalent via inverted conditions and swaps.
  341. SelectPatternFlavor LSPF, RSPF;
  342. Value *CondL, *CondR, *LHSA, *RHSA, *LHSB, *RHSB;
  343. if (matchSelectWithOptionalNotCond(LHSI, CondL, LHSA, LHSB, LSPF) &&
  344. matchSelectWithOptionalNotCond(RHSI, CondR, RHSA, RHSB, RSPF)) {
  345. if (LSPF == RSPF) {
  346. // TODO: We should also detect FP min/max.
  347. if (LSPF == SPF_SMIN || LSPF == SPF_SMAX ||
  348. LSPF == SPF_UMIN || LSPF == SPF_UMAX)
  349. return ((LHSA == RHSA && LHSB == RHSB) ||
  350. (LHSA == RHSB && LHSB == RHSA));
  351. // select Cond, A, B <--> select not(Cond), B, A
  352. if (CondL == CondR && LHSA == RHSA && LHSB == RHSB)
  353. return true;
  354. }
  355. // If the true/false operands are swapped and the conditions are compares
  356. // with inverted predicates, the selects are equal:
  357. // select (icmp Pred, X, Y), A, B <--> select (icmp InvPred, X, Y), B, A
  358. //
  359. // This also handles patterns with a double-negation in the sense of not +
  360. // inverse, because we looked through a 'not' in the matching function and
  361. // swapped A/B:
  362. // select (cmp Pred, X, Y), A, B <--> select (not (cmp InvPred, X, Y)), B, A
  363. //
  364. // This intentionally does NOT handle patterns with a double-negation in
  365. // the sense of not + not, because doing so could result in values
  366. // comparing
  367. // as equal that hash differently in the min/max cases like:
  368. // select (cmp slt, X, Y), X, Y <--> select (not (not (cmp slt, X, Y))), X, Y
  369. // ^ hashes as min ^ would not hash as min
  370. // In the context of the EarlyCSE pass, however, such cases never reach
  371. // this code, as we simplify the double-negation before hashing the second
  372. // select (and so still succeed at CSEing them).
  373. if (LHSA == RHSB && LHSB == RHSA) {
  374. CmpInst::Predicate PredL, PredR;
  375. Value *X, *Y;
  376. if (match(CondL, m_Cmp(PredL, m_Value(X), m_Value(Y))) &&
  377. match(CondR, m_Cmp(PredR, m_Specific(X), m_Specific(Y))) &&
  378. CmpInst::getInversePredicate(PredL) == PredR)
  379. return true;
  380. }
  381. }
  382. return false;
  383. }
  384. bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
  385. // These comparisons are nontrivial, so assert that equality implies
  386. // hash equality (DenseMap demands this as an invariant).
  387. bool Result = isEqualImpl(LHS, RHS);
  388. assert(!Result || (LHS.isSentinel() && LHS.Inst == RHS.Inst) ||
  389. getHashValueImpl(LHS) == getHashValueImpl(RHS));
  390. return Result;
  391. }
  392. //===----------------------------------------------------------------------===//
  393. // CallValue
  394. //===----------------------------------------------------------------------===//
  395. namespace {
  396. /// Struct representing the available call values in the scoped hash
  397. /// table.
  398. struct CallValue {
  399. Instruction *Inst;
  400. CallValue(Instruction *I) : Inst(I) {
  401. assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
  402. }
  403. bool isSentinel() const {
  404. return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
  405. Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
  406. }
  407. static bool canHandle(Instruction *Inst) {
  408. // Don't value number anything that returns void.
  409. if (Inst->getType()->isVoidTy())
  410. return false;
  411. CallInst *CI = dyn_cast<CallInst>(Inst);
  412. if (!CI || !CI->onlyReadsMemory() ||
  413. // FIXME: Currently the calls which may access the thread id may
  414. // be considered as not accessing the memory. But this is
  415. // problematic for coroutines, since coroutines may resume in a
  416. // different thread. So we disable the optimization here for the
  417. // correctness. However, it may block many other correct
  418. // optimizations. Revert this one when we detect the memory
  419. // accessing kind more precisely.
  420. CI->getFunction()->isPresplitCoroutine())
  421. return false;
  422. return true;
  423. }
  424. };
  425. } // end anonymous namespace
  426. namespace llvm {
  427. template <> struct DenseMapInfo<CallValue> {
  428. static inline CallValue getEmptyKey() {
  429. return DenseMapInfo<Instruction *>::getEmptyKey();
  430. }
  431. static inline CallValue getTombstoneKey() {
  432. return DenseMapInfo<Instruction *>::getTombstoneKey();
  433. }
  434. static unsigned getHashValue(CallValue Val);
  435. static bool isEqual(CallValue LHS, CallValue RHS);
  436. };
  437. } // end namespace llvm
  438. unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
  439. Instruction *Inst = Val.Inst;
  440. // Hash all of the operands as pointers and mix in the opcode.
  441. return hash_combine(
  442. Inst->getOpcode(),
  443. hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
  444. }
  445. bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
  446. Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
  447. if (LHS.isSentinel() || RHS.isSentinel())
  448. return LHSI == RHSI;
  449. return LHSI->isIdenticalTo(RHSI);
  450. }
  451. //===----------------------------------------------------------------------===//
  452. // EarlyCSE implementation
  453. //===----------------------------------------------------------------------===//
  454. namespace {
  455. /// A simple and fast domtree-based CSE pass.
  456. ///
  457. /// This pass does a simple depth-first walk over the dominator tree,
  458. /// eliminating trivially redundant instructions and using instsimplify to
  459. /// canonicalize things as it goes. It is intended to be fast and catch obvious
  460. /// cases so that instcombine and other passes are more effective. It is
  461. /// expected that a later pass of GVN will catch the interesting/hard cases.
  462. class EarlyCSE {
  463. public:
  464. const TargetLibraryInfo &TLI;
  465. const TargetTransformInfo &TTI;
  466. DominatorTree &DT;
  467. AssumptionCache &AC;
  468. const SimplifyQuery SQ;
  469. MemorySSA *MSSA;
  470. std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
  471. using AllocatorTy =
  472. RecyclingAllocator<BumpPtrAllocator,
  473. ScopedHashTableVal<SimpleValue, Value *>>;
  474. using ScopedHTType =
  475. ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
  476. AllocatorTy>;
  477. /// A scoped hash table of the current values of all of our simple
  478. /// scalar expressions.
  479. ///
  480. /// As we walk down the domtree, we look to see if instructions are in this:
  481. /// if so, we replace them with what we find, otherwise we insert them so
  482. /// that dominated values can succeed in their lookup.
  483. ScopedHTType AvailableValues;
  484. /// A scoped hash table of the current values of previously encountered
  485. /// memory locations.
  486. ///
  487. /// This allows us to get efficient access to dominating loads or stores when
  488. /// we have a fully redundant load. In addition to the most recent load, we
  489. /// keep track of a generation count of the read, which is compared against
  490. /// the current generation count. The current generation count is incremented
  491. /// after every possibly writing memory operation, which ensures that we only
  492. /// CSE loads with other loads that have no intervening store. Ordering
  493. /// events (such as fences or atomic instructions) increment the generation
  494. /// count as well; essentially, we model these as writes to all possible
  495. /// locations. Note that atomic and/or volatile loads and stores can be
  496. /// present the table; it is the responsibility of the consumer to inspect
  497. /// the atomicity/volatility if needed.
  498. struct LoadValue {
  499. Instruction *DefInst = nullptr;
  500. unsigned Generation = 0;
  501. int MatchingId = -1;
  502. bool IsAtomic = false;
  503. LoadValue() = default;
  504. LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
  505. bool IsAtomic)
  506. : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
  507. IsAtomic(IsAtomic) {}
  508. };
  509. using LoadMapAllocator =
  510. RecyclingAllocator<BumpPtrAllocator,
  511. ScopedHashTableVal<Value *, LoadValue>>;
  512. using LoadHTType =
  513. ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
  514. LoadMapAllocator>;
  515. LoadHTType AvailableLoads;
  516. // A scoped hash table mapping memory locations (represented as typed
  517. // addresses) to generation numbers at which that memory location became
  518. // (henceforth indefinitely) invariant.
  519. using InvariantMapAllocator =
  520. RecyclingAllocator<BumpPtrAllocator,
  521. ScopedHashTableVal<MemoryLocation, unsigned>>;
  522. using InvariantHTType =
  523. ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>,
  524. InvariantMapAllocator>;
  525. InvariantHTType AvailableInvariants;
  526. /// A scoped hash table of the current values of read-only call
  527. /// values.
  528. ///
  529. /// It uses the same generation count as loads.
  530. using CallHTType =
  531. ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>;
  532. CallHTType AvailableCalls;
  533. /// This is the current generation of the memory value.
  534. unsigned CurrentGeneration = 0;
  535. /// Set up the EarlyCSE runner for a particular function.
  536. EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI,
  537. const TargetTransformInfo &TTI, DominatorTree &DT,
  538. AssumptionCache &AC, MemorySSA *MSSA)
  539. : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA),
  540. MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {}
  541. bool run();
  542. private:
  543. unsigned ClobberCounter = 0;
  544. // Almost a POD, but needs to call the constructors for the scoped hash
  545. // tables so that a new scope gets pushed on. These are RAII so that the
  546. // scope gets popped when the NodeScope is destroyed.
  547. class NodeScope {
  548. public:
  549. NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
  550. InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls)
  551. : Scope(AvailableValues), LoadScope(AvailableLoads),
  552. InvariantScope(AvailableInvariants), CallScope(AvailableCalls) {}
  553. NodeScope(const NodeScope &) = delete;
  554. NodeScope &operator=(const NodeScope &) = delete;
  555. private:
  556. ScopedHTType::ScopeTy Scope;
  557. LoadHTType::ScopeTy LoadScope;
  558. InvariantHTType::ScopeTy InvariantScope;
  559. CallHTType::ScopeTy CallScope;
  560. };
  561. // Contains all the needed information to create a stack for doing a depth
  562. // first traversal of the tree. This includes scopes for values, loads, and
  563. // calls as well as the generation. There is a child iterator so that the
  564. // children do not need to be store separately.
  565. class StackNode {
  566. public:
  567. StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
  568. InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
  569. unsigned cg, DomTreeNode *n, DomTreeNode::const_iterator child,
  570. DomTreeNode::const_iterator end)
  571. : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
  572. EndIter(end),
  573. Scopes(AvailableValues, AvailableLoads, AvailableInvariants,
  574. AvailableCalls)
  575. {}
  576. StackNode(const StackNode &) = delete;
  577. StackNode &operator=(const StackNode &) = delete;
  578. // Accessors.
  579. unsigned currentGeneration() const { return CurrentGeneration; }
  580. unsigned childGeneration() const { return ChildGeneration; }
  581. void childGeneration(unsigned generation) { ChildGeneration = generation; }
  582. DomTreeNode *node() { return Node; }
  583. DomTreeNode::const_iterator childIter() const { return ChildIter; }
  584. DomTreeNode *nextChild() {
  585. DomTreeNode *child = *ChildIter;
  586. ++ChildIter;
  587. return child;
  588. }
  589. DomTreeNode::const_iterator end() const { return EndIter; }
  590. bool isProcessed() const { return Processed; }
  591. void process() { Processed = true; }
  592. private:
  593. unsigned CurrentGeneration;
  594. unsigned ChildGeneration;
  595. DomTreeNode *Node;
  596. DomTreeNode::const_iterator ChildIter;
  597. DomTreeNode::const_iterator EndIter;
  598. NodeScope Scopes;
  599. bool Processed = false;
  600. };
  601. /// Wrapper class to handle memory instructions, including loads,
  602. /// stores and intrinsic loads and stores defined by the target.
  603. class ParseMemoryInst {
  604. public:
  605. ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
  606. : Inst(Inst) {
  607. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
  608. IntrID = II->getIntrinsicID();
  609. if (TTI.getTgtMemIntrinsic(II, Info))
  610. return;
  611. if (isHandledNonTargetIntrinsic(IntrID)) {
  612. switch (IntrID) {
  613. case Intrinsic::masked_load:
  614. Info.PtrVal = Inst->getOperand(0);
  615. Info.MatchingId = Intrinsic::masked_load;
  616. Info.ReadMem = true;
  617. Info.WriteMem = false;
  618. Info.IsVolatile = false;
  619. break;
  620. case Intrinsic::masked_store:
  621. Info.PtrVal = Inst->getOperand(1);
  622. // Use the ID of masked load as the "matching id". This will
  623. // prevent matching non-masked loads/stores with masked ones
  624. // (which could be done), but at the moment, the code here
  625. // does not support matching intrinsics with non-intrinsics,
  626. // so keep the MatchingIds specific to masked instructions
  627. // for now (TODO).
  628. Info.MatchingId = Intrinsic::masked_load;
  629. Info.ReadMem = false;
  630. Info.WriteMem = true;
  631. Info.IsVolatile = false;
  632. break;
  633. }
  634. }
  635. }
  636. }
  637. Instruction *get() { return Inst; }
  638. const Instruction *get() const { return Inst; }
  639. bool isLoad() const {
  640. if (IntrID != 0)
  641. return Info.ReadMem;
  642. return isa<LoadInst>(Inst);
  643. }
  644. bool isStore() const {
  645. if (IntrID != 0)
  646. return Info.WriteMem;
  647. return isa<StoreInst>(Inst);
  648. }
  649. bool isAtomic() const {
  650. if (IntrID != 0)
  651. return Info.Ordering != AtomicOrdering::NotAtomic;
  652. return Inst->isAtomic();
  653. }
  654. bool isUnordered() const {
  655. if (IntrID != 0)
  656. return Info.isUnordered();
  657. if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  658. return LI->isUnordered();
  659. } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  660. return SI->isUnordered();
  661. }
  662. // Conservative answer
  663. return !Inst->isAtomic();
  664. }
  665. bool isVolatile() const {
  666. if (IntrID != 0)
  667. return Info.IsVolatile;
  668. if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  669. return LI->isVolatile();
  670. } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  671. return SI->isVolatile();
  672. }
  673. // Conservative answer
  674. return true;
  675. }
  676. bool isInvariantLoad() const {
  677. if (auto *LI = dyn_cast<LoadInst>(Inst))
  678. return LI->hasMetadata(LLVMContext::MD_invariant_load);
  679. return false;
  680. }
  681. bool isValid() const { return getPointerOperand() != nullptr; }
  682. // For regular (non-intrinsic) loads/stores, this is set to -1. For
  683. // intrinsic loads/stores, the id is retrieved from the corresponding
  684. // field in the MemIntrinsicInfo structure. That field contains
  685. // non-negative values only.
  686. int getMatchingId() const {
  687. if (IntrID != 0)
  688. return Info.MatchingId;
  689. return -1;
  690. }
  691. Value *getPointerOperand() const {
  692. if (IntrID != 0)
  693. return Info.PtrVal;
  694. return getLoadStorePointerOperand(Inst);
  695. }
  696. Type *getValueType() const {
  697. // TODO: handle target-specific intrinsics.
  698. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
  699. switch (II->getIntrinsicID()) {
  700. case Intrinsic::masked_load:
  701. return II->getType();
  702. case Intrinsic::masked_store:
  703. return II->getArgOperand(0)->getType();
  704. default:
  705. return nullptr;
  706. }
  707. }
  708. return getLoadStoreType(Inst);
  709. }
  710. bool mayReadFromMemory() const {
  711. if (IntrID != 0)
  712. return Info.ReadMem;
  713. return Inst->mayReadFromMemory();
  714. }
  715. bool mayWriteToMemory() const {
  716. if (IntrID != 0)
  717. return Info.WriteMem;
  718. return Inst->mayWriteToMemory();
  719. }
  720. private:
  721. Intrinsic::ID IntrID = 0;
  722. MemIntrinsicInfo Info;
  723. Instruction *Inst;
  724. };
  725. // This function is to prevent accidentally passing a non-target
  726. // intrinsic ID to TargetTransformInfo.
  727. static bool isHandledNonTargetIntrinsic(Intrinsic::ID ID) {
  728. switch (ID) {
  729. case Intrinsic::masked_load:
  730. case Intrinsic::masked_store:
  731. return true;
  732. }
  733. return false;
  734. }
  735. static bool isHandledNonTargetIntrinsic(const Value *V) {
  736. if (auto *II = dyn_cast<IntrinsicInst>(V))
  737. return isHandledNonTargetIntrinsic(II->getIntrinsicID());
  738. return false;
  739. }
  740. bool processNode(DomTreeNode *Node);
  741. bool handleBranchCondition(Instruction *CondInst, const BranchInst *BI,
  742. const BasicBlock *BB, const BasicBlock *Pred);
  743. Value *getMatchingValue(LoadValue &InVal, ParseMemoryInst &MemInst,
  744. unsigned CurrentGeneration);
  745. bool overridingStores(const ParseMemoryInst &Earlier,
  746. const ParseMemoryInst &Later);
  747. Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
  748. // TODO: We could insert relevant casts on type mismatch here.
  749. if (auto *LI = dyn_cast<LoadInst>(Inst))
  750. return LI->getType() == ExpectedType ? LI : nullptr;
  751. if (auto *SI = dyn_cast<StoreInst>(Inst)) {
  752. Value *V = SI->getValueOperand();
  753. return V->getType() == ExpectedType ? V : nullptr;
  754. }
  755. assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
  756. auto *II = cast<IntrinsicInst>(Inst);
  757. if (isHandledNonTargetIntrinsic(II->getIntrinsicID()))
  758. return getOrCreateResultNonTargetMemIntrinsic(II, ExpectedType);
  759. return TTI.getOrCreateResultFromMemIntrinsic(II, ExpectedType);
  760. }
  761. Value *getOrCreateResultNonTargetMemIntrinsic(IntrinsicInst *II,
  762. Type *ExpectedType) const {
  763. // TODO: We could insert relevant casts on type mismatch here.
  764. switch (II->getIntrinsicID()) {
  765. case Intrinsic::masked_load:
  766. return II->getType() == ExpectedType ? II : nullptr;
  767. case Intrinsic::masked_store: {
  768. Value *V = II->getOperand(0);
  769. return V->getType() == ExpectedType ? V : nullptr;
  770. }
  771. }
  772. return nullptr;
  773. }
  774. /// Return true if the instruction is known to only operate on memory
  775. /// provably invariant in the given "generation".
  776. bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt);
  777. bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
  778. Instruction *EarlierInst, Instruction *LaterInst);
  779. bool isNonTargetIntrinsicMatch(const IntrinsicInst *Earlier,
  780. const IntrinsicInst *Later) {
  781. auto IsSubmask = [](const Value *Mask0, const Value *Mask1) {
  782. // Is Mask0 a submask of Mask1?
  783. if (Mask0 == Mask1)
  784. return true;
  785. if (isa<UndefValue>(Mask0) || isa<UndefValue>(Mask1))
  786. return false;
  787. auto *Vec0 = dyn_cast<ConstantVector>(Mask0);
  788. auto *Vec1 = dyn_cast<ConstantVector>(Mask1);
  789. if (!Vec0 || !Vec1)
  790. return false;
  791. if (Vec0->getType() != Vec1->getType())
  792. return false;
  793. for (int i = 0, e = Vec0->getNumOperands(); i != e; ++i) {
  794. Constant *Elem0 = Vec0->getOperand(i);
  795. Constant *Elem1 = Vec1->getOperand(i);
  796. auto *Int0 = dyn_cast<ConstantInt>(Elem0);
  797. if (Int0 && Int0->isZero())
  798. continue;
  799. auto *Int1 = dyn_cast<ConstantInt>(Elem1);
  800. if (Int1 && !Int1->isZero())
  801. continue;
  802. if (isa<UndefValue>(Elem0) || isa<UndefValue>(Elem1))
  803. return false;
  804. if (Elem0 == Elem1)
  805. continue;
  806. return false;
  807. }
  808. return true;
  809. };
  810. auto PtrOp = [](const IntrinsicInst *II) {
  811. if (II->getIntrinsicID() == Intrinsic::masked_load)
  812. return II->getOperand(0);
  813. if (II->getIntrinsicID() == Intrinsic::masked_store)
  814. return II->getOperand(1);
  815. llvm_unreachable("Unexpected IntrinsicInst");
  816. };
  817. auto MaskOp = [](const IntrinsicInst *II) {
  818. if (II->getIntrinsicID() == Intrinsic::masked_load)
  819. return II->getOperand(2);
  820. if (II->getIntrinsicID() == Intrinsic::masked_store)
  821. return II->getOperand(3);
  822. llvm_unreachable("Unexpected IntrinsicInst");
  823. };
  824. auto ThruOp = [](const IntrinsicInst *II) {
  825. if (II->getIntrinsicID() == Intrinsic::masked_load)
  826. return II->getOperand(3);
  827. llvm_unreachable("Unexpected IntrinsicInst");
  828. };
  829. if (PtrOp(Earlier) != PtrOp(Later))
  830. return false;
  831. Intrinsic::ID IDE = Earlier->getIntrinsicID();
  832. Intrinsic::ID IDL = Later->getIntrinsicID();
  833. // We could really use specific intrinsic classes for masked loads
  834. // and stores in IntrinsicInst.h.
  835. if (IDE == Intrinsic::masked_load && IDL == Intrinsic::masked_load) {
  836. // Trying to replace later masked load with the earlier one.
  837. // Check that the pointers are the same, and
  838. // - masks and pass-throughs are the same, or
  839. // - replacee's pass-through is "undef" and replacer's mask is a
  840. // super-set of the replacee's mask.
  841. if (MaskOp(Earlier) == MaskOp(Later) && ThruOp(Earlier) == ThruOp(Later))
  842. return true;
  843. if (!isa<UndefValue>(ThruOp(Later)))
  844. return false;
  845. return IsSubmask(MaskOp(Later), MaskOp(Earlier));
  846. }
  847. if (IDE == Intrinsic::masked_store && IDL == Intrinsic::masked_load) {
  848. // Trying to replace a load of a stored value with the store's value.
  849. // Check that the pointers are the same, and
  850. // - load's mask is a subset of store's mask, and
  851. // - load's pass-through is "undef".
  852. if (!IsSubmask(MaskOp(Later), MaskOp(Earlier)))
  853. return false;
  854. return isa<UndefValue>(ThruOp(Later));
  855. }
  856. if (IDE == Intrinsic::masked_load && IDL == Intrinsic::masked_store) {
  857. // Trying to remove a store of the loaded value.
  858. // Check that the pointers are the same, and
  859. // - store's mask is a subset of the load's mask.
  860. return IsSubmask(MaskOp(Later), MaskOp(Earlier));
  861. }
  862. if (IDE == Intrinsic::masked_store && IDL == Intrinsic::masked_store) {
  863. // Trying to remove a dead store (earlier).
  864. // Check that the pointers are the same,
  865. // - the to-be-removed store's mask is a subset of the other store's
  866. // mask.
  867. return IsSubmask(MaskOp(Earlier), MaskOp(Later));
  868. }
  869. return false;
  870. }
  871. void removeMSSA(Instruction &Inst) {
  872. if (!MSSA)
  873. return;
  874. if (VerifyMemorySSA)
  875. MSSA->verifyMemorySSA();
  876. // Removing a store here can leave MemorySSA in an unoptimized state by
  877. // creating MemoryPhis that have identical arguments and by creating
  878. // MemoryUses whose defining access is not an actual clobber. The phi case
  879. // is handled by MemorySSA when passing OptimizePhis = true to
  880. // removeMemoryAccess. The non-optimized MemoryUse case is lazily updated
  881. // by MemorySSA's getClobberingMemoryAccess.
  882. MSSAUpdater->removeMemoryAccess(&Inst, true);
  883. }
  884. };
  885. } // end anonymous namespace
  886. /// Determine if the memory referenced by LaterInst is from the same heap
  887. /// version as EarlierInst.
  888. /// This is currently called in two scenarios:
  889. ///
  890. /// load p
  891. /// ...
  892. /// load p
  893. ///
  894. /// and
  895. ///
  896. /// x = load p
  897. /// ...
  898. /// store x, p
  899. ///
  900. /// in both cases we want to verify that there are no possible writes to the
  901. /// memory referenced by p between the earlier and later instruction.
  902. bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
  903. unsigned LaterGeneration,
  904. Instruction *EarlierInst,
  905. Instruction *LaterInst) {
  906. // Check the simple memory generation tracking first.
  907. if (EarlierGeneration == LaterGeneration)
  908. return true;
  909. if (!MSSA)
  910. return false;
  911. // If MemorySSA has determined that one of EarlierInst or LaterInst does not
  912. // read/write memory, then we can safely return true here.
  913. // FIXME: We could be more aggressive when checking doesNotAccessMemory(),
  914. // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass
  915. // by also checking the MemorySSA MemoryAccess on the instruction. Initial
  916. // experiments suggest this isn't worthwhile, at least for C/C++ code compiled
  917. // with the default optimization pipeline.
  918. auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst);
  919. if (!EarlierMA)
  920. return true;
  921. auto *LaterMA = MSSA->getMemoryAccess(LaterInst);
  922. if (!LaterMA)
  923. return true;
  924. // Since we know LaterDef dominates LaterInst and EarlierInst dominates
  925. // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
  926. // EarlierInst and LaterInst and neither can any other write that potentially
  927. // clobbers LaterInst.
  928. MemoryAccess *LaterDef;
  929. if (ClobberCounter < EarlyCSEMssaOptCap) {
  930. LaterDef = MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
  931. ClobberCounter++;
  932. } else
  933. LaterDef = LaterMA->getDefiningAccess();
  934. return MSSA->dominates(LaterDef, EarlierMA);
  935. }
  936. bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) {
  937. // A location loaded from with an invariant_load is assumed to *never* change
  938. // within the visible scope of the compilation.
  939. if (auto *LI = dyn_cast<LoadInst>(I))
  940. if (LI->hasMetadata(LLVMContext::MD_invariant_load))
  941. return true;
  942. auto MemLocOpt = MemoryLocation::getOrNone(I);
  943. if (!MemLocOpt)
  944. // "target" intrinsic forms of loads aren't currently known to
  945. // MemoryLocation::get. TODO
  946. return false;
  947. MemoryLocation MemLoc = *MemLocOpt;
  948. if (!AvailableInvariants.count(MemLoc))
  949. return false;
  950. // Is the generation at which this became invariant older than the
  951. // current one?
  952. return AvailableInvariants.lookup(MemLoc) <= GenAt;
  953. }
  954. bool EarlyCSE::handleBranchCondition(Instruction *CondInst,
  955. const BranchInst *BI, const BasicBlock *BB,
  956. const BasicBlock *Pred) {
  957. assert(BI->isConditional() && "Should be a conditional branch!");
  958. assert(BI->getCondition() == CondInst && "Wrong condition?");
  959. assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
  960. auto *TorF = (BI->getSuccessor(0) == BB)
  961. ? ConstantInt::getTrue(BB->getContext())
  962. : ConstantInt::getFalse(BB->getContext());
  963. auto MatchBinOp = [](Instruction *I, unsigned Opcode, Value *&LHS,
  964. Value *&RHS) {
  965. if (Opcode == Instruction::And &&
  966. match(I, m_LogicalAnd(m_Value(LHS), m_Value(RHS))))
  967. return true;
  968. else if (Opcode == Instruction::Or &&
  969. match(I, m_LogicalOr(m_Value(LHS), m_Value(RHS))))
  970. return true;
  971. return false;
  972. };
  973. // If the condition is AND operation, we can propagate its operands into the
  974. // true branch. If it is OR operation, we can propagate them into the false
  975. // branch.
  976. unsigned PropagateOpcode =
  977. (BI->getSuccessor(0) == BB) ? Instruction::And : Instruction::Or;
  978. bool MadeChanges = false;
  979. SmallVector<Instruction *, 4> WorkList;
  980. SmallPtrSet<Instruction *, 4> Visited;
  981. WorkList.push_back(CondInst);
  982. while (!WorkList.empty()) {
  983. Instruction *Curr = WorkList.pop_back_val();
  984. AvailableValues.insert(Curr, TorF);
  985. LLVM_DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
  986. << Curr->getName() << "' as " << *TorF << " in "
  987. << BB->getName() << "\n");
  988. if (!DebugCounter::shouldExecute(CSECounter)) {
  989. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  990. } else {
  991. // Replace all dominated uses with the known value.
  992. if (unsigned Count = replaceDominatedUsesWith(Curr, TorF, DT,
  993. BasicBlockEdge(Pred, BB))) {
  994. NumCSECVP += Count;
  995. MadeChanges = true;
  996. }
  997. }
  998. Value *LHS, *RHS;
  999. if (MatchBinOp(Curr, PropagateOpcode, LHS, RHS))
  1000. for (auto *Op : { LHS, RHS })
  1001. if (Instruction *OPI = dyn_cast<Instruction>(Op))
  1002. if (SimpleValue::canHandle(OPI) && Visited.insert(OPI).second)
  1003. WorkList.push_back(OPI);
  1004. }
  1005. return MadeChanges;
  1006. }
  1007. Value *EarlyCSE::getMatchingValue(LoadValue &InVal, ParseMemoryInst &MemInst,
  1008. unsigned CurrentGeneration) {
  1009. if (InVal.DefInst == nullptr)
  1010. return nullptr;
  1011. if (InVal.MatchingId != MemInst.getMatchingId())
  1012. return nullptr;
  1013. // We don't yet handle removing loads with ordering of any kind.
  1014. if (MemInst.isVolatile() || !MemInst.isUnordered())
  1015. return nullptr;
  1016. // We can't replace an atomic load with one which isn't also atomic.
  1017. if (MemInst.isLoad() && !InVal.IsAtomic && MemInst.isAtomic())
  1018. return nullptr;
  1019. // The value V returned from this function is used differently depending
  1020. // on whether MemInst is a load or a store. If it's a load, we will replace
  1021. // MemInst with V, if it's a store, we will check if V is the same as the
  1022. // available value.
  1023. bool MemInstMatching = !MemInst.isLoad();
  1024. Instruction *Matching = MemInstMatching ? MemInst.get() : InVal.DefInst;
  1025. Instruction *Other = MemInstMatching ? InVal.DefInst : MemInst.get();
  1026. // For stores check the result values before checking memory generation
  1027. // (otherwise isSameMemGeneration may crash).
  1028. Value *Result = MemInst.isStore()
  1029. ? getOrCreateResult(Matching, Other->getType())
  1030. : nullptr;
  1031. if (MemInst.isStore() && InVal.DefInst != Result)
  1032. return nullptr;
  1033. // Deal with non-target memory intrinsics.
  1034. bool MatchingNTI = isHandledNonTargetIntrinsic(Matching);
  1035. bool OtherNTI = isHandledNonTargetIntrinsic(Other);
  1036. if (OtherNTI != MatchingNTI)
  1037. return nullptr;
  1038. if (OtherNTI && MatchingNTI) {
  1039. if (!isNonTargetIntrinsicMatch(cast<IntrinsicInst>(InVal.DefInst),
  1040. cast<IntrinsicInst>(MemInst.get())))
  1041. return nullptr;
  1042. }
  1043. if (!isOperatingOnInvariantMemAt(MemInst.get(), InVal.Generation) &&
  1044. !isSameMemGeneration(InVal.Generation, CurrentGeneration, InVal.DefInst,
  1045. MemInst.get()))
  1046. return nullptr;
  1047. if (!Result)
  1048. Result = getOrCreateResult(Matching, Other->getType());
  1049. return Result;
  1050. }
  1051. bool EarlyCSE::overridingStores(const ParseMemoryInst &Earlier,
  1052. const ParseMemoryInst &Later) {
  1053. // Can we remove Earlier store because of Later store?
  1054. assert(Earlier.isUnordered() && !Earlier.isVolatile() &&
  1055. "Violated invariant");
  1056. if (Earlier.getPointerOperand() != Later.getPointerOperand())
  1057. return false;
  1058. if (!Earlier.getValueType() || !Later.getValueType() ||
  1059. Earlier.getValueType() != Later.getValueType())
  1060. return false;
  1061. if (Earlier.getMatchingId() != Later.getMatchingId())
  1062. return false;
  1063. // At the moment, we don't remove ordered stores, but do remove
  1064. // unordered atomic stores. There's no special requirement (for
  1065. // unordered atomics) about removing atomic stores only in favor of
  1066. // other atomic stores since we were going to execute the non-atomic
  1067. // one anyway and the atomic one might never have become visible.
  1068. if (!Earlier.isUnordered() || !Later.isUnordered())
  1069. return false;
  1070. // Deal with non-target memory intrinsics.
  1071. bool ENTI = isHandledNonTargetIntrinsic(Earlier.get());
  1072. bool LNTI = isHandledNonTargetIntrinsic(Later.get());
  1073. if (ENTI && LNTI)
  1074. return isNonTargetIntrinsicMatch(cast<IntrinsicInst>(Earlier.get()),
  1075. cast<IntrinsicInst>(Later.get()));
  1076. // Because of the check above, at least one of them is false.
  1077. // For now disallow matching intrinsics with non-intrinsics,
  1078. // so assume that the stores match if neither is an intrinsic.
  1079. return ENTI == LNTI;
  1080. }
  1081. bool EarlyCSE::processNode(DomTreeNode *Node) {
  1082. bool Changed = false;
  1083. BasicBlock *BB = Node->getBlock();
  1084. // If this block has a single predecessor, then the predecessor is the parent
  1085. // of the domtree node and all of the live out memory values are still current
  1086. // in this block. If this block has multiple predecessors, then they could
  1087. // have invalidated the live-out memory values of our parent value. For now,
  1088. // just be conservative and invalidate memory if this block has multiple
  1089. // predecessors.
  1090. if (!BB->getSinglePredecessor())
  1091. ++CurrentGeneration;
  1092. // If this node has a single predecessor which ends in a conditional branch,
  1093. // we can infer the value of the branch condition given that we took this
  1094. // path. We need the single predecessor to ensure there's not another path
  1095. // which reaches this block where the condition might hold a different
  1096. // value. Since we're adding this to the scoped hash table (like any other
  1097. // def), it will have been popped if we encounter a future merge block.
  1098. if (BasicBlock *Pred = BB->getSinglePredecessor()) {
  1099. auto *BI = dyn_cast<BranchInst>(Pred->getTerminator());
  1100. if (BI && BI->isConditional()) {
  1101. auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
  1102. if (CondInst && SimpleValue::canHandle(CondInst))
  1103. Changed |= handleBranchCondition(CondInst, BI, BB, Pred);
  1104. }
  1105. }
  1106. /// LastStore - Keep track of the last non-volatile store that we saw... for
  1107. /// as long as there in no instruction that reads memory. If we see a store
  1108. /// to the same location, we delete the dead store. This zaps trivial dead
  1109. /// stores which can occur in bitfield code among other things.
  1110. Instruction *LastStore = nullptr;
  1111. // See if any instructions in the block can be eliminated. If so, do it. If
  1112. // not, add them to AvailableValues.
  1113. for (Instruction &Inst : make_early_inc_range(*BB)) {
  1114. // Dead instructions should just be removed.
  1115. if (isInstructionTriviallyDead(&Inst, &TLI)) {
  1116. LLVM_DEBUG(dbgs() << "EarlyCSE DCE: " << Inst << '\n');
  1117. if (!DebugCounter::shouldExecute(CSECounter)) {
  1118. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  1119. continue;
  1120. }
  1121. salvageKnowledge(&Inst, &AC);
  1122. salvageDebugInfo(Inst);
  1123. removeMSSA(Inst);
  1124. Inst.eraseFromParent();
  1125. Changed = true;
  1126. ++NumSimplify;
  1127. continue;
  1128. }
  1129. // Skip assume intrinsics, they don't really have side effects (although
  1130. // they're marked as such to ensure preservation of control dependencies),
  1131. // and this pass will not bother with its removal. However, we should mark
  1132. // its condition as true for all dominated blocks.
  1133. if (auto *Assume = dyn_cast<AssumeInst>(&Inst)) {
  1134. auto *CondI = dyn_cast<Instruction>(Assume->getArgOperand(0));
  1135. if (CondI && SimpleValue::canHandle(CondI)) {
  1136. LLVM_DEBUG(dbgs() << "EarlyCSE considering assumption: " << Inst
  1137. << '\n');
  1138. AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
  1139. } else
  1140. LLVM_DEBUG(dbgs() << "EarlyCSE skipping assumption: " << Inst << '\n');
  1141. continue;
  1142. }
  1143. // Likewise, noalias intrinsics don't actually write.
  1144. if (match(&Inst,
  1145. m_Intrinsic<Intrinsic::experimental_noalias_scope_decl>())) {
  1146. LLVM_DEBUG(dbgs() << "EarlyCSE skipping noalias intrinsic: " << Inst
  1147. << '\n');
  1148. continue;
  1149. }
  1150. // Skip sideeffect intrinsics, for the same reason as assume intrinsics.
  1151. if (match(&Inst, m_Intrinsic<Intrinsic::sideeffect>())) {
  1152. LLVM_DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << Inst << '\n');
  1153. continue;
  1154. }
  1155. // Skip pseudoprobe intrinsics, for the same reason as assume intrinsics.
  1156. if (match(&Inst, m_Intrinsic<Intrinsic::pseudoprobe>())) {
  1157. LLVM_DEBUG(dbgs() << "EarlyCSE skipping pseudoprobe: " << Inst << '\n');
  1158. continue;
  1159. }
  1160. // We can skip all invariant.start intrinsics since they only read memory,
  1161. // and we can forward values across it. For invariant starts without
  1162. // invariant ends, we can use the fact that the invariantness never ends to
  1163. // start a scope in the current generaton which is true for all future
  1164. // generations. Also, we dont need to consume the last store since the
  1165. // semantics of invariant.start allow us to perform DSE of the last
  1166. // store, if there was a store following invariant.start. Consider:
  1167. //
  1168. // store 30, i8* p
  1169. // invariant.start(p)
  1170. // store 40, i8* p
  1171. // We can DSE the store to 30, since the store 40 to invariant location p
  1172. // causes undefined behaviour.
  1173. if (match(&Inst, m_Intrinsic<Intrinsic::invariant_start>())) {
  1174. // If there are any uses, the scope might end.
  1175. if (!Inst.use_empty())
  1176. continue;
  1177. MemoryLocation MemLoc =
  1178. MemoryLocation::getForArgument(&cast<CallInst>(Inst), 1, TLI);
  1179. // Don't start a scope if we already have a better one pushed
  1180. if (!AvailableInvariants.count(MemLoc))
  1181. AvailableInvariants.insert(MemLoc, CurrentGeneration);
  1182. continue;
  1183. }
  1184. if (isGuard(&Inst)) {
  1185. if (auto *CondI =
  1186. dyn_cast<Instruction>(cast<CallInst>(Inst).getArgOperand(0))) {
  1187. if (SimpleValue::canHandle(CondI)) {
  1188. // Do we already know the actual value of this condition?
  1189. if (auto *KnownCond = AvailableValues.lookup(CondI)) {
  1190. // Is the condition known to be true?
  1191. if (isa<ConstantInt>(KnownCond) &&
  1192. cast<ConstantInt>(KnownCond)->isOne()) {
  1193. LLVM_DEBUG(dbgs()
  1194. << "EarlyCSE removing guard: " << Inst << '\n');
  1195. salvageKnowledge(&Inst, &AC);
  1196. removeMSSA(Inst);
  1197. Inst.eraseFromParent();
  1198. Changed = true;
  1199. continue;
  1200. } else
  1201. // Use the known value if it wasn't true.
  1202. cast<CallInst>(Inst).setArgOperand(0, KnownCond);
  1203. }
  1204. // The condition we're on guarding here is true for all dominated
  1205. // locations.
  1206. AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
  1207. }
  1208. }
  1209. // Guard intrinsics read all memory, but don't write any memory.
  1210. // Accordingly, don't update the generation but consume the last store (to
  1211. // avoid an incorrect DSE).
  1212. LastStore = nullptr;
  1213. continue;
  1214. }
  1215. // If the instruction can be simplified (e.g. X+0 = X) then replace it with
  1216. // its simpler value.
  1217. if (Value *V = simplifyInstruction(&Inst, SQ)) {
  1218. LLVM_DEBUG(dbgs() << "EarlyCSE Simplify: " << Inst << " to: " << *V
  1219. << '\n');
  1220. if (!DebugCounter::shouldExecute(CSECounter)) {
  1221. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  1222. } else {
  1223. bool Killed = false;
  1224. if (!Inst.use_empty()) {
  1225. Inst.replaceAllUsesWith(V);
  1226. Changed = true;
  1227. }
  1228. if (isInstructionTriviallyDead(&Inst, &TLI)) {
  1229. salvageKnowledge(&Inst, &AC);
  1230. removeMSSA(Inst);
  1231. Inst.eraseFromParent();
  1232. Changed = true;
  1233. Killed = true;
  1234. }
  1235. if (Changed)
  1236. ++NumSimplify;
  1237. if (Killed)
  1238. continue;
  1239. }
  1240. }
  1241. // If this is a simple instruction that we can value number, process it.
  1242. if (SimpleValue::canHandle(&Inst)) {
  1243. if (auto *CI = dyn_cast<ConstrainedFPIntrinsic>(&Inst)) {
  1244. assert(CI->getExceptionBehavior() != fp::ebStrict &&
  1245. "Unexpected ebStrict from SimpleValue::canHandle()");
  1246. assert((!CI->getRoundingMode() ||
  1247. CI->getRoundingMode() != RoundingMode::Dynamic) &&
  1248. "Unexpected dynamic rounding from SimpleValue::canHandle()");
  1249. }
  1250. // See if the instruction has an available value. If so, use it.
  1251. if (Value *V = AvailableValues.lookup(&Inst)) {
  1252. LLVM_DEBUG(dbgs() << "EarlyCSE CSE: " << Inst << " to: " << *V
  1253. << '\n');
  1254. if (!DebugCounter::shouldExecute(CSECounter)) {
  1255. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  1256. continue;
  1257. }
  1258. if (auto *I = dyn_cast<Instruction>(V)) {
  1259. // If I being poison triggers UB, there is no need to drop those
  1260. // flags. Otherwise, only retain flags present on both I and Inst.
  1261. // TODO: Currently some fast-math flags are not treated as
  1262. // poison-generating even though they should. Until this is fixed,
  1263. // always retain flags present on both I and Inst for floating point
  1264. // instructions.
  1265. if (isa<FPMathOperator>(I) || (I->hasPoisonGeneratingFlags() && !programUndefinedIfPoison(I)))
  1266. I->andIRFlags(&Inst);
  1267. }
  1268. Inst.replaceAllUsesWith(V);
  1269. salvageKnowledge(&Inst, &AC);
  1270. removeMSSA(Inst);
  1271. Inst.eraseFromParent();
  1272. Changed = true;
  1273. ++NumCSE;
  1274. continue;
  1275. }
  1276. // Otherwise, just remember that this value is available.
  1277. AvailableValues.insert(&Inst, &Inst);
  1278. continue;
  1279. }
  1280. ParseMemoryInst MemInst(&Inst, TTI);
  1281. // If this is a non-volatile load, process it.
  1282. if (MemInst.isValid() && MemInst.isLoad()) {
  1283. // (conservatively) we can't peak past the ordering implied by this
  1284. // operation, but we can add this load to our set of available values
  1285. if (MemInst.isVolatile() || !MemInst.isUnordered()) {
  1286. LastStore = nullptr;
  1287. ++CurrentGeneration;
  1288. }
  1289. if (MemInst.isInvariantLoad()) {
  1290. // If we pass an invariant load, we know that memory location is
  1291. // indefinitely constant from the moment of first dereferenceability.
  1292. // We conservatively treat the invariant_load as that moment. If we
  1293. // pass a invariant load after already establishing a scope, don't
  1294. // restart it since we want to preserve the earliest point seen.
  1295. auto MemLoc = MemoryLocation::get(&Inst);
  1296. if (!AvailableInvariants.count(MemLoc))
  1297. AvailableInvariants.insert(MemLoc, CurrentGeneration);
  1298. }
  1299. // If we have an available version of this load, and if it is the right
  1300. // generation or the load is known to be from an invariant location,
  1301. // replace this instruction.
  1302. //
  1303. // If either the dominating load or the current load are invariant, then
  1304. // we can assume the current load loads the same value as the dominating
  1305. // load.
  1306. LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
  1307. if (Value *Op = getMatchingValue(InVal, MemInst, CurrentGeneration)) {
  1308. LLVM_DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << Inst
  1309. << " to: " << *InVal.DefInst << '\n');
  1310. if (!DebugCounter::shouldExecute(CSECounter)) {
  1311. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  1312. continue;
  1313. }
  1314. if (!Inst.use_empty())
  1315. Inst.replaceAllUsesWith(Op);
  1316. salvageKnowledge(&Inst, &AC);
  1317. removeMSSA(Inst);
  1318. Inst.eraseFromParent();
  1319. Changed = true;
  1320. ++NumCSELoad;
  1321. continue;
  1322. }
  1323. // Otherwise, remember that we have this instruction.
  1324. AvailableLoads.insert(MemInst.getPointerOperand(),
  1325. LoadValue(&Inst, CurrentGeneration,
  1326. MemInst.getMatchingId(),
  1327. MemInst.isAtomic()));
  1328. LastStore = nullptr;
  1329. continue;
  1330. }
  1331. // If this instruction may read from memory or throw (and potentially read
  1332. // from memory in the exception handler), forget LastStore. Load/store
  1333. // intrinsics will indicate both a read and a write to memory. The target
  1334. // may override this (e.g. so that a store intrinsic does not read from
  1335. // memory, and thus will be treated the same as a regular store for
  1336. // commoning purposes).
  1337. if ((Inst.mayReadFromMemory() || Inst.mayThrow()) &&
  1338. !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
  1339. LastStore = nullptr;
  1340. // If this is a read-only call, process it.
  1341. if (CallValue::canHandle(&Inst)) {
  1342. // If we have an available version of this call, and if it is the right
  1343. // generation, replace this instruction.
  1344. std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(&Inst);
  1345. if (InVal.first != nullptr &&
  1346. isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
  1347. &Inst)) {
  1348. LLVM_DEBUG(dbgs() << "EarlyCSE CSE CALL: " << Inst
  1349. << " to: " << *InVal.first << '\n');
  1350. if (!DebugCounter::shouldExecute(CSECounter)) {
  1351. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  1352. continue;
  1353. }
  1354. if (!Inst.use_empty())
  1355. Inst.replaceAllUsesWith(InVal.first);
  1356. salvageKnowledge(&Inst, &AC);
  1357. removeMSSA(Inst);
  1358. Inst.eraseFromParent();
  1359. Changed = true;
  1360. ++NumCSECall;
  1361. continue;
  1362. }
  1363. // Otherwise, remember that we have this instruction.
  1364. AvailableCalls.insert(&Inst, std::make_pair(&Inst, CurrentGeneration));
  1365. continue;
  1366. }
  1367. // A release fence requires that all stores complete before it, but does
  1368. // not prevent the reordering of following loads 'before' the fence. As a
  1369. // result, we don't need to consider it as writing to memory and don't need
  1370. // to advance the generation. We do need to prevent DSE across the fence,
  1371. // but that's handled above.
  1372. if (auto *FI = dyn_cast<FenceInst>(&Inst))
  1373. if (FI->getOrdering() == AtomicOrdering::Release) {
  1374. assert(Inst.mayReadFromMemory() && "relied on to prevent DSE above");
  1375. continue;
  1376. }
  1377. // write back DSE - If we write back the same value we just loaded from
  1378. // the same location and haven't passed any intervening writes or ordering
  1379. // operations, we can remove the write. The primary benefit is in allowing
  1380. // the available load table to remain valid and value forward past where
  1381. // the store originally was.
  1382. if (MemInst.isValid() && MemInst.isStore()) {
  1383. LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
  1384. if (InVal.DefInst &&
  1385. InVal.DefInst == getMatchingValue(InVal, MemInst, CurrentGeneration)) {
  1386. // It is okay to have a LastStore to a different pointer here if MemorySSA
  1387. // tells us that the load and store are from the same memory generation.
  1388. // In that case, LastStore should keep its present value since we're
  1389. // removing the current store.
  1390. assert((!LastStore ||
  1391. ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
  1392. MemInst.getPointerOperand() ||
  1393. MSSA) &&
  1394. "can't have an intervening store if not using MemorySSA!");
  1395. LLVM_DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << Inst << '\n');
  1396. if (!DebugCounter::shouldExecute(CSECounter)) {
  1397. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  1398. continue;
  1399. }
  1400. salvageKnowledge(&Inst, &AC);
  1401. removeMSSA(Inst);
  1402. Inst.eraseFromParent();
  1403. Changed = true;
  1404. ++NumDSE;
  1405. // We can avoid incrementing the generation count since we were able
  1406. // to eliminate this store.
  1407. continue;
  1408. }
  1409. }
  1410. // Okay, this isn't something we can CSE at all. Check to see if it is
  1411. // something that could modify memory. If so, our available memory values
  1412. // cannot be used so bump the generation count.
  1413. if (Inst.mayWriteToMemory()) {
  1414. ++CurrentGeneration;
  1415. if (MemInst.isValid() && MemInst.isStore()) {
  1416. // We do a trivial form of DSE if there are two stores to the same
  1417. // location with no intervening loads. Delete the earlier store.
  1418. if (LastStore) {
  1419. if (overridingStores(ParseMemoryInst(LastStore, TTI), MemInst)) {
  1420. LLVM_DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
  1421. << " due to: " << Inst << '\n');
  1422. if (!DebugCounter::shouldExecute(CSECounter)) {
  1423. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  1424. } else {
  1425. salvageKnowledge(&Inst, &AC);
  1426. removeMSSA(*LastStore);
  1427. LastStore->eraseFromParent();
  1428. Changed = true;
  1429. ++NumDSE;
  1430. LastStore = nullptr;
  1431. }
  1432. }
  1433. // fallthrough - we can exploit information about this store
  1434. }
  1435. // Okay, we just invalidated anything we knew about loaded values. Try
  1436. // to salvage *something* by remembering that the stored value is a live
  1437. // version of the pointer. It is safe to forward from volatile stores
  1438. // to non-volatile loads, so we don't have to check for volatility of
  1439. // the store.
  1440. AvailableLoads.insert(MemInst.getPointerOperand(),
  1441. LoadValue(&Inst, CurrentGeneration,
  1442. MemInst.getMatchingId(),
  1443. MemInst.isAtomic()));
  1444. // Remember that this was the last unordered store we saw for DSE. We
  1445. // don't yet handle DSE on ordered or volatile stores since we don't
  1446. // have a good way to model the ordering requirement for following
  1447. // passes once the store is removed. We could insert a fence, but
  1448. // since fences are slightly stronger than stores in their ordering,
  1449. // it's not clear this is a profitable transform. Another option would
  1450. // be to merge the ordering with that of the post dominating store.
  1451. if (MemInst.isUnordered() && !MemInst.isVolatile())
  1452. LastStore = &Inst;
  1453. else
  1454. LastStore = nullptr;
  1455. }
  1456. }
  1457. }
  1458. return Changed;
  1459. }
  1460. bool EarlyCSE::run() {
  1461. // Note, deque is being used here because there is significant performance
  1462. // gains over vector when the container becomes very large due to the
  1463. // specific access patterns. For more information see the mailing list
  1464. // discussion on this:
  1465. // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
  1466. std::deque<StackNode *> nodesToProcess;
  1467. bool Changed = false;
  1468. // Process the root node.
  1469. nodesToProcess.push_back(new StackNode(
  1470. AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
  1471. CurrentGeneration, DT.getRootNode(),
  1472. DT.getRootNode()->begin(), DT.getRootNode()->end()));
  1473. assert(!CurrentGeneration && "Create a new EarlyCSE instance to rerun it.");
  1474. // Process the stack.
  1475. while (!nodesToProcess.empty()) {
  1476. // Grab the first item off the stack. Set the current generation, remove
  1477. // the node from the stack, and process it.
  1478. StackNode *NodeToProcess = nodesToProcess.back();
  1479. // Initialize class members.
  1480. CurrentGeneration = NodeToProcess->currentGeneration();
  1481. // Check if the node needs to be processed.
  1482. if (!NodeToProcess->isProcessed()) {
  1483. // Process the node.
  1484. Changed |= processNode(NodeToProcess->node());
  1485. NodeToProcess->childGeneration(CurrentGeneration);
  1486. NodeToProcess->process();
  1487. } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
  1488. // Push the next child onto the stack.
  1489. DomTreeNode *child = NodeToProcess->nextChild();
  1490. nodesToProcess.push_back(
  1491. new StackNode(AvailableValues, AvailableLoads, AvailableInvariants,
  1492. AvailableCalls, NodeToProcess->childGeneration(),
  1493. child, child->begin(), child->end()));
  1494. } else {
  1495. // It has been processed, and there are no more children to process,
  1496. // so delete it and pop it off the stack.
  1497. delete NodeToProcess;
  1498. nodesToProcess.pop_back();
  1499. }
  1500. } // while (!nodes...)
  1501. return Changed;
  1502. }
  1503. PreservedAnalyses EarlyCSEPass::run(Function &F,
  1504. FunctionAnalysisManager &AM) {
  1505. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  1506. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  1507. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  1508. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  1509. auto *MSSA =
  1510. UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
  1511. EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
  1512. if (!CSE.run())
  1513. return PreservedAnalyses::all();
  1514. PreservedAnalyses PA;
  1515. PA.preserveSet<CFGAnalyses>();
  1516. if (UseMemorySSA)
  1517. PA.preserve<MemorySSAAnalysis>();
  1518. return PA;
  1519. }
  1520. void EarlyCSEPass::printPipeline(
  1521. raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
  1522. static_cast<PassInfoMixin<EarlyCSEPass> *>(this)->printPipeline(
  1523. OS, MapClassName2PassName);
  1524. OS << "<";
  1525. if (UseMemorySSA)
  1526. OS << "memssa";
  1527. OS << ">";
  1528. }
  1529. namespace {
  1530. /// A simple and fast domtree-based CSE pass.
  1531. ///
  1532. /// This pass does a simple depth-first walk over the dominator tree,
  1533. /// eliminating trivially redundant instructions and using instsimplify to
  1534. /// canonicalize things as it goes. It is intended to be fast and catch obvious
  1535. /// cases so that instcombine and other passes are more effective. It is
  1536. /// expected that a later pass of GVN will catch the interesting/hard cases.
  1537. template<bool UseMemorySSA>
  1538. class EarlyCSELegacyCommonPass : public FunctionPass {
  1539. public:
  1540. static char ID;
  1541. EarlyCSELegacyCommonPass() : FunctionPass(ID) {
  1542. if (UseMemorySSA)
  1543. initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry());
  1544. else
  1545. initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
  1546. }
  1547. bool runOnFunction(Function &F) override {
  1548. if (skipFunction(F))
  1549. return false;
  1550. auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  1551. auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  1552. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1553. auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1554. auto *MSSA =
  1555. UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
  1556. EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
  1557. return CSE.run();
  1558. }
  1559. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1560. AU.addRequired<AssumptionCacheTracker>();
  1561. AU.addRequired<DominatorTreeWrapperPass>();
  1562. AU.addRequired<TargetLibraryInfoWrapperPass>();
  1563. AU.addRequired<TargetTransformInfoWrapperPass>();
  1564. if (UseMemorySSA) {
  1565. AU.addRequired<AAResultsWrapperPass>();
  1566. AU.addRequired<MemorySSAWrapperPass>();
  1567. AU.addPreserved<MemorySSAWrapperPass>();
  1568. }
  1569. AU.addPreserved<GlobalsAAWrapperPass>();
  1570. AU.addPreserved<AAResultsWrapperPass>();
  1571. AU.setPreservesCFG();
  1572. }
  1573. };
  1574. } // end anonymous namespace
  1575. using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
  1576. template<>
  1577. char EarlyCSELegacyPass::ID = 0;
  1578. INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
  1579. false)
  1580. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  1581. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  1582. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  1583. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  1584. INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
  1585. using EarlyCSEMemSSALegacyPass =
  1586. EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
  1587. template<>
  1588. char EarlyCSEMemSSALegacyPass::ID = 0;
  1589. FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) {
  1590. if (UseMemorySSA)
  1591. return new EarlyCSEMemSSALegacyPass();
  1592. else
  1593. return new EarlyCSELegacyPass();
  1594. }
  1595. INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
  1596. "Early CSE w/ MemorySSA", false, false)
  1597. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  1598. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  1599. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  1600. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  1601. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  1602. INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
  1603. INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
  1604. "Early CSE w/ MemorySSA", false, false)