LICM.cpp revision e922c0201916e0b980ab3cfe91e1413e68d55647
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
292e6e741b737960ecd0b68610875050019aac0f07Chris Lattner//     the mem2reg functionality to construct the appropriate SSA form for the
302e6e741b737960ecd0b68610875050019aac0f07Chris Lattner//     variable.
31e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner//
32e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner//===----------------------------------------------------------------------===//
33e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
341f309c1a4e8068a64627c612a895d9b403dbcb26Chris Lattner#define DEBUG_TYPE "licm"
35e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner#include "llvm/Transforms/Scalar.h"
3679066fa6acce02c97c714a5a6e151ed8a249721cChris Lattner#include "llvm/Constants.h"
372741c971044d2165be572749b94398043caccfebChris Lattner#include "llvm/DerivedTypes.h"
382741c971044d2165be572749b94398043caccfebChris Lattner#include "llvm/Instructions.h"
391ff50b380e6f5549f5ddd9e6c390dcb00332e3e9Owen Anderson#include "llvm/LLVMContext.h"
402741c971044d2165be572749b94398043caccfebChris Lattner#include "llvm/Target/TargetData.h"
41e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner#include "llvm/Analysis/LoopInfo.h"
4254959d6cf68a9b575c98c074babe9867682a7271Devang Patel#include "llvm/Analysis/LoopPass.h"
43f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner#include "llvm/Analysis/AliasAnalysis.h"
440252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner#include "llvm/Analysis/AliasSetTracker.h"
45952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner#include "llvm/Analysis/Dominators.h"
4696b651c627160e1ea0f1bb86d352d697e6c1972dDevang Patel#include "llvm/Analysis/ScalarEvolution.h"
472741c971044d2165be572749b94398043caccfebChris Lattner#include "llvm/Transforms/Utils/PromoteMemToReg.h"
489133fe28954d498fc4de13064c7d65bd811de02cReid Spencer#include "llvm/Support/CFG.h"
499133fe28954d498fc4de13064c7d65bd811de02cReid Spencer#include "llvm/Support/Compiler.h"
50551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/Support/CommandLine.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
66d7168ddb116c2e9aa1f8325ae887eb63d6003037Chris Lattner// This feature is currently disabled by default because CodeGen is not yet
67d7168ddb116c2e9aa1f8325ae887eb63d6003037Chris Lattner// capable of rematerializing these constants in PIC mode, so it can lead to
68d7168ddb116c2e9aa1f8325ae887eb63d6003037Chris Lattner// degraded performance. Compile test/CodeGen/X86/remat-constant.ll with
693eee6542f5c65dce299361fa5435340513cf3fe4Dan Gohman// -relocation-model=pic to see an example of this.
703eee6542f5c65dce299361fa5435340513cf3fe4Dan Gohmanstatic cl::opt<bool>
713eee6542f5c65dce299361fa5435340513cf3fe4Dan GohmanEnableLICMConstantMotion("enable-licm-constant-variables", cl::Hidden,
723eee6542f5c65dce299361fa5435340513cf3fe4Dan Gohman                         cl::desc("Enable hoisting/sinking of constant "
733eee6542f5c65dce299361fa5435340513cf3fe4Dan Gohman                                  "global variables"));
743eee6542f5c65dce299361fa5435340513cf3fe4Dan Gohman
75844731a7f1909f55935e3514c9e713a62d67662eDan Gohmannamespace {
7654959d6cf68a9b575c98c074babe9867682a7271Devang Patel  struct VISIBILITY_HIDDEN LICM : public LoopPass {
77ecd94c804a563f2a86572dcf1d2e81f397e19daaNick Lewycky    static char ID; // Pass identification, replacement for typeid
78ae73dc1448d25b02cabc7c64c86c64371453dda8Dan Gohman    LICM() : LoopPass(&ID) {}
79794fd75c67a2cdc128d67342c6d88a504d186896Devang Patel
8054959d6cf68a9b575c98c074babe9867682a7271Devang Patel    virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
81e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
8294170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// This transformation requires natural loop information & requires that
8394170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// loop preheaders be inserted into the CFG...
8494170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    ///
85e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
86cb2610ea037a17115ef3a01a6bdaab4e3cfdca27Chris Lattner      AU.setPreservesCFG();
8798bf436e2e2ab463d79c54a42a46b12028905330Chris Lattner      AU.addRequiredID(LoopSimplifyID);
885f0eb8da62308126d5b61e3eee5bee75b9dc5194Chris Lattner      AU.addRequired<LoopInfo>();
893a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson      AU.addRequired<DominatorTree>();
900252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      AU.addRequired<DominanceFrontier>();  // For scalar promotion (mem2reg)
91f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner      AU.addRequired<AliasAnalysis>();
9296b651c627160e1ea0f1bb86d352d697e6c1972dDevang Patel      AU.addPreserved<ScalarEvolution>();
9396b651c627160e1ea0f1bb86d352d697e6c1972dDevang Patel      AU.addPreserved<DominanceFrontier>();
94e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner    }
95e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
96747603e39ea3f29add9ba6c07bbefcc5c2432612Dan Gohman    bool doFinalization() {
97fd94dd58ffef1be3597ef8cb64f3b1d476d7d5ecAnton Korobeynikov      // Free the values stored in the map
98fd94dd58ffef1be3597ef8cb64f3b1d476d7d5ecAnton Korobeynikov      for (std::map<Loop *, AliasSetTracker *>::iterator
99fd94dd58ffef1be3597ef8cb64f3b1d476d7d5ecAnton Korobeynikov             I = LoopToAliasMap.begin(), E = LoopToAliasMap.end(); I != E; ++I)
100fd94dd58ffef1be3597ef8cb64f3b1d476d7d5ecAnton Korobeynikov        delete I->second;
101fd94dd58ffef1be3597ef8cb64f3b1d476d7d5ecAnton Korobeynikov
10254959d6cf68a9b575c98c074babe9867682a7271Devang Patel      LoopToAliasMap.clear();
10354959d6cf68a9b575c98c074babe9867682a7271Devang Patel      return false;
10454959d6cf68a9b575c98c074babe9867682a7271Devang Patel    }
10554959d6cf68a9b575c98c074babe9867682a7271Devang Patel
106e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  private:
10792094b4d928119eceac1484331acffe950f4651cChris Lattner    // Various analyses that we use...
1082e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    AliasAnalysis *AA;       // Current AliasAnalysis information
10992094b4d928119eceac1484331acffe950f4651cChris Lattner    LoopInfo      *LI;       // Current LoopInfo
1103a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson    DominatorTree *DT;       // Dominator Tree for the current Loop...
11143f820d1f7638656be2158efac7dd8f5b08b8b77Chris Lattner    DominanceFrontier *DF;   // Current Dominance Frontier
11292094b4d928119eceac1484331acffe950f4651cChris Lattner
11392094b4d928119eceac1484331acffe950f4651cChris Lattner    // State that is updated as we process loops
1142e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    bool Changed;            // Set to true when we change anything.
1152e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    BasicBlock *Preheader;   // The preheader block of the current loop...
1162e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    Loop *CurLoop;           // The current loop we are working on...
1170252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner    AliasSetTracker *CurAST; // AliasSet information for the current loop...
11854959d6cf68a9b575c98c074babe9867682a7271Devang Patel    std::map<Loop *, AliasSetTracker *> LoopToAliasMap;
119e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
12091d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
12191d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
12291d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
12391d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
12491d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    /// set.
12591d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    void deleteAnalysisValue(Value *V, Loop *L);
12691d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
127e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
128e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    /// dominated by the specified block, and that are in the current loop) in
1293a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson    /// reverse depth first order w.r.t the DominatorTree.  This allows us to
130e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    /// visit uses before definitions, allowing us to sink a loop body in one
131e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    /// pass without iteration.
132e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    ///
13326042420d642e810f5cdfb2da6156b74aaf80945Devang Patel    void SinkRegion(DomTreeNode *N);
134e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
135952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    /// HoistRegion - Walk the specified region of the CFG (defined by all
136952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    /// blocks dominated by the specified block, and that are in the current
1373a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson    /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
138cf00c4ab3ba308d45d98c5ccab87362cf802facbMisha Brukman    /// visit definitions before uses, allowing us to hoist a loop body in one
139952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    /// pass without iteration.
140952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    ///
14126042420d642e810f5cdfb2da6156b74aaf80945Devang Patel    void HoistRegion(DomTreeNode *N);
142952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
143b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner    /// inSubLoop - Little predicate that returns true if the specified basic
144b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner    /// block is in a subloop of the current one, not the current one itself.
14594170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    ///
146b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner    bool inSubLoop(BasicBlock *BB) {
147b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner      assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
148329c1c6c949d07e3fe9722ec633b4258217fd99dChris Lattner      for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
149329c1c6c949d07e3fe9722ec633b4258217fd99dChris Lattner        if ((*I)->contains(BB))
150b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner          return true;  // A subloop actually contains this block!
151b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner      return false;
152e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner    }
153e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
154a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
155a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// specified exit block of the loop is dominated by the specified block
156a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// that is in the body of the loop.  We use these constraints to
157a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// dramatically limit the amount of the dominator tree that needs to be
158a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// searched.
159a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
160a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner                                           BasicBlock *BlockInLoop) const {
161a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // If the block in the loop is the loop header, it must be dominated!
162a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      BasicBlock *LoopHeader = CurLoop->getHeader();
163a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      if (BlockInLoop == LoopHeader)
164a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        return true;
165fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
16626042420d642e810f5cdfb2da6156b74aaf80945Devang Patel      DomTreeNode *BlockInLoopNode = DT->getNode(BlockInLoop);
16726042420d642e810f5cdfb2da6156b74aaf80945Devang Patel      DomTreeNode *IDom            = DT->getNode(ExitBlock);
168fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
169a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // Because the exit block is not in the loop, we know we have to get _at
1702741c971044d2165be572749b94398043caccfebChris Lattner      // least_ its immediate dominator.
171a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      do {
172a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // Get next Immediate Dominator.
1733a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson        IDom = IDom->getIDom();
174fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
175a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // If we have got to the header of the loop, then the instructions block
176a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // did not dominate the exit node, so we can't hoist it.
1773a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson        if (IDom->getBlock() == LoopHeader)
178a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          return false;
179fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
1803a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson      } while (IDom != BlockInLoopNode);
181a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
182a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      return true;
183a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    }
184a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
185a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// sink - When an instruction is found to only be used outside of the loop,
186a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// this function moves it to the exit blocks and patches up SSA form as
187a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// needed.
188a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    ///
189a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    void sink(Instruction &I);
190a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
19194170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// hoist - When an instruction is found to only use loop invariant operands
19294170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// that is safe to hoist, this instruction is called to do the dirty work.
19394170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    ///
1947e70829632f82de15db187845666aaca6e04b792Chris Lattner    void hoist(Instruction &I);
195e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
196a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
197a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// is not a trapping instruction or if it is a trapping instruction and is
198a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// guaranteed to execute.
1999966c03aad031f738718bed3bc00371e358beb5dTanya Lattner    ///
200a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    bool isSafeToExecuteUnconditionally(Instruction &I);
2019966c03aad031f738718bed3bc00371e358beb5dTanya Lattner
20294170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// pointerInvalidatedByLoop - Return true if the body of this loop may
20394170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// store into the memory location pointed to by V.
204fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman    ///
205f3e1d6977ee5fb6b66df314d65e28e2c35d6e244Chris Lattner    bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
2060252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      // Check to see if any of the basic blocks in CurLoop invalidate *V.
207f3e1d6977ee5fb6b66df314d65e28e2c35d6e244Chris Lattner      return CurAST->getAliasSetForPointer(V, Size).isMod();
2082e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    }
209f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner
210a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    bool canSinkOrHoistInst(Instruction &I);
211a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    bool isLoopInvariantInst(Instruction &I);
212a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    bool isNotUsedInLoop(Instruction &I);
213e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
2142e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
2152e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    /// to scalars as we can.
2162e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    ///
2172e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    void PromoteValuesInLoop();
2182e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
219fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner    /// FindPromotableValuesInLoop - Check the current loop for stores to
220352361b409d16045e703d986aa7fd77295173ef3Misha Brukman    /// definite pointers, which are not loaded and stored through may aliases.
2212e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    /// If these are found, create an alloca for the value, add it to the
2222e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    /// PromotedValues list, and keep track of the mapping from value to
2232e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    /// alloca...
2242e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    ///
225fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner    void FindPromotableValuesInLoop(
2262e6e741b737960ecd0b68610875050019aac0f07Chris Lattner                   std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
2272e6e741b737960ecd0b68610875050019aac0f07Chris Lattner                                    std::map<Value*, AllocaInst*> &Val2AlMap);
228e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  };
229e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner}
230e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
231844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanchar LICM::ID = 0;
232844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanstatic RegisterPass<LICM> X("licm", "Loop Invariant Code Motion");
233844731a7f1909f55935e3514c9e713a62d67662eDan Gohman
234394f0441e06dafca29f0752cf400990a5b8fe4b1Daniel DunbarPass *llvm::createLICMPass() { return new LICM(); }
235e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
2368d246f09cb46fe38aa71d2a4edcd84f30c4bf80eDevang Patel/// Hoist expressions out of the specified loop. Note, alias info for inner
2378d246f09cb46fe38aa71d2a4edcd84f30c4bf80eDevang Patel/// loop is not preserved so it is not a good idea to run LICM multiple
2388d246f09cb46fe38aa71d2a4edcd84f30c4bf80eDevang Patel/// times on one loop.
23994170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner///
24054959d6cf68a9b575c98c074babe9867682a7271Devang Patelbool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
2412e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  Changed = false;
242e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
2432e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Get our Loop and Alias Analysis information...
2442e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  LI = &getAnalysis<LoopInfo>();
245f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner  AA = &getAnalysis<AliasAnalysis>();
24643f820d1f7638656be2158efac7dd8f5b08b8b77Chris Lattner  DF = &getAnalysis<DominanceFrontier>();
2473a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  DT = &getAnalysis<DominatorTree>();
248f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner
24954959d6cf68a9b575c98c074babe9867682a7271Devang Patel  CurAST = new AliasSetTracker(*AA);
250f38ac5dd390ca583b6e6d1b40b378d07e49e5097Devang Patel  // Collect Alias info from subloops
25154959d6cf68a9b575c98c074babe9867682a7271Devang Patel  for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
25254959d6cf68a9b575c98c074babe9867682a7271Devang Patel       LoopItr != LoopItrE; ++LoopItr) {
25354959d6cf68a9b575c98c074babe9867682a7271Devang Patel    Loop *InnerL = *LoopItr;
25454959d6cf68a9b575c98c074babe9867682a7271Devang Patel    AliasSetTracker *InnerAST = LoopToAliasMap[InnerL];
25554959d6cf68a9b575c98c074babe9867682a7271Devang Patel    assert (InnerAST && "Where is my AST?");
25694170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner
25754959d6cf68a9b575c98c074babe9867682a7271Devang Patel    // What if InnerLoop was modified by other passes ?
25854959d6cf68a9b575c98c074babe9867682a7271Devang Patel    CurAST->add(*InnerAST);
2592e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  }
26054959d6cf68a9b575c98c074babe9867682a7271Devang Patel
261e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  CurLoop = L;
262e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
26399a57216a935a512c418032f590a4660bad9d846Chris Lattner  // Get the preheader block to move instructions into...
26499a57216a935a512c418032f590a4660bad9d846Chris Lattner  Preheader = L->getLoopPreheader();
26599a57216a935a512c418032f590a4660bad9d846Chris Lattner  assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
26699a57216a935a512c418032f590a4660bad9d846Chris Lattner
2672e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Loop over the body of this loop, looking for calls, invokes, and stores.
2680252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner  // Because subloops have already been incorporated into AST, we skip blocks in
2692e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // subloops.
2702e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  //
2719b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman  for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
2729b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman       I != E; ++I) {
2739b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman    BasicBlock *BB = *I;
2749b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman    if (LI->getLoopFor(BB) == L)        // Ignore blocks in subloops...
2759b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman      CurAST->add(*BB);                 // Incorporate the specified basic block
2769b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman  }
2772e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
278e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // We want to visit all of the instructions in this loop... that are not parts
279e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // of our subloops (they have already had their invariants hoisted out of
280e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // their loop, into this loop, so there is no need to process the BODIES of
281e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // the subloops).
282e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  //
283952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  // Traverse the body of the loop in depth first order on the dominator tree so
284952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  // that we are guaranteed to see definitions before we see uses.  This allows
285af5cbc82bb6410129425c98bbfc1ffc4c3d0f411Nick Lewycky  // us to sink instructions in one pass, without iteration.  After sinking
286e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  // instructions, we perform another pass to hoist them out of the loop.
287952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  //
2883a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  SinkRegion(DT->getNode(L->getHeader()));
2893a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  HoistRegion(DT->getNode(L->getHeader()));
290e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
2912e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Now that all loop invariants have been removed from the loop, promote any
2922e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // memory references to scalars that we can...
2932e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  if (!DisablePromotion)
2942e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    PromoteValuesInLoop();
2952e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
296e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // Clear out loops state information for the next iteration
297e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  CurLoop = 0;
29899a57216a935a512c418032f590a4660bad9d846Chris Lattner  Preheader = 0;
29954959d6cf68a9b575c98c074babe9867682a7271Devang Patel
30054959d6cf68a9b575c98c074babe9867682a7271Devang Patel  LoopToAliasMap[L] = CurAST;
30154959d6cf68a9b575c98c074babe9867682a7271Devang Patel  return Changed;
302e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner}
303e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
304e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner/// SinkRegion - Walk the specified region of the CFG (defined by all blocks
305e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner/// dominated by the specified block, and that are in the current loop) in
3063a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson/// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
307e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner/// uses before definitions, allowing us to sink a loop body in one pass without
308e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner/// iteration.
309e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner///
31026042420d642e810f5cdfb2da6156b74aaf80945Devang Patelvoid LICM::SinkRegion(DomTreeNode *N) {
3113a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  assert(N != 0 && "Null dominator tree node?");
3123a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  BasicBlock *BB = N->getBlock();
313e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
314e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  // If this subregion is not in the top level loop at all, exit.
315e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  if (!CurLoop->contains(BB)) return;
316e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
317e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  // We are processing blocks in reverse dfo, so process children first...
31826042420d642e810f5cdfb2da6156b74aaf80945Devang Patel  const std::vector<DomTreeNode*> &Children = N->getChildren();
319e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  for (unsigned i = 0, e = Children.size(); i != e; ++i)
320e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    SinkRegion(Children[i]);
321e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
322e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  // Only need to process the contents of this block if it is not part of a
323e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  // subloop (which would already have been processed).
324e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  if (inSubLoop(BB)) return;
325e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
326a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner  for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
327a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner    Instruction &I = *--II;
328fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
329e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    // Check to see if we can sink this instruction to the exit blocks
330e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    // of the loop.  We can do this if the all users of the instruction are
331e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    // outside of the loop.  In this case, it doesn't even matter if the
332e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    // operands of the instruction are loop invariant.
333e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner    //
33470ac2dcb841dc62f08e16f0b0e2cefbf01baa4c5Chris Lattner    if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
335a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner      ++II;
336e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      sink(I);
337a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner    }
338e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner  }
339e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner}
340e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
341e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner
342952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
343952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner/// dominated by the specified block, and that are in the current loop) in depth
3443a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson/// first order w.r.t the DominatorTree.  This allows us to visit definitions
345952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner/// before uses, allowing us to hoist a loop body in one pass without iteration.
346952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner///
34726042420d642e810f5cdfb2da6156b74aaf80945Devang Patelvoid LICM::HoistRegion(DomTreeNode *N) {
3483a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  assert(N != 0 && "Null dominator tree node?");
3493a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  BasicBlock *BB = N->getBlock();
350952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
351b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner  // If this subregion is not in the top level loop at all, exit.
352ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  if (!CurLoop->contains(BB)) return;
353952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
354a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // Only need to process the contents of this block if it is not part of a
355a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // subloop (which would already have been processed).
356ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  if (!inSubLoop(BB))
357a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
358a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      Instruction &I = *II++;
359fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
360e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      // Try hoisting the instruction out to the preheader.  We can only do this
361e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      // if all of the operands of the instruction are loop invariant and if it
362e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      // is safe to hoist the instruction.
363e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner      //
364fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
365e4365b2e8c79f9b2d564f31fdcc0568da8e5d60fChris Lattner          isSafeToExecuteUnconditionally(I))
3663c80a51cfd5e7187439ce4c051da77ee46e0ff9aChris Lattner        hoist(I);
367a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      }
368952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
36926042420d642e810f5cdfb2da6156b74aaf80945Devang Patel  const std::vector<DomTreeNode*> &Children = N->getChildren();
370952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  for (unsigned i = 0, e = Children.size(); i != e; ++i)
37156b7ee20dad7160a117ea0d102fc5432074ce2d0Chris Lattner    HoistRegion(Children[i]);
372952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner}
373952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
374a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
375a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// instruction.
376a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner///
377a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnerbool LICM::canSinkOrHoistInst(Instruction &I) {
378ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  // Loads have extra constraints we have to verify before we can hoist them.
379ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
380ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner    if (LI->isVolatile())
381ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner      return false;        // Don't hoist volatile loads!
382ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner
383967948b4e25cae3de68f38fddaa75d838e676decChris Lattner    // Loads from constant memory are always safe to move, even if they end up
384967948b4e25cae3de68f38fddaa75d838e676decChris Lattner    // in the same alias set as something that ends up being modified.
3853eee6542f5c65dce299361fa5435340513cf3fe4Dan Gohman    if (EnableLICMConstantMotion &&
3863eee6542f5c65dce299361fa5435340513cf3fe4Dan Gohman        AA->pointsToConstantMemory(LI->getOperand(0)))
387967948b4e25cae3de68f38fddaa75d838e676decChris Lattner      return true;
388967948b4e25cae3de68f38fddaa75d838e676decChris Lattner
389ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner    // Don't hoist loads which have may-aliased stores in loop.
390f3e1d6977ee5fb6b66df314d65e28e2c35d6e244Chris Lattner    unsigned Size = 0;
391f3e1d6977ee5fb6b66df314d65e28e2c35d6e244Chris Lattner    if (LI->getType()->isSized())
392514ab348fddcdffa8367685dc608b2f8d5de986dDuncan Sands      Size = AA->getTargetData().getTypeStoreSize(LI->getType());
393f3e1d6977ee5fb6b66df314d65e28e2c35d6e244Chris Lattner    return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
394118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner  } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
395118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    // Handle obvious cases efficiently.
396dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands    AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
397dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands    if (Behavior == AliasAnalysis::DoesNotAccessMemory)
398dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      return true;
399dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands    else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
400dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      // If this call only reads from memory and there are no writes to memory
401dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      // in the loop, we can hoist or sink the call as appropriate.
402dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      bool FoundMod = false;
403dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
404dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands           I != E; ++I) {
405dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands        AliasSet &AS = *I;
406dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands        if (!AS.isForwardingAliasSet() && AS.isMod()) {
407dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands          FoundMod = true;
408dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands          break;
409118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner        }
410118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner      }
411dff6710717b159f089c76a07eda074eb6347eb92Duncan Sands      if (!FoundMod) return true;
412118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    }
413118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner
414118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    // FIXME: This should use mod/ref information to see if we can hoist or sink
415118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    // the call.
416fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
417118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    return false;
418ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  }
419ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner
4203da59db637a887474c1b1346c1f3ccf53b6c4663Reid Spencer  // Otherwise these instructions are hoistable/sinkable
421832254e1c2387c0cbeb0a820b8315fbe85cb003aReid Spencer  return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
422d8af90c1da64b81a7aa167b5adcc1e81b0741252Dan Gohman         isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
423d8af90c1da64b81a7aa167b5adcc1e81b0741252Dan Gohman         isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
424d8af90c1da64b81a7aa167b5adcc1e81b0741252Dan Gohman         isa<ShuffleVectorInst>(I);
425a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner}
426a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
427a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// isNotUsedInLoop - Return true if the only users of this instruction are
428a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// outside of the loop.  If this is true, we can sink the instruction to the
429a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// exit blocks of the loop.
430a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner///
431a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnerbool LICM::isNotUsedInLoop(Instruction &I) {
432ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner  for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
433ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner    Instruction *User = cast<Instruction>(*UI);
434ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner    if (PHINode *PN = dyn_cast<PHINode>(User)) {
435ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner      // PHI node uses occur in predecessor blocks!
436ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
437ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner        if (PN->getIncomingValue(i) == &I)
438ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner          if (CurLoop->contains(PN->getIncomingBlock(i)))
439ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner            return false;
440ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner    } else if (CurLoop->contains(User->getParent())) {
441a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      return false;
442ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner    }
443ea9403f2aa078e840a49792d906390395f0cd2f6Chris Lattner  }
444a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  return true;
445a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner}
446a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
447a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
448a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// isLoopInvariantInst - Return true if all operands of this instruction are
449a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// loop invariant.  We also filter out non-hoistable instructions here just for
450a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// efficiency.
451a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner///
452a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnerbool LICM::isLoopInvariantInst(Instruction &I) {
453a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // The instruction is loop invariant if all of its operands are loop-invariant
454a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
4553280f7bd557250a448eb56edbddfc90c94a406e6Chris Lattner    if (!CurLoop->isLoopInvariant(I.getOperand(i)))
456a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      return false;
457a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
458ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  // If we got this far, the instruction is loop invariant!
459ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  return true;
460ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner}
461ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner
462a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// sink - When an instruction is found to only be used outside of the loop,
463a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner/// this function moves it to the exit blocks and patches up SSA form as needed.
464a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner/// This method is guaranteed to remove the original instruction from its
465a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner/// position, and may either delete it or move it to outside of the loop.
466a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner///
467a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnervoid LICM::sink(Instruction &I) {
468b7427031372337e6d67f9573ec6c722ab5ea913eBill Wendling  DOUT << "LICM sinking instruction: " << I;
469a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
470b7211a2ce13a0365e0e1dd2f27adda2ee3d1288bDevang Patel  SmallVector<BasicBlock*, 8> ExitBlocks;
4715fa802fe279f10f402e039bc931aa57c0e424bf5Chris Lattner  CurLoop->getExitBlocks(ExitBlocks);
472df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner
473df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner  if (isa<LoadInst>(I)) ++NumMovedLoads;
474118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner  else if (isa<CallInst>(I)) ++NumMovedCalls;
475df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner  ++NumSunk;
476df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner  Changed = true;
477df45bd3803ae0965a83cd1f30ee051b9f43e73ddChris Lattner
478e922c0201916e0b980ab3cfe91e1413e68d55647Owen Anderson  LLVMContext &Context = I.getContext();
479e922c0201916e0b980ab3cfe91e1413e68d55647Owen Anderson
480a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // The case where there is only a single exit node of this loop is common
481a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // enough that we handle it as a special (more efficient) case.  It is more
482a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // efficient to handle because there are no PHI nodes that need to be placed.
483a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  if (ExitBlocks.size() == 1) {
484a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
485a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // Instruction is not used, just delete it.
4862741c971044d2165be572749b94398043caccfebChris Lattner      CurAST->deleteValue(&I);
48792f7365740e9a116c59a8d33e636ebf6e4699301Chris Lattner      if (!I.use_empty())  // If I has users in unreachable blocks, eliminate.
488e922c0201916e0b980ab3cfe91e1413e68d55647Owen Anderson        I.replaceAllUsesWith(Context.getUndef(I.getType()));
4893c80a51cfd5e7187439ce4c051da77ee46e0ff9aChris Lattner      I.eraseFromParent();
490a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    } else {
491a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // Move the instruction to the start of the exit block, after any PHI
492a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // nodes in it.
4933c80a51cfd5e7187439ce4c051da77ee46e0ff9aChris Lattner      I.removeFromParent();
494fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
49502dea8b39f3acad5de1df36273444d149145e7fcDan Gohman      BasicBlock::iterator InsertPt = ExitBlocks[0]->getFirstNonPHI();
496a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      ExitBlocks[0]->getInstList().insert(InsertPt, &I);
497a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    }
498303595942502f17c087fa28874c2b89117148c45Dan Gohman  } else if (ExitBlocks.empty()) {
499a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // The instruction is actually dead if there ARE NO exit blocks.
5002741c971044d2165be572749b94398043caccfebChris Lattner    CurAST->deleteValue(&I);
50192f7365740e9a116c59a8d33e636ebf6e4699301Chris Lattner    if (!I.use_empty())  // If I has users in unreachable blocks, eliminate.
502e922c0201916e0b980ab3cfe91e1413e68d55647Owen Anderson      I.replaceAllUsesWith(Context.getUndef(I.getType()));
5033c80a51cfd5e7187439ce4c051da77ee46e0ff9aChris Lattner    I.eraseFromParent();
504a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  } else {
505a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
506a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // do all of the hard work of inserting PHI nodes as necessary.  We convert
507a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // the value into a stack object to get it to do this.
508a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
509a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // Firstly, we create a stack object to hold the value...
510eaa243039b6a83f8915f4f96ced58fabb520c851Chris Lattner    AllocaInst *AI = 0;
511a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
512e7ae1a9dee1b023dbd5f7d6d1fbdb165fbbcb26cDevang Patel    if (I.getType() != Type::VoidTy) {
51350dead06ffc107edb7e84857baaeeb09039c631cOwen Anderson      AI = new AllocaInst(I.getType(), 0, I.getName(),
514ecb7a77885b174cf4d001a9b48533b3979e7810dDan Gohman                          I.getParent()->getParent()->getEntryBlock().begin());
515e7ae1a9dee1b023dbd5f7d6d1fbdb165fbbcb26cDevang Patel      CurAST->add(AI);
516e7ae1a9dee1b023dbd5f7d6d1fbdb165fbbcb26cDevang Patel    }
517fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
518a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // Secondly, insert load instructions for each use of the instruction
519a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // outside of the loop.
520a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    while (!I.use_empty()) {
521a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      Instruction *U = cast<Instruction>(I.use_back());
522a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
523a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // If the user is a PHI Node, we actually have to insert load instructions
524a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // in all predecessor blocks, not in the PHI block itself!
525a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      if (PHINode *UPN = dyn_cast<PHINode>(U)) {
526a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // Only insert into each predecessor once, so that we don't have
527a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // different incoming values from the same block!
528a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        std::map<BasicBlock*, Value*> InsertedBlocks;
529a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
530a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          if (UPN->getIncomingValue(i) == &I) {
531a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            BasicBlock *Pred = UPN->getIncomingBlock(i);
532a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            Value *&PredVal = InsertedBlocks[Pred];
533a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            if (!PredVal) {
534a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner              // Insert a new load instruction right before the terminator in
535a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner              // the predecessor block.
536a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner              PredVal = new LoadInst(AI, "", Pred->getTerminator());
537e7ae1a9dee1b023dbd5f7d6d1fbdb165fbbcb26cDevang Patel              CurAST->add(cast<LoadInst>(PredVal));
538a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            }
539a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
540a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            UPN->setIncomingValue(i, PredVal);
541a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          }
542a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
543a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      } else {
544a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        LoadInst *L = new LoadInst(AI, "", U);
545a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        U->replaceUsesOfWith(&I, L);
546e7ae1a9dee1b023dbd5f7d6d1fbdb165fbbcb26cDevang Patel        CurAST->add(L);
547a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      }
548a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    }
549a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
550a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // Thirdly, insert a copy of the instruction in each exit block of the loop
551a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // that is dominated by the instruction, storing the result into the memory
552a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // location.  Be careful not to insert the instruction into any particular
553a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // basic block more than once.
554a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    std::set<BasicBlock*> InsertedBlocks;
555a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    BasicBlock *InstOrigBB = I.getParent();
556a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
557a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
558a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      BasicBlock *ExitBlock = ExitBlocks[i];
559a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
560a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
561a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // If we haven't already processed this exit block, do so now.
562e3cfe8d563fa06b274587aa38b1359ff707f33deChris Lattner        if (InsertedBlocks.insert(ExitBlock).second) {
563a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          // Insert the code after the last PHI node...
56402dea8b39f3acad5de1df36273444d149145e7fcDan Gohman          BasicBlock::iterator InsertPt = ExitBlock->getFirstNonPHI();
565fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
566a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          // If this is the first exit block processed, just move the original
567a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          // instruction, otherwise clone the original instruction and insert
568a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          // the copy.
569a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          Instruction *New;
5707d3ced934f1bb2c6845676c7333ef879d5219e88Chris Lattner          if (InsertedBlocks.size() == 1) {
5713c80a51cfd5e7187439ce4c051da77ee46e0ff9aChris Lattner            I.removeFromParent();
572a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            ExitBlock->getInstList().insert(InsertPt, &I);
573a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            New = &I;
574a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          } else {
575e922c0201916e0b980ab3cfe91e1413e68d55647Owen Anderson            New = I.clone(Context);
57670ac2dcb841dc62f08e16f0b0e2cefbf01baa4c5Chris Lattner            CurAST->copyValue(&I, New);
577eaa243039b6a83f8915f4f96ced58fabb520c851Chris Lattner            if (!I.getName().empty())
578eaa243039b6a83f8915f4f96ced58fabb520c851Chris Lattner              New->setName(I.getName()+".le");
579a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            ExitBlock->getInstList().insert(InsertPt, New);
580a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          }
581fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
582a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          // Now that we have inserted the instruction, store it into the alloca
583eaa243039b6a83f8915f4f96ced58fabb520c851Chris Lattner          if (AI) new StoreInst(New, AI, InsertPt);
584a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        }
585a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      }
586a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    }
587a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner
588a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner    // If the instruction doesn't dominate any exit blocks, it must be dead.
589a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner    if (InsertedBlocks.empty()) {
5902741c971044d2165be572749b94398043caccfebChris Lattner      CurAST->deleteValue(&I);
5913c80a51cfd5e7187439ce4c051da77ee46e0ff9aChris Lattner      I.eraseFromParent();
592a3df8a964aa9d0d171fd4f6e491c7d1cf9dee500Chris Lattner    }
593fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
594a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // Finally, promote the fine value to SSA form.
595eaa243039b6a83f8915f4f96ced58fabb520c851Chris Lattner    if (AI) {
596eaa243039b6a83f8915f4f96ced58fabb520c851Chris Lattner      std::vector<AllocaInst*> Allocas;
597eaa243039b6a83f8915f4f96ced58fabb520c851Chris Lattner      Allocas.push_back(AI);
5980a205a459884ec745df1c529396dd921f029dafdOwen Anderson      PromoteMemToReg(Allocas, *DT, *DF, Context, CurAST);
599eaa243039b6a83f8915f4f96ced58fabb520c851Chris Lattner    }
600a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  }
601a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner}
602952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
60394170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner/// hoist - When an instruction is found to only use loop invariant operands
60494170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner/// that is safe to hoist, this instruction is called to do the dirty work.
60594170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner///
606a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnervoid LICM::hoist(Instruction &I) {
607b7427031372337e6d67f9573ec6c722ab5ea913eBill Wendling  DOUT << "LICM hoisting to " << Preheader->getName() << ": " << I;
608ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner
60999a57216a935a512c418032f590a4660bad9d846Chris Lattner  // Remove the instruction from its current basic block... but don't delete the
61099a57216a935a512c418032f590a4660bad9d846Chris Lattner  // instruction.
6113c80a51cfd5e7187439ce4c051da77ee46e0ff9aChris Lattner  I.removeFromParent();
612e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
6139646e6b6af1f924f9366a2bffc6dde102f84d231Chris Lattner  // Insert the new node in Preheader, before the terminator.
614a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  Preheader->getInstList().insert(Preheader->getTerminator(), &I);
615fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
616a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  if (isa<LoadInst>(I)) ++NumMovedLoads;
617118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner  else if (isa<CallInst>(I)) ++NumMovedCalls;
6189646e6b6af1f924f9366a2bffc6dde102f84d231Chris Lattner  ++NumHoisted;
619e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  Changed = true;
620e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner}
621e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
622a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
623a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// not a trapping instruction or if it is a trapping instruction and is
624a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// guaranteed to execute.
6259966c03aad031f738718bed3bc00371e358beb5dTanya Lattner///
626a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnerbool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
62792094b4d928119eceac1484331acffe950f4651cChris Lattner  // If it is not a trapping instruction, it is always safe to hoist.
6280b79a7727d68a507837e827803859424cf3d997bEli Friedman  if (Inst.isSafeToSpeculativelyExecute())
6290b79a7727d68a507837e827803859424cf3d997bEli Friedman    return true;
630fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
63192094b4d928119eceac1484331acffe950f4651cChris Lattner  // Otherwise we have to check to make sure that the instruction dominates all
63292094b4d928119eceac1484331acffe950f4651cChris Lattner  // of the exit blocks.  If it doesn't, then there is a path out of the loop
63392094b4d928119eceac1484331acffe950f4651cChris Lattner  // which does not execute this instruction, so we can't hoist it.
63492094b4d928119eceac1484331acffe950f4651cChris Lattner
63592094b4d928119eceac1484331acffe950f4651cChris Lattner  // If the instruction is in the header block for the loop (which is very
63692094b4d928119eceac1484331acffe950f4651cChris Lattner  // common), it is always guaranteed to dominate the exit blocks.  Since this
63792094b4d928119eceac1484331acffe950f4651cChris Lattner  // is a common case, and can save some work, check it now.
638a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  if (Inst.getParent() == CurLoop->getHeader())
63992094b4d928119eceac1484331acffe950f4651cChris Lattner    return true;
64092094b4d928119eceac1484331acffe950f4651cChris Lattner
64192094b4d928119eceac1484331acffe950f4651cChris Lattner  // Get the exit blocks for the current loop.
642b7211a2ce13a0365e0e1dd2f27adda2ee3d1288bDevang Patel  SmallVector<BasicBlock*, 8> ExitBlocks;
6435fa802fe279f10f402e039bc931aa57c0e424bf5Chris Lattner  CurLoop->getExitBlocks(ExitBlocks);
6449966c03aad031f738718bed3bc00371e358beb5dTanya Lattner
6453a2b58f3adc5e9f9bffac7ce193f0570aa5a721fOwen Anderson  // For each exit block, get the DT node and walk up the DT until the
64692094b4d928119eceac1484331acffe950f4651cChris Lattner  // instruction's basic block is found or we exit the loop.
647a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
648a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
649a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      return false;
650fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
6519966c03aad031f738718bed3bc00371e358beb5dTanya Lattner  return true;
6529966c03aad031f738718bed3bc00371e358beb5dTanya Lattner}
6539966c03aad031f738718bed3bc00371e358beb5dTanya Lattner
654eb53ae4f2dc39e75e725b21b52d77d29cf1c11c9Chris Lattner
6552e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
6562e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// stores out of the loop and moving loads to before the loop.  We do this by
6572e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// looping over the stores in the loop, looking for stores to Must pointers
6582e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// which are loop invariant.  We promote these memory locations to use allocas
6592e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// instead.  These allocas can easily be raised to register values by the
6602e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// PromoteMem2Reg functionality.
6612e6e741b737960ecd0b68610875050019aac0f07Chris Lattner///
6622e6e741b737960ecd0b68610875050019aac0f07Chris Lattnervoid LICM::PromoteValuesInLoop() {
6632e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // PromotedValues - List of values that are promoted out of the loop.  Each
664065a616adad624152618b1b0084ff074e5b03bbbChris Lattner  // value has an alloca instruction for it, and a canonical version of the
6652e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // pointer.
6662e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
6672e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
6682e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
669fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner  FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
670fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner  if (ValueToAllocaMap.empty()) return;   // If there are values to promote.
6712e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
6722e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  Changed = true;
6732e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  NumPromoted += PromotedValues.size();
6742e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
675fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner  std::vector<Value*> PointerValueNumbers;
676fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner
6772e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Emit a copy from the value into the alloca'd value in the loop preheader
6782e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  TerminatorInst *LoopPredInst = Preheader->getTerminator();
6792e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
680fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner    Value *Ptr = PromotedValues[i].second;
681fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner
682fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner    // If we are promoting a pointer value, update alias information for the
683fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner    // inserted load.
684fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner    Value *LoadValue = 0;
685fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner    if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
686fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner      // Locate a load or store through the pointer, and assign the same value
687fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner      // to LI as we are loading or storing.  Since we know that the value is
688fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner      // stored in this loop, this will always succeed.
689fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner      for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
690fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner           UI != E; ++UI)
691fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner        if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
692fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner          LoadValue = LI;
693fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner          break;
694fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner        } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
695bdacd879578943efc98b75639cb8e7b4aab037f9Chris Lattner          if (SI->getOperand(1) == Ptr) {
696fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner            LoadValue = SI->getOperand(0);
697fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner            break;
698fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner          }
699fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner        }
700fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner      assert(LoadValue && "No store through the pointer found!");
701fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner      PointerValueNumbers.push_back(LoadValue);  // Remember this for later.
702fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner    }
703fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner
704fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner    // Load from the memory we are promoting.
705fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner    LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
706fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner
707fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner    if (LoadValue) CurAST->copyValue(LoadValue, LI);
708fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner
709fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner    // Store into the temporary alloca.
7102e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
7112e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  }
712fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
7132e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Scan the basic blocks in the loop, replacing uses of our pointers with
7140ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  // uses of the allocas in question.
7152e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  //
7169b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman  for (Loop::block_iterator I = CurLoop->block_begin(),
7179b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman         E = CurLoop->block_end(); I != E; ++I) {
7189b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman    BasicBlock *BB = *I;
7192e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    // Rewrite all loads and stores in the block of the pointer...
7209b78763fce4cb418e7a2e672efb84bac25559b79Dan Gohman    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
721e408e25132b8de8c757db1e3ddcd70432dfeb24dChris Lattner      if (LoadInst *L = dyn_cast<LoadInst>(II)) {
7222e6e741b737960ecd0b68610875050019aac0f07Chris Lattner        std::map<Value*, AllocaInst*>::iterator
7232e6e741b737960ecd0b68610875050019aac0f07Chris Lattner          I = ValueToAllocaMap.find(L->getOperand(0));
7242e6e741b737960ecd0b68610875050019aac0f07Chris Lattner        if (I != ValueToAllocaMap.end())
7252e6e741b737960ecd0b68610875050019aac0f07Chris Lattner          L->setOperand(0, I->second);    // Rewrite load instruction...
726e408e25132b8de8c757db1e3ddcd70432dfeb24dChris Lattner      } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
7272e6e741b737960ecd0b68610875050019aac0f07Chris Lattner        std::map<Value*, AllocaInst*>::iterator
7282e6e741b737960ecd0b68610875050019aac0f07Chris Lattner          I = ValueToAllocaMap.find(S->getOperand(1));
7292e6e741b737960ecd0b68610875050019aac0f07Chris Lattner        if (I != ValueToAllocaMap.end())
7302e6e741b737960ecd0b68610875050019aac0f07Chris Lattner          S->setOperand(1, I->second);    // Rewrite store instruction...
7312e6e741b737960ecd0b68610875050019aac0f07Chris Lattner      }
7322e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    }
7330ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  }
7342e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
7350ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  // Now that the body of the loop uses the allocas instead of the original
7360ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  // memory locations, insert code to copy the alloca value back into the
7370ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  // original memory location on all exits from the loop.  Note that we only
7380ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  // want to insert one copy of the code in each exit block, though the loop may
7390ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  // exit to the same block more than once.
7400ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  //
74119d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner  SmallPtrSet<BasicBlock*, 16> ProcessedBlocks;
7420ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner
743b7211a2ce13a0365e0e1dd2f27adda2ee3d1288bDevang Patel  SmallVector<BasicBlock*, 8> ExitBlocks;
7445fa802fe279f10f402e039bc931aa57c0e424bf5Chris Lattner  CurLoop->getExitBlocks(ExitBlocks);
74519d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
74619d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    if (!ProcessedBlocks.insert(ExitBlocks[i]))
74719d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner      continue;
74819d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner
74919d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    // Copy all of the allocas into their memory locations.
75002dea8b39f3acad5de1df36273444d149145e7fcDan Gohman    BasicBlock::iterator BI = ExitBlocks[i]->getFirstNonPHI();
75119d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    Instruction *InsertPos = BI;
75219d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    unsigned PVN = 0;
75319d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
75419d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner      // Load from the alloca.
75519d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner      LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
75619d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner
75719d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner      // If this is a pointer type, update alias info appropriately.
75819d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner      if (isa<PointerType>(LI->getType()))
75919d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner        CurAST->copyValue(PointerValueNumbers[PVN++], LI);
76019d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner
76119d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner      // Store into the memory we promoted.
76219d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner      new StoreInst(LI, PromotedValues[i].second, InsertPos);
7630ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner    }
76419d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner  }
7652e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
7662e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Now that we have done the deed, use the mem2reg functionality to promote
767fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner  // all of the new allocas we just created into real SSA registers.
7682e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  //
7692e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  std::vector<AllocaInst*> PromotedAllocas;
7702e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  PromotedAllocas.reserve(PromotedValues.size());
7712e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
7722e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    PromotedAllocas.push_back(PromotedValues[i].first);
773e922c0201916e0b980ab3cfe91e1413e68d55647Owen Anderson  PromoteMemToReg(PromotedAllocas, *DT, *DF, Preheader->getContext(), CurAST);
7742e6e741b737960ecd0b68610875050019aac0f07Chris Lattner}
7752e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
776fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner/// FindPromotableValuesInLoop - Check the current loop for stores to definite
777f2038b1d9325b23e73a20b57fcb3508f4dda1817Devang Patel/// pointers, which are not loaded and stored through may aliases and are safe
778f2038b1d9325b23e73a20b57fcb3508f4dda1817Devang Patel/// for promotion.  If these are found, create an alloca for the value, add it
779f2038b1d9325b23e73a20b57fcb3508f4dda1817Devang Patel/// to the PromotedValues list, and keep track of the mapping from value to
780f2038b1d9325b23e73a20b57fcb3508f4dda1817Devang Patel/// alloca.
781fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattnervoid LICM::FindPromotableValuesInLoop(
7822e6e741b737960ecd0b68610875050019aac0f07Chris Lattner                   std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
7832e6e741b737960ecd0b68610875050019aac0f07Chris Lattner                             std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
7842e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
7852e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
786fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner  // Loop over all of the alias sets in the tracker object.
7870252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner  for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
7880252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner       I != E; ++I) {
7890252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner    AliasSet &AS = *I;
7900252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner    // We can promote this alias set if it has a store, if it is a "Must" alias
791fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner    // set, if the pointer is loop invariant, and if we are not eliminating any
792118dd0ce3d8e4b0a945afc95c9538d5005abacdeChris Lattner    // volatile loads or stores.
79329d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
794d7168ddb116c2e9aa1f8325ae887eb63d6003037Chris Lattner        AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
79529d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner      continue;
79629d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner
79729d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    assert(!AS.empty() &&
79829d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner           "Must alias set should have at least one pointer element in it!");
799d7168ddb116c2e9aa1f8325ae887eb63d6003037Chris Lattner    Value *V = AS.begin()->getValue();
80029d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner
80129d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    // Check that all of the pointers in the alias set have the same type.  We
80229d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    // cannot (yet) promote a memory location that is loaded and stored in
80329d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    // different sizes.
80429d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    {
8050252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      bool PointerOk = true;
8060252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
807d7168ddb116c2e9aa1f8325ae887eb63d6003037Chris Lattner        if (V->getType() != I->getValue()->getType()) {
8080252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner          PointerOk = false;
8090252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner          break;
8102e6e741b737960ecd0b68610875050019aac0f07Chris Lattner        }
81129d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner      if (!PointerOk)
81229d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner        continue;
81329d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    }
8140252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner
81519d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    // It isn't safe to promote a load/store from the loop if the load/store is
81619d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    // conditional.  For example, turning:
81719d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    //
81819d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    //    for () { if (c) *P += 1; }
81919d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    //
82019d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    // into:
82119d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    //
82219d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
82319d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    //
82419d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    // is not safe, because *P may only be valid to access if 'c' is true.
82519d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    //
82619d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    // It is safe to promote P if all uses are direct load/stores and if at
82719d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    // least one is guaranteed to be executed.
82819d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    bool GuaranteedToExecute = false;
82919d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    bool InvalidInst = false;
83019d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
83119d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner         UI != UE; ++UI) {
83219d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner      // Ignore instructions not in this loop.
83329d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner      Instruction *Use = dyn_cast<Instruction>(*UI);
83429d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner      if (!Use || !CurLoop->contains(Use->getParent()))
83529d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner        continue;
836bc2265abe1d1b830995bb2f6322409bc7d7c5740Devang Patel
83719d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner      if (!isa<LoadInst>(Use) && !isa<StoreInst>(Use)) {
83819d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner        InvalidInst = true;
83929d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner        break;
84019d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner      }
84119d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner
84219d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner      if (!GuaranteedToExecute)
84319d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner        GuaranteedToExecute = isSafeToExecuteUnconditionally(*Use);
84429d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    }
845bc2265abe1d1b830995bb2f6322409bc7d7c5740Devang Patel
84619d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    // If there is an non-load/store instruction in the loop, we can't promote
84719d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    // it.  If there isn't a guaranteed-to-execute instruction, we can't
84819d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    // promote.
84919d9d4364e514f316f8757b577bb8bb33c22dbfcChris Lattner    if (InvalidInst || !GuaranteedToExecute)
85029d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner      continue;
85129d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner
85229d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    const Type *Ty = cast<PointerType>(V->getType())->getElementType();
85350dead06ffc107edb7e84857baaeeb09039c631cOwen Anderson    AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
85429d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    PromotedValues.push_back(std::make_pair(AI, V));
855fb3ee1930bfd0902f5fa3e6526775e3791e38d3cChris Lattner
85629d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    // Update the AST and alias analysis.
85729d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    CurAST->copyValue(V, AI);
858fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
85929d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
860d7168ddb116c2e9aa1f8325ae887eb63d6003037Chris Lattner      ValueToAllocaMap.insert(std::make_pair(I->getValue(), AI));
861fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
86229d929363d9b8a2c0d40c5d50fec022c736cb654Chris Lattner    DOUT << "LICM: Promoting value: " << *V << "\n";
8632e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  }
864f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner}
86591d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
86691d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel/// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
86791d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patelvoid LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
86891d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel  AliasSetTracker *AST = LoopToAliasMap[L];
86991d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel  if (!AST)
87091d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    return;
87191d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
87291d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel  AST->copyValue(From, To);
87391d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel}
87491d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
87591d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel/// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
87691d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel/// set.
87791d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patelvoid LICM::deleteAnalysisValue(Value *V, Loop *L) {
87891d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel  AliasSetTracker *AST = LoopToAliasMap[L];
87991d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel  if (!AST)
88091d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel    return;
88191d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel
88291d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel  AST->deleteValue(V);
88391d22c8b1ec2ad8f2f29804b729473ccf720fb3eDevang Patel}
884