9a88cd000d1adb7dfca8db0a15c80afea635cbaf
[oota-llvm.git] / lib / Transforms / Instrumentation / DebugIR.cpp
1 //===--- DebugIR.cpp - Transform debug metadata to allow debugging IR -----===//
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 //
10 // A Module transform pass that emits a succinct version of the IR and replaces
11 // the source file metadata to allow debuggers to step through the IR.
12 //
13 // FIXME: instead of replacing debug metadata, this pass should allow for
14 // additional metadata to be used to point capable debuggers to the IR file
15 // without destroying the mapping to the original source file.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "debug-ir"
20
21 #include "llvm/ADT/ValueMap.h"
22 #include "DebugIR.h"
23 #include "llvm/Assembly/AssemblyAnnotationWriter.h"
24 #include "llvm/DIBuilder.h"
25 #include "llvm/DebugInfo.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Instruction.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/InstVisitor.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/ToolOutputFile.h"
36 #include "llvm/Transforms/Instrumentation.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
38 #include <string>
39
40 #define STR_HELPER(x) #x
41 #define STR(x) STR_HELPER(x)
42
43 using namespace llvm;
44
45 namespace {
46
47 /// Builds a map of Value* to line numbers on which the Value appears in a
48 /// textual representation of the IR by plugging into the AssemblyWriter by
49 /// masquerading as an AssemblyAnnotationWriter.
50 class ValueToLineMap : public AssemblyAnnotationWriter {
51   ValueMap<const Value *, unsigned int> Lines;
52   typedef ValueMap<const Value *, unsigned int>::const_iterator LineIter;
53
54   void addEntry(const Value *V, formatted_raw_ostream &Out) {
55     Out.flush();
56     Lines.insert(std::make_pair(V, Out.getLine() + 1));
57   }
58
59 public:
60
61   /// Prints Module to a null buffer in order to build the map of Value pointers
62   /// to line numbers.
63   ValueToLineMap(const Module *M) {
64     raw_null_ostream ThrowAway;
65     M->print(ThrowAway, this);
66   }
67
68   // This function is called after an Instruction, GlobalValue, or GlobalAlias
69   // is printed.
70   void printInfoComment(const Value &V, formatted_raw_ostream &Out) {
71     addEntry(&V, Out);
72   }
73
74   void emitFunctionAnnot(const Function *F, formatted_raw_ostream &Out) {
75     addEntry(F, Out);
76   }
77
78   /// If V appears on a line in the textual IR representation, sets Line to the
79   /// line number and returns true, otherwise returns false.
80   bool getLine(const Value *V, unsigned int &Line) const {
81     LineIter i = Lines.find(V);
82     if (i != Lines.end()) {
83       Line = i->second;
84       return true;
85     }
86     return false;
87   }
88 };
89
90 /// Removes debug intrisncs like llvm.dbg.declare and llvm.dbg.value.
91 class DebugIntrinsicsRemover : public InstVisitor<DebugIntrinsicsRemover> {
92   void remove(Instruction &I) { I.eraseFromParent(); }
93
94 public:
95   static void process(Module &M) {
96     DebugIntrinsicsRemover Remover;
97     Remover.visit(&M);
98   }
99   void visitDbgDeclareInst(DbgDeclareInst &I) { remove(I); }
100   void visitDbgValueInst(DbgValueInst &I) { remove(I); }
101   void visitDbgInfoIntrinsic(DbgInfoIntrinsic &I) { remove(I); }
102 };
103
104 /// Removes debug metadata (!dbg) nodes from all instructions, and optionally
105 /// metadata named "llvm.dbg.cu" if RemoveNamedInfo is true.
106 class DebugMetadataRemover : public InstVisitor<DebugMetadataRemover> {
107   bool RemoveNamedInfo;
108
109 public:
110   static void process(Module &M, bool RemoveNamedInfo = true) {
111     DebugMetadataRemover Remover(RemoveNamedInfo);
112     Remover.run(&M);
113   }
114
115   DebugMetadataRemover(bool RemoveNamedInfo)
116       : RemoveNamedInfo(RemoveNamedInfo) {}
117
118   void visitInstruction(Instruction &I) {
119     if (I.getMetadata(LLVMContext::MD_dbg))
120       I.setMetadata(LLVMContext::MD_dbg, 0);
121   }
122
123   void run(Module *M) {
124     // Remove debug metadata attached to instructions
125     visit(M);
126
127     if (RemoveNamedInfo) {
128       // Remove CU named metadata (and all children nodes)
129       NamedMDNode *Node = M->getNamedMetadata("llvm.dbg.cu");
130       if (Node)
131         M->eraseNamedMetadata(Node);
132     }
133   }
134 };
135
136 /// Updates debug metadata in a Module:
137 ///   - changes Filename/Directory to values provided on construction
138 ///   - adds/updates line number (DebugLoc) entries associated with each
139 ///     instruction to reflect the instruction's location in an LLVM IR file
140 class DIUpdater : public InstVisitor<DIUpdater> {
141   /// Builder of debug information
142   DIBuilder Builder;
143
144   /// Helper for type attributes/sizes/etc
145   DataLayout Layout;
146
147   /// Map of Value* to line numbers
148   const ValueToLineMap LineTable;
149
150   /// Map of Value* (in original Module) to Value* (in optional cloned Module)
151   const ValueToValueMapTy *VMap;
152
153   /// Directory of debug metadata
154   DebugInfoFinder Finder;
155
156   /// Source filename and directory
157   StringRef Filename;
158   StringRef Directory;
159
160   // CU nodes needed when creating DI subprograms
161   MDNode *FileNode;
162   MDNode *LexicalBlockFileNode;
163   const MDNode *CUNode;
164
165   ValueMap<const Function *, MDNode *> SubprogramDescriptors;
166   DenseMap<const Type *, MDNode *> TypeDescriptors;
167
168 public:
169   DIUpdater(Module &M, StringRef Filename = StringRef(),
170             StringRef Directory = StringRef(), const Module *DisplayM = 0,
171             const ValueToValueMapTy *VMap = 0)
172       : Builder(M), Layout(&M), LineTable(DisplayM ? DisplayM : &M), VMap(VMap),
173         Finder(), Filename(Filename), Directory(Directory), FileNode(0),
174         LexicalBlockFileNode(0), CUNode(0) {
175     Finder.processModule(M);
176     visit(&M);
177   }
178
179   ~DIUpdater() { Builder.finalize(); }
180
181   void visitModule(Module &M) {
182     if (Finder.compile_unit_count() > 1)
183       report_fatal_error("DebugIR pass supports only a signle compile unit per "
184                          "Module.");
185     createCompileUnit(
186         Finder.compile_unit_count() == 1 ? *Finder.compile_unit_begin() : 0);
187   }
188
189   void visitFunction(Function &F) {
190     if (F.isDeclaration() || findDISubprogram(&F))
191       return;
192
193     StringRef MangledName = F.getName();
194     DICompositeType Sig = createFunctionSignature(&F);
195
196     // find line of function declaration
197     unsigned Line = 0;
198     if (!findLine(&F, Line)) {
199       DEBUG(dbgs() << "WARNING: No line for Function " << F.getName().str()
200                    << "\n");
201       return;
202     }
203
204     Instruction *FirstInst = F.begin()->begin();
205     unsigned ScopeLine = 0;
206     if (!findLine(FirstInst, ScopeLine)) {
207       DEBUG(dbgs() << "WARNING: No line for 1st Instruction in Function "
208                    << F.getName().str() << "\n");
209       return;
210     }
211
212     bool Local = F.hasInternalLinkage();
213     bool IsDefinition = !F.isDeclaration();
214     bool IsOptimized = false;
215
216     int FuncFlags = llvm::DIDescriptor::FlagPrototyped;
217     assert(CUNode && FileNode);
218     DISubprogram Sub = Builder.createFunction(
219         DICompileUnit(CUNode), F.getName(), MangledName, DIFile(FileNode), Line,
220         Sig, Local, IsDefinition, ScopeLine, FuncFlags, IsOptimized, &F);
221     assert(Sub.isSubprogram());
222     DEBUG(dbgs() << "create subprogram mdnode " << *Sub << ": "
223                  << "\n");
224
225     SubprogramDescriptors.insert(std::make_pair(&F, Sub));
226   }
227
228   void visitInstruction(Instruction &I) {
229     DebugLoc Loc(I.getDebugLoc());
230
231     /// If a ValueToValueMap is provided, use it to get the real instruction as
232     /// the line table was generated on a clone of the module on which we are
233     /// operating.
234     Value *RealInst = 0;
235     if (VMap)
236       RealInst = VMap->lookup(&I);
237
238     if (!RealInst)
239       RealInst = &I;
240
241     unsigned Col = 0; // FIXME: support columns
242     unsigned Line;
243     if (!LineTable.getLine(RealInst, Line)) {
244       // Instruction has no line, it may have been removed (in the module that
245       // will be passed to the debugger) so there is nothing to do here.
246       DEBUG(dbgs() << "WARNING: no LineTable entry for instruction " << RealInst
247                    << "\n");
248       DEBUG(RealInst->dump());
249       return;
250     }
251
252     DebugLoc NewLoc;
253     if (!Loc.isUnknown())
254       // I had a previous debug location: re-use the DebugLoc
255       NewLoc = DebugLoc::get(Line, Col, Loc.getScope(RealInst->getContext()),
256                              Loc.getInlinedAt(RealInst->getContext()));
257     else if (MDNode *scope = findScope(&I))
258       NewLoc = DebugLoc::get(Line, Col, scope, 0);
259     else {
260       DEBUG(dbgs() << "WARNING: no valid scope for instruction " << &I
261                    << ". no DebugLoc will be present."
262                    << "\n");
263       return;
264     }
265
266     addDebugLocation(I, NewLoc);
267   }
268
269 private:
270
271   void createCompileUnit(MDNode *CUToReplace) {
272     std::string Flags;
273     bool IsOptimized = false;
274     StringRef Producer;
275     unsigned RuntimeVersion(0);
276     StringRef SplitName;
277
278     if (CUToReplace) {
279       // save fields from existing CU to re-use in the new CU
280       DICompileUnit ExistingCU(CUToReplace);
281       Producer = ExistingCU.getProducer();
282       IsOptimized = ExistingCU.isOptimized();
283       Flags = ExistingCU.getFlags();
284       RuntimeVersion = ExistingCU.getRunTimeVersion();
285       SplitName = ExistingCU.getSplitDebugFilename();
286     } else {
287       Producer =
288           "LLVM Version " STR(LLVM_VERSION_MAJOR) "." STR(LLVM_VERSION_MINOR);
289     }
290
291     CUNode =
292         Builder.createCompileUnit(dwarf::DW_LANG_C99, Filename, Directory,
293                                   Producer, IsOptimized, Flags, RuntimeVersion);
294
295     if (CUToReplace)
296       CUToReplace->replaceAllUsesWith(const_cast<MDNode *>(CUNode));
297
298     DICompileUnit CU(CUNode);
299     FileNode = Builder.createFile(Filename, Directory);
300     LexicalBlockFileNode = Builder.createLexicalBlockFile(CU, DIFile(FileNode));
301   }
302
303   /// Returns the MDNode* that represents the DI scope to associate with I
304   MDNode *findScope(const Instruction *I) {
305     const Function *F = I->getParent()->getParent();
306     if (MDNode *ret = findDISubprogram(F))
307       return ret;
308
309     DEBUG(dbgs() << "WARNING: Using fallback lexical block file scope "
310                  << LexicalBlockFileNode << " as scope for instruction " << I
311                  << "\n");
312     return LexicalBlockFileNode;
313   }
314
315   /// Returns the MDNode* that is the descriptor for F
316   MDNode *findDISubprogram(const Function *F) {
317     typedef ValueMap<const Function *, MDNode *>::const_iterator FuncNodeIter;
318     FuncNodeIter i = SubprogramDescriptors.find(F);
319     if (i != SubprogramDescriptors.end())
320       return i->second;
321
322     DEBUG(dbgs() << "searching for DI scope node for Function " << F
323                  << " in a list of " << Finder.subprogram_count()
324                  << " subprogram nodes"
325                  << "\n");
326
327     for (DebugInfoFinder::iterator i = Finder.subprogram_begin(),
328                                    e = Finder.subprogram_end();
329          i != e; ++i) {
330       DISubprogram S(*i);
331       if (S.getFunction() == F) {
332         DEBUG(dbgs() << "Found DISubprogram " << *i << " for function "
333                      << S.getFunction() << "\n");
334         return *i;
335       }
336     }
337     DEBUG(dbgs() << "unable to find DISubprogram node for function "
338                  << F->getName().str() << "\n");
339     return 0;
340   }
341
342   /// Sets Line to the line number on which V appears and returns true. If a
343   /// line location for V is not found, returns false.
344   bool findLine(const Value *V, unsigned &Line) {
345     if (LineTable.getLine(V, Line))
346       return true;
347
348     if (VMap) {
349       Value *mapped = VMap->lookup(V);
350       if (mapped && LineTable.getLine(mapped, Line))
351         return true;
352     }
353     return false;
354   }
355
356   std::string getTypeName(Type *T) {
357     std::string TypeName;
358     raw_string_ostream TypeStream(TypeName);
359     T->print(TypeStream);
360     TypeStream.flush();
361     return TypeName;
362   }
363
364   /// Returns the MDNode that represents type T if it is already created, or 0
365   /// if it is not.
366   MDNode *getType(const Type *T) {
367     typedef DenseMap<const Type *, MDNode *>::const_iterator TypeNodeIter;
368     TypeNodeIter i = TypeDescriptors.find(T);
369     if (i != TypeDescriptors.end())
370       return i->second;
371     return 0;
372   }
373
374   /// Returns a DebugInfo type from an LLVM type T.
375   DIDerivedType getOrCreateType(Type *T) {
376     MDNode *N = getType(T);
377     if (N)
378       return DIDerivedType(N);
379     else if (T->isVoidTy())
380       return DIDerivedType(0);
381     else if (T->isStructTy()) {
382       N = Builder.createStructType(
383           DIScope(LexicalBlockFileNode), T->getStructName(), DIFile(FileNode),
384           0, Layout.getTypeSizeInBits(T), Layout.getABITypeAlignment(T), 0,
385           DIType(0), DIArray(0)); // filled in later
386
387       // N is added to the map (early) so that element search below can find it,
388       // so as to avoid infinite recursion for structs that contain pointers to
389       // their own type.
390       TypeDescriptors[T] = N;
391       DICompositeType StructDescriptor(N);
392
393       SmallVector<Value *, 4> Elements;
394       for (unsigned i = 0; i < T->getStructNumElements(); ++i)
395         Elements.push_back(getOrCreateType(T->getStructElementType(i)));
396
397       // set struct elements
398       StructDescriptor.setTypeArray(Builder.getOrCreateArray(Elements));
399     } else if (T->isPointerTy()) {
400       Type *PointeeTy = T->getPointerElementType();
401       if (!(N = getType(PointeeTy)))
402         N = Builder.createPointerType(
403             getOrCreateType(PointeeTy), Layout.getPointerTypeSizeInBits(T),
404             Layout.getPrefTypeAlignment(T), getTypeName(T));
405     } else if (T->isArrayTy()) {
406       SmallVector<Value *, 1> Subrange;
407       Subrange.push_back(
408           Builder.getOrCreateSubrange(0, T->getArrayNumElements() - 1));
409
410       N = Builder.createArrayType(Layout.getTypeSizeInBits(T),
411                                   Layout.getPrefTypeAlignment(T),
412                                   getOrCreateType(T->getArrayElementType()),
413                                   Builder.getOrCreateArray(Subrange));
414     } else {
415       int encoding = llvm::dwarf::DW_ATE_signed;
416       if (T->isIntegerTy())
417         encoding = llvm::dwarf::DW_ATE_unsigned;
418       else if (T->isFloatingPointTy())
419         encoding = llvm::dwarf::DW_ATE_float;
420
421       N = Builder.createBasicType(getTypeName(T), T->getPrimitiveSizeInBits(),
422                                   0, encoding);
423     }
424     TypeDescriptors[T] = N;
425     return DIDerivedType(N);
426   }
427
428   /// Returns a DebugInfo type that represents a function signature for Func.
429   DICompositeType createFunctionSignature(const Function *Func) {
430     SmallVector<Value *, 4> Params;
431     DIDerivedType ReturnType(getOrCreateType(Func->getReturnType()));
432     Params.push_back(ReturnType);
433
434     const Function::ArgumentListType &Args(Func->getArgumentList());
435     for (Function::ArgumentListType::const_iterator i = Args.begin(),
436                                                     e = Args.end();
437          i != e; ++i) {
438       Type *T(i->getType());
439       Params.push_back(getOrCreateType(T));
440     }
441
442     DIArray ParamArray = Builder.getOrCreateArray(Params);
443     return Builder.createSubroutineType(DIFile(FileNode), ParamArray);
444   }
445
446   /// Associates Instruction I with debug location Loc.
447   void addDebugLocation(Instruction &I, DebugLoc Loc) {
448     MDNode *MD = Loc.getAsMDNode(I.getContext());
449     I.setMetadata(LLVMContext::MD_dbg, MD);
450   }
451 };
452
453 /// Sets Filename/Directory from the Module identifier and returns true, or
454 /// false if source information is not present.
455 bool getSourceInfoFromModule(const Module &M, std::string &Directory,
456                              std::string &Filename) {
457   std::string PathStr(M.getModuleIdentifier());
458   if (PathStr.length() == 0 || PathStr == "<stdin>")
459     return false;
460
461   Filename = sys::path::filename(PathStr);
462   SmallVector<char, 16> Path(PathStr.begin(), PathStr.end());
463   sys::path::remove_filename(Path);
464   Directory = StringRef(Path.data(), Path.size());
465   return true;
466 }
467
468 // Sets Filename/Directory from debug information in M and returns true, or
469 // false if no debug information available, or cannot be parsed.
470 bool getSourceInfoFromDI(const Module &M, std::string &Directory,
471                          std::string &Filename) {
472   NamedMDNode *CUNode = M.getNamedMetadata("llvm.dbg.cu");
473   if (!CUNode || CUNode->getNumOperands() == 0)
474     return false;
475
476   DICompileUnit CU(CUNode->getOperand(0));
477   if (!CU.Verify())
478     return false;
479
480   Filename = CU.getFilename();
481   Directory = CU.getDirectory();
482   return true;
483 }
484
485 } // anonymous namespace
486
487 namespace llvm {
488
489 bool DebugIR::getSourceInfo(const Module &M) {
490   ParsedPath = getSourceInfoFromDI(M, Directory, Filename) ||
491                getSourceInfoFromModule(M, Directory, Filename);
492   return ParsedPath;
493 }
494
495 bool DebugIR::updateExtension(StringRef NewExtension) {
496   size_t dot = Filename.find_last_of(".");
497   if (dot == std::string::npos)
498     return false;
499
500   Filename.erase(dot);
501   Filename += NewExtension.str();
502   return true;
503 }
504
505 void DebugIR::generateFilename(OwningPtr<int> &fd) {
506   SmallVector<char, 16> PathVec;
507   fd.reset(new int);
508   sys::fs::createTemporaryFile("debug-ir", "ll", *fd, PathVec);
509   StringRef Path(PathVec.data(), PathVec.size());
510   Filename = sys::path::filename(Path);
511   sys::path::remove_filename(PathVec);
512   Directory = StringRef(PathVec.data(), PathVec.size());
513
514   GeneratedPath = true;
515 }
516
517 std::string DebugIR::getPath() {
518   SmallVector<char, 16> Path;
519   sys::path::append(Path, Directory, Filename);
520   Path.resize(Filename.size() + Directory.size() + 2);
521   Path[Filename.size() + Directory.size() + 1] = '\0';
522   return std::string(Path.data());
523 }
524
525 void DebugIR::writeDebugBitcode(const Module *M, int *fd) {
526   OwningPtr<raw_fd_ostream> Out;
527   std::string error;
528
529   if (!fd) {
530     std::string Path = getPath();
531     Out.reset(new raw_fd_ostream(Path.c_str(), error));
532     DEBUG(dbgs() << "WRITING debug bitcode from Module " << M << " to file "
533                  << Path << "\n");
534   } else {
535     DEBUG(dbgs() << "WRITING debug bitcode from Module " << M << " to fd "
536                  << *fd << "\n");
537     Out.reset(new raw_fd_ostream(*fd, true));
538   }
539
540   M->print(*Out, 0);
541   Out->close();
542 }
543
544 void DebugIR::createDebugInfo(Module &M, OwningPtr<Module> &DisplayM) {
545   if (M.getFunctionList().size() == 0)
546     // no functions -- no debug info needed
547     return;
548
549   OwningPtr<ValueToValueMapTy> VMap;
550
551   if (WriteSourceToDisk && (HideDebugIntrinsics || HideDebugMetadata)) {
552     VMap.reset(new ValueToValueMapTy);
553     DisplayM.reset(CloneModule(&M, *VMap));
554
555     if (HideDebugIntrinsics)
556       DebugIntrinsicsRemover::process(*DisplayM);
557
558     if (HideDebugMetadata)
559       DebugMetadataRemover::process(*DisplayM);
560   }
561
562   DIUpdater R(M, Filename, Directory, DisplayM.get(), VMap.get());
563 }
564
565 bool DebugIR::isMissingPath() { return Filename.empty() || Directory.empty(); }
566
567 bool DebugIR::runOnModule(Module &M) {
568   OwningPtr<int> fd;
569
570   if (isMissingPath() && !getSourceInfo(M)) {
571     if (!WriteSourceToDisk)
572       report_fatal_error("DebugIR unable to determine file name in input. "
573                          "Ensure Module contains an identifier, a valid "
574                          "DICompileUnit, or construct DebugIR with "
575                          "non-empty Filename/Directory parameters.");
576     else
577       generateFilename(fd);
578   }
579
580   if (!GeneratedPath && WriteSourceToDisk)
581     updateExtension(".debug-ll");
582
583   // Clear line numbers. Keep debug info (if any) if we were able to read the
584   // file name from the DICompileUnit descriptor.
585   DebugMetadataRemover::process(M, !ParsedPath);
586
587   OwningPtr<Module> DisplayM;
588   createDebugInfo(M, DisplayM);
589   if (WriteSourceToDisk) {
590     Module *OutputM = DisplayM.get() ? DisplayM.get() : &M;
591     writeDebugBitcode(OutputM, fd.get());
592   }
593
594   DEBUG(M.dump());
595   return true;
596 }
597
598 bool DebugIR::runOnModule(Module &M, std::string &Path) {
599   bool result = runOnModule(M);
600   Path = getPath();
601   return result;
602 }
603
604 } // llvm namespace
605
606 char DebugIR::ID = 0;
607 INITIALIZE_PASS(DebugIR, "debug-ir", "Enable debugging IR", false, false)
608
609 ModulePass *llvm::createDebugIRPass(bool HideDebugIntrinsics,
610                                     bool HideDebugMetadata, StringRef Directory,
611                                     StringRef Filename) {
612   return new DebugIR(HideDebugIntrinsics, HideDebugMetadata, Directory,
613                      Filename);
614 }
615
616 ModulePass *llvm::createDebugIRPass() { return new DebugIR(); }