LICM.cpp revision 2ab36d350293c77fc8941ce1023e4899df7e3a82
1e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman//
3b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//                     The LLVM Compiler Infrastructure
4b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//
54ee451de366474b9c228b4e5fa573795a715216dChris Lattner// This file is distributed under the University of Illinois Open Source
64ee451de366474b9c228b4e5fa573795a715216dChris Lattner// License. See LICENSE.TXT for details.
7fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman//
8b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//===----------------------------------------------------------------------===//
9e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner//
1092094b4d928119eceac1484331acffe950f4651cChris Lattner// This pass performs loop invariant code motion, attempting to remove as much
1192094b4d928119eceac1484331acffe950f4651cChris Lattner// code from the body of a loop as possible.  It does this by either hoisting
1292094b4d928119eceac1484331acffe950f4651cChris Lattner// code into the preheader block, or by sinking code to the exit blocks if it is
1392094b4d928119eceac1484331acffe950f4651cChris Lattner// safe.  This pass also promotes must-aliased memory locations in the loop to
14e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner// live in registers, thus hoisting and sinking "invariant" loads and stores.
1592094b4d928119eceac1484331acffe950f4651cChris Lattner//
1692094b4d928119eceac1484331acffe950f4651cChris Lattner// This pass uses alias analysis for two purposes:
172e6e741b737960ecd0b68610875050019aac0f07Chris Lattner//
182741c971044d2165be572749b94398043caccfebChris Lattner//  1. Moving loop invariant loads and calls out of loops.  If we can determine
192741c971044d2165be572749b94398043caccfebChris Lattner//     that a load or call inside of a loop never aliases anything stored to,
202741c971044d2165be572749b94398043caccfebChris Lattner//     we can hoist it or sink it like any other instruction.
212e6e741b737960ecd0b68610875050019aac0f07Chris Lattner//  2. Scalar Promotion of Memory - If there is a store instruction inside of
222e6e741b737960ecd0b68610875050019aac0f07Chris Lattner//     the loop, we try to move the store to happen AFTER the loop instead of
232e6e741b737960ecd0b68610875050019aac0f07Chris Lattner//     inside of the loop.  This can only happen if a few conditions are true:
242e6e741b737960ecd0b68610875050019aac0f07Chris Lattner//       A. The pointer stored through is loop invariant
252e6e741b737960ecd0b68610875050019aac0f07Chris Lattner//       B. There are no stores or loads in the loop which _may_ alias the
262e6e741b737960ecd0b68610875050019aac0f07Chris Lattner//          pointer.  There are no calls in the loop which mod/ref the pointer.
272e6e741b737960ecd0b68610875050019aac0f07Chris Lattner//     If these conditions are true, we can promote the loads and stores in the
282e6e741b737960ecd0b68610875050019aac0f07Chris Lattner//     loop of the pointer to use a temporary alloca'd variable.  We then use
29e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner//     the SSAUpdater to construct the appropriate SSA form for the value.
30e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner//
31e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner//===----------------------------------------------------------------------===//
32e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
331f309c1a4e8068a64627c612a895d9b403dbcb26Chris Lattner#define DEBUG_TYPE "licm"
34e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner#include "llvm/Transforms/Scalar.h"
3579066fa6acce02c97c714a5a6e151ed8a249721cChris Lattner#include "llvm/Constants.h"
362741c971044d2165be572749b94398043caccfebChris Lattner#include "llvm/DerivedTypes.h"
379289ae85b41eef62ae1fadb93e99d33f723fb682Torok Edwin#include "llvm/IntrinsicInst.h"
382741c971044d2165be572749b94398043caccfebChris Lattner#include "llvm/Instructions.h"
39f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner#include "llvm/Analysis/AliasAnalysis.h"
400252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner#include "llvm/Analysis/AliasSetTracker.h"
412ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner#include "llvm/Analysis/ConstantFolding.h"
422ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner#include "llvm/Analysis/LoopInfo.h"
432ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner#include "llvm/Analysis/LoopPass.h"
44952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner#include "llvm/Analysis/Dominators.h"
4596b651c627160e1ea0f1bb86d352d697e6c1972dDevang Patel#include "llvm/Analysis/ScalarEvolution.h"
460de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner#include "llvm/Transforms/Utils/Local.h"
47a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner#include "llvm/Transforms/Utils/SSAUpdater.h"
489133fe28954d498fc4de13064c7d65bd811de02cReid Spencer#include "llvm/Support/CFG.h"
49551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/Support/CommandLine.h"
50ce63ffb52f249b62cdf2d250c128007b13f27e71Daniel Dunbar#include "llvm/Support/raw_ostream.h"
51551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/Support/Debug.h"
52551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/ADT/Statistic.h"
53e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner#include <algorithm>
5492094b4d928119eceac1484331acffe950f4651cChris Lattnerusing namespace llvm;
55d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke
560e5f499638c8d277b9dc4a4385712177c53b5681Chris LattnerSTATISTIC(NumSunk      , "Number of instructions sunk out of loop");
570e5f499638c8d277b9dc4a4385712177c53b5681Chris LattnerSTATISTIC(NumHoisted   , "Number of instructions hoisted out of loop");
580e5f499638c8d277b9dc4a4385712177c53b5681Chris LattnerSTATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
590e5f499638c8d277b9dc4a4385712177c53b5681Chris LattnerSTATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
600e5f499638c8d277b9dc4a4385712177c53b5681Chris LattnerSTATISTIC(NumPromoted  , "Number of memory locations promoted to registers");
610e5f499638c8d277b9dc4a4385712177c53b5681Chris Lattner
62844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanstatic cl::opt<bool>
63844731a7f1909f55935e3514c9e713a62d67662eDan GohmanDisablePromotion("disable-licm-promotion", cl::Hidden,
64844731a7f1909f55935e3514c9e713a62d67662eDan Gohman                 cl::desc("Disable memory promotion in LICM pass"));
652e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
66844731a7f1909f55935e3514c9e713a62d67662eDan Gohmannamespace {
673e8b6631e67e01e4960a7ba4668a50c596607473Chris Lattner  struct LICM : public LoopPass {
68ecd94c804a563f2a86572dcf1d2e81f397e19daaNick Lewycky    static char ID; // Pass identification, replacement for typeid
6990c579de5a383cee278acc3f7e7b9d0a656e6a35Owen Anderson    LICM() : LoopPass(ID) {}
70794fd75c67a2cdc128d67342c6d88a504d186896Devang Patel
7154959d6cf68a9b575c98c074babe9867682a7271Devang Patel    virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
72e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
7394170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// This transformation requires natural loop information & requires that
7494170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// loop preheaders be inserted into the CFG...
7594170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    ///
76e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77cb2610ea037a17115ef3a01a6bdaab4e3cfdca27Chris Lattner      AU.setPreservesCFG();
783a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson      AU.addRequired<DominatorTree>();
791e381fcd553a3955a10338fd305efc023d7d22e1Dan Gohman      AU.addRequired<LoopInfo>();
801e381fcd553a3955a10338fd305efc023d7d22e1Dan Gohman      AU.addRequiredID(LoopSimplifyID);
81f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner      AU.addRequired<AliasAnalysis>();
82e418ac832c1a2813736c44f6ec5c646b4c89c339Chris Lattner      AU.addPreserved<AliasAnalysis>();
8396b651c627160e1ea0f1bb86d352d697e6c1972dDevang Patel      AU.addPreserved<ScalarEvolution>();
845c89b5240c90eb8171f999e5f06f815502d0321cDan Gohman      AU.addPreservedID(LoopSimplifyID);
85e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner    }
86e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
87747603e39ea3f29add9ba6c07bbefcc5c2432612Dan Gohman    bool doFinalization() {
884282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner      assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
8954959d6cf68a9b575c98c074babe9867682a7271Devang Patel      return false;
9054959d6cf68a9b575c98c074babe9867682a7271Devang Patel    }
9154959d6cf68a9b575c98c074babe9867682a7271Devang Patel
92e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  private:
932e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    AliasAnalysis *AA;       // Current AliasAnalysis information
9492094b4d928119eceac1484331acffe950f4651cChris Lattner    LoopInfo      *LI;       // Current LoopInfo
9544e2bd31f13da68bca451e4210560db3644b8208Chris Lattner    DominatorTree *DT;       // Dominator Tree for the current Loop.
9692094b4d928119eceac1484331acffe950f4651cChris Lattner
974282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    // State that is updated as we process loops.
982e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    bool Changed;            // Set to true when we change anything.
992e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    BasicBlock *Preheader;   // The preheader block of the current loop...
1002e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    Loop *CurLoop;           // The current loop we are working on...
1010252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner    AliasSetTracker *CurAST; // AliasSet information for the current loop...
1024282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
103e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
10491d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
10591d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
10691d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
10791d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
10891d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    /// set.
10991d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    void deleteAnalysisValue(Value *V, Loop *L);
11091d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
111e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
112e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    /// dominated by the specified block, and that are in the current loop) in
1133a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson    /// reverse depth first order w.r.t the DominatorTree.  This allows us to
114e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    /// visit uses before definitions, allowing us to sink a loop body in one
115e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    /// pass without iteration.
116e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    ///
11726042420d642e810f5cdfb2da6156b74aaf80945Devang Patel    void SinkRegion(DomTreeNode *N);
118e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
119952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    /// HoistRegion - Walk the specified region of the CFG (defined by all
120952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    /// blocks dominated by the specified block, and that are in the current
1213a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson    /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
122cf00c4ab3ba308d45d98c5ccab87362cf802facbMisha Brukman    /// visit definitions before uses, allowing us to hoist a loop body in one
123952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    /// pass without iteration.
124952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    ///
12526042420d642e810f5cdfb2da6156b74aaf80945Devang Patel    void HoistRegion(DomTreeNode *N);
126952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
127b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner    /// inSubLoop - Little predicate that returns true if the specified basic
128b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner    /// block is in a subloop of the current one, not the current one itself.
12994170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    ///
130b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner    bool inSubLoop(BasicBlock *BB) {
131b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner      assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
132329c1c6c949d07e3fe9722ec633b4258217fd99dChris Lattner      for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
133329c1c6c949d07e3fe9722ec633b4258217fd99dChris Lattner        if ((*I)->contains(BB))
134b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner          return true;  // A subloop actually contains this block!
135b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner      return false;
136e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner    }
137e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
138a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
139a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// specified exit block of the loop is dominated by the specified block
140a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// that is in the body of the loop.  We use these constraints to
141a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// dramatically limit the amount of the dominator tree that needs to be
142a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// searched.
143a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
144a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner                                           BasicBlock *BlockInLoop) const {
145a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // If the block in the loop is the loop header, it must be dominated!
146a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      BasicBlock *LoopHeader = CurLoop->getHeader();
147a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      if (BlockInLoop == LoopHeader)
148a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        return true;
149fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
15026042420d642e810f5cdfb2da6156b74aaf80945Devang Patel      DomTreeNode *BlockInLoopNode = DT->getNode(BlockInLoop);
15126042420d642e810f5cdfb2da6156b74aaf80945Devang Patel      DomTreeNode *IDom            = DT->getNode(ExitBlock);
152fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
153a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // Because the exit block is not in the loop, we know we have to get _at
1542741c971044d2165be572749b94398043caccfebChris Lattner      // least_ its immediate dominator.
1553472ae1e7b0f38c4ac0802ffc2900f71a5470c3bEric Christopher      IDom = IDom->getIDom();
1563472ae1e7b0f38c4ac0802ffc2900f71a5470c3bEric Christopher
1573472ae1e7b0f38c4ac0802ffc2900f71a5470c3bEric Christopher      while (IDom && IDom != BlockInLoopNode) {
158a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // If we have got to the header of the loop, then the instructions block
159a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // did not dominate the exit node, so we can't hoist it.
1603a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson        if (IDom->getBlock() == LoopHeader)
161a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          return false;
162fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
1633472ae1e7b0f38c4ac0802ffc2900f71a5470c3bEric Christopher        // Get next Immediate Dominator.
1643472ae1e7b0f38c4ac0802ffc2900f71a5470c3bEric Christopher        IDom = IDom->getIDom();
1653472ae1e7b0f38c4ac0802ffc2900f71a5470c3bEric Christopher      };
166a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
167a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      return true;
168a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    }
169a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
170a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// sink - When an instruction is found to only be used outside of the loop,
171a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// this function moves it to the exit blocks and patches up SSA form as
172a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// needed.
173a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    ///
174a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    void sink(Instruction &I);
175a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
17694170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// hoist - When an instruction is found to only use loop invariant operands
17794170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// that is safe to hoist, this instruction is called to do the dirty work.
17894170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    ///
1797e70829632f82de15db187845666aaca6e04b792Chris Lattner    void hoist(Instruction &I);
180e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
181a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
182a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// is not a trapping instruction or if it is a trapping instruction and is
183a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// guaranteed to execute.
1849966c03aad031f738718bed3bc00371e358beb5dTanya Lattner    ///
185a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    bool isSafeToExecuteUnconditionally(Instruction &I);
1869966c03aad031f738718bed3bc00371e358beb5dTanya Lattner
18794170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// pointerInvalidatedByLoop - Return true if the body of this loop may
18894170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// store into the memory location pointed to by V.
189fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman    ///
190f3e1d6977ee5fb6b66df314d65e28e2c35d6e244Chris Lattner    bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
1910252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      // Check to see if any of the basic blocks in CurLoop invalidate *V.
192f3e1d6977ee5fb6b66df314d65e28e2c35d6e244Chris Lattner      return CurAST->getAliasSetForPointer(V, Size).isMod();
1932e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    }
194f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner
195a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    bool canSinkOrHoistInst(Instruction &I);
196a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    bool isNotUsedInLoop(Instruction &I);
197e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
198e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    void PromoteAliasSet(AliasSet &AS);
199e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  };
200e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner}
201e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
202844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanchar LICM::ID = 0;
2032ab36d350293c77fc8941ce1023e4899df7e3a82Owen AndersonINITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
2042ab36d350293c77fc8941ce1023e4899df7e3a82Owen AndersonINITIALIZE_PASS_DEPENDENCY(DominatorTree)
2052ab36d350293c77fc8941ce1023e4899df7e3a82Owen AndersonINITIALIZE_PASS_DEPENDENCY(LoopInfo)
2062ab36d350293c77fc8941ce1023e4899df7e3a82Owen AndersonINITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2072ab36d350293c77fc8941ce1023e4899df7e3a82Owen AndersonINITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2082ab36d350293c77fc8941ce1023e4899df7e3a82Owen AndersonINITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2092ab36d350293c77fc8941ce1023e4899df7e3a82Owen AndersonINITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
210844731a7f1909f55935e3514c9e713a62d67662eDan Gohman
211394f0441e06dafca29f0752cf400990a5b8fe4b1Daniel DunbarPass *llvm::createLICMPass() { return new LICM(); }
212e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
2138d246f09cb46fe38aa71d2a4edcd84f30c4bf80eDevang Patel/// Hoist expressions out of the specified loop. Note, alias info for inner
2148d246f09cb46fe38aa71d2a4edcd84f30c4bf80eDevang Patel/// loop is not preserved so it is not a good idea to run LICM multiple
2158d246f09cb46fe38aa71d2a4edcd84f30c4bf80eDevang Patel/// times on one loop.
21694170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner///
21754959d6cf68a9b575c98c074babe9867682a7271Devang Patelbool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
2182e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  Changed = false;
219e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
2202e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Get our Loop and Alias Analysis information...
2212e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  LI = &getAnalysis<LoopInfo>();
222f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner  AA = &getAnalysis<AliasAnalysis>();
2233a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  DT = &getAnalysis<DominatorTree>();
224f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner
22554959d6cf68a9b575c98c074babe9867682a7271Devang Patel  CurAST = new AliasSetTracker(*AA);
2264282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner  // Collect Alias info from subloops.
22754959d6cf68a9b575c98c074babe9867682a7271Devang Patel  for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
22854959d6cf68a9b575c98c074babe9867682a7271Devang Patel       LoopItr != LoopItrE; ++LoopItr) {
22954959d6cf68a9b575c98c074babe9867682a7271Devang Patel    Loop *InnerL = *LoopItr;
2304282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
2314282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    assert(InnerAST && "Where is my AST?");
23294170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner
23354959d6cf68a9b575c98c074babe9867682a7271Devang Patel    // What if InnerLoop was modified by other passes ?
23454959d6cf68a9b575c98c074babe9867682a7271Devang Patel    CurAST->add(*InnerAST);
2354282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner
2364282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    // Once we've incorporated the inner loop's AST into ours, we don't need the
2374282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    // subloop's anymore.
2384282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    delete InnerAST;
2394282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    LoopToAliasSetMap.erase(InnerL);
2402e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  }
24154959d6cf68a9b575c98c074babe9867682a7271Devang Patel
242e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  CurLoop = L;
243e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
24499a57216a935a512c418032f590a4660bad9d846Chris Lattner  // Get the preheader block to move instructions into...
24599a57216a935a512c418032f590a4660bad9d846Chris Lattner  Preheader = L->getLoopPreheader();
24699a57216a935a512c418032f590a4660bad9d846Chris Lattner
2472e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Loop over the body of this loop, looking for calls, invokes, and stores.
2480252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner  // Because subloops have already been incorporated into AST, we skip blocks in
2492e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // subloops.
2502e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  //
2519b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman  for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
2529b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman       I != E; ++I) {
2539b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman    BasicBlock *BB = *I;
2544282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    if (LI->getLoopFor(BB) == L)        // Ignore blocks in subloops.
2559b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman      CurAST->add(*BB);                 // Incorporate the specified basic block
2569b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman  }
2572e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
258e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // We want to visit all of the instructions in this loop... that are not parts
259e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // of our subloops (they have already had their invariants hoisted out of
260e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // their loop, into this loop, so there is no need to process the BODIES of
261e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // the subloops).
262e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  //
263952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  // Traverse the body of the loop in depth first order on the dominator tree so
264952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  // that we are guaranteed to see definitions before we see uses.  This allows
265af5cbc82bb6410129425c98bbfc1ffc4c3d0f411Nick Lewycky  // us to sink instructions in one pass, without iteration.  After sinking
266e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  // instructions, we perform another pass to hoist them out of the loop.
267952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  //
26803e896bd6073efc4523d8bcd0239d6ed62126db7Dan Gohman  if (L->hasDedicatedExits())
26903e896bd6073efc4523d8bcd0239d6ed62126db7Dan Gohman    SinkRegion(DT->getNode(L->getHeader()));
27003e896bd6073efc4523d8bcd0239d6ed62126db7Dan Gohman  if (Preheader)
27103e896bd6073efc4523d8bcd0239d6ed62126db7Dan Gohman    HoistRegion(DT->getNode(L->getHeader()));
272e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
2732e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Now that all loop invariants have been removed from the loop, promote any
274e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // memory references to scalars that we can.
275e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
276e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // Loop over all of the alias sets in the tracker object.
277e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
278e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner         I != E; ++I)
279e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      PromoteAliasSet(*I);
280e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  }
281e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
282e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // Clear out loops state information for the next iteration
283e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  CurLoop = 0;
28499a57216a935a512c418032f590a4660bad9d846Chris Lattner  Preheader = 0;
28554959d6cf68a9b575c98c074babe9867682a7271Devang Patel
2864282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner  // If this loop is nested inside of another one, save the alias information
2874282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner  // for when we process the outer loop.
2884282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner  if (L->getParentLoop())
2894282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    LoopToAliasSetMap[L] = CurAST;
2904282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner  else
2914282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    delete CurAST;
29254959d6cf68a9b575c98c074babe9867682a7271Devang Patel  return Changed;
293e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner}
294e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
295e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner/// SinkRegion - Walk the specified region of the CFG (defined by all blocks
296e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner/// dominated by the specified block, and that are in the current loop) in
2973a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson/// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
298e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner/// uses before definitions, allowing us to sink a loop body in one pass without
299e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner/// iteration.
300e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner///
30126042420d642e810f5cdfb2da6156b74aaf80945Devang Patelvoid LICM::SinkRegion(DomTreeNode *N) {
3023a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  assert(N != 0 && "Null dominator tree node?");
3033a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  BasicBlock *BB = N->getBlock();
304e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
305e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  // If this subregion is not in the top level loop at all, exit.
306e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  if (!CurLoop->contains(BB)) return;
307e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
3080de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner  // We are processing blocks in reverse dfo, so process children first.
30926042420d642e810f5cdfb2da6156b74aaf80945Devang Patel  const std::vector<DomTreeNode*> &Children = N->getChildren();
310e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  for (unsigned i = 0, e = Children.size(); i != e; ++i)
311e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    SinkRegion(Children[i]);
312e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
313e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  // Only need to process the contents of this block if it is not part of a
314e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  // subloop (which would already have been processed).
315e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  if (inSubLoop(BB)) return;
316e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
317a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner  for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
318a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner    Instruction &I = *--II;
3190de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner
3200de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner    // If the instruction is dead, we would try to sink it because it isn't used
3210de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner    // in the loop, instead, just delete it.
3220de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner    if (isInstructionTriviallyDead(&I)) {
323cb7f65342291caa3636cb50c0ee04b383cd79f8dChris Lattner      DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
3240de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner      ++II;
3250de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner      CurAST->deleteValue(&I);
3260de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner      I.eraseFromParent();
3270de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner      Changed = true;
3280de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner      continue;
3290de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner    }
330fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
331e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    // Check to see if we can sink this instruction to the exit blocks
332e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    // of the loop.  We can do this if the all users of the instruction are
333e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    // outside of the loop.  In this case, it doesn't even matter if the
334e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    // operands of the instruction are loop invariant.
335e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    //
33670ac2dcb841dc62f08e16f0b0e2cefbf01baa4c5Chris Lattner    if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
337a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner      ++II;
338e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      sink(I);
339a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner    }
340e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  }
341e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner}
342e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
343952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
344952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner/// dominated by the specified block, and that are in the current loop) in depth
3453a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson/// first order w.r.t the DominatorTree.  This allows us to visit definitions
346952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner/// before uses, allowing us to hoist a loop body in one pass without iteration.
347952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner///
34826042420d642e810f5cdfb2da6156b74aaf80945Devang Patelvoid LICM::HoistRegion(DomTreeNode *N) {
3493a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  assert(N != 0 && "Null dominator tree node?");
3503a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  BasicBlock *BB = N->getBlock();
351952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
352b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner  // If this subregion is not in the top level loop at all, exit.
353ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  if (!CurLoop->contains(BB)) return;
354952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
355a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // Only need to process the contents of this block if it is not part of a
356a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // subloop (which would already have been processed).
357ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  if (!inSubLoop(BB))
358a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
359a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      Instruction &I = *II++;
360fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
3612ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner      // Try constant folding this instruction.  If all the operands are
3622ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner      // constants, it is technically hoistable, but it would be better to just
3632ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner      // fold it.
3642ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner      if (Constant *C = ConstantFoldInstruction(&I)) {
3652ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner        DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C << '\n');
3662ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner        CurAST->copyValue(&I, C);
3672ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner        CurAST->deleteValue(&I);
3682ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner        I.replaceAllUsesWith(C);
3692ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner        I.eraseFromParent();
3702ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner        continue;
3712ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner      }
3722ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner
373e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      // Try hoisting the instruction out to the preheader.  We can only do this
374e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      // if all of the operands of the instruction are loop invariant and if it
375e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      // is safe to hoist the instruction.
376e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      //
377adc799112dc180b3cd099038c05101b85d217716Chris Lattner      if (CurLoop->hasLoopInvariantOperands(&I) && canSinkOrHoistInst(I) &&
378e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner          isSafeToExecuteUnconditionally(I))
3793c80a51cfd5e7187439ce4c051da77ee46e0ff9aChris Lattner        hoist(I);
3802ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner    }
381952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
38226042420d642e810f5cdfb2da6156b74aaf80945Devang Patel  const std::vector<DomTreeNode*> &Children = N->getChildren();
383952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  for (unsigned i = 0, e = Children.size(); i != e; ++i)
38456b7ee20dad7160a117ea0d102fc5432074ce2d0Chris Lattner    HoistRegion(Children[i]);
385952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner}
386952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
387a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
388a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// instruction.
389a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner///
390a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnerbool LICM::canSinkOrHoistInst(Instruction &I) {
391ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  // Loads have extra constraints we have to verify before we can hoist them.
392ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
393ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner    if (LI->isVolatile())
394ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner      return false;        // Don't hoist volatile loads!
395ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner
396967948b4e25cae3de68f38fddaa75d838e676decChris Lattner    // Loads from constant memory are always safe to move, even if they end up
397967948b4e25cae3de68f38fddaa75d838e676decChris Lattner    // in the same alias set as something that ends up being modified.
398dab249b3b762cff0ff16069b3233e4c885e75347Dan Gohman    if (AA->pointsToConstantMemory(LI->getOperand(0)))
399967948b4e25cae3de68f38fddaa75d838e676decChris Lattner      return true;
400967948b4e25cae3de68f38fddaa75d838e676decChris Lattner
401ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner    // Don't hoist loads which have may-aliased stores in loop.
402f3e1d6977ee5fb6b66df314d65e28e2c35d6e244Chris Lattner    unsigned Size = 0;
403f3e1d6977ee5fb6b66df314d65e28e2c35d6e244Chris Lattner    if (LI->getType()->isSized())
404fc2a3ed0c9e32cf7edaf5030fa0972b916cc5f0bDan Gohman      Size = AA->getTypeStoreSize(LI->getType());
405f3e1d6977ee5fb6b66df314d65e28e2c35d6e244Chris Lattner    return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
406118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner  } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
407118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    // Handle obvious cases efficiently.
408dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands    AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
409dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands    if (Behavior == AliasAnalysis::DoesNotAccessMemory)
410dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      return true;
411dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands    else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
412dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      // If this call only reads from memory and there are no writes to memory
413dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      // in the loop, we can hoist or sink the call as appropriate.
414dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      bool FoundMod = false;
415dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
416dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands           I != E; ++I) {
417dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands        AliasSet &AS = *I;
418dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands        if (!AS.isForwardingAliasSet() && AS.isMod()) {
419dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands          FoundMod = true;
420dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands          break;
421118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner        }
422118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner      }
423dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      if (!FoundMod) return true;
424118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    }
425118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner
426118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    // FIXME: This should use mod/ref information to see if we can hoist or sink
427118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    // the call.
428fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
429118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    return false;
430ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  }
431ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner
4323da59db637a887474c1b1346c1f3ccf53b6c4663Reid Spencer  // Otherwise these instructions are hoistable/sinkable
433832254e1c2387c0cbeb0a820b8315fbe85cb003aReid Spencer  return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
434d8af90c1da64b81a7aa167b5adcc1e81b0741252Dan Gohman         isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
435d8af90c1da64b81a7aa167b5adcc1e81b0741252Dan Gohman         isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
436d8af90c1da64b81a7aa167b5adcc1e81b0741252Dan Gohman         isa<ShuffleVectorInst>(I);
437a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner}
438a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
439a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// isNotUsedInLoop - Return true if the only users of this instruction are
440a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// outside of the loop.  If this is true, we can sink the instruction to the
441a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// exit blocks of the loop.
442a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner///
443a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnerbool LICM::isNotUsedInLoop(Instruction &I) {
444ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner  for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
445ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner    Instruction *User = cast<Instruction>(*UI);
446ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner    if (PHINode *PN = dyn_cast<PHINode>(User)) {
447ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner      // PHI node uses occur in predecessor blocks!
448ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
449ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner        if (PN->getIncomingValue(i) == &I)
450ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner          if (CurLoop->contains(PN->getIncomingBlock(i)))
451ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner            return false;
45292329c7fbe572892c17aa2d2542a10e3ea16132fDan Gohman    } else if (CurLoop->contains(User)) {
453a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      return false;
454ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner    }
455ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner  }
456a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  return true;
457a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner}
458a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
459a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
460a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// sink - When an instruction is found to only be used outside of the loop,
461a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner/// this function moves it to the exit blocks and patches up SSA form as needed.
462a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner/// This method is guaranteed to remove the original instruction from its
463a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner/// position, and may either delete it or move it to outside of the loop.
464a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner///
465a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnervoid LICM::sink(Instruction &I) {
46639a383124b70dda1fea18288235114029ede76cfNick Lewycky  DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
467a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
468b7211a2ce13a0365e0e1dd2f27adda2ee3d1288bDevang Patel  SmallVector<BasicBlock*, 8> ExitBlocks;
469d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  CurLoop->getUniqueExitBlocks(ExitBlocks);
470df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner
471df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner  if (isa<LoadInst>(I)) ++NumMovedLoads;
472118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner  else if (isa<CallInst>(I)) ++NumMovedCalls;
473df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner  ++NumSunk;
474df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner  Changed = true;
475df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner
476a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // The case where there is only a single exit node of this loop is common
477a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // enough that we handle it as a special (more efficient) case.  It is more
478a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // efficient to handle because there are no PHI nodes that need to be placed.
479a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  if (ExitBlocks.size() == 1) {
480a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
481a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // Instruction is not used, just delete it.
4822741c971044d2165be572749b94398043caccfebChris Lattner      CurAST->deleteValue(&I);
4831bf5ebc7be0d5b05e4175c7adb767b38896adef1Devang Patel      // If I has users in unreachable blocks, eliminate.
484228ebd0f4cf9207d32d61ef4b11b81736895dc09Devang Patel      // If I is not void type then replaceAllUsesWith undef.
485228ebd0f4cf9207d32d61ef4b11b81736895dc09Devang Patel      // This allows ValueHandlers and custom metadata to adjust itself.
486a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner      if (!I.use_empty())
487228ebd0f4cf9207d32d61ef4b11b81736895dc09Devang Patel        I.replaceAllUsesWith(UndefValue::get(I.getType()));
4883c80a51cfd5e7187439ce4c051da77ee46e0ff9aChris Lattner      I.eraseFromParent();
489a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    } else {
490a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // Move the instruction to the start of the exit block, after any PHI
491a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // nodes in it.
492d9a5daeb7719c83136c0dc43d6ef732402d1a1b5Chris Lattner      I.moveBefore(ExitBlocks[0]->getFirstNonPHI());
4934282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner
4944282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner      // This instruction is no longer in the AST for the current loop, because
4954282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner      // we just sunk it out of the loop.  If we just sunk it into an outer
4964282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner      // loop, we will rediscover the operation when we process it.
4974282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner      CurAST->deleteValue(&I);
498a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    }
499d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    return;
500d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  }
501d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner
502d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  if (ExitBlocks.empty()) {
503a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // The instruction is actually dead if there ARE NO exit blocks.
5042741c971044d2165be572749b94398043caccfebChris Lattner    CurAST->deleteValue(&I);
5051bf5ebc7be0d5b05e4175c7adb767b38896adef1Devang Patel    // If I has users in unreachable blocks, eliminate.
506228ebd0f4cf9207d32d61ef4b11b81736895dc09Devang Patel    // If I is not void type then replaceAllUsesWith undef.
507228ebd0f4cf9207d32d61ef4b11b81736895dc09Devang Patel    // This allows ValueHandlers and custom metadata to adjust itself.
508a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    if (!I.use_empty())
509228ebd0f4cf9207d32d61ef4b11b81736895dc09Devang Patel      I.replaceAllUsesWith(UndefValue::get(I.getType()));
5103c80a51cfd5e7187439ce4c051da77ee46e0ff9aChris Lattner    I.eraseFromParent();
511d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    return;
512d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  }
513d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner
514a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  // Otherwise, if we have multiple exits, use the SSAUpdater to do all of the
515a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  // hard work of inserting PHI nodes as necessary.
516a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  SmallVector<PHINode*, 8> NewPHIs;
517a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  SSAUpdater SSA(&NewPHIs);
518a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner
519a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  if (!I.use_empty())
520fc6e29d4ab52b7d3efd83846ed495a9ca7e51e49Duncan Sands    SSA.Initialize(I.getType(), I.getName());
521d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner
522a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  // Insert a copy of the instruction in each exit block of the loop that is
523a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  // dominated by the instruction.  Each exit block is known to only be in the
524a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  // ExitBlocks list once.
525a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  BasicBlock *InstOrigBB = I.getParent();
526d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  unsigned NumInserted = 0;
527a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner
528d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
529d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    BasicBlock *ExitBlock = ExitBlocks[i];
530a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner
531d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    if (!isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB))
532d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner      continue;
533d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner
534a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    // Insert the code after the last PHI node.
535d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    BasicBlock::iterator InsertPt = ExitBlock->getFirstNonPHI();
536a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner
537d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    // If this is the first exit block processed, just move the original
538d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    // instruction, otherwise clone the original instruction and insert
539d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    // the copy.
540d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    Instruction *New;
541a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    if (NumInserted++ == 0) {
542a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner      I.moveBefore(InsertPt);
543d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner      New = &I;
544d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    } else {
545d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner      New = I.clone();
546d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner      if (!I.getName().empty())
547d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner        New->setName(I.getName()+".le");
548d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner      ExitBlock->getInstList().insert(InsertPt, New);
549a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    }
550d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner
551a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    // Now that we have inserted the instruction, inform SSAUpdater.
552a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    if (!I.use_empty())
553a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner      SSA.AddAvailableValue(ExitBlock, New);
554d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  }
555a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner
556d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  // If the instruction doesn't dominate any exit blocks, it must be dead.
557d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  if (NumInserted == 0) {
558d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    CurAST->deleteValue(&I);
559a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    if (!I.use_empty())
560a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner      I.replaceAllUsesWith(UndefValue::get(I.getType()));
561d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    I.eraseFromParent();
562a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    return;
563d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  }
564a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner
565a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  // Next, rewrite uses of the instruction, inserting PHI nodes as needed.
566a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE; ) {
567a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    // Grab the use before incrementing the iterator.
568a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    Use &U = UI.getUse();
569a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    // Increment the iterator before removing the use from the list.
570a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    ++UI;
571a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    SSA.RewriteUseAfterInsertions(U);
572a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  }
573a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner
574a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  // Update CurAST for NewPHIs if I had pointer type.
575a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  if (I.getType()->isPointerTy())
576a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
5779c282011e6b7a6e23a3a163ec9c865890449e8dcChris Lattner      CurAST->copyValue(&I, NewPHIs[i]);
57898917503c702e16f35ccdec3f6b4c48e5c4759acChris Lattner
57998917503c702e16f35ccdec3f6b4c48e5c4759acChris Lattner  // Finally, remove the instruction from CurAST.  It is no longer in the loop.
58098917503c702e16f35ccdec3f6b4c48e5c4759acChris Lattner  CurAST->deleteValue(&I);
581a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner}
582952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
58394170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner/// hoist - When an instruction is found to only use loop invariant operands
58494170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner/// that is safe to hoist, this instruction is called to do the dirty work.
58594170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner///
586a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnervoid LICM::hoist(Instruction &I) {
587f15826999bc560ee6f67cff5ecd71bf9cce7a7aaDavid Greene  DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
58867d1d1f8322bdc460158888cd233be8d1cb1d4abEvan Cheng        << I << "\n");
589ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner
590d9a5daeb7719c83136c0dc43d6ef732402d1a1b5Chris Lattner  // Move the new node to the Preheader, before its terminator.
591d9a5daeb7719c83136c0dc43d6ef732402d1a1b5Chris Lattner  I.moveBefore(Preheader->getTerminator());
592fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
593a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  if (isa<LoadInst>(I)) ++NumMovedLoads;
594118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner  else if (isa<CallInst>(I)) ++NumMovedCalls;
5959646e6b6af1f924f9366a2bffc6dde102f84d231Chris Lattner  ++NumHoisted;
596e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  Changed = true;
597e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner}
598e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
599a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
600a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// not a trapping instruction or if it is a trapping instruction and is
601a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// guaranteed to execute.
6029966c03aad031f738718bed3bc00371e358beb5dTanya Lattner///
603a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnerbool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
60492094b4d928119eceac1484331acffe950f4651cChris Lattner  // If it is not a trapping instruction, it is always safe to hoist.
6050b79a7727d68a507837e827803859424cf3d997bEli Friedman  if (Inst.isSafeToSpeculativelyExecute())
6060b79a7727d68a507837e827803859424cf3d997bEli Friedman    return true;
607fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
60892094b4d928119eceac1484331acffe950f4651cChris Lattner  // Otherwise we have to check to make sure that the instruction dominates all
60992094b4d928119eceac1484331acffe950f4651cChris Lattner  // of the exit blocks.  If it doesn't, then there is a path out of the loop
61092094b4d928119eceac1484331acffe950f4651cChris Lattner  // which does not execute this instruction, so we can't hoist it.
61192094b4d928119eceac1484331acffe950f4651cChris Lattner
61292094b4d928119eceac1484331acffe950f4651cChris Lattner  // If the instruction is in the header block for the loop (which is very
61392094b4d928119eceac1484331acffe950f4651cChris Lattner  // common), it is always guaranteed to dominate the exit blocks.  Since this
61492094b4d928119eceac1484331acffe950f4651cChris Lattner  // is a common case, and can save some work, check it now.
615a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  if (Inst.getParent() == CurLoop->getHeader())
61692094b4d928119eceac1484331acffe950f4651cChris Lattner    return true;
61792094b4d928119eceac1484331acffe950f4651cChris Lattner
61892094b4d928119eceac1484331acffe950f4651cChris Lattner  // Get the exit blocks for the current loop.
619b7211a2ce13a0365e0e1dd2f27adda2ee3d1288bDevang Patel  SmallVector<BasicBlock*, 8> ExitBlocks;
6205fa802fe279f10f402e039bc931aa57c0e424bf5Chris Lattner  CurLoop->getExitBlocks(ExitBlocks);
6219966c03aad031f738718bed3bc00371e358beb5dTanya Lattner
6223a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  // For each exit block, get the DT node and walk up the DT until the
62392094b4d928119eceac1484331acffe950f4651cChris Lattner  // instruction's basic block is found or we exit the loop.
624a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
625a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
626a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      return false;
627fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
6289966c03aad031f738718bed3bc00371e358beb5dTanya Lattner  return true;
6299966c03aad031f738718bed3bc00371e358beb5dTanya Lattner}
6309966c03aad031f738718bed3bc00371e358beb5dTanya Lattner
631e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner/// PromoteAliasSet - Try to promote memory values to scalars by sinking
6322e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// stores out of the loop and moving loads to before the loop.  We do this by
6332e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// looping over the stores in the loop, looking for stores to Must pointers
634e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner/// which are loop invariant.
6352e6e741b737960ecd0b68610875050019aac0f07Chris Lattner///
636e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattnervoid LICM::PromoteAliasSet(AliasSet &AS) {
637e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // We can promote this alias set if it has a store, if it is a "Must" alias
638e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // set, if the pointer is loop invariant, and if we are not eliminating any
639e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // volatile loads or stores.
640e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
641e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
642e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    return;
643e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
644e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  assert(!AS.empty() &&
645e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner         "Must alias set should have at least one pointer element in it!");
646e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  Value *SomePtr = AS.begin()->getValue();
647fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
648e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // It isn't safe to promote a load/store from the loop if the load/store is
649e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // conditional.  For example, turning:
6502e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  //
651e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  //    for () { if (c) *P += 1; }
6522e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  //
653e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // into:
654e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  //
655e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
656e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  //
657e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // is not safe, because *P may only be valid to access if 'c' is true.
658e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  //
659e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // It is safe to promote P if all uses are direct load/stores and if at
660e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // least one is guaranteed to be executed.
661e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  bool GuaranteedToExecute = false;
662e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
663e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  SmallVector<Instruction*, 64> LoopUses;
664e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  SmallPtrSet<Value*, 4> PointerMustAliases;
665e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
666e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // Check that all of the pointers in the alias set have the same type.  We
667e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // cannot (yet) promote a memory location that is loaded and stored in
668e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // different sizes.
669e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
670e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    Value *ASIV = ASI->getValue();
671e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    PointerMustAliases.insert(ASIV);
67229d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner
67329d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    // Check that all of the pointers in the alias set have the same type.  We
67429d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    // cannot (yet) promote a memory location that is loaded and stored in
67529d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    // different sizes.
676e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    if (SomePtr->getType() != ASIV->getType())
677e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      return;
678e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
679e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    for (Value::use_iterator UI = ASIV->use_begin(), UE = ASIV->use_end();
68019d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner         UI != UE; ++UI) {
681e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      // Ignore instructions that are outside the loop.
68229d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner      Instruction *Use = dyn_cast<Instruction>(*UI);
68392329c7fbe572892c17aa2d2542a10e3ea16132fDan Gohman      if (!Use || !CurLoop->contains(Use))
68429d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner        continue;
685e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
686e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      // If there is an non-load/store instruction in the loop, we can't promote
687e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      // it.
688e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      if (isa<LoadInst>(Use))
689e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        assert(!cast<LoadInst>(Use)->isVolatile() && "AST broken");
6900cccd7633e4a0ba36b5ff9a3dfda2a09d16dc337Chris Lattner      else if (isa<StoreInst>(Use)) {
6910cccd7633e4a0ba36b5ff9a3dfda2a09d16dc337Chris Lattner        assert(!cast<StoreInst>(Use)->isVolatile() && "AST broken");
6920cccd7633e4a0ba36b5ff9a3dfda2a09d16dc337Chris Lattner        if (Use->getOperand(0) == ASIV) return;
6930cccd7633e4a0ba36b5ff9a3dfda2a09d16dc337Chris Lattner      } else
694e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        return; // Not a load or store.
69519d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner
69619d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner      if (!GuaranteedToExecute)
69719d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner        GuaranteedToExecute = isSafeToExecuteUnconditionally(*Use);
698e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
699e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      LoopUses.push_back(Use);
70029d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    }
701e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  }
702e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
703e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // If there isn't a guaranteed-to-execute instruction, we can't promote.
704e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  if (!GuaranteedToExecute)
705e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    return;
706e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
707e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // Otherwise, this is safe to promote, lets do it!
708e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
709e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  Changed = true;
710e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  ++NumPromoted;
711bc2265abe1d1b830995bb2f6322409bc7d7c5740Devang Patel
712e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // We use the SSAUpdater interface to insert phi nodes as required.
713e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  SmallVector<PHINode*, 16> NewPHIs;
714e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  SSAUpdater SSA(&NewPHIs);
715e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
716e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // It wants to know some value of the same type as what we'll be inserting.
717e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  Value *SomeValue;
718e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  if (isa<LoadInst>(LoopUses[0]))
719e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    SomeValue = LoopUses[0];
720e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  else
721e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    SomeValue = cast<StoreInst>(LoopUses[0])->getOperand(0);
722fc6e29d4ab52b7d3efd83846ed495a9ca7e51e49Duncan Sands  SSA.Initialize(SomeValue->getType(), SomeValue->getName());
723e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
724e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // First step: bucket up uses of the pointers by the block they occur in.
725e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // This is important because we have to handle multiple defs/uses in a block
726e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // ourselves: SSAUpdater is purely for cross-block references.
727e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // FIXME: Want a TinyVector<Instruction*> since there is usually 0/1 element.
728e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  DenseMap<BasicBlock*, std::vector<Instruction*> > UsesByBlock;
729e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  for (unsigned i = 0, e = LoopUses.size(); i != e; ++i) {
730e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    Instruction *User = LoopUses[i];
731e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    UsesByBlock[User->getParent()].push_back(User);
732e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  }
733e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
734e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // Okay, now we can iterate over all the blocks in the loop with uses,
735e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // processing them.  Keep track of which loads are loading a live-in value.
736e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  SmallVector<LoadInst*, 32> LiveInLoads;
737469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner  DenseMap<Value*, Value*> ReplacedLoads;
738e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
739e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  for (unsigned LoopUse = 0, e = LoopUses.size(); LoopUse != e; ++LoopUse) {
740e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    Instruction *User = LoopUses[LoopUse];
741e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    std::vector<Instruction*> &BlockUses = UsesByBlock[User->getParent()];
742e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
743e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // If this block has already been processed, ignore this repeat use.
744e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    if (BlockUses.empty()) continue;
745e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
746e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // Okay, this is the first use in the block.  If this block just has a
747e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // single user in it, we can rewrite it trivially.
748e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    if (BlockUses.size() == 1) {
749e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      // If it is a store, it is a trivial def of the value in the block.
750e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      if (isa<StoreInst>(User)) {
751e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        SSA.AddAvailableValue(User->getParent(),
752e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner                              cast<StoreInst>(User)->getOperand(0));
753e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      } else {
754e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        // Otherwise it is a load, queue it to rewrite as a live-in load.
755e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        LiveInLoads.push_back(cast<LoadInst>(User));
756e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      }
757e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      BlockUses.clear();
75829d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner      continue;
759e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    }
760e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
761e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // Otherwise, check to see if this block is all loads.  If so, we can queue
762e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // them all as live in loads.
763e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    bool HasStore = false;
764e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) {
765e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      if (isa<StoreInst>(BlockUses[i])) {
766e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        HasStore = true;
767e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        break;
768e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      }
769e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    }
77029d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner
771e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    if (!HasStore) {
772e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      for (unsigned i = 0, e = BlockUses.size(); i != e; ++i)
773e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        LiveInLoads.push_back(cast<LoadInst>(BlockUses[i]));
774e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      BlockUses.clear();
775e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      continue;
776e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    }
777e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
778e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // Otherwise, we have mixed loads and stores (or just a bunch of stores).
779e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // Since SSAUpdater is purely for cross-block values, we need to determine
780e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // the order of these instructions in the block.  If the first use in the
781e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // block is a load, then it uses the live in value.  The last store defines
782e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // the live out value.  We handle this by doing a linear scan of the block.
783e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    BasicBlock *BB = User->getParent();
784e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    Value *StoredValue = 0;
785e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
786e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      if (LoadInst *L = dyn_cast<LoadInst>(II)) {
787469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner        // If this is a load from an unrelated pointer, ignore it.
788e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        if (!PointerMustAliases.count(L->getOperand(0))) continue;
789e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
790e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        // If we haven't seen a store yet, this is a live in use, otherwise
791e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        // use the stored value.
792469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner        if (StoredValue) {
793e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner          L->replaceAllUsesWith(StoredValue);
794469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner          ReplacedLoads[L] = StoredValue;
795469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner        } else {
796e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner          LiveInLoads.push_back(L);
797469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner        }
798e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        continue;
799e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      }
800e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
801e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      if (StoreInst *S = dyn_cast<StoreInst>(II)) {
802445560881898fe212c185bd4c0485140d7b4fc88Chris Lattner        // If this is a store to an unrelated pointer, ignore it.
803e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        if (!PointerMustAliases.count(S->getOperand(1))) continue;
804fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner
805e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        // Remember that this is the active value in the block.
806e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        StoredValue = S->getOperand(0);
807e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      }
808e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    }
809e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
810e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // The last stored value that happened is the live-out for the block.
811e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    assert(StoredValue && "Already checked that there is a store in block");
812e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    SSA.AddAvailableValue(BB, StoredValue);
813e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    BlockUses.clear();
814e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  }
815e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
816e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // Now that all the intra-loop values are classified, set up the preheader.
817e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // It gets a load of the pointer we're promoting, and it is the live-out value
818e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // from the preheader.
819e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  LoadInst *PreheaderLoad = new LoadInst(SomePtr,SomePtr->getName()+".promoted",
820e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner                                         Preheader->getTerminator());
821e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  SSA.AddAvailableValue(Preheader, PreheaderLoad);
822e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
823e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // Now that the preheader is good to go, set up the exit blocks.  Each exit
824e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // block gets a store of the live-out values that feed them.  Since we've
825e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // already told the SSA updater about the defs in the loop and the preheader
826e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // definition, it is all set and we can start using it.
827e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  SmallVector<BasicBlock*, 8> ExitBlocks;
828e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  CurLoop->getUniqueExitBlocks(ExitBlocks);
829e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
830e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    BasicBlock *ExitBlock = ExitBlocks[i];
831e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
832e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    Instruction *InsertPos = ExitBlock->getFirstNonPHI();
833e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    new StoreInst(LiveInValue, SomePtr, InsertPos);
834e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  }
835fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
836e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // Okay, now we rewrite all loads that use live-in values in the loop,
837e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // inserting PHI nodes as necessary.
838e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  for (unsigned i = 0, e = LiveInLoads.size(); i != e; ++i) {
839e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    LoadInst *ALoad = LiveInLoads[i];
8409c282011e6b7a6e23a3a163ec9c865890449e8dcChris Lattner    Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
8419c282011e6b7a6e23a3a163ec9c865890449e8dcChris Lattner    ALoad->replaceAllUsesWith(NewVal);
8429c282011e6b7a6e23a3a163ec9c865890449e8dcChris Lattner    CurAST->copyValue(ALoad, NewVal);
843469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner    ReplacedLoads[ALoad] = NewVal;
844e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  }
845e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
8467abdb22e52e2122cb04479a1129dc68916dece4cChris Lattner  // If the preheader load is itself a pointer, we need to tell alias analysis
8477abdb22e52e2122cb04479a1129dc68916dece4cChris Lattner  // about the new pointer we created in the preheader block and about any PHI
8487abdb22e52e2122cb04479a1129dc68916dece4cChris Lattner  // nodes that just got inserted.
8497abdb22e52e2122cb04479a1129dc68916dece4cChris Lattner  if (PreheaderLoad->getType()->isPointerTy()) {
8507abdb22e52e2122cb04479a1129dc68916dece4cChris Lattner    // Copy any value stored to or loaded from a must-alias of the pointer.
8517abdb22e52e2122cb04479a1129dc68916dece4cChris Lattner    CurAST->copyValue(SomeValue, PreheaderLoad);
8527abdb22e52e2122cb04479a1129dc68916dece4cChris Lattner
8537abdb22e52e2122cb04479a1129dc68916dece4cChris Lattner    for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
8547abdb22e52e2122cb04479a1129dc68916dece4cChris Lattner      CurAST->copyValue(SomeValue, NewPHIs[i]);
8557abdb22e52e2122cb04479a1129dc68916dece4cChris Lattner  }
8567abdb22e52e2122cb04479a1129dc68916dece4cChris Lattner
857e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // Now that everything is rewritten, delete the old instructions from the body
858e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // of the loop.  They should all be dead now.
859e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  for (unsigned i = 0, e = LoopUses.size(); i != e; ++i) {
860e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    Instruction *User = LoopUses[i];
861469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner
862469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner    // If this is a load that still has uses, then the load must have been added
863469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner    // as a live value in the SSAUpdate data structure for a block (e.g. because
864469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner    // the loaded value was stored later).  In this case, we need to recursively
865469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner    // propagate the updates until we get to the real value.
866469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner    if (!User->use_empty()) {
867469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      Value *NewVal = ReplacedLoads[User];
868469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      assert(NewVal && "not a replaced load?");
869469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner
870469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      // Propagate down to the ultimate replacee.  The intermediately loads
871469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      // could theoretically already have been deleted, so we don't want to
872469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      // dereference the Value*'s.
873469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
874469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      while (RLI != ReplacedLoads.end()) {
875469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner        NewVal = RLI->second;
876469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner        RLI = ReplacedLoads.find(NewVal);
877469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      }
878469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner
879469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      User->replaceAllUsesWith(NewVal);
880469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      CurAST->copyValue(User, NewVal);
881469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner    }
882469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner
883e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    CurAST->deleteValue(User);
884e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    User->eraseFromParent();
885e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  }
886e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
887e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // fwew, we're done!
888f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner}
88991d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
890e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
89191d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel/// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
89291d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patelvoid LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
8934282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner  AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
89491d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel  if (!AST)
89591d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    return;
89691d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
89791d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel  AST->copyValue(From, To);
89891d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel}
89991d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
90091d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel/// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
90191d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel/// set.
90291d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patelvoid LICM::deleteAnalysisValue(Value *V, Loop *L) {
9034282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner  AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
90491d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel  if (!AST)
90591d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    return;
90691d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
90791d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel  AST->deleteValue(V);
90891d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel}
909