xref: /llvm-project/flang/lib/Optimizer/Transforms/AddDebugInfo.cpp (revision fa5971c298c96c965ba6d8fb855867f23518aad4)
1 //===-------------- AddDebugInfo.cpp -- add debug info -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 //===----------------------------------------------------------------------===//
10 /// \file
11 /// This pass populates some debug information for the module and functions.
12 //===----------------------------------------------------------------------===//
13 
14 #include "DebugTypeGenerator.h"
15 #include "flang/Common/Version.h"
16 #include "flang/Optimizer/Builder/FIRBuilder.h"
17 #include "flang/Optimizer/Builder/Todo.h"
18 #include "flang/Optimizer/CodeGen/CGOps.h"
19 #include "flang/Optimizer/Dialect/FIRDialect.h"
20 #include "flang/Optimizer/Dialect/FIROps.h"
21 #include "flang/Optimizer/Dialect/FIRType.h"
22 #include "flang/Optimizer/Dialect/Support/FIRContext.h"
23 #include "flang/Optimizer/Support/InternalNames.h"
24 #include "flang/Optimizer/Transforms/Passes.h"
25 #include "mlir/Dialect/Func/IR/FuncOps.h"
26 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
27 #include "mlir/IR/Matchers.h"
28 #include "mlir/IR/TypeUtilities.h"
29 #include "mlir/Pass/Pass.h"
30 #include "mlir/Transforms/DialectConversion.h"
31 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
32 #include "mlir/Transforms/RegionUtils.h"
33 #include "llvm/BinaryFormat/Dwarf.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/raw_ostream.h"
38 
39 namespace fir {
40 #define GEN_PASS_DEF_ADDDEBUGINFO
41 #include "flang/Optimizer/Transforms/Passes.h.inc"
42 } // namespace fir
43 
44 #define DEBUG_TYPE "flang-add-debug-info"
45 
46 namespace {
47 
48 class AddDebugInfoPass : public fir::impl::AddDebugInfoBase<AddDebugInfoPass> {
49   void handleDeclareOp(fir::cg::XDeclareOp declOp,
50                        mlir::LLVM::DIFileAttr fileAttr,
51                        mlir::LLVM::DIScopeAttr scopeAttr,
52                        fir::DebugTypeGenerator &typeGen,
53                        mlir::SymbolTable *symbolTable);
54 
55 public:
56   AddDebugInfoPass(fir::AddDebugInfoOptions options) : Base(options) {}
57   void runOnOperation() override;
58 
59 private:
60   llvm::StringMap<mlir::LLVM::DIModuleAttr> moduleMap;
61 
62   mlir::LLVM::DIModuleAttr getOrCreateModuleAttr(
63       const std::string &name, mlir::LLVM::DIFileAttr fileAttr,
64       mlir::LLVM::DIScopeAttr scope, unsigned line, bool decl);
65 
66   void handleGlobalOp(fir::GlobalOp glocalOp, mlir::LLVM::DIFileAttr fileAttr,
67                       mlir::LLVM::DIScopeAttr scope,
68                       mlir::SymbolTable *symbolTable);
69 };
70 
71 static uint32_t getLineFromLoc(mlir::Location loc) {
72   uint32_t line = 1;
73   if (auto fileLoc = mlir::dyn_cast<mlir::FileLineColLoc>(loc))
74     line = fileLoc.getLine();
75   return line;
76 }
77 
78 bool debugInfoIsAlreadySet(mlir::Location loc) {
79   if (mlir::isa<mlir::FusedLoc>(loc))
80     return true;
81   return false;
82 }
83 
84 } // namespace
85 
86 void AddDebugInfoPass::handleDeclareOp(fir::cg::XDeclareOp declOp,
87                                        mlir::LLVM::DIFileAttr fileAttr,
88                                        mlir::LLVM::DIScopeAttr scopeAttr,
89                                        fir::DebugTypeGenerator &typeGen,
90                                        mlir::SymbolTable *symbolTable) {
91   mlir::MLIRContext *context = &getContext();
92   mlir::OpBuilder builder(context);
93   auto result = fir::NameUniquer::deconstruct(declOp.getUniqName());
94 
95   if (result.first != fir::NameUniquer::NameKind::VARIABLE)
96     return;
97 
98   // If this DeclareOp actually represents a global then treat it as such.
99   if (auto global = symbolTable->lookup<fir::GlobalOp>(declOp.getUniqName())) {
100     handleGlobalOp(global, fileAttr, scopeAttr, symbolTable);
101     return;
102   }
103 
104   // Only accept local variables.
105   if (result.second.procs.empty())
106     return;
107 
108   // FIXME: There may be cases where an argument is processed a bit before
109   // DeclareOp is generated. In that case, DeclareOp may point to an
110   // intermediate op and not to BlockArgument.
111   // Moreover, with MLIR inlining we cannot use the BlockArgument
112   // position to identify the original number of the dummy argument.
113   // If we want to keep running AddDebugInfoPass late, the dummy argument
114   // position in the argument list has to be expressed in FIR (e.g. as a
115   // constant attribute of [hl]fir.declare/fircg.ext_declare operation that has
116   // a dummy_scope operand).
117   unsigned argNo = 0;
118   if (fir::isDummyArgument(declOp.getMemref())) {
119     auto arg = llvm::cast<mlir::BlockArgument>(declOp.getMemref());
120     argNo = arg.getArgNumber() + 1;
121   }
122 
123   auto tyAttr = typeGen.convertType(fir::unwrapRefType(declOp.getType()),
124                                     fileAttr, scopeAttr, declOp.getLoc());
125 
126   auto localVarAttr = mlir::LLVM::DILocalVariableAttr::get(
127       context, scopeAttr, mlir::StringAttr::get(context, result.second.name),
128       fileAttr, getLineFromLoc(declOp.getLoc()), argNo, /* alignInBits*/ 0,
129       tyAttr);
130   declOp->setLoc(builder.getFusedLoc({declOp->getLoc()}, localVarAttr));
131 }
132 
133 // The `module` does not have a first class representation in the `FIR`. We
134 // extract information about it from the name of the identifiers and keep a
135 // map to avoid duplication.
136 mlir::LLVM::DIModuleAttr AddDebugInfoPass::getOrCreateModuleAttr(
137     const std::string &name, mlir::LLVM::DIFileAttr fileAttr,
138     mlir::LLVM::DIScopeAttr scope, unsigned line, bool decl) {
139   mlir::MLIRContext *context = &getContext();
140   mlir::LLVM::DIModuleAttr modAttr;
141   if (auto iter{moduleMap.find(name)}; iter != moduleMap.end()) {
142     modAttr = iter->getValue();
143   } else {
144     modAttr = mlir::LLVM::DIModuleAttr::get(
145         context, fileAttr, scope, mlir::StringAttr::get(context, name),
146         /* configMacros */ mlir::StringAttr(),
147         /* includePath */ mlir::StringAttr(),
148         /* apinotes */ mlir::StringAttr(), line, decl);
149     moduleMap[name] = modAttr;
150   }
151   return modAttr;
152 }
153 
154 void AddDebugInfoPass::handleGlobalOp(fir::GlobalOp globalOp,
155                                       mlir::LLVM::DIFileAttr fileAttr,
156                                       mlir::LLVM::DIScopeAttr scope,
157                                       mlir::SymbolTable *symbolTable) {
158   if (debugInfoIsAlreadySet(globalOp.getLoc()))
159     return;
160   mlir::ModuleOp module = getOperation();
161   mlir::MLIRContext *context = &getContext();
162   fir::DebugTypeGenerator typeGen(module);
163   mlir::OpBuilder builder(context);
164 
165   std::pair result = fir::NameUniquer::deconstruct(globalOp.getSymName());
166   if (result.first != fir::NameUniquer::NameKind::VARIABLE)
167     return;
168 
169   unsigned line = getLineFromLoc(globalOp.getLoc());
170 
171   // DWARF5 says following about the fortran modules:
172   // A Fortran 90 module may also be represented by a module entry
173   // (but no declaration attribute is warranted because Fortran has no concept
174   // of a corresponding module body).
175   // But in practice, compilers use declaration attribute with a module in cases
176   // where module was defined in another source file (only being used in this
177   // one). The isInitialized() seems to provide the right information
178   // but inverted. It is true where module is actually defined but false where
179   // it is used.
180   // FIXME: Currently we don't have the line number on which a module was
181   // declared. We are using a best guess of line - 1 where line is the source
182   // line of the first member of the module that we encounter.
183 
184   if (result.second.procs.empty()) {
185     // Only look for module if this variable is not part of a function.
186     if (result.second.modules.empty())
187       return;
188 
189     // Modules are generated at compile unit scope
190     if (mlir::LLVM::DISubprogramAttr sp =
191             mlir::dyn_cast_if_present<mlir::LLVM::DISubprogramAttr>(scope))
192       scope = sp.getCompileUnit();
193 
194     scope = getOrCreateModuleAttr(result.second.modules[0], fileAttr, scope,
195                                   line - 1, !globalOp.isInitialized());
196   }
197   mlir::LLVM::DITypeAttr diType = typeGen.convertType(
198       globalOp.getType(), fileAttr, scope, globalOp.getLoc());
199   auto gvAttr = mlir::LLVM::DIGlobalVariableAttr::get(
200       context, scope, mlir::StringAttr::get(context, result.second.name),
201       mlir::StringAttr::get(context, globalOp.getName()), fileAttr, line,
202       diType, /*isLocalToUnit*/ false,
203       /*isDefinition*/ globalOp.isInitialized(), /* alignInBits*/ 0);
204   globalOp->setLoc(builder.getFusedLoc({globalOp->getLoc()}, gvAttr));
205 }
206 
207 void AddDebugInfoPass::runOnOperation() {
208   mlir::ModuleOp module = getOperation();
209   mlir::MLIRContext *context = &getContext();
210   mlir::SymbolTable symbolTable(module);
211   mlir::OpBuilder builder(context);
212   llvm::StringRef fileName;
213   std::string filePath;
214   // We need 2 type of file paths here.
215   // 1. Name of the file as was presented to compiler. This can be absolute
216   // or relative to 2.
217   // 2. Current working directory
218   //
219   // We are also dealing with 2 different situations below. One is normal
220   // compilation where we will have a value in 'inputFilename' and we can
221   // obtain the current directory using 'current_path'.
222   // The 2nd case is when this pass is invoked directly from 'fir-opt' tool.
223   // In that case, 'inputFilename' may be empty. Location embedded in the
224   // module will be used to get file name and its directory.
225   if (inputFilename.empty()) {
226     if (auto fileLoc = mlir::dyn_cast<mlir::FileLineColLoc>(module.getLoc())) {
227       fileName = llvm::sys::path::filename(fileLoc.getFilename().getValue());
228       filePath = llvm::sys::path::parent_path(fileLoc.getFilename().getValue());
229     } else
230       fileName = "-";
231   } else {
232     fileName = inputFilename;
233     llvm::SmallString<256> cwd;
234     if (!llvm::sys::fs::current_path(cwd))
235       filePath = cwd.str();
236   }
237 
238   mlir::LLVM::DIFileAttr fileAttr =
239       mlir::LLVM::DIFileAttr::get(context, fileName, filePath);
240   mlir::StringAttr producer =
241       mlir::StringAttr::get(context, Fortran::common::getFlangFullVersion());
242   mlir::LLVM::DICompileUnitAttr cuAttr = mlir::LLVM::DICompileUnitAttr::get(
243       mlir::DistinctAttr::create(mlir::UnitAttr::get(context)),
244       llvm::dwarf::getLanguage("DW_LANG_Fortran95"), fileAttr, producer,
245       isOptimized, debugLevel);
246 
247   module.walk([&](mlir::func::FuncOp funcOp) {
248     mlir::Location l = funcOp->getLoc();
249     // If fused location has already been created then nothing to do
250     // Otherwise, create a fused location.
251     if (debugInfoIsAlreadySet(l))
252       return;
253 
254     unsigned int CC = (funcOp.getName() == fir::NameUniquer::doProgramEntry())
255                           ? llvm::dwarf::getCallingConvention("DW_CC_program")
256                           : llvm::dwarf::getCallingConvention("DW_CC_normal");
257 
258     if (auto funcLoc = mlir::dyn_cast<mlir::FileLineColLoc>(l)) {
259       fileName = llvm::sys::path::filename(funcLoc.getFilename().getValue());
260       filePath = llvm::sys::path::parent_path(funcLoc.getFilename().getValue());
261     }
262 
263     mlir::StringAttr fullName =
264         mlir::StringAttr::get(context, funcOp.getName());
265     mlir::Attribute attr = funcOp->getAttr(fir::getInternalFuncNameAttrName());
266     mlir::StringAttr funcName =
267         (attr) ? mlir::cast<mlir::StringAttr>(attr)
268                : mlir::StringAttr::get(context, funcOp.getName());
269 
270     auto result = fir::NameUniquer::deconstruct(funcName);
271     funcName = mlir::StringAttr::get(context, result.second.name);
272 
273     llvm::SmallVector<mlir::LLVM::DITypeAttr> types;
274     fir::DebugTypeGenerator typeGen(module);
275     for (auto resTy : funcOp.getResultTypes()) {
276       auto tyAttr =
277           typeGen.convertType(resTy, fileAttr, cuAttr, funcOp.getLoc());
278       types.push_back(tyAttr);
279     }
280     for (auto inTy : funcOp.getArgumentTypes()) {
281       auto tyAttr = typeGen.convertType(fir::unwrapRefType(inTy), fileAttr,
282                                         cuAttr, funcOp.getLoc());
283       types.push_back(tyAttr);
284     }
285 
286     mlir::LLVM::DISubroutineTypeAttr subTypeAttr =
287         mlir::LLVM::DISubroutineTypeAttr::get(context, CC, types);
288     mlir::LLVM::DIFileAttr funcFileAttr =
289         mlir::LLVM::DIFileAttr::get(context, fileName, filePath);
290 
291     // Only definitions need a distinct identifier and a compilation unit.
292     mlir::DistinctAttr id;
293     mlir::LLVM::DIScopeAttr Scope = fileAttr;
294     mlir::LLVM::DICompileUnitAttr compilationUnit;
295     mlir::LLVM::DISubprogramFlags subprogramFlags =
296         mlir::LLVM::DISubprogramFlags{};
297     if (isOptimized)
298       subprogramFlags = mlir::LLVM::DISubprogramFlags::Optimized;
299     if (!funcOp.isExternal()) {
300       id = mlir::DistinctAttr::create(mlir::UnitAttr::get(context));
301       compilationUnit = cuAttr;
302       subprogramFlags =
303           subprogramFlags | mlir::LLVM::DISubprogramFlags::Definition;
304     }
305     unsigned line = getLineFromLoc(l);
306     if (!result.second.modules.empty())
307       Scope = getOrCreateModuleAttr(result.second.modules[0], fileAttr, cuAttr,
308                                     line - 1, false);
309 
310     auto spAttr = mlir::LLVM::DISubprogramAttr::get(
311         context, id, compilationUnit, Scope, funcName, fullName, funcFileAttr,
312         line, line, subprogramFlags, subTypeAttr);
313     funcOp->setLoc(builder.getFusedLoc({funcOp->getLoc()}, spAttr));
314 
315     // Don't process variables if user asked for line tables only.
316     if (debugLevel == mlir::LLVM::DIEmissionKind::LineTablesOnly)
317       return;
318 
319     funcOp.walk([&](fir::cg::XDeclareOp declOp) {
320       handleDeclareOp(declOp, fileAttr, spAttr, typeGen, &symbolTable);
321     });
322   });
323   // Process any global which was not processed through DeclareOp.
324   if (debugLevel == mlir::LLVM::DIEmissionKind::Full) {
325     // Process 'GlobalOp' only if full debug info is requested.
326     for (auto globalOp : module.getOps<fir::GlobalOp>())
327       handleGlobalOp(globalOp, fileAttr, cuAttr, &symbolTable);
328   }
329 }
330 
331 std::unique_ptr<mlir::Pass>
332 fir::createAddDebugInfoPass(fir::AddDebugInfoOptions options) {
333   return std::make_unique<AddDebugInfoPass>(options);
334 }
335