1 //===--- ASTConsumers.cpp - ASTConsumer implementations -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // AST Consumer Implementations.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/ASTConsumers.h"
15 #include "clang/Frontend/DocumentXML.h"
16 #include "clang/Frontend/PathDiagnosticClients.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Basic/FileManager.h"
20 #include "clang/AST/AST.h"
21 #include "clang/AST/ASTConsumer.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/PrettyPrinter.h"
25 #include "clang/CodeGen/ModuleBuilder.h"
26 #include "llvm/Module.h"
27 #include "llvm/Support/Format.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Path.h"
31 using namespace clang;
33 //===----------------------------------------------------------------------===//
34 /// ASTPrinter - Pretty-printer and dumper of ASTs
37 class ASTPrinter : public ASTConsumer {
38 llvm::raw_ostream &Out;
42 ASTPrinter(llvm::raw_ostream* o = NULL, bool Dump = false)
43 : Out(o? *o : llvm::errs()), Dump(Dump) { }
45 virtual void HandleTranslationUnit(ASTContext &Context) {
46 PrintingPolicy Policy = Context.PrintingPolicy;
48 Context.getTranslationUnitDecl()->print(Out, Policy);
51 } // end anonymous namespace
53 ASTConsumer *clang::CreateASTPrinter(llvm::raw_ostream* out) {
54 return new ASTPrinter(out);
57 //===----------------------------------------------------------------------===//
58 /// ASTPrinterXML - XML-printer of ASTs
61 class ASTPrinterXML : public ASTConsumer {
65 ASTPrinterXML(llvm::raw_ostream& o) : Doc("CLANG_XML", o) {}
67 void Initialize(ASTContext &Context) {
68 Doc.initialize(Context);
71 virtual void HandleTranslationUnit(ASTContext &Ctx) {
72 Doc.addSubNode("TranslationUnit");
73 for (DeclContext::decl_iterator
74 D = Ctx.getTranslationUnitDecl()->decls_begin(),
75 DEnd = Ctx.getTranslationUnitDecl()->decls_end();
83 } // end anonymous namespace
86 ASTConsumer *clang::CreateASTPrinterXML(llvm::raw_ostream* out) {
87 return new ASTPrinterXML(out ? *out : llvm::outs());
90 ASTConsumer *clang::CreateASTDumper() {
91 return new ASTPrinter(0, true);
94 //===----------------------------------------------------------------------===//
95 /// ASTViewer - AST Visualization
98 class ASTViewer : public ASTConsumer {
101 void Initialize(ASTContext &Context) {
102 this->Context = &Context;
105 virtual void HandleTopLevelDecl(DeclGroupRef D) {
106 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
107 HandleTopLevelSingleDecl(*I);
110 void HandleTopLevelSingleDecl(Decl *D);
114 void ASTViewer::HandleTopLevelSingleDecl(Decl *D) {
115 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
116 FD->print(llvm::errs());
118 if (Stmt *Body = FD->getBody()) {
119 llvm::errs() << '\n';
121 llvm::errs() << '\n';
126 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
127 MD->print(llvm::errs());
130 llvm::errs() << '\n';
131 MD->getBody()->viewAST();
132 llvm::errs() << '\n';
138 ASTConsumer *clang::CreateASTViewer() { return new ASTViewer(); }
140 //===----------------------------------------------------------------------===//
141 /// DeclContextPrinter - Decl and DeclContext Visualization
145 class DeclContextPrinter : public ASTConsumer {
146 llvm::raw_ostream& Out;
148 DeclContextPrinter() : Out(llvm::errs()) {}
150 void HandleTranslationUnit(ASTContext &C) {
151 PrintDeclContext(C.getTranslationUnitDecl(), 4);
154 void PrintDeclContext(const DeclContext* DC, unsigned Indentation);
156 } // end anonymous namespace
158 void DeclContextPrinter::PrintDeclContext(const DeclContext* DC,
159 unsigned Indentation) {
160 // Print DeclContext name.
161 switch (DC->getDeclKind()) {
162 case Decl::TranslationUnit:
163 Out << "[translation unit] " << DC;
165 case Decl::Namespace: {
166 Out << "[namespace] ";
167 const NamespaceDecl* ND = cast<NamespaceDecl>(DC);
168 Out << ND->getNameAsString();
172 const EnumDecl* ED = cast<EnumDecl>(DC);
173 if (ED->isDefinition())
177 Out << ED->getNameAsString();
181 const RecordDecl* RD = cast<RecordDecl>(DC);
182 if (RD->isDefinition())
186 Out << RD->getNameAsString();
189 case Decl::CXXRecord: {
190 const CXXRecordDecl* RD = cast<CXXRecordDecl>(DC);
191 if (RD->isDefinition())
195 Out << RD->getNameAsString() << " " << DC;
198 case Decl::ObjCMethod:
199 Out << "[objc method]";
201 case Decl::ObjCInterface:
202 Out << "[objc interface]";
204 case Decl::ObjCCategory:
205 Out << "[objc category]";
207 case Decl::ObjCProtocol:
208 Out << "[objc protocol]";
210 case Decl::ObjCImplementation:
211 Out << "[objc implementation]";
213 case Decl::ObjCCategoryImpl:
214 Out << "[objc categoryimpl]";
216 case Decl::LinkageSpec:
217 Out << "[linkage spec]";
222 case Decl::Function: {
223 const FunctionDecl* FD = cast<FunctionDecl>(DC);
224 if (FD->isThisDeclarationADefinition())
225 Out << "[function] ";
227 Out << "<function> ";
228 Out << FD->getNameAsString();
229 // Print the parameters.
231 bool PrintComma = false;
232 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
233 E = FD->param_end(); I != E; ++I) {
238 Out << (*I)->getNameAsString();
243 case Decl::CXXMethod: {
244 const CXXMethodDecl* D = cast<CXXMethodDecl>(DC);
245 if (D->isOutOfLine())
246 Out << "[c++ method] ";
247 else if (D->isImplicit())
248 Out << "(c++ method) ";
250 Out << "<c++ method> ";
251 Out << D->getNameAsString();
252 // Print the parameters.
254 bool PrintComma = false;
255 for (FunctionDecl::param_const_iterator I = D->param_begin(),
256 E = D->param_end(); I != E; ++I) {
261 Out << (*I)->getNameAsString();
265 // Check the semantic DeclContext.
266 const DeclContext* SemaDC = D->getDeclContext();
267 const DeclContext* LexicalDC = D->getLexicalDeclContext();
268 if (SemaDC != LexicalDC)
269 Out << " [[" << SemaDC << "]]";
273 case Decl::CXXConstructor: {
274 const CXXConstructorDecl* D = cast<CXXConstructorDecl>(DC);
275 if (D->isOutOfLine())
276 Out << "[c++ ctor] ";
277 else if (D->isImplicit())
278 Out << "(c++ ctor) ";
280 Out << "<c++ ctor> ";
281 Out << D->getNameAsString();
282 // Print the parameters.
284 bool PrintComma = false;
285 for (FunctionDecl::param_const_iterator I = D->param_begin(),
286 E = D->param_end(); I != E; ++I) {
291 Out << (*I)->getNameAsString();
295 // Check the semantic DC.
296 const DeclContext* SemaDC = D->getDeclContext();
297 const DeclContext* LexicalDC = D->getLexicalDeclContext();
298 if (SemaDC != LexicalDC)
299 Out << " [[" << SemaDC << "]]";
302 case Decl::CXXDestructor: {
303 const CXXDestructorDecl* D = cast<CXXDestructorDecl>(DC);
304 if (D->isOutOfLine())
305 Out << "[c++ dtor] ";
306 else if (D->isImplicit())
307 Out << "(c++ dtor) ";
309 Out << "<c++ dtor> ";
310 Out << D->getNameAsString();
311 // Check the semantic DC.
312 const DeclContext* SemaDC = D->getDeclContext();
313 const DeclContext* LexicalDC = D->getLexicalDeclContext();
314 if (SemaDC != LexicalDC)
315 Out << " [[" << SemaDC << "]]";
318 case Decl::CXXConversion: {
319 const CXXConversionDecl* D = cast<CXXConversionDecl>(DC);
320 if (D->isOutOfLine())
321 Out << "[c++ conversion] ";
322 else if (D->isImplicit())
323 Out << "(c++ conversion) ";
325 Out << "<c++ conversion> ";
326 Out << D->getNameAsString();
327 // Check the semantic DC.
328 const DeclContext* SemaDC = D->getDeclContext();
329 const DeclContext* LexicalDC = D->getLexicalDeclContext();
330 if (SemaDC != LexicalDC)
331 Out << " [[" << SemaDC << "]]";
336 assert(0 && "a decl that inherits DeclContext isn't handled");
341 // Print decls in the DeclContext.
342 for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
344 for (unsigned i = 0; i < Indentation; ++i)
347 Decl::Kind DK = I->getKind();
349 case Decl::Namespace:
352 case Decl::CXXRecord:
353 case Decl::ObjCMethod:
354 case Decl::ObjCInterface:
355 case Decl::ObjCCategory:
356 case Decl::ObjCProtocol:
357 case Decl::ObjCImplementation:
358 case Decl::ObjCCategoryImpl:
359 case Decl::LinkageSpec:
362 case Decl::CXXMethod:
363 case Decl::CXXConstructor:
364 case Decl::CXXDestructor:
365 case Decl::CXXConversion:
367 DeclContext* DC = cast<DeclContext>(*I);
368 PrintDeclContext(DC, Indentation+2);
372 FieldDecl* FD = cast<FieldDecl>(*I);
373 Out << "<field> " << FD->getNameAsString() << "\n";
376 case Decl::Typedef: {
377 TypedefDecl* TD = cast<TypedefDecl>(*I);
378 Out << "<typedef> " << TD->getNameAsString() << "\n";
381 case Decl::EnumConstant: {
382 EnumConstantDecl* ECD = cast<EnumConstantDecl>(*I);
383 Out << "<enum constant> " << ECD->getNameAsString() << "\n";
387 VarDecl* VD = cast<VarDecl>(*I);
388 Out << "<var> " << VD->getNameAsString() << "\n";
391 case Decl::ImplicitParam: {
392 ImplicitParamDecl* IPD = cast<ImplicitParamDecl>(*I);
393 Out << "<implicit parameter> " << IPD->getNameAsString() << "\n";
396 case Decl::ParmVar: {
397 ParmVarDecl* PVD = cast<ParmVarDecl>(*I);
398 Out << "<parameter> " << PVD->getNameAsString() << "\n";
401 case Decl::ObjCProperty: {
402 ObjCPropertyDecl* OPD = cast<ObjCPropertyDecl>(*I);
403 Out << "<objc property> " << OPD->getNameAsString() << "\n";
406 case Decl::FunctionTemplate: {
407 FunctionTemplateDecl* FTD = cast<FunctionTemplateDecl>(*I);
408 Out << "<function template> " << FTD->getNameAsString() << "\n";
411 case Decl::FileScopeAsm: {
412 Out << "<file-scope asm>\n";
415 case Decl::UsingDirective: {
416 Out << "<using directive>\n";
419 case Decl::NamespaceAlias: {
420 NamespaceAliasDecl* NAD = cast<NamespaceAliasDecl>(*I);
421 Out << "<namespace alias> " << NAD->getNameAsString() << "\n";
424 case Decl::ClassTemplate: {
425 ClassTemplateDecl *CTD = cast<ClassTemplateDecl>(*I);
426 Out << "<class template> " << CTD->getNameAsString() << '\n';
430 Out << "DeclKind: " << DK << '"' << I->getDeclKindName() << "\"\n";
431 assert(0 && "decl unhandled");
435 ASTConsumer *clang::CreateDeclContextPrinter() {
436 return new DeclContextPrinter();
439 //===----------------------------------------------------------------------===//
440 /// RecordLayoutDumper - C++ Record Layout Dumping.
442 class RecordLayoutDumper : public ASTConsumer {
443 llvm::raw_ostream& Out;
445 void PrintOffset(uint64_t Offset, unsigned IndentLevel) {
446 Out << llvm::format("%4d | ", Offset);
447 for (unsigned I = 0; I < IndentLevel * 2; ++I) Out << ' ';
450 void DumpRecordLayoutOffsets(const CXXRecordDecl *RD, ASTContext &C,
452 unsigned IndentLevel, const char* Description,
453 bool IncludeVirtualBases) {
454 const ASTRecordLayout &Info = C.getASTRecordLayout(RD);
456 PrintOffset(Offset, IndentLevel);
457 Out << C.getTypeDeclType((CXXRecordDecl *)RD).getAsString();
459 Out << ' ' << Description;
466 const CXXRecordDecl *PrimaryBase = Info.getPrimaryBase();
469 if (RD->isDynamicClass() && !PrimaryBase) {
470 PrintOffset(Offset, IndentLevel);
471 Out << '(' << RD->getNameAsString() << " vtable pointer)\n";
473 // Dump (non-virtual) bases
474 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
475 E = RD->bases_end(); I != E; ++I) {
476 assert(!I->getType()->isDependentType() &&
477 "Cannot layout class with dependent bases.");
481 const CXXRecordDecl *Base =
482 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
484 uint64_t BaseOffset = Offset + Info.getBaseClassOffset(Base) / 8;
486 DumpRecordLayoutOffsets(Base, C, BaseOffset, IndentLevel,
487 Base == PrimaryBase ? "(primary base)" : "(base)",
488 /*IncludeVirtualBases=*/false);
492 uint64_t FieldNo = 0;
493 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
494 E = RD->field_end(); I != E; ++I, ++FieldNo) {
495 const FieldDecl *Field = *I;
496 uint64_t FieldOffset = Offset + Info.getFieldOffset(FieldNo) / 8;
498 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
499 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
500 DumpRecordLayoutOffsets(D, C, FieldOffset, IndentLevel,
501 Field->getNameAsCString(),
502 /*IncludeVirtualBases=*/true);
507 PrintOffset(FieldOffset, IndentLevel);
508 Out << Field->getType().getAsString() << ' ';
509 Out << Field->getNameAsString() << '\n';
512 if (!IncludeVirtualBases)
515 // Dump virtual bases.
516 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
517 E = RD->vbases_end(); I != E; ++I) {
518 assert(I->isVirtual() && "Found non-virtual class!");
519 const CXXRecordDecl *VBase =
520 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
522 uint64_t VBaseOffset = Offset + Info.getVBaseClassOffset(VBase) / 8;
523 DumpRecordLayoutOffsets(VBase, C, VBaseOffset, IndentLevel,
524 VBase == PrimaryBase ?
525 "(primary virtual base)" : "(virtual base)",
526 /*IncludeVirtualBases=*/false);
530 // FIXME: Maybe this could be useful in ASTContext.cpp.
531 void DumpRecordLayout(const CXXRecordDecl *RD, ASTContext &C) {
532 const ASTRecordLayout &Info = C.getASTRecordLayout(RD);
534 DumpRecordLayoutOffsets(RD, C, 0, 0, 0,
535 /*IncludeVirtualBases=*/true);
536 Out << " sizeof=" << Info.getSize() / 8;
537 Out << ", dsize=" << Info.getDataSize() / 8;
538 Out << ", align=" << Info.getAlignment() / 8 << '\n';
539 Out << " nvsize=" << Info.getNonVirtualSize() / 8;
540 Out << ", nvalign=" << Info.getNonVirtualAlign() / 8 << '\n';
545 RecordLayoutDumper() : Out(llvm::errs()) {}
547 void HandleTranslationUnit(ASTContext &C) {
548 for (ASTContext::type_iterator I = C.types_begin(), E = C.types_end();
550 const RecordType *RT = dyn_cast<RecordType>(*I);
554 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
558 if (RD->isImplicit())
561 if (RD->isDependentType())
564 if (RD->isInvalidDecl())
567 if (!RD->getDefinition(C))
570 // FIXME: Do we really need to hard code this?
571 if (RD->getQualifiedNameAsString() == "__va_list_tag")
574 DumpRecordLayout(RD, C);
578 } // end anonymous namespace
579 ASTConsumer *clang::CreateRecordLayoutDumper() {
580 return new RecordLayoutDumper();
583 //===----------------------------------------------------------------------===//
584 /// InheritanceViewer - C++ Inheritance Visualization
587 class InheritanceViewer : public ASTConsumer {
588 const std::string clsname;
590 InheritanceViewer(const std::string& cname) : clsname(cname) {}
592 void HandleTranslationUnit(ASTContext &C) {
593 for (ASTContext::type_iterator I=C.types_begin(),E=C.types_end(); I!=E; ++I)
594 if (RecordType *T = dyn_cast<RecordType>(*I)) {
595 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(T->getDecl())) {
596 // FIXME: This lookup needs to be generalized to handle namespaces and
597 // (when we support them) templates.
598 if (D->getNameAsString() == clsname) {
599 D->viewInheritance(C);
607 ASTConsumer *clang::CreateInheritanceViewer(const std::string& clsname) {
608 return new InheritanceViewer(clsname);