xref: /llvm-project/flang/lib/Optimizer/Transforms/AddDebugInfo.cpp (revision 6fd46089c9fbd5b22bb67ac3d6196fe70ba684c6)
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                       fir::cg::XDeclareOp declOp);
70   void handleFuncOp(mlir::func::FuncOp funcOp, mlir::LLVM::DIFileAttr fileAttr,
71                     mlir::LLVM::DICompileUnitAttr cuAttr,
72                     mlir::SymbolTable *symbolTable);
73 };
74 
75 static uint32_t getLineFromLoc(mlir::Location loc) {
76   uint32_t line = 1;
77   if (auto fileLoc = mlir::dyn_cast<mlir::FileLineColLoc>(loc))
78     line = fileLoc.getLine();
79   return line;
80 }
81 
82 bool debugInfoIsAlreadySet(mlir::Location loc) {
83   if (mlir::isa<mlir::FusedLoc>(loc)) {
84     if (loc->findInstanceOf<mlir::FusedLocWith<fir::LocationKindAttr>>())
85       return false;
86     return true;
87   }
88   return false;
89 }
90 
91 } // namespace
92 
93 void AddDebugInfoPass::handleDeclareOp(fir::cg::XDeclareOp declOp,
94                                        mlir::LLVM::DIFileAttr fileAttr,
95                                        mlir::LLVM::DIScopeAttr scopeAttr,
96                                        fir::DebugTypeGenerator &typeGen,
97                                        mlir::SymbolTable *symbolTable) {
98   mlir::MLIRContext *context = &getContext();
99   mlir::OpBuilder builder(context);
100   auto result = fir::NameUniquer::deconstruct(declOp.getUniqName());
101 
102   if (result.first != fir::NameUniquer::NameKind::VARIABLE)
103     return;
104   // If this DeclareOp actually represents a global then treat it as such.
105   if (auto global = symbolTable->lookup<fir::GlobalOp>(declOp.getUniqName())) {
106     handleGlobalOp(global, fileAttr, scopeAttr, symbolTable, declOp);
107     return;
108   }
109 
110   // Only accept local variables.
111   if (result.second.procs.empty())
112     return;
113 
114   // FIXME: There may be cases where an argument is processed a bit before
115   // DeclareOp is generated. In that case, DeclareOp may point to an
116   // intermediate op and not to BlockArgument.
117   // Moreover, with MLIR inlining we cannot use the BlockArgument
118   // position to identify the original number of the dummy argument.
119   // If we want to keep running AddDebugInfoPass late, the dummy argument
120   // position in the argument list has to be expressed in FIR (e.g. as a
121   // constant attribute of [hl]fir.declare/fircg.ext_declare operation that has
122   // a dummy_scope operand).
123   unsigned argNo = 0;
124   if (fir::isDummyArgument(declOp.getMemref())) {
125     auto arg = llvm::cast<mlir::BlockArgument>(declOp.getMemref());
126     argNo = arg.getArgNumber() + 1;
127   }
128 
129   auto tyAttr = typeGen.convertType(fir::unwrapRefType(declOp.getType()),
130                                     fileAttr, scopeAttr, declOp);
131 
132   auto localVarAttr = mlir::LLVM::DILocalVariableAttr::get(
133       context, scopeAttr, mlir::StringAttr::get(context, result.second.name),
134       fileAttr, getLineFromLoc(declOp.getLoc()), argNo, /* alignInBits*/ 0,
135       tyAttr, mlir::LLVM::DIFlags::Zero);
136   declOp->setLoc(builder.getFusedLoc({declOp->getLoc()}, localVarAttr));
137 }
138 
139 // The `module` does not have a first class representation in the `FIR`. We
140 // extract information about it from the name of the identifiers and keep a
141 // map to avoid duplication.
142 mlir::LLVM::DIModuleAttr AddDebugInfoPass::getOrCreateModuleAttr(
143     const std::string &name, mlir::LLVM::DIFileAttr fileAttr,
144     mlir::LLVM::DIScopeAttr scope, unsigned line, bool decl) {
145   mlir::MLIRContext *context = &getContext();
146   mlir::LLVM::DIModuleAttr modAttr;
147   if (auto iter{moduleMap.find(name)}; iter != moduleMap.end()) {
148     modAttr = iter->getValue();
149   } else {
150     modAttr = mlir::LLVM::DIModuleAttr::get(
151         context, fileAttr, scope, mlir::StringAttr::get(context, name),
152         /* configMacros */ mlir::StringAttr(),
153         /* includePath */ mlir::StringAttr(),
154         /* apinotes */ mlir::StringAttr(), line, decl);
155     moduleMap[name] = modAttr;
156   }
157   return modAttr;
158 }
159 
160 void AddDebugInfoPass::handleGlobalOp(fir::GlobalOp globalOp,
161                                       mlir::LLVM::DIFileAttr fileAttr,
162                                       mlir::LLVM::DIScopeAttr scope,
163                                       mlir::SymbolTable *symbolTable,
164                                       fir::cg::XDeclareOp declOp) {
165   if (debugInfoIsAlreadySet(globalOp.getLoc()))
166     return;
167   mlir::ModuleOp module = getOperation();
168   mlir::MLIRContext *context = &getContext();
169   fir::DebugTypeGenerator typeGen(module);
170   mlir::OpBuilder builder(context);
171 
172   std::pair result = fir::NameUniquer::deconstruct(globalOp.getSymName());
173   if (result.first != fir::NameUniquer::NameKind::VARIABLE)
174     return;
175 
176   unsigned line = getLineFromLoc(globalOp.getLoc());
177 
178   // DWARF5 says following about the fortran modules:
179   // A Fortran 90 module may also be represented by a module entry
180   // (but no declaration attribute is warranted because Fortran has no concept
181   // of a corresponding module body).
182   // But in practice, compilers use declaration attribute with a module in cases
183   // where module was defined in another source file (only being used in this
184   // one). The isInitialized() seems to provide the right information
185   // but inverted. It is true where module is actually defined but false where
186   // it is used.
187   // FIXME: Currently we don't have the line number on which a module was
188   // declared. We are using a best guess of line - 1 where line is the source
189   // line of the first member of the module that we encounter.
190 
191   if (result.second.procs.empty()) {
192     // Only look for module if this variable is not part of a function.
193     if (result.second.modules.empty())
194       return;
195 
196     // Modules are generated at compile unit scope
197     if (mlir::LLVM::DISubprogramAttr sp =
198             mlir::dyn_cast_if_present<mlir::LLVM::DISubprogramAttr>(scope))
199       scope = sp.getCompileUnit();
200 
201     scope = getOrCreateModuleAttr(result.second.modules[0], fileAttr, scope,
202                                   line - 1, !globalOp.isInitialized());
203   }
204   mlir::LLVM::DITypeAttr diType =
205       typeGen.convertType(globalOp.getType(), fileAttr, scope, declOp);
206   auto gvAttr = mlir::LLVM::DIGlobalVariableAttr::get(
207       context, scope, mlir::StringAttr::get(context, result.second.name),
208       mlir::StringAttr::get(context, globalOp.getName()), fileAttr, line,
209       diType, /*isLocalToUnit*/ false,
210       /*isDefinition*/ globalOp.isInitialized(), /* alignInBits*/ 0);
211   globalOp->setLoc(builder.getFusedLoc({globalOp->getLoc()}, gvAttr));
212 }
213 
214 void AddDebugInfoPass::handleFuncOp(mlir::func::FuncOp funcOp,
215                                     mlir::LLVM::DIFileAttr fileAttr,
216                                     mlir::LLVM::DICompileUnitAttr cuAttr,
217                                     mlir::SymbolTable *symbolTable) {
218   mlir::Location l = funcOp->getLoc();
219   // If fused location has already been created then nothing to do
220   // Otherwise, create a fused location.
221   if (debugInfoIsAlreadySet(l))
222     return;
223 
224   mlir::ModuleOp module = getOperation();
225   mlir::MLIRContext *context = &getContext();
226   mlir::OpBuilder builder(context);
227   llvm::StringRef fileName(fileAttr.getName());
228   llvm::StringRef filePath(fileAttr.getDirectory());
229   unsigned int CC = (funcOp.getName() == fir::NameUniquer::doProgramEntry())
230                         ? llvm::dwarf::getCallingConvention("DW_CC_program")
231                         : llvm::dwarf::getCallingConvention("DW_CC_normal");
232 
233   if (auto funcLoc = mlir::dyn_cast<mlir::FileLineColLoc>(l)) {
234     fileName = llvm::sys::path::filename(funcLoc.getFilename().getValue());
235     filePath = llvm::sys::path::parent_path(funcLoc.getFilename().getValue());
236   }
237 
238   mlir::StringAttr fullName = mlir::StringAttr::get(context, funcOp.getName());
239   mlir::Attribute attr = funcOp->getAttr(fir::getInternalFuncNameAttrName());
240   mlir::StringAttr funcName =
241       (attr) ? mlir::cast<mlir::StringAttr>(attr)
242              : mlir::StringAttr::get(context, funcOp.getName());
243 
244   auto result = fir::NameUniquer::deconstruct(funcName);
245   funcName = mlir::StringAttr::get(context, result.second.name);
246 
247   llvm::SmallVector<mlir::LLVM::DITypeAttr> types;
248   fir::DebugTypeGenerator typeGen(module);
249   for (auto resTy : funcOp.getResultTypes()) {
250     auto tyAttr =
251         typeGen.convertType(resTy, fileAttr, cuAttr, /*declOp=*/nullptr);
252     types.push_back(tyAttr);
253   }
254   for (auto inTy : funcOp.getArgumentTypes()) {
255     auto tyAttr = typeGen.convertType(fir::unwrapRefType(inTy), fileAttr,
256                                       cuAttr, /*declOp=*/nullptr);
257     types.push_back(tyAttr);
258   }
259 
260   mlir::LLVM::DISubroutineTypeAttr subTypeAttr =
261       mlir::LLVM::DISubroutineTypeAttr::get(context, CC, types);
262   mlir::LLVM::DIFileAttr funcFileAttr =
263       mlir::LLVM::DIFileAttr::get(context, fileName, filePath);
264 
265   // Only definitions need a distinct identifier and a compilation unit.
266   mlir::DistinctAttr id;
267   mlir::LLVM::DIScopeAttr Scope = fileAttr;
268   mlir::LLVM::DICompileUnitAttr compilationUnit;
269   mlir::LLVM::DISubprogramFlags subprogramFlags =
270       mlir::LLVM::DISubprogramFlags{};
271   if (isOptimized)
272     subprogramFlags = mlir::LLVM::DISubprogramFlags::Optimized;
273   if (!funcOp.isExternal()) {
274     id = mlir::DistinctAttr::create(mlir::UnitAttr::get(context));
275     compilationUnit = cuAttr;
276     subprogramFlags =
277         subprogramFlags | mlir::LLVM::DISubprogramFlags::Definition;
278   }
279   unsigned line = getLineFromLoc(l);
280   if (fir::isInternalProcedure(funcOp)) {
281     // For contained functions, the scope is the parent subroutine.
282     mlir::SymbolRefAttr sym = mlir::cast<mlir::SymbolRefAttr>(
283         funcOp->getAttr(fir::getHostSymbolAttrName()));
284     if (sym) {
285       if (auto func =
286               symbolTable->lookup<mlir::func::FuncOp>(sym.getLeafReference())) {
287         // Make sure that parent is processed.
288         handleFuncOp(func, fileAttr, cuAttr, symbolTable);
289         if (auto fusedLoc =
290                 mlir::dyn_cast_if_present<mlir::FusedLoc>(func.getLoc())) {
291           if (auto spAttr =
292                   mlir::dyn_cast_if_present<mlir::LLVM::DISubprogramAttr>(
293                       fusedLoc.getMetadata()))
294             Scope = spAttr;
295         }
296       }
297     }
298   } else if (!result.second.modules.empty()) {
299     Scope = getOrCreateModuleAttr(result.second.modules[0], fileAttr, cuAttr,
300                                   line - 1, false);
301   }
302 
303   auto spAttr = mlir::LLVM::DISubprogramAttr::get(
304       context, id, compilationUnit, Scope, funcName, fullName, funcFileAttr,
305       line, line, subprogramFlags, subTypeAttr);
306   funcOp->setLoc(builder.getFusedLoc({funcOp->getLoc()}, spAttr));
307 
308   // Don't process variables if user asked for line tables only.
309   if (debugLevel == mlir::LLVM::DIEmissionKind::LineTablesOnly)
310     return;
311 
312   funcOp.walk([&](fir::cg::XDeclareOp declOp) {
313     handleDeclareOp(declOp, fileAttr, spAttr, typeGen, symbolTable);
314   });
315 }
316 
317 void AddDebugInfoPass::runOnOperation() {
318   mlir::ModuleOp module = getOperation();
319   mlir::MLIRContext *context = &getContext();
320   mlir::SymbolTable symbolTable(module);
321   llvm::StringRef fileName;
322   std::string filePath;
323   // We need 2 type of file paths here.
324   // 1. Name of the file as was presented to compiler. This can be absolute
325   // or relative to 2.
326   // 2. Current working directory
327   //
328   // We are also dealing with 2 different situations below. One is normal
329   // compilation where we will have a value in 'inputFilename' and we can
330   // obtain the current directory using 'current_path'.
331   // The 2nd case is when this pass is invoked directly from 'fir-opt' tool.
332   // In that case, 'inputFilename' may be empty. Location embedded in the
333   // module will be used to get file name and its directory.
334   if (inputFilename.empty()) {
335     if (auto fileLoc = mlir::dyn_cast<mlir::FileLineColLoc>(module.getLoc())) {
336       fileName = llvm::sys::path::filename(fileLoc.getFilename().getValue());
337       filePath = llvm::sys::path::parent_path(fileLoc.getFilename().getValue());
338     } else
339       fileName = "-";
340   } else {
341     fileName = inputFilename;
342     llvm::SmallString<256> cwd;
343     if (!llvm::sys::fs::current_path(cwd))
344       filePath = cwd.str();
345   }
346 
347   mlir::LLVM::DIFileAttr fileAttr =
348       mlir::LLVM::DIFileAttr::get(context, fileName, filePath);
349   mlir::StringAttr producer =
350       mlir::StringAttr::get(context, Fortran::common::getFlangFullVersion());
351   mlir::LLVM::DICompileUnitAttr cuAttr = mlir::LLVM::DICompileUnitAttr::get(
352       mlir::DistinctAttr::create(mlir::UnitAttr::get(context)),
353       llvm::dwarf::getLanguage("DW_LANG_Fortran95"), fileAttr, producer,
354       isOptimized, debugLevel);
355 
356   module.walk([&](mlir::func::FuncOp funcOp) {
357     handleFuncOp(funcOp, fileAttr, cuAttr, &symbolTable);
358   });
359   // Process any global which was not processed through DeclareOp.
360   if (debugLevel == mlir::LLVM::DIEmissionKind::Full) {
361     // Process 'GlobalOp' only if full debug info is requested.
362     for (auto globalOp : module.getOps<fir::GlobalOp>())
363       handleGlobalOp(globalOp, fileAttr, cuAttr, &symbolTable,
364                      /*declOp=*/nullptr);
365   }
366 }
367 
368 std::unique_ptr<mlir::Pass>
369 fir::createAddDebugInfoPass(fir::AddDebugInfoOptions options) {
370   return std::make_unique<AddDebugInfoPass>(options);
371 }
372