Clean up the use of static and anonymous namespaces. This turned up
[oota-llvm.git] / lib / Transforms / IPO / GlobalOpt.cpp
index fd71dfb826148bcd968f8fda23dfdb86ff5f63ac..e822d9c7b958dc8863b3a673a8f93b996f18fed5 100644 (file)
 #include "llvm/Instructions.h"
 #include "llvm/IntrinsicInst.h"
 #include "llvm/Module.h"
-#include "llvm/ParameterAttributes.h"
 #include "llvm/Pass.h"
 #include "llvm/Analysis/ConstantFolding.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Support/CallSite.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/GetElementPtrTypeIterator.h"
+#include "llvm/Support/MathExtras.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/StringExtras.h"
 #include <algorithm>
+#include <map>
 #include <set>
 using namespace llvm;
 
@@ -66,13 +68,15 @@ namespace {
     bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
     bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
   };
-
-  char GlobalOpt::ID = 0;
-  RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
 }
 
+char GlobalOpt::ID = 0;
+static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
+
 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
 
+namespace {
+
 /// GlobalStatus - As we analyze each global, keep track of some information
 /// about it.  If we find out that the address of the global is taken, none of
 /// this info will be accurate.
@@ -127,7 +131,7 @@ struct VISIBILITY_HIDDEN GlobalStatus {
                    HasNonInstructionUser(false), HasPHIUser(false) {}
 };
 
-
+}
 
 /// ConstantIsDead - Return true if the specified constant is (transitively)
 /// dead.  The constant may be used by other constants (e.g. constant arrays and
@@ -177,7 +181,7 @@ static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
         // If this is a direct store to the global (i.e., the global is a scalar
         // value, not an aggregate), keep more specific information about
         // stores.
-        if (GS.StoredType != GlobalStatus::isStored)
+        if (GS.StoredType != GlobalStatus::isStored) {
           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
             Value *StoredVal = SI->getOperand(0);
             if (StoredVal == GV->getInitializer()) {
@@ -200,6 +204,7 @@ static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
           } else {
             GS.StoredType = GlobalStatus::isStored;
           }
+        }
       } else if (isa<GetElementPtrInst>(I)) {
         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
       } else if (isa<SelectInst>(I)) {
@@ -453,7 +458,7 @@ static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
 /// behavior of the program in a more fine-grained way.  We have determined that
 /// this transformation is safe already.  We return the first global variable we
 /// insert so that the caller can reprocess it.
-static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
+static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
   // Make sure this global only has simple uses that we can SRA.
   if (!GlobalUsersSafeToSRA(GV))
     return 0;
@@ -465,8 +470,14 @@ static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
   std::vector<GlobalVariable*> NewGlobals;
   Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
 
+  // Get the alignment of the global, either explicit or target-specific.
+  unsigned StartAlignment = GV->getAlignment();
+  if (StartAlignment == 0)
+    StartAlignment = TD.getABITypeAlignment(GV->getType());
+   
   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
     NewGlobals.reserve(STy->getNumElements());
+    const StructLayout &Layout = *TD.getStructLayout(STy);
     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
       Constant *In = getAggregateConstantElement(Init,
                                             ConstantInt::get(Type::Int32Ty, i));
@@ -478,19 +489,28 @@ static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
                                                GV->isThreadLocal());
       Globals.insert(GV, NGV);
       NewGlobals.push_back(NGV);
+      
+      // Calculate the known alignment of the field.  If the original aggregate
+      // had 256 byte alignment for example, something might depend on that:
+      // propagate info to each field.
+      uint64_t FieldOffset = Layout.getElementOffset(i);
+      unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
+      if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
+        NGV->setAlignment(NewAlign);
     }
   } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
     unsigned NumElements = 0;
     if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
       NumElements = ATy->getNumElements();
-    else if (const VectorType *PTy = dyn_cast<VectorType>(STy))
-      NumElements = PTy->getNumElements();
     else
-      assert(0 && "Unknown aggregate sequential type!");
+      NumElements = cast<VectorType>(STy)->getNumElements();
 
     if (NumElements > 16 && GV->hasNUsesOrMore(16))
       return 0; // It's not worth it.
     NewGlobals.reserve(NumElements);
+    
+    uint64_t EltSize = TD.getABITypeSize(STy->getElementType());
+    unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
     for (unsigned i = 0, e = NumElements; i != e; ++i) {
       Constant *In = getAggregateConstantElement(Init,
                                             ConstantInt::get(Type::Int32Ty, i));
@@ -503,6 +523,13 @@ static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
                                                GV->isThreadLocal());
       Globals.insert(GV, NGV);
       NewGlobals.push_back(NGV);
+      
+      // Calculate the known alignment of the field.  If the original aggregate
+      // had 256 byte alignment for example, something might depend on that:
+      // propagate info to each field.
+      unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
+      if (NewAlign > EltAlign)
+        NGV->setAlignment(NewAlign);
     }
   }
 
@@ -530,7 +557,7 @@ static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
     Value *NewPtr = NewGlobals[Val];
 
     // Form a shorter GEP if needed.
-    if (GEP->getNumOperands() > 3)
+    if (GEP->getNumOperands() > 3) {
       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
         SmallVector<Constant*, 8> Idxs;
         Idxs.push_back(NullInt);
@@ -544,9 +571,10 @@ static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
         Idxs.push_back(NullInt);
         for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
           Idxs.push_back(GEPI->getOperand(i));
-        NewPtr = new GetElementPtrInst(NewPtr, Idxs.begin(), Idxs.end(),
-                                       GEPI->getName()+"."+utostr(Val), GEPI);
+        NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
+                                           GEPI->getName()+"."+utostr(Val), GEPI);
       }
+    }
     GEP->replaceAllUsesWith(NewPtr);
 
     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
@@ -786,8 +814,8 @@ static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
                      MI->getAlignment(), MI->getName(), MI);
     Value* Indices[2];
     Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
-    Value *NewGEP = new GetElementPtrInst(NewMI, Indices, Indices + 2,
-                                          NewMI->getName()+".el0", MI);
+    Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
+                                              NewMI->getName()+".el0", MI);
     MI->replaceAllUsesWith(NewGEP);
     MI->eraseFromParent();
     MI = NewMI;
@@ -801,6 +829,9 @@ static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
                                              GV->getName()+".body",
                                              (Module *)NULL,
                                              GV->isThreadLocal());
+  // FIXME: This new global should have the alignment returned by malloc.  Code
+  // could depend on malloc returning large alignment (on the mac, 16 bytes) but
+  // this would only guarantee some lower alignment.
   GV->getParent()->getGlobalList().insert(GV, NewGV);
 
   // Anything that used the malloc now uses the global directly.
@@ -1051,8 +1082,8 @@ static void RewriteHeapSROALoadUser(LoadInst *Load, Instruction *LoadUser,
     GEPIdx.push_back(GEPI->getOperand(1));
     GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
     
-    Value *NGEPI = new GetElementPtrInst(NewPtr, GEPIdx.begin(), GEPIdx.end(),
-                                         GEPI->getName(), GEPI);
+    Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx.begin(), GEPIdx.end(),
+                                             GEPI->getName(), GEPI);
     GEPI->replaceAllUsesWith(NGEPI);
     GEPI->eraseFromParent();
     return;
@@ -1067,8 +1098,8 @@ static void RewriteHeapSROALoadUser(LoadInst *Load, Instruction *LoadUser,
   for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
     Value *LoadV = GetHeapSROALoad(Load, i, FieldGlobals, InsertedLoadsForPtr);
 
-    PHINode *FieldPN = new PHINode(LoadV->getType(),
-                                   PN->getName()+"."+utostr(i), PN);
+    PHINode *FieldPN = PHINode::Create(LoadV->getType(),
+                                       PN->getName()+"."+utostr(i), PN);
     // Fill in the predecessor values.
     for (unsigned pred = 0, e = PN->getNumIncomingValues(); pred != e; ++pred) {
       // Each predecessor either uses the load or the original malloc.
@@ -1170,13 +1201,13 @@ static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
   
   // Create the block to check the first condition.  Put all these blocks at the
   // end of the function as they are unlikely to be executed.
-  BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
-                                            OrigBB->getParent());
+  BasicBlock *NullPtrBlock = BasicBlock::Create("malloc_ret_null",
+                                                OrigBB->getParent());
   
   // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
   // branch on RunningOr.
   OrigBB->getTerminator()->eraseFromParent();
-  new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
+  BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
   
   // Within the NullPtrBlock, we need to emit a comparison and branch for each
   // pointer, because some may be null while others are not.
@@ -1185,21 +1216,20 @@ static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
     Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal, 
                               Constant::getNullValue(GVVal->getType()),
                               "tmp", NullPtrBlock);
-    BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
-    BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
-    new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
+    BasicBlock *FreeBlock = BasicBlock::Create("free_it", OrigBB->getParent());
+    BasicBlock *NextBlock = BasicBlock::Create("next", OrigBB->getParent());
+    BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
 
     // Fill in FreeBlock.
     new FreeInst(GVVal, FreeBlock);
     new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
                   FreeBlock);
-    new BranchInst(NextBlock, FreeBlock);
+    BranchInst::Create(NextBlock, FreeBlock);
     
     NullPtrBlock = NextBlock;
   }
   
-  new BranchInst(ContBB, NullPtrBlock);
-  
+  BranchInst::Create(ContBB, NullPtrBlock);
   
   // MI is no longer needed, remove it.
   MI->eraseFromParent();
@@ -1408,7 +1438,7 @@ static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
       if (IsOneZero)
         NSI = new ZExtInst(NLI, LI->getType(), "", LI);
       else
-        NSI = new SelectInst(NLI, OtherVal, InitVal, "", LI);
+        NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
       NSI->takeName(LI);
       LI->replaceAllUsesWith(NSI);
     }
@@ -1518,7 +1548,8 @@ bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
       ++NumMarked;
       return true;
     } else if (!GV->getInitializer()->getType()->isFirstClassType()) {
-      if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
+      if (GlobalVariable *FirstNewGV = SRAGlobal(GV, 
+                                                 getAnalysis<TargetData>())) {
         GVI = FirstNewGV;  // Don't skip the newly produced globals!
         return true;
       }
@@ -1584,25 +1615,18 @@ static bool OnlyCalledDirectly(Function *F) {
 /// function, changing them to FastCC.
 static void ChangeCalleesToFastCall(Function *F) {
   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
-    Instruction *User = cast<Instruction>(*UI);
-    if (CallInst *CI = dyn_cast<CallInst>(User))
-      CI->setCallingConv(CallingConv::Fast);
-    else
-      cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
+    CallSite User(cast<Instruction>(*UI));
+    User.setCallingConv(CallingConv::Fast);
   }
 }
 
-static const ParamAttrsList *StripNest(const ParamAttrsList *Attrs) {
-  if (Attrs) {
-    for (unsigned i = 0, e = Attrs->size(); i != e; ++i) {
-      uint16_t A = Attrs->getParamAttrsAtIndex(i);
-      if (A & ParamAttr::Nest) {
-        Attrs = ParamAttrsList::excludeAttrs(Attrs, Attrs->getParamIndex(i),
-                                             ParamAttr::Nest);
-        // There can be only one.
-        break;
-      }
-    }
+static PAListPtr StripNest(const PAListPtr &Attrs) {
+  for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
+    if ((Attrs.getSlot(i).Attrs & ParamAttr::Nest) == 0)
+      continue;
+
+    // There can be only one.
+    return Attrs.removeAttr(Attrs.getSlot(i).Index, ParamAttr::Nest);
   }
 
   return Attrs;
@@ -1611,13 +1635,8 @@ static const ParamAttrsList *StripNest(const ParamAttrsList *Attrs) {
 static void RemoveNestAttribute(Function *F) {
   F->setParamAttrs(StripNest(F->getParamAttrs()));
   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
-    Instruction *User = cast<Instruction>(*UI);
-    if (CallInst *CI = dyn_cast<CallInst>(User)) {
-      CI->setParamAttrs(StripNest(CI->getParamAttrs()));
-    } else {
-      InvokeInst *II = cast<InvokeInst>(User);
-      II->setParamAttrs(StripNest(II->getParamAttrs()));
-    }
+    CallSite User(cast<Instruction>(*UI));
+    User.setParamAttrs(StripNest(User.getParamAttrs()));
   }
 }
 
@@ -1644,8 +1663,7 @@ bool GlobalOpt::OptimizeFunctions(Module &M) {
         Changed = true;
       }
 
-      if (F->getParamAttrs() &&
-          F->getParamAttrs()->hasAttrSomewhere(ParamAttr::Nest) &&
+      if (F->getParamAttrs().hasAttrSomewhere(ParamAttr::Nest) &&
           OnlyCalledDirectly(F)) {
         // The function is not used by a trampoline intrinsic, so it is safe
         // to remove the 'nest' attribute.