Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/IPO/ConstantMerge.cpp
35266 views
//===- ConstantMerge.cpp - Merge duplicate global constants ---------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file defines the interface to a pass that merges duplicate global9// constants together into a single constant that is shared. This is useful10// because some passes (ie TraceValues) insert a lot of string constants into11// the program, regardless of whether or not an existing string is available.12//13// Algorithm: ConstantMerge is designed to build up a map of available constants14// and eliminate duplicates when it is initialized.15//16//===----------------------------------------------------------------------===//1718#include "llvm/Transforms/IPO/ConstantMerge.h"19#include "llvm/ADT/DenseMap.h"20#include "llvm/ADT/SmallPtrSet.h"21#include "llvm/ADT/SmallVector.h"22#include "llvm/ADT/Statistic.h"23#include "llvm/IR/Constants.h"24#include "llvm/IR/DataLayout.h"25#include "llvm/IR/DerivedTypes.h"26#include "llvm/IR/GlobalValue.h"27#include "llvm/IR/GlobalVariable.h"28#include "llvm/IR/LLVMContext.h"29#include "llvm/IR/Module.h"30#include "llvm/Support/Casting.h"31#include "llvm/Support/Debug.h"32#include "llvm/Transforms/IPO.h"33#include <algorithm>34#include <cassert>35#include <utility>3637using namespace llvm;3839#define DEBUG_TYPE "constmerge"4041STATISTIC(NumIdenticalMerged, "Number of identical global constants merged");4243/// Find values that are marked as llvm.used.44static void FindUsedValues(GlobalVariable *LLVMUsed,45SmallPtrSetImpl<const GlobalValue*> &UsedValues) {46if (!LLVMUsed) return;47ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());4849for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) {50Value *Operand = Inits->getOperand(i)->stripPointerCasts();51GlobalValue *GV = cast<GlobalValue>(Operand);52UsedValues.insert(GV);53}54}5556// True if A is better than B.57static bool IsBetterCanonical(const GlobalVariable &A,58const GlobalVariable &B) {59if (!A.hasLocalLinkage() && B.hasLocalLinkage())60return true;6162if (A.hasLocalLinkage() && !B.hasLocalLinkage())63return false;6465return A.hasGlobalUnnamedAddr();66}6768static bool hasMetadataOtherThanDebugLoc(const GlobalVariable *GV) {69SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;70GV->getAllMetadata(MDs);71for (const auto &V : MDs)72if (V.first != LLVMContext::MD_dbg)73return true;74return false;75}7677static void copyDebugLocMetadata(const GlobalVariable *From,78GlobalVariable *To) {79SmallVector<DIGlobalVariableExpression *, 1> MDs;80From->getDebugInfo(MDs);81for (auto *MD : MDs)82To->addDebugInfo(MD);83}8485static Align getAlign(GlobalVariable *GV) {86return GV->getAlign().value_or(87GV->getDataLayout().getPreferredAlign(GV));88}8990static bool91isUnmergeableGlobal(GlobalVariable *GV,92const SmallPtrSetImpl<const GlobalValue *> &UsedGlobals) {93// Only process constants with initializers in the default address space.94return !GV->isConstant() || !GV->hasDefinitiveInitializer() ||95GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||96// Don't touch thread-local variables.97GV->isThreadLocal() ||98// Don't touch values marked with attribute(used).99UsedGlobals.count(GV);100}101102enum class CanMerge { No, Yes };103static CanMerge makeMergeable(GlobalVariable *Old, GlobalVariable *New) {104if (!Old->hasGlobalUnnamedAddr() && !New->hasGlobalUnnamedAddr())105return CanMerge::No;106if (hasMetadataOtherThanDebugLoc(Old))107return CanMerge::No;108assert(!hasMetadataOtherThanDebugLoc(New));109if (!Old->hasGlobalUnnamedAddr())110New->setUnnamedAddr(GlobalValue::UnnamedAddr::None);111return CanMerge::Yes;112}113114static void replace(Module &M, GlobalVariable *Old, GlobalVariable *New) {115Constant *NewConstant = New;116117LLVM_DEBUG(dbgs() << "Replacing global: @" << Old->getName() << " -> @"118<< New->getName() << "\n");119120// Bump the alignment if necessary.121if (Old->getAlign() || New->getAlign())122New->setAlignment(std::max(getAlign(Old), getAlign(New)));123124copyDebugLocMetadata(Old, New);125Old->replaceAllUsesWith(NewConstant);126127// Delete the global value from the module.128assert(Old->hasLocalLinkage() &&129"Refusing to delete an externally visible global variable.");130Old->eraseFromParent();131}132133static bool mergeConstants(Module &M) {134// Find all the globals that are marked "used". These cannot be merged.135SmallPtrSet<const GlobalValue*, 8> UsedGlobals;136FindUsedValues(M.getGlobalVariable("llvm.used"), UsedGlobals);137FindUsedValues(M.getGlobalVariable("llvm.compiler.used"), UsedGlobals);138139// Map unique constants to globals.140DenseMap<Constant *, GlobalVariable *> CMap;141142SmallVector<std::pair<GlobalVariable *, GlobalVariable *>, 32>143SameContentReplacements;144145size_t ChangesMade = 0;146size_t OldChangesMade = 0;147148// Iterate constant merging while we are still making progress. Merging two149// constants together may allow us to merge other constants together if the150// second level constants have initializers which point to the globals that151// were just merged.152while (true) {153// Find the canonical constants others will be merged with.154for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) {155// If this GV is dead, remove it.156GV.removeDeadConstantUsers();157if (GV.use_empty() && GV.hasLocalLinkage()) {158GV.eraseFromParent();159++ChangesMade;160continue;161}162163if (isUnmergeableGlobal(&GV, UsedGlobals))164continue;165166// This transformation is legal for weak ODR globals in the sense it167// doesn't change semantics, but we really don't want to perform it168// anyway; it's likely to pessimize code generation, and some tools169// (like the Darwin linker in cases involving CFString) don't expect it.170if (GV.isWeakForLinker())171continue;172173// Don't touch globals with metadata other then !dbg.174if (hasMetadataOtherThanDebugLoc(&GV))175continue;176177Constant *Init = GV.getInitializer();178179// Check to see if the initializer is already known.180GlobalVariable *&Slot = CMap[Init];181182// If this is the first constant we find or if the old one is local,183// replace with the current one. If the current is externally visible184// it cannot be replace, but can be the canonical constant we merge with.185bool FirstConstantFound = !Slot;186if (FirstConstantFound || IsBetterCanonical(GV, *Slot)) {187Slot = &GV;188LLVM_DEBUG(dbgs() << "Cmap[" << *Init << "] = " << GV.getName()189<< (FirstConstantFound ? "\n" : " (updated)\n"));190}191}192193// Identify all globals that can be merged together, filling in the194// SameContentReplacements vector. We cannot do the replacement in this pass195// because doing so may cause initializers of other globals to be rewritten,196// invalidating the Constant* pointers in CMap.197for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) {198if (isUnmergeableGlobal(&GV, UsedGlobals))199continue;200201// We can only replace constant with local linkage.202if (!GV.hasLocalLinkage())203continue;204205Constant *Init = GV.getInitializer();206207// Check to see if the initializer is already known.208auto Found = CMap.find(Init);209if (Found == CMap.end())210continue;211212GlobalVariable *Slot = Found->second;213if (Slot == &GV)214continue;215216if (makeMergeable(&GV, Slot) == CanMerge::No)217continue;218219// Make all uses of the duplicate constant use the canonical version.220LLVM_DEBUG(dbgs() << "Will replace: @" << GV.getName() << " -> @"221<< Slot->getName() << "\n");222SameContentReplacements.push_back(std::make_pair(&GV, Slot));223}224225// Now that we have figured out which replacements must be made, do them all226// now. This avoid invalidating the pointers in CMap, which are unneeded227// now.228for (unsigned i = 0, e = SameContentReplacements.size(); i != e; ++i) {229GlobalVariable *Old = SameContentReplacements[i].first;230GlobalVariable *New = SameContentReplacements[i].second;231replace(M, Old, New);232++ChangesMade;233++NumIdenticalMerged;234}235236if (ChangesMade == OldChangesMade)237break;238OldChangesMade = ChangesMade;239240SameContentReplacements.clear();241CMap.clear();242}243244return ChangesMade;245}246247PreservedAnalyses ConstantMergePass::run(Module &M, ModuleAnalysisManager &) {248if (!mergeConstants(M))249return PreservedAnalyses::all();250return PreservedAnalyses::none();251}252253254