Index: tools/llvm-project/llvm/lib/Transforms/IPO/GlobalOpt.cpp =================================================================== --- tools/llvm-project/llvm/lib/Transforms/IPO/GlobalOpt.cpp +++ tools/llvm-project/llvm/lib/Transforms/IPO/GlobalOpt.cpp @@ -28,6 +28,7 @@ #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" +#include "llvm/IR/DIBuilder.h" #include "llvm/IR/GetElementPtrTypeIterator.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" @@ -86,6 +87,7 @@ const GlobalStatus &GS); bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn); + std::unique_ptr DIB; TargetLibraryInfo *TLI; SmallSet NotDiscardableComdats; }; @@ -1749,6 +1751,16 @@ } } +static DIGlobalVariable *FindDebugInfo(GlobalVariable *GV) { + DebugInfoFinder F; + F.processModule(*GV->getParent()); + for (DICompileUnit *DIC : F.compile_units()) + for (DIGlobalVariable *DIG : DIC->getGlobalVariables()) + if (DIG->getVariable() == GV) + return DIG; + return nullptr; +} + /// Analyze the specified global variable and optimize /// it if possible. If we make a change, return true. bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV, @@ -1776,11 +1788,26 @@ // FIXME: Pass Global's alignment when globals have alignment AllocaInst *Alloca = new AllocaInst(ElemTy, nullptr, GV->getName(), &FirstI); + StoreInst *Store = nullptr; if (!isa(GV->getInitializer())) - new StoreInst(GV->getInitializer(), Alloca, &FirstI); + Store = new StoreInst(GV->getInitializer(), Alloca, &FirstI); + + if (DIGlobalVariable *D = FindDebugInfo(GV)) { + if (DIType *T = dyn_cast(D->getRawType())) { + DEBUG(dbgs() << " ... and transferring its DebugInfo\n"); + auto *Scope = D->getScope(); + auto *Variable = DIB->createAutoVariable(Scope, + D->getLinkageName(), + D->getFile(), D->getLine(), + T); + auto *E = DIB->createExpression(); + auto *DL = DILocation::get(GV->getContext(), D->getLine(), 0, + Scope); + DIB->insertDeclare(Alloca, Variable, E, DL, Store); + } makeAllConstantUsesInstructions(GV); - + GV->replaceAllUsesWith(Alloca); GV->eraseFromParent(); ++NumLocalized; @@ -3062,6 +3089,7 @@ } bool GlobalOpt::runOnModule(Module &M) { + DIB = llvm::make_unique(M, /*AllowUnresolved=*/ false); bool Changed = false; auto &DL = M.getDataLayout();