1 //===-- Analyzer.cpp - Analysis and Dumping of Bytecode ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AnalyzerHandler class and PrintBytecodeAnalysis
11 // function which together comprise the basic functionality of the llmv-abcd
12 // tool. The AnalyzerHandler collects information about the bytecode file into
13 // the BytecodeAnalysis structure. The PrintBytecodeAnalysis function prints
14 // out the content of that structure.
15 // @see include/llvm/Bytecode/Analysis.h
17 //===----------------------------------------------------------------------===//
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/Analysis/Verifier.h"
24 #include "llvm/Bytecode/BytecodeHandler.h"
25 #include "llvm/Assembly/Writer.h"
33 /// @brief Bytecode reading handler for analyzing bytecode.
34 class AnalyzerHandler : public BytecodeHandler {
35 BytecodeAnalysis& bca; ///< The structure in which data is recorded
36 std::ostream* os; ///< A convenience for osing data.
37 /// @brief Keeps track of current function
38 BytecodeAnalysis::BytecodeFunctionInfo* currFunc;
39 Module* M; ///< Keeps track of current module
44 /// The only way to construct an AnalyzerHandler. All that is needed is a
45 /// reference to the BytecodeAnalysis structure where the output will be
47 AnalyzerHandler(BytecodeAnalysis& TheBca, std::ostream* output)
54 /// @name BytecodeHandler Implementations
57 virtual void handleError(const std::string& str ) {
59 *os << "ERROR: " << str << "\n";
62 virtual void handleStart( Module* Mod, unsigned theSize ) {
65 *os << "Bytecode {\n";
66 bca.byteSize = theSize;
73 bca.numGlobalVars = 0;
74 bca.numInstructions = 0;
75 bca.numBasicBlocks = 0;
77 bca.numCmpctnTables = 0;
84 bca.fileDensity = 0.0;
85 bca.globalsDensity = 0.0;
86 bca.functionDensity = 0.0;
87 bca.instructionSize = 0;
88 bca.longInstructions = 0;
89 bca.FunctionInfo.clear();
90 bca.BlockSizes[BytecodeFormat::Reserved_DoNotUse] = 0;
91 bca.BlockSizes[BytecodeFormat::ModuleBlockID] = theSize;
92 bca.BlockSizes[BytecodeFormat::FunctionBlockID] = 0;
93 bca.BlockSizes[BytecodeFormat::ConstantPoolBlockID] = 0;
94 bca.BlockSizes[BytecodeFormat::ValueSymbolTableBlockID] = 0;
95 bca.BlockSizes[BytecodeFormat::ModuleGlobalInfoBlockID] = 0;
96 bca.BlockSizes[BytecodeFormat::GlobalTypePlaneBlockID] = 0;
97 bca.BlockSizes[BytecodeFormat::InstructionListBlockID] = 0;
98 bca.BlockSizes[BytecodeFormat::TypeSymbolTableBlockID] = 0;
101 virtual void handleFinish() {
103 *os << "} End Bytecode\n";
105 bca.fileDensity = double(bca.byteSize) / double( bca.numTypes + bca.numValues );
106 double globalSize = 0.0;
107 globalSize += double(bca.BlockSizes[BytecodeFormat::ConstantPoolBlockID]);
108 globalSize += double(bca.BlockSizes[BytecodeFormat::ModuleGlobalInfoBlockID]);
109 globalSize += double(bca.BlockSizes[BytecodeFormat::GlobalTypePlaneBlockID]);
110 bca.globalsDensity = globalSize / double( bca.numTypes + bca.numConstants +
112 bca.functionDensity = double(bca.BlockSizes[BytecodeFormat::FunctionBlockID]) /
113 double(bca.numFunctions);
115 if (bca.progressiveVerify) {
117 if (verifyModule(*M, ReturnStatusAction, &msg))
118 bca.VerifyInfo += "Verify@Finish: " + msg + "\n";
122 virtual void handleModuleBegin(const std::string& id) {
124 *os << " Module " << id << " {\n";
128 virtual void handleModuleEnd(const std::string& id) {
130 *os << " } End Module " << id << "\n";
131 if (bca.progressiveVerify) {
133 if (verifyModule(*M, ReturnStatusAction, &msg))
134 bca.VerifyInfo += "Verify@EndModule: " + msg + "\n";
138 virtual void handleVersionInfo(
139 unsigned char RevisionNum ///< Byte code revision number
142 *os << " RevisionNum: " << int(RevisionNum) << "\n";
143 bca.version = RevisionNum;
146 virtual void handleModuleGlobalsBegin() {
148 *os << " BLOCK: ModuleGlobalInfo {\n";
151 virtual void handleGlobalVariable(
152 const Type* ElemType,
154 GlobalValue::LinkageTypes Linkage,
155 GlobalValue::VisibilityTypes Visibility,
161 << ( initSlot == 0 ? "Uni" : "I" ) << "nitialized, "
162 << ( isConstant? "Constant, " : "Variable, ")
163 << " Linkage=" << Linkage
164 << " Visibility="<< Visibility
166 WriteTypeSymbolic(*os, ElemType, M);
167 *os << " Slot=" << SlotNum << " InitSlot=" << initSlot
173 if (SlotNum > bca.maxValueSlot)
174 bca.maxValueSlot = SlotNum;
175 if (initSlot > bca.maxValueSlot)
176 bca.maxValueSlot = initSlot;
180 virtual void handleTypeList(unsigned numEntries) {
181 bca.maxTypeSlot = numEntries - 1;
184 virtual void handleType( const Type* Ty ) {
188 WriteTypeSymbolic(*os,Ty,M);
193 virtual void handleFunctionDeclaration(
194 Function* Func ///< The function
199 *os << " Function Decl: ";
200 WriteTypeSymbolic(*os,Func->getType(),M);
201 *os <<", Linkage=" << Func->getLinkage();
202 *os <<", Visibility=" << Func->getVisibility();
207 virtual void handleGlobalInitializer(GlobalVariable* GV, Constant* CV) {
209 *os << " Initializer: GV=";
217 virtual void handleDependentLibrary(const std::string& libName) {
219 bca.libSize += libName.size() + (libName.size() < 128 ? 1 : 2);
221 *os << " Library: '" << libName << "'\n";
224 virtual void handleModuleGlobalsEnd() {
226 *os << " } END BLOCK: ModuleGlobalInfo\n";
227 if (bca.progressiveVerify) {
229 if (verifyModule(*M, ReturnStatusAction, &msg))
230 bca.VerifyInfo += "Verify@EndModuleGlobalInfo: " + msg + "\n";
234 virtual void handleTypeSymbolTableBegin(TypeSymbolTable* ST) {
237 *os << " BLOCK: TypeSymbolTable {\n";
239 virtual void handleValueSymbolTableBegin(Function* CF, ValueSymbolTable* ST) {
242 *os << " BLOCK: ValueSymbolTable {\n";
245 virtual void handleSymbolTableType(unsigned i, unsigned TypSlot,
246 const std::string& name ) {
248 *os << " Type " << i << " Slot=" << TypSlot
249 << " Name: " << name << "\n";
252 virtual void handleSymbolTableValue(unsigned TySlot, unsigned ValSlot,
253 const char *Name, unsigned NameLen) {
255 *os << " Value " << TySlot << " Slot=" << ValSlot
256 << " Name: " << std::string(Name, Name+NameLen) << "\n";
257 if (ValSlot > bca.maxValueSlot)
258 bca.maxValueSlot = ValSlot;
261 virtual void handleValueSymbolTableEnd() {
263 *os << " } END BLOCK: ValueSymbolTable\n";
266 virtual void handleTypeSymbolTableEnd() {
268 *os << " } END BLOCK: TypeSymbolTable\n";
271 virtual void handleFunctionBegin(Function* Func, unsigned Size) {
273 *os << " BLOCK: Function {\n"
274 << " Linkage: " << Func->getLinkage() << "\n"
275 << " Visibility: " << Func->getVisibility() << "\n"
277 WriteTypeSymbolic(*os,Func->getType(),M);
281 currFunc = &bca.FunctionInfo[Func];
282 std::ostringstream tmp;
283 WriteTypeSymbolic(tmp,Func->getType(),M);
284 currFunc->description = tmp.str();
285 currFunc->name = Func->getName();
286 currFunc->byteSize = Size;
287 currFunc->numInstructions = 0;
288 currFunc->numBasicBlocks = 0;
289 currFunc->numPhis = 0;
290 currFunc->numOperands = 0;
291 currFunc->density = 0.0;
292 currFunc->instructionSize = 0;
293 currFunc->longInstructions = 0;
297 virtual void handleFunctionEnd( Function* Func) {
299 *os << " } END BLOCK: Function\n";
300 currFunc->density = double(currFunc->byteSize) /
301 double(currFunc->numInstructions);
303 if (bca.progressiveVerify) {
305 if (verifyModule(*M, ReturnStatusAction, &msg))
306 bca.VerifyInfo += "Verify@EndFunction: " + msg + "\n";
310 virtual void handleBasicBlockBegin( unsigned blocknum) {
312 *os << " BLOCK: BasicBlock #" << blocknum << "{\n";
313 bca.numBasicBlocks++;
315 if ( currFunc ) currFunc->numBasicBlocks++;
318 virtual bool handleInstruction( unsigned Opcode, const Type* iType,
319 unsigned *Operands, unsigned NumOps,
323 *os << " INST: OpCode="
324 << Instruction::getOpcodeName(Opcode);
325 for (unsigned i = 0; i != NumOps; ++i)
326 *os << " Op(" << Operands[i] << ")";
330 bca.numInstructions++;
332 bca.instructionSize += Size;
333 if (Size > 4 ) bca.longInstructions++;
334 bca.numOperands += NumOps;
335 for (unsigned i = 0; i != NumOps; ++i)
336 if (Operands[i] > bca.maxValueSlot)
337 bca.maxValueSlot = Operands[i];
339 currFunc->numInstructions++;
340 currFunc->instructionSize += Size;
341 if (Size > 4 ) currFunc->longInstructions++;
342 if (Opcode == Instruction::PHI) currFunc->numPhis++;
344 return Instruction::isTerminator(Opcode);
347 virtual void handleBasicBlockEnd(unsigned blocknum) {
349 *os << " } END BLOCK: BasicBlock #" << blocknum << "\n";
352 virtual void handleGlobalConstantsBegin() {
354 *os << " BLOCK: GlobalConstants {\n";
357 virtual void handleConstantExpression(unsigned Opcode,
358 Constant**ArgVec, unsigned NumArgs, Constant* C) {
360 *os << " EXPR: " << Instruction::getOpcodeName(Opcode) << "\n";
361 for ( unsigned i = 0; i != NumArgs; ++i ) {
362 *os << " Arg#" << i << " "; ArgVec[i]->print(*os);
373 virtual void handleConstantValue( Constant * c ) {
383 virtual void handleConstantArray( const ArrayType* AT,
384 Constant**Elements, unsigned NumElts,
386 Constant* ArrayVal ) {
389 WriteTypeSymbolic(*os,AT,M);
390 *os << " TypeSlot=" << TypeSlot << "\n";
391 for (unsigned i = 0; i != NumElts; ++i) {
393 Elements[i]->print(*os);
397 ArrayVal->print(*os);
405 virtual void handleConstantStruct(
406 const StructType* ST,
407 Constant**Elements, unsigned NumElts,
412 WriteTypeSymbolic(*os,ST,M);
414 for ( unsigned i = 0; i != NumElts; ++i) {
415 *os << " #" << i << " "; Elements[i]->print(*os);
419 StructVal->print(*os);
426 virtual void handleConstantVector(
427 const VectorType* PT,
428 Constant**Elements, unsigned NumElts,
434 WriteTypeSymbolic(*os,PT,M);
435 *os << " TypeSlot=" << TypeSlot << "\n";
436 for ( unsigned i = 0; i != NumElts; ++i ) {
438 Elements[i]->print(*os);
442 VectorVal->print(*os);
450 virtual void handleConstantPointer( const PointerType* PT,
451 unsigned Slot, GlobalValue* GV ) {
454 WriteTypeSymbolic(*os,PT,M);
455 *os << " Slot=" << Slot << " GlobalValue=";
463 virtual void handleConstantString( const ConstantArray* CA ) {
473 virtual void handleGlobalConstantsEnd() {
475 *os << " } END BLOCK: GlobalConstants\n";
477 if (bca.progressiveVerify) {
479 if (verifyModule(*M, ReturnStatusAction, &msg))
480 bca.VerifyInfo += "Verify@EndGlobalConstants: " + msg + "\n";
484 virtual void handleAlignment(unsigned numBytes) {
485 bca.numAlignment += numBytes;
488 virtual void handleBlock(
489 unsigned BType, const unsigned char* StartPtr, unsigned Size) {
491 assert(BType >= BytecodeFormat::ModuleBlockID);
492 assert(BType < BytecodeFormat::NumberOfBlockIDs);
494 llvm::BytecodeFormat::BytecodeBlockIdentifiers(BType)] += Size;
496 if (bca.version < 3) // Check for long block headers versions
497 bca.BlockSizes[llvm::BytecodeFormat::Reserved_DoNotUse] += 8;
499 bca.BlockSizes[llvm::BytecodeFormat::Reserved_DoNotUse] += 4;
503 } // end anonymous namespace
505 /// @brief Utility for printing a titled unsigned value with
506 /// an aligned colon.
507 inline static void print(std::ostream& Out, const char*title,
508 unsigned val, bool nl = true ) {
509 Out << std::setw(30) << std::right << title
510 << std::setw(0) << ": "
511 << std::setw(9) << val << "\n";
514 /// @brief Utility for printing a titled double value with an
516 inline static void print(std::ostream&Out, const char*title,
518 Out << std::setw(30) << std::right << title
519 << std::setw(0) << ": "
520 << std::setw(9) << std::setprecision(6) << val << "\n" ;
523 /// @brief Utility for printing a titled double value with a
524 /// percentage and aligned colon.
525 inline static void print(std::ostream&Out, const char*title,
526 double top, double bot ) {
527 Out << std::setw(30) << std::right << title
528 << std::setw(0) << ": "
529 << std::setw(9) << std::setprecision(6) << top
530 << " (" << std::left << std::setw(0) << std::setprecision(4)
531 << (top/bot)*100.0 << "%)\n";
534 /// @brief Utility for printing a titled string value with
535 /// an aligned colon.
536 inline static void print(std::ostream&Out, const char*title,
537 std::string val, bool nl = true) {
538 Out << std::setw(30) << std::right << title
539 << std::setw(0) << ": "
540 << std::left << val << (nl ? "\n" : "");
543 /// This function prints the contents of rhe BytecodeAnalysis structure in
544 /// a human legible form.
545 /// @brief Print BytecodeAnalysis structure to an ostream
546 void llvm::PrintBytecodeAnalysis(BytecodeAnalysis& bca, std::ostream& Out )
548 Out << "\nSummary Analysis Of " << bca.ModuleId << ": \n\n";
549 print(Out, "Bytecode Analysis Of Module", bca.ModuleId);
550 print(Out, "Bytecode Version Number", bca.version);
551 print(Out, "File Size", bca.byteSize);
552 print(Out, "Module Bytes",
553 double(bca.BlockSizes[BytecodeFormat::ModuleBlockID]),
554 double(bca.byteSize));
555 print(Out, "Function Bytes",
556 double(bca.BlockSizes[BytecodeFormat::FunctionBlockID]),
557 double(bca.byteSize));
558 print(Out, "Global Types Bytes",
559 double(bca.BlockSizes[BytecodeFormat::GlobalTypePlaneBlockID]),
560 double(bca.byteSize));
561 print(Out, "Constant Pool Bytes",
562 double(bca.BlockSizes[BytecodeFormat::ConstantPoolBlockID]),
563 double(bca.byteSize));
564 print(Out, "Module Globals Bytes",
565 double(bca.BlockSizes[BytecodeFormat::ModuleGlobalInfoBlockID]),
566 double(bca.byteSize));
567 print(Out, "Instruction List Bytes",
568 double(bca.BlockSizes[BytecodeFormat::InstructionListBlockID]),
569 double(bca.byteSize));
570 print(Out, "Value Symbol Table Bytes",
571 double(bca.BlockSizes[BytecodeFormat::ValueSymbolTableBlockID]),
572 double(bca.byteSize));
573 print(Out, "Type Symbol Table Bytes",
574 double(bca.BlockSizes[BytecodeFormat::TypeSymbolTableBlockID]),
575 double(bca.byteSize));
576 print(Out, "Alignment Bytes",
577 double(bca.numAlignment), double(bca.byteSize));
578 print(Out, "Block Header Bytes",
579 double(bca.BlockSizes[BytecodeFormat::Reserved_DoNotUse]),
580 double(bca.byteSize));
581 print(Out, "Dependent Libraries Bytes", double(bca.libSize),
582 double(bca.byteSize));
583 print(Out, "Number Of Bytecode Blocks", bca.numBlocks);
584 print(Out, "Number Of Functions", bca.numFunctions);
585 print(Out, "Number Of Types", bca.numTypes);
586 print(Out, "Number Of Constants", bca.numConstants);
587 print(Out, "Number Of Global Variables", bca.numGlobalVars);
588 print(Out, "Number Of Values", bca.numValues);
589 print(Out, "Number Of Basic Blocks", bca.numBasicBlocks);
590 print(Out, "Number Of Instructions", bca.numInstructions);
591 print(Out, "Number Of Long Instructions", bca.longInstructions);
592 print(Out, "Number Of Operands", bca.numOperands);
593 print(Out, "Number Of Symbol Tables", bca.numSymTab);
594 print(Out, "Number Of Dependent Libs", bca.numLibraries);
595 print(Out, "Total Instruction Size", bca.instructionSize);
596 print(Out, "Average Instruction Size",
597 double(bca.instructionSize)/double(bca.numInstructions));
599 print(Out, "Maximum Type Slot Number", bca.maxTypeSlot);
600 print(Out, "Maximum Value Slot Number", bca.maxValueSlot);
601 print(Out, "Bytes Per Value ", bca.fileDensity);
602 print(Out, "Bytes Per Global", bca.globalsDensity);
603 print(Out, "Bytes Per Function", bca.functionDensity);
605 if (bca.detailedResults) {
606 Out << "\nDetailed Analysis Of " << bca.ModuleId << " Functions:\n";
608 std::map<const Function*,BytecodeAnalysis::BytecodeFunctionInfo>::iterator I =
609 bca.FunctionInfo.begin();
610 std::map<const Function*,BytecodeAnalysis::BytecodeFunctionInfo>::iterator E =
611 bca.FunctionInfo.end();
614 Out << std::left << std::setw(0) << "\n";
615 if (I->second.numBasicBlocks == 0) Out << "External ";
616 Out << "Function: " << I->second.name << "\n";
617 print(Out, "Type:", I->second.description);
618 print(Out, "Byte Size", I->second.byteSize);
619 if (I->second.numBasicBlocks) {
620 print(Out, "Basic Blocks", I->second.numBasicBlocks);
621 print(Out, "Instructions", I->second.numInstructions);
622 print(Out, "Long Instructions", I->second.longInstructions);
623 print(Out, "Operands", I->second.numOperands);
624 print(Out, "Instruction Size", I->second.instructionSize);
625 print(Out, "Average Instruction Size",
626 double(I->second.instructionSize) / I->second.numInstructions);
627 print(Out, "Bytes Per Instruction", I->second.density);
633 if ( bca.progressiveVerify )
634 Out << bca.VerifyInfo;
637 // AnalyzeBytecodeFile - analyze one file
638 Module* llvm::AnalyzeBytecodeFile(const std::string &Filename, ///< File to analyze
639 BytecodeAnalysis& bca, ///< Statistical output
640 BCDecompressor_t *BCDC,
641 std::string *ErrMsg, ///< Error output
642 std::ostream* output ///< Dump output
644 BytecodeHandler* AH = new AnalyzerHandler(bca, output);
645 ModuleProvider* MP = getBytecodeModuleProvider(Filename, BCDC, ErrMsg, AH);
647 Module *M = MP->releaseModule(ErrMsg);