1 //===-- GlobalMerge.cpp - Internal globals merging -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // This pass merges globals with internal linkage into one. This way all the 10 // globals which were merged into a biggest one can be addressed using offsets 11 // from the same base pointer (no need for separate base pointer for each of the 12 // global). Such a transformation can significantly reduce the register pressure 13 // when many globals are involved. 14 // 15 // For example, consider the code which touches several global variables at 16 // once: 17 // 18 // static int foo[N], bar[N], baz[N]; 19 // 20 // for (i = 0; i < N; ++i) { 21 // foo[i] = bar[i] * baz[i]; 22 // } 23 // 24 // On ARM the addresses of 3 arrays should be kept in the registers, thus 25 // this code has quite large register pressure (loop body): 26 // 27 // ldr r1, [r5], #4 28 // ldr r2, [r6], #4 29 // mul r1, r2, r1 30 // str r1, [r0], #4 31 // 32 // Pass converts the code to something like: 33 // 34 // static struct { 35 // int foo[N]; 36 // int bar[N]; 37 // int baz[N]; 38 // } merged; 39 // 40 // for (i = 0; i < N; ++i) { 41 // merged.foo[i] = merged.bar[i] * merged.baz[i]; 42 // } 43 // 44 // and in ARM code this becomes: 45 // 46 // ldr r0, [r5, #40] 47 // ldr r1, [r5, #80] 48 // mul r0, r1, r0 49 // str r0, [r5], #4 50 // 51 // note that we saved 2 registers here almostly "for free". 52 // ===---------------------------------------------------------------------===// 53 54 #include "llvm/Transforms/Scalar.h" 55 #include "llvm/ADT/SmallPtrSet.h" 56 #include "llvm/ADT/Statistic.h" 57 #include "llvm/CodeGen/Passes.h" 58 #include "llvm/IR/Attributes.h" 59 #include "llvm/IR/Constants.h" 60 #include "llvm/IR/DataLayout.h" 61 #include "llvm/IR/DerivedTypes.h" 62 #include "llvm/IR/Function.h" 63 #include "llvm/IR/GlobalVariable.h" 64 #include "llvm/IR/Instructions.h" 65 #include "llvm/IR/Intrinsics.h" 66 #include "llvm/IR/Module.h" 67 #include "llvm/Pass.h" 68 #include "llvm/Support/CommandLine.h" 69 #include "llvm/Target/TargetLowering.h" 70 #include "llvm/Target/TargetLoweringObjectFile.h" 71 #include "llvm/Target/TargetSubtargetInfo.h" 72 using namespace llvm; 73 74 #define DEBUG_TYPE "global-merge" 75 76 // FIXME: This is only useful as a last-resort way to disable the pass. 77 static cl::opt<bool> 78 EnableGlobalMerge("enable-global-merge", cl::Hidden, 79 cl::desc("Enable the global merge pass"), 80 cl::init(true)); 81 82 static cl::opt<bool> 83 EnableGlobalMergeOnConst("global-merge-on-const", cl::Hidden, 84 cl::desc("Enable global merge pass on constants"), 85 cl::init(false)); 86 87 // FIXME: this could be a transitional option, and we probably need to remove 88 // it if only we are sure this optimization could always benefit all targets. 89 static cl::opt<bool> 90 EnableGlobalMergeOnExternal("global-merge-on-external", cl::Hidden, 91 cl::desc("Enable global merge pass on external linkage"), 92 cl::init(false)); 93 94 STATISTIC(NumMerged, "Number of globals merged"); 95 namespace { 96 class GlobalMerge : public FunctionPass { 97 const TargetMachine *TM; 98 const DataLayout *DL; 99 // FIXME: Infer the maximum possible offset depending on the actual users 100 // (these max offsets are different for the users inside Thumb or ARM 101 // functions), see the code that passes in the offset in the ARM backend 102 // for more information. 103 unsigned MaxOffset; 104 105 bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals, 106 Module &M, bool isConst, unsigned AddrSpace) const; 107 108 /// \brief Check if the given variable has been identified as must keep 109 /// \pre setMustKeepGlobalVariables must have been called on the Module that 110 /// contains GV 111 bool isMustKeepGlobalVariable(const GlobalVariable *GV) const { 112 return MustKeepGlobalVariables.count(GV); 113 } 114 115 /// Collect every variables marked as "used" or used in a landing pad 116 /// instruction for this Module. 117 void setMustKeepGlobalVariables(Module &M); 118 119 /// Collect every variables marked as "used" 120 void collectUsedGlobalVariables(Module &M); 121 122 /// Keep track of the GlobalVariable that must not be merged away 123 SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables; 124 125 public: 126 static char ID; // Pass identification, replacement for typeid. 127 explicit GlobalMerge(const TargetMachine *TM = nullptr, 128 unsigned MaximalOffset = 0) 129 : FunctionPass(ID), TM(TM), DL(TM->getDataLayout()), 130 MaxOffset(MaximalOffset) { 131 initializeGlobalMergePass(*PassRegistry::getPassRegistry()); 132 } 133 134 bool doInitialization(Module &M) override; 135 bool runOnFunction(Function &F) override; 136 bool doFinalization(Module &M) override; 137 138 const char *getPassName() const override { 139 return "Merge internal globals"; 140 } 141 142 void getAnalysisUsage(AnalysisUsage &AU) const override { 143 AU.setPreservesCFG(); 144 FunctionPass::getAnalysisUsage(AU); 145 } 146 }; 147 } // end anonymous namespace 148 149 char GlobalMerge::ID = 0; 150 INITIALIZE_PASS_BEGIN(GlobalMerge, "global-merge", "Merge global variables", 151 false, false) 152 INITIALIZE_PASS_END(GlobalMerge, "global-merge", "Merge global variables", 153 false, false) 154 155 bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals, 156 Module &M, bool isConst, unsigned AddrSpace) const { 157 // FIXME: Find better heuristics 158 std::stable_sort(Globals.begin(), Globals.end(), 159 [this](const GlobalVariable *GV1, const GlobalVariable *GV2) { 160 Type *Ty1 = cast<PointerType>(GV1->getType())->getElementType(); 161 Type *Ty2 = cast<PointerType>(GV2->getType())->getElementType(); 162 163 return (DL->getTypeAllocSize(Ty1) < DL->getTypeAllocSize(Ty2)); 164 }); 165 166 Type *Int32Ty = Type::getInt32Ty(M.getContext()); 167 168 assert(Globals.size() > 1); 169 170 // FIXME: This simple solution merges globals all together as maximum as 171 // possible. However, with this solution it would be hard to remove dead 172 // global symbols at link-time. An alternative solution could be checking 173 // global symbols references function by function, and make the symbols 174 // being referred in the same function merged and we would probably need 175 // to introduce heuristic algorithm to solve the merge conflict from 176 // different functions. 177 for (size_t i = 0, e = Globals.size(); i != e; ) { 178 size_t j = 0; 179 uint64_t MergedSize = 0; 180 std::vector<Type*> Tys; 181 std::vector<Constant*> Inits; 182 183 bool HasExternal = false; 184 GlobalVariable *TheFirstExternal = 0; 185 for (j = i; j != e; ++j) { 186 Type *Ty = Globals[j]->getType()->getElementType(); 187 MergedSize += DL->getTypeAllocSize(Ty); 188 if (MergedSize > MaxOffset) { 189 break; 190 } 191 Tys.push_back(Ty); 192 Inits.push_back(Globals[j]->getInitializer()); 193 194 if (Globals[j]->hasExternalLinkage() && !HasExternal) { 195 HasExternal = true; 196 TheFirstExternal = Globals[j]; 197 } 198 } 199 200 // If merged variables doesn't have external linkage, we needn't to expose 201 // the symbol after merging. 202 GlobalValue::LinkageTypes Linkage = HasExternal 203 ? GlobalValue::ExternalLinkage 204 : GlobalValue::InternalLinkage; 205 206 StructType *MergedTy = StructType::get(M.getContext(), Tys); 207 Constant *MergedInit = ConstantStruct::get(MergedTy, Inits); 208 209 // If merged variables have external linkage, we use symbol name of the 210 // first variable merged as the suffix of global symbol name. This would 211 // be able to avoid the link-time naming conflict for globalm symbols. 212 GlobalVariable *MergedGV = new GlobalVariable( 213 M, MergedTy, isConst, Linkage, MergedInit, 214 HasExternal ? "_MergedGlobals_" + TheFirstExternal->getName() 215 : "_MergedGlobals", 216 nullptr, GlobalVariable::NotThreadLocal, AddrSpace); 217 218 for (size_t k = i; k < j; ++k) { 219 GlobalValue::LinkageTypes Linkage = Globals[k]->getLinkage(); 220 std::string Name = Globals[k]->getName(); 221 222 Constant *Idx[2] = { 223 ConstantInt::get(Int32Ty, 0), 224 ConstantInt::get(Int32Ty, k-i) 225 }; 226 Constant *GEP = 227 ConstantExpr::getInBoundsGetElementPtr(MergedTy, MergedGV, Idx); 228 Globals[k]->replaceAllUsesWith(GEP); 229 Globals[k]->eraseFromParent(); 230 231 if (Linkage != GlobalValue::InternalLinkage) { 232 // Generate a new alias... 233 auto *PTy = cast<PointerType>(GEP->getType()); 234 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 235 Linkage, Name, GEP, &M); 236 } 237 238 NumMerged++; 239 } 240 i = j; 241 } 242 243 return true; 244 } 245 246 void GlobalMerge::collectUsedGlobalVariables(Module &M) { 247 // Extract global variables from llvm.used array 248 const GlobalVariable *GV = M.getGlobalVariable("llvm.used"); 249 if (!GV || !GV->hasInitializer()) return; 250 251 // Should be an array of 'i8*'. 252 const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer()); 253 254 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) 255 if (const GlobalVariable *G = 256 dyn_cast<GlobalVariable>(InitList->getOperand(i)->stripPointerCasts())) 257 MustKeepGlobalVariables.insert(G); 258 } 259 260 void GlobalMerge::setMustKeepGlobalVariables(Module &M) { 261 collectUsedGlobalVariables(M); 262 263 for (Module::iterator IFn = M.begin(), IEndFn = M.end(); IFn != IEndFn; 264 ++IFn) { 265 for (Function::iterator IBB = IFn->begin(), IEndBB = IFn->end(); 266 IBB != IEndBB; ++IBB) { 267 // Follow the invoke link to find the landing pad instruction 268 const InvokeInst *II = dyn_cast<InvokeInst>(IBB->getTerminator()); 269 if (!II) continue; 270 271 const LandingPadInst *LPInst = II->getUnwindDest()->getLandingPadInst(); 272 // Look for globals in the clauses of the landing pad instruction 273 for (unsigned Idx = 0, NumClauses = LPInst->getNumClauses(); 274 Idx != NumClauses; ++Idx) 275 if (const GlobalVariable *GV = 276 dyn_cast<GlobalVariable>(LPInst->getClause(Idx) 277 ->stripPointerCasts())) 278 MustKeepGlobalVariables.insert(GV); 279 } 280 } 281 } 282 283 bool GlobalMerge::doInitialization(Module &M) { 284 if (!EnableGlobalMerge) 285 return false; 286 287 DenseMap<unsigned, SmallVector<GlobalVariable*, 16> > Globals, ConstGlobals, 288 BSSGlobals; 289 bool Changed = false; 290 setMustKeepGlobalVariables(M); 291 292 // Grab all non-const globals. 293 for (Module::global_iterator I = M.global_begin(), 294 E = M.global_end(); I != E; ++I) { 295 // Merge is safe for "normal" internal or external globals only 296 if (I->isDeclaration() || I->isThreadLocal() || I->hasSection()) 297 continue; 298 299 if (!(EnableGlobalMergeOnExternal && I->hasExternalLinkage()) && 300 !I->hasInternalLinkage()) 301 continue; 302 303 PointerType *PT = dyn_cast<PointerType>(I->getType()); 304 assert(PT && "Global variable is not a pointer!"); 305 306 unsigned AddressSpace = PT->getAddressSpace(); 307 308 // Ignore fancy-aligned globals for now. 309 unsigned Alignment = DL->getPreferredAlignment(I); 310 Type *Ty = I->getType()->getElementType(); 311 if (Alignment > DL->getABITypeAlignment(Ty)) 312 continue; 313 314 // Ignore all 'special' globals. 315 if (I->getName().startswith("llvm.") || 316 I->getName().startswith(".llvm.")) 317 continue; 318 319 // Ignore all "required" globals: 320 if (isMustKeepGlobalVariable(I)) 321 continue; 322 323 if (DL->getTypeAllocSize(Ty) < MaxOffset) { 324 if (TargetLoweringObjectFile::getKindForGlobal(I, *TM).isBSSLocal()) 325 BSSGlobals[AddressSpace].push_back(I); 326 else if (I->isConstant()) 327 ConstGlobals[AddressSpace].push_back(I); 328 else 329 Globals[AddressSpace].push_back(I); 330 } 331 } 332 333 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator 334 I = Globals.begin(), E = Globals.end(); I != E; ++I) 335 if (I->second.size() > 1) 336 Changed |= doMerge(I->second, M, false, I->first); 337 338 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator 339 I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I) 340 if (I->second.size() > 1) 341 Changed |= doMerge(I->second, M, false, I->first); 342 343 if (EnableGlobalMergeOnConst) 344 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator 345 I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I) 346 if (I->second.size() > 1) 347 Changed |= doMerge(I->second, M, true, I->first); 348 349 return Changed; 350 } 351 352 bool GlobalMerge::runOnFunction(Function &F) { 353 return false; 354 } 355 356 bool GlobalMerge::doFinalization(Module &M) { 357 MustKeepGlobalVariables.clear(); 358 return false; 359 } 360 361 Pass *llvm::createGlobalMergePass(const TargetMachine *TM, unsigned Offset) { 362 return new GlobalMerge(TM, Offset); 363 } 364