blob: 8bb8738c6577e6fc1a84f3705e402fedc5b9ed39 [file] [log] [blame]
Chris Lattner2eacf262004-01-05 05:25:10 +00001//===-- ProgramInfo.cpp - Compute and cache info about a program ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ProgramInfo and related classes, by sorting through
11// the loaded Module.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Debugger/ProgramInfo.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Intrinsics.h"
Chris Lattner4ab78e02004-07-29 17:15:38 +000019#include "llvm/Instructions.h"
Chris Lattner2eacf262004-01-05 05:25:10 +000020#include "llvm/Module.h"
21#include "llvm/Debugger/SourceFile.h"
22#include "llvm/Debugger/SourceLanguage.h"
23#include "Support/FileUtilities.h"
24#include "Support/SlowOperationInformer.h"
25#include "Support/STLExtras.h"
Reid Spencer954da372004-07-04 12:19:56 +000026#include <iostream>
27
Chris Lattner2eacf262004-01-05 05:25:10 +000028using namespace llvm;
29
30/// getGlobalVariablesUsing - Return all of the global variables which have the
31/// specified value in their initializer somewhere.
32static void getGlobalVariablesUsing(Value *V,
33 std::vector<GlobalVariable*> &Found) {
34 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
35 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
36 Found.push_back(GV);
37 else if (Constant *C = dyn_cast<Constant>(*I))
38 getGlobalVariablesUsing(C, Found);
39 }
40}
41
42/// getStringValue - Turn an LLVM constant pointer that eventually points to a
43/// global into a string value. Return an empty string if we can't do it.
44///
45static std::string getStringValue(Value *V, unsigned Offset = 0) {
46 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
47 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
48 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
Chris Lattnere3f84f52004-01-14 17:07:46 +000049 if (Init->isString()) {
Chris Lattner2eacf262004-01-05 05:25:10 +000050 std::string Result = Init->getAsString();
51 if (Offset < Result.size()) {
52 // If we are pointing INTO The string, erase the beginning...
53 Result.erase(Result.begin(), Result.begin()+Offset);
54
55 // Take off the null terminator, and any string fragments after it.
56 std::string::size_type NullPos = Result.find_first_of((char)0);
57 if (NullPos != std::string::npos)
58 Result.erase(Result.begin()+NullPos, Result.end());
59 return Result;
60 }
61 }
62 }
63 } else if (Constant *C = dyn_cast<Constant>(V)) {
Reid Spencer518310c2004-07-18 00:44:37 +000064 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
65 return getStringValue(GV, Offset);
Chris Lattner2eacf262004-01-05 05:25:10 +000066 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
67 if (CE->getOpcode() == Instruction::GetElementPtr) {
68 // Turn a gep into the specified offset.
69 if (CE->getNumOperands() == 3 &&
70 cast<Constant>(CE->getOperand(1))->isNullValue() &&
71 isa<ConstantInt>(CE->getOperand(2))) {
72 return getStringValue(CE->getOperand(0),
73 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
74 }
75 }
76 }
77 }
78 return "";
79}
80
81/// getNextStopPoint - Follow the def-use chains of the specified LLVM value,
82/// traversing the use chains until we get to a stoppoint. When we do, return
83/// the source location of the stoppoint. If we don't find a stoppoint, return
84/// null.
85static const GlobalVariable *getNextStopPoint(const Value *V, unsigned &LineNo,
86 unsigned &ColNo) {
87 // The use-def chains can fork. As such, we pick the lowest numbered one we
88 // find.
89 const GlobalVariable *LastDesc = 0;
90 unsigned LastLineNo = ~0;
91 unsigned LastColNo = ~0;
92
93 for (Value::use_const_iterator UI = V->use_begin(), E = V->use_end();
94 UI != E; ++UI) {
95 bool ShouldRecurse = true;
96 if (cast<Instruction>(*UI)->getOpcode() == Instruction::PHI) {
97 // Infinite loops == bad, ignore PHI nodes.
98 ShouldRecurse = false;
99 } else if (const CallInst *CI = dyn_cast<CallInst>(*UI)) {
100 // If we found a stop point, check to see if it is earlier than what we
101 // already have. If so, remember it.
102 if (const Function *F = CI->getCalledFunction())
103 if (F->getIntrinsicID() == Intrinsic::dbg_stoppoint) {
104 unsigned CurLineNo = ~0, CurColNo = ~0;
105 const GlobalVariable *CurDesc = 0;
106 if (const ConstantInt *C = dyn_cast<ConstantInt>(CI->getOperand(2)))
107 CurLineNo = C->getRawValue();
108 if (const ConstantInt *C = dyn_cast<ConstantInt>(CI->getOperand(3)))
109 CurColNo = C->getRawValue();
110 const Value *Op = CI->getOperand(4);
Chris Lattner2eacf262004-01-05 05:25:10 +0000111
112 if ((CurDesc = dyn_cast<GlobalVariable>(Op)) &&
113 (LineNo < LastLineNo ||
114 (LineNo == LastLineNo && ColNo < LastColNo))) {
115 LastDesc = CurDesc;
116 LastLineNo = CurLineNo;
117 LastColNo = CurColNo;
118 }
119 ShouldRecurse = false;
120 }
121
122 }
123
124 // If this is not a phi node or a stopping point, recursively scan the users
125 // of this instruction to skip over region.begin's and the like.
126 if (ShouldRecurse) {
127 unsigned CurLineNo, CurColNo;
128 if (const GlobalVariable *GV = getNextStopPoint(*UI, CurLineNo,CurColNo)){
129 if (LineNo < LastLineNo || (LineNo == LastLineNo && ColNo < LastColNo)){
130 LastDesc = GV;
131 LastLineNo = CurLineNo;
132 LastColNo = CurColNo;
133 }
134 }
135 }
136 }
137
138 if (LastDesc) {
139 LineNo = LastLineNo != ~0U ? LastLineNo : 0;
140 ColNo = LastColNo != ~0U ? LastColNo : 0;
141 }
142 return LastDesc;
143}
144
145
146//===----------------------------------------------------------------------===//
147// SourceFileInfo implementation
148//
149
150SourceFileInfo::SourceFileInfo(const GlobalVariable *Desc,
151 const SourceLanguage &Lang)
152 : Language(&Lang), Descriptor(Desc) {
153 Version = 0;
154 SourceText = 0;
155
156 if (Desc && Desc->hasInitializer())
157 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Desc->getInitializer()))
158 if (CS->getNumOperands() > 4) {
159 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(CS->getOperand(1)))
160 Version = CUI->getValue();
161
162 BaseName = getStringValue(CS->getOperand(3));
163 Directory = getStringValue(CS->getOperand(4));
164 }
165}
166
167SourceFileInfo::~SourceFileInfo() {
168 delete SourceText;
169}
170
171SourceFile &SourceFileInfo::getSourceText() const {
172 // FIXME: this should take into account the source search directories!
173 if (SourceText == 0) // Read the file in if we haven't already.
174 if (!Directory.empty() && FileOpenable(Directory+"/"+BaseName))
175 SourceText = new SourceFile(Directory+"/"+BaseName, Descriptor);
176 else
177 SourceText = new SourceFile(BaseName, Descriptor);
178 return *SourceText;
179}
180
181
182//===----------------------------------------------------------------------===//
183// SourceFunctionInfo implementation
184//
185SourceFunctionInfo::SourceFunctionInfo(ProgramInfo &PI,
186 const GlobalVariable *Desc)
187 : Descriptor(Desc) {
188 LineNo = ColNo = 0;
189 if (Desc && Desc->hasInitializer())
190 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Desc->getInitializer()))
191 if (CS->getNumOperands() > 2) {
192 // Entry #1 is the file descriptor.
Reid Spencer518310c2004-07-18 00:44:37 +0000193 if (const GlobalVariable *GV =
194 dyn_cast<GlobalVariable>(CS->getOperand(1)))
195 SourceFile = &PI.getSourceFile(GV);
Chris Lattner2eacf262004-01-05 05:25:10 +0000196
197 // Entry #2 is the function name.
198 Name = getStringValue(CS->getOperand(2));
199 }
200}
201
202/// getSourceLocation - This method returns the location of the first stopping
203/// point in the function.
204void SourceFunctionInfo::getSourceLocation(unsigned &RetLineNo,
205 unsigned &RetColNo) const {
206 // If we haven't computed this yet...
207 if (!LineNo) {
208 // Look at all of the users of the function descriptor, looking for calls to
209 // %llvm.dbg.func.start.
210 for (Value::use_const_iterator UI = Descriptor->use_begin(),
211 E = Descriptor->use_end(); UI != E; ++UI)
212 if (const CallInst *CI = dyn_cast<CallInst>(*UI))
213 if (const Function *F = CI->getCalledFunction())
214 if (F->getIntrinsicID() == Intrinsic::dbg_func_start) {
215 // We found the start of the function. Check to see if there are
216 // any stop points on the use-list of the function start.
217 const GlobalVariable *SD = getNextStopPoint(CI, LineNo, ColNo);
218 if (SD) { // We found the first stop point!
219 // This is just a sanity check.
220 if (getSourceFile().getDescriptor() != SD)
221 std::cout << "WARNING: first line of function is not in the"
222 " file that the function descriptor claims it is in.\n";
223 break;
224 }
225 }
226 }
227 RetLineNo = LineNo; RetColNo = ColNo;
228}
229
230//===----------------------------------------------------------------------===//
231// ProgramInfo implementation
232//
233
234ProgramInfo::ProgramInfo(Module *m) : M(m) {
235 assert(M && "Cannot create program information with a null module!");
236 ProgramTimeStamp = getFileTimestamp(M->getModuleIdentifier());
237
238 SourceFilesIsComplete = false;
239 SourceFunctionsIsComplete = false;
240}
241
242ProgramInfo::~ProgramInfo() {
243 // Delete cached information about source program objects...
244 for (std::map<const GlobalVariable*, SourceFileInfo*>::iterator
245 I = SourceFiles.begin(), E = SourceFiles.end(); I != E; ++I)
246 delete I->second;
247 for (std::map<const GlobalVariable*, SourceFunctionInfo*>::iterator
248 I = SourceFunctions.begin(), E = SourceFunctions.end(); I != E; ++I)
249 delete I->second;
250
251 // Delete the source language caches.
252 for (unsigned i = 0, e = LanguageCaches.size(); i != e; ++i)
253 delete LanguageCaches[i].second;
254}
255
256
257//===----------------------------------------------------------------------===//
258// SourceFileInfo tracking...
259//
260
261/// getSourceFile - Return source file information for the specified source file
262/// descriptor object, adding it to the collection as needed. This method
263/// always succeeds (is unambiguous), and is always efficient.
264///
265const SourceFileInfo &
266ProgramInfo::getSourceFile(const GlobalVariable *Desc) {
267 SourceFileInfo *&Result = SourceFiles[Desc];
268 if (Result) return *Result;
269
270 // Figure out what language this source file comes from...
271 unsigned LangID = 0; // Zero is unknown language
272 if (Desc && Desc->hasInitializer())
273 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Desc->getInitializer()))
274 if (CS->getNumOperands() > 2)
275 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(CS->getOperand(2)))
276 LangID = CUI->getValue();
277
278 const SourceLanguage &Lang = SourceLanguage::get(LangID);
279 SourceFileInfo *New = Lang.createSourceFileInfo(Desc, *this);
280
281 // FIXME: this should check to see if there is already a Filename/WorkingDir
282 // pair that matches this one. If so, we shouldn't create the duplicate!
283 //
284 SourceFileIndex.insert(std::make_pair(New->getBaseName(), New));
285 return *(Result = New);
286}
287
288
289/// getSourceFiles - Index all of the source files in the program and return
290/// a mapping of it. This information is lazily computed the first time
291/// that it is requested. Since this information can take a long time to
292/// compute, the user is given a chance to cancel it. If this occurs, an
293/// exception is thrown.
294const std::map<const GlobalVariable*, SourceFileInfo*> &
295ProgramInfo::getSourceFiles(bool RequiresCompleteMap) {
296 // If we have a fully populated map, or if the client doesn't need one, just
297 // return what we have.
298 if (SourceFilesIsComplete || !RequiresCompleteMap)
299 return SourceFiles;
300
301 // Ok, all of the source file descriptors (compile_unit in dwarf terms),
302 // should be on the use list of the llvm.dbg.translation_units global.
303 //
304 GlobalVariable *Units =
305 M->getGlobalVariable("llvm.dbg.translation_units",
306 StructType::get(std::vector<const Type*>()));
307 if (Units == 0)
308 throw "Program contains no debugging information!";
309
310 std::vector<GlobalVariable*> TranslationUnits;
311 getGlobalVariablesUsing(Units, TranslationUnits);
312
313 SlowOperationInformer SOI("building source files index");
314
315 // Loop over all of the translation units found, building the SourceFiles
316 // mapping.
317 for (unsigned i = 0, e = TranslationUnits.size(); i != e; ++i) {
318 getSourceFile(TranslationUnits[i]);
319 SOI.progress(i+1, e);
320 }
321
322 // Ok, if we got this far, then we indexed the whole program.
323 SourceFilesIsComplete = true;
324 return SourceFiles;
325}
326
327/// getSourceFile - Look up the file with the specified name. If there is
328/// more than one match for the specified filename, prompt the user to pick
329/// one. If there is no source file that matches the specified name, throw
330/// an exception indicating that we can't find the file. Otherwise, return
331/// the file information for that file.
332const SourceFileInfo &ProgramInfo::getSourceFile(const std::string &Filename) {
333 std::multimap<std::string, SourceFileInfo*>::const_iterator Start, End;
334 getSourceFiles();
335 tie(Start, End) = SourceFileIndex.equal_range(Filename);
336
337 if (Start == End) throw "Could not find source file '" + Filename + "'!";
338 const SourceFileInfo &SFI = *Start->second;
339 ++Start;
340 if (Start == End) return SFI;
341
342 throw "FIXME: Multiple source files with the same name not implemented!";
343}
344
345
346//===----------------------------------------------------------------------===//
347// SourceFunctionInfo tracking...
348//
349
350
351/// getFunction - Return function information for the specified function
352/// descriptor object, adding it to the collection as needed. This method
353/// always succeeds (is unambiguous), and is always efficient.
354///
355const SourceFunctionInfo &
356ProgramInfo::getFunction(const GlobalVariable *Desc) {
357 SourceFunctionInfo *&Result = SourceFunctions[Desc];
358 if (Result) return *Result;
359
360 // Figure out what language this function comes from...
361 const GlobalVariable *SourceFileDesc = 0;
362 if (Desc && Desc->hasInitializer())
363 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Desc->getInitializer()))
364 if (CS->getNumOperands() > 0)
Reid Spencer518310c2004-07-18 00:44:37 +0000365 if (const GlobalVariable *GV =
366 dyn_cast<GlobalVariable>(CS->getOperand(1)))
367 SourceFileDesc = GV;
Chris Lattner2eacf262004-01-05 05:25:10 +0000368
369 const SourceLanguage &Lang = getSourceFile(SourceFileDesc).getLanguage();
370 return *(Result = Lang.createSourceFunctionInfo(Desc, *this));
371}
372
373
374// getSourceFunctions - Index all of the functions in the program and return
375// them. This information is lazily computed the first time that it is
376// requested. Since this information can take a long time to compute, the user
377// is given a chance to cancel it. If this occurs, an exception is thrown.
378const std::map<const GlobalVariable*, SourceFunctionInfo*> &
379ProgramInfo::getSourceFunctions(bool RequiresCompleteMap) {
380 if (SourceFunctionsIsComplete || !RequiresCompleteMap)
381 return SourceFunctions;
382
383 // Ok, all of the source function descriptors (subprogram in dwarf terms),
384 // should be on the use list of the llvm.dbg.translation_units global.
385 //
386 GlobalVariable *Units =
387 M->getGlobalVariable("llvm.dbg.globals",
388 StructType::get(std::vector<const Type*>()));
389 if (Units == 0)
390 throw "Program contains no debugging information!";
391
392 std::vector<GlobalVariable*> Functions;
393 getGlobalVariablesUsing(Units, Functions);
394
395 SlowOperationInformer SOI("building functions index");
396
397 // Loop over all of the functions found, building the SourceFunctions mapping.
398 for (unsigned i = 0, e = Functions.size(); i != e; ++i) {
399 getFunction(Functions[i]);
400 SOI.progress(i+1, e);
401 }
402
403 // Ok, if we got this far, then we indexed the whole program.
404 SourceFunctionsIsComplete = true;
405 return SourceFunctions;
406}