Get rid of a static boolean.
[oota-llvm.git] / lib / Analysis / ProfileInfoLoader.cpp
1 //===- ProfileInfoLoad.cpp - Load profile information from disk -----------===//
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 // The ProfileInfoLoader class is used to load and represent profiling
11 // information read in from the dump file.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/ProfileInfoLoader.h"
16 #include "llvm/Analysis/ProfileInfoTypes.h"
17 #include "llvm/Module.h"
18 #include "llvm/InstrTypes.h"
19 #include "llvm/Support/Streams.h"
20 #include <cstdio>
21 #include <cstdlib>
22 #include <map>
23 using namespace llvm;
24
25 // ByteSwap - Byteswap 'Var' if 'Really' is true.
26 //
27 static inline unsigned ByteSwap(unsigned Var, bool Really) {
28   if (!Really) return Var;
29   return ((Var & (255<< 0)) << 24) |
30          ((Var & (255<< 8)) <<  8) |
31          ((Var & (255<<16)) >>  8) |
32          ((Var & (255<<24)) >> 24);
33 }
34
35 static void ReadProfilingBlock(const char *ToolName, FILE *F,
36                                bool ShouldByteSwap,
37                                std::vector<unsigned> &Data) {
38   // Read the number of entries...
39   unsigned NumEntries;
40   if (fread(&NumEntries, sizeof(unsigned), 1, F) != 1) {
41     cerr << ToolName << ": data packet truncated!\n";
42     perror(0);
43     exit(1);
44   }
45   NumEntries = ByteSwap(NumEntries, ShouldByteSwap);
46
47   // Read the counts...
48   std::vector<unsigned> TempSpace(NumEntries);
49
50   // Read in the block of data...
51   if (fread(&TempSpace[0], sizeof(unsigned)*NumEntries, 1, F) != 1) {
52     cerr << ToolName << ": data packet truncated!\n";
53     perror(0);
54     exit(1);
55   }
56
57   // Make sure we have enough space...
58   if (Data.size() < NumEntries)
59     Data.resize(NumEntries);
60
61   // Accumulate the data we just read into the data.
62   if (!ShouldByteSwap) {
63     for (unsigned i = 0; i != NumEntries; ++i)
64       Data[i] += TempSpace[i];
65   } else {
66     for (unsigned i = 0; i != NumEntries; ++i)
67       Data[i] += ByteSwap(TempSpace[i], true);
68   }
69 }
70
71 // ProfileInfoLoader ctor - Read the specified profiling data file, exiting the
72 // program if the file is invalid or broken.
73 //
74 ProfileInfoLoader::ProfileInfoLoader(const char *ToolName,
75                                      const std::string &Filename,
76                                      Module &TheModule) : 
77                               M(TheModule), Warned(false) {
78   FILE *F = fopen(Filename.c_str(), "r");
79   if (F == 0) {
80     cerr << ToolName << ": Error opening '" << Filename << "': ";
81     perror(0);
82     exit(1);
83   }
84
85   // Keep reading packets until we run out of them.
86   unsigned PacketType;
87   while (fread(&PacketType, sizeof(unsigned), 1, F) == 1) {
88     // If the low eight bits of the packet are zero, we must be dealing with an
89     // endianness mismatch.  Byteswap all words read from the profiling
90     // information.
91     bool ShouldByteSwap = (char)PacketType == 0;
92     PacketType = ByteSwap(PacketType, ShouldByteSwap);
93
94     switch (PacketType) {
95     case ArgumentInfo: {
96       unsigned ArgLength;
97       if (fread(&ArgLength, sizeof(unsigned), 1, F) != 1) {
98         cerr << ToolName << ": arguments packet truncated!\n";
99         perror(0);
100         exit(1);
101       }
102       ArgLength = ByteSwap(ArgLength, ShouldByteSwap);
103
104       // Read in the arguments...
105       std::vector<char> Chars(ArgLength+4);
106
107       if (ArgLength)
108         if (fread(&Chars[0], (ArgLength+3) & ~3, 1, F) != 1) {
109           cerr << ToolName << ": arguments packet truncated!\n";
110           perror(0);
111           exit(1);
112         }
113       CommandLines.push_back(std::string(&Chars[0], &Chars[ArgLength]));
114       break;
115     }
116
117     case FunctionInfo:
118       ReadProfilingBlock(ToolName, F, ShouldByteSwap, FunctionCounts);
119       break;
120
121     case BlockInfo:
122       ReadProfilingBlock(ToolName, F, ShouldByteSwap, BlockCounts);
123       break;
124
125     case EdgeInfo:
126       ReadProfilingBlock(ToolName, F, ShouldByteSwap, EdgeCounts);
127       break;
128
129     case BBTraceInfo:
130       ReadProfilingBlock(ToolName, F, ShouldByteSwap, BBTrace);
131       break;
132
133     default:
134       cerr << ToolName << ": Unknown packet type #" << PacketType << "!\n";
135       exit(1);
136     }
137   }
138
139   fclose(F);
140 }
141
142
143 // getFunctionCounts - This method is used by consumers of function counting
144 // information.  If we do not directly have function count information, we
145 // compute it from other, more refined, types of profile information.
146 //
147 void ProfileInfoLoader::getFunctionCounts(std::vector<std::pair<Function*,
148                                                       unsigned> > &Counts) {
149   if (FunctionCounts.empty()) {
150     if (hasAccurateBlockCounts()) {
151       // Synthesize function frequency information from the number of times
152       // their entry blocks were executed.
153       std::vector<std::pair<BasicBlock*, unsigned> > BlockCounts;
154       getBlockCounts(BlockCounts);
155
156       for (unsigned i = 0, e = BlockCounts.size(); i != e; ++i)
157         if (&BlockCounts[i].first->getParent()->getEntryBlock() ==
158             BlockCounts[i].first)
159           Counts.push_back(std::make_pair(BlockCounts[i].first->getParent(),
160                                           BlockCounts[i].second));
161     } else {
162       cerr << "Function counts are not available!\n";
163     }
164     return;
165   }
166
167   unsigned Counter = 0;
168   for (Module::iterator I = M.begin(), E = M.end();
169        I != E && Counter != FunctionCounts.size(); ++I)
170     if (!I->isDeclaration())
171       Counts.push_back(std::make_pair(I, FunctionCounts[Counter++]));
172 }
173
174 // getBlockCounts - This method is used by consumers of block counting
175 // information.  If we do not directly have block count information, we
176 // compute it from other, more refined, types of profile information.
177 //
178 void ProfileInfoLoader::getBlockCounts(std::vector<std::pair<BasicBlock*,
179                                                          unsigned> > &Counts) {
180   if (BlockCounts.empty()) {
181     if (hasAccurateEdgeCounts()) {
182       // Synthesize block count information from edge frequency information.
183       // The block execution frequency is equal to the sum of the execution
184       // frequency of all outgoing edges from a block.
185       //
186       // If a block has no successors, this will not be correct, so we have to
187       // special case it. :(
188       std::vector<std::pair<Edge, unsigned> > EdgeCounts;
189       getEdgeCounts(EdgeCounts);
190
191       std::map<BasicBlock*, unsigned> InEdgeFreqs;
192
193       BasicBlock *LastBlock = 0;
194       TerminatorInst *TI = 0;
195       for (unsigned i = 0, e = EdgeCounts.size(); i != e; ++i) {
196         if (EdgeCounts[i].first.first != LastBlock) {
197           LastBlock = EdgeCounts[i].first.first;
198           TI = LastBlock->getTerminator();
199           Counts.push_back(std::make_pair(LastBlock, 0));
200         }
201         Counts.back().second += EdgeCounts[i].second;
202         unsigned SuccNum = EdgeCounts[i].first.second;
203         if (SuccNum >= TI->getNumSuccessors()) {
204           if (!Warned) {
205             cerr << "WARNING: profile info doesn't seem to match"
206                  << " the program!\n";
207             Warned = true;
208           }
209         } else {
210           // If this successor has no successors of its own, we will never
211           // compute an execution count for that block.  Remember the incoming
212           // edge frequencies to add later.
213           BasicBlock *Succ = TI->getSuccessor(SuccNum);
214           if (Succ->getTerminator()->getNumSuccessors() == 0)
215             InEdgeFreqs[Succ] += EdgeCounts[i].second;
216         }
217       }
218
219       // Now we have to accumulate information for those blocks without
220       // successors into our table.
221       for (std::map<BasicBlock*, unsigned>::iterator I = InEdgeFreqs.begin(),
222              E = InEdgeFreqs.end(); I != E; ++I) {
223         unsigned i = 0;
224         for (; i != Counts.size() && Counts[i].first != I->first; ++i)
225           /*empty*/;
226         if (i == Counts.size()) Counts.push_back(std::make_pair(I->first, 0));
227         Counts[i].second += I->second;
228       }
229
230     } else {
231       cerr << "Block counts are not available!\n";
232     }
233     return;
234   }
235
236   unsigned Counter = 0;
237   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
238     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
239       Counts.push_back(std::make_pair(BB, BlockCounts[Counter++]));
240       if (Counter == BlockCounts.size())
241         return;
242     }
243 }
244
245 // getEdgeCounts - This method is used by consumers of edge counting
246 // information.  If we do not directly have edge count information, we compute
247 // it from other, more refined, types of profile information.
248 //
249 void ProfileInfoLoader::getEdgeCounts(std::vector<std::pair<Edge,
250                                                   unsigned> > &Counts) {
251   if (EdgeCounts.empty()) {
252     cerr << "Edge counts not available, and no synthesis "
253          << "is implemented yet!\n";
254     return;
255   }
256
257   unsigned Counter = 0;
258   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
259     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
260       for (unsigned i = 0, e = BB->getTerminator()->getNumSuccessors();
261            i != e; ++i) {
262         Counts.push_back(std::make_pair(Edge(BB, i), EdgeCounts[Counter++]));
263         if (Counter == EdgeCounts.size())
264           return;
265       }
266 }
267
268 // getBBTrace - This method is used by consumers of basic-block trace
269 // information.
270 //
271 void ProfileInfoLoader::getBBTrace(std::vector<BasicBlock *> &Trace) {
272   if (BBTrace.empty ()) {
273     cerr << "Basic block trace is not available!\n";
274     return;
275   }
276   cerr << "Basic block trace loading is not implemented yet!\n";
277 }