LICM.cpp revision 0ed2da9ac733c51ba004c067d3b552c1fa54613d
1e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//
3b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//                     The LLVM Compiler Infrastructure
4b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//
5b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell// This file was developed by the LLVM research group and is distributed under
6b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell// the University of Illinois Open Source License. See LICENSE.TXT for details.
7b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//
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
1492094b4d928119eceac1484331acffe950f4651cChris Lattner// live in registers.
1592094b4d928119eceac1484331acffe950f4651cChris Lattner//
1692094b4d928119eceac1484331acffe950f4651cChris Lattner// This pass uses alias analysis for two purposes:
172e6e741b737960ecd0b68610875050019aac0f07Chris Lattner//
182e6e741b737960ecd0b68610875050019aac0f07Chris Lattner//  1. Moving loop invariant loads out of loops.  If we can determine that a
192e6e741b737960ecd0b68610875050019aac0f07Chris Lattner//     load inside of a loop never aliases anything stored to, we can hoist it
2092094b4d928119eceac1484331acffe950f4651cChris Lattner//     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
34e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner#include "llvm/Transforms/Scalar.h"
352e6e741b737960ecd0b68610875050019aac0f07Chris Lattner#include "llvm/Transforms/Utils/PromoteMemToReg.h"
36e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner#include "llvm/Transforms/Utils/Local.h"
37e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner#include "llvm/Analysis/LoopInfo.h"
38f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner#include "llvm/Analysis/AliasAnalysis.h"
390252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner#include "llvm/Analysis/AliasSetTracker.h"
40952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner#include "llvm/Analysis/Dominators.h"
412e6e741b737960ecd0b68610875050019aac0f07Chris Lattner#include "llvm/Instructions.h"
422e6e741b737960ecd0b68610875050019aac0f07Chris Lattner#include "llvm/DerivedTypes.h"
43fb743a937f6856e3ab1f8ed599677038750a550eChris Lattner#include "llvm/Target/TargetData.h"
442e6e741b737960ecd0b68610875050019aac0f07Chris Lattner#include "llvm/Support/CFG.h"
452e6e741b737960ecd0b68610875050019aac0f07Chris Lattner#include "Support/CommandLine.h"
466806f5614d2ec260fda954c951d33f58e77ed610Chris Lattner#include "Support/Debug.h"
476806f5614d2ec260fda954c951d33f58e77ed610Chris Lattner#include "Support/Statistic.h"
48b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner#include "llvm/Assembly/Writer.h"
49e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner#include <algorithm>
5092094b4d928119eceac1484331acffe950f4651cChris Lattnerusing namespace llvm;
51d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke
52e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattnernamespace {
534a650af59912110a246c0a041bff38c92f0e56a2Chris Lattner  cl::opt<bool>
544a650af59912110a246c0a041bff38c92f0e56a2Chris Lattner  DisablePromotion("disable-licm-promotion", cl::Hidden,
554a650af59912110a246c0a041bff38c92f0e56a2Chris Lattner                   cl::desc("Disable memory promotion in LICM pass"));
562e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
57a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  Statistic<> NumSunk("licm", "Number of instructions sunk out of loop");
58a92f696b74a99325026ebbdbffd2a44317e0c10bChris Lattner  Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
59a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  Statistic<> NumMovedLoads("licm", "Number of load insts hoisted or sunk");
604a650af59912110a246c0a041bff38c92f0e56a2Chris Lattner  Statistic<> NumPromoted("licm",
614a650af59912110a246c0a041bff38c92f0e56a2Chris Lattner                          "Number of memory locations promoted to registers");
622e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
63ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  struct LICM : public FunctionPass {
647e70829632f82de15db187845666aaca6e04b792Chris Lattner    virtual bool runOnFunction(Function &F);
65e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
6694170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// This transformation requires natural loop information & requires that
6794170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// loop preheaders be inserted into the CFG...
6894170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    ///
69e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
70cb2610ea037a17115ef3a01a6bdaab4e3cfdca27Chris Lattner      AU.setPreservesCFG();
7198bf436e2e2ab463d79c54a42a46b12028905330Chris Lattner      AU.addRequiredID(LoopSimplifyID);
725f0eb8da62308126d5b61e3eee5bee75b9dc5194Chris Lattner      AU.addRequired<LoopInfo>();
73952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner      AU.addRequired<DominatorTree>();
740252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      AU.addRequired<DominanceFrontier>();  // For scalar promotion (mem2reg)
75f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner      AU.addRequired<AliasAnalysis>();
76e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner    }
77e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
78e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  private:
7992094b4d928119eceac1484331acffe950f4651cChris Lattner    // Various analyses that we use...
802e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    AliasAnalysis *AA;       // Current AliasAnalysis information
8192094b4d928119eceac1484331acffe950f4651cChris Lattner    LoopInfo      *LI;       // Current LoopInfo
8292094b4d928119eceac1484331acffe950f4651cChris Lattner    DominatorTree *DT;       // Dominator Tree for the current Loop...
8343f820d1f7638656be2158efac7dd8f5b08b8b77Chris Lattner    DominanceFrontier *DF;   // Current Dominance Frontier
8492094b4d928119eceac1484331acffe950f4651cChris Lattner
8592094b4d928119eceac1484331acffe950f4651cChris Lattner    // State that is updated as we process loops
862e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    bool Changed;            // Set to true when we change anything.
872e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    BasicBlock *Preheader;   // The preheader block of the current loop...
882e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    Loop *CurLoop;           // The current loop we are working on...
890252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner    AliasSetTracker *CurAST; // AliasSet information for the current loop...
90e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
9194170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// visitLoop - Hoist expressions out of the specified loop...
9294170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    ///
930252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner    void visitLoop(Loop *L, AliasSetTracker &AST);
94e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
95952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    /// HoistRegion - Walk the specified region of the CFG (defined by all
96952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    /// blocks dominated by the specified block, and that are in the current
97952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
98cf00c4ab3ba308d45d98c5ccab87362cf802facbMisha Brukman    /// visit definitions before uses, allowing us to hoist a loop body in one
99952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    /// pass without iteration.
100952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    ///
101952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    void HoistRegion(DominatorTree::Node *N);
102952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
103b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner    /// inSubLoop - Little predicate that returns true if the specified basic
104b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner    /// block is in a subloop of the current one, not the current one itself.
10594170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    ///
106b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner    bool inSubLoop(BasicBlock *BB) {
107b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner      assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
108e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner      for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
109e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner        if (CurLoop->getSubLoops()[i]->contains(BB))
110b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner          return true;  // A subloop actually contains this block!
111b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner      return false;
112e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner    }
113e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
114a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
115a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// specified exit block of the loop is dominated by the specified block
116a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// that is in the body of the loop.  We use these constraints to
117a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// dramatically limit the amount of the dominator tree that needs to be
118a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// searched.
119a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
120a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner                                           BasicBlock *BlockInLoop) const {
121a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // If the block in the loop is the loop header, it must be dominated!
122a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      BasicBlock *LoopHeader = CurLoop->getHeader();
123a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      if (BlockInLoop == LoopHeader)
124a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        return true;
125a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
126a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      DominatorTree::Node *BlockInLoopNode = DT->getNode(BlockInLoop);
127a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      DominatorTree::Node *IDom            = DT->getNode(ExitBlock);
128a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
129a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // Because the exit block is not in the loop, we know we have to get _at
130a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // least_ it's immediate dominator.
131a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      do {
132a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // Get next Immediate Dominator.
133a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        IDom = IDom->getIDom();
134a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
135a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // If we have got to the header of the loop, then the instructions block
136a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // did not dominate the exit node, so we can't hoist it.
137a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        if (IDom->getBlock() == LoopHeader)
138a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          return false;
139a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
140a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      } while (IDom != BlockInLoopNode);
141a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
142a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      return true;
143a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    }
144a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
145a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// sink - When an instruction is found to only be used outside of the loop,
146a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// this function moves it to the exit blocks and patches up SSA form as
147a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// needed.
148a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    ///
149a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    void sink(Instruction &I);
150a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
15194170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// hoist - When an instruction is found to only use loop invariant operands
15294170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// that is safe to hoist, this instruction is called to do the dirty work.
15394170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    ///
1547e70829632f82de15db187845666aaca6e04b792Chris Lattner    void hoist(Instruction &I);
155e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
156a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
157a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// is not a trapping instruction or if it is a trapping instruction and is
158a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    /// guaranteed to execute.
1599966c03aad031f738718bed3bc00371e358beb5dTanya Lattner    ///
160a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    bool isSafeToExecuteUnconditionally(Instruction &I);
1619966c03aad031f738718bed3bc00371e358beb5dTanya Lattner
16294170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// pointerInvalidatedByLoop - Return true if the body of this loop may
16394170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// store into the memory location pointed to by V.
16494170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    ///
1652e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    bool pointerInvalidatedByLoop(Value *V) {
1660252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      // Check to see if any of the basic blocks in CurLoop invalidate *V.
1670252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      return CurAST->getAliasSetForPointer(V, 0).isMod();
1682e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    }
169f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner
17094170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    /// isLoopInvariant - Return true if the specified value is loop invariant
17194170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner    ///
172e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner    inline bool isLoopInvariant(Value *V) {
173e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner      if (Instruction *I = dyn_cast<Instruction>(V))
174e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner        return !CurLoop->contains(I->getParent());
175e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner      return true;  // All non-instructions are loop invariant
176e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner    }
177a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
178a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    bool canSinkOrHoistInst(Instruction &I);
179a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    bool isLoopInvariantInst(Instruction &I);
180a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    bool isNotUsedInLoop(Instruction &I);
181e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
1822e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
1832e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    /// to scalars as we can.
1842e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    ///
1852e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    void PromoteValuesInLoop();
1862e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
1872e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    /// findPromotableValuesInLoop - Check the current loop for stores to
188352361b409d16045e703d986aa7fd77295173ef3Misha Brukman    /// definite pointers, which are not loaded and stored through may aliases.
1892e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    /// If these are found, create an alloca for the value, add it to the
1902e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    /// PromotedValues list, and keep track of the mapping from value to
1912e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    /// alloca...
1922e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    ///
1932e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    void findPromotableValuesInLoop(
1942e6e741b737960ecd0b68610875050019aac0f07Chris Lattner                   std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
1952e6e741b737960ecd0b68610875050019aac0f07Chris Lattner                                    std::map<Value*, AllocaInst*> &Val2AlMap);
196e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  };
197f629309f74cf1a64aa7fd1cd5784fd7db9a8f59eChris Lattner
198a6275ccdf5e1aa208afde56c498e2b13e16442f0Chris Lattner  RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
199e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner}
200e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
20192094b4d928119eceac1484331acffe950f4651cChris LattnerFunctionPass *llvm::createLICMPass() { return new LICM(); }
202e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
20394170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner/// runOnFunction - For LICM, this simply traverses the loop structure of the
20494170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner/// function, hoisting expressions out of loops if possible.
20594170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner///
2067e70829632f82de15db187845666aaca6e04b792Chris Lattnerbool LICM::runOnFunction(Function &) {
2072e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  Changed = false;
208e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
2092e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Get our Loop and Alias Analysis information...
2102e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  LI = &getAnalysis<LoopInfo>();
211f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner  AA = &getAnalysis<AliasAnalysis>();
21243f820d1f7638656be2158efac7dd8f5b08b8b77Chris Lattner  DF = &getAnalysis<DominanceFrontier>();
21311a49a722f657294f38865019af51f82dc31c1c3Tanya Lattner  DT = &getAnalysis<DominatorTree>();
214f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner
2152e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Hoist expressions out of all of the top-level loops.
2162e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  const std::vector<Loop*> &TopLevelLoops = LI->getTopLevelLoops();
2172e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  for (std::vector<Loop*>::const_iterator I = TopLevelLoops.begin(),
2182e6e741b737960ecd0b68610875050019aac0f07Chris Lattner         E = TopLevelLoops.end(); I != E; ++I) {
2190252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner    AliasSetTracker AST(*AA);
220ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner    visitLoop(*I, AST);
2212e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  }
222e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  return Changed;
223e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner}
224e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
22594170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner
22694170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner/// visitLoop - Hoist expressions out of the specified loop...
22794170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner///
2280252e49f6d6973b6f347c8feafc49e28af27163aChris Lattnervoid LICM::visitLoop(Loop *L, AliasSetTracker &AST) {
229e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // Recurse through all subloops before we process this loop...
2302e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  for (std::vector<Loop*>::const_iterator I = L->getSubLoops().begin(),
2312e6e741b737960ecd0b68610875050019aac0f07Chris Lattner         E = L->getSubLoops().end(); I != E; ++I) {
2320252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner    AliasSetTracker SubAST(*AA);
233ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner    visitLoop(*I, SubAST);
2342e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
2352e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    // Incorporate information about the subloops into this loop...
2360252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner    AST.add(SubAST);
2372e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  }
238e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  CurLoop = L;
2390252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner  CurAST = &AST;
240e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
24199a57216a935a512c418032f590a4660bad9d846Chris Lattner  // Get the preheader block to move instructions into...
24299a57216a935a512c418032f590a4660bad9d846Chris Lattner  Preheader = L->getLoopPreheader();
24399a57216a935a512c418032f590a4660bad9d846Chris Lattner  assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
24499a57216a935a512c418032f590a4660bad9d846Chris Lattner
2452e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Loop over the body of this loop, looking for calls, invokes, and stores.
2460252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner  // Because subloops have already been incorporated into AST, we skip blocks in
2472e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // subloops.
2482e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  //
249a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  for (std::vector<BasicBlock*>::const_iterator I = L->getBlocks().begin(),
250a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner         E = L->getBlocks().end(); I != E; ++I)
2512e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    if (LI->getLoopFor(*I) == L)        // Ignore blocks in subloops...
2520252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      AST.add(**I);                     // Incorporate the specified basic block
2532e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
254e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // We want to visit all of the instructions in this loop... that are not parts
255e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // of our subloops (they have already had their invariants hoisted out of
256e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // their loop, into this loop, so there is no need to process the BODIES of
257e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // the subloops).
258e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  //
259952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  // Traverse the body of the loop in depth first order on the dominator tree so
260952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  // that we are guaranteed to see definitions before we see uses.  This allows
261952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  // us to perform the LICM transformation in one pass, without iteration.
262952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  //
26311a49a722f657294f38865019af51f82dc31c1c3Tanya Lattner  HoistRegion(DT->getNode(L->getHeader()));
264e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
2652e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Now that all loop invariants have been removed from the loop, promote any
2662e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // memory references to scalars that we can...
2672e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  if (!DisablePromotion)
2682e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    PromoteValuesInLoop();
2692e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
270e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  // Clear out loops state information for the next iteration
271e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  CurLoop = 0;
27299a57216a935a512c418032f590a4660bad9d846Chris Lattner  Preheader = 0;
273e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner}
274e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
275952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
276952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner/// dominated by the specified block, and that are in the current loop) in depth
277cf00c4ab3ba308d45d98c5ccab87362cf802facbMisha Brukman/// first order w.r.t the DominatorTree.  This allows us to visit definitions
278952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner/// before uses, allowing us to hoist a loop body in one pass without iteration.
279952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner///
280952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattnervoid LICM::HoistRegion(DominatorTree::Node *N) {
281952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  assert(N != 0 && "Null dominator tree node?");
282ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  BasicBlock *BB = N->getBlock();
283952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
284b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner  // If this subregion is not in the top level loop at all, exit.
285ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  if (!CurLoop->contains(BB)) return;
286952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
287a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // Only need to process the contents of this block if it is not part of a
288a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // subloop (which would already have been processed).
289ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  if (!inSubLoop(BB))
290a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
291a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      Instruction &I = *II++;
292a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
293a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // We can only handle simple expressions and loads with this code.
294a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      if (canSinkOrHoistInst(I)) {
295a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // First check to see if we can sink this instruction to the exit blocks
296a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // of the loop.  We can do this if the only users of the instruction are
297a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // outside of the loop.  In this case, it doesn't even matter if the
298a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // operands of the instruction are loop invariant.
299a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        //
300a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        if (isNotUsedInLoop(I))
301a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          sink(I);
302a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
303a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // If we can't sink the instruction, try hoisting it out to the
304a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // preheader.  We can only do this if all of the operands of the
305a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // instruction are loop invariant and if it is safe to hoist the
306a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // instruction.
307a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        //
308a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        else if (isLoopInvariantInst(I) && isSafeToExecuteUnconditionally(I))
309a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          hoist(I);
310a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      }
311ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner    }
312952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
313952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  const std::vector<DominatorTree::Node*> &Children = N->getChildren();
314952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner  for (unsigned i = 0, e = Children.size(); i != e; ++i)
315952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner    HoistRegion(Children[i]);
316952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner}
317952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
318a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
319a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// instruction.
320a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner///
321a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnerbool LICM::canSinkOrHoistInst(Instruction &I) {
322ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  // Loads have extra constraints we have to verify before we can hoist them.
323ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
324ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner    if (LI->isVolatile())
325ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner      return false;        // Don't hoist volatile loads!
326ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner
327ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner    // Don't hoist loads which have may-aliased stores in loop.
328a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    return !pointerInvalidatedByLoop(LI->getOperand(0));
329ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  }
330ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner
331a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  return isa<BinaryOperator>(I) || isa<ShiftInst>(I) || isa<CastInst>(I) ||
332a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner         isa<GetElementPtrInst>(I) || isa<VANextInst>(I) || isa<VAArgInst>(I);
333a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner}
334a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
335a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// isNotUsedInLoop - Return true if the only users of this instruction are
336a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// outside of the loop.  If this is true, we can sink the instruction to the
337a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// exit blocks of the loop.
338a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner///
339a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnerbool LICM::isNotUsedInLoop(Instruction &I) {
340a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
341a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    if (CurLoop->contains(cast<Instruction>(*UI)->getParent()))
342a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      return false;
343a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  return true;
344a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner}
345a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
346a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
347a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// isLoopInvariantInst - Return true if all operands of this instruction are
348a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// loop invariant.  We also filter out non-hoistable instructions here just for
349a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// efficiency.
350a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner///
351a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnerbool LICM::isLoopInvariantInst(Instruction &I) {
352a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // The instruction is loop invariant if all of its operands are loop-invariant
353a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
354a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    if (!isLoopInvariant(I.getOperand(i)))
355a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      return false;
356a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
357ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  // If we got this far, the instruction is loop invariant!
358ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner  return true;
359ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner}
360ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner
361a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// sink - When an instruction is found to only be used outside of the loop,
362a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// this function moves it to the exit blocks and patches up SSA form as
363a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// needed.
364a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner///
365a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnervoid LICM::sink(Instruction &I) {
366a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  DEBUG(std::cerr << "LICM sinking instruction: " << I);
367a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
368a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  const std::vector<BasicBlock*> &ExitBlocks = CurLoop->getExitBlocks();
369a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
370a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // The case where there is only a single exit node of this loop is common
371a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // enough that we handle it as a special (more efficient) case.  It is more
372a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // efficient to handle because there are no PHI nodes that need to be placed.
373a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  if (ExitBlocks.size() == 1) {
374a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
375a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // Instruction is not used, just delete it.
376a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      I.getParent()->getInstList().erase(&I);
377a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    } else {
378a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // Move the instruction to the start of the exit block, after any PHI
379a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // nodes in it.
380a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      I.getParent()->getInstList().remove(&I);
381a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
382a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      BasicBlock::iterator InsertPt = ExitBlocks[0]->begin();
383a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      while (isa<PHINode>(InsertPt)) ++InsertPt;
384a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      ExitBlocks[0]->getInstList().insert(InsertPt, &I);
385a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    }
386a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  } else if (ExitBlocks.size() == 0) {
387a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // The instruction is actually dead if there ARE NO exit blocks.
388a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    I.getParent()->getInstList().erase(&I);
389a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    return;   // Don't count this as a sunk instruction, don't check operands.
390a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  } else {
391a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
392a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // do all of the hard work of inserting PHI nodes as necessary.  We convert
393a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // the value into a stack object to get it to do this.
394a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
395a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // Firstly, we create a stack object to hold the value...
396a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    AllocaInst *AI = new AllocaInst(I.getType(), 0, I.getName(),
397a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner                                   I.getParent()->getParent()->front().begin());
398a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
399a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // Secondly, insert load instructions for each use of the instruction
400a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // outside of the loop.
401a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    while (!I.use_empty()) {
402a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      Instruction *U = cast<Instruction>(I.use_back());
403a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
404a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // If the user is a PHI Node, we actually have to insert load instructions
405a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      // in all predecessor blocks, not in the PHI block itself!
406a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      if (PHINode *UPN = dyn_cast<PHINode>(U)) {
407a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // Only insert into each predecessor once, so that we don't have
408a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // different incoming values from the same block!
409a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        std::map<BasicBlock*, Value*> InsertedBlocks;
410a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
411a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          if (UPN->getIncomingValue(i) == &I) {
412a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            BasicBlock *Pred = UPN->getIncomingBlock(i);
413a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            Value *&PredVal = InsertedBlocks[Pred];
414a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            if (!PredVal) {
415a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner              // Insert a new load instruction right before the terminator in
416a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner              // the predecessor block.
417a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner              PredVal = new LoadInst(AI, "", Pred->getTerminator());
418a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            }
419a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
420a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            UPN->setIncomingValue(i, PredVal);
421a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          }
422a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
423a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      } else {
424a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        LoadInst *L = new LoadInst(AI, "", U);
425a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        U->replaceUsesOfWith(&I, L);
426a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      }
427a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    }
428a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
429a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // Thirdly, insert a copy of the instruction in each exit block of the loop
430a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // that is dominated by the instruction, storing the result into the memory
431a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // location.  Be careful not to insert the instruction into any particular
432a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // basic block more than once.
433a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    std::set<BasicBlock*> InsertedBlocks;
434a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    BasicBlock *InstOrigBB = I.getParent();
435a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
436a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
437a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      BasicBlock *ExitBlock = ExitBlocks[i];
438a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
439a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
440a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        std::set<BasicBlock*>::iterator SI =
441a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          InsertedBlocks.lower_bound(ExitBlock);
442a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        // If we haven't already processed this exit block, do so now.
443a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        if (SI == InsertedBlocks.end() || *SI != ExitBlock) {
444a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          // Insert the code after the last PHI node...
445a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          BasicBlock::iterator InsertPt = ExitBlock->begin();
446a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          while (isa<PHINode>(InsertPt)) ++InsertPt;
447a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
448a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          // If this is the first exit block processed, just move the original
449a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          // instruction, otherwise clone the original instruction and insert
450a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          // the copy.
451a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          Instruction *New;
452a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          if (InsertedBlocks.empty()) {
453a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            I.getParent()->getInstList().remove(&I);
454a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            ExitBlock->getInstList().insert(InsertPt, &I);
455a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            New = &I;
456a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          } else {
457a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            New = I.clone();
458a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            New->setName(I.getName()+".le");
459a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner            ExitBlock->getInstList().insert(InsertPt, New);
460a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          }
461a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
462a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          // Now that we have inserted the instruction, store it into the alloca
463a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          new StoreInst(New, AI, InsertPt);
464a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
465a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          // Remember we processed this block
466a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          InsertedBlocks.insert(SI, ExitBlock);
467a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        }
468a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      }
469a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    }
470a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
471a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    // Finally, promote the fine value to SSA form.
472a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    std::vector<AllocaInst*> Allocas;
473a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    Allocas.push_back(AI);
474a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    PromoteMemToReg(Allocas, *DT, *DF, AA->getTargetData());
475a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  }
476a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
477a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  if (isa<LoadInst>(I)) ++NumMovedLoads;
478a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  ++NumSunk;
479a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  Changed = true;
480a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner
481a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // Since we just sunk an instruction, check to see if any other instructions
482a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  // used by this instruction are now sinkable.  If so, sink them too.
483a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
484a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    if (Instruction *OpI = dyn_cast<Instruction>(I.getOperand(i)))
485a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      if (CurLoop->contains(OpI->getParent()) && canSinkOrHoistInst(*OpI) &&
486a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          isNotUsedInLoop(*OpI) &&
487a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner          isSafeToExecuteUnconditionally(*OpI))
488a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        sink(*OpI);
489a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner}
490952eaee239d6c38f5121ed68277555344c2d6bf0Chris Lattner
49194170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner/// hoist - When an instruction is found to only use loop invariant operands
49294170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner/// that is safe to hoist, this instruction is called to do the dirty work.
49394170596b715928794a55bc5a1671e3992fd2dc9Chris Lattner///
494a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnervoid LICM::hoist(Instruction &I) {
495b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner  DEBUG(std::cerr << "LICM hoisting to";
496b461373fbcdc5909cc7331fa64791cd039de4bc8Chris Lattner        WriteAsOperand(std::cerr, Preheader, false);
497a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner        std::cerr << ": " << I);
498ed6dfc2856cd44a8aa608a9074eabbf42dd6cadcChris Lattner
49999a57216a935a512c418032f590a4660bad9d846Chris Lattner  // Remove the instruction from its current basic block... but don't delete the
50099a57216a935a512c418032f590a4660bad9d846Chris Lattner  // instruction.
501a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  I.getParent()->getInstList().remove(&I);
502e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
5039646e6b6af1f924f9366a2bffc6dde102f84d231Chris Lattner  // Insert the new node in Preheader, before the terminator.
504a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  Preheader->getInstList().insert(Preheader->getTerminator(), &I);
5059646e6b6af1f924f9366a2bffc6dde102f84d231Chris Lattner
506a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  if (isa<LoadInst>(I)) ++NumMovedLoads;
5079646e6b6af1f924f9366a2bffc6dde102f84d231Chris Lattner  ++NumHoisted;
508e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner  Changed = true;
509e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner}
510e0e734eea052a4e8372e6f430ef41149128ba0a6Chris Lattner
511a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
512a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// not a trapping instruction or if it is a trapping instruction and is
513a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner/// guaranteed to execute.
5149966c03aad031f738718bed3bc00371e358beb5dTanya Lattner///
515a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattnerbool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
51692094b4d928119eceac1484331acffe950f4651cChris Lattner  // If it is not a trapping instruction, it is always safe to hoist.
51792094b4d928119eceac1484331acffe950f4651cChris Lattner  if (!Inst.isTrapping()) return true;
51892094b4d928119eceac1484331acffe950f4651cChris Lattner
51992094b4d928119eceac1484331acffe950f4651cChris Lattner  // Otherwise we have to check to make sure that the instruction dominates all
52092094b4d928119eceac1484331acffe950f4651cChris Lattner  // of the exit blocks.  If it doesn't, then there is a path out of the loop
52192094b4d928119eceac1484331acffe950f4651cChris Lattner  // which does not execute this instruction, so we can't hoist it.
52292094b4d928119eceac1484331acffe950f4651cChris Lattner
52392094b4d928119eceac1484331acffe950f4651cChris Lattner  // If the instruction is in the header block for the loop (which is very
52492094b4d928119eceac1484331acffe950f4651cChris Lattner  // common), it is always guaranteed to dominate the exit blocks.  Since this
52592094b4d928119eceac1484331acffe950f4651cChris Lattner  // is a common case, and can save some work, check it now.
526a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  if (Inst.getParent() == CurLoop->getHeader())
52792094b4d928119eceac1484331acffe950f4651cChris Lattner    return true;
52892094b4d928119eceac1484331acffe950f4651cChris Lattner
52992094b4d928119eceac1484331acffe950f4651cChris Lattner  // Get the exit blocks for the current loop.
530a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  const std::vector<BasicBlock*> &ExitBlocks = CurLoop->getExitBlocks();
5319966c03aad031f738718bed3bc00371e358beb5dTanya Lattner
53292094b4d928119eceac1484331acffe950f4651cChris Lattner  // For each exit block, get the DT node and walk up the DT until the
53392094b4d928119eceac1484331acffe950f4651cChris Lattner  // instruction's basic block is found or we exit the loop.
534a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
535a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner    if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
536a2706518f9cc34358cba1072f78235aa091d6d93Chris Lattner      return false;
53711a49a722f657294f38865019af51f82dc31c1c3Tanya Lattner
5389966c03aad031f738718bed3bc00371e358beb5dTanya Lattner  return true;
5399966c03aad031f738718bed3bc00371e358beb5dTanya Lattner}
5409966c03aad031f738718bed3bc00371e358beb5dTanya Lattner
541eb53ae4f2dc39e75e725b21b52d77d29cf1c11c9Chris Lattner
5422e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
5432e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// stores out of the loop and moving loads to before the loop.  We do this by
5442e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// looping over the stores in the loop, looking for stores to Must pointers
5452e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// which are loop invariant.  We promote these memory locations to use allocas
5462e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// instead.  These allocas can easily be raised to register values by the
5472e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// PromoteMem2Reg functionality.
5482e6e741b737960ecd0b68610875050019aac0f07Chris Lattner///
5492e6e741b737960ecd0b68610875050019aac0f07Chris Lattnervoid LICM::PromoteValuesInLoop() {
5502e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // PromotedValues - List of values that are promoted out of the loop.  Each
551065a616adad624152618b1b0084ff074e5b03bbbChris Lattner  // value has an alloca instruction for it, and a canonical version of the
5522e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // pointer.
5532e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
5542e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
5552e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
5562e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  findPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
5572e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  if (ValueToAllocaMap.empty()) return;   // If there are values to promote...
5582e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
5592e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  Changed = true;
5602e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  NumPromoted += PromotedValues.size();
5612e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
5622e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Emit a copy from the value into the alloca'd value in the loop preheader
5632e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  TerminatorInst *LoopPredInst = Preheader->getTerminator();
5642e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
5652e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    // Load from the memory we are promoting...
5662e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    LoadInst *LI = new LoadInst(PromotedValues[i].second,
5672e6e741b737960ecd0b68610875050019aac0f07Chris Lattner                                PromotedValues[i].second->getName()+".promoted",
5682e6e741b737960ecd0b68610875050019aac0f07Chris Lattner                                LoopPredInst);
5692e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    // Store into the temporary alloca...
5702e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
5712e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  }
5722e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
5732e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Scan the basic blocks in the loop, replacing uses of our pointers with
5740ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  // uses of the allocas in question.
5752e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  //
5762e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
5772e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
5782e6e741b737960ecd0b68610875050019aac0f07Chris Lattner         E = LoopBBs.end(); I != E; ++I) {
5792e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    // Rewrite all loads and stores in the block of the pointer...
5802e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
5812e6e741b737960ecd0b68610875050019aac0f07Chris Lattner         II != E; ++II) {
582e408e25132b8de8c757db1e3ddcd70432dfeb24dChris Lattner      if (LoadInst *L = dyn_cast<LoadInst>(II)) {
5832e6e741b737960ecd0b68610875050019aac0f07Chris Lattner        std::map<Value*, AllocaInst*>::iterator
5842e6e741b737960ecd0b68610875050019aac0f07Chris Lattner          I = ValueToAllocaMap.find(L->getOperand(0));
5852e6e741b737960ecd0b68610875050019aac0f07Chris Lattner        if (I != ValueToAllocaMap.end())
5862e6e741b737960ecd0b68610875050019aac0f07Chris Lattner          L->setOperand(0, I->second);    // Rewrite load instruction...
587e408e25132b8de8c757db1e3ddcd70432dfeb24dChris Lattner      } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
5882e6e741b737960ecd0b68610875050019aac0f07Chris Lattner        std::map<Value*, AllocaInst*>::iterator
5892e6e741b737960ecd0b68610875050019aac0f07Chris Lattner          I = ValueToAllocaMap.find(S->getOperand(1));
5902e6e741b737960ecd0b68610875050019aac0f07Chris Lattner        if (I != ValueToAllocaMap.end())
5912e6e741b737960ecd0b68610875050019aac0f07Chris Lattner          S->setOperand(1, I->second);    // Rewrite store instruction...
5922e6e741b737960ecd0b68610875050019aac0f07Chris Lattner      }
5932e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    }
5940ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  }
5952e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
5960ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  // Now that the body of the loop uses the allocas instead of the original
5970ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  // memory locations, insert code to copy the alloca value back into the
5980ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  // original memory location on all exits from the loop.  Note that we only
5990ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  // want to insert one copy of the code in each exit block, though the loop may
6000ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  // exit to the same block more than once.
6010ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  //
6020ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  std::set<BasicBlock*> ProcessedBlocks;
6030ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner
6040ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  const std::vector<BasicBlock*> &ExitBlocks = CurLoop->getExitBlocks();
6050ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
6060ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner    if (!ProcessedBlocks.count(ExitBlocks[i])) {
6070ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner      ProcessedBlocks.insert(ExitBlocks[i]);
6080ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner
6090ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner      // Copy all of the allocas into their memory locations...
6100ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner      BasicBlock::iterator BI = ExitBlocks[i]->begin();
6110ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner      while (isa<PHINode>(*BI))
6120ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner        ++BI;             // Skip over all of the phi nodes in the block...
6130ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner      Instruction *InsertPos = BI;
6140ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner      for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
6150ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner        // Load from the alloca...
6160ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner        LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
6170ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner        // Store into the memory we promoted...
6180ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner        new StoreInst(LI, PromotedValues[i].second, InsertPos);
6192e6e741b737960ecd0b68610875050019aac0f07Chris Lattner      }
6200ed2da9ac733c51ba004c067d3b552c1fa54613dChris Lattner    }
6212e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
6222e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // Now that we have done the deed, use the mem2reg functionality to promote
6232e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  // all of the new allocas we just created into real SSA registers...
6242e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  //
6252e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  std::vector<AllocaInst*> PromotedAllocas;
6262e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  PromotedAllocas.reserve(PromotedValues.size());
6272e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
6282e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    PromotedAllocas.push_back(PromotedValues[i].first);
62943f820d1f7638656be2158efac7dd8f5b08b8b77Chris Lattner  PromoteMemToReg(PromotedAllocas, *DT, *DF, AA->getTargetData());
6302e6e741b737960ecd0b68610875050019aac0f07Chris Lattner}
6312e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
632352361b409d16045e703d986aa7fd77295173ef3Misha Brukman/// findPromotableValuesInLoop - Check the current loop for stores to definite
6332e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// pointers, which are not loaded and stored through may aliases.  If these are
6342e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// found, create an alloca for the value, add it to the PromotedValues list,
6352e6e741b737960ecd0b68610875050019aac0f07Chris Lattner/// and keep track of the mapping from value to alloca...
6362e6e741b737960ecd0b68610875050019aac0f07Chris Lattner///
6372e6e741b737960ecd0b68610875050019aac0f07Chris Lattnervoid LICM::findPromotableValuesInLoop(
6382e6e741b737960ecd0b68610875050019aac0f07Chris Lattner                   std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
6392e6e741b737960ecd0b68610875050019aac0f07Chris Lattner                             std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
6402e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
6412e6e741b737960ecd0b68610875050019aac0f07Chris Lattner
6420252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner  // Loop over all of the alias sets in the tracker object...
6430252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner  for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
6440252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner       I != E; ++I) {
6450252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner    AliasSet &AS = *I;
6460252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner    // We can promote this alias set if it has a store, if it is a "Must" alias
6470252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner    // set, and if the pointer is loop invariant.
6480252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner    if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
6490252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner        isLoopInvariant(AS.begin()->first)) {
6500252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      assert(AS.begin() != AS.end() &&
6510252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner             "Must alias set should have at least one pointer element in it!");
6520252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      Value *V = AS.begin()->first;
6530252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner
6540252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      // Check that all of the pointers in the alias set have the same type.  We
6550252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      // cannot (yet) promote a memory location that is loaded and stored in
6560252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      // different sizes.
6570252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      bool PointerOk = true;
6580252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
6590252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner        if (V->getType() != I->first->getType()) {
6600252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner          PointerOk = false;
6610252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner          break;
6622e6e741b737960ecd0b68610875050019aac0f07Chris Lattner        }
6630252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner
6640252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner      if (PointerOk) {
6650252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner        const Type *Ty = cast<PointerType>(V->getType())->getElementType();
6660252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner        AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
6670252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner        PromotedValues.push_back(std::make_pair(AI, V));
6680252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner
6690252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner        for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
6700252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner          ValueToAllocaMap.insert(std::make_pair(I->first, AI));
6710252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner
6720252e49f6d6973b6f347c8feafc49e28af27163aChris Lattner        DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");
6732e6e741b737960ecd0b68610875050019aac0f07Chris Lattner      }
6742e6e741b737960ecd0b68610875050019aac0f07Chris Lattner    }
6752e6e741b737960ecd0b68610875050019aac0f07Chris Lattner  }
676f5e84aa0887d3fcd752d4a4fa1bb0e526be49f20Chris Lattner}
677