LICM.cpp revision adc799112dc180b3cd099038c05101b85d217716
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;
203d13db2c59cc94162d6cf0a04187d408bfef6d4a7Owen AndersonINITIALIZE_PASS(LICM, "licm", "Loop Invariant Code Motion", false, false);
204844731a7f1909f55935e3514c9e713a62d67662eDan Gohman
205394f0441e06dafca29f0752cf400990a5b8fe4b1Daniel DunbarPass *llvm::createLICMPass() { return new LICM(); }
206e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
2078d246f09cb46fe38aa71d2a4edcd84f30c4bf80eDevang Patel/// Hoist expressions out of the specified loop. Note, alias info for inner
2088d246f09cb46fe38aa71d2a4edcd84f30c4bf80eDevang Patel/// loop is not preserved so it is not a good idea to run LICM multiple
2098d246f09cb46fe38aa71d2a4edcd84f30c4bf80eDevang Patel/// times on one loop.
21094170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner///
21154959d6cf68a9b575c98c074babe9867682a7271Devang Patelbool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
2122e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  Changed = false;
213e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
2142e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Get our Loop and Alias Analysis information...
2152e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  LI = &getAnalysis<LoopInfo>();
216f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner  AA = &getAnalysis<AliasAnalysis>();
2173a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  DT = &getAnalysis<DominatorTree>();
218f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner
21954959d6cf68a9b575c98c074babe9867682a7271Devang Patel  CurAST = new AliasSetTracker(*AA);
2204282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner  // Collect Alias info from subloops.
22154959d6cf68a9b575c98c074babe9867682a7271Devang Patel  for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
22254959d6cf68a9b575c98c074babe9867682a7271Devang Patel       LoopItr != LoopItrE; ++LoopItr) {
22354959d6cf68a9b575c98c074babe9867682a7271Devang Patel    Loop *InnerL = *LoopItr;
2244282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
2254282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    assert(InnerAST && "Where is my AST?");
22694170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner
22754959d6cf68a9b575c98c074babe9867682a7271Devang Patel    // What if InnerLoop was modified by other passes ?
22854959d6cf68a9b575c98c074babe9867682a7271Devang Patel    CurAST->add(*InnerAST);
2294282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner
2304282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    // Once we've incorporated the inner loop's AST into ours, we don't need the
2314282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    // subloop's anymore.
2324282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    delete InnerAST;
2334282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    LoopToAliasSetMap.erase(InnerL);
2342e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  }
23554959d6cf68a9b575c98c074babe9867682a7271Devang Patel
236e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  CurLoop = L;
237e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
23899a57216a935a512c418032f590a4660bad9d846Chris Lattner  // Get the preheader block to move instructions into...
23999a57216a935a512c418032f590a4660bad9d846Chris Lattner  Preheader = L->getLoopPreheader();
24099a57216a935a512c418032f590a4660bad9d846Chris Lattner
2412e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Loop over the body of this loop, looking for calls, invokes, and stores.
2420252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner  // Because subloops have already been incorporated into AST, we skip blocks in
2432e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // subloops.
2442e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  //
2459b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman  for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
2469b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman       I != E; ++I) {
2479b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman    BasicBlock *BB = *I;
2484282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    if (LI->getLoopFor(BB) == L)        // Ignore blocks in subloops.
2499b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman      CurAST->add(*BB);                 // Incorporate the specified basic block
2509b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman  }
2512e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
252e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // We want to visit all of the instructions in this loop... that are not parts
253e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // of our subloops (they have already had their invariants hoisted out of
254e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // their loop, into this loop, so there is no need to process the BODIES of
255e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // the subloops).
256e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  //
257952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  // Traverse the body of the loop in depth first order on the dominator tree so
258952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  // that we are guaranteed to see definitions before we see uses.  This allows
259af5cbc82bb6410129425c98bbfc1ffc4c3d0f411Nick Lewycky  // us to sink instructions in one pass, without iteration.  After sinking
260e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  // instructions, we perform another pass to hoist them out of the loop.
261952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  //
26203e896bd6073efc4523d8bcd0239d6ed62126db7Dan Gohman  if (L->hasDedicatedExits())
26303e896bd6073efc4523d8bcd0239d6ed62126db7Dan Gohman    SinkRegion(DT->getNode(L->getHeader()));
26403e896bd6073efc4523d8bcd0239d6ed62126db7Dan Gohman  if (Preheader)
26503e896bd6073efc4523d8bcd0239d6ed62126db7Dan Gohman    HoistRegion(DT->getNode(L->getHeader()));
266e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
2672e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Now that all loop invariants have been removed from the loop, promote any
268e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // memory references to scalars that we can.
269e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
270e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // Loop over all of the alias sets in the tracker object.
271e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
272e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner         I != E; ++I)
273e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      PromoteAliasSet(*I);
274e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  }
275e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
276e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // Clear out loops state information for the next iteration
277e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  CurLoop = 0;
27899a57216a935a512c418032f590a4660bad9d846Chris Lattner  Preheader = 0;
27954959d6cf68a9b575c98c074babe9867682a7271Devang Patel
2804282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner  // If this loop is nested inside of another one, save the alias information
2814282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner  // for when we process the outer loop.
2824282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner  if (L->getParentLoop())
2834282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    LoopToAliasSetMap[L] = CurAST;
2844282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner  else
2854282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner    delete CurAST;
28654959d6cf68a9b575c98c074babe9867682a7271Devang Patel  return Changed;
287e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner}
288e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
289e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner/// SinkRegion - Walk the specified region of the CFG (defined by all blocks
290e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner/// dominated by the specified block, and that are in the current loop) in
2913a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson/// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
292e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner/// uses before definitions, allowing us to sink a loop body in one pass without
293e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner/// iteration.
294e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner///
29526042420d642e810f5cdfb2da6156b74aaf80945Devang Patelvoid LICM::SinkRegion(DomTreeNode *N) {
2963a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  assert(N != 0 && "Null dominator tree node?");
2973a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  BasicBlock *BB = N->getBlock();
298e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
299e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  // If this subregion is not in the top level loop at all, exit.
300e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  if (!CurLoop->contains(BB)) return;
301e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
3020de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner  // We are processing blocks in reverse dfo, so process children first.
30326042420d642e810f5cdfb2da6156b74aaf80945Devang Patel  const std::vector<DomTreeNode*> &Children = N->getChildren();
304e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  for (unsigned i = 0, e = Children.size(); i != e; ++i)
305e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    SinkRegion(Children[i]);
306e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
307e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  // Only need to process the contents of this block if it is not part of a
308e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  // subloop (which would already have been processed).
309e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  if (inSubLoop(BB)) return;
310e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
311a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner  for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
312a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner    Instruction &I = *--II;
3130de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner
3140de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner    // If the instruction is dead, we would try to sink it because it isn't used
3150de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner    // in the loop, instead, just delete it.
3160de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner    if (isInstructionTriviallyDead(&I)) {
317cb7f65342291caa3636cb50c0ee04b383cd79f8dChris Lattner      DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
3180de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner      ++II;
3190de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner      CurAST->deleteValue(&I);
3200de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner      I.eraseFromParent();
3210de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner      Changed = true;
3220de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner      continue;
3230de5cad74d8d2987b92b8d76af3f1eab988b3c7bChris Lattner    }
324fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
325e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    // Check to see if we can sink this instruction to the exit blocks
326e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    // of the loop.  We can do this if the all users of the instruction are
327e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    // outside of the loop.  In this case, it doesn't even matter if the
328e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    // operands of the instruction are loop invariant.
329e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    //
33070ac2dcb841dc62f08e16f0b0e2cefbf01baa4c5Chris Lattner    if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
331a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner      ++II;
332e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      sink(I);
333a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner    }
334e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  }
335e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner}
336e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
337952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
338952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner/// dominated by the specified block, and that are in the current loop) in depth
3393a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson/// first order w.r.t the DominatorTree.  This allows us to visit definitions
340952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner/// before uses, allowing us to hoist a loop body in one pass without iteration.
341952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner///
34226042420d642e810f5cdfb2da6156b74aaf80945Devang Patelvoid LICM::HoistRegion(DomTreeNode *N) {
3433a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  assert(N != 0 && "Null dominator tree node?");
3443a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  BasicBlock *BB = N->getBlock();
345952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
346b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner  // If this subregion is not in the top level loop at all, exit.
347ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  if (!CurLoop->contains(BB)) return;
348952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
349a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // Only need to process the contents of this block if it is not part of a
350a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // subloop (which would already have been processed).
351ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  if (!inSubLoop(BB))
352a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
353a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      Instruction &I = *II++;
354fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
3552ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner      // Try constant folding this instruction.  If all the operands are
3562ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner      // constants, it is technically hoistable, but it would be better to just
3572ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner      // fold it.
3582ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner      if (Constant *C = ConstantFoldInstruction(&I)) {
3592ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner        DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C << '\n');
3602ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner        CurAST->copyValue(&I, C);
3612ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner        CurAST->deleteValue(&I);
3622ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner        I.replaceAllUsesWith(C);
3632ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner        I.eraseFromParent();
3642ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner        continue;
3652ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner      }
3662ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner
367e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      // Try hoisting the instruction out to the preheader.  We can only do this
368e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      // if all of the operands of the instruction are loop invariant and if it
369e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      // is safe to hoist the instruction.
370e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      //
371adc799112dc180b3cd099038c05101b85d217716Chris Lattner      if (CurLoop->hasLoopInvariantOperands(&I) && canSinkOrHoistInst(I) &&
372e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner          isSafeToExecuteUnconditionally(I))
3733c80a51cfd5e7187439ce4c051da77ee46e0ff9aChris Lattner        hoist(I);
3742ac6e2354ac9961b00fa351635ed04baf7fdd234Chris Lattner    }
375952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
37626042420d642e810f5cdfb2da6156b74aaf80945Devang Patel  const std::vector<DomTreeNode*> &Children = N->getChildren();
377952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  for (unsigned i = 0, e = Children.size(); i != e; ++i)
37856b7ee20dad7160a117ea0d102fc5432074ce2d0Chris Lattner    HoistRegion(Children[i]);
379952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner}
380952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
381a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
382a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// instruction.
383a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner///
384a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnerbool LICM::canSinkOrHoistInst(Instruction &I) {
385ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  // Loads have extra constraints we have to verify before we can hoist them.
386ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
387ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner    if (LI->isVolatile())
388ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner      return false;        // Don't hoist volatile loads!
389ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner
390967948b4e25cae3de68f38fddaa75d838e676decChris Lattner    // Loads from constant memory are always safe to move, even if they end up
391967948b4e25cae3de68f38fddaa75d838e676decChris Lattner    // in the same alias set as something that ends up being modified.
392dab249b3b762cff0ff16069b3233e4c885e75347Dan Gohman    if (AA->pointsToConstantMemory(LI->getOperand(0)))
393967948b4e25cae3de68f38fddaa75d838e676decChris Lattner      return true;
394967948b4e25cae3de68f38fddaa75d838e676decChris Lattner
395ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner    // Don't hoist loads which have may-aliased stores in loop.
396f3e1d6977ee5fb6b66df314d65e28e2c35d6e244Chris Lattner    unsigned Size = 0;
397f3e1d6977ee5fb6b66df314d65e28e2c35d6e244Chris Lattner    if (LI->getType()->isSized())
398fc2a3ed0c9e32cf7edaf5030fa0972b916cc5f0bDan Gohman      Size = AA->getTypeStoreSize(LI->getType());
399f3e1d6977ee5fb6b66df314d65e28e2c35d6e244Chris Lattner    return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
400118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner  } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
401118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    // Handle obvious cases efficiently.
402dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands    AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
403dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands    if (Behavior == AliasAnalysis::DoesNotAccessMemory)
404dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      return true;
405dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands    else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
406dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      // If this call only reads from memory and there are no writes to memory
407dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      // in the loop, we can hoist or sink the call as appropriate.
408dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      bool FoundMod = false;
409dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
410dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands           I != E; ++I) {
411dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands        AliasSet &AS = *I;
412dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands        if (!AS.isForwardingAliasSet() && AS.isMod()) {
413dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands          FoundMod = true;
414dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands          break;
415118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner        }
416118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner      }
417dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      if (!FoundMod) return true;
418118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    }
419118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner
420118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    // FIXME: This should use mod/ref information to see if we can hoist or sink
421118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    // the call.
422fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
423118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    return false;
424ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  }
425ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner
4263da59db637a887474c1b1346c1f3ccf53b6c4663Reid Spencer  // Otherwise these instructions are hoistable/sinkable
427832254e1c2387c0cbeb0a820b8315fbe85cb003aReid Spencer  return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
428d8af90c1da64b81a7aa167b5adcc1e81b0741252Dan Gohman         isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
429d8af90c1da64b81a7aa167b5adcc1e81b0741252Dan Gohman         isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
430d8af90c1da64b81a7aa167b5adcc1e81b0741252Dan Gohman         isa<ShuffleVectorInst>(I);
431a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner}
432a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
433a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// isNotUsedInLoop - Return true if the only users of this instruction are
434a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// outside of the loop.  If this is true, we can sink the instruction to the
435a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// exit blocks of the loop.
436a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner///
437a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnerbool LICM::isNotUsedInLoop(Instruction &I) {
438ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner  for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
439ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner    Instruction *User = cast<Instruction>(*UI);
440ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner    if (PHINode *PN = dyn_cast<PHINode>(User)) {
441ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner      // PHI node uses occur in predecessor blocks!
442ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
443ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner        if (PN->getIncomingValue(i) == &I)
444ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner          if (CurLoop->contains(PN->getIncomingBlock(i)))
445ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner            return false;
44692329c7fbe572892c17aa2d2542a10e3ea16132fDan Gohman    } else if (CurLoop->contains(User)) {
447a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      return false;
448ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner    }
449ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner  }
450a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  return true;
451a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner}
452a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
453a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
454a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// sink - When an instruction is found to only be used outside of the loop,
455a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner/// this function moves it to the exit blocks and patches up SSA form as needed.
456a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner/// This method is guaranteed to remove the original instruction from its
457a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner/// position, and may either delete it or move it to outside of the loop.
458a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner///
459a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnervoid LICM::sink(Instruction &I) {
46039a383124b70dda1fea18288235114029ede76cfNick Lewycky  DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
461a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
462b7211a2ce13a0365e0e1dd2f27adda2ee3d1288bDevang Patel  SmallVector<BasicBlock*, 8> ExitBlocks;
463d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  CurLoop->getUniqueExitBlocks(ExitBlocks);
464df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner
465df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner  if (isa<LoadInst>(I)) ++NumMovedLoads;
466118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner  else if (isa<CallInst>(I)) ++NumMovedCalls;
467df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner  ++NumSunk;
468df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner  Changed = true;
469df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner
470a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // The case where there is only a single exit node of this loop is common
471a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // enough that we handle it as a special (more efficient) case.  It is more
472a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // efficient to handle because there are no PHI nodes that need to be placed.
473a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  if (ExitBlocks.size() == 1) {
474a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
475a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // Instruction is not used, just delete it.
4762741c971044d2165be572749b94398043caccfebChris Lattner      CurAST->deleteValue(&I);
4771bf5ebc7be0d5b05e4175c7adb767b38896adef1Devang Patel      // If I has users in unreachable blocks, eliminate.
478228ebd0f4cf9207d32d61ef4b11b81736895dc09Devang Patel      // If I is not void type then replaceAllUsesWith undef.
479228ebd0f4cf9207d32d61ef4b11b81736895dc09Devang Patel      // This allows ValueHandlers and custom metadata to adjust itself.
480a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner      if (!I.use_empty())
481228ebd0f4cf9207d32d61ef4b11b81736895dc09Devang Patel        I.replaceAllUsesWith(UndefValue::get(I.getType()));
4823c80a51cfd5e7187439ce4c051da77ee46e0ff9aChris Lattner      I.eraseFromParent();
483a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    } else {
484a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // Move the instruction to the start of the exit block, after any PHI
485a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // nodes in it.
486d9a5daeb7719c83136c0dc43d6ef732402d1a1b5Chris Lattner      I.moveBefore(ExitBlocks[0]->getFirstNonPHI());
4874282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner
4884282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner      // This instruction is no longer in the AST for the current loop, because
4894282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner      // we just sunk it out of the loop.  If we just sunk it into an outer
4904282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner      // loop, we will rediscover the operation when we process it.
4914282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner      CurAST->deleteValue(&I);
492a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    }
493d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    return;
494d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  }
495d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner
496d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  if (ExitBlocks.empty()) {
497a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // The instruction is actually dead if there ARE NO exit blocks.
4982741c971044d2165be572749b94398043caccfebChris Lattner    CurAST->deleteValue(&I);
4991bf5ebc7be0d5b05e4175c7adb767b38896adef1Devang Patel    // If I has users in unreachable blocks, eliminate.
500228ebd0f4cf9207d32d61ef4b11b81736895dc09Devang Patel    // If I is not void type then replaceAllUsesWith undef.
501228ebd0f4cf9207d32d61ef4b11b81736895dc09Devang Patel    // This allows ValueHandlers and custom metadata to adjust itself.
502a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    if (!I.use_empty())
503228ebd0f4cf9207d32d61ef4b11b81736895dc09Devang Patel      I.replaceAllUsesWith(UndefValue::get(I.getType()));
5043c80a51cfd5e7187439ce4c051da77ee46e0ff9aChris Lattner    I.eraseFromParent();
505d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    return;
506d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  }
507d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner
508a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  // Otherwise, if we have multiple exits, use the SSAUpdater to do all of the
509a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  // hard work of inserting PHI nodes as necessary.
510a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  SmallVector<PHINode*, 8> NewPHIs;
511a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  SSAUpdater SSA(&NewPHIs);
512a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner
513a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  if (!I.use_empty())
514fc6e29d4ab52b7d3efd83846ed495a9ca7e51e49Duncan Sands    SSA.Initialize(I.getType(), I.getName());
515d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner
516a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  // Insert a copy of the instruction in each exit block of the loop that is
517a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  // dominated by the instruction.  Each exit block is known to only be in the
518a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  // ExitBlocks list once.
519a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  BasicBlock *InstOrigBB = I.getParent();
520d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  unsigned NumInserted = 0;
521a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner
522d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
523d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    BasicBlock *ExitBlock = ExitBlocks[i];
524a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner
525d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    if (!isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB))
526d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner      continue;
527d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner
528a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    // Insert the code after the last PHI node.
529d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    BasicBlock::iterator InsertPt = ExitBlock->getFirstNonPHI();
530a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner
531d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    // If this is the first exit block processed, just move the original
532d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    // instruction, otherwise clone the original instruction and insert
533d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    // the copy.
534d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    Instruction *New;
535a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    if (NumInserted++ == 0) {
536a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner      I.moveBefore(InsertPt);
537d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner      New = &I;
538d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    } else {
539d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner      New = I.clone();
540d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner      if (!I.getName().empty())
541d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner        New->setName(I.getName()+".le");
542d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner      ExitBlock->getInstList().insert(InsertPt, New);
543a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    }
544d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner
545a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    // Now that we have inserted the instruction, inform SSAUpdater.
546a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    if (!I.use_empty())
547a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner      SSA.AddAvailableValue(ExitBlock, New);
548d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  }
549a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner
550d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  // If the instruction doesn't dominate any exit blocks, it must be dead.
551d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  if (NumInserted == 0) {
552d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    CurAST->deleteValue(&I);
553a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    if (!I.use_empty())
554a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner      I.replaceAllUsesWith(UndefValue::get(I.getType()));
555d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner    I.eraseFromParent();
556a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    return;
557d7bc19dfee3f2ce8e9c8b9193bdfb93a67008a39Chris Lattner  }
558a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner
559a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  // Next, rewrite uses of the instruction, inserting PHI nodes as needed.
560a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE; ) {
561a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    // Grab the use before incrementing the iterator.
562a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    Use &U = UI.getUse();
563a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    // Increment the iterator before removing the use from the list.
564a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    ++UI;
565a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    SSA.RewriteUseAfterInsertions(U);
566a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  }
567a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner
568a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  // Update CurAST for NewPHIs if I had pointer type.
569a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner  if (I.getType()->isPointerTy())
570a6a36f59b42703c5da0f68e0db37605c2e1633bfChris Lattner    for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
5719c282011e6b7a6e23a3a163ec9c865890449e8dcChris Lattner      CurAST->copyValue(&I, NewPHIs[i]);
57298917503c702e16f35ccdec3f6b4c48e5c4759acChris Lattner
57398917503c702e16f35ccdec3f6b4c48e5c4759acChris Lattner  // Finally, remove the instruction from CurAST.  It is no longer in the loop.
57498917503c702e16f35ccdec3f6b4c48e5c4759acChris Lattner  CurAST->deleteValue(&I);
575a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner}
576952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
57794170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner/// hoist - When an instruction is found to only use loop invariant operands
57894170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner/// that is safe to hoist, this instruction is called to do the dirty work.
57994170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner///
580a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnervoid LICM::hoist(Instruction &I) {
581f15826999bc560ee6f67cff5ecd71bf9cce7a7aaDavid Greene  DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
58267d1d1f8322bdc460158888cd233be8d1cb1d4abEvan Cheng        << I << "\n");
583ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner
584d9a5daeb7719c83136c0dc43d6ef732402d1a1b5Chris Lattner  // Move the new node to the Preheader, before its terminator.
585d9a5daeb7719c83136c0dc43d6ef732402d1a1b5Chris Lattner  I.moveBefore(Preheader->getTerminator());
586fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
587a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  if (isa<LoadInst>(I)) ++NumMovedLoads;
588118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner  else if (isa<CallInst>(I)) ++NumMovedCalls;
5899646e6b6af1f924f9366a2bffc6dde102f84d231Chris Lattner  ++NumHoisted;
590e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  Changed = true;
591e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner}
592e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
593a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
594a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// not a trapping instruction or if it is a trapping instruction and is
595a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// guaranteed to execute.
5969966c03aad031f738718bed3bc00371e358beb5dTanya Lattner///
597a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnerbool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
59892094b4d928119eceac1484331acffe950f4651cChris Lattner  // If it is not a trapping instruction, it is always safe to hoist.
5990b79a7727d68a507837e827803859424cf3d997bEli Friedman  if (Inst.isSafeToSpeculativelyExecute())
6000b79a7727d68a507837e827803859424cf3d997bEli Friedman    return true;
601fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
60292094b4d928119eceac1484331acffe950f4651cChris Lattner  // Otherwise we have to check to make sure that the instruction dominates all
60392094b4d928119eceac1484331acffe950f4651cChris Lattner  // of the exit blocks.  If it doesn't, then there is a path out of the loop
60492094b4d928119eceac1484331acffe950f4651cChris Lattner  // which does not execute this instruction, so we can't hoist it.
60592094b4d928119eceac1484331acffe950f4651cChris Lattner
60692094b4d928119eceac1484331acffe950f4651cChris Lattner  // If the instruction is in the header block for the loop (which is very
60792094b4d928119eceac1484331acffe950f4651cChris Lattner  // common), it is always guaranteed to dominate the exit blocks.  Since this
60892094b4d928119eceac1484331acffe950f4651cChris Lattner  // is a common case, and can save some work, check it now.
609a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  if (Inst.getParent() == CurLoop->getHeader())
61092094b4d928119eceac1484331acffe950f4651cChris Lattner    return true;
61192094b4d928119eceac1484331acffe950f4651cChris Lattner
61292094b4d928119eceac1484331acffe950f4651cChris Lattner  // Get the exit blocks for the current loop.
613b7211a2ce13a0365e0e1dd2f27adda2ee3d1288bDevang Patel  SmallVector<BasicBlock*, 8> ExitBlocks;
6145fa802fe279f10f402e039bc931aa57c0e424bf5Chris Lattner  CurLoop->getExitBlocks(ExitBlocks);
6159966c03aad031f738718bed3bc00371e358beb5dTanya Lattner
6163a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  // For each exit block, get the DT node and walk up the DT until the
61792094b4d928119eceac1484331acffe950f4651cChris Lattner  // instruction's basic block is found or we exit the loop.
618a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
619a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
620a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      return false;
621fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
6229966c03aad031f738718bed3bc00371e358beb5dTanya Lattner  return true;
6239966c03aad031f738718bed3bc00371e358beb5dTanya Lattner}
6249966c03aad031f738718bed3bc00371e358beb5dTanya Lattner
625e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner/// PromoteAliasSet - Try to promote memory values to scalars by sinking
6262e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// stores out of the loop and moving loads to before the loop.  We do this by
6272e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// looping over the stores in the loop, looking for stores to Must pointers
628e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner/// which are loop invariant.
6292e6e741b737960ecd0b68610875050019aac0f07Chris Lattner///
630e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattnervoid LICM::PromoteAliasSet(AliasSet &AS) {
631e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // We can promote this alias set if it has a store, if it is a "Must" alias
632e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // set, if the pointer is loop invariant, and if we are not eliminating any
633e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // volatile loads or stores.
634e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
635e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
636e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    return;
637e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
638e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  assert(!AS.empty() &&
639e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner         "Must alias set should have at least one pointer element in it!");
640e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  Value *SomePtr = AS.begin()->getValue();
641fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
642e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // It isn't safe to promote a load/store from the loop if the load/store is
643e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // conditional.  For example, turning:
6442e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  //
645e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  //    for () { if (c) *P += 1; }
6462e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  //
647e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // into:
648e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  //
649e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
650e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  //
651e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // is not safe, because *P may only be valid to access if 'c' is true.
652e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  //
653e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // It is safe to promote P if all uses are direct load/stores and if at
654e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // least one is guaranteed to be executed.
655e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  bool GuaranteedToExecute = false;
656e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
657e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  SmallVector<Instruction*, 64> LoopUses;
658e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  SmallPtrSet<Value*, 4> PointerMustAliases;
659e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
660e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // Check that all of the pointers in the alias set have the same type.  We
661e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // cannot (yet) promote a memory location that is loaded and stored in
662e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // different sizes.
663e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
664e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    Value *ASIV = ASI->getValue();
665e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    PointerMustAliases.insert(ASIV);
66629d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner
66729d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    // Check that all of the pointers in the alias set have the same type.  We
66829d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    // cannot (yet) promote a memory location that is loaded and stored in
66929d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    // different sizes.
670e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    if (SomePtr->getType() != ASIV->getType())
671e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      return;
672e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
673e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    for (Value::use_iterator UI = ASIV->use_begin(), UE = ASIV->use_end();
67419d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner         UI != UE; ++UI) {
675e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      // Ignore instructions that are outside the loop.
67629d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner      Instruction *Use = dyn_cast<Instruction>(*UI);
67792329c7fbe572892c17aa2d2542a10e3ea16132fDan Gohman      if (!Use || !CurLoop->contains(Use))
67829d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner        continue;
679e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
680e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      // If there is an non-load/store instruction in the loop, we can't promote
681e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      // it.
682e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      if (isa<LoadInst>(Use))
683e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        assert(!cast<LoadInst>(Use)->isVolatile() && "AST broken");
684e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      else if (isa<StoreInst>(Use))
685e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        assert(!cast<StoreInst>(Use)->isVolatile() &&
686e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner               Use->getOperand(0) != ASIV && "AST broken");
687e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      else
688e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        return; // Not a load or store.
68919d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner
69019d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner      if (!GuaranteedToExecute)
69119d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner        GuaranteedToExecute = isSafeToExecuteUnconditionally(*Use);
692e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
693e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      LoopUses.push_back(Use);
69429d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    }
695e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  }
696e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
697e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // If there isn't a guaranteed-to-execute instruction, we can't promote.
698e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  if (!GuaranteedToExecute)
699e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    return;
700e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
701e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // Otherwise, this is safe to promote, lets do it!
702e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
703e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  Changed = true;
704e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  ++NumPromoted;
705bc2265abe1d1b830995bb2f6322409bc7d7c5740Devang Patel
706e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // We use the SSAUpdater interface to insert phi nodes as required.
707e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  SmallVector<PHINode*, 16> NewPHIs;
708e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  SSAUpdater SSA(&NewPHIs);
709e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
710e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // It wants to know some value of the same type as what we'll be inserting.
711e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  Value *SomeValue;
712e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  if (isa<LoadInst>(LoopUses[0]))
713e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    SomeValue = LoopUses[0];
714e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  else
715e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    SomeValue = cast<StoreInst>(LoopUses[0])->getOperand(0);
716fc6e29d4ab52b7d3efd83846ed495a9ca7e51e49Duncan Sands  SSA.Initialize(SomeValue->getType(), SomeValue->getName());
717e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
718e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // First step: bucket up uses of the pointers by the block they occur in.
719e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // This is important because we have to handle multiple defs/uses in a block
720e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // ourselves: SSAUpdater is purely for cross-block references.
721e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // FIXME: Want a TinyVector<Instruction*> since there is usually 0/1 element.
722e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  DenseMap<BasicBlock*, std::vector<Instruction*> > UsesByBlock;
723e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  for (unsigned i = 0, e = LoopUses.size(); i != e; ++i) {
724e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    Instruction *User = LoopUses[i];
725e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    UsesByBlock[User->getParent()].push_back(User);
726e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  }
727e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
728e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // Okay, now we can iterate over all the blocks in the loop with uses,
729e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // processing them.  Keep track of which loads are loading a live-in value.
730e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  SmallVector<LoadInst*, 32> LiveInLoads;
731469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner  DenseMap<Value*, Value*> ReplacedLoads;
732e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
733e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  for (unsigned LoopUse = 0, e = LoopUses.size(); LoopUse != e; ++LoopUse) {
734e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    Instruction *User = LoopUses[LoopUse];
735e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    std::vector<Instruction*> &BlockUses = UsesByBlock[User->getParent()];
736e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
737e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // If this block has already been processed, ignore this repeat use.
738e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    if (BlockUses.empty()) continue;
739e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
740e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // Okay, this is the first use in the block.  If this block just has a
741e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // single user in it, we can rewrite it trivially.
742e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    if (BlockUses.size() == 1) {
743e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      // If it is a store, it is a trivial def of the value in the block.
744e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      if (isa<StoreInst>(User)) {
745e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        SSA.AddAvailableValue(User->getParent(),
746e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner                              cast<StoreInst>(User)->getOperand(0));
747e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      } else {
748e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        // Otherwise it is a load, queue it to rewrite as a live-in load.
749e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        LiveInLoads.push_back(cast<LoadInst>(User));
750e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      }
751e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      BlockUses.clear();
75229d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner      continue;
753e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    }
754e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
755e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // Otherwise, check to see if this block is all loads.  If so, we can queue
756e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // them all as live in loads.
757e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    bool HasStore = false;
758e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) {
759e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      if (isa<StoreInst>(BlockUses[i])) {
760e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        HasStore = true;
761e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        break;
762e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      }
763e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    }
76429d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner
765e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    if (!HasStore) {
766e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      for (unsigned i = 0, e = BlockUses.size(); i != e; ++i)
767e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        LiveInLoads.push_back(cast<LoadInst>(BlockUses[i]));
768e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      BlockUses.clear();
769e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      continue;
770e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    }
771e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
772e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // Otherwise, we have mixed loads and stores (or just a bunch of stores).
773e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // Since SSAUpdater is purely for cross-block values, we need to determine
774e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // the order of these instructions in the block.  If the first use in the
775e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // block is a load, then it uses the live in value.  The last store defines
776e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // the live out value.  We handle this by doing a linear scan of the block.
777e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    BasicBlock *BB = User->getParent();
778e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    Value *StoredValue = 0;
779e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
780e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      if (LoadInst *L = dyn_cast<LoadInst>(II)) {
781469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner        // If this is a load from an unrelated pointer, ignore it.
782e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        if (!PointerMustAliases.count(L->getOperand(0))) continue;
783e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
784e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        // If we haven't seen a store yet, this is a live in use, otherwise
785e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        // use the stored value.
786469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner        if (StoredValue) {
787e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner          L->replaceAllUsesWith(StoredValue);
788469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner          ReplacedLoads[L] = StoredValue;
789469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner        } else {
790e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner          LiveInLoads.push_back(L);
791469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner        }
792e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        continue;
793e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      }
794e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
795e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      if (StoreInst *S = dyn_cast<StoreInst>(II)) {
796445560881898fe212c185bd4c0485140d7b4fc88Chris Lattner        // If this is a store to an unrelated pointer, ignore it.
797e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        if (!PointerMustAliases.count(S->getOperand(1))) continue;
798fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner
799e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        // Remember that this is the active value in the block.
800e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner        StoredValue = S->getOperand(0);
801e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      }
802e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    }
803e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
804e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // The last stored value that happened is the live-out for the block.
805e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    assert(StoredValue && "Already checked that there is a store in block");
806e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    SSA.AddAvailableValue(BB, StoredValue);
807e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    BlockUses.clear();
808e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  }
809e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
810e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // Now that all the intra-loop values are classified, set up the preheader.
811e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // It gets a load of the pointer we're promoting, and it is the live-out value
812e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // from the preheader.
813e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  LoadInst *PreheaderLoad = new LoadInst(SomePtr,SomePtr->getName()+".promoted",
814e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner                                         Preheader->getTerminator());
815e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  SSA.AddAvailableValue(Preheader, PreheaderLoad);
816e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
817e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // Now that the preheader is good to go, set up the exit blocks.  Each exit
818e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // block gets a store of the live-out values that feed them.  Since we've
819e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // already told the SSA updater about the defs in the loop and the preheader
820e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // definition, it is all set and we can start using it.
821e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  SmallVector<BasicBlock*, 8> ExitBlocks;
822e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  CurLoop->getUniqueExitBlocks(ExitBlocks);
823e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
824e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    BasicBlock *ExitBlock = ExitBlocks[i];
825e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
826e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    Instruction *InsertPos = ExitBlock->getFirstNonPHI();
827e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    new StoreInst(LiveInValue, SomePtr, InsertPos);
828e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  }
829fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
830e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // Okay, now we rewrite all loads that use live-in values in the loop,
831e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // inserting PHI nodes as necessary.
832e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  for (unsigned i = 0, e = LiveInLoads.size(); i != e; ++i) {
833e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    LoadInst *ALoad = LiveInLoads[i];
8349c282011e6b7a6e23a3a163ec9c865890449e8dcChris Lattner    Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
8359c282011e6b7a6e23a3a163ec9c865890449e8dcChris Lattner    ALoad->replaceAllUsesWith(NewVal);
8369c282011e6b7a6e23a3a163ec9c865890449e8dcChris Lattner    CurAST->copyValue(ALoad, NewVal);
837469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner    ReplacedLoads[ALoad] = NewVal;
838e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  }
839e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
840e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // Now that everything is rewritten, delete the old instructions from the body
841e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // of the loop.  They should all be dead now.
842e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  for (unsigned i = 0, e = LoopUses.size(); i != e; ++i) {
843e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    Instruction *User = LoopUses[i];
844469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner
845469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner    // If this is a load that still has uses, then the load must have been added
846469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner    // as a live value in the SSAUpdate data structure for a block (e.g. because
847469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner    // the loaded value was stored later).  In this case, we need to recursively
848469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner    // propagate the updates until we get to the real value.
849469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner    if (!User->use_empty()) {
850469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      Value *NewVal = ReplacedLoads[User];
851469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      assert(NewVal && "not a replaced load?");
852469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner
853469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      // Propagate down to the ultimate replacee.  The intermediately loads
854469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      // could theoretically already have been deleted, so we don't want to
855469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      // dereference the Value*'s.
856469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
857469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      while (RLI != ReplacedLoads.end()) {
858469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner        NewVal = RLI->second;
859469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner        RLI = ReplacedLoads.find(NewVal);
860469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      }
861469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner
862469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      User->replaceAllUsesWith(NewVal);
863469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner      CurAST->copyValue(User, NewVal);
864469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner    }
865469996400c4ab89d5ddb2eb80acc1c1553439f07Chris Lattner
866e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    CurAST->deleteValue(User);
867e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    User->eraseFromParent();
868e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  }
869e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
870e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // If the preheader load is itself a pointer, we need to tell alias analysis
871e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // about the new pointer we created in the preheader block and about any PHI
872e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // nodes that just got inserted.
873e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  if (PreheaderLoad->getType()->isPointerTy()) {
874e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    // Copy any value stored to or loaded from a must-alias of the pointer.
875e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    CurAST->copyValue(SomeValue, PreheaderLoad);
876fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
877e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner    for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
878e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner      CurAST->copyValue(SomeValue, NewPHIs[i]);
8792e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  }
880e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
881e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner  // fwew, we're done!
882f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner}
88391d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
884e488064922f12c4cf07f3aef9a4d2d3ffd15f9c0Chris Lattner
88591d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel/// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
88691d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patelvoid LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
8874282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner  AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
88891d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel  if (!AST)
88991d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    return;
89091d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
89191d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel  AST->copyValue(From, To);
89291d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel}
89391d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
89491d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel/// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
89591d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel/// set.
89691d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patelvoid LICM::deleteAnalysisValue(Value *V, Loop *L) {
8974282e32712da220fd97177772e22ec1ee7e50af2Chris Lattner  AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
89891d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel  if (!AST)
89991d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    return;
90091d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
90191d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel  AST->deleteValue(V);
90291d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel}
903