blob: 70b55674c07978c6661a2f85a61a7d125bb67626 [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"
Teresa Johnson3624bdf2016-11-14 17:12:32 +000031#include "llvm/Object/IRObjectFile.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 Collingbourne0c30f082016-12-20 21:12:28 +000040static void findRefEdges(const User *CurUser, SetVector<ValueInfo> &RefEdges,
Teresa Johnson2d5487c2016-04-11 13:58:45 +000041 SmallPtrSet<const User *, 8> &Visited) {
42 SmallVector<const User *, 32> Worklist;
43 Worklist.push_back(CurUser);
44
45 while (!Worklist.empty()) {
46 const User *U = Worklist.pop_back_val();
47
48 if (!Visited.insert(U).second)
49 continue;
50
51 ImmutableCallSite CS(U);
52
53 for (const auto &OI : U->operands()) {
54 const User *Operand = dyn_cast<User>(OI);
55 if (!Operand)
56 continue;
57 if (isa<BlockAddress>(Operand))
58 continue;
Peter Collingbourne0c30f082016-12-20 21:12:28 +000059 if (auto *GV = dyn_cast<GlobalValue>(Operand)) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +000060 // We have a reference to a global value. This should be added to
61 // the reference set unless it is a callee. Callees are handled
62 // specially by WriteFunction and are added to a separate list.
63 if (!(CS && CS.isCallee(&OI)))
Peter Collingbourne0c30f082016-12-20 21:12:28 +000064 RefEdges.insert(GV);
Teresa Johnson2d5487c2016-04-11 13:58:45 +000065 continue;
66 }
67 Worklist.push_back(Operand);
68 }
69 }
70}
71
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000072static CalleeInfo::HotnessType getHotness(uint64_t ProfileCount,
73 ProfileSummaryInfo *PSI) {
74 if (!PSI)
75 return CalleeInfo::HotnessType::Unknown;
76 if (PSI->isHotCount(ProfileCount))
77 return CalleeInfo::HotnessType::Hot;
78 if (PSI->isColdCount(ProfileCount))
79 return CalleeInfo::HotnessType::Cold;
80 return CalleeInfo::HotnessType::None;
81}
82
Teresa Johnson519465b2017-01-05 14:32:16 +000083static bool isNonRenamableLocal(const GlobalValue &GV) {
84 return GV.hasSection() && GV.hasLocalLinkage();
85}
86
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +000087/// Determine whether this call has all constant integer arguments (excluding
88/// "this") and summarize it to VCalls or ConstVCalls as appropriate.
89static void addVCallToSet(DevirtCallSite Call, GlobalValue::GUID Guid,
90 SetVector<FunctionSummary::VFuncId> &VCalls,
91 SetVector<FunctionSummary::ConstVCall> &ConstVCalls) {
92 std::vector<uint64_t> Args;
93 // Start from the second argument to skip the "this" pointer.
94 for (auto &Arg : make_range(Call.CS.arg_begin() + 1, Call.CS.arg_end())) {
95 auto *CI = dyn_cast<ConstantInt>(Arg);
96 if (!CI || CI->getBitWidth() > 64) {
97 VCalls.insert({Guid, Call.Offset});
98 return;
99 }
100 Args.push_back(CI->getZExtValue());
101 }
102 ConstVCalls.insert({{Guid, Call.Offset}, std::move(Args)});
103}
104
105/// If this intrinsic call requires that we add information to the function
106/// summary, do so via the non-constant reference arguments.
107static void addIntrinsicToSummary(
108 const CallInst *CI, SetVector<GlobalValue::GUID> &TypeTests,
109 SetVector<FunctionSummary::VFuncId> &TypeTestAssumeVCalls,
110 SetVector<FunctionSummary::VFuncId> &TypeCheckedLoadVCalls,
111 SetVector<FunctionSummary::ConstVCall> &TypeTestAssumeConstVCalls,
112 SetVector<FunctionSummary::ConstVCall> &TypeCheckedLoadConstVCalls) {
113 switch (CI->getCalledFunction()->getIntrinsicID()) {
114 case Intrinsic::type_test: {
115 auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(1));
116 auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
117 if (!TypeId)
118 break;
119 GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
120
121 // Produce a summary from type.test intrinsics. We only summarize type.test
122 // intrinsics that are used other than by an llvm.assume intrinsic.
123 // Intrinsics that are assumed are relevant only to the devirtualization
124 // pass, not the type test lowering pass.
125 bool HasNonAssumeUses = llvm::any_of(CI->uses(), [](const Use &CIU) {
126 auto *AssumeCI = dyn_cast<CallInst>(CIU.getUser());
127 if (!AssumeCI)
128 return true;
129 Function *F = AssumeCI->getCalledFunction();
130 return !F || F->getIntrinsicID() != Intrinsic::assume;
131 });
132 if (HasNonAssumeUses)
133 TypeTests.insert(Guid);
134
135 SmallVector<DevirtCallSite, 4> DevirtCalls;
136 SmallVector<CallInst *, 4> Assumes;
137 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
138 for (auto &Call : DevirtCalls)
139 addVCallToSet(Call, Guid, TypeTestAssumeVCalls,
140 TypeTestAssumeConstVCalls);
141
142 break;
143 }
144
145 case Intrinsic::type_checked_load: {
146 auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(2));
147 auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
148 if (!TypeId)
149 break;
150 GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
151
152 SmallVector<DevirtCallSite, 4> DevirtCalls;
153 SmallVector<Instruction *, 4> LoadedPtrs;
154 SmallVector<Instruction *, 4> Preds;
155 bool HasNonCallUses = false;
156 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
157 HasNonCallUses, CI);
158 // Any non-call uses of the result of llvm.type.checked.load will
159 // prevent us from optimizing away the llvm.type.test.
160 if (HasNonCallUses)
161 TypeTests.insert(Guid);
162 for (auto &Call : DevirtCalls)
163 addVCallToSet(Call, Guid, TypeCheckedLoadVCalls,
164 TypeCheckedLoadConstVCalls);
165
166 break;
167 }
168 default:
169 break;
170 }
171}
172
Teresa Johnson519465b2017-01-05 14:32:16 +0000173static void
174computeFunctionSummary(ModuleSummaryIndex &Index, const Module &M,
175 const Function &F, BlockFrequencyInfo *BFI,
176 ProfileSummaryInfo *PSI, bool HasLocalsInUsed,
Teresa Johnsone27b0582017-01-05 14:59:56 +0000177 DenseSet<GlobalValue::GUID> &CantBePromoted) {
Teresa Johnson02563cd2016-10-28 02:39:38 +0000178 // Summary not currently supported for anonymous functions, they should
179 // have been named.
180 assert(F.hasName());
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000181
182 unsigned NumInsts = 0;
183 // Map from callee ValueId to profile count. Used to accumulate profile
184 // counts for all static calls to a given callee.
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000185 MapVector<ValueInfo, CalleeInfo> CallGraphEdges;
186 SetVector<ValueInfo> RefEdges;
Peter Collingbourne1b4137a72016-12-21 23:03:45 +0000187 SetVector<GlobalValue::GUID> TypeTests;
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000188 SetVector<FunctionSummary::VFuncId> TypeTestAssumeVCalls,
189 TypeCheckedLoadVCalls;
190 SetVector<FunctionSummary::ConstVCall> TypeTestAssumeConstVCalls,
191 TypeCheckedLoadConstVCalls;
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000192 ICallPromotionAnalysis ICallAnalysis;
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000193
Teresa Johnsond5033a42016-11-14 16:40:19 +0000194 bool HasInlineAsmMaybeReferencingInternal = false;
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000195 SmallPtrSet<const User *, 8> Visited;
Benjamin Krameraa209152016-06-26 17:27:42 +0000196 for (const BasicBlock &BB : F)
197 for (const Instruction &I : BB) {
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000198 if (isa<DbgInfoIntrinsic>(I))
199 continue;
200 ++NumInsts;
Benjamin Krameraa209152016-06-26 17:27:42 +0000201 findRefEdges(&I, RefEdges, Visited);
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000202 auto CS = ImmutableCallSite(&I);
203 if (!CS)
204 continue;
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000205
206 const auto *CI = dyn_cast<CallInst>(&I);
207 // Since we don't know exactly which local values are referenced in inline
Teresa Johnsond5033a42016-11-14 16:40:19 +0000208 // assembly, conservatively mark the function as possibly referencing
209 // a local value from inline assembly to ensure we don't export a
210 // reference (which would require renaming and promotion of the
211 // referenced value).
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000212 if (HasLocalsInUsed && CI && CI->isInlineAsm())
Teresa Johnsond5033a42016-11-14 16:40:19 +0000213 HasInlineAsmMaybeReferencingInternal = true;
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000214
Teresa Johnson897bab92016-10-08 16:11:42 +0000215 auto *CalledValue = CS.getCalledValue();
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000216 auto *CalledFunction = CS.getCalledFunction();
Teresa Johnson897bab92016-10-08 16:11:42 +0000217 // Check if this is an alias to a function. If so, get the
218 // called aliasee for the checks below.
219 if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) {
220 assert(!CalledFunction && "Expected null called function in callsite for alias");
221 CalledFunction = dyn_cast<Function>(GA->getBaseObject());
222 }
Peter Collingbourne1b4137a72016-12-21 23:03:45 +0000223 // Check if this is a direct call to a known function or a known
224 // intrinsic, or an indirect call with profile data.
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000225 if (CalledFunction) {
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000226 if (CI && CalledFunction->isIntrinsic()) {
227 addIntrinsicToSummary(
228 CI, TypeTests, TypeTestAssumeVCalls, TypeCheckedLoadVCalls,
229 TypeTestAssumeConstVCalls, TypeCheckedLoadConstVCalls);
230 continue;
Peter Collingbourne1b4137a72016-12-21 23:03:45 +0000231 }
Teresa Johnson02563cd2016-10-28 02:39:38 +0000232 // We should have named any anonymous globals
233 assert(CalledFunction->hasName());
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000234 auto ScaledCount = BFI ? BFI->getBlockProfileCount(&BB) : None;
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000235 auto Hotness = ScaledCount ? getHotness(ScaledCount.getValue(), PSI)
236 : CalleeInfo::HotnessType::Unknown;
237
Teresa Johnson897bab92016-10-08 16:11:42 +0000238 // Use the original CalledValue, in case it was an alias. We want
239 // to record the call edge to the alias in that case. Eventually
240 // an alias summary will be created to associate the alias and
241 // aliasee.
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000242 CallGraphEdges[cast<GlobalValue>(CalledValue)].updateHotness(Hotness);
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000243 } else {
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000244 // Skip inline assembly calls.
245 if (CI && CI->isInlineAsm())
246 continue;
247 // Skip direct calls.
248 if (!CS.getCalledValue() || isa<Constant>(CS.getCalledValue()))
249 continue;
250
251 uint32_t NumVals, NumCandidates;
252 uint64_t TotalCount;
253 auto CandidateProfileData =
254 ICallAnalysis.getPromotionCandidatesForInstruction(
255 &I, NumVals, TotalCount, NumCandidates);
256 for (auto &Candidate : CandidateProfileData)
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000257 CallGraphEdges[Candidate.Value].updateHotness(
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000258 getHotness(Candidate.Count, PSI));
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000259 }
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000260 }
261
Teresa Johnson519465b2017-01-05 14:32:16 +0000262 bool NonRenamableLocal = isNonRenamableLocal(F);
263 bool NotEligibleForImport =
264 NonRenamableLocal || HasInlineAsmMaybeReferencingInternal ||
265 // Inliner doesn't handle variadic functions.
266 // FIXME: refactor this to use the same code that inliner is using.
267 F.isVarArg();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000268 GlobalValueSummary::GVFlags Flags(F.getLinkage(), NotEligibleForImport,
Mehdi Amini1380edf2017-02-03 07:41:43 +0000269 /* LiveRoot = */ false);
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000270 auto FuncSummary = llvm::make_unique<FunctionSummary>(
Peter Collingbourne1b4137a72016-12-21 23:03:45 +0000271 Flags, NumInsts, RefEdges.takeVector(), CallGraphEdges.takeVector(),
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000272 TypeTests.takeVector(), TypeTestAssumeVCalls.takeVector(),
273 TypeCheckedLoadVCalls.takeVector(),
274 TypeTestAssumeConstVCalls.takeVector(),
275 TypeCheckedLoadConstVCalls.takeVector());
Teresa Johnson519465b2017-01-05 14:32:16 +0000276 if (NonRenamableLocal)
277 CantBePromoted.insert(F.getGUID());
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000278 Index.addGlobalValueSummary(F.getName(), std::move(FuncSummary));
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000279}
280
Teresa Johnson519465b2017-01-05 14:32:16 +0000281static void
282computeVariableSummary(ModuleSummaryIndex &Index, const GlobalVariable &V,
Teresa Johnsone27b0582017-01-05 14:59:56 +0000283 DenseSet<GlobalValue::GUID> &CantBePromoted) {
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000284 SetVector<ValueInfo> RefEdges;
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000285 SmallPtrSet<const User *, 8> Visited;
286 findRefEdges(&V, RefEdges, Visited);
Teresa Johnson519465b2017-01-05 14:32:16 +0000287 bool NonRenamableLocal = isNonRenamableLocal(V);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000288 GlobalValueSummary::GVFlags Flags(V.getLinkage(), NonRenamableLocal,
Mehdi Amini1380edf2017-02-03 07:41:43 +0000289 /* LiveRoot = */ false);
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000290 auto GVarSummary =
291 llvm::make_unique<GlobalVarSummary>(Flags, RefEdges.takeVector());
Teresa Johnson519465b2017-01-05 14:32:16 +0000292 if (NonRenamableLocal)
293 CantBePromoted.insert(V.getGUID());
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000294 Index.addGlobalValueSummary(V.getName(), std::move(GVarSummary));
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000295}
296
Teresa Johnson519465b2017-01-05 14:32:16 +0000297static void
298computeAliasSummary(ModuleSummaryIndex &Index, const GlobalAlias &A,
Teresa Johnsone27b0582017-01-05 14:59:56 +0000299 DenseSet<GlobalValue::GUID> &CantBePromoted) {
Teresa Johnson519465b2017-01-05 14:32:16 +0000300 bool NonRenamableLocal = isNonRenamableLocal(A);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000301 GlobalValueSummary::GVFlags Flags(A.getLinkage(), NonRenamableLocal,
Mehdi Amini1380edf2017-02-03 07:41:43 +0000302 /* LiveRoot = */ false);
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000303 auto AS = llvm::make_unique<AliasSummary>(Flags, ArrayRef<ValueInfo>{});
Teresa Johnson02563cd2016-10-28 02:39:38 +0000304 auto *Aliasee = A.getBaseObject();
305 auto *AliaseeSummary = Index.getGlobalValueSummary(*Aliasee);
306 assert(AliaseeSummary && "Alias expects aliasee summary to be parsed");
307 AS->setAliasee(AliaseeSummary);
Teresa Johnson519465b2017-01-05 14:32:16 +0000308 if (NonRenamableLocal)
309 CantBePromoted.insert(A.getGUID());
Teresa Johnson02563cd2016-10-28 02:39:38 +0000310 Index.addGlobalValueSummary(A.getName(), std::move(AS));
311}
312
Teresa Johnson6c475a72017-01-05 21:34:18 +0000313// Set LiveRoot flag on entries matching the given value name.
314static void setLiveRoot(ModuleSummaryIndex &Index, StringRef Name) {
315 auto SummaryList =
316 Index.findGlobalValueSummaryList(GlobalValue::getGUID(Name));
317 if (SummaryList == Index.end())
318 return;
319 for (auto &Summary : SummaryList->second)
320 Summary->setLiveRoot();
321}
322
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000323ModuleSummaryIndex llvm::buildModuleSummaryIndex(
324 const Module &M,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000325 std::function<BlockFrequencyInfo *(const Function &F)> GetBFICallback,
326 ProfileSummaryInfo *PSI) {
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000327 ModuleSummaryIndex Index;
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000328
Teresa Johnsona0811452016-11-10 16:57:32 +0000329 // Identify the local values in the llvm.used and llvm.compiler.used sets,
330 // which should not be exported as they would then require renaming and
331 // promotion, but we may have opaque uses e.g. in inline asm. We collect them
332 // here because we use this information to mark functions containing inline
333 // assembly calls as not importable.
Mehdi Aminib6a11a72016-11-09 01:45:13 +0000334 SmallPtrSet<GlobalValue *, 8> LocalsUsed;
Teresa Johnsona0811452016-11-10 16:57:32 +0000335 SmallPtrSet<GlobalValue *, 8> Used;
336 // First collect those in the llvm.used set.
337 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
Teresa Johnsona0811452016-11-10 16:57:32 +0000338 // Next collect those in the llvm.compiler.used set.
339 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ true);
Teresa Johnsone27b0582017-01-05 14:59:56 +0000340 DenseSet<GlobalValue::GUID> CantBePromoted;
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000341 for (auto *V : Used) {
Teresa Johnson519465b2017-01-05 14:32:16 +0000342 if (V->hasLocalLinkage()) {
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000343 LocalsUsed.insert(V);
Teresa Johnson519465b2017-01-05 14:32:16 +0000344 CantBePromoted.insert(V->getGUID());
345 }
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000346 }
Teresa Johnsonb35cc692016-04-20 14:39:45 +0000347
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000348 // Compute summaries for all functions defined in module, and save in the
349 // index.
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000350 for (auto &F : M) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000351 if (F.isDeclaration())
352 continue;
353
354 BlockFrequencyInfo *BFI = nullptr;
355 std::unique_ptr<BlockFrequencyInfo> BFIPtr;
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000356 if (GetBFICallback)
357 BFI = GetBFICallback(F);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000358 else if (F.getEntryCount().hasValue()) {
359 LoopInfo LI{DominatorTree(const_cast<Function &>(F))};
360 BranchProbabilityInfo BPI{F, LI};
361 BFIPtr = llvm::make_unique<BlockFrequencyInfo>(F, BPI, LI);
362 BFI = BFIPtr.get();
363 }
364
Teresa Johnson519465b2017-01-05 14:32:16 +0000365 computeFunctionSummary(Index, M, F, BFI, PSI, !LocalsUsed.empty(),
366 CantBePromoted);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000367 }
368
369 // Compute summaries for all variables defined in module, and save in the
370 // index.
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000371 for (const GlobalVariable &G : M.globals()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000372 if (G.isDeclaration())
373 continue;
Teresa Johnson519465b2017-01-05 14:32:16 +0000374 computeVariableSummary(Index, G, CantBePromoted);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000375 }
Teresa Johnson02563cd2016-10-28 02:39:38 +0000376
377 // Compute summaries for all aliases defined in module, and save in the
378 // index.
379 for (const GlobalAlias &A : M.aliases())
Teresa Johnson519465b2017-01-05 14:32:16 +0000380 computeAliasSummary(Index, A, CantBePromoted);
Teresa Johnson02563cd2016-10-28 02:39:38 +0000381
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000382 for (auto *V : LocalsUsed) {
383 auto *Summary = Index.getGlobalValueSummary(*V);
384 assert(Summary && "Missing summary for global value");
Teresa Johnson519465b2017-01-05 14:32:16 +0000385 Summary->setNotEligibleToImport();
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000386 }
387
Teresa Johnson6c475a72017-01-05 21:34:18 +0000388 // The linker doesn't know about these LLVM produced values, so we need
389 // to flag them as live in the index to ensure index-based dead value
390 // analysis treats them as live roots of the analysis.
391 setLiveRoot(Index, "llvm.used");
392 setLiveRoot(Index, "llvm.compiler.used");
393 setLiveRoot(Index, "llvm.global_ctors");
394 setLiveRoot(Index, "llvm.global_dtors");
395 setLiveRoot(Index, "llvm.global.annotations");
396
Teresa Johnson3624bdf2016-11-14 17:12:32 +0000397 if (!M.getModuleInlineAsm().empty()) {
398 // Collect the local values defined by module level asm, and set up
399 // summaries for these symbols so that they can be marked as NoRename,
400 // to prevent export of any use of them in regular IR that would require
401 // renaming within the module level asm. Note we don't need to create a
402 // summary for weak or global defs, as they don't need to be flagged as
403 // NoRename, and defs in module level asm can't be imported anyway.
404 // Also, any values used but not defined within module level asm should
405 // be listed on the llvm.used or llvm.compiler.used global and marked as
406 // referenced from there.
Peter Collingbourne863cbfb2016-12-01 06:51:47 +0000407 ModuleSymbolTable::CollectAsmSymbols(
Teresa Johnson3624bdf2016-11-14 17:12:32 +0000408 Triple(M.getTargetTriple()), M.getModuleInlineAsm(),
Teresa Johnson519465b2017-01-05 14:32:16 +0000409 [&M, &Index, &CantBePromoted](StringRef Name,
410 object::BasicSymbolRef::Flags Flags) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +0000411 // Symbols not marked as Weak or Global are local definitions.
Teresa Johnsone0ee5cf2016-12-27 17:45:09 +0000412 if (Flags & (object::BasicSymbolRef::SF_Weak |
Teresa Johnson3624bdf2016-11-14 17:12:32 +0000413 object::BasicSymbolRef::SF_Global))
414 return;
415 GlobalValue *GV = M.getNamedValue(Name);
416 if (!GV)
417 return;
418 assert(GV->isDeclaration() && "Def in module asm already has definition");
Teresa Johnson519465b2017-01-05 14:32:16 +0000419 GlobalValueSummary::GVFlags GVFlags(GlobalValue::InternalLinkage,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000420 /* NotEligibleToImport */ true,
Mehdi Amini1380edf2017-02-03 07:41:43 +0000421 /* LiveRoot */ true);
Teresa Johnson519465b2017-01-05 14:32:16 +0000422 CantBePromoted.insert(GlobalValue::getGUID(Name));
Teresa Johnson3624bdf2016-11-14 17:12:32 +0000423 // Create the appropriate summary type.
424 if (isa<Function>(GV)) {
425 std::unique_ptr<FunctionSummary> Summary =
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000426 llvm::make_unique<FunctionSummary>(
427 GVFlags, 0, ArrayRef<ValueInfo>{},
Peter Collingbourne1b4137a72016-12-21 23:03:45 +0000428 ArrayRef<FunctionSummary::EdgeTy>{},
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000429 ArrayRef<GlobalValue::GUID>{},
430 ArrayRef<FunctionSummary::VFuncId>{},
431 ArrayRef<FunctionSummary::VFuncId>{},
432 ArrayRef<FunctionSummary::ConstVCall>{},
433 ArrayRef<FunctionSummary::ConstVCall>{});
Teresa Johnson3624bdf2016-11-14 17:12:32 +0000434 Index.addGlobalValueSummary(Name, std::move(Summary));
435 } else {
436 std::unique_ptr<GlobalVarSummary> Summary =
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000437 llvm::make_unique<GlobalVarSummary>(GVFlags,
438 ArrayRef<ValueInfo>{});
Teresa Johnson3624bdf2016-11-14 17:12:32 +0000439 Index.addGlobalValueSummary(Name, std::move(Summary));
440 }
441 });
442 }
443
Teresa Johnson519465b2017-01-05 14:32:16 +0000444 for (auto &GlobalList : Index) {
445 assert(GlobalList.second.size() == 1 &&
446 "Expected module's index to have one summary per GUID");
447 auto &Summary = GlobalList.second[0];
448 bool AllRefsCanBeExternallyReferenced =
449 llvm::all_of(Summary->refs(), [&](const ValueInfo &VI) {
450 return !CantBePromoted.count(VI.getValue()->getGUID());
451 });
452 if (!AllRefsCanBeExternallyReferenced) {
453 Summary->setNotEligibleToImport();
454 continue;
455 }
456
457 if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
458 bool AllCallsCanBeExternallyReferenced = llvm::all_of(
459 FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
460 auto GUID = Edge.first.isGUID() ? Edge.first.getGUID()
461 : Edge.first.getValue()->getGUID();
462 return !CantBePromoted.count(GUID);
463 });
464 if (!AllCallsCanBeExternallyReferenced)
465 Summary->setNotEligibleToImport();
466 }
467 }
468
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000469 return Index;
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000470}
471
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000472AnalysisKey ModuleSummaryIndexAnalysis::Key;
Teresa Johnsonf93b2462016-08-12 13:53:02 +0000473
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000474ModuleSummaryIndex
Teresa Johnsonf93b2462016-08-12 13:53:02 +0000475ModuleSummaryIndexAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000476 ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M);
Teresa Johnsonf93b2462016-08-12 13:53:02 +0000477 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000478 return buildModuleSummaryIndex(
479 M,
480 [&FAM](const Function &F) {
481 return &FAM.getResult<BlockFrequencyAnalysis>(
482 *const_cast<Function *>(&F));
483 },
484 &PSI);
Teresa Johnsonf93b2462016-08-12 13:53:02 +0000485}
486
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000487char ModuleSummaryIndexWrapperPass::ID = 0;
488INITIALIZE_PASS_BEGIN(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
489 "Module Summary Analysis", false, true)
490INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Mehdi Amini89029482017-01-21 06:01:22 +0000491INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000492INITIALIZE_PASS_END(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
493 "Module Summary Analysis", false, true)
494
495ModulePass *llvm::createModuleSummaryIndexWrapperPass() {
496 return new ModuleSummaryIndexWrapperPass();
497}
498
499ModuleSummaryIndexWrapperPass::ModuleSummaryIndexWrapperPass()
500 : ModulePass(ID) {
501 initializeModuleSummaryIndexWrapperPassPass(*PassRegistry::getPassRegistry());
502}
503
504bool ModuleSummaryIndexWrapperPass::runOnModule(Module &M) {
Dehao Chen5461d8b2016-09-28 21:00:58 +0000505 auto &PSI = *getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000506 Index = buildModuleSummaryIndex(
507 M,
508 [this](const Function &F) {
509 return &(this->getAnalysis<BlockFrequencyInfoWrapperPass>(
510 *const_cast<Function *>(&F))
511 .getBFI());
512 },
513 &PSI);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000514 return false;
515}
516
517bool ModuleSummaryIndexWrapperPass::doFinalization(Module &M) {
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000518 Index.reset();
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000519 return false;
520}
521
522void ModuleSummaryIndexWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
523 AU.setPreservesAll();
524 AU.addRequired<BlockFrequencyInfoWrapperPass>();
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000525 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000526}