@@ -73,6 +73,8 @@ class SILGlobalOpt {
73
73
// / A map from each visited global let variable to the store instructions
74
74
// / which initialize it.
75
75
llvm::MapVector<SILGlobalVariable *, StoreInst *> GlobalVarStore;
76
+
77
+ llvm::MapVector<SILGlobalVariable *, AllocGlobalInst *> AllocGlobalStore;
76
78
77
79
// / A set of visited global variables that for some reason we have decided is
78
80
// / not able to be optimized safely or for which we do not know how to
@@ -117,6 +119,9 @@ class SILGlobalOpt {
117
119
118
120
// / This is the main entrypoint for collecting global accesses.
119
121
void collectGlobalAccess (GlobalAddrInst *GAI);
122
+
123
+ void collectAllocGlobal (SILGlobalVariable *global,
124
+ AllocGlobalInst *allocGlobal);
120
125
121
126
// / Returns true if we think that \p CurBB is inside a loop.
122
127
bool isInLoop (SILBasicBlock *CurBB);
@@ -878,6 +883,10 @@ void SILGlobalOpt::collectGlobalAccess(GlobalAddrInst *GAI) {
878
883
}
879
884
}
880
885
886
+ void SILGlobalOpt::collectAllocGlobal (SILGlobalVariable *global, AllocGlobalInst *allocGlobal) {
887
+ AllocGlobalStore[global] = allocGlobal;
888
+ }
889
+
881
890
// Optimize access to the global variable, which is known to have a constant
882
891
// value. Replace all loads from the global address by invocations of a getter
883
892
// that returns the value of this variable.
@@ -955,12 +964,15 @@ bool SILGlobalOpt::run() {
955
964
continue ;
956
965
}
957
966
958
- auto *GAI = dyn_cast<GlobalAddrInst>(&I);
959
- if (! GAI) {
967
+ if ( auto *GAI = dyn_cast<GlobalAddrInst>(&I)) {
968
+ collectGlobalAccess ( GAI);
960
969
continue ;
961
970
}
962
971
963
- collectGlobalAccess (GAI);
972
+ if (auto *allocGlobal = dyn_cast<AllocGlobalInst>(&I)) {
973
+ collectAllocGlobal (allocGlobal->getReferencedGlobal (), allocGlobal);
974
+ continue ;
975
+ }
964
976
}
965
977
}
966
978
}
@@ -974,6 +986,24 @@ bool SILGlobalOpt::run() {
974
986
for (auto &Init : GlobalVarStore) {
975
987
// Optimize the access to globals if possible.
976
988
optimizeGlobalAccess (Init.first , Init.second );
989
+
990
+ if (Init.first ->getLinkage () != SILLinkage::Private) continue ;
991
+ bool canRemove = true ;
992
+ auto globalAddr = cast<GlobalAddrInst>(Init.second ->getDest ());
993
+ for (auto *use : globalAddr->getUses ()) {
994
+ if (!isa<StoreInst>(use->getUser ())) {
995
+ canRemove = false ;
996
+ break ;
997
+ }
998
+ }
999
+ if (canRemove) {
1000
+ Init.second ->eraseFromParent ();
1001
+ assert (globalAddr->getUses ().begin () == globalAddr->getUses ().end ());
1002
+ globalAddr->eraseFromParent ();
1003
+ if (AllocGlobalStore.count (Init.first ))
1004
+ AllocGlobalStore[Init.first ]->eraseFromParent ();
1005
+ Init.first ->getModule ().eraseGlobalVariable (Init.first );
1006
+ }
977
1007
}
978
1008
979
1009
return HasChanged;
0 commit comments