blob: 86df30e5475ae89087f8fa5aad4c9a5f17b47d95 [file] [log] [blame]
Justin Bogneref512b92014-01-06 22:27:43 +00001//===--- CodeGenPGO.cpp - PGO Instrumentation for LLVM CodeGen --*- C++ -*-===//
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// Instrumentation-based profile-guided optimization
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenPGO.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/RecursiveASTVisitor.h"
17#include "clang/AST/StmtVisitor.h"
Justin Bogner529f6dd2014-01-07 03:43:15 +000018#include "llvm/Config/config.h" // for strtoull()/strtoll() define
Justin Bogneref512b92014-01-06 22:27:43 +000019#include "llvm/IR/MDBuilder.h"
20#include "llvm/Support/FileSystem.h"
21
22using namespace clang;
23using namespace CodeGen;
24
Justin Bognerd66a17d2014-03-12 21:06:31 +000025static void ReportBadPGOData(CodeGenModule &CGM, const char *Message) {
26 DiagnosticsEngine &Diags = CGM.getDiags();
27 unsigned diagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0");
28 Diags.Report(diagID) << Message;
29}
30
31PGOProfileData::PGOProfileData(CodeGenModule &CGM, std::string Path)
32 : CGM(CGM) {
33 if (llvm::MemoryBuffer::getFile(Path, DataBuffer)) {
34 ReportBadPGOData(CGM, "failed to open pgo data file");
35 return;
36 }
37
38 if (DataBuffer->getBufferSize() > std::numeric_limits<unsigned>::max()) {
39 ReportBadPGOData(CGM, "pgo data file too big");
40 return;
41 }
42
43 // Scan through the data file and map each function to the corresponding
44 // file offset where its counts are stored.
45 const char *BufferStart = DataBuffer->getBufferStart();
46 const char *BufferEnd = DataBuffer->getBufferEnd();
47 const char *CurPtr = BufferStart;
48 uint64_t MaxCount = 0;
49 while (CurPtr < BufferEnd) {
50 // Read the function name.
51 const char *FuncStart = CurPtr;
52 // For Objective-C methods, the name may include whitespace, so search
53 // backward from the end of the line to find the space that separates the
54 // name from the number of counters. (This is a temporary hack since we are
55 // going to completely replace this file format in the near future.)
56 CurPtr = strchr(CurPtr, '\n');
57 if (!CurPtr) {
58 ReportBadPGOData(CGM, "pgo data file has malformed function entry");
59 return;
60 }
Justin Bognerd66a17d2014-03-12 21:06:31 +000061 StringRef FuncName(FuncStart, CurPtr - FuncStart);
62
Justin Bognerb4416f52014-03-18 21:58:06 +000063 // Skip over the function hash.
64 CurPtr = strchr(++CurPtr, '\n');
65 if (!CurPtr) {
66 ReportBadPGOData(CGM, "pgo data file is missing the function hash");
67 return;
68 }
69
Justin Bognerd66a17d2014-03-12 21:06:31 +000070 // Read the number of counters.
71 char *EndPtr;
72 unsigned NumCounters = strtol(++CurPtr, &EndPtr, 10);
73 if (EndPtr == CurPtr || *EndPtr != '\n' || NumCounters <= 0) {
74 ReportBadPGOData(CGM, "pgo data file has unexpected number of counters");
75 return;
76 }
77 CurPtr = EndPtr;
78
79 // Read function count.
80 uint64_t Count = strtoll(CurPtr, &EndPtr, 10);
81 if (EndPtr == CurPtr || *EndPtr != '\n') {
82 ReportBadPGOData(CGM, "pgo-data file has bad count value");
83 return;
84 }
85 CurPtr = EndPtr; // Point to '\n'.
86 FunctionCounts[FuncName] = Count;
87 MaxCount = Count > MaxCount ? Count : MaxCount;
88
89 // There is one line for each counter; skip over those lines.
90 // Since function count is already read, we start the loop from 1.
91 for (unsigned N = 1; N < NumCounters; ++N) {
92 CurPtr = strchr(++CurPtr, '\n');
93 if (!CurPtr) {
94 ReportBadPGOData(CGM, "pgo data file is missing some counter info");
95 return;
96 }
97 }
98
99 // Skip over the blank line separating functions.
100 CurPtr += 2;
101
102 DataOffsets[FuncName] = FuncStart - BufferStart;
103 }
104 MaxFunctionCount = MaxCount;
105}
106
Justin Bognerb4416f52014-03-18 21:58:06 +0000107bool PGOProfileData::getFunctionCounts(StringRef FuncName, uint64_t &FuncHash,
Justin Bognerd66a17d2014-03-12 21:06:31 +0000108 std::vector<uint64_t> &Counts) {
109 // Find the relevant section of the pgo-data file.
110 llvm::StringMap<unsigned>::const_iterator OffsetIter =
111 DataOffsets.find(FuncName);
112 if (OffsetIter == DataOffsets.end())
113 return true;
114 const char *CurPtr = DataBuffer->getBufferStart() + OffsetIter->getValue();
115
116 // Skip over the function name.
117 CurPtr = strchr(CurPtr, '\n');
118 assert(CurPtr && "pgo-data has corrupted function entry");
Justin Bognerb4416f52014-03-18 21:58:06 +0000119
120 char *EndPtr;
121 // Read the function hash.
122 FuncHash = strtoll(++CurPtr, &EndPtr, 10);
123 assert(EndPtr != CurPtr && *EndPtr == '\n' &&
124 "pgo-data file has corrupted function hash");
125 CurPtr = EndPtr;
Justin Bognerd66a17d2014-03-12 21:06:31 +0000126
127 // Read the number of counters.
Justin Bognerd66a17d2014-03-12 21:06:31 +0000128 unsigned NumCounters = strtol(++CurPtr, &EndPtr, 10);
129 assert(EndPtr != CurPtr && *EndPtr == '\n' && NumCounters > 0 &&
130 "pgo-data file has corrupted number of counters");
131 CurPtr = EndPtr;
132
133 Counts.reserve(NumCounters);
134
135 for (unsigned N = 0; N < NumCounters; ++N) {
136 // Read the count value.
137 uint64_t Count = strtoll(CurPtr, &EndPtr, 10);
138 if (EndPtr == CurPtr || *EndPtr != '\n') {
139 ReportBadPGOData(CGM, "pgo-data file has bad count value");
140 return true;
141 }
142 Counts.push_back(Count);
143 CurPtr = EndPtr + 1;
144 }
145
146 // Make sure the number of counters matches up.
147 if (Counts.size() != NumCounters) {
148 ReportBadPGOData(CGM, "pgo-data file has inconsistent counters");
149 return true;
150 }
151
152 return false;
153}
154
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000155void CodeGenPGO::setFuncName(llvm::Function *Fn) {
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000156 RawFuncName = Fn->getName();
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000157
158 // Function names may be prefixed with a binary '1' to indicate
159 // that the backend should not modify the symbols due to any platform
160 // naming convention. Do not include that '1' in the PGO profile name.
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000161 if (RawFuncName[0] == '\1')
162 RawFuncName = RawFuncName.substr(1);
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000163
164 if (!Fn->hasLocalLinkage()) {
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000165 PrefixedFuncName = new std::string(RawFuncName);
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000166 return;
167 }
168
169 // For local symbols, prepend the main file name to distinguish them.
170 // Do not include the full path in the file name since there's no guarantee
171 // that it will stay the same, e.g., if the files are checked out from
172 // version control in different locations.
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000173 PrefixedFuncName = new std::string(CGM.getCodeGenOpts().MainFileName);
174 if (PrefixedFuncName->empty())
175 PrefixedFuncName->assign("<unknown>");
176 PrefixedFuncName->append(":");
177 PrefixedFuncName->append(RawFuncName);
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000178}
179
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000180static llvm::Function *getRegisterFunc(CodeGenModule &CGM) {
181 return CGM.getModule().getFunction("__llvm_pgo_register_functions");
182}
183
184static llvm::BasicBlock *getOrInsertRegisterBB(CodeGenModule &CGM) {
185 // Only need to insert this once per module.
186 if (llvm::Function *RegisterF = getRegisterFunc(CGM))
187 return &RegisterF->getEntryBlock();
188
189 // Construct the function.
190 auto *VoidTy = llvm::Type::getVoidTy(CGM.getLLVMContext());
191 auto *RegisterFTy = llvm::FunctionType::get(VoidTy, false);
192 auto *RegisterF = llvm::Function::Create(RegisterFTy,
193 llvm::GlobalValue::InternalLinkage,
194 "__llvm_pgo_register_functions",
195 &CGM.getModule());
196 RegisterF->setUnnamedAddr(true);
197 RegisterF->addFnAttr(llvm::Attribute::NoInline);
198 if (CGM.getCodeGenOpts().DisableRedZone)
199 RegisterF->addFnAttr(llvm::Attribute::NoRedZone);
200
201 // Construct and return the entry block.
202 auto *BB = llvm::BasicBlock::Create(CGM.getLLVMContext(), "", RegisterF);
203 CGBuilderTy Builder(BB);
204 Builder.CreateRetVoid();
205 return BB;
206}
207
208static llvm::Constant *getOrInsertRuntimeRegister(CodeGenModule &CGM) {
209 auto *VoidTy = llvm::Type::getVoidTy(CGM.getLLVMContext());
210 auto *VoidPtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
211 auto *RuntimeRegisterTy = llvm::FunctionType::get(VoidTy, VoidPtrTy, false);
212 return CGM.getModule().getOrInsertFunction("__llvm_pgo_register_function",
213 RuntimeRegisterTy);
214}
215
216static llvm::Constant *getOrInsertRuntimeWriteAtExit(CodeGenModule &CGM) {
217 // TODO: make this depend on a command-line option.
218 auto *VoidTy = llvm::Type::getVoidTy(CGM.getLLVMContext());
219 auto *WriteAtExitTy = llvm::FunctionType::get(VoidTy, false);
220 return CGM.getModule().getOrInsertFunction("__llvm_pgo_register_write_atexit",
221 WriteAtExitTy);
222}
223
Duncan P. N. Exon Smith7134d472014-03-20 03:17:15 +0000224static bool isMachO(const CodeGenModule &CGM) {
225 return CGM.getTarget().getTriple().isOSBinFormatMachO();
226}
227
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000228static StringRef getCountersSection(const CodeGenModule &CGM) {
Duncan P. N. Exon Smith7134d472014-03-20 03:17:15 +0000229 return isMachO(CGM) ? "__DATA,__llvm_pgo_cnts" : "__llvm_pgo_cnts";
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000230}
231
232static StringRef getNameSection(const CodeGenModule &CGM) {
Duncan P. N. Exon Smith7134d472014-03-20 03:17:15 +0000233 return isMachO(CGM) ? "__DATA,__llvm_pgo_names" : "__llvm_pgo_names";
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000234}
235
236static StringRef getDataSection(const CodeGenModule &CGM) {
Duncan P. N. Exon Smith7134d472014-03-20 03:17:15 +0000237 return isMachO(CGM) ? "__DATA,__llvm_pgo_data" : "__llvm_pgo_data";
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000238}
239
240llvm::GlobalVariable *CodeGenPGO::buildDataVar() {
241 // Create name variable.
242 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
243 auto *VarName = llvm::ConstantDataArray::getString(Ctx, getFuncName(),
244 false);
245 auto *Name = new llvm::GlobalVariable(CGM.getModule(), VarName->getType(),
246 true, FuncLinkage, VarName,
247 getFuncVarName("name"));
248 Name->setSection(getNameSection(CGM));
249 Name->setAlignment(1);
250
251 // Create data variable.
252 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
Justin Bognerb4416f52014-03-18 21:58:06 +0000253 auto *Int64Ty = llvm::Type::getInt64Ty(Ctx);
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000254 auto *Int8PtrTy = llvm::Type::getInt8PtrTy(Ctx);
255 auto *Int64PtrTy = llvm::Type::getInt64PtrTy(Ctx);
256 llvm::Type *DataTypes[] = {
Justin Bognerb4416f52014-03-18 21:58:06 +0000257 Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int64PtrTy
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000258 };
259 auto *DataTy = llvm::StructType::get(Ctx, makeArrayRef(DataTypes));
260 llvm::Constant *DataVals[] = {
261 llvm::ConstantInt::get(Int32Ty, getFuncName().size()),
262 llvm::ConstantInt::get(Int32Ty, NumRegionCounters),
Justin Bognerb4416f52014-03-18 21:58:06 +0000263 llvm::ConstantInt::get(Int64Ty, FunctionHash),
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000264 llvm::ConstantExpr::getBitCast(Name, Int8PtrTy),
265 llvm::ConstantExpr::getBitCast(RegionCounters, Int64PtrTy)
266 };
267 auto *Data =
268 new llvm::GlobalVariable(CGM.getModule(), DataTy, true, FuncLinkage,
269 llvm::ConstantStruct::get(DataTy, DataVals),
270 getFuncVarName("data"));
271
272 // All the data should be packed into an array in its own section.
273 Data->setSection(getDataSection(CGM));
274 Data->setAlignment(8);
275
276 // Make sure the data doesn't get deleted.
277 CGM.addUsedGlobal(Data);
278 return Data;
279}
280
281void CodeGenPGO::emitInstrumentationData() {
Justin Bogneref512b92014-01-06 22:27:43 +0000282 if (!CGM.getCodeGenOpts().ProfileInstrGenerate)
283 return;
284
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000285 // Build the data.
286 auto *Data = buildDataVar();
Justin Bogneref512b92014-01-06 22:27:43 +0000287
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000288 // Register the data.
289 //
290 // TODO: only register when static initialization is required.
291 CGBuilderTy Builder(getOrInsertRegisterBB(CGM)->getTerminator());
292 auto *VoidPtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
293 Builder.CreateCall(getOrInsertRuntimeRegister(CGM),
294 Builder.CreateBitCast(Data, VoidPtrTy));
Justin Bogneref512b92014-01-06 22:27:43 +0000295}
296
297llvm::Function *CodeGenPGO::emitInitialization(CodeGenModule &CGM) {
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000298 if (!CGM.getCodeGenOpts().ProfileInstrGenerate)
299 return 0;
Justin Bogneref512b92014-01-06 22:27:43 +0000300
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000301 // Only need to create this once per module.
302 if (CGM.getModule().getFunction("__llvm_pgo_init"))
303 return 0;
Justin Bogneref512b92014-01-06 22:27:43 +0000304
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000305 // Get the functions to call at initialization.
306 llvm::Constant *RegisterF = getRegisterFunc(CGM);
307 llvm::Constant *WriteAtExitF = getOrInsertRuntimeWriteAtExit(CGM);
308 if (!RegisterF && !WriteAtExitF)
309 return 0;
310
311 // Create the initialization function.
312 auto *VoidTy = llvm::Type::getVoidTy(CGM.getLLVMContext());
313 auto *F = llvm::Function::Create(llvm::FunctionType::get(VoidTy, false),
314 llvm::GlobalValue::InternalLinkage,
315 "__llvm_pgo_init", &CGM.getModule());
Justin Bogneref512b92014-01-06 22:27:43 +0000316 F->setUnnamedAddr(true);
Justin Bogneref512b92014-01-06 22:27:43 +0000317 F->addFnAttr(llvm::Attribute::NoInline);
318 if (CGM.getCodeGenOpts().DisableRedZone)
319 F->addFnAttr(llvm::Attribute::NoRedZone);
320
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000321 // Add the basic block and the necessary calls.
322 CGBuilderTy Builder(llvm::BasicBlock::Create(CGM.getLLVMContext(), "", F));
323 if (RegisterF)
324 Builder.CreateCall(RegisterF);
325 if (WriteAtExitF)
326 Builder.CreateCall(WriteAtExitF);
327 Builder.CreateRetVoid();
Justin Bogneref512b92014-01-06 22:27:43 +0000328
329 return F;
330}
331
332namespace {
333 /// A StmtVisitor that fills a map of statements to PGO counters.
334 struct MapRegionCounters : public ConstStmtVisitor<MapRegionCounters> {
335 /// The next counter value to assign.
336 unsigned NextCounter;
337 /// The map of statements to counters.
338 llvm::DenseMap<const Stmt*, unsigned> *CounterMap;
339
340 MapRegionCounters(llvm::DenseMap<const Stmt*, unsigned> *CounterMap) :
341 NextCounter(0), CounterMap(CounterMap) {
342 }
343
344 void VisitChildren(const Stmt *S) {
345 for (Stmt::const_child_range I = S->children(); I; ++I)
346 if (*I)
347 this->Visit(*I);
348 }
349 void VisitStmt(const Stmt *S) { VisitChildren(S); }
350
Justin Bognerea278c32014-01-07 00:20:28 +0000351 /// Assign a counter to track entry to the function body.
Justin Bogneref512b92014-01-06 22:27:43 +0000352 void VisitFunctionDecl(const FunctionDecl *S) {
353 (*CounterMap)[S->getBody()] = NextCounter++;
354 Visit(S->getBody());
355 }
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000356 void VisitObjCMethodDecl(const ObjCMethodDecl *S) {
357 (*CounterMap)[S->getBody()] = NextCounter++;
358 Visit(S->getBody());
359 }
Bob Wilsonc845c002014-03-06 20:24:27 +0000360 void VisitBlockDecl(const BlockDecl *S) {
361 (*CounterMap)[S->getBody()] = NextCounter++;
362 Visit(S->getBody());
363 }
Justin Bognerea278c32014-01-07 00:20:28 +0000364 /// Assign a counter to track the block following a label.
Justin Bogneref512b92014-01-06 22:27:43 +0000365 void VisitLabelStmt(const LabelStmt *S) {
366 (*CounterMap)[S] = NextCounter++;
367 Visit(S->getSubStmt());
368 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000369 /// Assign a counter for the body of a while loop.
Justin Bogneref512b92014-01-06 22:27:43 +0000370 void VisitWhileStmt(const WhileStmt *S) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000371 (*CounterMap)[S] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000372 Visit(S->getCond());
373 Visit(S->getBody());
374 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000375 /// Assign a counter for the body of a do-while loop.
Justin Bogneref512b92014-01-06 22:27:43 +0000376 void VisitDoStmt(const DoStmt *S) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000377 (*CounterMap)[S] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000378 Visit(S->getBody());
379 Visit(S->getCond());
380 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000381 /// Assign a counter for the body of a for loop.
Justin Bogneref512b92014-01-06 22:27:43 +0000382 void VisitForStmt(const ForStmt *S) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000383 (*CounterMap)[S] = NextCounter++;
384 if (S->getInit())
385 Visit(S->getInit());
Justin Bogneref512b92014-01-06 22:27:43 +0000386 const Expr *E;
387 if ((E = S->getCond()))
388 Visit(E);
Justin Bogneref512b92014-01-06 22:27:43 +0000389 if ((E = S->getInc()))
390 Visit(E);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000391 Visit(S->getBody());
Justin Bogneref512b92014-01-06 22:27:43 +0000392 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000393 /// Assign a counter for the body of a for-range loop.
Justin Bogneref512b92014-01-06 22:27:43 +0000394 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000395 (*CounterMap)[S] = NextCounter++;
396 Visit(S->getRangeStmt());
397 Visit(S->getBeginEndStmt());
398 Visit(S->getCond());
399 Visit(S->getLoopVarStmt());
Justin Bogneref512b92014-01-06 22:27:43 +0000400 Visit(S->getBody());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000401 Visit(S->getInc());
Justin Bogneref512b92014-01-06 22:27:43 +0000402 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000403 /// Assign a counter for the body of a for-collection loop.
Justin Bogneref512b92014-01-06 22:27:43 +0000404 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000405 (*CounterMap)[S] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000406 Visit(S->getElement());
407 Visit(S->getBody());
408 }
409 /// Assign a counter for the exit block of the switch statement.
410 void VisitSwitchStmt(const SwitchStmt *S) {
411 (*CounterMap)[S] = NextCounter++;
412 Visit(S->getCond());
413 Visit(S->getBody());
414 }
415 /// Assign a counter for a particular case in a switch. This counts jumps
416 /// from the switch header as well as fallthrough from the case before this
417 /// one.
418 void VisitCaseStmt(const CaseStmt *S) {
419 (*CounterMap)[S] = NextCounter++;
420 Visit(S->getSubStmt());
421 }
422 /// Assign a counter for the default case of a switch statement. The count
423 /// is the number of branches from the loop header to the default, and does
424 /// not include fallthrough from previous cases. If we have multiple
425 /// conditional branch blocks from the switch instruction to the default
426 /// block, as with large GNU case ranges, this is the counter for the last
427 /// edge in that series, rather than the first.
428 void VisitDefaultStmt(const DefaultStmt *S) {
429 (*CounterMap)[S] = NextCounter++;
430 Visit(S->getSubStmt());
431 }
432 /// Assign a counter for the "then" part of an if statement. The count for
433 /// the "else" part, if it exists, will be calculated from this counter.
434 void VisitIfStmt(const IfStmt *S) {
435 (*CounterMap)[S] = NextCounter++;
436 Visit(S->getCond());
437 Visit(S->getThen());
438 if (S->getElse())
439 Visit(S->getElse());
440 }
441 /// Assign a counter for the continuation block of a C++ try statement.
442 void VisitCXXTryStmt(const CXXTryStmt *S) {
443 (*CounterMap)[S] = NextCounter++;
444 Visit(S->getTryBlock());
445 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
446 Visit(S->getHandler(I));
447 }
448 /// Assign a counter for a catch statement's handler block.
449 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
450 (*CounterMap)[S] = NextCounter++;
451 Visit(S->getHandlerBlock());
452 }
453 /// Assign a counter for the "true" part of a conditional operator. The
454 /// count in the "false" part will be calculated from this counter.
455 void VisitConditionalOperator(const ConditionalOperator *E) {
456 (*CounterMap)[E] = NextCounter++;
457 Visit(E->getCond());
458 Visit(E->getTrueExpr());
459 Visit(E->getFalseExpr());
460 }
461 /// Assign a counter for the right hand side of a logical and operator.
462 void VisitBinLAnd(const BinaryOperator *E) {
463 (*CounterMap)[E] = NextCounter++;
464 Visit(E->getLHS());
465 Visit(E->getRHS());
466 }
467 /// Assign a counter for the right hand side of a logical or operator.
468 void VisitBinLOr(const BinaryOperator *E) {
469 (*CounterMap)[E] = NextCounter++;
470 Visit(E->getLHS());
471 Visit(E->getRHS());
472 }
473 };
Bob Wilsonbf854f02014-02-17 19:21:09 +0000474
475 /// A StmtVisitor that propagates the raw counts through the AST and
476 /// records the count at statements where the value may change.
477 struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
478 /// PGO state.
479 CodeGenPGO &PGO;
480
481 /// A flag that is set when the current count should be recorded on the
482 /// next statement, such as at the exit of a loop.
483 bool RecordNextStmtCount;
484
485 /// The map of statements to count values.
486 llvm::DenseMap<const Stmt*, uint64_t> *CountMap;
487
488 /// BreakContinueStack - Keep counts of breaks and continues inside loops.
489 struct BreakContinue {
490 uint64_t BreakCount;
491 uint64_t ContinueCount;
492 BreakContinue() : BreakCount(0), ContinueCount(0) {}
493 };
494 SmallVector<BreakContinue, 8> BreakContinueStack;
495
496 ComputeRegionCounts(llvm::DenseMap<const Stmt*, uint64_t> *CountMap,
497 CodeGenPGO &PGO) :
498 PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {
499 }
500
501 void RecordStmtCount(const Stmt *S) {
502 if (RecordNextStmtCount) {
503 (*CountMap)[S] = PGO.getCurrentRegionCount();
504 RecordNextStmtCount = false;
505 }
506 }
507
508 void VisitStmt(const Stmt *S) {
509 RecordStmtCount(S);
510 for (Stmt::const_child_range I = S->children(); I; ++I) {
511 if (*I)
512 this->Visit(*I);
513 }
514 }
515
516 void VisitFunctionDecl(const FunctionDecl *S) {
517 RegionCounter Cnt(PGO, S->getBody());
518 Cnt.beginRegion();
519 (*CountMap)[S->getBody()] = PGO.getCurrentRegionCount();
520 Visit(S->getBody());
521 }
522
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000523 void VisitObjCMethodDecl(const ObjCMethodDecl *S) {
524 RegionCounter Cnt(PGO, S->getBody());
525 Cnt.beginRegion();
526 (*CountMap)[S->getBody()] = PGO.getCurrentRegionCount();
527 Visit(S->getBody());
528 }
529
Bob Wilsonc845c002014-03-06 20:24:27 +0000530 void VisitBlockDecl(const BlockDecl *S) {
531 RegionCounter Cnt(PGO, S->getBody());
532 Cnt.beginRegion();
533 (*CountMap)[S->getBody()] = PGO.getCurrentRegionCount();
534 Visit(S->getBody());
535 }
536
Bob Wilsonbf854f02014-02-17 19:21:09 +0000537 void VisitReturnStmt(const ReturnStmt *S) {
538 RecordStmtCount(S);
539 if (S->getRetValue())
540 Visit(S->getRetValue());
541 PGO.setCurrentRegionUnreachable();
542 RecordNextStmtCount = true;
543 }
544
545 void VisitGotoStmt(const GotoStmt *S) {
546 RecordStmtCount(S);
547 PGO.setCurrentRegionUnreachable();
548 RecordNextStmtCount = true;
549 }
550
551 void VisitLabelStmt(const LabelStmt *S) {
552 RecordNextStmtCount = false;
553 RegionCounter Cnt(PGO, S);
554 Cnt.beginRegion();
555 (*CountMap)[S] = PGO.getCurrentRegionCount();
556 Visit(S->getSubStmt());
557 }
558
559 void VisitBreakStmt(const BreakStmt *S) {
560 RecordStmtCount(S);
561 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
562 BreakContinueStack.back().BreakCount += PGO.getCurrentRegionCount();
563 PGO.setCurrentRegionUnreachable();
564 RecordNextStmtCount = true;
565 }
566
567 void VisitContinueStmt(const ContinueStmt *S) {
568 RecordStmtCount(S);
569 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
570 BreakContinueStack.back().ContinueCount += PGO.getCurrentRegionCount();
571 PGO.setCurrentRegionUnreachable();
572 RecordNextStmtCount = true;
573 }
574
575 void VisitWhileStmt(const WhileStmt *S) {
576 RecordStmtCount(S);
577 RegionCounter Cnt(PGO, S);
578 BreakContinueStack.push_back(BreakContinue());
579 // Visit the body region first so the break/continue adjustments can be
580 // included when visiting the condition.
581 Cnt.beginRegion();
582 (*CountMap)[S->getBody()] = PGO.getCurrentRegionCount();
583 Visit(S->getBody());
584 Cnt.adjustForControlFlow();
585
586 // ...then go back and propagate counts through the condition. The count
587 // at the start of the condition is the sum of the incoming edges,
588 // the backedge from the end of the loop body, and the edges from
589 // continue statements.
590 BreakContinue BC = BreakContinueStack.pop_back_val();
591 Cnt.setCurrentRegionCount(Cnt.getParentCount() +
592 Cnt.getAdjustedCount() + BC.ContinueCount);
593 (*CountMap)[S->getCond()] = PGO.getCurrentRegionCount();
594 Visit(S->getCond());
595 Cnt.adjustForControlFlow();
596 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
597 RecordNextStmtCount = true;
598 }
599
600 void VisitDoStmt(const DoStmt *S) {
601 RecordStmtCount(S);
602 RegionCounter Cnt(PGO, S);
603 BreakContinueStack.push_back(BreakContinue());
604 Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
605 (*CountMap)[S->getBody()] = PGO.getCurrentRegionCount();
606 Visit(S->getBody());
607 Cnt.adjustForControlFlow();
608
609 BreakContinue BC = BreakContinueStack.pop_back_val();
610 // The count at the start of the condition is equal to the count at the
611 // end of the body. The adjusted count does not include either the
612 // fall-through count coming into the loop or the continue count, so add
613 // both of those separately. This is coincidentally the same equation as
614 // with while loops but for different reasons.
615 Cnt.setCurrentRegionCount(Cnt.getParentCount() +
616 Cnt.getAdjustedCount() + BC.ContinueCount);
617 (*CountMap)[S->getCond()] = PGO.getCurrentRegionCount();
618 Visit(S->getCond());
619 Cnt.adjustForControlFlow();
620 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
621 RecordNextStmtCount = true;
622 }
623
624 void VisitForStmt(const ForStmt *S) {
625 RecordStmtCount(S);
626 if (S->getInit())
627 Visit(S->getInit());
628 RegionCounter Cnt(PGO, S);
629 BreakContinueStack.push_back(BreakContinue());
630 // Visit the body region first. (This is basically the same as a while
631 // loop; see further comments in VisitWhileStmt.)
632 Cnt.beginRegion();
633 (*CountMap)[S->getBody()] = PGO.getCurrentRegionCount();
634 Visit(S->getBody());
635 Cnt.adjustForControlFlow();
636
637 // The increment is essentially part of the body but it needs to include
638 // the count for all the continue statements.
639 if (S->getInc()) {
640 Cnt.setCurrentRegionCount(PGO.getCurrentRegionCount() +
641 BreakContinueStack.back().ContinueCount);
642 (*CountMap)[S->getInc()] = PGO.getCurrentRegionCount();
643 Visit(S->getInc());
644 Cnt.adjustForControlFlow();
645 }
646
647 BreakContinue BC = BreakContinueStack.pop_back_val();
648
649 // ...then go back and propagate counts through the condition.
650 if (S->getCond()) {
651 Cnt.setCurrentRegionCount(Cnt.getParentCount() +
652 Cnt.getAdjustedCount() +
653 BC.ContinueCount);
654 (*CountMap)[S->getCond()] = PGO.getCurrentRegionCount();
655 Visit(S->getCond());
656 Cnt.adjustForControlFlow();
657 }
658 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
659 RecordNextStmtCount = true;
660 }
661
662 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
663 RecordStmtCount(S);
664 Visit(S->getRangeStmt());
665 Visit(S->getBeginEndStmt());
666 RegionCounter Cnt(PGO, S);
667 BreakContinueStack.push_back(BreakContinue());
668 // Visit the body region first. (This is basically the same as a while
669 // loop; see further comments in VisitWhileStmt.)
670 Cnt.beginRegion();
671 (*CountMap)[S->getLoopVarStmt()] = PGO.getCurrentRegionCount();
672 Visit(S->getLoopVarStmt());
673 Visit(S->getBody());
674 Cnt.adjustForControlFlow();
675
676 // The increment is essentially part of the body but it needs to include
677 // the count for all the continue statements.
678 Cnt.setCurrentRegionCount(PGO.getCurrentRegionCount() +
679 BreakContinueStack.back().ContinueCount);
680 (*CountMap)[S->getInc()] = PGO.getCurrentRegionCount();
681 Visit(S->getInc());
682 Cnt.adjustForControlFlow();
683
684 BreakContinue BC = BreakContinueStack.pop_back_val();
685
686 // ...then go back and propagate counts through the condition.
687 Cnt.setCurrentRegionCount(Cnt.getParentCount() +
688 Cnt.getAdjustedCount() +
689 BC.ContinueCount);
690 (*CountMap)[S->getCond()] = PGO.getCurrentRegionCount();
691 Visit(S->getCond());
692 Cnt.adjustForControlFlow();
693 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
694 RecordNextStmtCount = true;
695 }
696
697 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
698 RecordStmtCount(S);
699 Visit(S->getElement());
700 RegionCounter Cnt(PGO, S);
701 BreakContinueStack.push_back(BreakContinue());
702 Cnt.beginRegion();
703 (*CountMap)[S->getBody()] = PGO.getCurrentRegionCount();
704 Visit(S->getBody());
705 BreakContinue BC = BreakContinueStack.pop_back_val();
706 Cnt.adjustForControlFlow();
707 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
708 RecordNextStmtCount = true;
709 }
710
711 void VisitSwitchStmt(const SwitchStmt *S) {
712 RecordStmtCount(S);
713 Visit(S->getCond());
714 PGO.setCurrentRegionUnreachable();
715 BreakContinueStack.push_back(BreakContinue());
716 Visit(S->getBody());
717 // If the switch is inside a loop, add the continue counts.
718 BreakContinue BC = BreakContinueStack.pop_back_val();
719 if (!BreakContinueStack.empty())
720 BreakContinueStack.back().ContinueCount += BC.ContinueCount;
721 RegionCounter ExitCnt(PGO, S);
722 ExitCnt.beginRegion();
723 RecordNextStmtCount = true;
724 }
725
726 void VisitCaseStmt(const CaseStmt *S) {
727 RecordNextStmtCount = false;
728 RegionCounter Cnt(PGO, S);
729 Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
730 (*CountMap)[S] = Cnt.getCount();
731 RecordNextStmtCount = true;
732 Visit(S->getSubStmt());
733 }
734
735 void VisitDefaultStmt(const DefaultStmt *S) {
736 RecordNextStmtCount = false;
737 RegionCounter Cnt(PGO, S);
738 Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
739 (*CountMap)[S] = Cnt.getCount();
740 RecordNextStmtCount = true;
741 Visit(S->getSubStmt());
742 }
743
744 void VisitIfStmt(const IfStmt *S) {
745 RecordStmtCount(S);
746 RegionCounter Cnt(PGO, S);
747 Visit(S->getCond());
748
749 Cnt.beginRegion();
750 (*CountMap)[S->getThen()] = PGO.getCurrentRegionCount();
751 Visit(S->getThen());
752 Cnt.adjustForControlFlow();
753
754 if (S->getElse()) {
755 Cnt.beginElseRegion();
756 (*CountMap)[S->getElse()] = PGO.getCurrentRegionCount();
757 Visit(S->getElse());
758 Cnt.adjustForControlFlow();
759 }
760 Cnt.applyAdjustmentsToRegion(0);
761 RecordNextStmtCount = true;
762 }
763
764 void VisitCXXTryStmt(const CXXTryStmt *S) {
765 RecordStmtCount(S);
766 Visit(S->getTryBlock());
767 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
768 Visit(S->getHandler(I));
769 RegionCounter Cnt(PGO, S);
770 Cnt.beginRegion();
771 RecordNextStmtCount = true;
772 }
773
774 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
775 RecordNextStmtCount = false;
776 RegionCounter Cnt(PGO, S);
777 Cnt.beginRegion();
778 (*CountMap)[S] = PGO.getCurrentRegionCount();
779 Visit(S->getHandlerBlock());
780 }
781
782 void VisitConditionalOperator(const ConditionalOperator *E) {
783 RecordStmtCount(E);
784 RegionCounter Cnt(PGO, E);
785 Visit(E->getCond());
786
787 Cnt.beginRegion();
788 (*CountMap)[E->getTrueExpr()] = PGO.getCurrentRegionCount();
789 Visit(E->getTrueExpr());
790 Cnt.adjustForControlFlow();
791
792 Cnt.beginElseRegion();
793 (*CountMap)[E->getFalseExpr()] = PGO.getCurrentRegionCount();
794 Visit(E->getFalseExpr());
795 Cnt.adjustForControlFlow();
796
797 Cnt.applyAdjustmentsToRegion(0);
798 RecordNextStmtCount = true;
799 }
800
801 void VisitBinLAnd(const BinaryOperator *E) {
802 RecordStmtCount(E);
803 RegionCounter Cnt(PGO, E);
804 Visit(E->getLHS());
805 Cnt.beginRegion();
806 (*CountMap)[E->getRHS()] = PGO.getCurrentRegionCount();
807 Visit(E->getRHS());
808 Cnt.adjustForControlFlow();
809 Cnt.applyAdjustmentsToRegion(0);
810 RecordNextStmtCount = true;
811 }
812
813 void VisitBinLOr(const BinaryOperator *E) {
814 RecordStmtCount(E);
815 RegionCounter Cnt(PGO, E);
816 Visit(E->getLHS());
817 Cnt.beginRegion();
818 (*CountMap)[E->getRHS()] = PGO.getCurrentRegionCount();
819 Visit(E->getRHS());
820 Cnt.adjustForControlFlow();
821 Cnt.applyAdjustmentsToRegion(0);
822 RecordNextStmtCount = true;
823 }
824 };
Justin Bogneref512b92014-01-06 22:27:43 +0000825}
826
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000827void CodeGenPGO::assignRegionCounters(const Decl *D, llvm::Function *Fn) {
Justin Bogneref512b92014-01-06 22:27:43 +0000828 bool InstrumentRegions = CGM.getCodeGenOpts().ProfileInstrGenerate;
Justin Bognerd66a17d2014-03-12 21:06:31 +0000829 PGOProfileData *PGOData = CGM.getPGOData();
830 if (!InstrumentRegions && !PGOData)
Justin Bogneref512b92014-01-06 22:27:43 +0000831 return;
Justin Bogneref512b92014-01-06 22:27:43 +0000832 if (!D)
833 return;
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000834 setFuncName(Fn);
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000835 FuncLinkage = Fn->getLinkage();
Justin Bogneref512b92014-01-06 22:27:43 +0000836 mapRegionCounters(D);
837 if (InstrumentRegions)
838 emitCounterVariables();
Justin Bognerd66a17d2014-03-12 21:06:31 +0000839 if (PGOData) {
840 loadRegionCounts(PGOData);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000841 computeRegionCounts(D);
Justin Bognerd66a17d2014-03-12 21:06:31 +0000842 applyFunctionAttributes(PGOData, Fn);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000843 }
Justin Bogneref512b92014-01-06 22:27:43 +0000844}
845
846void CodeGenPGO::mapRegionCounters(const Decl *D) {
847 RegionCounterMap = new llvm::DenseMap<const Stmt*, unsigned>();
848 MapRegionCounters Walker(RegionCounterMap);
849 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
850 Walker.VisitFunctionDecl(FD);
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000851 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
852 Walker.VisitObjCMethodDecl(MD);
Bob Wilsonc845c002014-03-06 20:24:27 +0000853 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
854 Walker.VisitBlockDecl(BD);
Justin Bogneref512b92014-01-06 22:27:43 +0000855 NumRegionCounters = Walker.NextCounter;
Justin Bognerb4416f52014-03-18 21:58:06 +0000856 // FIXME: The number of counters isn't sufficient for the hash
857 FunctionHash = NumRegionCounters;
Justin Bogneref512b92014-01-06 22:27:43 +0000858}
859
Bob Wilsonbf854f02014-02-17 19:21:09 +0000860void CodeGenPGO::computeRegionCounts(const Decl *D) {
861 StmtCountMap = new llvm::DenseMap<const Stmt*, uint64_t>();
862 ComputeRegionCounts Walker(StmtCountMap, *this);
863 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
864 Walker.VisitFunctionDecl(FD);
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000865 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
866 Walker.VisitObjCMethodDecl(MD);
Bob Wilsonc845c002014-03-06 20:24:27 +0000867 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
868 Walker.VisitBlockDecl(BD);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000869}
870
Justin Bognerd66a17d2014-03-12 21:06:31 +0000871void CodeGenPGO::applyFunctionAttributes(PGOProfileData *PGOData,
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000872 llvm::Function *Fn) {
873 if (!haveRegionCounts())
874 return;
875
Justin Bognerd66a17d2014-03-12 21:06:31 +0000876 uint64_t MaxFunctionCount = PGOData->getMaximumFunctionCount();
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000877 uint64_t FunctionCount = getRegionCount(0);
878 if (FunctionCount >= (uint64_t)(0.3 * (double)MaxFunctionCount))
879 // Turn on InlineHint attribute for hot functions.
880 // FIXME: 30% is from preliminary tuning on SPEC, it may not be optimal.
881 Fn->addFnAttr(llvm::Attribute::InlineHint);
882 else if (FunctionCount <= (uint64_t)(0.01 * (double)MaxFunctionCount))
883 // Turn on Cold attribute for cold functions.
884 // FIXME: 1% is from preliminary tuning on SPEC, it may not be optimal.
885 Fn->addFnAttr(llvm::Attribute::Cold);
886}
887
Justin Bogneref512b92014-01-06 22:27:43 +0000888void CodeGenPGO::emitCounterVariables() {
889 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
890 llvm::ArrayType *CounterTy = llvm::ArrayType::get(llvm::Type::getInt64Ty(Ctx),
891 NumRegionCounters);
892 RegionCounters =
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000893 new llvm::GlobalVariable(CGM.getModule(), CounterTy, false, FuncLinkage,
Justin Bogneref512b92014-01-06 22:27:43 +0000894 llvm::Constant::getNullValue(CounterTy),
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000895 getFuncVarName("counters"));
896 RegionCounters->setAlignment(8);
897 RegionCounters->setSection(getCountersSection(CGM));
Justin Bogneref512b92014-01-06 22:27:43 +0000898}
899
900void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, unsigned Counter) {
Bob Wilson749ebc72014-03-06 04:55:28 +0000901 if (!RegionCounters)
Justin Bogneref512b92014-01-06 22:27:43 +0000902 return;
903 llvm::Value *Addr =
904 Builder.CreateConstInBoundsGEP2_64(RegionCounters, 0, Counter);
905 llvm::Value *Count = Builder.CreateLoad(Addr, "pgocount");
906 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
907 Builder.CreateStore(Count, Addr);
908}
909
Justin Bognerd66a17d2014-03-12 21:06:31 +0000910void CodeGenPGO::loadRegionCounts(PGOProfileData *PGOData) {
Justin Bogneref512b92014-01-06 22:27:43 +0000911 // For now, ignore the counts from the PGO data file only if the number of
912 // counters does not match. This could be tightened down in the future to
913 // ignore counts when the input changes in various ways, e.g., by comparing a
914 // hash value based on some characteristics of the input.
915 RegionCounts = new std::vector<uint64_t>();
Justin Bognerb4416f52014-03-18 21:58:06 +0000916 uint64_t Hash;
917 if (PGOData->getFunctionCounts(getFuncName(), Hash, *RegionCounts) ||
918 Hash != FunctionHash || RegionCounts->size() != NumRegionCounters) {
Justin Bogneref512b92014-01-06 22:27:43 +0000919 delete RegionCounts;
920 RegionCounts = 0;
921 }
922}
923
924void CodeGenPGO::destroyRegionCounters() {
925 if (RegionCounterMap != 0)
926 delete RegionCounterMap;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000927 if (StmtCountMap != 0)
928 delete StmtCountMap;
Justin Bogneref512b92014-01-06 22:27:43 +0000929 if (RegionCounts != 0)
930 delete RegionCounts;
931}
932
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000933/// \brief Calculate what to divide by to scale weights.
934///
935/// Given the maximum weight, calculate a divisor that will scale all the
936/// weights to strictly less than UINT32_MAX.
937static uint64_t calculateWeightScale(uint64_t MaxWeight) {
938 return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
939}
940
941/// \brief Scale an individual branch weight (and add 1).
942///
943/// Scale a 64-bit weight down to 32-bits using \c Scale.
944///
945/// According to Laplace's Rule of Succession, it is better to compute the
946/// weight based on the count plus 1, so universally add 1 to the value.
947///
948/// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
949/// greater than \c Weight.
950static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
951 assert(Scale && "scale by 0?");
952 uint64_t Scaled = Weight / Scale + 1;
953 assert(Scaled <= UINT32_MAX && "overflow 32-bits");
954 return Scaled;
955}
956
Justin Bogneref512b92014-01-06 22:27:43 +0000957llvm::MDNode *CodeGenPGO::createBranchWeights(uint64_t TrueCount,
958 uint64_t FalseCount) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000959 // Check for empty weights.
Justin Bogneref512b92014-01-06 22:27:43 +0000960 if (!TrueCount && !FalseCount)
961 return 0;
962
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000963 // Calculate how to scale down to 32-bits.
964 uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
965
Justin Bogneref512b92014-01-06 22:27:43 +0000966 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000967 return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
968 scaleBranchWeight(FalseCount, Scale));
Justin Bogneref512b92014-01-06 22:27:43 +0000969}
970
Bob Wilson95a27b02014-02-17 19:20:59 +0000971llvm::MDNode *CodeGenPGO::createBranchWeights(ArrayRef<uint64_t> Weights) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000972 // We need at least two elements to create meaningful weights.
973 if (Weights.size() < 2)
974 return 0;
975
976 // Calculate how to scale down to 32-bits.
977 uint64_t Scale = calculateWeightScale(*std::max_element(Weights.begin(),
978 Weights.end()));
979
Justin Bogneref512b92014-01-06 22:27:43 +0000980 SmallVector<uint32_t, 16> ScaledWeights;
981 ScaledWeights.reserve(Weights.size());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000982 for (uint64_t W : Weights)
983 ScaledWeights.push_back(scaleBranchWeight(W, Scale));
984
985 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Justin Bogneref512b92014-01-06 22:27:43 +0000986 return MDHelper.createBranchWeights(ScaledWeights);
987}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000988
989llvm::MDNode *CodeGenPGO::createLoopWeights(const Stmt *Cond,
990 RegionCounter &Cnt) {
991 if (!haveRegionCounts())
992 return 0;
993 uint64_t LoopCount = Cnt.getCount();
994 uint64_t CondCount = 0;
995 bool Found = getStmtCount(Cond, CondCount);
996 assert(Found && "missing expected loop condition count");
997 (void)Found;
998 if (CondCount == 0)
999 return 0;
1000 return createBranchWeights(LoopCount,
1001 std::max(CondCount, LoopCount) - LoopCount);
1002}