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 (Constant *C = dyn_cast<Constant>(*UI)) {
48 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
49 if (isStoredThrough(CE))
51 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
52 if (isStoredThrough(GV)) return true;
54 // Must be an element of a constant array or something.
57 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
58 if (I->getOpcode() == Instruction::GetElementPtr) {
59 if (isStoredThrough(I)) return true;
60 } else if (!isa<LoadInst>(*UI) && !isa<SetCondInst>(*UI))
61 return true; // Any other non-load instruction might store!
63 // Otherwise must be a global or some other user.
70 bool Constifier::run(Module &M) {
72 for (Module::giterator GV = M.gbegin(), E = M.gend(); GV != E; ++GV)
73 if (!GV->isConstant() && GV->hasInternalLinkage() && GV->hasInitializer()) {
74 if (!isStoredThrough(GV)) {
75 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV << "\n");
76 GV->setConstant(true);