blob: 9ad6c472b9bac4f173ed9a31b5976a3026a378d9 [file] [log] [blame]
Daniel Malea3c5bed12013-05-08 20:44:14 +00001//===--- 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//
Daniel Malea31321fa2013-06-28 19:05:23 +000013// 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.
Daniel Malea3c5bed12013-05-08 20:44:14 +000016//
17//===----------------------------------------------------------------------===//
18
Daniel Malea31321fa2013-06-28 19:05:23 +000019#define DEBUG_TYPE "debug-ir"
Daniel Malea3c5bed12013-05-08 20:44:14 +000020
Daniel Maleafddddbe2013-05-23 22:34:33 +000021#include "llvm/ADT/ValueMap.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000022#include "DebugIR.h"
Daniel Malea3c5bed12013-05-08 20:44:14 +000023#include "llvm/DIBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000024#include "llvm/DebugInfo.h"
Chandler Carruth9aca9182014-01-07 12:34:26 +000025#include "llvm/IR/AssemblyAnnotationWriter.h"
Daniel Malea31321fa2013-06-28 19:05:23 +000026#include "llvm/IR/DataLayout.h"
Daniel Malea3c5bed12013-05-08 20:44:14 +000027#include "llvm/IR/Instruction.h"
Bob Wilsone4077362013-09-09 19:14:35 +000028#include "llvm/IR/LLVMContext.h"
Daniel Malea3c5bed12013-05-08 20:44:14 +000029#include "llvm/IR/Module.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000030#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"
Daniel Malea3c5bed12013-05-08 20:44:14 +000036#include "llvm/Transforms/Instrumentation.h"
Daniel Maleafddddbe2013-05-23 22:34:33 +000037#include "llvm/Transforms/Utils/Cloning.h"
Daniel Malea31321fa2013-06-28 19:05:23 +000038#include <string>
Daniel Malea31321fa2013-06-28 19:05:23 +000039
40#define STR_HELPER(x) #x
41#define STR(x) STR_HELPER(x)
42
Daniel Malea3c5bed12013-05-08 20:44:14 +000043using namespace llvm;
44
45namespace {
46
Daniel Maleafddddbe2013-05-23 22:34:33 +000047/// 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.
50class ValueToLineMap : public AssemblyAnnotationWriter {
51 ValueMap<const Value *, unsigned int> Lines;
52 typedef ValueMap<const Value *, unsigned int>::const_iterator LineIter;
Daniel Malea3c5bed12013-05-08 20:44:14 +000053
Daniel Malea31321fa2013-06-28 19:05:23 +000054 void addEntry(const Value *V, formatted_raw_ostream &Out) {
55 Out.flush();
56 Lines.insert(std::make_pair(V, Out.getLine() + 1));
57 }
58
Daniel Maleafddddbe2013-05-23 22:34:33 +000059public:
Daniel Malea3c5bed12013-05-08 20:44:14 +000060
Daniel Maleafddddbe2013-05-23 22:34:33 +000061 /// Prints Module to a null buffer in order to build the map of Value pointers
62 /// to line numbers.
Daniel Malea31321fa2013-06-28 19:05:23 +000063 ValueToLineMap(const Module *M) {
Daniel Maleafddddbe2013-05-23 22:34:33 +000064 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) {
Daniel Malea31321fa2013-06-28 19:05:23 +000071 addEntry(&V, Out);
72 }
73
74 void emitFunctionAnnot(const Function *F, formatted_raw_ostream &Out) {
75 addEntry(F, Out);
Daniel Maleafddddbe2013-05-23 22:34:33 +000076 }
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.
91class DebugIntrinsicsRemover : public InstVisitor<DebugIntrinsicsRemover> {
92 void remove(Instruction &I) { I.eraseFromParent(); }
93
94public:
Daniel Malea31321fa2013-06-28 19:05:23 +000095 static void process(Module &M) {
96 DebugIntrinsicsRemover Remover;
97 Remover.visit(&M);
98 }
Daniel Maleafddddbe2013-05-23 22:34:33 +000099 void visitDbgDeclareInst(DbgDeclareInst &I) { remove(I); }
100 void visitDbgValueInst(DbgValueInst &I) { remove(I); }
101 void visitDbgInfoIntrinsic(DbgInfoIntrinsic &I) { remove(I); }
102};
103
Daniel Malea31321fa2013-06-28 19:05:23 +0000104/// Removes debug metadata (!dbg) nodes from all instructions, and optionally
105/// metadata named "llvm.dbg.cu" if RemoveNamedInfo is true.
Daniel Maleafddddbe2013-05-23 22:34:33 +0000106class DebugMetadataRemover : public InstVisitor<DebugMetadataRemover> {
Daniel Malea31321fa2013-06-28 19:05:23 +0000107 bool RemoveNamedInfo;
108
Daniel Maleafddddbe2013-05-23 22:34:33 +0000109public:
Daniel Malea31321fa2013-06-28 19:05:23 +0000110 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
Daniel Maleafddddbe2013-05-23 22:34:33 +0000118 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
Daniel Malea31321fa2013-06-28 19:05:23 +0000127 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 }
Daniel Maleafddddbe2013-05-23 22:34:33 +0000133 }
134};
135
Daniel Malea31321fa2013-06-28 19:05:23 +0000136/// 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
140class DIUpdater : public InstVisitor<DIUpdater> {
141 /// Builder of debug information
142 DIBuilder Builder;
Daniel Maleafddddbe2013-05-23 22:34:33 +0000143
Daniel Malea31321fa2013-06-28 19:05:23 +0000144 /// 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;
Daniel Maleafddddbe2013-05-23 22:34:33 +0000152
Daniel Malea3c5bed12013-05-08 20:44:14 +0000153 /// Directory of debug metadata
Daniel Malea31321fa2013-06-28 19:05:23 +0000154 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;
Daniel Malea3c5bed12013-05-08 20:44:14 +0000167
Daniel Malea3c5bed12013-05-08 20:44:14 +0000168public:
Daniel Malea31321fa2013-06-28 19:05:23 +0000169 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);
Manman Rend0e67aa2013-07-02 18:37:35 +0000218 DISubprogram Sub = Builder.createFunction(
Daniel Malea31321fa2013-06-28 19:05:23 +0000219 DICompileUnit(CUNode), F.getName(), MangledName, DIFile(FileNode), Line,
220 Sig, Local, IsDefinition, ScopeLine, FuncFlags, IsOptimized, &F);
Manman Rend0e67aa2013-07-02 18:37:35 +0000221 assert(Sub.isSubprogram());
Eric Christopher7ab2c3e2013-07-17 23:25:22 +0000222 DEBUG(dbgs() << "create subprogram mdnode " << *Sub << ": "
Daniel Malea31321fa2013-06-28 19:05:23 +0000223 << "\n");
224
225 SubprogramDescriptors.insert(std::make_pair(&F, Sub));
226 }
Daniel Malea3c5bed12013-05-08 20:44:14 +0000227
Daniel Maleafddddbe2013-05-23 22:34:33 +0000228 void visitInstruction(Instruction &I) {
Daniel Malea3c5bed12013-05-08 20:44:14 +0000229 DebugLoc Loc(I.getDebugLoc());
230
Daniel Malea31321fa2013-06-28 19:05:23 +0000231 /// 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
Daniel Maleafddddbe2013-05-23 22:34:33 +0000241 unsigned Col = 0; // FIXME: support columns
242 unsigned Line;
Daniel Malea31321fa2013-06-28 19:05:23 +0000243 if (!LineTable.getLine(RealInst, Line)) {
Daniel Maleafddddbe2013-05-23 22:34:33 +0000244 // 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.
Daniel Malea31321fa2013-06-28 19:05:23 +0000246 DEBUG(dbgs() << "WARNING: no LineTable entry for instruction " << RealInst
247 << "\n");
248 DEBUG(RealInst->dump());
Daniel Maleafddddbe2013-05-23 22:34:33 +0000249 return;
Daniel Malea31321fa2013-06-28 19:05:23 +0000250 }
Daniel Malea3c5bed12013-05-08 20:44:14 +0000251
252 DebugLoc NewLoc;
253 if (!Loc.isUnknown())
254 // I had a previous debug location: re-use the DebugLoc
Daniel Malea31321fa2013-06-28 19:05:23 +0000255 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");
Daniel Malea3c5bed12013-05-08 20:44:14 +0000263 return;
Daniel Malea31321fa2013-06-28 19:05:23 +0000264 }
Daniel Malea3c5bed12013-05-08 20:44:14 +0000265
Daniel Malea31321fa2013-06-28 19:05:23 +0000266 addDebugLocation(I, NewLoc);
Daniel Malea3c5bed12013-05-08 20:44:14 +0000267 }
268
Daniel Maleafddddbe2013-05-23 22:34:33 +0000269private:
Daniel Malea3c5bed12013-05-08 20:44:14 +0000270
Daniel Malea31321fa2013-06-28 19:05:23 +0000271 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
Eric Christopher03b3e112013-07-19 00:51:47 +0000291 CUNode =
292 Builder.createCompileUnit(dwarf::DW_LANG_C99, Filename, Directory,
293 Producer, IsOptimized, Flags, RuntimeVersion);
Daniel Malea31321fa2013-06-28 19:05:23 +0000294
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
Daniel Malea3c5bed12013-05-08 20:44:14 +0000327 for (DebugInfoFinder::iterator i = Finder.subprogram_begin(),
328 e = Finder.subprogram_end();
329 i != e; ++i) {
330 DISubprogram S(*i);
Daniel Malea31321fa2013-06-28 19:05:23 +0000331 if (S.getFunction() == F) {
332 DEBUG(dbgs() << "Found DISubprogram " << *i << " for function "
333 << S.getFunction() << "\n");
Daniel Malea3c5bed12013-05-08 20:44:14 +0000334 return *i;
Daniel Malea31321fa2013-06-28 19:05:23 +0000335 }
Daniel Malea3c5bed12013-05-08 20:44:14 +0000336 }
Daniel Malea31321fa2013-06-28 19:05:23 +0000337 DEBUG(dbgs() << "unable to find DISubprogram node for function "
338 << F->getName().str() << "\n");
Daniel Malea3c5bed12013-05-08 20:44:14 +0000339 return 0;
340 }
341
Daniel Malea31321fa2013-06-28 19:05:23 +0000342 /// 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(
Matt Arsenault31cfc782013-09-27 22:26:25 +0000403 getOrCreateType(PointeeTy), Layout.getPointerTypeSizeInBits(T),
Daniel Malea31321fa2013-06-28 19:05:23 +0000404 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.
Daniel Malea3c5bed12013-05-08 20:44:14 +0000447 void addDebugLocation(Instruction &I, DebugLoc Loc) {
448 MDNode *MD = Loc.getAsMDNode(I.getContext());
449 I.setMetadata(LLVMContext::MD_dbg, MD);
450 }
451};
452
Daniel Malea31321fa2013-06-28 19:05:23 +0000453/// Sets Filename/Directory from the Module identifier and returns true, or
454/// false if source information is not present.
455bool 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;
Daniel Maleafddddbe2013-05-23 22:34:33 +0000460
Daniel Malea31321fa2013-06-28 19:05:23 +0000461 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}
Daniel Malea3c5bed12013-05-08 20:44:14 +0000467
Daniel Malea31321fa2013-06-28 19:05:23 +0000468// Sets Filename/Directory from debug information in M and returns true, or
469// false if no debug information available, or cannot be parsed.
470bool 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;
Daniel Malea3c5bed12013-05-08 20:44:14 +0000475
Daniel Malea31321fa2013-06-28 19:05:23 +0000476 DICompileUnit CU(CUNode->getOperand(0));
477 if (!CU.Verify())
478 return false;
Daniel Maleafddddbe2013-05-23 22:34:33 +0000479
Daniel Malea31321fa2013-06-28 19:05:23 +0000480 Filename = CU.getFilename();
481 Directory = CU.getDirectory();
482 return true;
483}
Daniel Malea3c5bed12013-05-08 20:44:14 +0000484
485} // anonymous namespace
486
Daniel Malea31321fa2013-06-28 19:05:23 +0000487namespace llvm {
488
489bool DebugIR::getSourceInfo(const Module &M) {
490 ParsedPath = getSourceInfoFromDI(M, Directory, Filename) ||
491 getSourceInfoFromModule(M, Directory, Filename);
492 return ParsedPath;
493}
494
495bool 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
505void DebugIR::generateFilename(OwningPtr<int> &fd) {
Daniel Malea31321fa2013-06-28 19:05:23 +0000506 SmallVector<char, 16> PathVec;
507 fd.reset(new int);
Rafael Espindola155cf0f2013-07-05 20:14:52 +0000508 sys::fs::createTemporaryFile("debug-ir", "ll", *fd, PathVec);
Daniel Malea31321fa2013-06-28 19:05:23 +0000509 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
517std::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
525void 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();
Daniel Malea31321fa2013-06-28 19:05:23 +0000542}
543
544void 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
565bool DebugIR::isMissingPath() { return Filename.empty() || Directory.empty(); }
566
567bool 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
598bool DebugIR::runOnModule(Module &M, std::string &Path) {
599 bool result = runOnModule(M);
600 Path = getPath();
601 return result;
602}
603
604} // llvm namespace
605
Daniel Malea3c5bed12013-05-08 20:44:14 +0000606char DebugIR::ID = 0;
607INITIALIZE_PASS(DebugIR, "debug-ir", "Enable debugging IR", false, false)
Daniel Maleafddddbe2013-05-23 22:34:33 +0000608
Daniel Malea31321fa2013-06-28 19:05:23 +0000609ModulePass *llvm::createDebugIRPass(bool HideDebugIntrinsics,
610 bool HideDebugMetadata, StringRef Directory,
611 StringRef Filename) {
612 return new DebugIR(HideDebugIntrinsics, HideDebugMetadata, Directory,
613 Filename);
Daniel Malea3c5bed12013-05-08 20:44:14 +0000614}
Daniel Malea31321fa2013-06-28 19:05:23 +0000615
616ModulePass *llvm::createDebugIRPass() { return new DebugIR(); }