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