EarlyCSE.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. //===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
  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 a simple dominator tree walk that eliminates trivially
  11. // redundant instructions.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Scalar/EarlyCSE.h"
  15. #include "llvm/ADT/Hashing.h"
  16. #include "llvm/ADT/ScopedHashTable.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/Analysis/AssumptionCache.h"
  19. #include "llvm/Analysis/InstructionSimplify.h"
  20. #include "llvm/Analysis/TargetLibraryInfo.h"
  21. #include "llvm/Analysis/TargetTransformInfo.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/Dominators.h"
  24. #include "llvm/IR/Instructions.h"
  25. #include "llvm/IR/IntrinsicInst.h"
  26. #include "llvm/IR/PatternMatch.h"
  27. #include "llvm/Pass.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/RecyclingAllocator.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include "llvm/Transforms/Scalar.h"
  32. #include "llvm/Transforms/Utils/Local.h"
  33. #include <deque>
  34. using namespace llvm;
  35. using namespace llvm::PatternMatch;
  36. #define DEBUG_TYPE "early-cse"
  37. STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
  38. STATISTIC(NumCSE, "Number of instructions CSE'd");
  39. STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
  40. STATISTIC(NumCSECall, "Number of call instructions CSE'd");
  41. STATISTIC(NumDSE, "Number of trivial dead stores removed");
  42. //===----------------------------------------------------------------------===//
  43. // SimpleValue
  44. //===----------------------------------------------------------------------===//
  45. namespace {
  46. /// \brief Struct representing the available values in the scoped hash table.
  47. struct SimpleValue {
  48. Instruction *Inst;
  49. SimpleValue(Instruction *I) : Inst(I) {
  50. assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
  51. }
  52. bool isSentinel() const {
  53. return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
  54. Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
  55. }
  56. static bool canHandle(Instruction *Inst) {
  57. // This can only handle non-void readnone functions.
  58. if (CallInst *CI = dyn_cast<CallInst>(Inst))
  59. return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
  60. return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
  61. isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
  62. isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
  63. isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
  64. isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
  65. }
  66. };
  67. }
  68. namespace llvm {
  69. template <> struct DenseMapInfo<SimpleValue> {
  70. static inline SimpleValue getEmptyKey() {
  71. return DenseMapInfo<Instruction *>::getEmptyKey();
  72. }
  73. static inline SimpleValue getTombstoneKey() {
  74. return DenseMapInfo<Instruction *>::getTombstoneKey();
  75. }
  76. static unsigned getHashValue(SimpleValue Val);
  77. static bool isEqual(SimpleValue LHS, SimpleValue RHS);
  78. };
  79. }
  80. unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
  81. Instruction *Inst = Val.Inst;
  82. // Hash in all of the operands as pointers.
  83. if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
  84. Value *LHS = BinOp->getOperand(0);
  85. Value *RHS = BinOp->getOperand(1);
  86. if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
  87. std::swap(LHS, RHS);
  88. if (isa<OverflowingBinaryOperator>(BinOp)) {
  89. // Hash the overflow behavior
  90. unsigned Overflow =
  91. BinOp->hasNoSignedWrap() * OverflowingBinaryOperator::NoSignedWrap |
  92. BinOp->hasNoUnsignedWrap() *
  93. OverflowingBinaryOperator::NoUnsignedWrap;
  94. return hash_combine(BinOp->getOpcode(), Overflow, LHS, RHS);
  95. }
  96. return hash_combine(BinOp->getOpcode(), LHS, RHS);
  97. }
  98. if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
  99. Value *LHS = CI->getOperand(0);
  100. Value *RHS = CI->getOperand(1);
  101. CmpInst::Predicate Pred = CI->getPredicate();
  102. if (Inst->getOperand(0) > Inst->getOperand(1)) {
  103. std::swap(LHS, RHS);
  104. Pred = CI->getSwappedPredicate();
  105. }
  106. return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
  107. }
  108. if (CastInst *CI = dyn_cast<CastInst>(Inst))
  109. return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
  110. if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
  111. return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
  112. hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
  113. if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
  114. return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
  115. IVI->getOperand(1),
  116. hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
  117. assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
  118. isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
  119. isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
  120. isa<ShuffleVectorInst>(Inst)) &&
  121. "Invalid/unknown instruction");
  122. // Mix in the opcode.
  123. return hash_combine(
  124. Inst->getOpcode(),
  125. hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
  126. }
  127. bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
  128. Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
  129. if (LHS.isSentinel() || RHS.isSentinel())
  130. return LHSI == RHSI;
  131. if (LHSI->getOpcode() != RHSI->getOpcode())
  132. return false;
  133. if (LHSI->isIdenticalTo(RHSI))
  134. return true;
  135. // If we're not strictly identical, we still might be a commutable instruction
  136. if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
  137. if (!LHSBinOp->isCommutative())
  138. return false;
  139. assert(isa<BinaryOperator>(RHSI) &&
  140. "same opcode, but different instruction type?");
  141. BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
  142. // Check overflow attributes
  143. if (isa<OverflowingBinaryOperator>(LHSBinOp)) {
  144. assert(isa<OverflowingBinaryOperator>(RHSBinOp) &&
  145. "same opcode, but different operator type?");
  146. if (LHSBinOp->hasNoUnsignedWrap() != RHSBinOp->hasNoUnsignedWrap() ||
  147. LHSBinOp->hasNoSignedWrap() != RHSBinOp->hasNoSignedWrap())
  148. return false;
  149. }
  150. // Commuted equality
  151. return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
  152. LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
  153. }
  154. if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
  155. assert(isa<CmpInst>(RHSI) &&
  156. "same opcode, but different instruction type?");
  157. CmpInst *RHSCmp = cast<CmpInst>(RHSI);
  158. // Commuted equality
  159. return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
  160. LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
  161. LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
  162. }
  163. return false;
  164. }
  165. //===----------------------------------------------------------------------===//
  166. // CallValue
  167. //===----------------------------------------------------------------------===//
  168. namespace {
  169. /// \brief Struct representing the available call values in the scoped hash
  170. /// table.
  171. struct CallValue {
  172. Instruction *Inst;
  173. CallValue(Instruction *I) : Inst(I) {
  174. assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
  175. }
  176. bool isSentinel() const {
  177. return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
  178. Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
  179. }
  180. static bool canHandle(Instruction *Inst) {
  181. // Don't value number anything that returns void.
  182. if (Inst->getType()->isVoidTy())
  183. return false;
  184. CallInst *CI = dyn_cast<CallInst>(Inst);
  185. if (!CI || !CI->onlyReadsMemory())
  186. return false;
  187. return true;
  188. }
  189. };
  190. }
  191. namespace llvm {
  192. template <> struct DenseMapInfo<CallValue> {
  193. static inline CallValue getEmptyKey() {
  194. return DenseMapInfo<Instruction *>::getEmptyKey();
  195. }
  196. static inline CallValue getTombstoneKey() {
  197. return DenseMapInfo<Instruction *>::getTombstoneKey();
  198. }
  199. static unsigned getHashValue(CallValue Val);
  200. static bool isEqual(CallValue LHS, CallValue RHS);
  201. };
  202. }
  203. unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
  204. Instruction *Inst = Val.Inst;
  205. // Hash all of the operands as pointers and mix in the opcode.
  206. return hash_combine(
  207. Inst->getOpcode(),
  208. hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
  209. }
  210. bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
  211. Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
  212. if (LHS.isSentinel() || RHS.isSentinel())
  213. return LHSI == RHSI;
  214. return LHSI->isIdenticalTo(RHSI);
  215. }
  216. //===----------------------------------------------------------------------===//
  217. // EarlyCSE implementation
  218. //===----------------------------------------------------------------------===//
  219. namespace {
  220. /// \brief A simple and fast domtree-based CSE pass.
  221. ///
  222. /// This pass does a simple depth-first walk over the dominator tree,
  223. /// eliminating trivially redundant instructions and using instsimplify to
  224. /// canonicalize things as it goes. It is intended to be fast and catch obvious
  225. /// cases so that instcombine and other passes are more effective. It is
  226. /// expected that a later pass of GVN will catch the interesting/hard cases.
  227. class EarlyCSE {
  228. public:
  229. Function &F;
  230. const TargetLibraryInfo &TLI;
  231. const TargetTransformInfo &TTI;
  232. DominatorTree &DT;
  233. AssumptionCache &AC;
  234. typedef RecyclingAllocator<
  235. BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
  236. typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
  237. AllocatorTy> ScopedHTType;
  238. /// \brief A scoped hash table of the current values of all of our simple
  239. /// scalar expressions.
  240. ///
  241. /// As we walk down the domtree, we look to see if instructions are in this:
  242. /// if so, we replace them with what we find, otherwise we insert them so
  243. /// that dominated values can succeed in their lookup.
  244. ScopedHTType AvailableValues;
  245. /// \brief A scoped hash table of the current values of loads.
  246. ///
  247. /// This allows us to get efficient access to dominating loads when we have
  248. /// a fully redundant load. In addition to the most recent load, we keep
  249. /// track of a generation count of the read, which is compared against the
  250. /// current generation count. The current generation count is incremented
  251. /// after every possibly writing memory operation, which ensures that we only
  252. /// CSE loads with other loads that have no intervening store.
  253. typedef RecyclingAllocator<
  254. BumpPtrAllocator,
  255. ScopedHashTableVal<Value *, std::pair<Value *, unsigned>>>
  256. LoadMapAllocator;
  257. typedef ScopedHashTable<Value *, std::pair<Value *, unsigned>,
  258. DenseMapInfo<Value *>, LoadMapAllocator> LoadHTType;
  259. LoadHTType AvailableLoads;
  260. /// \brief A scoped hash table of the current values of read-only call
  261. /// values.
  262. ///
  263. /// It uses the same generation count as loads.
  264. typedef ScopedHashTable<CallValue, std::pair<Value *, unsigned>> CallHTType;
  265. CallHTType AvailableCalls;
  266. /// \brief This is the current generation of the memory value.
  267. unsigned CurrentGeneration;
  268. /// \brief Set up the EarlyCSE runner for a particular function.
  269. EarlyCSE(Function &F, const TargetLibraryInfo &TLI,
  270. const TargetTransformInfo &TTI, DominatorTree &DT,
  271. AssumptionCache &AC)
  272. : F(F), TLI(TLI), TTI(TTI), DT(DT), AC(AC), CurrentGeneration(0) {}
  273. bool run();
  274. private:
  275. // Almost a POD, but needs to call the constructors for the scoped hash
  276. // tables so that a new scope gets pushed on. These are RAII so that the
  277. // scope gets popped when the NodeScope is destroyed.
  278. class NodeScope {
  279. public:
  280. NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
  281. CallHTType &AvailableCalls)
  282. : Scope(AvailableValues), LoadScope(AvailableLoads),
  283. CallScope(AvailableCalls) {}
  284. private:
  285. NodeScope(const NodeScope &) = delete;
  286. void operator=(const NodeScope &) = delete;
  287. ScopedHTType::ScopeTy Scope;
  288. LoadHTType::ScopeTy LoadScope;
  289. CallHTType::ScopeTy CallScope;
  290. };
  291. // Contains all the needed information to create a stack for doing a depth
  292. // first tranversal of the tree. This includes scopes for values, loads, and
  293. // calls as well as the generation. There is a child iterator so that the
  294. // children do not need to be store spearately.
  295. class StackNode {
  296. public:
  297. StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
  298. CallHTType &AvailableCalls, unsigned cg, DomTreeNode *n,
  299. DomTreeNode::iterator child, DomTreeNode::iterator end)
  300. : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
  301. EndIter(end), Scopes(AvailableValues, AvailableLoads, AvailableCalls),
  302. Processed(false) {}
  303. // Accessors.
  304. unsigned currentGeneration() { return CurrentGeneration; }
  305. unsigned childGeneration() { return ChildGeneration; }
  306. void childGeneration(unsigned generation) { ChildGeneration = generation; }
  307. DomTreeNode *node() { return Node; }
  308. DomTreeNode::iterator childIter() { return ChildIter; }
  309. DomTreeNode *nextChild() {
  310. DomTreeNode *child = *ChildIter;
  311. ++ChildIter;
  312. return child;
  313. }
  314. DomTreeNode::iterator end() { return EndIter; }
  315. bool isProcessed() { return Processed; }
  316. void process() { Processed = true; }
  317. private:
  318. StackNode(const StackNode &) = delete;
  319. void operator=(const StackNode &) = delete;
  320. // Members.
  321. unsigned CurrentGeneration;
  322. unsigned ChildGeneration;
  323. DomTreeNode *Node;
  324. DomTreeNode::iterator ChildIter;
  325. DomTreeNode::iterator EndIter;
  326. NodeScope Scopes;
  327. bool Processed;
  328. };
  329. /// \brief Wrapper class to handle memory instructions, including loads,
  330. /// stores and intrinsic loads and stores defined by the target.
  331. class ParseMemoryInst {
  332. public:
  333. ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
  334. : Load(false), Store(false), Vol(false), MayReadFromMemory(false),
  335. MayWriteToMemory(false), MatchingId(-1), Ptr(nullptr) {
  336. MayReadFromMemory = Inst->mayReadFromMemory();
  337. MayWriteToMemory = Inst->mayWriteToMemory();
  338. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
  339. MemIntrinsicInfo Info;
  340. if (!TTI.getTgtMemIntrinsic(II, Info))
  341. return;
  342. if (Info.NumMemRefs == 1) {
  343. Store = Info.WriteMem;
  344. Load = Info.ReadMem;
  345. MatchingId = Info.MatchingId;
  346. MayReadFromMemory = Info.ReadMem;
  347. MayWriteToMemory = Info.WriteMem;
  348. Vol = Info.Vol;
  349. Ptr = Info.PtrVal;
  350. }
  351. } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  352. Load = true;
  353. Vol = !LI->isSimple();
  354. Ptr = LI->getPointerOperand();
  355. } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  356. Store = true;
  357. Vol = !SI->isSimple();
  358. Ptr = SI->getPointerOperand();
  359. }
  360. }
  361. bool isLoad() { return Load; }
  362. bool isStore() { return Store; }
  363. bool isVolatile() { return Vol; }
  364. bool isMatchingMemLoc(const ParseMemoryInst &Inst) {
  365. return Ptr == Inst.Ptr && MatchingId == Inst.MatchingId;
  366. }
  367. bool isValid() { return Ptr != nullptr; }
  368. int getMatchingId() { return MatchingId; }
  369. Value *getPtr() { return Ptr; }
  370. bool mayReadFromMemory() { return MayReadFromMemory; }
  371. bool mayWriteToMemory() { return MayWriteToMemory; }
  372. private:
  373. bool Load;
  374. bool Store;
  375. bool Vol;
  376. bool MayReadFromMemory;
  377. bool MayWriteToMemory;
  378. // For regular (non-intrinsic) loads/stores, this is set to -1. For
  379. // intrinsic loads/stores, the id is retrieved from the corresponding
  380. // field in the MemIntrinsicInfo structure. That field contains
  381. // non-negative values only.
  382. int MatchingId;
  383. Value *Ptr;
  384. };
  385. bool processNode(DomTreeNode *Node);
  386. Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
  387. if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
  388. return LI;
  389. else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
  390. return SI->getValueOperand();
  391. assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
  392. return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
  393. ExpectedType);
  394. }
  395. };
  396. }
  397. bool EarlyCSE::processNode(DomTreeNode *Node) {
  398. BasicBlock *BB = Node->getBlock();
  399. // If this block has a single predecessor, then the predecessor is the parent
  400. // of the domtree node and all of the live out memory values are still current
  401. // in this block. If this block has multiple predecessors, then they could
  402. // have invalidated the live-out memory values of our parent value. For now,
  403. // just be conservative and invalidate memory if this block has multiple
  404. // predecessors.
  405. if (!BB->getSinglePredecessor())
  406. ++CurrentGeneration;
  407. // If this node has a single predecessor which ends in a conditional branch,
  408. // we can infer the value of the branch condition given that we took this
  409. // path. We need the single predeccesor to ensure there's not another path
  410. // which reaches this block where the condition might hold a different
  411. // value. Since we're adding this to the scoped hash table (like any other
  412. // def), it will have been popped if we encounter a future merge block.
  413. if (BasicBlock *Pred = BB->getSinglePredecessor())
  414. if (auto *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
  415. if (BI->isConditional())
  416. if (auto *CondInst = dyn_cast<Instruction>(BI->getCondition()))
  417. if (SimpleValue::canHandle(CondInst)) {
  418. assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
  419. auto *ConditionalConstant = (BI->getSuccessor(0) == BB) ?
  420. ConstantInt::getTrue(BB->getContext()) :
  421. ConstantInt::getFalse(BB->getContext());
  422. AvailableValues.insert(CondInst, ConditionalConstant);
  423. DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
  424. << CondInst->getName() << "' as " << *ConditionalConstant
  425. << " in " << BB->getName() << "\n");
  426. // Replace all dominated uses with the known value
  427. replaceDominatedUsesWith(CondInst, ConditionalConstant, DT,
  428. BasicBlockEdge(Pred, BB));
  429. }
  430. /// LastStore - Keep track of the last non-volatile store that we saw... for
  431. /// as long as there in no instruction that reads memory. If we see a store
  432. /// to the same location, we delete the dead store. This zaps trivial dead
  433. /// stores which can occur in bitfield code among other things.
  434. Instruction *LastStore = nullptr;
  435. bool Changed = false;
  436. const DataLayout &DL = BB->getModule()->getDataLayout();
  437. // See if any instructions in the block can be eliminated. If so, do it. If
  438. // not, add them to AvailableValues.
  439. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
  440. Instruction *Inst = I++;
  441. // Dead instructions should just be removed.
  442. if (isInstructionTriviallyDead(Inst, &TLI)) {
  443. DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
  444. Inst->eraseFromParent();
  445. Changed = true;
  446. ++NumSimplify;
  447. continue;
  448. }
  449. // Skip assume intrinsics, they don't really have side effects (although
  450. // they're marked as such to ensure preservation of control dependencies),
  451. // and this pass will not disturb any of the assumption's control
  452. // dependencies.
  453. if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
  454. DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
  455. continue;
  456. }
  457. // If the instruction can be simplified (e.g. X+0 = X) then replace it with
  458. // its simpler value.
  459. if (Value *V = SimplifyInstruction(Inst, DL, &TLI, &DT, &AC)) {
  460. DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
  461. Inst->replaceAllUsesWith(V);
  462. Inst->eraseFromParent();
  463. Changed = true;
  464. ++NumSimplify;
  465. continue;
  466. }
  467. // If this is a simple instruction that we can value number, process it.
  468. if (SimpleValue::canHandle(Inst)) {
  469. // See if the instruction has an available value. If so, use it.
  470. if (Value *V = AvailableValues.lookup(Inst)) {
  471. DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
  472. Inst->replaceAllUsesWith(V);
  473. Inst->eraseFromParent();
  474. Changed = true;
  475. ++NumCSE;
  476. continue;
  477. }
  478. // Otherwise, just remember that this value is available.
  479. AvailableValues.insert(Inst, Inst);
  480. continue;
  481. }
  482. ParseMemoryInst MemInst(Inst, TTI);
  483. // If this is a non-volatile load, process it.
  484. if (MemInst.isValid() && MemInst.isLoad()) {
  485. // Ignore volatile loads.
  486. if (MemInst.isVolatile()) {
  487. LastStore = nullptr;
  488. // Don't CSE across synchronization boundaries.
  489. if (Inst->mayWriteToMemory())
  490. ++CurrentGeneration;
  491. continue;
  492. }
  493. // If we have an available version of this load, and if it is the right
  494. // generation, replace this instruction.
  495. std::pair<Value *, unsigned> InVal =
  496. AvailableLoads.lookup(MemInst.getPtr());
  497. if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
  498. Value *Op = getOrCreateResult(InVal.first, Inst->getType());
  499. if (Op != nullptr) {
  500. DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
  501. << " to: " << *InVal.first << '\n');
  502. if (!Inst->use_empty())
  503. Inst->replaceAllUsesWith(Op);
  504. Inst->eraseFromParent();
  505. Changed = true;
  506. ++NumCSELoad;
  507. continue;
  508. }
  509. }
  510. // Otherwise, remember that we have this instruction.
  511. AvailableLoads.insert(MemInst.getPtr(), std::pair<Value *, unsigned>(
  512. Inst, CurrentGeneration));
  513. LastStore = nullptr;
  514. continue;
  515. }
  516. // If this instruction may read from memory, forget LastStore.
  517. // Load/store intrinsics will indicate both a read and a write to
  518. // memory. The target may override this (e.g. so that a store intrinsic
  519. // does not read from memory, and thus will be treated the same as a
  520. // regular store for commoning purposes).
  521. if (Inst->mayReadFromMemory() &&
  522. !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
  523. LastStore = nullptr;
  524. // If this is a read-only call, process it.
  525. if (CallValue::canHandle(Inst)) {
  526. // If we have an available version of this call, and if it is the right
  527. // generation, replace this instruction.
  528. std::pair<Value *, unsigned> InVal = AvailableCalls.lookup(Inst);
  529. if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
  530. DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
  531. << " to: " << *InVal.first << '\n');
  532. if (!Inst->use_empty())
  533. Inst->replaceAllUsesWith(InVal.first);
  534. Inst->eraseFromParent();
  535. Changed = true;
  536. ++NumCSECall;
  537. continue;
  538. }
  539. // Otherwise, remember that we have this instruction.
  540. AvailableCalls.insert(
  541. Inst, std::pair<Value *, unsigned>(Inst, CurrentGeneration));
  542. continue;
  543. }
  544. // Okay, this isn't something we can CSE at all. Check to see if it is
  545. // something that could modify memory. If so, our available memory values
  546. // cannot be used so bump the generation count.
  547. if (Inst->mayWriteToMemory()) {
  548. ++CurrentGeneration;
  549. if (MemInst.isValid() && MemInst.isStore()) {
  550. // We do a trivial form of DSE if there are two stores to the same
  551. // location with no intervening loads. Delete the earlier store.
  552. if (LastStore) {
  553. ParseMemoryInst LastStoreMemInst(LastStore, TTI);
  554. if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
  555. DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
  556. << " due to: " << *Inst << '\n');
  557. LastStore->eraseFromParent();
  558. Changed = true;
  559. ++NumDSE;
  560. LastStore = nullptr;
  561. }
  562. // fallthrough - we can exploit information about this store
  563. }
  564. // Okay, we just invalidated anything we knew about loaded values. Try
  565. // to salvage *something* by remembering that the stored value is a live
  566. // version of the pointer. It is safe to forward from volatile stores
  567. // to non-volatile loads, so we don't have to check for volatility of
  568. // the store.
  569. AvailableLoads.insert(MemInst.getPtr(), std::pair<Value *, unsigned>(
  570. Inst, CurrentGeneration));
  571. // Remember that this was the last store we saw for DSE.
  572. if (!MemInst.isVolatile())
  573. LastStore = Inst;
  574. }
  575. }
  576. }
  577. return Changed;
  578. }
  579. bool EarlyCSE::run() {
  580. // Note, deque is being used here because there is significant performance
  581. // gains over vector when the container becomes very large due to the
  582. // specific access patterns. For more information see the mailing list
  583. // discussion on this:
  584. // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
  585. std::deque<StackNode *> nodesToProcess;
  586. bool Changed = false;
  587. // Process the root node.
  588. nodesToProcess.push_back(new StackNode(
  589. AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
  590. DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end()));
  591. // Save the current generation.
  592. unsigned LiveOutGeneration = CurrentGeneration;
  593. // Process the stack.
  594. while (!nodesToProcess.empty()) {
  595. // Grab the first item off the stack. Set the current generation, remove
  596. // the node from the stack, and process it.
  597. StackNode *NodeToProcess = nodesToProcess.back();
  598. // Initialize class members.
  599. CurrentGeneration = NodeToProcess->currentGeneration();
  600. // Check if the node needs to be processed.
  601. if (!NodeToProcess->isProcessed()) {
  602. // Process the node.
  603. Changed |= processNode(NodeToProcess->node());
  604. NodeToProcess->childGeneration(CurrentGeneration);
  605. NodeToProcess->process();
  606. } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
  607. // Push the next child onto the stack.
  608. DomTreeNode *child = NodeToProcess->nextChild();
  609. nodesToProcess.push_back(
  610. new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
  611. NodeToProcess->childGeneration(), child, child->begin(),
  612. child->end()));
  613. } else {
  614. // It has been processed, and there are no more children to process,
  615. // so delete it and pop it off the stack.
  616. delete NodeToProcess;
  617. nodesToProcess.pop_back();
  618. }
  619. } // while (!nodes...)
  620. // Reset the current generation.
  621. CurrentGeneration = LiveOutGeneration;
  622. return Changed;
  623. }
  624. PreservedAnalyses EarlyCSEPass::run(Function &F,
  625. AnalysisManager<Function> *AM) {
  626. auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
  627. auto &TTI = AM->getResult<TargetIRAnalysis>(F);
  628. auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
  629. auto &AC = AM->getResult<AssumptionAnalysis>(F);
  630. EarlyCSE CSE(F, TLI, TTI, DT, AC);
  631. if (!CSE.run())
  632. return PreservedAnalyses::all();
  633. // CSE preserves the dominator tree because it doesn't mutate the CFG.
  634. // FIXME: Bundle this with other CFG-preservation.
  635. PreservedAnalyses PA;
  636. PA.preserve<DominatorTreeAnalysis>();
  637. return PA;
  638. }
  639. namespace {
  640. /// \brief A simple and fast domtree-based CSE pass.
  641. ///
  642. /// This pass does a simple depth-first walk over the dominator tree,
  643. /// eliminating trivially redundant instructions and using instsimplify to
  644. /// canonicalize things as it goes. It is intended to be fast and catch obvious
  645. /// cases so that instcombine and other passes are more effective. It is
  646. /// expected that a later pass of GVN will catch the interesting/hard cases.
  647. class EarlyCSELegacyPass : public FunctionPass {
  648. public:
  649. static char ID;
  650. EarlyCSELegacyPass() : FunctionPass(ID) {
  651. initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
  652. }
  653. bool runOnFunction(Function &F) override {
  654. if (skipOptnoneFunction(F))
  655. return false;
  656. auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  657. auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  658. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  659. auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  660. EarlyCSE CSE(F, TLI, TTI, DT, AC);
  661. return CSE.run();
  662. }
  663. void getAnalysisUsage(AnalysisUsage &AU) const override {
  664. AU.addRequired<AssumptionCacheTracker>();
  665. AU.addRequired<DominatorTreeWrapperPass>();
  666. AU.addRequired<TargetLibraryInfoWrapperPass>();
  667. AU.addRequired<TargetTransformInfoWrapperPass>();
  668. AU.setPreservesCFG();
  669. }
  670. };
  671. }
  672. char EarlyCSELegacyPass::ID = 0;
  673. FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSELegacyPass(); }
  674. INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
  675. false)
  676. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  677. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  678. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  679. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  680. INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)