blob: e9e354ebb88f921d0e151f5b9a7b2f67b83b18c0 [file] [log] [blame]
Teresa Johnson2d5487c2016-04-11 13:58:45 +00001//===- ModuleSummaryAnalysis.cpp - Module summary index builder -----------===//
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// This pass builds a ModuleSummaryIndex object for the module, to be written
11// to bitcode or LLVM assembly.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Peter Collingbourne0c30f082016-12-20 21:12:28 +000016#include "llvm/ADT/MapVector.h"
17#include "llvm/ADT/SetVector.h"
Teresa Johnson3624bdf2016-11-14 17:12:32 +000018#include "llvm/ADT/Triple.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000019#include "llvm/Analysis/BlockFrequencyInfo.h"
20#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
21#include "llvm/Analysis/BranchProbabilityInfo.h"
Teresa Johnsoncd21a642016-07-17 14:47:01 +000022#include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000023#include "llvm/Analysis/LoopInfo.h"
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000024#include "llvm/Analysis/ProfileSummaryInfo.h"
Peter Collingbourne1b4137a72016-12-21 23:03:45 +000025#include "llvm/Analysis/TypeMetadataUtils.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000026#include "llvm/IR/CallSite.h"
27#include "llvm/IR/Dominators.h"
Teresa Johnsondf5ef872016-04-27 14:19:38 +000028#include "llvm/IR/InstIterator.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000029#include "llvm/IR/IntrinsicInst.h"
30#include "llvm/IR/ValueSymbolTable.h"
Peter Collingbourne61781ac2017-03-31 00:08:24 +000031#include "llvm/Object/ModuleSymbolTable.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000032#include "llvm/Pass.h"
33using namespace llvm;
34
35#define DEBUG_TYPE "module-summary-analysis"
36
37// Walk through the operands of a given User via worklist iteration and populate
38// the set of GlobalValue references encountered. Invoked either on an
39// Instruction or a GlobalVariable (which walks its initializer).
Peter Collingbourne9667b912017-05-04 18:03:25 +000040static void findRefEdges(ModuleSummaryIndex &Index, const User *CurUser,
41 SetVector<ValueInfo> &RefEdges,
Teresa Johnson2d5487c2016-04-11 13:58:45 +000042 SmallPtrSet<const User *, 8> &Visited) {
43 SmallVector<const User *, 32> Worklist;
44 Worklist.push_back(CurUser);
45
46 while (!Worklist.empty()) {
47 const User *U = Worklist.pop_back_val();
48
49 if (!Visited.insert(U).second)
50 continue;
51
52 ImmutableCallSite CS(U);
53
54 for (const auto &OI : U->operands()) {
55 const User *Operand = dyn_cast<User>(OI);
56 if (!Operand)
57 continue;
58 if (isa<BlockAddress>(Operand))
59 continue;
Peter Collingbourne0c30f082016-12-20 21:12:28 +000060 if (auto *GV = dyn_cast<GlobalValue>(Operand)) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +000061 // We have a reference to a global value. This should be added to
62 // the reference set unless it is a callee. Callees are handled
63 // specially by WriteFunction and are added to a separate list.
64 if (!(CS && CS.isCallee(&OI)))
Peter Collingbourne9667b912017-05-04 18:03:25 +000065 RefEdges.insert(Index.getOrInsertValueInfo(GV));
Teresa Johnson2d5487c2016-04-11 13:58:45 +000066 continue;
67 }
68 Worklist.push_back(Operand);
69 }
70 }
71}
72
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000073static CalleeInfo::HotnessType getHotness(uint64_t ProfileCount,
74 ProfileSummaryInfo *PSI) {
75 if (!PSI)
76 return CalleeInfo::HotnessType::Unknown;
77 if (PSI->isHotCount(ProfileCount))
78 return CalleeInfo::HotnessType::Hot;
79 if (PSI->isColdCount(ProfileCount))
80 return CalleeInfo::HotnessType::Cold;
81 return CalleeInfo::HotnessType::None;
82}
83
Teresa Johnson519465b2017-01-05 14:32:16 +000084static bool isNonRenamableLocal(const GlobalValue &GV) {
85 return GV.hasSection() && GV.hasLocalLinkage();
86}
87
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +000088/// Determine whether this call has all constant integer arguments (excluding
89/// "this") and summarize it to VCalls or ConstVCalls as appropriate.
90static void addVCallToSet(DevirtCallSite Call, GlobalValue::GUID Guid,
91 SetVector<FunctionSummary::VFuncId> &VCalls,
92 SetVector<FunctionSummary::ConstVCall> &ConstVCalls) {
93 std::vector<uint64_t> Args;
94 // Start from the second argument to skip the "this" pointer.
95 for (auto &Arg : make_range(Call.CS.arg_begin() + 1, Call.CS.arg_end())) {
96 auto *CI = dyn_cast<ConstantInt>(Arg);
97 if (!CI || CI->getBitWidth() > 64) {
98 VCalls.insert({Guid, Call.Offset});
99 return;
100 }
101 Args.push_back(CI->getZExtValue());
102 }
103 ConstVCalls.insert({{Guid, Call.Offset}, std::move(Args)});
104}
105
106/// If this intrinsic call requires that we add information to the function
107/// summary, do so via the non-constant reference arguments.
108static void addIntrinsicToSummary(
109 const CallInst *CI, SetVector<GlobalValue::GUID> &TypeTests,
110 SetVector<FunctionSummary::VFuncId> &TypeTestAssumeVCalls,
111 SetVector<FunctionSummary::VFuncId> &TypeCheckedLoadVCalls,
112 SetVector<FunctionSummary::ConstVCall> &TypeTestAssumeConstVCalls,
113 SetVector<FunctionSummary::ConstVCall> &TypeCheckedLoadConstVCalls) {
114 switch (CI->getCalledFunction()->getIntrinsicID()) {
115 case Intrinsic::type_test: {
116 auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(1));
117 auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
118 if (!TypeId)
119 break;
120 GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
121
122 // Produce a summary from type.test intrinsics. We only summarize type.test
123 // intrinsics that are used other than by an llvm.assume intrinsic.
124 // Intrinsics that are assumed are relevant only to the devirtualization
125 // pass, not the type test lowering pass.
126 bool HasNonAssumeUses = llvm::any_of(CI->uses(), [](const Use &CIU) {
127 auto *AssumeCI = dyn_cast<CallInst>(CIU.getUser());
128 if (!AssumeCI)
129 return true;
130 Function *F = AssumeCI->getCalledFunction();
131 return !F || F->getIntrinsicID() != Intrinsic::assume;
132 });
133 if (HasNonAssumeUses)
134 TypeTests.insert(Guid);
135
136 SmallVector<DevirtCallSite, 4> DevirtCalls;
137 SmallVector<CallInst *, 4> Assumes;
138 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
139 for (auto &Call : DevirtCalls)
140 addVCallToSet(Call, Guid, TypeTestAssumeVCalls,
141 TypeTestAssumeConstVCalls);
142
143 break;
144 }
145
146 case Intrinsic::type_checked_load: {
147 auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(2));
148 auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
149 if (!TypeId)
150 break;
151 GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
152
153 SmallVector<DevirtCallSite, 4> DevirtCalls;
154 SmallVector<Instruction *, 4> LoadedPtrs;
155 SmallVector<Instruction *, 4> Preds;
156 bool HasNonCallUses = false;
157 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
158 HasNonCallUses, CI);
159 // Any non-call uses of the result of llvm.type.checked.load will
160 // prevent us from optimizing away the llvm.type.test.
161 if (HasNonCallUses)
162 TypeTests.insert(Guid);
163 for (auto &Call : DevirtCalls)
164 addVCallToSet(Call, Guid, TypeCheckedLoadVCalls,
165 TypeCheckedLoadConstVCalls);
166
167 break;
168 }
169 default:
170 break;
171 }
172}
173
Teresa Johnson519465b2017-01-05 14:32:16 +0000174static void
175computeFunctionSummary(ModuleSummaryIndex &Index, const Module &M,
176 const Function &F, BlockFrequencyInfo *BFI,
177 ProfileSummaryInfo *PSI, bool HasLocalsInUsed,
Teresa Johnsone27b0582017-01-05 14:59:56 +0000178 DenseSet<GlobalValue::GUID> &CantBePromoted) {
Teresa Johnson02563cd2016-10-28 02:39:38 +0000179 // Summary not currently supported for anonymous functions, they should
180 // have been named.
181 assert(F.hasName());
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000182
183 unsigned NumInsts = 0;
184 // Map from callee ValueId to profile count. Used to accumulate profile
185 // counts for all static calls to a given callee.
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000186 MapVector<ValueInfo, CalleeInfo> CallGraphEdges;
187 SetVector<ValueInfo> RefEdges;
Peter Collingbourne1b4137a72016-12-21 23:03:45 +0000188 SetVector<GlobalValue::GUID> TypeTests;
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000189 SetVector<FunctionSummary::VFuncId> TypeTestAssumeVCalls,
190 TypeCheckedLoadVCalls;
191 SetVector<FunctionSummary::ConstVCall> TypeTestAssumeConstVCalls,
192 TypeCheckedLoadConstVCalls;
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000193 ICallPromotionAnalysis ICallAnalysis;
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000194
Teresa Johnsond5033a42016-11-14 16:40:19 +0000195 bool HasInlineAsmMaybeReferencingInternal = false;
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000196 SmallPtrSet<const User *, 8> Visited;
Benjamin Krameraa209152016-06-26 17:27:42 +0000197 for (const BasicBlock &BB : F)
198 for (const Instruction &I : BB) {
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000199 if (isa<DbgInfoIntrinsic>(I))
200 continue;
201 ++NumInsts;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000202 findRefEdges(Index, &I, RefEdges, Visited);
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000203 auto CS = ImmutableCallSite(&I);
204 if (!CS)
205 continue;
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000206
207 const auto *CI = dyn_cast<CallInst>(&I);
208 // Since we don't know exactly which local values are referenced in inline
Teresa Johnsond5033a42016-11-14 16:40:19 +0000209 // assembly, conservatively mark the function as possibly referencing
210 // a local value from inline assembly to ensure we don't export a
211 // reference (which would require renaming and promotion of the
212 // referenced value).
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000213 if (HasLocalsInUsed && CI && CI->isInlineAsm())
Teresa Johnsond5033a42016-11-14 16:40:19 +0000214 HasInlineAsmMaybeReferencingInternal = true;
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000215
Teresa Johnson897bab92016-10-08 16:11:42 +0000216 auto *CalledValue = CS.getCalledValue();
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000217 auto *CalledFunction = CS.getCalledFunction();
Teresa Johnson897bab92016-10-08 16:11:42 +0000218 // Check if this is an alias to a function. If so, get the
219 // called aliasee for the checks below.
220 if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) {
221 assert(!CalledFunction && "Expected null called function in callsite for alias");
222 CalledFunction = dyn_cast<Function>(GA->getBaseObject());
223 }
Peter Collingbourne1b4137a72016-12-21 23:03:45 +0000224 // Check if this is a direct call to a known function or a known
225 // intrinsic, or an indirect call with profile data.
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000226 if (CalledFunction) {
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000227 if (CI && CalledFunction->isIntrinsic()) {
228 addIntrinsicToSummary(
229 CI, TypeTests, TypeTestAssumeVCalls, TypeCheckedLoadVCalls,
230 TypeTestAssumeConstVCalls, TypeCheckedLoadConstVCalls);
231 continue;
Peter Collingbourne1b4137a72016-12-21 23:03:45 +0000232 }
Teresa Johnson02563cd2016-10-28 02:39:38 +0000233 // We should have named any anonymous globals
234 assert(CalledFunction->hasName());
Easwaran Ramanf5f91602017-05-09 23:21:10 +0000235 auto ScaledCount = PSI->getProfileCount(&I, BFI);
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000236 auto Hotness = ScaledCount ? getHotness(ScaledCount.getValue(), PSI)
237 : CalleeInfo::HotnessType::Unknown;
238
Teresa Johnson897bab92016-10-08 16:11:42 +0000239 // Use the original CalledValue, in case it was an alias. We want
240 // to record the call edge to the alias in that case. Eventually
241 // an alias summary will be created to associate the alias and
242 // aliasee.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000243 CallGraphEdges[Index.getOrInsertValueInfo(
244 cast<GlobalValue>(CalledValue))]
245 .updateHotness(Hotness);
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000246 } else {
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000247 // Skip inline assembly calls.
248 if (CI && CI->isInlineAsm())
249 continue;
250 // Skip direct calls.
251 if (!CS.getCalledValue() || isa<Constant>(CS.getCalledValue()))
252 continue;
253
254 uint32_t NumVals, NumCandidates;
255 uint64_t TotalCount;
256 auto CandidateProfileData =
257 ICallAnalysis.getPromotionCandidatesForInstruction(
258 &I, NumVals, TotalCount, NumCandidates);
259 for (auto &Candidate : CandidateProfileData)
Peter Collingbourne9667b912017-05-04 18:03:25 +0000260 CallGraphEdges[Index.getOrInsertValueInfo(Candidate.Value)]
261 .updateHotness(getHotness(Candidate.Count, PSI));
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000262 }
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000263 }
264
Dehao Chena60cdd32017-02-28 18:09:44 +0000265 // Explicit add hot edges to enforce importing for designated GUIDs for
266 // sample PGO, to enable the same inlines as the profiled optimized binary.
267 for (auto &I : F.getImportGUIDs())
Peter Collingbourne9667b912017-05-04 18:03:25 +0000268 CallGraphEdges[Index.getOrInsertValueInfo(I)].updateHotness(
Dehao Chen64c46572017-07-07 21:01:00 +0000269 CalleeInfo::HotnessType::Critical);
Dehao Chena60cdd32017-02-28 18:09:44 +0000270
Teresa Johnson519465b2017-01-05 14:32:16 +0000271 bool NonRenamableLocal = isNonRenamableLocal(F);
272 bool NotEligibleForImport =
273 NonRenamableLocal || HasInlineAsmMaybeReferencingInternal ||
274 // Inliner doesn't handle variadic functions.
275 // FIXME: refactor this to use the same code that inliner is using.
276 F.isVarArg();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000277 GlobalValueSummary::GVFlags Flags(F.getLinkage(), NotEligibleForImport,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000278 /* Live = */ false);
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000279 auto FuncSummary = llvm::make_unique<FunctionSummary>(
Peter Collingbourne1b4137a72016-12-21 23:03:45 +0000280 Flags, NumInsts, RefEdges.takeVector(), CallGraphEdges.takeVector(),
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000281 TypeTests.takeVector(), TypeTestAssumeVCalls.takeVector(),
282 TypeCheckedLoadVCalls.takeVector(),
283 TypeTestAssumeConstVCalls.takeVector(),
284 TypeCheckedLoadConstVCalls.takeVector());
Teresa Johnson519465b2017-01-05 14:32:16 +0000285 if (NonRenamableLocal)
286 CantBePromoted.insert(F.getGUID());
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000287 Index.addGlobalValueSummary(F.getName(), std::move(FuncSummary));
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000288}
289
Teresa Johnson519465b2017-01-05 14:32:16 +0000290static void
291computeVariableSummary(ModuleSummaryIndex &Index, const GlobalVariable &V,
Teresa Johnsone27b0582017-01-05 14:59:56 +0000292 DenseSet<GlobalValue::GUID> &CantBePromoted) {
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000293 SetVector<ValueInfo> RefEdges;
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000294 SmallPtrSet<const User *, 8> Visited;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000295 findRefEdges(Index, &V, RefEdges, Visited);
Teresa Johnson519465b2017-01-05 14:32:16 +0000296 bool NonRenamableLocal = isNonRenamableLocal(V);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000297 GlobalValueSummary::GVFlags Flags(V.getLinkage(), NonRenamableLocal,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000298 /* Live = */ false);
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000299 auto GVarSummary =
300 llvm::make_unique<GlobalVarSummary>(Flags, RefEdges.takeVector());
Teresa Johnson519465b2017-01-05 14:32:16 +0000301 if (NonRenamableLocal)
302 CantBePromoted.insert(V.getGUID());
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000303 Index.addGlobalValueSummary(V.getName(), std::move(GVarSummary));
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000304}
305
Teresa Johnson519465b2017-01-05 14:32:16 +0000306static void
307computeAliasSummary(ModuleSummaryIndex &Index, const GlobalAlias &A,
Teresa Johnsone27b0582017-01-05 14:59:56 +0000308 DenseSet<GlobalValue::GUID> &CantBePromoted) {
Teresa Johnson519465b2017-01-05 14:32:16 +0000309 bool NonRenamableLocal = isNonRenamableLocal(A);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000310 GlobalValueSummary::GVFlags Flags(A.getLinkage(), NonRenamableLocal,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000311 /* Live = */ false);
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000312 auto AS = llvm::make_unique<AliasSummary>(Flags, ArrayRef<ValueInfo>{});
Teresa Johnson02563cd2016-10-28 02:39:38 +0000313 auto *Aliasee = A.getBaseObject();
314 auto *AliaseeSummary = Index.getGlobalValueSummary(*Aliasee);
315 assert(AliaseeSummary && "Alias expects aliasee summary to be parsed");
316 AS->setAliasee(AliaseeSummary);
Teresa Johnson519465b2017-01-05 14:32:16 +0000317 if (NonRenamableLocal)
318 CantBePromoted.insert(A.getGUID());
Teresa Johnson02563cd2016-10-28 02:39:38 +0000319 Index.addGlobalValueSummary(A.getName(), std::move(AS));
320}
321
Teresa Johnson6c475a72017-01-05 21:34:18 +0000322// Set LiveRoot flag on entries matching the given value name.
323static void setLiveRoot(ModuleSummaryIndex &Index, StringRef Name) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000324 if (ValueInfo VI = Index.getValueInfo(GlobalValue::getGUID(Name)))
325 for (auto &Summary : VI.getSummaryList())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000326 Summary->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000327}
328
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000329ModuleSummaryIndex llvm::buildModuleSummaryIndex(
330 const Module &M,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000331 std::function<BlockFrequencyInfo *(const Function &F)> GetBFICallback,
332 ProfileSummaryInfo *PSI) {
Teresa Johnson94624ac2017-05-10 18:52:16 +0000333 assert(PSI);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000334 ModuleSummaryIndex Index;
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000335
Teresa Johnsona0811452016-11-10 16:57:32 +0000336 // Identify the local values in the llvm.used and llvm.compiler.used sets,
337 // which should not be exported as they would then require renaming and
338 // promotion, but we may have opaque uses e.g. in inline asm. We collect them
339 // here because we use this information to mark functions containing inline
340 // assembly calls as not importable.
Mehdi Aminib6a11a72016-11-09 01:45:13 +0000341 SmallPtrSet<GlobalValue *, 8> LocalsUsed;
Teresa Johnsona0811452016-11-10 16:57:32 +0000342 SmallPtrSet<GlobalValue *, 8> Used;
343 // First collect those in the llvm.used set.
344 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
Teresa Johnsona0811452016-11-10 16:57:32 +0000345 // Next collect those in the llvm.compiler.used set.
346 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ true);
Teresa Johnsone27b0582017-01-05 14:59:56 +0000347 DenseSet<GlobalValue::GUID> CantBePromoted;
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000348 for (auto *V : Used) {
Teresa Johnson519465b2017-01-05 14:32:16 +0000349 if (V->hasLocalLinkage()) {
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000350 LocalsUsed.insert(V);
Teresa Johnson519465b2017-01-05 14:32:16 +0000351 CantBePromoted.insert(V->getGUID());
352 }
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000353 }
Teresa Johnsonb35cc692016-04-20 14:39:45 +0000354
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000355 // Compute summaries for all functions defined in module, and save in the
356 // index.
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000357 for (auto &F : M) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000358 if (F.isDeclaration())
359 continue;
360
361 BlockFrequencyInfo *BFI = nullptr;
362 std::unique_ptr<BlockFrequencyInfo> BFIPtr;
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000363 if (GetBFICallback)
364 BFI = GetBFICallback(F);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000365 else if (F.getEntryCount().hasValue()) {
366 LoopInfo LI{DominatorTree(const_cast<Function &>(F))};
367 BranchProbabilityInfo BPI{F, LI};
368 BFIPtr = llvm::make_unique<BlockFrequencyInfo>(F, BPI, LI);
369 BFI = BFIPtr.get();
370 }
371
Teresa Johnson519465b2017-01-05 14:32:16 +0000372 computeFunctionSummary(Index, M, F, BFI, PSI, !LocalsUsed.empty(),
373 CantBePromoted);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000374 }
375
376 // Compute summaries for all variables defined in module, and save in the
377 // index.
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000378 for (const GlobalVariable &G : M.globals()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000379 if (G.isDeclaration())
380 continue;
Teresa Johnson519465b2017-01-05 14:32:16 +0000381 computeVariableSummary(Index, G, CantBePromoted);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000382 }
Teresa Johnson02563cd2016-10-28 02:39:38 +0000383
384 // Compute summaries for all aliases defined in module, and save in the
385 // index.
386 for (const GlobalAlias &A : M.aliases())
Teresa Johnson519465b2017-01-05 14:32:16 +0000387 computeAliasSummary(Index, A, CantBePromoted);
Teresa Johnson02563cd2016-10-28 02:39:38 +0000388
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000389 for (auto *V : LocalsUsed) {
390 auto *Summary = Index.getGlobalValueSummary(*V);
391 assert(Summary && "Missing summary for global value");
Teresa Johnson519465b2017-01-05 14:32:16 +0000392 Summary->setNotEligibleToImport();
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000393 }
394
Teresa Johnson6c475a72017-01-05 21:34:18 +0000395 // The linker doesn't know about these LLVM produced values, so we need
396 // to flag them as live in the index to ensure index-based dead value
397 // analysis treats them as live roots of the analysis.
398 setLiveRoot(Index, "llvm.used");
399 setLiveRoot(Index, "llvm.compiler.used");
400 setLiveRoot(Index, "llvm.global_ctors");
401 setLiveRoot(Index, "llvm.global_dtors");
402 setLiveRoot(Index, "llvm.global.annotations");
403
Teresa Johnson3624bdf2016-11-14 17:12:32 +0000404 if (!M.getModuleInlineAsm().empty()) {
405 // Collect the local values defined by module level asm, and set up
406 // summaries for these symbols so that they can be marked as NoRename,
407 // to prevent export of any use of them in regular IR that would require
408 // renaming within the module level asm. Note we don't need to create a
409 // summary for weak or global defs, as they don't need to be flagged as
410 // NoRename, and defs in module level asm can't be imported anyway.
411 // Also, any values used but not defined within module level asm should
412 // be listed on the llvm.used or llvm.compiler.used global and marked as
413 // referenced from there.
Peter Collingbourne863cbfb2016-12-01 06:51:47 +0000414 ModuleSymbolTable::CollectAsmSymbols(
Teresa Johnsond8204472017-03-09 00:19:49 +0000415 M, [&M, &Index, &CantBePromoted](StringRef Name,
416 object::BasicSymbolRef::Flags Flags) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +0000417 // Symbols not marked as Weak or Global are local definitions.
Teresa Johnsone0ee5cf2016-12-27 17:45:09 +0000418 if (Flags & (object::BasicSymbolRef::SF_Weak |
Teresa Johnson3624bdf2016-11-14 17:12:32 +0000419 object::BasicSymbolRef::SF_Global))
420 return;
421 GlobalValue *GV = M.getNamedValue(Name);
422 if (!GV)
423 return;
424 assert(GV->isDeclaration() && "Def in module asm already has definition");
Teresa Johnson519465b2017-01-05 14:32:16 +0000425 GlobalValueSummary::GVFlags GVFlags(GlobalValue::InternalLinkage,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000426 /* NotEligibleToImport = */ true,
427 /* Live = */ true);
Teresa Johnson519465b2017-01-05 14:32:16 +0000428 CantBePromoted.insert(GlobalValue::getGUID(Name));
Teresa Johnson3624bdf2016-11-14 17:12:32 +0000429 // Create the appropriate summary type.
430 if (isa<Function>(GV)) {
431 std::unique_ptr<FunctionSummary> Summary =
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000432 llvm::make_unique<FunctionSummary>(
433 GVFlags, 0, ArrayRef<ValueInfo>{},
Peter Collingbourne1b4137a72016-12-21 23:03:45 +0000434 ArrayRef<FunctionSummary::EdgeTy>{},
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000435 ArrayRef<GlobalValue::GUID>{},
436 ArrayRef<FunctionSummary::VFuncId>{},
437 ArrayRef<FunctionSummary::VFuncId>{},
438 ArrayRef<FunctionSummary::ConstVCall>{},
439 ArrayRef<FunctionSummary::ConstVCall>{});
Teresa Johnson3624bdf2016-11-14 17:12:32 +0000440 Index.addGlobalValueSummary(Name, std::move(Summary));
441 } else {
442 std::unique_ptr<GlobalVarSummary> Summary =
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000443 llvm::make_unique<GlobalVarSummary>(GVFlags,
444 ArrayRef<ValueInfo>{});
Teresa Johnson3624bdf2016-11-14 17:12:32 +0000445 Index.addGlobalValueSummary(Name, std::move(Summary));
446 }
447 });
448 }
449
Peter Collingbournee357fbd2017-06-08 23:01:49 +0000450 bool IsThinLTO = true;
451 if (auto *MD =
452 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
453 IsThinLTO = MD->getZExtValue();
454
Teresa Johnson519465b2017-01-05 14:32:16 +0000455 for (auto &GlobalList : Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000456 // Ignore entries for references that are undefined in the current module.
457 if (GlobalList.second.SummaryList.empty())
458 continue;
459
460 assert(GlobalList.second.SummaryList.size() == 1 &&
Teresa Johnson519465b2017-01-05 14:32:16 +0000461 "Expected module's index to have one summary per GUID");
Peter Collingbourne9667b912017-05-04 18:03:25 +0000462 auto &Summary = GlobalList.second.SummaryList[0];
Peter Collingbournee357fbd2017-06-08 23:01:49 +0000463 if (!IsThinLTO) {
464 Summary->setNotEligibleToImport();
465 continue;
466 }
467
Teresa Johnson519465b2017-01-05 14:32:16 +0000468 bool AllRefsCanBeExternallyReferenced =
469 llvm::all_of(Summary->refs(), [&](const ValueInfo &VI) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000470 return !CantBePromoted.count(VI.getGUID());
Teresa Johnson519465b2017-01-05 14:32:16 +0000471 });
472 if (!AllRefsCanBeExternallyReferenced) {
473 Summary->setNotEligibleToImport();
474 continue;
475 }
476
477 if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
478 bool AllCallsCanBeExternallyReferenced = llvm::all_of(
479 FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000480 return !CantBePromoted.count(Edge.first.getGUID());
Teresa Johnson519465b2017-01-05 14:32:16 +0000481 });
482 if (!AllCallsCanBeExternallyReferenced)
483 Summary->setNotEligibleToImport();
484 }
485 }
486
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000487 return Index;
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000488}
489
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000490AnalysisKey ModuleSummaryIndexAnalysis::Key;
Teresa Johnsonf93b2462016-08-12 13:53:02 +0000491
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000492ModuleSummaryIndex
Teresa Johnsonf93b2462016-08-12 13:53:02 +0000493ModuleSummaryIndexAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000494 ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M);
Teresa Johnsonf93b2462016-08-12 13:53:02 +0000495 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000496 return buildModuleSummaryIndex(
497 M,
498 [&FAM](const Function &F) {
499 return &FAM.getResult<BlockFrequencyAnalysis>(
500 *const_cast<Function *>(&F));
501 },
502 &PSI);
Teresa Johnsonf93b2462016-08-12 13:53:02 +0000503}
504
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000505char ModuleSummaryIndexWrapperPass::ID = 0;
506INITIALIZE_PASS_BEGIN(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
507 "Module Summary Analysis", false, true)
508INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Mehdi Amini89029482017-01-21 06:01:22 +0000509INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000510INITIALIZE_PASS_END(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
511 "Module Summary Analysis", false, true)
512
513ModulePass *llvm::createModuleSummaryIndexWrapperPass() {
514 return new ModuleSummaryIndexWrapperPass();
515}
516
517ModuleSummaryIndexWrapperPass::ModuleSummaryIndexWrapperPass()
518 : ModulePass(ID) {
519 initializeModuleSummaryIndexWrapperPassPass(*PassRegistry::getPassRegistry());
520}
521
522bool ModuleSummaryIndexWrapperPass::runOnModule(Module &M) {
Dehao Chen5461d8b2016-09-28 21:00:58 +0000523 auto &PSI = *getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000524 Index = buildModuleSummaryIndex(
525 M,
526 [this](const Function &F) {
527 return &(this->getAnalysis<BlockFrequencyInfoWrapperPass>(
528 *const_cast<Function *>(&F))
529 .getBFI());
530 },
531 &PSI);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000532 return false;
533}
534
535bool ModuleSummaryIndexWrapperPass::doFinalization(Module &M) {
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000536 Index.reset();
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000537 return false;
538}
539
540void ModuleSummaryIndexWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
541 AU.setPreservesAll();
542 AU.addRequired<BlockFrequencyInfoWrapperPass>();
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000543 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000544}