1 //===- GlobalConstifier.cpp - Mark read-only globals constant -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass loops over the non-constant internal global variables in the
11 // program. If it can prove that they are never written to, it marks them
14 // NOTE: this should eventually use the alias analysis interfaces to do the
15 // transformation, but for now we just stick with a simple solution. DSA in
16 // particular could give a much more accurate answer to the mod/ref query, but
17 // it's not quite ready for this.
19 //===----------------------------------------------------------------------===//
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "Support/Debug.h"
27 #include "Support/Statistic.h"
31 Statistic<> NumMarked("constify", "Number of globals marked constant");
33 struct Constifier : public Pass {
37 RegisterOpt<Constifier> X("constify", "Global Constifier");
40 Pass *llvm::createGlobalConstifierPass() { return new Constifier(); }
42 /// isStoredThrough - Return false if the specified pointer is provably never
43 /// stored through. If we can't tell, we must conservatively assume it might.
45 static bool isStoredThrough(Value *V) {
46 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
47 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
48 if (isStoredThrough(CE))
50 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
51 if (I->getOpcode() == Instruction::GetElementPtr) {
52 if (isStoredThrough(I)) return true;
53 } else if (!isa<LoadInst>(*UI) && !isa<SetCondInst>(*UI))
54 return true; // Any other non-load instruction might store!
56 // Otherwise must be a global or some other user.
63 bool Constifier::run(Module &M) {
65 for (Module::giterator GV = M.gbegin(), E = M.gend(); GV != E; ++GV)
66 if (!GV->isConstant() && GV->hasInternalLinkage() && GV->hasInitializer()) {
67 if (!isStoredThrough(GV)) {
68 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV << "\n");
69 GV->setConstant(true);