File: | llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp |
Warning: | line 1255, column 18 Access to field 'TheKind' results in a dereference of a null pointer (loaded from variable 'Res') |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===// | ||||||||
2 | // | ||||||||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||||||
4 | // See https://llvm.org/LICENSE.txt for license information. | ||||||||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||||||
6 | // | ||||||||
7 | //===----------------------------------------------------------------------===// | ||||||||
8 | // | ||||||||
9 | // This pass implements whole program optimization of virtual calls in cases | ||||||||
10 | // where we know (via !type metadata) that the list of callees is fixed. This | ||||||||
11 | // includes the following: | ||||||||
12 | // - Single implementation devirtualization: if a virtual call has a single | ||||||||
13 | // possible callee, replace all calls with a direct call to that callee. | ||||||||
14 | // - Virtual constant propagation: if the virtual function's return type is an | ||||||||
15 | // integer <=64 bits and all possible callees are readnone, for each class and | ||||||||
16 | // each list of constant arguments: evaluate the function, store the return | ||||||||
17 | // value alongside the virtual table, and rewrite each virtual call as a load | ||||||||
18 | // from the virtual table. | ||||||||
19 | // - Uniform return value optimization: if the conditions for virtual constant | ||||||||
20 | // propagation hold and each function returns the same constant value, replace | ||||||||
21 | // each virtual call with that constant. | ||||||||
22 | // - Unique return value optimization for i1 return values: if the conditions | ||||||||
23 | // for virtual constant propagation hold and a single vtable's function | ||||||||
24 | // returns 0, or a single vtable's function returns 1, replace each virtual | ||||||||
25 | // call with a comparison of the vptr against that vtable's address. | ||||||||
26 | // | ||||||||
27 | // This pass is intended to be used during the regular and thin LTO pipelines: | ||||||||
28 | // | ||||||||
29 | // During regular LTO, the pass determines the best optimization for each | ||||||||
30 | // virtual call and applies the resolutions directly to virtual calls that are | ||||||||
31 | // eligible for virtual call optimization (i.e. calls that use either of the | ||||||||
32 | // llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics). | ||||||||
33 | // | ||||||||
34 | // During hybrid Regular/ThinLTO, the pass operates in two phases: | ||||||||
35 | // - Export phase: this is run during the thin link over a single merged module | ||||||||
36 | // that contains all vtables with !type metadata that participate in the link. | ||||||||
37 | // The pass computes a resolution for each virtual call and stores it in the | ||||||||
38 | // type identifier summary. | ||||||||
39 | // - Import phase: this is run during the thin backends over the individual | ||||||||
40 | // modules. The pass applies the resolutions previously computed during the | ||||||||
41 | // import phase to each eligible virtual call. | ||||||||
42 | // | ||||||||
43 | // During ThinLTO, the pass operates in two phases: | ||||||||
44 | // - Export phase: this is run during the thin link over the index which | ||||||||
45 | // contains a summary of all vtables with !type metadata that participate in | ||||||||
46 | // the link. It computes a resolution for each virtual call and stores it in | ||||||||
47 | // the type identifier summary. Only single implementation devirtualization | ||||||||
48 | // is supported. | ||||||||
49 | // - Import phase: (same as with hybrid case above). | ||||||||
50 | // | ||||||||
51 | //===----------------------------------------------------------------------===// | ||||||||
52 | |||||||||
53 | #include "llvm/Transforms/IPO/WholeProgramDevirt.h" | ||||||||
54 | #include "llvm/ADT/ArrayRef.h" | ||||||||
55 | #include "llvm/ADT/DenseMap.h" | ||||||||
56 | #include "llvm/ADT/DenseMapInfo.h" | ||||||||
57 | #include "llvm/ADT/DenseSet.h" | ||||||||
58 | #include "llvm/ADT/MapVector.h" | ||||||||
59 | #include "llvm/ADT/SmallVector.h" | ||||||||
60 | #include "llvm/ADT/Triple.h" | ||||||||
61 | #include "llvm/ADT/iterator_range.h" | ||||||||
62 | #include "llvm/Analysis/AssumptionCache.h" | ||||||||
63 | #include "llvm/Analysis/BasicAliasAnalysis.h" | ||||||||
64 | #include "llvm/Analysis/OptimizationRemarkEmitter.h" | ||||||||
65 | #include "llvm/Analysis/TypeMetadataUtils.h" | ||||||||
66 | #include "llvm/Bitcode/BitcodeReader.h" | ||||||||
67 | #include "llvm/Bitcode/BitcodeWriter.h" | ||||||||
68 | #include "llvm/IR/Constants.h" | ||||||||
69 | #include "llvm/IR/DataLayout.h" | ||||||||
70 | #include "llvm/IR/DebugLoc.h" | ||||||||
71 | #include "llvm/IR/DerivedTypes.h" | ||||||||
72 | #include "llvm/IR/Dominators.h" | ||||||||
73 | #include "llvm/IR/Function.h" | ||||||||
74 | #include "llvm/IR/GlobalAlias.h" | ||||||||
75 | #include "llvm/IR/GlobalVariable.h" | ||||||||
76 | #include "llvm/IR/IRBuilder.h" | ||||||||
77 | #include "llvm/IR/InstrTypes.h" | ||||||||
78 | #include "llvm/IR/Instruction.h" | ||||||||
79 | #include "llvm/IR/Instructions.h" | ||||||||
80 | #include "llvm/IR/Intrinsics.h" | ||||||||
81 | #include "llvm/IR/LLVMContext.h" | ||||||||
82 | #include "llvm/IR/Metadata.h" | ||||||||
83 | #include "llvm/IR/Module.h" | ||||||||
84 | #include "llvm/IR/ModuleSummaryIndexYAML.h" | ||||||||
85 | #include "llvm/InitializePasses.h" | ||||||||
86 | #include "llvm/Pass.h" | ||||||||
87 | #include "llvm/PassRegistry.h" | ||||||||
88 | #include "llvm/Support/Casting.h" | ||||||||
89 | #include "llvm/Support/CommandLine.h" | ||||||||
90 | #include "llvm/Support/Errc.h" | ||||||||
91 | #include "llvm/Support/Error.h" | ||||||||
92 | #include "llvm/Support/FileSystem.h" | ||||||||
93 | #include "llvm/Support/GlobPattern.h" | ||||||||
94 | #include "llvm/Support/MathExtras.h" | ||||||||
95 | #include "llvm/Transforms/IPO.h" | ||||||||
96 | #include "llvm/Transforms/IPO/FunctionAttrs.h" | ||||||||
97 | #include "llvm/Transforms/Utils/Evaluator.h" | ||||||||
98 | #include <algorithm> | ||||||||
99 | #include <cstddef> | ||||||||
100 | #include <map> | ||||||||
101 | #include <set> | ||||||||
102 | #include <string> | ||||||||
103 | |||||||||
104 | using namespace llvm; | ||||||||
105 | using namespace wholeprogramdevirt; | ||||||||
106 | |||||||||
107 | #define DEBUG_TYPE"wholeprogramdevirt" "wholeprogramdevirt" | ||||||||
108 | |||||||||
109 | static cl::opt<PassSummaryAction> ClSummaryAction( | ||||||||
110 | "wholeprogramdevirt-summary-action", | ||||||||
111 | cl::desc("What to do with the summary when running this pass"), | ||||||||
112 | cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing")llvm::cl::OptionEnumValue { "none", int(PassSummaryAction::None ), "Do nothing" }, | ||||||||
113 | clEnumValN(PassSummaryAction::Import, "import",llvm::cl::OptionEnumValue { "import", int(PassSummaryAction:: Import), "Import typeid resolutions from summary and globals" } | ||||||||
114 | "Import typeid resolutions from summary and globals")llvm::cl::OptionEnumValue { "import", int(PassSummaryAction:: Import), "Import typeid resolutions from summary and globals" }, | ||||||||
115 | clEnumValN(PassSummaryAction::Export, "export",llvm::cl::OptionEnumValue { "export", int(PassSummaryAction:: Export), "Export typeid resolutions to summary and globals" } | ||||||||
116 | "Export typeid resolutions to summary and globals")llvm::cl::OptionEnumValue { "export", int(PassSummaryAction:: Export), "Export typeid resolutions to summary and globals" }), | ||||||||
117 | cl::Hidden); | ||||||||
118 | |||||||||
119 | static cl::opt<std::string> ClReadSummary( | ||||||||
120 | "wholeprogramdevirt-read-summary", | ||||||||
121 | cl::desc( | ||||||||
122 | "Read summary from given bitcode or YAML file before running pass"), | ||||||||
123 | cl::Hidden); | ||||||||
124 | |||||||||
125 | static cl::opt<std::string> ClWriteSummary( | ||||||||
126 | "wholeprogramdevirt-write-summary", | ||||||||
127 | cl::desc("Write summary to given bitcode or YAML file after running pass. " | ||||||||
128 | "Output file format is deduced from extension: *.bc means writing " | ||||||||
129 | "bitcode, otherwise YAML"), | ||||||||
130 | cl::Hidden); | ||||||||
131 | |||||||||
132 | static cl::opt<unsigned> | ||||||||
133 | ClThreshold("wholeprogramdevirt-branch-funnel-threshold", cl::Hidden, | ||||||||
134 | cl::init(10), cl::ZeroOrMore, | ||||||||
135 | cl::desc("Maximum number of call targets per " | ||||||||
136 | "call site to enable branch funnels")); | ||||||||
137 | |||||||||
138 | static cl::opt<bool> | ||||||||
139 | PrintSummaryDevirt("wholeprogramdevirt-print-index-based", cl::Hidden, | ||||||||
140 | cl::init(false), cl::ZeroOrMore, | ||||||||
141 | cl::desc("Print index-based devirtualization messages")); | ||||||||
142 | |||||||||
143 | /// Provide a way to force enable whole program visibility in tests. | ||||||||
144 | /// This is needed to support legacy tests that don't contain | ||||||||
145 | /// !vcall_visibility metadata (the mere presense of type tests | ||||||||
146 | /// previously implied hidden visibility). | ||||||||
147 | cl::opt<bool> | ||||||||
148 | WholeProgramVisibility("whole-program-visibility", cl::init(false), | ||||||||
149 | cl::Hidden, cl::ZeroOrMore, | ||||||||
150 | cl::desc("Enable whole program visibility")); | ||||||||
151 | |||||||||
152 | /// Provide a way to force disable whole program for debugging or workarounds, | ||||||||
153 | /// when enabled via the linker. | ||||||||
154 | cl::opt<bool> DisableWholeProgramVisibility( | ||||||||
155 | "disable-whole-program-visibility", cl::init(false), cl::Hidden, | ||||||||
156 | cl::ZeroOrMore, | ||||||||
157 | cl::desc("Disable whole program visibility (overrides enabling options)")); | ||||||||
158 | |||||||||
159 | /// Provide way to prevent certain function from being devirtualized | ||||||||
160 | cl::list<std::string> | ||||||||
161 | SkipFunctionNames("wholeprogramdevirt-skip", | ||||||||
162 | cl::desc("Prevent function(s) from being devirtualized"), | ||||||||
163 | cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated); | ||||||||
164 | |||||||||
165 | namespace { | ||||||||
166 | struct PatternList { | ||||||||
167 | std::vector<GlobPattern> Patterns; | ||||||||
168 | template <class T> void init(const T &StringList) { | ||||||||
169 | for (const auto &S : StringList) | ||||||||
170 | if (Expected<GlobPattern> Pat = GlobPattern::create(S)) | ||||||||
171 | Patterns.push_back(std::move(*Pat)); | ||||||||
172 | } | ||||||||
173 | bool match(StringRef S) { | ||||||||
174 | for (const GlobPattern &P : Patterns) | ||||||||
175 | if (P.match(S)) | ||||||||
176 | return true; | ||||||||
177 | return false; | ||||||||
178 | } | ||||||||
179 | }; | ||||||||
180 | } // namespace | ||||||||
181 | |||||||||
182 | // Find the minimum offset that we may store a value of size Size bits at. If | ||||||||
183 | // IsAfter is set, look for an offset before the object, otherwise look for an | ||||||||
184 | // offset after the object. | ||||||||
185 | uint64_t | ||||||||
186 | wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets, | ||||||||
187 | bool IsAfter, uint64_t Size) { | ||||||||
188 | // Find a minimum offset taking into account only vtable sizes. | ||||||||
189 | uint64_t MinByte = 0; | ||||||||
190 | for (const VirtualCallTarget &Target : Targets) { | ||||||||
191 | if (IsAfter) | ||||||||
192 | MinByte = std::max(MinByte, Target.minAfterBytes()); | ||||||||
193 | else | ||||||||
194 | MinByte = std::max(MinByte, Target.minBeforeBytes()); | ||||||||
195 | } | ||||||||
196 | |||||||||
197 | // Build a vector of arrays of bytes covering, for each target, a slice of the | ||||||||
198 | // used region (see AccumBitVector::BytesUsed in | ||||||||
199 | // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively, | ||||||||
200 | // this aligns the used regions to start at MinByte. | ||||||||
201 | // | ||||||||
202 | // In this example, A, B and C are vtables, # is a byte already allocated for | ||||||||
203 | // a virtual function pointer, AAAA... (etc.) are the used regions for the | ||||||||
204 | // vtables and Offset(X) is the value computed for the Offset variable below | ||||||||
205 | // for X. | ||||||||
206 | // | ||||||||
207 | // Offset(A) | ||||||||
208 | // | | | ||||||||
209 | // |MinByte | ||||||||
210 | // A: ################AAAAAAAA|AAAAAAAA | ||||||||
211 | // B: ########BBBBBBBBBBBBBBBB|BBBB | ||||||||
212 | // C: ########################|CCCCCCCCCCCCCCCC | ||||||||
213 | // | Offset(B) | | ||||||||
214 | // | ||||||||
215 | // This code produces the slices of A, B and C that appear after the divider | ||||||||
216 | // at MinByte. | ||||||||
217 | std::vector<ArrayRef<uint8_t>> Used; | ||||||||
218 | for (const VirtualCallTarget &Target : Targets) { | ||||||||
219 | ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed | ||||||||
220 | : Target.TM->Bits->Before.BytesUsed; | ||||||||
221 | uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes() | ||||||||
222 | : MinByte - Target.minBeforeBytes(); | ||||||||
223 | |||||||||
224 | // Disregard used regions that are smaller than Offset. These are | ||||||||
225 | // effectively all-free regions that do not need to be checked. | ||||||||
226 | if (VTUsed.size() > Offset) | ||||||||
227 | Used.push_back(VTUsed.slice(Offset)); | ||||||||
228 | } | ||||||||
229 | |||||||||
230 | if (Size == 1) { | ||||||||
231 | // Find a free bit in each member of Used. | ||||||||
232 | for (unsigned I = 0;; ++I) { | ||||||||
233 | uint8_t BitsUsed = 0; | ||||||||
234 | for (auto &&B : Used) | ||||||||
235 | if (I < B.size()) | ||||||||
236 | BitsUsed |= B[I]; | ||||||||
237 | if (BitsUsed != 0xff) | ||||||||
238 | return (MinByte + I) * 8 + | ||||||||
239 | countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined); | ||||||||
240 | } | ||||||||
241 | } else { | ||||||||
242 | // Find a free (Size/8) byte region in each member of Used. | ||||||||
243 | // FIXME: see if alignment helps. | ||||||||
244 | for (unsigned I = 0;; ++I) { | ||||||||
245 | for (auto &&B : Used) { | ||||||||
246 | unsigned Byte = 0; | ||||||||
247 | while ((I + Byte) < B.size() && Byte < (Size / 8)) { | ||||||||
248 | if (B[I + Byte]) | ||||||||
249 | goto NextI; | ||||||||
250 | ++Byte; | ||||||||
251 | } | ||||||||
252 | } | ||||||||
253 | return (MinByte + I) * 8; | ||||||||
254 | NextI:; | ||||||||
255 | } | ||||||||
256 | } | ||||||||
257 | } | ||||||||
258 | |||||||||
259 | void wholeprogramdevirt::setBeforeReturnValues( | ||||||||
260 | MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore, | ||||||||
261 | unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { | ||||||||
262 | if (BitWidth == 1) | ||||||||
263 | OffsetByte = -(AllocBefore / 8 + 1); | ||||||||
264 | else | ||||||||
265 | OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8); | ||||||||
266 | OffsetBit = AllocBefore % 8; | ||||||||
267 | |||||||||
268 | for (VirtualCallTarget &Target : Targets) { | ||||||||
269 | if (BitWidth == 1) | ||||||||
270 | Target.setBeforeBit(AllocBefore); | ||||||||
271 | else | ||||||||
272 | Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8); | ||||||||
273 | } | ||||||||
274 | } | ||||||||
275 | |||||||||
276 | void wholeprogramdevirt::setAfterReturnValues( | ||||||||
277 | MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter, | ||||||||
278 | unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { | ||||||||
279 | if (BitWidth == 1) | ||||||||
280 | OffsetByte = AllocAfter / 8; | ||||||||
281 | else | ||||||||
282 | OffsetByte = (AllocAfter + 7) / 8; | ||||||||
283 | OffsetBit = AllocAfter % 8; | ||||||||
284 | |||||||||
285 | for (VirtualCallTarget &Target : Targets) { | ||||||||
286 | if (BitWidth == 1) | ||||||||
287 | Target.setAfterBit(AllocAfter); | ||||||||
288 | else | ||||||||
289 | Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8); | ||||||||
290 | } | ||||||||
291 | } | ||||||||
292 | |||||||||
293 | VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM) | ||||||||
294 | : Fn(Fn), TM(TM), | ||||||||
295 | IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {} | ||||||||
296 | |||||||||
297 | namespace { | ||||||||
298 | |||||||||
299 | // A slot in a set of virtual tables. The TypeID identifies the set of virtual | ||||||||
300 | // tables, and the ByteOffset is the offset in bytes from the address point to | ||||||||
301 | // the virtual function pointer. | ||||||||
302 | struct VTableSlot { | ||||||||
303 | Metadata *TypeID; | ||||||||
304 | uint64_t ByteOffset; | ||||||||
305 | }; | ||||||||
306 | |||||||||
307 | } // end anonymous namespace | ||||||||
308 | |||||||||
309 | namespace llvm { | ||||||||
310 | |||||||||
311 | template <> struct DenseMapInfo<VTableSlot> { | ||||||||
312 | static VTableSlot getEmptyKey() { | ||||||||
313 | return {DenseMapInfo<Metadata *>::getEmptyKey(), | ||||||||
314 | DenseMapInfo<uint64_t>::getEmptyKey()}; | ||||||||
315 | } | ||||||||
316 | static VTableSlot getTombstoneKey() { | ||||||||
317 | return {DenseMapInfo<Metadata *>::getTombstoneKey(), | ||||||||
318 | DenseMapInfo<uint64_t>::getTombstoneKey()}; | ||||||||
319 | } | ||||||||
320 | static unsigned getHashValue(const VTableSlot &I) { | ||||||||
321 | return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^ | ||||||||
322 | DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset); | ||||||||
323 | } | ||||||||
324 | static bool isEqual(const VTableSlot &LHS, | ||||||||
325 | const VTableSlot &RHS) { | ||||||||
326 | return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset; | ||||||||
327 | } | ||||||||
328 | }; | ||||||||
329 | |||||||||
330 | template <> struct DenseMapInfo<VTableSlotSummary> { | ||||||||
331 | static VTableSlotSummary getEmptyKey() { | ||||||||
332 | return {DenseMapInfo<StringRef>::getEmptyKey(), | ||||||||
333 | DenseMapInfo<uint64_t>::getEmptyKey()}; | ||||||||
334 | } | ||||||||
335 | static VTableSlotSummary getTombstoneKey() { | ||||||||
336 | return {DenseMapInfo<StringRef>::getTombstoneKey(), | ||||||||
337 | DenseMapInfo<uint64_t>::getTombstoneKey()}; | ||||||||
338 | } | ||||||||
339 | static unsigned getHashValue(const VTableSlotSummary &I) { | ||||||||
340 | return DenseMapInfo<StringRef>::getHashValue(I.TypeID) ^ | ||||||||
341 | DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset); | ||||||||
342 | } | ||||||||
343 | static bool isEqual(const VTableSlotSummary &LHS, | ||||||||
344 | const VTableSlotSummary &RHS) { | ||||||||
345 | return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset; | ||||||||
346 | } | ||||||||
347 | }; | ||||||||
348 | |||||||||
349 | } // end namespace llvm | ||||||||
350 | |||||||||
351 | namespace { | ||||||||
352 | |||||||||
353 | // A virtual call site. VTable is the loaded virtual table pointer, and CS is | ||||||||
354 | // the indirect virtual call. | ||||||||
355 | struct VirtualCallSite { | ||||||||
356 | Value *VTable = nullptr; | ||||||||
357 | CallBase &CB; | ||||||||
358 | |||||||||
359 | // If non-null, this field points to the associated unsafe use count stored in | ||||||||
360 | // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description | ||||||||
361 | // of that field for details. | ||||||||
362 | unsigned *NumUnsafeUses = nullptr; | ||||||||
363 | |||||||||
364 | void | ||||||||
365 | emitRemark(const StringRef OptName, const StringRef TargetName, | ||||||||
366 | function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) { | ||||||||
367 | Function *F = CB.getCaller(); | ||||||||
368 | DebugLoc DLoc = CB.getDebugLoc(); | ||||||||
369 | BasicBlock *Block = CB.getParent(); | ||||||||
370 | |||||||||
371 | using namespace ore; | ||||||||
372 | OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE"wholeprogramdevirt", OptName, DLoc, Block) | ||||||||
373 | << NV("Optimization", OptName) | ||||||||
374 | << ": devirtualized a call to " | ||||||||
375 | << NV("FunctionName", TargetName)); | ||||||||
376 | } | ||||||||
377 | |||||||||
378 | void replaceAndErase( | ||||||||
379 | const StringRef OptName, const StringRef TargetName, bool RemarksEnabled, | ||||||||
380 | function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, | ||||||||
381 | Value *New) { | ||||||||
382 | if (RemarksEnabled) | ||||||||
383 | emitRemark(OptName, TargetName, OREGetter); | ||||||||
384 | CB.replaceAllUsesWith(New); | ||||||||
385 | if (auto *II = dyn_cast<InvokeInst>(&CB)) { | ||||||||
386 | BranchInst::Create(II->getNormalDest(), &CB); | ||||||||
387 | II->getUnwindDest()->removePredecessor(II->getParent()); | ||||||||
388 | } | ||||||||
389 | CB.eraseFromParent(); | ||||||||
390 | // This use is no longer unsafe. | ||||||||
391 | if (NumUnsafeUses) | ||||||||
392 | --*NumUnsafeUses; | ||||||||
393 | } | ||||||||
394 | }; | ||||||||
395 | |||||||||
396 | // Call site information collected for a specific VTableSlot and possibly a list | ||||||||
397 | // of constant integer arguments. The grouping by arguments is handled by the | ||||||||
398 | // VTableSlotInfo class. | ||||||||
399 | struct CallSiteInfo { | ||||||||
400 | /// The set of call sites for this slot. Used during regular LTO and the | ||||||||
401 | /// import phase of ThinLTO (as well as the export phase of ThinLTO for any | ||||||||
402 | /// call sites that appear in the merged module itself); in each of these | ||||||||
403 | /// cases we are directly operating on the call sites at the IR level. | ||||||||
404 | std::vector<VirtualCallSite> CallSites; | ||||||||
405 | |||||||||
406 | /// Whether all call sites represented by this CallSiteInfo, including those | ||||||||
407 | /// in summaries, have been devirtualized. This starts off as true because a | ||||||||
408 | /// default constructed CallSiteInfo represents no call sites. | ||||||||
409 | bool AllCallSitesDevirted = true; | ||||||||
410 | |||||||||
411 | // These fields are used during the export phase of ThinLTO and reflect | ||||||||
412 | // information collected from function summaries. | ||||||||
413 | |||||||||
414 | /// Whether any function summary contains an llvm.assume(llvm.type.test) for | ||||||||
415 | /// this slot. | ||||||||
416 | bool SummaryHasTypeTestAssumeUsers = false; | ||||||||
417 | |||||||||
418 | /// CFI-specific: a vector containing the list of function summaries that use | ||||||||
419 | /// the llvm.type.checked.load intrinsic and therefore will require | ||||||||
420 | /// resolutions for llvm.type.test in order to implement CFI checks if | ||||||||
421 | /// devirtualization was unsuccessful. If devirtualization was successful, the | ||||||||
422 | /// pass will clear this vector by calling markDevirt(). If at the end of the | ||||||||
423 | /// pass the vector is non-empty, we will need to add a use of llvm.type.test | ||||||||
424 | /// to each of the function summaries in the vector. | ||||||||
425 | std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers; | ||||||||
426 | std::vector<FunctionSummary *> SummaryTypeTestAssumeUsers; | ||||||||
427 | |||||||||
428 | bool isExported() const { | ||||||||
429 | return SummaryHasTypeTestAssumeUsers || | ||||||||
430 | !SummaryTypeCheckedLoadUsers.empty(); | ||||||||
431 | } | ||||||||
432 | |||||||||
433 | void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) { | ||||||||
434 | SummaryTypeCheckedLoadUsers.push_back(FS); | ||||||||
435 | AllCallSitesDevirted = false; | ||||||||
436 | } | ||||||||
437 | |||||||||
438 | void addSummaryTypeTestAssumeUser(FunctionSummary *FS) { | ||||||||
439 | SummaryTypeTestAssumeUsers.push_back(FS); | ||||||||
440 | SummaryHasTypeTestAssumeUsers = true; | ||||||||
441 | AllCallSitesDevirted = false; | ||||||||
442 | } | ||||||||
443 | |||||||||
444 | void markDevirt() { | ||||||||
445 | AllCallSitesDevirted = true; | ||||||||
446 | |||||||||
447 | // As explained in the comment for SummaryTypeCheckedLoadUsers. | ||||||||
448 | SummaryTypeCheckedLoadUsers.clear(); | ||||||||
449 | } | ||||||||
450 | }; | ||||||||
451 | |||||||||
452 | // Call site information collected for a specific VTableSlot. | ||||||||
453 | struct VTableSlotInfo { | ||||||||
454 | // The set of call sites which do not have all constant integer arguments | ||||||||
455 | // (excluding "this"). | ||||||||
456 | CallSiteInfo CSInfo; | ||||||||
457 | |||||||||
458 | // The set of call sites with all constant integer arguments (excluding | ||||||||
459 | // "this"), grouped by argument list. | ||||||||
460 | std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo; | ||||||||
461 | |||||||||
462 | void addCallSite(Value *VTable, CallBase &CB, unsigned *NumUnsafeUses); | ||||||||
463 | |||||||||
464 | private: | ||||||||
465 | CallSiteInfo &findCallSiteInfo(CallBase &CB); | ||||||||
466 | }; | ||||||||
467 | |||||||||
468 | CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallBase &CB) { | ||||||||
469 | std::vector<uint64_t> Args; | ||||||||
470 | auto *CBType = dyn_cast<IntegerType>(CB.getType()); | ||||||||
471 | if (!CBType || CBType->getBitWidth() > 64 || CB.arg_empty()) | ||||||||
472 | return CSInfo; | ||||||||
473 | for (auto &&Arg : drop_begin(CB.args(), 1)) { | ||||||||
474 | auto *CI = dyn_cast<ConstantInt>(Arg); | ||||||||
475 | if (!CI || CI->getBitWidth() > 64) | ||||||||
476 | return CSInfo; | ||||||||
477 | Args.push_back(CI->getZExtValue()); | ||||||||
478 | } | ||||||||
479 | return ConstCSInfo[Args]; | ||||||||
480 | } | ||||||||
481 | |||||||||
482 | void VTableSlotInfo::addCallSite(Value *VTable, CallBase &CB, | ||||||||
483 | unsigned *NumUnsafeUses) { | ||||||||
484 | auto &CSI = findCallSiteInfo(CB); | ||||||||
485 | CSI.AllCallSitesDevirted = false; | ||||||||
486 | CSI.CallSites.push_back({VTable, CB, NumUnsafeUses}); | ||||||||
487 | } | ||||||||
488 | |||||||||
489 | struct DevirtModule { | ||||||||
490 | Module &M; | ||||||||
491 | function_ref<AAResults &(Function &)> AARGetter; | ||||||||
492 | function_ref<DominatorTree &(Function &)> LookupDomTree; | ||||||||
493 | |||||||||
494 | ModuleSummaryIndex *ExportSummary; | ||||||||
495 | const ModuleSummaryIndex *ImportSummary; | ||||||||
496 | |||||||||
497 | IntegerType *Int8Ty; | ||||||||
498 | PointerType *Int8PtrTy; | ||||||||
499 | IntegerType *Int32Ty; | ||||||||
500 | IntegerType *Int64Ty; | ||||||||
501 | IntegerType *IntPtrTy; | ||||||||
502 | /// Sizeless array type, used for imported vtables. This provides a signal | ||||||||
503 | /// to analyzers that these imports may alias, as they do for example | ||||||||
504 | /// when multiple unique return values occur in the same vtable. | ||||||||
505 | ArrayType *Int8Arr0Ty; | ||||||||
506 | |||||||||
507 | bool RemarksEnabled; | ||||||||
508 | function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter; | ||||||||
509 | |||||||||
510 | MapVector<VTableSlot, VTableSlotInfo> CallSlots; | ||||||||
511 | |||||||||
512 | // This map keeps track of the number of "unsafe" uses of a loaded function | ||||||||
513 | // pointer. The key is the associated llvm.type.test intrinsic call generated | ||||||||
514 | // by this pass. An unsafe use is one that calls the loaded function pointer | ||||||||
515 | // directly. Every time we eliminate an unsafe use (for example, by | ||||||||
516 | // devirtualizing it or by applying virtual constant propagation), we | ||||||||
517 | // decrement the value stored in this map. If a value reaches zero, we can | ||||||||
518 | // eliminate the type check by RAUWing the associated llvm.type.test call with | ||||||||
519 | // true. | ||||||||
520 | std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest; | ||||||||
521 | PatternList FunctionsToSkip; | ||||||||
522 | |||||||||
523 | DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter, | ||||||||
524 | function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, | ||||||||
525 | function_ref<DominatorTree &(Function &)> LookupDomTree, | ||||||||
526 | ModuleSummaryIndex *ExportSummary, | ||||||||
527 | const ModuleSummaryIndex *ImportSummary) | ||||||||
528 | : M(M), AARGetter(AARGetter), LookupDomTree(LookupDomTree), | ||||||||
529 | ExportSummary(ExportSummary), ImportSummary(ImportSummary), | ||||||||
530 | Int8Ty(Type::getInt8Ty(M.getContext())), | ||||||||
531 | Int8PtrTy(Type::getInt8PtrTy(M.getContext())), | ||||||||
532 | Int32Ty(Type::getInt32Ty(M.getContext())), | ||||||||
533 | Int64Ty(Type::getInt64Ty(M.getContext())), | ||||||||
534 | IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)), | ||||||||
535 | Int8Arr0Ty(ArrayType::get(Type::getInt8Ty(M.getContext()), 0)), | ||||||||
536 | RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) { | ||||||||
537 | assert(!(ExportSummary && ImportSummary))((!(ExportSummary && ImportSummary)) ? static_cast< void> (0) : __assert_fail ("!(ExportSummary && ImportSummary)" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp" , 537, __PRETTY_FUNCTION__)); | ||||||||
538 | FunctionsToSkip.init(SkipFunctionNames); | ||||||||
539 | } | ||||||||
540 | |||||||||
541 | bool areRemarksEnabled(); | ||||||||
542 | |||||||||
543 | void | ||||||||
544 | scanTypeTestUsers(Function *TypeTestFunc, | ||||||||
545 | DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap); | ||||||||
546 | void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc); | ||||||||
547 | |||||||||
548 | void buildTypeIdentifierMap( | ||||||||
549 | std::vector<VTableBits> &Bits, | ||||||||
550 | DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap); | ||||||||
551 | bool | ||||||||
552 | tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot, | ||||||||
553 | const std::set<TypeMemberInfo> &TypeMemberInfos, | ||||||||
554 | uint64_t ByteOffset); | ||||||||
555 | |||||||||
556 | void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn, | ||||||||
557 | bool &IsExported); | ||||||||
558 | bool trySingleImplDevirt(ModuleSummaryIndex *ExportSummary, | ||||||||
559 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, | ||||||||
560 | VTableSlotInfo &SlotInfo, | ||||||||
561 | WholeProgramDevirtResolution *Res); | ||||||||
562 | |||||||||
563 | void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Constant *JT, | ||||||||
564 | bool &IsExported); | ||||||||
565 | void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot, | ||||||||
566 | VTableSlotInfo &SlotInfo, | ||||||||
567 | WholeProgramDevirtResolution *Res, VTableSlot Slot); | ||||||||
568 | |||||||||
569 | bool tryEvaluateFunctionsWithArgs( | ||||||||
570 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, | ||||||||
571 | ArrayRef<uint64_t> Args); | ||||||||
572 | |||||||||
573 | void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, | ||||||||
574 | uint64_t TheRetVal); | ||||||||
575 | bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot, | ||||||||
576 | CallSiteInfo &CSInfo, | ||||||||
577 | WholeProgramDevirtResolution::ByArg *Res); | ||||||||
578 | |||||||||
579 | // Returns the global symbol name that is used to export information about the | ||||||||
580 | // given vtable slot and list of arguments. | ||||||||
581 | std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args, | ||||||||
582 | StringRef Name); | ||||||||
583 | |||||||||
584 | bool shouldExportConstantsAsAbsoluteSymbols(); | ||||||||
585 | |||||||||
586 | // This function is called during the export phase to create a symbol | ||||||||
587 | // definition containing information about the given vtable slot and list of | ||||||||
588 | // arguments. | ||||||||
589 | void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name, | ||||||||
590 | Constant *C); | ||||||||
591 | void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name, | ||||||||
592 | uint32_t Const, uint32_t &Storage); | ||||||||
593 | |||||||||
594 | // This function is called during the import phase to create a reference to | ||||||||
595 | // the symbol definition created during the export phase. | ||||||||
596 | Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, | ||||||||
597 | StringRef Name); | ||||||||
598 | Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, | ||||||||
599 | StringRef Name, IntegerType *IntTy, | ||||||||
600 | uint32_t Storage); | ||||||||
601 | |||||||||
602 | Constant *getMemberAddr(const TypeMemberInfo *M); | ||||||||
603 | |||||||||
604 | void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne, | ||||||||
605 | Constant *UniqueMemberAddr); | ||||||||
606 | bool tryUniqueRetValOpt(unsigned BitWidth, | ||||||||
607 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, | ||||||||
608 | CallSiteInfo &CSInfo, | ||||||||
609 | WholeProgramDevirtResolution::ByArg *Res, | ||||||||
610 | VTableSlot Slot, ArrayRef<uint64_t> Args); | ||||||||
611 | |||||||||
612 | void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, | ||||||||
613 | Constant *Byte, Constant *Bit); | ||||||||
614 | bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot, | ||||||||
615 | VTableSlotInfo &SlotInfo, | ||||||||
616 | WholeProgramDevirtResolution *Res, VTableSlot Slot); | ||||||||
617 | |||||||||
618 | void rebuildGlobal(VTableBits &B); | ||||||||
619 | |||||||||
620 | // Apply the summary resolution for Slot to all virtual calls in SlotInfo. | ||||||||
621 | void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo); | ||||||||
622 | |||||||||
623 | // If we were able to eliminate all unsafe uses for a type checked load, | ||||||||
624 | // eliminate the associated type tests by replacing them with true. | ||||||||
625 | void removeRedundantTypeTests(); | ||||||||
626 | |||||||||
627 | bool run(); | ||||||||
628 | |||||||||
629 | // Lower the module using the action and summary passed as command line | ||||||||
630 | // arguments. For testing purposes only. | ||||||||
631 | static bool | ||||||||
632 | runForTesting(Module &M, function_ref<AAResults &(Function &)> AARGetter, | ||||||||
633 | function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, | ||||||||
634 | function_ref<DominatorTree &(Function &)> LookupDomTree); | ||||||||
635 | }; | ||||||||
636 | |||||||||
637 | struct DevirtIndex { | ||||||||
638 | ModuleSummaryIndex &ExportSummary; | ||||||||
639 | // The set in which to record GUIDs exported from their module by | ||||||||
640 | // devirtualization, used by client to ensure they are not internalized. | ||||||||
641 | std::set<GlobalValue::GUID> &ExportedGUIDs; | ||||||||
642 | // A map in which to record the information necessary to locate the WPD | ||||||||
643 | // resolution for local targets in case they are exported by cross module | ||||||||
644 | // importing. | ||||||||
645 | std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap; | ||||||||
646 | |||||||||
647 | MapVector<VTableSlotSummary, VTableSlotInfo> CallSlots; | ||||||||
648 | |||||||||
649 | PatternList FunctionsToSkip; | ||||||||
650 | |||||||||
651 | DevirtIndex( | ||||||||
652 | ModuleSummaryIndex &ExportSummary, | ||||||||
653 | std::set<GlobalValue::GUID> &ExportedGUIDs, | ||||||||
654 | std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) | ||||||||
655 | : ExportSummary(ExportSummary), ExportedGUIDs(ExportedGUIDs), | ||||||||
656 | LocalWPDTargetsMap(LocalWPDTargetsMap) { | ||||||||
657 | FunctionsToSkip.init(SkipFunctionNames); | ||||||||
658 | } | ||||||||
659 | |||||||||
660 | bool tryFindVirtualCallTargets(std::vector<ValueInfo> &TargetsForSlot, | ||||||||
661 | const TypeIdCompatibleVtableInfo TIdInfo, | ||||||||
662 | uint64_t ByteOffset); | ||||||||
663 | |||||||||
664 | bool trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot, | ||||||||
665 | VTableSlotSummary &SlotSummary, | ||||||||
666 | VTableSlotInfo &SlotInfo, | ||||||||
667 | WholeProgramDevirtResolution *Res, | ||||||||
668 | std::set<ValueInfo> &DevirtTargets); | ||||||||
669 | |||||||||
670 | void run(); | ||||||||
671 | }; | ||||||||
672 | |||||||||
673 | struct WholeProgramDevirt : public ModulePass { | ||||||||
674 | static char ID; | ||||||||
675 | |||||||||
676 | bool UseCommandLine = false; | ||||||||
677 | |||||||||
678 | ModuleSummaryIndex *ExportSummary = nullptr; | ||||||||
679 | const ModuleSummaryIndex *ImportSummary = nullptr; | ||||||||
680 | |||||||||
681 | WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) { | ||||||||
682 | initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); | ||||||||
683 | } | ||||||||
684 | |||||||||
685 | WholeProgramDevirt(ModuleSummaryIndex *ExportSummary, | ||||||||
686 | const ModuleSummaryIndex *ImportSummary) | ||||||||
687 | : ModulePass(ID), ExportSummary(ExportSummary), | ||||||||
688 | ImportSummary(ImportSummary) { | ||||||||
689 | initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); | ||||||||
690 | } | ||||||||
691 | |||||||||
692 | bool runOnModule(Module &M) override { | ||||||||
693 | if (skipModule(M)) | ||||||||
694 | return false; | ||||||||
695 | |||||||||
696 | // In the new pass manager, we can request the optimization | ||||||||
697 | // remark emitter pass on a per-function-basis, which the | ||||||||
698 | // OREGetter will do for us. | ||||||||
699 | // In the old pass manager, this is harder, so we just build | ||||||||
700 | // an optimization remark emitter on the fly, when we need it. | ||||||||
701 | std::unique_ptr<OptimizationRemarkEmitter> ORE; | ||||||||
702 | auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & { | ||||||||
703 | ORE = std::make_unique<OptimizationRemarkEmitter>(F); | ||||||||
704 | return *ORE; | ||||||||
705 | }; | ||||||||
706 | |||||||||
707 | auto LookupDomTree = [this](Function &F) -> DominatorTree & { | ||||||||
708 | return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); | ||||||||
709 | }; | ||||||||
710 | |||||||||
711 | if (UseCommandLine) | ||||||||
712 | return DevirtModule::runForTesting(M, LegacyAARGetter(*this), OREGetter, | ||||||||
713 | LookupDomTree); | ||||||||
714 | |||||||||
715 | return DevirtModule(M, LegacyAARGetter(*this), OREGetter, LookupDomTree, | ||||||||
716 | ExportSummary, ImportSummary) | ||||||||
717 | .run(); | ||||||||
718 | } | ||||||||
719 | |||||||||
720 | void getAnalysisUsage(AnalysisUsage &AU) const override { | ||||||||
721 | AU.addRequired<AssumptionCacheTracker>(); | ||||||||
722 | AU.addRequired<TargetLibraryInfoWrapperPass>(); | ||||||||
723 | AU.addRequired<DominatorTreeWrapperPass>(); | ||||||||
724 | } | ||||||||
725 | }; | ||||||||
726 | |||||||||
727 | } // end anonymous namespace | ||||||||
728 | |||||||||
729 | INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",static void *initializeWholeProgramDevirtPassOnce(PassRegistry &Registry) { | ||||||||
730 | "Whole program devirtualization", false, false)static void *initializeWholeProgramDevirtPassOnce(PassRegistry &Registry) { | ||||||||
731 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry); | ||||||||
732 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry); | ||||||||
733 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry); | ||||||||
734 | INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",PassInfo *PI = new PassInfo( "Whole program devirtualization" , "wholeprogramdevirt", &WholeProgramDevirt::ID, PassInfo ::NormalCtor_t(callDefaultCtor<WholeProgramDevirt>), false , false); Registry.registerPass(*PI, true); return PI; } static llvm::once_flag InitializeWholeProgramDevirtPassFlag; void llvm ::initializeWholeProgramDevirtPass(PassRegistry &Registry ) { llvm::call_once(InitializeWholeProgramDevirtPassFlag, initializeWholeProgramDevirtPassOnce , std::ref(Registry)); } | ||||||||
735 | "Whole program devirtualization", false, false)PassInfo *PI = new PassInfo( "Whole program devirtualization" , "wholeprogramdevirt", &WholeProgramDevirt::ID, PassInfo ::NormalCtor_t(callDefaultCtor<WholeProgramDevirt>), false , false); Registry.registerPass(*PI, true); return PI; } static llvm::once_flag InitializeWholeProgramDevirtPassFlag; void llvm ::initializeWholeProgramDevirtPass(PassRegistry &Registry ) { llvm::call_once(InitializeWholeProgramDevirtPassFlag, initializeWholeProgramDevirtPassOnce , std::ref(Registry)); } | ||||||||
736 | char WholeProgramDevirt::ID = 0; | ||||||||
737 | |||||||||
738 | ModulePass * | ||||||||
739 | llvm::createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary, | ||||||||
740 | const ModuleSummaryIndex *ImportSummary) { | ||||||||
741 | return new WholeProgramDevirt(ExportSummary, ImportSummary); | ||||||||
742 | } | ||||||||
743 | |||||||||
744 | PreservedAnalyses WholeProgramDevirtPass::run(Module &M, | ||||||||
745 | ModuleAnalysisManager &AM) { | ||||||||
746 | auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); | ||||||||
747 | auto AARGetter = [&](Function &F) -> AAResults & { | ||||||||
748 | return FAM.getResult<AAManager>(F); | ||||||||
749 | }; | ||||||||
750 | auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & { | ||||||||
751 | return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F); | ||||||||
752 | }; | ||||||||
753 | auto LookupDomTree = [&FAM](Function &F) -> DominatorTree & { | ||||||||
754 | return FAM.getResult<DominatorTreeAnalysis>(F); | ||||||||
755 | }; | ||||||||
756 | if (UseCommandLine) { | ||||||||
757 | if (DevirtModule::runForTesting(M, AARGetter, OREGetter, LookupDomTree)) | ||||||||
758 | return PreservedAnalyses::all(); | ||||||||
759 | return PreservedAnalyses::none(); | ||||||||
760 | } | ||||||||
761 | if (!DevirtModule(M, AARGetter, OREGetter, LookupDomTree, ExportSummary, | ||||||||
762 | ImportSummary) | ||||||||
763 | .run()) | ||||||||
764 | return PreservedAnalyses::all(); | ||||||||
765 | return PreservedAnalyses::none(); | ||||||||
766 | } | ||||||||
767 | |||||||||
768 | // Enable whole program visibility if enabled by client (e.g. linker) or | ||||||||
769 | // internal option, and not force disabled. | ||||||||
770 | static bool hasWholeProgramVisibility(bool WholeProgramVisibilityEnabledInLTO) { | ||||||||
771 | return (WholeProgramVisibilityEnabledInLTO || WholeProgramVisibility) && | ||||||||
772 | !DisableWholeProgramVisibility; | ||||||||
773 | } | ||||||||
774 | |||||||||
775 | namespace llvm { | ||||||||
776 | |||||||||
777 | /// If whole program visibility asserted, then upgrade all public vcall | ||||||||
778 | /// visibility metadata on vtable definitions to linkage unit visibility in | ||||||||
779 | /// Module IR (for regular or hybrid LTO). | ||||||||
780 | void updateVCallVisibilityInModule(Module &M, | ||||||||
781 | bool WholeProgramVisibilityEnabledInLTO) { | ||||||||
782 | if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO)) | ||||||||
783 | return; | ||||||||
784 | for (GlobalVariable &GV : M.globals()) | ||||||||
785 | // Add linkage unit visibility to any variable with type metadata, which are | ||||||||
786 | // the vtable definitions. We won't have an existing vcall_visibility | ||||||||
787 | // metadata on vtable definitions with public visibility. | ||||||||
788 | if (GV.hasMetadata(LLVMContext::MD_type) && | ||||||||
789 | GV.getVCallVisibility() == GlobalObject::VCallVisibilityPublic) | ||||||||
790 | GV.setVCallVisibilityMetadata(GlobalObject::VCallVisibilityLinkageUnit); | ||||||||
791 | } | ||||||||
792 | |||||||||
793 | /// If whole program visibility asserted, then upgrade all public vcall | ||||||||
794 | /// visibility metadata on vtable definition summaries to linkage unit | ||||||||
795 | /// visibility in Module summary index (for ThinLTO). | ||||||||
796 | void updateVCallVisibilityInIndex(ModuleSummaryIndex &Index, | ||||||||
797 | bool WholeProgramVisibilityEnabledInLTO) { | ||||||||
798 | if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO)) | ||||||||
799 | return; | ||||||||
800 | for (auto &P : Index) { | ||||||||
801 | for (auto &S : P.second.SummaryList) { | ||||||||
802 | auto *GVar = dyn_cast<GlobalVarSummary>(S.get()); | ||||||||
803 | if (!GVar || GVar->vTableFuncs().empty() || | ||||||||
804 | GVar->getVCallVisibility() != GlobalObject::VCallVisibilityPublic) | ||||||||
805 | continue; | ||||||||
806 | GVar->setVCallVisibility(GlobalObject::VCallVisibilityLinkageUnit); | ||||||||
807 | } | ||||||||
808 | } | ||||||||
809 | } | ||||||||
810 | |||||||||
811 | void runWholeProgramDevirtOnIndex( | ||||||||
812 | ModuleSummaryIndex &Summary, std::set<GlobalValue::GUID> &ExportedGUIDs, | ||||||||
813 | std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) { | ||||||||
814 | DevirtIndex(Summary, ExportedGUIDs, LocalWPDTargetsMap).run(); | ||||||||
815 | } | ||||||||
816 | |||||||||
817 | void updateIndexWPDForExports( | ||||||||
818 | ModuleSummaryIndex &Summary, | ||||||||
819 | function_ref<bool(StringRef, ValueInfo)> isExported, | ||||||||
820 | std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) { | ||||||||
821 | for (auto &T : LocalWPDTargetsMap) { | ||||||||
822 | auto &VI = T.first; | ||||||||
823 | // This was enforced earlier during trySingleImplDevirt. | ||||||||
824 | assert(VI.getSummaryList().size() == 1 &&((VI.getSummaryList().size() == 1 && "Devirt of local target has more than one copy" ) ? static_cast<void> (0) : __assert_fail ("VI.getSummaryList().size() == 1 && \"Devirt of local target has more than one copy\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp" , 825, __PRETTY_FUNCTION__)) | ||||||||
825 | "Devirt of local target has more than one copy")((VI.getSummaryList().size() == 1 && "Devirt of local target has more than one copy" ) ? static_cast<void> (0) : __assert_fail ("VI.getSummaryList().size() == 1 && \"Devirt of local target has more than one copy\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp" , 825, __PRETTY_FUNCTION__)); | ||||||||
826 | auto &S = VI.getSummaryList()[0]; | ||||||||
827 | if (!isExported(S->modulePath(), VI)) | ||||||||
828 | continue; | ||||||||
829 | |||||||||
830 | // It's been exported by a cross module import. | ||||||||
831 | for (auto &SlotSummary : T.second) { | ||||||||
832 | auto *TIdSum = Summary.getTypeIdSummary(SlotSummary.TypeID); | ||||||||
833 | assert(TIdSum)((TIdSum) ? static_cast<void> (0) : __assert_fail ("TIdSum" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp" , 833, __PRETTY_FUNCTION__)); | ||||||||
834 | auto WPDRes = TIdSum->WPDRes.find(SlotSummary.ByteOffset); | ||||||||
835 | assert(WPDRes != TIdSum->WPDRes.end())((WPDRes != TIdSum->WPDRes.end()) ? static_cast<void> (0) : __assert_fail ("WPDRes != TIdSum->WPDRes.end()", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp" , 835, __PRETTY_FUNCTION__)); | ||||||||
836 | WPDRes->second.SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal( | ||||||||
837 | WPDRes->second.SingleImplName, | ||||||||
838 | Summary.getModuleHash(S->modulePath())); | ||||||||
839 | } | ||||||||
840 | } | ||||||||
841 | } | ||||||||
842 | |||||||||
843 | } // end namespace llvm | ||||||||
844 | |||||||||
845 | static Error checkCombinedSummaryForTesting(ModuleSummaryIndex *Summary) { | ||||||||
846 | // Check that summary index contains regular LTO module when performing | ||||||||
847 | // export to prevent occasional use of index from pure ThinLTO compilation | ||||||||
848 | // (-fno-split-lto-module). This kind of summary index is passed to | ||||||||
849 | // DevirtIndex::run, not to DevirtModule::run used by opt/runForTesting. | ||||||||
850 | const auto &ModPaths = Summary->modulePaths(); | ||||||||
851 | if (ClSummaryAction != PassSummaryAction::Import && | ||||||||
852 | ModPaths.find(ModuleSummaryIndex::getRegularLTOModuleName()) == | ||||||||
853 | ModPaths.end()) | ||||||||
854 | return createStringError( | ||||||||
855 | errc::invalid_argument, | ||||||||
856 | "combined summary should contain Regular LTO module"); | ||||||||
857 | return ErrorSuccess(); | ||||||||
858 | } | ||||||||
859 | |||||||||
860 | bool DevirtModule::runForTesting( | ||||||||
861 | Module &M, function_ref<AAResults &(Function &)> AARGetter, | ||||||||
862 | function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, | ||||||||
863 | function_ref<DominatorTree &(Function &)> LookupDomTree) { | ||||||||
864 | std::unique_ptr<ModuleSummaryIndex> Summary = | ||||||||
865 | std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); | ||||||||
866 | |||||||||
867 | // Handle the command-line summary arguments. This code is for testing | ||||||||
868 | // purposes only, so we handle errors directly. | ||||||||
869 | if (!ClReadSummary.empty()) { | ||||||||
870 | ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary + | ||||||||
871 | ": "); | ||||||||
872 | auto ReadSummaryFile = | ||||||||
873 | ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary))); | ||||||||
874 | if (Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = | ||||||||
875 | getModuleSummaryIndex(*ReadSummaryFile)) { | ||||||||
876 | Summary = std::move(*SummaryOrErr); | ||||||||
877 | ExitOnErr(checkCombinedSummaryForTesting(Summary.get())); | ||||||||
878 | } else { | ||||||||
879 | // Try YAML if we've failed with bitcode. | ||||||||
880 | consumeError(SummaryOrErr.takeError()); | ||||||||
881 | yaml::Input In(ReadSummaryFile->getBuffer()); | ||||||||
882 | In >> *Summary; | ||||||||
883 | ExitOnErr(errorCodeToError(In.error())); | ||||||||
884 | } | ||||||||
885 | } | ||||||||
886 | |||||||||
887 | bool Changed = | ||||||||
888 | DevirtModule(M, AARGetter, OREGetter, LookupDomTree, | ||||||||
889 | ClSummaryAction == PassSummaryAction::Export ? Summary.get() | ||||||||
890 | : nullptr, | ||||||||
891 | ClSummaryAction == PassSummaryAction::Import ? Summary.get() | ||||||||
892 | : nullptr) | ||||||||
893 | .run(); | ||||||||
894 | |||||||||
895 | if (!ClWriteSummary.empty()) { | ||||||||
896 | ExitOnError ExitOnErr( | ||||||||
897 | "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": "); | ||||||||
898 | std::error_code EC; | ||||||||
899 | if (StringRef(ClWriteSummary).endswith(".bc")) { | ||||||||
900 | raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_None); | ||||||||
901 | ExitOnErr(errorCodeToError(EC)); | ||||||||
902 | WriteIndexToFile(*Summary, OS); | ||||||||
903 | } else { | ||||||||
904 | raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_Text); | ||||||||
905 | ExitOnErr(errorCodeToError(EC)); | ||||||||
906 | yaml::Output Out(OS); | ||||||||
907 | Out << *Summary; | ||||||||
908 | } | ||||||||
909 | } | ||||||||
910 | |||||||||
911 | return Changed; | ||||||||
912 | } | ||||||||
913 | |||||||||
914 | void DevirtModule::buildTypeIdentifierMap( | ||||||||
915 | std::vector<VTableBits> &Bits, | ||||||||
916 | DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) { | ||||||||
917 | DenseMap<GlobalVariable *, VTableBits *> GVToBits; | ||||||||
918 | Bits.reserve(M.getGlobalList().size()); | ||||||||
919 | SmallVector<MDNode *, 2> Types; | ||||||||
920 | for (GlobalVariable &GV : M.globals()) { | ||||||||
921 | Types.clear(); | ||||||||
922 | GV.getMetadata(LLVMContext::MD_type, Types); | ||||||||
923 | if (GV.isDeclaration() || Types.empty()) | ||||||||
924 | continue; | ||||||||
925 | |||||||||
926 | VTableBits *&BitsPtr = GVToBits[&GV]; | ||||||||
927 | if (!BitsPtr) { | ||||||||
928 | Bits.emplace_back(); | ||||||||
929 | Bits.back().GV = &GV; | ||||||||
930 | Bits.back().ObjectSize = | ||||||||
931 | M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType()); | ||||||||
932 | BitsPtr = &Bits.back(); | ||||||||
933 | } | ||||||||
934 | |||||||||
935 | for (MDNode *Type : Types) { | ||||||||
936 | auto TypeID = Type->getOperand(1).get(); | ||||||||
937 | |||||||||
938 | uint64_t Offset = | ||||||||
939 | cast<ConstantInt>( | ||||||||
940 | cast<ConstantAsMetadata>(Type->getOperand(0))->getValue()) | ||||||||
941 | ->getZExtValue(); | ||||||||
942 | |||||||||
943 | TypeIdMap[TypeID].insert({BitsPtr, Offset}); | ||||||||
944 | } | ||||||||
945 | } | ||||||||
946 | } | ||||||||
947 | |||||||||
948 | bool DevirtModule::tryFindVirtualCallTargets( | ||||||||
949 | std::vector<VirtualCallTarget> &TargetsForSlot, | ||||||||
950 | const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) { | ||||||||
951 | for (const TypeMemberInfo &TM : TypeMemberInfos) { | ||||||||
952 | if (!TM.Bits->GV->isConstant()) | ||||||||
953 | return false; | ||||||||
954 | |||||||||
955 | // We cannot perform whole program devirtualization analysis on a vtable | ||||||||
956 | // with public LTO visibility. | ||||||||
957 | if (TM.Bits->GV->getVCallVisibility() == | ||||||||
958 | GlobalObject::VCallVisibilityPublic) | ||||||||
959 | return false; | ||||||||
960 | |||||||||
961 | Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(), | ||||||||
962 | TM.Offset + ByteOffset, M); | ||||||||
963 | if (!Ptr) | ||||||||
964 | return false; | ||||||||
965 | |||||||||
966 | auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts()); | ||||||||
967 | if (!Fn) | ||||||||
968 | return false; | ||||||||
969 | |||||||||
970 | if (FunctionsToSkip.match(Fn->getName())) | ||||||||
971 | return false; | ||||||||
972 | |||||||||
973 | // We can disregard __cxa_pure_virtual as a possible call target, as | ||||||||
974 | // calls to pure virtuals are UB. | ||||||||
975 | if (Fn->getName() == "__cxa_pure_virtual") | ||||||||
976 | continue; | ||||||||
977 | |||||||||
978 | TargetsForSlot.push_back({Fn, &TM}); | ||||||||
979 | } | ||||||||
980 | |||||||||
981 | // Give up if we couldn't find any targets. | ||||||||
982 | return !TargetsForSlot.empty(); | ||||||||
983 | } | ||||||||
984 | |||||||||
985 | bool DevirtIndex::tryFindVirtualCallTargets( | ||||||||
986 | std::vector<ValueInfo> &TargetsForSlot, const TypeIdCompatibleVtableInfo TIdInfo, | ||||||||
987 | uint64_t ByteOffset) { | ||||||||
988 | for (const TypeIdOffsetVtableInfo &P : TIdInfo) { | ||||||||
989 | // Find the first non-available_externally linkage vtable initializer. | ||||||||
990 | // We can have multiple available_externally, linkonce_odr and weak_odr | ||||||||
991 | // vtable initializers, however we want to skip available_externally as they | ||||||||
992 | // do not have type metadata attached, and therefore the summary will not | ||||||||
993 | // contain any vtable functions. We can also have multiple external | ||||||||
994 | // vtable initializers in the case of comdats, which we cannot check here. | ||||||||
995 | // The linker should give an error in this case. | ||||||||
996 | // | ||||||||
997 | // Also, handle the case of same-named local Vtables with the same path | ||||||||
998 | // and therefore the same GUID. This can happen if there isn't enough | ||||||||
999 | // distinguishing path when compiling the source file. In that case we | ||||||||
1000 | // conservatively return false early. | ||||||||
1001 | const GlobalVarSummary *VS = nullptr; | ||||||||
1002 | bool LocalFound = false; | ||||||||
1003 | for (auto &S : P.VTableVI.getSummaryList()) { | ||||||||
1004 | if (GlobalValue::isLocalLinkage(S->linkage())) { | ||||||||
1005 | if (LocalFound) | ||||||||
1006 | return false; | ||||||||
1007 | LocalFound = true; | ||||||||
1008 | } | ||||||||
1009 | if (!GlobalValue::isAvailableExternallyLinkage(S->linkage())) { | ||||||||
1010 | VS = cast<GlobalVarSummary>(S->getBaseObject()); | ||||||||
1011 | // We cannot perform whole program devirtualization analysis on a vtable | ||||||||
1012 | // with public LTO visibility. | ||||||||
1013 | if (VS->getVCallVisibility() == GlobalObject::VCallVisibilityPublic) | ||||||||
1014 | return false; | ||||||||
1015 | } | ||||||||
1016 | } | ||||||||
1017 | if (!VS->isLive()) | ||||||||
1018 | continue; | ||||||||
1019 | for (auto VTP : VS->vTableFuncs()) { | ||||||||
1020 | if (VTP.VTableOffset != P.AddressPointOffset + ByteOffset) | ||||||||
1021 | continue; | ||||||||
1022 | |||||||||
1023 | TargetsForSlot.push_back(VTP.FuncVI); | ||||||||
1024 | } | ||||||||
1025 | } | ||||||||
1026 | |||||||||
1027 | // Give up if we couldn't find any targets. | ||||||||
1028 | return !TargetsForSlot.empty(); | ||||||||
1029 | } | ||||||||
1030 | |||||||||
1031 | void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo, | ||||||||
1032 | Constant *TheFn, bool &IsExported) { | ||||||||
1033 | // Don't devirtualize function if we're told to skip it | ||||||||
1034 | // in -wholeprogramdevirt-skip. | ||||||||
1035 | if (FunctionsToSkip.match(TheFn->stripPointerCasts()->getName())) | ||||||||
1036 | return; | ||||||||
1037 | auto Apply = [&](CallSiteInfo &CSInfo) { | ||||||||
1038 | for (auto &&VCallSite : CSInfo.CallSites) { | ||||||||
1039 | if (RemarksEnabled) | ||||||||
1040 | VCallSite.emitRemark("single-impl", | ||||||||
1041 | TheFn->stripPointerCasts()->getName(), OREGetter); | ||||||||
1042 | VCallSite.CB.setCalledOperand(ConstantExpr::getBitCast( | ||||||||
1043 | TheFn, VCallSite.CB.getCalledOperand()->getType())); | ||||||||
1044 | // This use is no longer unsafe. | ||||||||
1045 | if (VCallSite.NumUnsafeUses) | ||||||||
1046 | --*VCallSite.NumUnsafeUses; | ||||||||
1047 | } | ||||||||
1048 | if (CSInfo.isExported()) | ||||||||
1049 | IsExported = true; | ||||||||
1050 | CSInfo.markDevirt(); | ||||||||
1051 | }; | ||||||||
1052 | Apply(SlotInfo.CSInfo); | ||||||||
1053 | for (auto &P : SlotInfo.ConstCSInfo) | ||||||||
1054 | Apply(P.second); | ||||||||
1055 | } | ||||||||
1056 | |||||||||
1057 | static bool AddCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee) { | ||||||||
1058 | // We can't add calls if we haven't seen a definition | ||||||||
1059 | if (Callee.getSummaryList().empty()) | ||||||||
1060 | return false; | ||||||||
1061 | |||||||||
1062 | // Insert calls into the summary index so that the devirtualized targets | ||||||||
1063 | // are eligible for import. | ||||||||
1064 | // FIXME: Annotate type tests with hotness. For now, mark these as hot | ||||||||
1065 | // to better ensure we have the opportunity to inline them. | ||||||||
1066 | bool IsExported = false; | ||||||||
1067 | auto &S = Callee.getSummaryList()[0]; | ||||||||
1068 | CalleeInfo CI(CalleeInfo::HotnessType::Hot, /* RelBF = */ 0); | ||||||||
1069 | auto AddCalls = [&](CallSiteInfo &CSInfo) { | ||||||||
1070 | for (auto *FS : CSInfo.SummaryTypeCheckedLoadUsers) { | ||||||||
1071 | FS->addCall({Callee, CI}); | ||||||||
1072 | IsExported |= S->modulePath() != FS->modulePath(); | ||||||||
1073 | } | ||||||||
1074 | for (auto *FS : CSInfo.SummaryTypeTestAssumeUsers) { | ||||||||
1075 | FS->addCall({Callee, CI}); | ||||||||
1076 | IsExported |= S->modulePath() != FS->modulePath(); | ||||||||
1077 | } | ||||||||
1078 | }; | ||||||||
1079 | AddCalls(SlotInfo.CSInfo); | ||||||||
1080 | for (auto &P : SlotInfo.ConstCSInfo) | ||||||||
1081 | AddCalls(P.second); | ||||||||
1082 | return IsExported; | ||||||||
1083 | } | ||||||||
1084 | |||||||||
1085 | bool DevirtModule::trySingleImplDevirt( | ||||||||
1086 | ModuleSummaryIndex *ExportSummary, | ||||||||
1087 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo, | ||||||||
1088 | WholeProgramDevirtResolution *Res) { | ||||||||
1089 | // See if the program contains a single implementation of this virtual | ||||||||
1090 | // function. | ||||||||
1091 | Function *TheFn = TargetsForSlot[0].Fn; | ||||||||
1092 | for (auto &&Target : TargetsForSlot) | ||||||||
1093 | if (TheFn != Target.Fn) | ||||||||
1094 | return false; | ||||||||
1095 | |||||||||
1096 | // If so, update each call site to call that implementation directly. | ||||||||
1097 | if (RemarksEnabled) | ||||||||
1098 | TargetsForSlot[0].WasDevirt = true; | ||||||||
1099 | |||||||||
1100 | bool IsExported = false; | ||||||||
1101 | applySingleImplDevirt(SlotInfo, TheFn, IsExported); | ||||||||
1102 | if (!IsExported
| ||||||||
1103 | return false; | ||||||||
1104 | |||||||||
1105 | // If the only implementation has local linkage, we must promote to external | ||||||||
1106 | // to make it visible to thin LTO objects. We can only get here during the | ||||||||
1107 | // ThinLTO export phase. | ||||||||
1108 | if (TheFn->hasLocalLinkage()) { | ||||||||
1109 | std::string NewName = (TheFn->getName() + "$merged").str(); | ||||||||
1110 | |||||||||
1111 | // Since we are renaming the function, any comdats with the same name must | ||||||||
1112 | // also be renamed. This is required when targeting COFF, as the comdat name | ||||||||
1113 | // must match one of the names of the symbols in the comdat. | ||||||||
1114 | if (Comdat *C = TheFn->getComdat()) { | ||||||||
1115 | if (C->getName() == TheFn->getName()) { | ||||||||
1116 | Comdat *NewC = M.getOrInsertComdat(NewName); | ||||||||
1117 | NewC->setSelectionKind(C->getSelectionKind()); | ||||||||
1118 | for (GlobalObject &GO : M.global_objects()) | ||||||||
1119 | if (GO.getComdat() == C) | ||||||||
1120 | GO.setComdat(NewC); | ||||||||
1121 | } | ||||||||
1122 | } | ||||||||
1123 | |||||||||
1124 | TheFn->setLinkage(GlobalValue::ExternalLinkage); | ||||||||
1125 | TheFn->setVisibility(GlobalValue::HiddenVisibility); | ||||||||
1126 | TheFn->setName(NewName); | ||||||||
1127 | } | ||||||||
1128 | if (ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFn->getGUID())) | ||||||||
1129 | // Any needed promotion of 'TheFn' has already been done during | ||||||||
1130 | // LTO unit split, so we can ignore return value of AddCalls. | ||||||||
1131 | AddCalls(SlotInfo, TheFnVI); | ||||||||
1132 | |||||||||
1133 | Res->TheKind = WholeProgramDevirtResolution::SingleImpl; | ||||||||
1134 | Res->SingleImplName = std::string(TheFn->getName()); | ||||||||
1135 | |||||||||
1136 | return true; | ||||||||
1137 | } | ||||||||
1138 | |||||||||
1139 | bool DevirtIndex::trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot, | ||||||||
1140 | VTableSlotSummary &SlotSummary, | ||||||||
1141 | VTableSlotInfo &SlotInfo, | ||||||||
1142 | WholeProgramDevirtResolution *Res, | ||||||||
1143 | std::set<ValueInfo> &DevirtTargets) { | ||||||||
1144 | // See if the program contains a single implementation of this virtual | ||||||||
1145 | // function. | ||||||||
1146 | auto TheFn = TargetsForSlot[0]; | ||||||||
1147 | for (auto &&Target : TargetsForSlot) | ||||||||
1148 | if (TheFn != Target) | ||||||||
1149 | return false; | ||||||||
1150 | |||||||||
1151 | // Don't devirtualize if we don't have target definition. | ||||||||
1152 | auto Size = TheFn.getSummaryList().size(); | ||||||||
1153 | if (!Size) | ||||||||
1154 | return false; | ||||||||
1155 | |||||||||
1156 | // Don't devirtualize function if we're told to skip it | ||||||||
1157 | // in -wholeprogramdevirt-skip. | ||||||||
1158 | if (FunctionsToSkip.match(TheFn.name())) | ||||||||
1159 | return false; | ||||||||
1160 | |||||||||
1161 | // If the summary list contains multiple summaries where at least one is | ||||||||
1162 | // a local, give up, as we won't know which (possibly promoted) name to use. | ||||||||
1163 | for (auto &S : TheFn.getSummaryList()) | ||||||||
1164 | if (GlobalValue::isLocalLinkage(S->linkage()) && Size > 1) | ||||||||
1165 | return false; | ||||||||
1166 | |||||||||
1167 | // Collect functions devirtualized at least for one call site for stats. | ||||||||
1168 | if (PrintSummaryDevirt) | ||||||||
1169 | DevirtTargets.insert(TheFn); | ||||||||
1170 | |||||||||
1171 | auto &S = TheFn.getSummaryList()[0]; | ||||||||
1172 | bool IsExported = AddCalls(SlotInfo, TheFn); | ||||||||
1173 | if (IsExported) | ||||||||
1174 | ExportedGUIDs.insert(TheFn.getGUID()); | ||||||||
1175 | |||||||||
1176 | // Record in summary for use in devirtualization during the ThinLTO import | ||||||||
1177 | // step. | ||||||||
1178 | Res->TheKind = WholeProgramDevirtResolution::SingleImpl; | ||||||||
1179 | if (GlobalValue::isLocalLinkage(S->linkage())) { | ||||||||
1180 | if (IsExported) | ||||||||
1181 | // If target is a local function and we are exporting it by | ||||||||
1182 | // devirtualizing a call in another module, we need to record the | ||||||||
1183 | // promoted name. | ||||||||
1184 | Res->SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal( | ||||||||
1185 | TheFn.name(), ExportSummary.getModuleHash(S->modulePath())); | ||||||||
1186 | else { | ||||||||
1187 | LocalWPDTargetsMap[TheFn].push_back(SlotSummary); | ||||||||
1188 | Res->SingleImplName = std::string(TheFn.name()); | ||||||||
1189 | } | ||||||||
1190 | } else | ||||||||
1191 | Res->SingleImplName = std::string(TheFn.name()); | ||||||||
1192 | |||||||||
1193 | // Name will be empty if this thin link driven off of serialized combined | ||||||||
1194 | // index (e.g. llvm-lto). However, WPD is not supported/invoked for the | ||||||||
1195 | // legacy LTO API anyway. | ||||||||
1196 | assert(!Res->SingleImplName.empty())((!Res->SingleImplName.empty()) ? static_cast<void> ( 0) : __assert_fail ("!Res->SingleImplName.empty()", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp" , 1196, __PRETTY_FUNCTION__)); | ||||||||
1197 | |||||||||
1198 | return true; | ||||||||
1199 | } | ||||||||
1200 | |||||||||
1201 | void DevirtModule::tryICallBranchFunnel( | ||||||||
1202 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo, | ||||||||
1203 | WholeProgramDevirtResolution *Res, VTableSlot Slot) { | ||||||||
1204 | Triple T(M.getTargetTriple()); | ||||||||
1205 | if (T.getArch() != Triple::x86_64) | ||||||||
1206 | return; | ||||||||
1207 | |||||||||
1208 | if (TargetsForSlot.size() > ClThreshold) | ||||||||
1209 | return; | ||||||||
1210 | |||||||||
1211 | bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted; | ||||||||
1212 | if (!HasNonDevirt
| ||||||||
1213 | for (auto &P : SlotInfo.ConstCSInfo) | ||||||||
1214 | if (!P.second.AllCallSitesDevirted) { | ||||||||
1215 | HasNonDevirt = true; | ||||||||
1216 | break; | ||||||||
1217 | } | ||||||||
1218 | |||||||||
1219 | if (!HasNonDevirt
| ||||||||
1220 | return; | ||||||||
1221 | |||||||||
1222 | FunctionType *FT = | ||||||||
1223 | FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true); | ||||||||
1224 | Function *JT; | ||||||||
1225 | if (isa<MDString>(Slot.TypeID)) { | ||||||||
1226 | JT = Function::Create(FT, Function::ExternalLinkage, | ||||||||
1227 | M.getDataLayout().getProgramAddressSpace(), | ||||||||
1228 | getGlobalName(Slot, {}, "branch_funnel"), &M); | ||||||||
1229 | JT->setVisibility(GlobalValue::HiddenVisibility); | ||||||||
1230 | } else { | ||||||||
1231 | JT = Function::Create(FT, Function::InternalLinkage, | ||||||||
1232 | M.getDataLayout().getProgramAddressSpace(), | ||||||||
1233 | "branch_funnel", &M); | ||||||||
1234 | } | ||||||||
1235 | JT->addAttribute(1, Attribute::Nest); | ||||||||
1236 | |||||||||
1237 | std::vector<Value *> JTArgs; | ||||||||
1238 | JTArgs.push_back(JT->arg_begin()); | ||||||||
1239 | for (auto &T : TargetsForSlot) { | ||||||||
1240 | JTArgs.push_back(getMemberAddr(T.TM)); | ||||||||
1241 | JTArgs.push_back(T.Fn); | ||||||||
1242 | } | ||||||||
1243 | |||||||||
1244 | BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr); | ||||||||
1245 | Function *Intr = | ||||||||
1246 | Intrinsic::getDeclaration(&M, llvm::Intrinsic::icall_branch_funnel, {}); | ||||||||
1247 | |||||||||
1248 | auto *CI = CallInst::Create(Intr, JTArgs, "", BB); | ||||||||
1249 | CI->setTailCallKind(CallInst::TCK_MustTail); | ||||||||
1250 | ReturnInst::Create(M.getContext(), nullptr, BB); | ||||||||
1251 | |||||||||
1252 | bool IsExported = false; | ||||||||
1253 | applyICallBranchFunnel(SlotInfo, JT, IsExported); | ||||||||
1254 | if (IsExported
| ||||||||
1255 | Res->TheKind = WholeProgramDevirtResolution::BranchFunnel; | ||||||||
| |||||||||
1256 | } | ||||||||
1257 | |||||||||
1258 | void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo, | ||||||||
1259 | Constant *JT, bool &IsExported) { | ||||||||
1260 | auto Apply = [&](CallSiteInfo &CSInfo) { | ||||||||
1261 | if (CSInfo.isExported()) | ||||||||
1262 | IsExported = true; | ||||||||
1263 | if (CSInfo.AllCallSitesDevirted) | ||||||||
1264 | return; | ||||||||
1265 | for (auto &&VCallSite : CSInfo.CallSites) { | ||||||||
1266 | CallBase &CB = VCallSite.CB; | ||||||||
1267 | |||||||||
1268 | // Jump tables are only profitable if the retpoline mitigation is enabled. | ||||||||
1269 | Attribute FSAttr = CB.getCaller()->getFnAttribute("target-features"); | ||||||||
1270 | if (!FSAttr.isValid() || | ||||||||
1271 | !FSAttr.getValueAsString().contains("+retpoline")) | ||||||||
1272 | continue; | ||||||||
1273 | |||||||||
1274 | if (RemarksEnabled) | ||||||||
1275 | VCallSite.emitRemark("branch-funnel", | ||||||||
1276 | JT->stripPointerCasts()->getName(), OREGetter); | ||||||||
1277 | |||||||||
1278 | // Pass the address of the vtable in the nest register, which is r10 on | ||||||||
1279 | // x86_64. | ||||||||
1280 | std::vector<Type *> NewArgs; | ||||||||
1281 | NewArgs.push_back(Int8PtrTy); | ||||||||
1282 | for (Type *T : CB.getFunctionType()->params()) | ||||||||
1283 | NewArgs.push_back(T); | ||||||||
1284 | FunctionType *NewFT = | ||||||||
1285 | FunctionType::get(CB.getFunctionType()->getReturnType(), NewArgs, | ||||||||
1286 | CB.getFunctionType()->isVarArg()); | ||||||||
1287 | PointerType *NewFTPtr = PointerType::getUnqual(NewFT); | ||||||||
1288 | |||||||||
1289 | IRBuilder<> IRB(&CB); | ||||||||
1290 | std::vector<Value *> Args; | ||||||||
1291 | Args.push_back(IRB.CreateBitCast(VCallSite.VTable, Int8PtrTy)); | ||||||||
1292 | llvm::append_range(Args, CB.args()); | ||||||||
1293 | |||||||||
1294 | CallBase *NewCS = nullptr; | ||||||||
1295 | if (isa<CallInst>(CB)) | ||||||||
1296 | NewCS = IRB.CreateCall(NewFT, IRB.CreateBitCast(JT, NewFTPtr), Args); | ||||||||
1297 | else | ||||||||
1298 | NewCS = IRB.CreateInvoke(NewFT, IRB.CreateBitCast(JT, NewFTPtr), | ||||||||
1299 | cast<InvokeInst>(CB).getNormalDest(), | ||||||||
1300 | cast<InvokeInst>(CB).getUnwindDest(), Args); | ||||||||
1301 | NewCS->setCallingConv(CB.getCallingConv()); | ||||||||
1302 | |||||||||
1303 | AttributeList Attrs = CB.getAttributes(); | ||||||||
1304 | std::vector<AttributeSet> NewArgAttrs; | ||||||||
1305 | NewArgAttrs.push_back(AttributeSet::get( | ||||||||
1306 | M.getContext(), ArrayRef<Attribute>{Attribute::get( | ||||||||
1307 | M.getContext(), Attribute::Nest)})); | ||||||||
1308 | for (unsigned I = 0; I + 2 < Attrs.getNumAttrSets(); ++I) | ||||||||
1309 | NewArgAttrs.push_back(Attrs.getParamAttributes(I)); | ||||||||
1310 | NewCS->setAttributes( | ||||||||
1311 | AttributeList::get(M.getContext(), Attrs.getFnAttributes(), | ||||||||
1312 | Attrs.getRetAttributes(), NewArgAttrs)); | ||||||||
1313 | |||||||||
1314 | CB.replaceAllUsesWith(NewCS); | ||||||||
1315 | CB.eraseFromParent(); | ||||||||
1316 | |||||||||
1317 | // This use is no longer unsafe. | ||||||||
1318 | if (VCallSite.NumUnsafeUses) | ||||||||
1319 | --*VCallSite.NumUnsafeUses; | ||||||||
1320 | } | ||||||||
1321 | // Don't mark as devirtualized because there may be callers compiled without | ||||||||
1322 | // retpoline mitigation, which would mean that they are lowered to | ||||||||
1323 | // llvm.type.test and therefore require an llvm.type.test resolution for the | ||||||||
1324 | // type identifier. | ||||||||
1325 | }; | ||||||||
1326 | Apply(SlotInfo.CSInfo); | ||||||||
1327 | for (auto &P : SlotInfo.ConstCSInfo) | ||||||||
1328 | Apply(P.second); | ||||||||
1329 | } | ||||||||
1330 | |||||||||
1331 | bool DevirtModule::tryEvaluateFunctionsWithArgs( | ||||||||
1332 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, | ||||||||
1333 | ArrayRef<uint64_t> Args) { | ||||||||
1334 | // Evaluate each function and store the result in each target's RetVal | ||||||||
1335 | // field. | ||||||||
1336 | for (VirtualCallTarget &Target : TargetsForSlot) { | ||||||||
1337 | if (Target.Fn->arg_size() != Args.size() + 1) | ||||||||
1338 | return false; | ||||||||
1339 | |||||||||
1340 | Evaluator Eval(M.getDataLayout(), nullptr); | ||||||||
1341 | SmallVector<Constant *, 2> EvalArgs; | ||||||||
1342 | EvalArgs.push_back( | ||||||||
1343 | Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0))); | ||||||||
1344 | for (unsigned I = 0; I != Args.size(); ++I) { | ||||||||
1345 | auto *ArgTy = dyn_cast<IntegerType>( | ||||||||
1346 | Target.Fn->getFunctionType()->getParamType(I + 1)); | ||||||||
1347 | if (!ArgTy) | ||||||||
1348 | return false; | ||||||||
1349 | EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I])); | ||||||||
1350 | } | ||||||||
1351 | |||||||||
1352 | Constant *RetVal; | ||||||||
1353 | if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) || | ||||||||
1354 | !isa<ConstantInt>(RetVal)) | ||||||||
1355 | return false; | ||||||||
1356 | Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue(); | ||||||||
1357 | } | ||||||||
1358 | return true; | ||||||||
1359 | } | ||||||||
1360 | |||||||||
1361 | void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, | ||||||||
1362 | uint64_t TheRetVal) { | ||||||||
1363 | for (auto Call : CSInfo.CallSites) | ||||||||
1364 | Call.replaceAndErase( | ||||||||
1365 | "uniform-ret-val", FnName, RemarksEnabled, OREGetter, | ||||||||
1366 | ConstantInt::get(cast<IntegerType>(Call.CB.getType()), TheRetVal)); | ||||||||
1367 | CSInfo.markDevirt(); | ||||||||
1368 | } | ||||||||
1369 | |||||||||
1370 | bool DevirtModule::tryUniformRetValOpt( | ||||||||
1371 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo, | ||||||||
1372 | WholeProgramDevirtResolution::ByArg *Res) { | ||||||||
1373 | // Uniform return value optimization. If all functions return the same | ||||||||
1374 | // constant, replace all calls with that constant. | ||||||||
1375 | uint64_t TheRetVal = TargetsForSlot[0].RetVal; | ||||||||
1376 | for (const VirtualCallTarget &Target : TargetsForSlot) | ||||||||
1377 | if (Target.RetVal != TheRetVal) | ||||||||
1378 | return false; | ||||||||
1379 | |||||||||
1380 | if (CSInfo.isExported()) { | ||||||||
1381 | Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; | ||||||||
1382 | Res->Info = TheRetVal; | ||||||||
1383 | } | ||||||||
1384 | |||||||||
1385 | applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal); | ||||||||
1386 | if (RemarksEnabled) | ||||||||
1387 | for (auto &&Target : TargetsForSlot) | ||||||||
1388 | Target.WasDevirt = true; | ||||||||
1389 | return true; | ||||||||
1390 | } | ||||||||
1391 | |||||||||
1392 | std::string DevirtModule::getGlobalName(VTableSlot Slot, | ||||||||
1393 | ArrayRef<uint64_t> Args, | ||||||||
1394 | StringRef Name) { | ||||||||
1395 | std::string FullName = "__typeid_"; | ||||||||
1396 | raw_string_ostream OS(FullName); | ||||||||
1397 | OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset; | ||||||||
1398 | for (uint64_t Arg : Args) | ||||||||
1399 | OS << '_' << Arg; | ||||||||
1400 | OS << '_' << Name; | ||||||||
1401 | return OS.str(); | ||||||||
1402 | } | ||||||||
1403 | |||||||||
1404 | bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() { | ||||||||
1405 | Triple T(M.getTargetTriple()); | ||||||||
1406 | return T.isX86() && T.getObjectFormat() == Triple::ELF; | ||||||||
1407 | } | ||||||||
1408 | |||||||||
1409 | void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, | ||||||||
1410 | StringRef Name, Constant *C) { | ||||||||
1411 | GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage, | ||||||||
1412 | getGlobalName(Slot, Args, Name), C, &M); | ||||||||
1413 | GA->setVisibility(GlobalValue::HiddenVisibility); | ||||||||
1414 | } | ||||||||
1415 | |||||||||
1416 | void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, | ||||||||
1417 | StringRef Name, uint32_t Const, | ||||||||
1418 | uint32_t &Storage) { | ||||||||
1419 | if (shouldExportConstantsAsAbsoluteSymbols()) { | ||||||||
1420 | exportGlobal( | ||||||||
1421 | Slot, Args, Name, | ||||||||
1422 | ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy)); | ||||||||
1423 | return; | ||||||||
1424 | } | ||||||||
1425 | |||||||||
1426 | Storage = Const; | ||||||||
1427 | } | ||||||||
1428 | |||||||||
1429 | Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, | ||||||||
1430 | StringRef Name) { | ||||||||
1431 | Constant *C = | ||||||||
1432 | M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Arr0Ty); | ||||||||
1433 | auto *GV = dyn_cast<GlobalVariable>(C); | ||||||||
1434 | if (GV) | ||||||||
1435 | GV->setVisibility(GlobalValue::HiddenVisibility); | ||||||||
1436 | return C; | ||||||||
1437 | } | ||||||||
1438 | |||||||||
1439 | Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, | ||||||||
1440 | StringRef Name, IntegerType *IntTy, | ||||||||
1441 | uint32_t Storage) { | ||||||||
1442 | if (!shouldExportConstantsAsAbsoluteSymbols()) | ||||||||
1443 | return ConstantInt::get(IntTy, Storage); | ||||||||
1444 | |||||||||
1445 | Constant *C = importGlobal(Slot, Args, Name); | ||||||||
1446 | auto *GV = cast<GlobalVariable>(C->stripPointerCasts()); | ||||||||
1447 | C = ConstantExpr::getPtrToInt(C, IntTy); | ||||||||
1448 | |||||||||
1449 | // We only need to set metadata if the global is newly created, in which | ||||||||
1450 | // case it would not have hidden visibility. | ||||||||
1451 | if (GV->hasMetadata(LLVMContext::MD_absolute_symbol)) | ||||||||
1452 | return C; | ||||||||
1453 | |||||||||
1454 | auto SetAbsRange = [&](uint64_t Min, uint64_t Max) { | ||||||||
1455 | auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min)); | ||||||||
1456 | auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max)); | ||||||||
1457 | GV->setMetadata(LLVMContext::MD_absolute_symbol, | ||||||||
1458 | MDNode::get(M.getContext(), {MinC, MaxC})); | ||||||||
1459 | }; | ||||||||
1460 | unsigned AbsWidth = IntTy->getBitWidth(); | ||||||||
1461 | if (AbsWidth == IntPtrTy->getBitWidth()) | ||||||||
1462 | SetAbsRange(~0ull, ~0ull); // Full set. | ||||||||
1463 | else | ||||||||
1464 | SetAbsRange(0, 1ull << AbsWidth); | ||||||||
1465 | return C; | ||||||||
1466 | } | ||||||||
1467 | |||||||||
1468 | void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, | ||||||||
1469 | bool IsOne, | ||||||||
1470 | Constant *UniqueMemberAddr) { | ||||||||
1471 | for (auto &&Call : CSInfo.CallSites) { | ||||||||
1472 | IRBuilder<> B(&Call.CB); | ||||||||
1473 | Value *Cmp = | ||||||||
1474 | B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, Call.VTable, | ||||||||
1475 | B.CreateBitCast(UniqueMemberAddr, Call.VTable->getType())); | ||||||||
1476 | Cmp = B.CreateZExt(Cmp, Call.CB.getType()); | ||||||||
1477 | Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter, | ||||||||
1478 | Cmp); | ||||||||
1479 | } | ||||||||
1480 | CSInfo.markDevirt(); | ||||||||
1481 | } | ||||||||
1482 | |||||||||
1483 | Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) { | ||||||||
1484 | Constant *C = ConstantExpr::getBitCast(M->Bits->GV, Int8PtrTy); | ||||||||
1485 | return ConstantExpr::getGetElementPtr(Int8Ty, C, | ||||||||
1486 | ConstantInt::get(Int64Ty, M->Offset)); | ||||||||
1487 | } | ||||||||
1488 | |||||||||
1489 | bool DevirtModule::tryUniqueRetValOpt( | ||||||||
1490 | unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot, | ||||||||
1491 | CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res, | ||||||||
1492 | VTableSlot Slot, ArrayRef<uint64_t> Args) { | ||||||||
1493 | // IsOne controls whether we look for a 0 or a 1. | ||||||||
1494 | auto tryUniqueRetValOptFor = [&](bool IsOne) { | ||||||||
1495 | const TypeMemberInfo *UniqueMember = nullptr; | ||||||||
1496 | for (const VirtualCallTarget &Target : TargetsForSlot) { | ||||||||
1497 | if (Target.RetVal == (IsOne ? 1 : 0)) { | ||||||||
1498 | if (UniqueMember) | ||||||||
1499 | return false; | ||||||||
1500 | UniqueMember = Target.TM; | ||||||||
1501 | } | ||||||||
1502 | } | ||||||||
1503 | |||||||||
1504 | // We should have found a unique member or bailed out by now. We already | ||||||||
1505 | // checked for a uniform return value in tryUniformRetValOpt. | ||||||||
1506 | assert(UniqueMember)((UniqueMember) ? static_cast<void> (0) : __assert_fail ("UniqueMember", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp" , 1506, __PRETTY_FUNCTION__)); | ||||||||
1507 | |||||||||
1508 | Constant *UniqueMemberAddr = getMemberAddr(UniqueMember); | ||||||||
1509 | if (CSInfo.isExported()) { | ||||||||
1510 | Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; | ||||||||
1511 | Res->Info = IsOne; | ||||||||
1512 | |||||||||
1513 | exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr); | ||||||||
1514 | } | ||||||||
1515 | |||||||||
1516 | // Replace each call with the comparison. | ||||||||
1517 | applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne, | ||||||||
1518 | UniqueMemberAddr); | ||||||||
1519 | |||||||||
1520 | // Update devirtualization statistics for targets. | ||||||||
1521 | if (RemarksEnabled) | ||||||||
1522 | for (auto &&Target : TargetsForSlot) | ||||||||
1523 | Target.WasDevirt = true; | ||||||||
1524 | |||||||||
1525 | return true; | ||||||||
1526 | }; | ||||||||
1527 | |||||||||
1528 | if (BitWidth == 1) { | ||||||||
1529 | if (tryUniqueRetValOptFor(true)) | ||||||||
1530 | return true; | ||||||||
1531 | if (tryUniqueRetValOptFor(false)) | ||||||||
1532 | return true; | ||||||||
1533 | } | ||||||||
1534 | return false; | ||||||||
1535 | } | ||||||||
1536 | |||||||||
1537 | void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, | ||||||||
1538 | Constant *Byte, Constant *Bit) { | ||||||||
1539 | for (auto Call : CSInfo.CallSites) { | ||||||||
1540 | auto *RetType = cast<IntegerType>(Call.CB.getType()); | ||||||||
1541 | IRBuilder<> B(&Call.CB); | ||||||||
1542 | Value *Addr = | ||||||||
1543 | B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte); | ||||||||
1544 | if (RetType->getBitWidth() == 1) { | ||||||||
1545 | Value *Bits = B.CreateLoad(Int8Ty, Addr); | ||||||||
1546 | Value *BitsAndBit = B.CreateAnd(Bits, Bit); | ||||||||
1547 | auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0)); | ||||||||
1548 | Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled, | ||||||||
1549 | OREGetter, IsBitSet); | ||||||||
1550 | } else { | ||||||||
1551 | Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo()); | ||||||||
1552 | Value *Val = B.CreateLoad(RetType, ValAddr); | ||||||||
1553 | Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, | ||||||||
1554 | OREGetter, Val); | ||||||||
1555 | } | ||||||||
1556 | } | ||||||||
1557 | CSInfo.markDevirt(); | ||||||||
1558 | } | ||||||||
1559 | |||||||||
1560 | bool DevirtModule::tryVirtualConstProp( | ||||||||
1561 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo, | ||||||||
1562 | WholeProgramDevirtResolution *Res, VTableSlot Slot) { | ||||||||
1563 | // This only works if the function returns an integer. | ||||||||
1564 | auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType()); | ||||||||
1565 | if (!RetType
| ||||||||
1566 | return false; | ||||||||
1567 | unsigned BitWidth = RetType->getBitWidth(); | ||||||||
1568 | if (BitWidth > 64) | ||||||||
1569 | return false; | ||||||||
1570 | |||||||||
1571 | // Make sure that each function is defined, does not access memory, takes at | ||||||||
1572 | // least one argument, does not use its first argument (which we assume is | ||||||||
1573 | // 'this'), and has the same return type. | ||||||||
1574 | // | ||||||||
1575 | // Note that we test whether this copy of the function is readnone, rather | ||||||||
1576 | // than testing function attributes, which must hold for any copy of the | ||||||||
1577 | // function, even a less optimized version substituted at link time. This is | ||||||||
1578 | // sound because the virtual constant propagation optimizations effectively | ||||||||
1579 | // inline all implementations of the virtual function into each call site, | ||||||||
1580 | // rather than using function attributes to perform local optimization. | ||||||||
1581 | for (VirtualCallTarget &Target : TargetsForSlot) { | ||||||||
1582 | if (Target.Fn->isDeclaration() || | ||||||||
1583 | computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) != | ||||||||
1584 | MAK_ReadNone || | ||||||||
1585 | Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() || | ||||||||
1586 | Target.Fn->getReturnType() != RetType) | ||||||||
1587 | return false; | ||||||||
1588 | } | ||||||||
1589 | |||||||||
1590 | for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) { | ||||||||
1591 | if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first)) | ||||||||
1592 | continue; | ||||||||
1593 | |||||||||
1594 | WholeProgramDevirtResolution::ByArg *ResByArg = nullptr; | ||||||||
1595 | if (Res) | ||||||||
1596 | ResByArg = &Res->ResByArg[CSByConstantArg.first]; | ||||||||
1597 | |||||||||
1598 | if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg)) | ||||||||
1599 | continue; | ||||||||
1600 | |||||||||
1601 | if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second, | ||||||||
1602 | ResByArg, Slot, CSByConstantArg.first)) | ||||||||
1603 | continue; | ||||||||
1604 | |||||||||
1605 | // Find an allocation offset in bits in all vtables associated with the | ||||||||
1606 | // type. | ||||||||
1607 | uint64_t AllocBefore = | ||||||||
1608 | findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth); | ||||||||
1609 | uint64_t AllocAfter = | ||||||||
1610 | findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth); | ||||||||
1611 | |||||||||
1612 | // Calculate the total amount of padding needed to store a value at both | ||||||||
1613 | // ends of the object. | ||||||||
1614 | uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0; | ||||||||
1615 | for (auto &&Target : TargetsForSlot) { | ||||||||
1616 | TotalPaddingBefore += std::max<int64_t>( | ||||||||
1617 | (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0); | ||||||||
1618 | TotalPaddingAfter += std::max<int64_t>( | ||||||||
1619 | (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0); | ||||||||
1620 | } | ||||||||
1621 | |||||||||
1622 | // If the amount of padding is too large, give up. | ||||||||
1623 | // FIXME: do something smarter here. | ||||||||
1624 | if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128) | ||||||||
1625 | continue; | ||||||||
1626 | |||||||||
1627 | // Calculate the offset to the value as a (possibly negative) byte offset | ||||||||
1628 | // and (if applicable) a bit offset, and store the values in the targets. | ||||||||
1629 | int64_t OffsetByte; | ||||||||
1630 | uint64_t OffsetBit; | ||||||||
1631 | if (TotalPaddingBefore <= TotalPaddingAfter) | ||||||||
1632 | setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte, | ||||||||
1633 | OffsetBit); | ||||||||
1634 | else | ||||||||
1635 | setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte, | ||||||||
1636 | OffsetBit); | ||||||||
1637 | |||||||||
1638 | if (RemarksEnabled) | ||||||||
1639 | for (auto &&Target : TargetsForSlot) | ||||||||
1640 | Target.WasDevirt = true; | ||||||||
1641 | |||||||||
1642 | |||||||||
1643 | if (CSByConstantArg.second.isExported()) { | ||||||||
1644 | ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; | ||||||||
1645 | exportConstant(Slot, CSByConstantArg.first, "byte", OffsetByte, | ||||||||
1646 | ResByArg->Byte); | ||||||||
1647 | exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit, | ||||||||
1648 | ResByArg->Bit); | ||||||||
1649 | } | ||||||||
1650 | |||||||||
1651 | // Rewrite each call to a load from OffsetByte/OffsetBit. | ||||||||
1652 | Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte); | ||||||||
1653 | Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit); | ||||||||
1654 | applyVirtualConstProp(CSByConstantArg.second, | ||||||||
1655 | TargetsForSlot[0].Fn->getName(), ByteConst, BitConst); | ||||||||
1656 | } | ||||||||
1657 | return true; | ||||||||
1658 | } | ||||||||
1659 | |||||||||
1660 | void DevirtModule::rebuildGlobal(VTableBits &B) { | ||||||||
1661 | if (B.Before.Bytes.empty() && B.After.Bytes.empty()) | ||||||||
1662 | return; | ||||||||
1663 | |||||||||
1664 | // Align the before byte array to the global's minimum alignment so that we | ||||||||
1665 | // don't break any alignment requirements on the global. | ||||||||
1666 | Align Alignment = M.getDataLayout().getValueOrABITypeAlignment( | ||||||||
1667 | B.GV->getAlign(), B.GV->getValueType()); | ||||||||
1668 | B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), Alignment)); | ||||||||
1669 | |||||||||
1670 | // Before was stored in reverse order; flip it now. | ||||||||
1671 | for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I) | ||||||||
1672 | std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]); | ||||||||
1673 | |||||||||
1674 | // Build an anonymous global containing the before bytes, followed by the | ||||||||
1675 | // original initializer, followed by the after bytes. | ||||||||
1676 | auto NewInit = ConstantStruct::getAnon( | ||||||||
1677 | {ConstantDataArray::get(M.getContext(), B.Before.Bytes), | ||||||||
1678 | B.GV->getInitializer(), | ||||||||
1679 | ConstantDataArray::get(M.getContext(), B.After.Bytes)}); | ||||||||
1680 | auto NewGV = | ||||||||
1681 | new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(), | ||||||||
1682 | GlobalVariable::PrivateLinkage, NewInit, "", B.GV); | ||||||||
1683 | NewGV->setSection(B.GV->getSection()); | ||||||||
1684 | NewGV->setComdat(B.GV->getComdat()); | ||||||||
1685 | NewGV->setAlignment(MaybeAlign(B.GV->getAlignment())); | ||||||||
1686 | |||||||||
1687 | // Copy the original vtable's metadata to the anonymous global, adjusting | ||||||||
1688 | // offsets as required. | ||||||||
1689 | NewGV->copyMetadata(B.GV, B.Before.Bytes.size()); | ||||||||
1690 | |||||||||
1691 | // Build an alias named after the original global, pointing at the second | ||||||||
1692 | // element (the original initializer). | ||||||||
1693 | auto Alias = GlobalAlias::create( | ||||||||
1694 | B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "", | ||||||||
1695 | ConstantExpr::getGetElementPtr( | ||||||||
1696 | NewInit->getType(), NewGV, | ||||||||
1697 | ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0), | ||||||||
1698 | ConstantInt::get(Int32Ty, 1)}), | ||||||||
1699 | &M); | ||||||||
1700 | Alias->setVisibility(B.GV->getVisibility()); | ||||||||
1701 | Alias->takeName(B.GV); | ||||||||
1702 | |||||||||
1703 | B.GV->replaceAllUsesWith(Alias); | ||||||||
1704 | B.GV->eraseFromParent(); | ||||||||
1705 | } | ||||||||
1706 | |||||||||
1707 | bool DevirtModule::areRemarksEnabled() { | ||||||||
1708 | const auto &FL = M.getFunctionList(); | ||||||||
1709 | for (const Function &Fn : FL) { | ||||||||
1710 | const auto &BBL = Fn.getBasicBlockList(); | ||||||||
1711 | if (BBL.empty()) | ||||||||
1712 | continue; | ||||||||
1713 | auto DI = OptimizationRemark(DEBUG_TYPE"wholeprogramdevirt", "", DebugLoc(), &BBL.front()); | ||||||||
1714 | return DI.isEnabled(); | ||||||||
1715 | } | ||||||||
1716 | return false; | ||||||||
1717 | } | ||||||||
1718 | |||||||||
1719 | void DevirtModule::scanTypeTestUsers( | ||||||||
1720 | Function *TypeTestFunc, | ||||||||
1721 | DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) { | ||||||||
1722 | // Find all virtual calls via a virtual table pointer %p under an assumption | ||||||||
1723 | // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p | ||||||||
1724 | // points to a member of the type identifier %md. Group calls by (type ID, | ||||||||
1725 | // offset) pair (effectively the identity of the virtual function) and store | ||||||||
1726 | // to CallSlots. | ||||||||
1727 | for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end(); | ||||||||
1728 | I != E;) { | ||||||||
1729 | auto CI = dyn_cast<CallInst>(I->getUser()); | ||||||||
1730 | ++I; | ||||||||
1731 | if (!CI) | ||||||||
1732 | continue; | ||||||||
1733 | |||||||||
1734 | // Search for virtual calls based on %p and add them to DevirtCalls. | ||||||||
1735 | SmallVector<DevirtCallSite, 1> DevirtCalls; | ||||||||
1736 | SmallVector<CallInst *, 1> Assumes; | ||||||||
1737 | auto &DT = LookupDomTree(*CI->getFunction()); | ||||||||
1738 | findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT); | ||||||||
1739 | |||||||||
1740 | Metadata *TypeId = | ||||||||
1741 | cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata(); | ||||||||
1742 | // If we found any, add them to CallSlots. | ||||||||
1743 | if (!Assumes.empty()) { | ||||||||
1744 | Value *Ptr = CI->getArgOperand(0)->stripPointerCasts(); | ||||||||
1745 | for (DevirtCallSite Call : DevirtCalls) | ||||||||
1746 | CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB, nullptr); | ||||||||
1747 | } | ||||||||
1748 | |||||||||
1749 | auto RemoveTypeTestAssumes = [&]() { | ||||||||
1750 | // We no longer need the assumes or the type test. | ||||||||
1751 | for (auto Assume : Assumes) | ||||||||
1752 | Assume->eraseFromParent(); | ||||||||
1753 | // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we | ||||||||
1754 | // may use the vtable argument later. | ||||||||
1755 | if (CI->use_empty()) | ||||||||
1756 | CI->eraseFromParent(); | ||||||||
1757 | }; | ||||||||
1758 | |||||||||
1759 | // At this point we could remove all type test assume sequences, as they | ||||||||
1760 | // were originally inserted for WPD. However, we can keep these in the | ||||||||
1761 | // code stream for later analysis (e.g. to help drive more efficient ICP | ||||||||
1762 | // sequences). They will eventually be removed by a second LowerTypeTests | ||||||||
1763 | // invocation that cleans them up. In order to do this correctly, the first | ||||||||
1764 | // LowerTypeTests invocation needs to know that they have "Unknown" type | ||||||||
1765 | // test resolution, so that they aren't treated as Unsat and lowered to | ||||||||
1766 | // False, which will break any uses on assumes. Below we remove any type | ||||||||
1767 | // test assumes that will not be treated as Unknown by LTT. | ||||||||
1768 | |||||||||
1769 | // The type test assumes will be treated by LTT as Unsat if the type id is | ||||||||
1770 | // not used on a global (in which case it has no entry in the TypeIdMap). | ||||||||
1771 | if (!TypeIdMap.count(TypeId)) | ||||||||
1772 | RemoveTypeTestAssumes(); | ||||||||
1773 | |||||||||
1774 | // For ThinLTO importing, we need to remove the type test assumes if this is | ||||||||
1775 | // an MDString type id without a corresponding TypeIdSummary. Any | ||||||||
1776 | // non-MDString type ids are ignored and treated as Unknown by LTT, so their | ||||||||
1777 | // type test assumes can be kept. If the MDString type id is missing a | ||||||||
1778 | // TypeIdSummary (e.g. because there was no use on a vcall, preventing the | ||||||||
1779 | // exporting phase of WPD from analyzing it), then it would be treated as | ||||||||
1780 | // Unsat by LTT and we need to remove its type test assumes here. If not | ||||||||
1781 | // used on a vcall we don't need them for later optimization use in any | ||||||||
1782 | // case. | ||||||||
1783 | else if (ImportSummary && isa<MDString>(TypeId)) { | ||||||||
1784 | const TypeIdSummary *TidSummary = | ||||||||
1785 | ImportSummary->getTypeIdSummary(cast<MDString>(TypeId)->getString()); | ||||||||
1786 | if (!TidSummary) | ||||||||
1787 | RemoveTypeTestAssumes(); | ||||||||
1788 | else | ||||||||
1789 | // If one was created it should not be Unsat, because if we reached here | ||||||||
1790 | // the type id was used on a global. | ||||||||
1791 | assert(TidSummary->TTRes.TheKind != TypeTestResolution::Unsat)((TidSummary->TTRes.TheKind != TypeTestResolution::Unsat) ? static_cast<void> (0) : __assert_fail ("TidSummary->TTRes.TheKind != TypeTestResolution::Unsat" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp" , 1791, __PRETTY_FUNCTION__)); | ||||||||
1792 | } | ||||||||
1793 | } | ||||||||
1794 | } | ||||||||
1795 | |||||||||
1796 | void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) { | ||||||||
1797 | Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test); | ||||||||
1798 | |||||||||
1799 | for (auto I = TypeCheckedLoadFunc->use_begin(), | ||||||||
1800 | E = TypeCheckedLoadFunc->use_end(); | ||||||||
1801 | I != E;) { | ||||||||
1802 | auto CI = dyn_cast<CallInst>(I->getUser()); | ||||||||
1803 | ++I; | ||||||||
1804 | if (!CI) | ||||||||
1805 | continue; | ||||||||
1806 | |||||||||
1807 | Value *Ptr = CI->getArgOperand(0); | ||||||||
1808 | Value *Offset = CI->getArgOperand(1); | ||||||||
1809 | Value *TypeIdValue = CI->getArgOperand(2); | ||||||||
1810 | Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata(); | ||||||||
1811 | |||||||||
1812 | SmallVector<DevirtCallSite, 1> DevirtCalls; | ||||||||
1813 | SmallVector<Instruction *, 1> LoadedPtrs; | ||||||||
1814 | SmallVector<Instruction *, 1> Preds; | ||||||||
1815 | bool HasNonCallUses = false; | ||||||||
1816 | auto &DT = LookupDomTree(*CI->getFunction()); | ||||||||
1817 | findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds, | ||||||||
1818 | HasNonCallUses, CI, DT); | ||||||||
1819 | |||||||||
1820 | // Start by generating "pessimistic" code that explicitly loads the function | ||||||||
1821 | // pointer from the vtable and performs the type check. If possible, we will | ||||||||
1822 | // eliminate the load and the type check later. | ||||||||
1823 | |||||||||
1824 | // If possible, only generate the load at the point where it is used. | ||||||||
1825 | // This helps avoid unnecessary spills. | ||||||||
1826 | IRBuilder<> LoadB( | ||||||||
1827 | (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI); | ||||||||
1828 | Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset); | ||||||||
1829 | Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy)); | ||||||||
1830 | Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr); | ||||||||
1831 | |||||||||
1832 | for (Instruction *LoadedPtr : LoadedPtrs) { | ||||||||
1833 | LoadedPtr->replaceAllUsesWith(LoadedValue); | ||||||||
1834 | LoadedPtr->eraseFromParent(); | ||||||||
1835 | } | ||||||||
1836 | |||||||||
1837 | // Likewise for the type test. | ||||||||
1838 | IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI); | ||||||||
1839 | CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue}); | ||||||||
1840 | |||||||||
1841 | for (Instruction *Pred : Preds) { | ||||||||
1842 | Pred->replaceAllUsesWith(TypeTestCall); | ||||||||
1843 | Pred->eraseFromParent(); | ||||||||
1844 | } | ||||||||
1845 | |||||||||
1846 | // We have already erased any extractvalue instructions that refer to the | ||||||||
1847 | // intrinsic call, but the intrinsic may have other non-extractvalue uses | ||||||||
1848 | // (although this is unlikely). In that case, explicitly build a pair and | ||||||||
1849 | // RAUW it. | ||||||||
1850 | if (!CI->use_empty()) { | ||||||||
1851 | Value *Pair = UndefValue::get(CI->getType()); | ||||||||
1852 | IRBuilder<> B(CI); | ||||||||
1853 | Pair = B.CreateInsertValue(Pair, LoadedValue, {0}); | ||||||||
1854 | Pair = B.CreateInsertValue(Pair, TypeTestCall, {1}); | ||||||||
1855 | CI->replaceAllUsesWith(Pair); | ||||||||
1856 | } | ||||||||
1857 | |||||||||
1858 | // The number of unsafe uses is initially the number of uses. | ||||||||
1859 | auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall]; | ||||||||
1860 | NumUnsafeUses = DevirtCalls.size(); | ||||||||
1861 | |||||||||
1862 | // If the function pointer has a non-call user, we cannot eliminate the type | ||||||||
1863 | // check, as one of those users may eventually call the pointer. Increment | ||||||||
1864 | // the unsafe use count to make sure it cannot reach zero. | ||||||||
1865 | if (HasNonCallUses) | ||||||||
1866 | ++NumUnsafeUses; | ||||||||
1867 | for (DevirtCallSite Call : DevirtCalls) { | ||||||||
1868 | CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB, | ||||||||
1869 | &NumUnsafeUses); | ||||||||
1870 | } | ||||||||
1871 | |||||||||
1872 | CI->eraseFromParent(); | ||||||||
1873 | } | ||||||||
1874 | } | ||||||||
1875 | |||||||||
1876 | void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) { | ||||||||
1877 | auto *TypeId = dyn_cast<MDString>(Slot.TypeID); | ||||||||
1878 | if (!TypeId) | ||||||||
1879 | return; | ||||||||
1880 | const TypeIdSummary *TidSummary = | ||||||||
1881 | ImportSummary->getTypeIdSummary(TypeId->getString()); | ||||||||
1882 | if (!TidSummary) | ||||||||
1883 | return; | ||||||||
1884 | auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset); | ||||||||
1885 | if (ResI == TidSummary->WPDRes.end()) | ||||||||
1886 | return; | ||||||||
1887 | const WholeProgramDevirtResolution &Res = ResI->second; | ||||||||
1888 | |||||||||
1889 | if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) { | ||||||||
1890 | assert(!Res.SingleImplName.empty())((!Res.SingleImplName.empty()) ? static_cast<void> (0) : __assert_fail ("!Res.SingleImplName.empty()", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp" , 1890, __PRETTY_FUNCTION__)); | ||||||||
1891 | // The type of the function in the declaration is irrelevant because every | ||||||||
1892 | // call site will cast it to the correct type. | ||||||||
1893 | Constant *SingleImpl = | ||||||||
1894 | cast<Constant>(M.getOrInsertFunction(Res.SingleImplName, | ||||||||
1895 | Type::getVoidTy(M.getContext())) | ||||||||
1896 | .getCallee()); | ||||||||
1897 | |||||||||
1898 | // This is the import phase so we should not be exporting anything. | ||||||||
1899 | bool IsExported = false; | ||||||||
1900 | applySingleImplDevirt(SlotInfo, SingleImpl, IsExported); | ||||||||
1901 | assert(!IsExported)((!IsExported) ? static_cast<void> (0) : __assert_fail ( "!IsExported", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp" , 1901, __PRETTY_FUNCTION__)); | ||||||||
1902 | } | ||||||||
1903 | |||||||||
1904 | for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) { | ||||||||
1905 | auto I = Res.ResByArg.find(CSByConstantArg.first); | ||||||||
1906 | if (I == Res.ResByArg.end()) | ||||||||
1907 | continue; | ||||||||
1908 | auto &ResByArg = I->second; | ||||||||
1909 | // FIXME: We should figure out what to do about the "function name" argument | ||||||||
1910 | // to the apply* functions, as the function names are unavailable during the | ||||||||
1911 | // importing phase. For now we just pass the empty string. This does not | ||||||||
1912 | // impact correctness because the function names are just used for remarks. | ||||||||
1913 | switch (ResByArg.TheKind) { | ||||||||
1914 | case WholeProgramDevirtResolution::ByArg::UniformRetVal: | ||||||||
1915 | applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info); | ||||||||
1916 | break; | ||||||||
1917 | case WholeProgramDevirtResolution::ByArg::UniqueRetVal: { | ||||||||
1918 | Constant *UniqueMemberAddr = | ||||||||
1919 | importGlobal(Slot, CSByConstantArg.first, "unique_member"); | ||||||||
1920 | applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info, | ||||||||
1921 | UniqueMemberAddr); | ||||||||
1922 | break; | ||||||||
1923 | } | ||||||||
1924 | case WholeProgramDevirtResolution::ByArg::VirtualConstProp: { | ||||||||
1925 | Constant *Byte = importConstant(Slot, CSByConstantArg.first, "byte", | ||||||||
1926 | Int32Ty, ResByArg.Byte); | ||||||||
1927 | Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty, | ||||||||
1928 | ResByArg.Bit); | ||||||||
1929 | applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit); | ||||||||
1930 | break; | ||||||||
1931 | } | ||||||||
1932 | default: | ||||||||
1933 | break; | ||||||||
1934 | } | ||||||||
1935 | } | ||||||||
1936 | |||||||||
1937 | if (Res.TheKind == WholeProgramDevirtResolution::BranchFunnel) { | ||||||||
1938 | // The type of the function is irrelevant, because it's bitcast at calls | ||||||||
1939 | // anyhow. | ||||||||
1940 | Constant *JT = cast<Constant>( | ||||||||
1941 | M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"), | ||||||||
1942 | Type::getVoidTy(M.getContext())) | ||||||||
1943 | .getCallee()); | ||||||||
1944 | bool IsExported = false; | ||||||||
1945 | applyICallBranchFunnel(SlotInfo, JT, IsExported); | ||||||||
1946 | assert(!IsExported)((!IsExported) ? static_cast<void> (0) : __assert_fail ( "!IsExported", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp" , 1946, __PRETTY_FUNCTION__)); | ||||||||
1947 | } | ||||||||
1948 | } | ||||||||
1949 | |||||||||
1950 | void DevirtModule::removeRedundantTypeTests() { | ||||||||
1951 | auto True = ConstantInt::getTrue(M.getContext()); | ||||||||
1952 | for (auto &&U : NumUnsafeUsesForTypeTest) { | ||||||||
1953 | if (U.second == 0) { | ||||||||
1954 | U.first->replaceAllUsesWith(True); | ||||||||
1955 | U.first->eraseFromParent(); | ||||||||
1956 | } | ||||||||
1957 | } | ||||||||
1958 | } | ||||||||
1959 | |||||||||
1960 | bool DevirtModule::run() { | ||||||||
1961 | // If only some of the modules were split, we cannot correctly perform | ||||||||
1962 | // this transformation. We already checked for the presense of type tests | ||||||||
1963 | // with partially split modules during the thin link, and would have emitted | ||||||||
1964 | // an error if any were found, so here we can simply return. | ||||||||
1965 | if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) || | ||||||||
| |||||||||
1966 | (ImportSummary && ImportSummary->partiallySplitLTOUnits())) | ||||||||
1967 | return false; | ||||||||
1968 | |||||||||
1969 | Function *TypeTestFunc = | ||||||||
1970 | M.getFunction(Intrinsic::getName(Intrinsic::type_test)); | ||||||||
1971 | Function *TypeCheckedLoadFunc = | ||||||||
1972 | M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load)); | ||||||||
1973 | Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume)); | ||||||||
1974 | |||||||||
1975 | // Normally if there are no users of the devirtualization intrinsics in the | ||||||||
1976 | // module, this pass has nothing to do. But if we are exporting, we also need | ||||||||
1977 | // to handle any users that appear only in the function summaries. | ||||||||
1978 | if (!ExportSummary
| ||||||||
1979 | (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc || | ||||||||
1980 | AssumeFunc->use_empty()) && | ||||||||
1981 | (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty())) | ||||||||
1982 | return false; | ||||||||
1983 | |||||||||
1984 | // Rebuild type metadata into a map for easy lookup. | ||||||||
1985 | std::vector<VTableBits> Bits; | ||||||||
1986 | DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap; | ||||||||
1987 | buildTypeIdentifierMap(Bits, TypeIdMap); | ||||||||
1988 | |||||||||
1989 | if (TypeTestFunc
| ||||||||
1990 | scanTypeTestUsers(TypeTestFunc, TypeIdMap); | ||||||||
1991 | |||||||||
1992 | if (TypeCheckedLoadFunc) | ||||||||
1993 | scanTypeCheckedLoadUsers(TypeCheckedLoadFunc); | ||||||||
1994 | |||||||||
1995 | if (ImportSummary
| ||||||||
1996 | for (auto &S : CallSlots) | ||||||||
1997 | importResolution(S.first, S.second); | ||||||||
1998 | |||||||||
1999 | removeRedundantTypeTests(); | ||||||||
2000 | |||||||||
2001 | // We have lowered or deleted the type instrinsics, so we will no | ||||||||
2002 | // longer have enough information to reason about the liveness of virtual | ||||||||
2003 | // function pointers in GlobalDCE. | ||||||||
2004 | for (GlobalVariable &GV : M.globals()) | ||||||||
2005 | GV.eraseMetadata(LLVMContext::MD_vcall_visibility); | ||||||||
2006 | |||||||||
2007 | // The rest of the code is only necessary when exporting or during regular | ||||||||
2008 | // LTO, so we are done. | ||||||||
2009 | return true; | ||||||||
2010 | } | ||||||||
2011 | |||||||||
2012 | if (TypeIdMap.empty()) | ||||||||
2013 | return true; | ||||||||
2014 | |||||||||
2015 | // Collect information from summary about which calls to try to devirtualize. | ||||||||
2016 | if (ExportSummary
| ||||||||
2017 | DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID; | ||||||||
2018 | for (auto &P : TypeIdMap) { | ||||||||
2019 | if (auto *TypeId = dyn_cast<MDString>(P.first)) | ||||||||
2020 | MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back( | ||||||||
2021 | TypeId); | ||||||||
2022 | } | ||||||||
2023 | |||||||||
2024 | for (auto &P : *ExportSummary) { | ||||||||
2025 | for (auto &S : P.second.SummaryList) { | ||||||||
2026 | auto *FS = dyn_cast<FunctionSummary>(S.get()); | ||||||||
2027 | if (!FS) | ||||||||
2028 | continue; | ||||||||
2029 | // FIXME: Only add live functions. | ||||||||
2030 | for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) { | ||||||||
2031 | for (Metadata *MD : MetadataByGUID[VF.GUID]) { | ||||||||
2032 | CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS); | ||||||||
2033 | } | ||||||||
2034 | } | ||||||||
2035 | for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) { | ||||||||
2036 | for (Metadata *MD : MetadataByGUID[VF.GUID]) { | ||||||||
2037 | CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS); | ||||||||
2038 | } | ||||||||
2039 | } | ||||||||
2040 | for (const FunctionSummary::ConstVCall &VC : | ||||||||
2041 | FS->type_test_assume_const_vcalls()) { | ||||||||
2042 | for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) { | ||||||||
2043 | CallSlots[{MD, VC.VFunc.Offset}] | ||||||||
2044 | .ConstCSInfo[VC.Args] | ||||||||
2045 | .addSummaryTypeTestAssumeUser(FS); | ||||||||
2046 | } | ||||||||
2047 | } | ||||||||
2048 | for (const FunctionSummary::ConstVCall &VC : | ||||||||
2049 | FS->type_checked_load_const_vcalls()) { | ||||||||
2050 | for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) { | ||||||||
2051 | CallSlots[{MD, VC.VFunc.Offset}] | ||||||||
2052 | .ConstCSInfo[VC.Args] | ||||||||
2053 | .addSummaryTypeCheckedLoadUser(FS); | ||||||||
2054 | } | ||||||||
2055 | } | ||||||||
2056 | } | ||||||||
2057 | } | ||||||||
2058 | } | ||||||||
2059 | |||||||||
2060 | // For each (type, offset) pair: | ||||||||
2061 | bool DidVirtualConstProp = false; | ||||||||
2062 | std::map<std::string, Function*> DevirtTargets; | ||||||||
2063 | for (auto &S : CallSlots) { | ||||||||
2064 | // Search each of the members of the type identifier for the virtual | ||||||||
2065 | // function implementation at offset S.first.ByteOffset, and add to | ||||||||
2066 | // TargetsForSlot. | ||||||||
2067 | std::vector<VirtualCallTarget> TargetsForSlot; | ||||||||
2068 | WholeProgramDevirtResolution *Res = nullptr; | ||||||||
2069 | const std::set<TypeMemberInfo> &TypeMemberInfos = TypeIdMap[S.first.TypeID]; | ||||||||
2070 | if (ExportSummary && isa<MDString>(S.first.TypeID) && | ||||||||
2071 | TypeMemberInfos.size()) | ||||||||
2072 | // For any type id used on a global's type metadata, create the type id | ||||||||
2073 | // summary resolution regardless of whether we can devirtualize, so that | ||||||||
2074 | // lower type tests knows the type id is not Unsat. If it was not used on | ||||||||
2075 | // a global's type metadata, the TypeIdMap entry set will be empty, and | ||||||||
2076 | // we don't want to create an entry (with the default Unknown type | ||||||||
2077 | // resolution), which can prevent detection of the Unsat. | ||||||||
2078 | Res = &ExportSummary | ||||||||
2079 | ->getOrInsertTypeIdSummary( | ||||||||
2080 | cast<MDString>(S.first.TypeID)->getString()) | ||||||||
2081 | .WPDRes[S.first.ByteOffset]; | ||||||||
2082 | if (tryFindVirtualCallTargets(TargetsForSlot, TypeMemberInfos, | ||||||||
2083 | S.first.ByteOffset)) { | ||||||||
2084 | |||||||||
2085 | if (!trySingleImplDevirt(ExportSummary, TargetsForSlot, S.second, Res)) { | ||||||||
2086 | DidVirtualConstProp |= | ||||||||
2087 | tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first); | ||||||||
2088 | |||||||||
2089 | tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first); | ||||||||
2090 | } | ||||||||
2091 | |||||||||
2092 | // Collect functions devirtualized at least for one call site for stats. | ||||||||
2093 | if (RemarksEnabled) | ||||||||
2094 | for (const auto &T : TargetsForSlot) | ||||||||
2095 | if (T.WasDevirt) | ||||||||
2096 | DevirtTargets[std::string(T.Fn->getName())] = T.Fn; | ||||||||
2097 | } | ||||||||
2098 | |||||||||
2099 | // CFI-specific: if we are exporting and any llvm.type.checked.load | ||||||||
2100 | // intrinsics were *not* devirtualized, we need to add the resulting | ||||||||
2101 | // llvm.type.test intrinsics to the function summaries so that the | ||||||||
2102 | // LowerTypeTests pass will export them. | ||||||||
2103 | if (ExportSummary && isa<MDString>(S.first.TypeID)) { | ||||||||
2104 | auto GUID = | ||||||||
2105 | GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString()); | ||||||||
2106 | for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers) | ||||||||
2107 | FS->addTypeTest(GUID); | ||||||||
2108 | for (auto &CCS : S.second.ConstCSInfo) | ||||||||
2109 | for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers) | ||||||||
2110 | FS->addTypeTest(GUID); | ||||||||
2111 | } | ||||||||
2112 | } | ||||||||
2113 | |||||||||
2114 | if (RemarksEnabled) { | ||||||||
2115 | // Generate remarks for each devirtualized function. | ||||||||
2116 | for (const auto &DT : DevirtTargets) { | ||||||||
2117 | Function *F = DT.second; | ||||||||
2118 | |||||||||
2119 | using namespace ore; | ||||||||
2120 | OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE"wholeprogramdevirt", "Devirtualized", F) | ||||||||
2121 | << "devirtualized " | ||||||||
2122 | << NV("FunctionName", DT.first)); | ||||||||
2123 | } | ||||||||
2124 | } | ||||||||
2125 | |||||||||
2126 | removeRedundantTypeTests(); | ||||||||
2127 | |||||||||
2128 | // Rebuild each global we touched as part of virtual constant propagation to | ||||||||
2129 | // include the before and after bytes. | ||||||||
2130 | if (DidVirtualConstProp) | ||||||||
2131 | for (VTableBits &B : Bits) | ||||||||
2132 | rebuildGlobal(B); | ||||||||
2133 | |||||||||
2134 | // We have lowered or deleted the type instrinsics, so we will no | ||||||||
2135 | // longer have enough information to reason about the liveness of virtual | ||||||||
2136 | // function pointers in GlobalDCE. | ||||||||
2137 | for (GlobalVariable &GV : M.globals()) | ||||||||
2138 | GV.eraseMetadata(LLVMContext::MD_vcall_visibility); | ||||||||
2139 | |||||||||
2140 | return true; | ||||||||
2141 | } | ||||||||
2142 | |||||||||
2143 | void DevirtIndex::run() { | ||||||||
2144 | if (ExportSummary.typeIdCompatibleVtableMap().empty()) | ||||||||
2145 | return; | ||||||||
2146 | |||||||||
2147 | DenseMap<GlobalValue::GUID, std::vector<StringRef>> NameByGUID; | ||||||||
2148 | for (auto &P : ExportSummary.typeIdCompatibleVtableMap()) { | ||||||||
2149 | NameByGUID[GlobalValue::getGUID(P.first)].push_back(P.first); | ||||||||
2150 | } | ||||||||
2151 | |||||||||
2152 | // Collect information from summary about which calls to try to devirtualize. | ||||||||
2153 | for (auto &P : ExportSummary) { | ||||||||
2154 | for (auto &S : P.second.SummaryList) { | ||||||||
2155 | auto *FS = dyn_cast<FunctionSummary>(S.get()); | ||||||||
2156 | if (!FS) | ||||||||
2157 | continue; | ||||||||
2158 | // FIXME: Only add live functions. | ||||||||
2159 | for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) { | ||||||||
2160 | for (StringRef Name : NameByGUID[VF.GUID]) { | ||||||||
2161 | CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS); | ||||||||
2162 | } | ||||||||
2163 | } | ||||||||
2164 | for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) { | ||||||||
2165 | for (StringRef Name : NameByGUID[VF.GUID]) { | ||||||||
2166 | CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS); | ||||||||
2167 | } | ||||||||
2168 | } | ||||||||
2169 | for (const FunctionSummary::ConstVCall &VC : | ||||||||
2170 | FS->type_test_assume_const_vcalls()) { | ||||||||
2171 | for (StringRef Name : NameByGUID[VC.VFunc.GUID]) { | ||||||||
2172 | CallSlots[{Name, VC.VFunc.Offset}] | ||||||||
2173 | .ConstCSInfo[VC.Args] | ||||||||
2174 | .addSummaryTypeTestAssumeUser(FS); | ||||||||
2175 | } | ||||||||
2176 | } | ||||||||
2177 | for (const FunctionSummary::ConstVCall &VC : | ||||||||
2178 | FS->type_checked_load_const_vcalls()) { | ||||||||
2179 | for (StringRef Name : NameByGUID[VC.VFunc.GUID]) { | ||||||||
2180 | CallSlots[{Name, VC.VFunc.Offset}] | ||||||||
2181 | .ConstCSInfo[VC.Args] | ||||||||
2182 | .addSummaryTypeCheckedLoadUser(FS); | ||||||||
2183 | } | ||||||||
2184 | } | ||||||||
2185 | } | ||||||||
2186 | } | ||||||||
2187 | |||||||||
2188 | std::set<ValueInfo> DevirtTargets; | ||||||||
2189 | // For each (type, offset) pair: | ||||||||
2190 | for (auto &S : CallSlots) { | ||||||||
2191 | // Search each of the members of the type identifier for the virtual | ||||||||
2192 | // function implementation at offset S.first.ByteOffset, and add to | ||||||||
2193 | // TargetsForSlot. | ||||||||
2194 | std::vector<ValueInfo> TargetsForSlot; | ||||||||
2195 | auto TidSummary = ExportSummary.getTypeIdCompatibleVtableSummary(S.first.TypeID); | ||||||||
2196 | assert(TidSummary)((TidSummary) ? static_cast<void> (0) : __assert_fail ( "TidSummary", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp" , 2196, __PRETTY_FUNCTION__)); | ||||||||
2197 | // Create the type id summary resolution regardlness of whether we can | ||||||||
2198 | // devirtualize, so that lower type tests knows the type id is used on | ||||||||
2199 | // a global and not Unsat. | ||||||||
2200 | WholeProgramDevirtResolution *Res = | ||||||||
2201 | &ExportSummary.getOrInsertTypeIdSummary(S.first.TypeID) | ||||||||
2202 | .WPDRes[S.first.ByteOffset]; | ||||||||
2203 | if (tryFindVirtualCallTargets(TargetsForSlot, *TidSummary, | ||||||||
2204 | S.first.ByteOffset)) { | ||||||||
2205 | |||||||||
2206 | if (!trySingleImplDevirt(TargetsForSlot, S.first, S.second, Res, | ||||||||
2207 | DevirtTargets)) | ||||||||
2208 | continue; | ||||||||
2209 | } | ||||||||
2210 | } | ||||||||
2211 | |||||||||
2212 | // Optionally have the thin link print message for each devirtualized | ||||||||
2213 | // function. | ||||||||
2214 | if (PrintSummaryDevirt) | ||||||||
2215 | for (const auto &DT : DevirtTargets) | ||||||||
2216 | errs() << "Devirtualized call to " << DT << "\n"; | ||||||||
2217 | } |
1 | //===- llvm/Value.h - Definition of the Value class -------------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file declares the Value class. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_IR_VALUE_H |
14 | #define LLVM_IR_VALUE_H |
15 | |
16 | #include "llvm-c/Types.h" |
17 | #include "llvm/ADT/STLExtras.h" |
18 | #include "llvm/ADT/StringRef.h" |
19 | #include "llvm/ADT/iterator_range.h" |
20 | #include "llvm/IR/Use.h" |
21 | #include "llvm/Support/Alignment.h" |
22 | #include "llvm/Support/CBindingWrapping.h" |
23 | #include "llvm/Support/Casting.h" |
24 | #include <cassert> |
25 | #include <iterator> |
26 | #include <memory> |
27 | |
28 | namespace llvm { |
29 | |
30 | class APInt; |
31 | class Argument; |
32 | class BasicBlock; |
33 | class Constant; |
34 | class ConstantData; |
35 | class ConstantAggregate; |
36 | class DataLayout; |
37 | class Function; |
38 | class GlobalAlias; |
39 | class GlobalIFunc; |
40 | class GlobalIndirectSymbol; |
41 | class GlobalObject; |
42 | class GlobalValue; |
43 | class GlobalVariable; |
44 | class InlineAsm; |
45 | class Instruction; |
46 | class LLVMContext; |
47 | class MDNode; |
48 | class Module; |
49 | class ModuleSlotTracker; |
50 | class raw_ostream; |
51 | template<typename ValueTy> class StringMapEntry; |
52 | class Twine; |
53 | class Type; |
54 | class User; |
55 | |
56 | using ValueName = StringMapEntry<Value *>; |
57 | |
58 | //===----------------------------------------------------------------------===// |
59 | // Value Class |
60 | //===----------------------------------------------------------------------===// |
61 | |
62 | /// LLVM Value Representation |
63 | /// |
64 | /// This is a very important LLVM class. It is the base class of all values |
65 | /// computed by a program that may be used as operands to other values. Value is |
66 | /// the super class of other important classes such as Instruction and Function. |
67 | /// All Values have a Type. Type is not a subclass of Value. Some values can |
68 | /// have a name and they belong to some Module. Setting the name on the Value |
69 | /// automatically updates the module's symbol table. |
70 | /// |
71 | /// Every value has a "use list" that keeps track of which other Values are |
72 | /// using this Value. A Value can also have an arbitrary number of ValueHandle |
73 | /// objects that watch it and listen to RAUW and Destroy events. See |
74 | /// llvm/IR/ValueHandle.h for details. |
75 | class Value { |
76 | Type *VTy; |
77 | Use *UseList; |
78 | |
79 | friend class ValueAsMetadata; // Allow access to IsUsedByMD. |
80 | friend class ValueHandleBase; |
81 | |
82 | const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast) |
83 | unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this? |
84 | |
85 | protected: |
86 | /// Hold subclass data that can be dropped. |
87 | /// |
88 | /// This member is similar to SubclassData, however it is for holding |
89 | /// information which may be used to aid optimization, but which may be |
90 | /// cleared to zero without affecting conservative interpretation. |
91 | unsigned char SubclassOptionalData : 7; |
92 | |
93 | private: |
94 | /// Hold arbitrary subclass data. |
95 | /// |
96 | /// This member is defined by this class, but is not used for anything. |
97 | /// Subclasses can use it to hold whatever state they find useful. This |
98 | /// field is initialized to zero by the ctor. |
99 | unsigned short SubclassData; |
100 | |
101 | protected: |
102 | /// The number of operands in the subclass. |
103 | /// |
104 | /// This member is defined by this class, but not used for anything. |
105 | /// Subclasses can use it to store their number of operands, if they have |
106 | /// any. |
107 | /// |
108 | /// This is stored here to save space in User on 64-bit hosts. Since most |
109 | /// instances of Value have operands, 32-bit hosts aren't significantly |
110 | /// affected. |
111 | /// |
112 | /// Note, this should *NOT* be used directly by any class other than User. |
113 | /// User uses this value to find the Use list. |
114 | enum : unsigned { NumUserOperandsBits = 27 }; |
115 | unsigned NumUserOperands : NumUserOperandsBits; |
116 | |
117 | // Use the same type as the bitfield above so that MSVC will pack them. |
118 | unsigned IsUsedByMD : 1; |
119 | unsigned HasName : 1; |
120 | unsigned HasMetadata : 1; // Has metadata attached to this? |
121 | unsigned HasHungOffUses : 1; |
122 | unsigned HasDescriptor : 1; |
123 | |
124 | private: |
125 | template <typename UseT> // UseT == 'Use' or 'const Use' |
126 | class use_iterator_impl |
127 | : public std::iterator<std::forward_iterator_tag, UseT *> { |
128 | friend class Value; |
129 | |
130 | UseT *U; |
131 | |
132 | explicit use_iterator_impl(UseT *u) : U(u) {} |
133 | |
134 | public: |
135 | use_iterator_impl() : U() {} |
136 | |
137 | bool operator==(const use_iterator_impl &x) const { return U == x.U; } |
138 | bool operator!=(const use_iterator_impl &x) const { return !operator==(x); } |
139 | |
140 | use_iterator_impl &operator++() { // Preincrement |
141 | assert(U && "Cannot increment end iterator!")((U && "Cannot increment end iterator!") ? static_cast <void> (0) : __assert_fail ("U && \"Cannot increment end iterator!\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/include/llvm/IR/Value.h" , 141, __PRETTY_FUNCTION__)); |
142 | U = U->getNext(); |
143 | return *this; |
144 | } |
145 | |
146 | use_iterator_impl operator++(int) { // Postincrement |
147 | auto tmp = *this; |
148 | ++*this; |
149 | return tmp; |
150 | } |
151 | |
152 | UseT &operator*() const { |
153 | assert(U && "Cannot dereference end iterator!")((U && "Cannot dereference end iterator!") ? static_cast <void> (0) : __assert_fail ("U && \"Cannot dereference end iterator!\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/include/llvm/IR/Value.h" , 153, __PRETTY_FUNCTION__)); |
154 | return *U; |
155 | } |
156 | |
157 | UseT *operator->() const { return &operator*(); } |
158 | |
159 | operator use_iterator_impl<const UseT>() const { |
160 | return use_iterator_impl<const UseT>(U); |
161 | } |
162 | }; |
163 | |
164 | template <typename UserTy> // UserTy == 'User' or 'const User' |
165 | class user_iterator_impl |
166 | : public std::iterator<std::forward_iterator_tag, UserTy *> { |
167 | use_iterator_impl<Use> UI; |
168 | explicit user_iterator_impl(Use *U) : UI(U) {} |
169 | friend class Value; |
170 | |
171 | public: |
172 | user_iterator_impl() = default; |
173 | |
174 | bool operator==(const user_iterator_impl &x) const { return UI == x.UI; } |
175 | bool operator!=(const user_iterator_impl &x) const { return !operator==(x); } |
176 | |
177 | /// Returns true if this iterator is equal to user_end() on the value. |
178 | bool atEnd() const { return *this == user_iterator_impl(); } |
179 | |
180 | user_iterator_impl &operator++() { // Preincrement |
181 | ++UI; |
182 | return *this; |
183 | } |
184 | |
185 | user_iterator_impl operator++(int) { // Postincrement |
186 | auto tmp = *this; |
187 | ++*this; |
188 | return tmp; |
189 | } |
190 | |
191 | // Retrieve a pointer to the current User. |
192 | UserTy *operator*() const { |
193 | return UI->getUser(); |
194 | } |
195 | |
196 | UserTy *operator->() const { return operator*(); } |
197 | |
198 | operator user_iterator_impl<const UserTy>() const { |
199 | return user_iterator_impl<const UserTy>(*UI); |
200 | } |
201 | |
202 | Use &getUse() const { return *UI; } |
203 | }; |
204 | |
205 | protected: |
206 | Value(Type *Ty, unsigned scid); |
207 | |
208 | /// Value's destructor should be virtual by design, but that would require |
209 | /// that Value and all of its subclasses have a vtable that effectively |
210 | /// duplicates the information in the value ID. As a size optimization, the |
211 | /// destructor has been protected, and the caller should manually call |
212 | /// deleteValue. |
213 | ~Value(); // Use deleteValue() to delete a generic Value. |
214 | |
215 | public: |
216 | Value(const Value &) = delete; |
217 | Value &operator=(const Value &) = delete; |
218 | |
219 | /// Delete a pointer to a generic Value. |
220 | void deleteValue(); |
221 | |
222 | /// Support for debugging, callable in GDB: V->dump() |
223 | void dump() const; |
224 | |
225 | /// Implement operator<< on Value. |
226 | /// @{ |
227 | void print(raw_ostream &O, bool IsForDebug = false) const; |
228 | void print(raw_ostream &O, ModuleSlotTracker &MST, |
229 | bool IsForDebug = false) const; |
230 | /// @} |
231 | |
232 | /// Print the name of this Value out to the specified raw_ostream. |
233 | /// |
234 | /// This is useful when you just want to print 'int %reg126', not the |
235 | /// instruction that generated it. If you specify a Module for context, then |
236 | /// even constanst get pretty-printed; for example, the type of a null |
237 | /// pointer is printed symbolically. |
238 | /// @{ |
239 | void printAsOperand(raw_ostream &O, bool PrintType = true, |
240 | const Module *M = nullptr) const; |
241 | void printAsOperand(raw_ostream &O, bool PrintType, |
242 | ModuleSlotTracker &MST) const; |
243 | /// @} |
244 | |
245 | /// All values are typed, get the type of this value. |
246 | Type *getType() const { return VTy; } |
247 | |
248 | /// All values hold a context through their type. |
249 | LLVMContext &getContext() const; |
250 | |
251 | // All values can potentially be named. |
252 | bool hasName() const { return HasName; } |
253 | ValueName *getValueName() const; |
254 | void setValueName(ValueName *VN); |
255 | |
256 | private: |
257 | void destroyValueName(); |
258 | enum class ReplaceMetadataUses { No, Yes }; |
259 | void doRAUW(Value *New, ReplaceMetadataUses); |
260 | void setNameImpl(const Twine &Name); |
261 | |
262 | public: |
263 | /// Return a constant reference to the value's name. |
264 | /// |
265 | /// This guaranteed to return the same reference as long as the value is not |
266 | /// modified. If the value has a name, this does a hashtable lookup, so it's |
267 | /// not free. |
268 | StringRef getName() const; |
269 | |
270 | /// Change the name of the value. |
271 | /// |
272 | /// Choose a new unique name if the provided name is taken. |
273 | /// |
274 | /// \param Name The new name; or "" if the value's name should be removed. |
275 | void setName(const Twine &Name); |
276 | |
277 | /// Transfer the name from V to this value. |
278 | /// |
279 | /// After taking V's name, sets V's name to empty. |
280 | /// |
281 | /// \note It is an error to call V->takeName(V). |
282 | void takeName(Value *V); |
283 | |
284 | #ifndef NDEBUG |
285 | std::string getNameOrAsOperand() const; |
286 | #endif |
287 | |
288 | /// Change all uses of this to point to a new Value. |
289 | /// |
290 | /// Go through the uses list for this definition and make each use point to |
291 | /// "V" instead of "this". After this completes, 'this's use list is |
292 | /// guaranteed to be empty. |
293 | void replaceAllUsesWith(Value *V); |
294 | |
295 | /// Change non-metadata uses of this to point to a new Value. |
296 | /// |
297 | /// Go through the uses list for this definition and make each use point to |
298 | /// "V" instead of "this". This function skips metadata entries in the list. |
299 | void replaceNonMetadataUsesWith(Value *V); |
300 | |
301 | /// Go through the uses list for this definition and make each use point |
302 | /// to "V" if the callback ShouldReplace returns true for the given Use. |
303 | /// Unlike replaceAllUsesWith() this function does not support basic block |
304 | /// values or constant users. |
305 | void replaceUsesWithIf(Value *New, |
306 | llvm::function_ref<bool(Use &U)> ShouldReplace) { |
307 | assert(New && "Value::replaceUsesWithIf(<null>) is invalid!")((New && "Value::replaceUsesWithIf(<null>) is invalid!" ) ? static_cast<void> (0) : __assert_fail ("New && \"Value::replaceUsesWithIf(<null>) is invalid!\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/include/llvm/IR/Value.h" , 307, __PRETTY_FUNCTION__)); |
308 | assert(New->getType() == getType() &&((New->getType() == getType() && "replaceUses of value with new value of different type!" ) ? static_cast<void> (0) : __assert_fail ("New->getType() == getType() && \"replaceUses of value with new value of different type!\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/include/llvm/IR/Value.h" , 309, __PRETTY_FUNCTION__)) |
309 | "replaceUses of value with new value of different type!")((New->getType() == getType() && "replaceUses of value with new value of different type!" ) ? static_cast<void> (0) : __assert_fail ("New->getType() == getType() && \"replaceUses of value with new value of different type!\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/include/llvm/IR/Value.h" , 309, __PRETTY_FUNCTION__)); |
310 | |
311 | for (use_iterator UI = use_begin(), E = use_end(); UI != E;) { |
312 | Use &U = *UI; |
313 | ++UI; |
314 | if (!ShouldReplace(U)) |
315 | continue; |
316 | U.set(New); |
317 | } |
318 | } |
319 | |
320 | /// replaceUsesOutsideBlock - Go through the uses list for this definition and |
321 | /// make each use point to "V" instead of "this" when the use is outside the |
322 | /// block. 'This's use list is expected to have at least one element. |
323 | /// Unlike replaceAllUsesWith() this function does not support basic block |
324 | /// values or constant users. |
325 | void replaceUsesOutsideBlock(Value *V, BasicBlock *BB); |
326 | |
327 | //---------------------------------------------------------------------- |
328 | // Methods for handling the chain of uses of this Value. |
329 | // |
330 | // Materializing a function can introduce new uses, so these methods come in |
331 | // two variants: |
332 | // The methods that start with materialized_ check the uses that are |
333 | // currently known given which functions are materialized. Be very careful |
334 | // when using them since you might not get all uses. |
335 | // The methods that don't start with materialized_ assert that modules is |
336 | // fully materialized. |
337 | void assertModuleIsMaterializedImpl() const; |
338 | // This indirection exists so we can keep assertModuleIsMaterializedImpl() |
339 | // around in release builds of Value.cpp to be linked with other code built |
340 | // in debug mode. But this avoids calling it in any of the release built code. |
341 | void assertModuleIsMaterialized() const { |
342 | #ifndef NDEBUG |
343 | assertModuleIsMaterializedImpl(); |
344 | #endif |
345 | } |
346 | |
347 | bool use_empty() const { |
348 | assertModuleIsMaterialized(); |
349 | return UseList == nullptr; |
350 | } |
351 | |
352 | bool materialized_use_empty() const { |
353 | return UseList == nullptr; |
354 | } |
355 | |
356 | using use_iterator = use_iterator_impl<Use>; |
357 | using const_use_iterator = use_iterator_impl<const Use>; |
358 | |
359 | use_iterator materialized_use_begin() { return use_iterator(UseList); } |
360 | const_use_iterator materialized_use_begin() const { |
361 | return const_use_iterator(UseList); |
362 | } |
363 | use_iterator use_begin() { |
364 | assertModuleIsMaterialized(); |
365 | return materialized_use_begin(); |
366 | } |
367 | const_use_iterator use_begin() const { |
368 | assertModuleIsMaterialized(); |
369 | return materialized_use_begin(); |
370 | } |
371 | use_iterator use_end() { return use_iterator(); } |
372 | const_use_iterator use_end() const { return const_use_iterator(); } |
373 | iterator_range<use_iterator> materialized_uses() { |
374 | return make_range(materialized_use_begin(), use_end()); |
375 | } |
376 | iterator_range<const_use_iterator> materialized_uses() const { |
377 | return make_range(materialized_use_begin(), use_end()); |
378 | } |
379 | iterator_range<use_iterator> uses() { |
380 | assertModuleIsMaterialized(); |
381 | return materialized_uses(); |
382 | } |
383 | iterator_range<const_use_iterator> uses() const { |
384 | assertModuleIsMaterialized(); |
385 | return materialized_uses(); |
386 | } |
387 | |
388 | bool user_empty() const { |
389 | assertModuleIsMaterialized(); |
390 | return UseList == nullptr; |
391 | } |
392 | |
393 | using user_iterator = user_iterator_impl<User>; |
394 | using const_user_iterator = user_iterator_impl<const User>; |
395 | |
396 | user_iterator materialized_user_begin() { return user_iterator(UseList); } |
397 | const_user_iterator materialized_user_begin() const { |
398 | return const_user_iterator(UseList); |
399 | } |
400 | user_iterator user_begin() { |
401 | assertModuleIsMaterialized(); |
402 | return materialized_user_begin(); |
403 | } |
404 | const_user_iterator user_begin() const { |
405 | assertModuleIsMaterialized(); |
406 | return materialized_user_begin(); |
407 | } |
408 | user_iterator user_end() { return user_iterator(); } |
409 | const_user_iterator user_end() const { return const_user_iterator(); } |
410 | User *user_back() { |
411 | assertModuleIsMaterialized(); |
412 | return *materialized_user_begin(); |
413 | } |
414 | const User *user_back() const { |
415 | assertModuleIsMaterialized(); |
416 | return *materialized_user_begin(); |
417 | } |
418 | iterator_range<user_iterator> materialized_users() { |
419 | return make_range(materialized_user_begin(), user_end()); |
420 | } |
421 | iterator_range<const_user_iterator> materialized_users() const { |
422 | return make_range(materialized_user_begin(), user_end()); |
423 | } |
424 | iterator_range<user_iterator> users() { |
425 | assertModuleIsMaterialized(); |
426 | return materialized_users(); |
427 | } |
428 | iterator_range<const_user_iterator> users() const { |
429 | assertModuleIsMaterialized(); |
430 | return materialized_users(); |
431 | } |
432 | |
433 | /// Return true if there is exactly one use of this value. |
434 | /// |
435 | /// This is specialized because it is a common request and does not require |
436 | /// traversing the whole use list. |
437 | bool hasOneUse() const { |
438 | const_use_iterator I = use_begin(), E = use_end(); |
439 | if (I == E) return false; |
440 | return ++I == E; |
441 | } |
442 | |
443 | /// Return true if this Value has exactly N uses. |
444 | bool hasNUses(unsigned N) const; |
445 | |
446 | /// Return true if this value has N uses or more. |
447 | /// |
448 | /// This is logically equivalent to getNumUses() >= N. |
449 | bool hasNUsesOrMore(unsigned N) const; |
450 | |
451 | /// Return true if there is exactly one user of this value. |
452 | /// |
453 | /// Note that this is not the same as "has one use". If a value has one use, |
454 | /// then there certainly is a single user. But if value has several uses, |
455 | /// it is possible that all uses are in a single user, or not. |
456 | /// |
457 | /// This check is potentially costly, since it requires traversing, |
458 | /// in the worst case, the whole use list of a value. |
459 | bool hasOneUser() const; |
460 | |
461 | /// Return true if there is exactly one use of this value that cannot be |
462 | /// dropped. |
463 | /// |
464 | /// This is specialized because it is a common request and does not require |
465 | /// traversing the whole use list. |
466 | Use *getSingleUndroppableUse(); |
467 | |
468 | /// Return true if there this value. |
469 | /// |
470 | /// This is specialized because it is a common request and does not require |
471 | /// traversing the whole use list. |
472 | bool hasNUndroppableUses(unsigned N) const; |
473 | |
474 | /// Return true if this value has N uses or more. |
475 | /// |
476 | /// This is logically equivalent to getNumUses() >= N. |
477 | bool hasNUndroppableUsesOrMore(unsigned N) const; |
478 | |
479 | /// Remove every uses that can safely be removed. |
480 | /// |
481 | /// This will remove for example uses in llvm.assume. |
482 | /// This should be used when performing want to perform a tranformation but |
483 | /// some Droppable uses pervent it. |
484 | /// This function optionally takes a filter to only remove some droppable |
485 | /// uses. |
486 | void dropDroppableUses(llvm::function_ref<bool(const Use *)> ShouldDrop = |
487 | [](const Use *) { return true; }); |
488 | |
489 | /// Remove every use of this value in \p User that can safely be removed. |
490 | void dropDroppableUsesIn(User &Usr); |
491 | |
492 | /// Remove the droppable use \p U. |
493 | static void dropDroppableUse(Use &U); |
494 | |
495 | /// Check if this value is used in the specified basic block. |
496 | bool isUsedInBasicBlock(const BasicBlock *BB) const; |
497 | |
498 | /// This method computes the number of uses of this Value. |
499 | /// |
500 | /// This is a linear time operation. Use hasOneUse, hasNUses, or |
501 | /// hasNUsesOrMore to check for specific values. |
502 | unsigned getNumUses() const; |
503 | |
504 | /// This method should only be used by the Use class. |
505 | void addUse(Use &U) { U.addToList(&UseList); } |
506 | |
507 | /// Concrete subclass of this. |
508 | /// |
509 | /// An enumeration for keeping track of the concrete subclass of Value that |
510 | /// is actually instantiated. Values of this enumeration are kept in the |
511 | /// Value classes SubclassID field. They are used for concrete type |
512 | /// identification. |
513 | enum ValueTy { |
514 | #define HANDLE_VALUE(Name) Name##Val, |
515 | #include "llvm/IR/Value.def" |
516 | |
517 | // Markers: |
518 | #define HANDLE_CONSTANT_MARKER(Marker, Constant) Marker = Constant##Val, |
519 | #include "llvm/IR/Value.def" |
520 | }; |
521 | |
522 | /// Return an ID for the concrete type of this object. |
523 | /// |
524 | /// This is used to implement the classof checks. This should not be used |
525 | /// for any other purpose, as the values may change as LLVM evolves. Also, |
526 | /// note that for instructions, the Instruction's opcode is added to |
527 | /// InstructionVal. So this means three things: |
528 | /// # there is no value with code InstructionVal (no opcode==0). |
529 | /// # there are more possible values for the value type than in ValueTy enum. |
530 | /// # the InstructionVal enumerator must be the highest valued enumerator in |
531 | /// the ValueTy enum. |
532 | unsigned getValueID() const { |
533 | return SubclassID; |
534 | } |
535 | |
536 | /// Return the raw optional flags value contained in this value. |
537 | /// |
538 | /// This should only be used when testing two Values for equivalence. |
539 | unsigned getRawSubclassOptionalData() const { |
540 | return SubclassOptionalData; |
541 | } |
542 | |
543 | /// Clear the optional flags contained in this value. |
544 | void clearSubclassOptionalData() { |
545 | SubclassOptionalData = 0; |
546 | } |
547 | |
548 | /// Check the optional flags for equality. |
549 | bool hasSameSubclassOptionalData(const Value *V) const { |
550 | return SubclassOptionalData == V->SubclassOptionalData; |
551 | } |
552 | |
553 | /// Return true if there is a value handle associated with this value. |
554 | bool hasValueHandle() const { return HasValueHandle; } |
555 | |
556 | /// Return true if there is metadata referencing this value. |
557 | bool isUsedByMetadata() const { return IsUsedByMD; } |
558 | |
559 | protected: |
560 | /// Get the current metadata attachments for the given kind, if any. |
561 | /// |
562 | /// These functions require that the value have at most a single attachment |
563 | /// of the given kind, and return \c nullptr if such an attachment is missing. |
564 | /// @{ |
565 | MDNode *getMetadata(unsigned KindID) const; |
566 | MDNode *getMetadata(StringRef Kind) const; |
567 | /// @} |
568 | |
569 | /// Appends all attachments with the given ID to \c MDs in insertion order. |
570 | /// If the Value has no attachments with the given ID, or if ID is invalid, |
571 | /// leaves MDs unchanged. |
572 | /// @{ |
573 | void getMetadata(unsigned KindID, SmallVectorImpl<MDNode *> &MDs) const; |
574 | void getMetadata(StringRef Kind, SmallVectorImpl<MDNode *> &MDs) const; |
575 | /// @} |
576 | |
577 | /// Appends all metadata attached to this value to \c MDs, sorting by |
578 | /// KindID. The first element of each pair returned is the KindID, the second |
579 | /// element is the metadata value. Attachments with the same ID appear in |
580 | /// insertion order. |
581 | void |
582 | getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const; |
583 | |
584 | /// Return true if this value has any metadata attached to it. |
585 | bool hasMetadata() const { return (bool)HasMetadata; } |
586 | |
587 | /// Return true if this value has the given type of metadata attached. |
588 | /// @{ |
589 | bool hasMetadata(unsigned KindID) const { |
590 | return getMetadata(KindID) != nullptr; |
591 | } |
592 | bool hasMetadata(StringRef Kind) const { |
593 | return getMetadata(Kind) != nullptr; |
594 | } |
595 | /// @} |
596 | |
597 | /// Set a particular kind of metadata attachment. |
598 | /// |
599 | /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or |
600 | /// replacing it if it already exists. |
601 | /// @{ |
602 | void setMetadata(unsigned KindID, MDNode *Node); |
603 | void setMetadata(StringRef Kind, MDNode *Node); |
604 | /// @} |
605 | |
606 | /// Add a metadata attachment. |
607 | /// @{ |
608 | void addMetadata(unsigned KindID, MDNode &MD); |
609 | void addMetadata(StringRef Kind, MDNode &MD); |
610 | /// @} |
611 | |
612 | /// Erase all metadata attachments with the given kind. |
613 | /// |
614 | /// \returns true if any metadata was removed. |
615 | bool eraseMetadata(unsigned KindID); |
616 | |
617 | /// Erase all metadata attached to this Value. |
618 | void clearMetadata(); |
619 | |
620 | public: |
621 | /// Return true if this value is a swifterror value. |
622 | /// |
623 | /// swifterror values can be either a function argument or an alloca with a |
624 | /// swifterror attribute. |
625 | bool isSwiftError() const; |
626 | |
627 | /// Strip off pointer casts, all-zero GEPs and address space casts. |
628 | /// |
629 | /// Returns the original uncasted value. If this is called on a non-pointer |
630 | /// value, it returns 'this'. |
631 | const Value *stripPointerCasts() const; |
632 | Value *stripPointerCasts() { |
633 | return const_cast<Value *>( |
634 | static_cast<const Value *>(this)->stripPointerCasts()); |
635 | } |
636 | |
637 | /// Strip off pointer casts, all-zero GEPs, address space casts, and aliases. |
638 | /// |
639 | /// Returns the original uncasted value. If this is called on a non-pointer |
640 | /// value, it returns 'this'. |
641 | const Value *stripPointerCastsAndAliases() const; |
642 | Value *stripPointerCastsAndAliases() { |
643 | return const_cast<Value *>( |
644 | static_cast<const Value *>(this)->stripPointerCastsAndAliases()); |
645 | } |
646 | |
647 | /// Strip off pointer casts, all-zero GEPs and address space casts |
648 | /// but ensures the representation of the result stays the same. |
649 | /// |
650 | /// Returns the original uncasted value with the same representation. If this |
651 | /// is called on a non-pointer value, it returns 'this'. |
652 | const Value *stripPointerCastsSameRepresentation() const; |
653 | Value *stripPointerCastsSameRepresentation() { |
654 | return const_cast<Value *>(static_cast<const Value *>(this) |
655 | ->stripPointerCastsSameRepresentation()); |
656 | } |
657 | |
658 | /// Strip off pointer casts, all-zero GEPs and invariant group info. |
659 | /// |
660 | /// Returns the original uncasted value. If this is called on a non-pointer |
661 | /// value, it returns 'this'. This function should be used only in |
662 | /// Alias analysis. |
663 | const Value *stripPointerCastsAndInvariantGroups() const; |
664 | Value *stripPointerCastsAndInvariantGroups() { |
665 | return const_cast<Value *>(static_cast<const Value *>(this) |
666 | ->stripPointerCastsAndInvariantGroups()); |
667 | } |
668 | |
669 | /// Strip off pointer casts and all-constant inbounds GEPs. |
670 | /// |
671 | /// Returns the original pointer value. If this is called on a non-pointer |
672 | /// value, it returns 'this'. |
673 | const Value *stripInBoundsConstantOffsets() const; |
674 | Value *stripInBoundsConstantOffsets() { |
675 | return const_cast<Value *>( |
676 | static_cast<const Value *>(this)->stripInBoundsConstantOffsets()); |
677 | } |
678 | |
679 | /// Accumulate the constant offset this value has compared to a base pointer. |
680 | /// Only 'getelementptr' instructions (GEPs) are accumulated but other |
681 | /// instructions, e.g., casts, are stripped away as well. |
682 | /// The accumulated constant offset is added to \p Offset and the base |
683 | /// pointer is returned. |
684 | /// |
685 | /// The APInt \p Offset has to have a bit-width equal to the IntPtr type for |
686 | /// the address space of 'this' pointer value, e.g., use |
687 | /// DataLayout::getIndexTypeSizeInBits(Ty). |
688 | /// |
689 | /// If \p AllowNonInbounds is true, offsets in GEPs are stripped and |
690 | /// accumulated even if the GEP is not "inbounds". |
691 | /// |
692 | /// If \p ExternalAnalysis is provided it will be used to calculate a offset |
693 | /// when a operand of GEP is not constant. |
694 | /// For example, for a value \p ExternalAnalysis might try to calculate a |
695 | /// lower bound. If \p ExternalAnalysis is successful, it should return true. |
696 | /// |
697 | /// If this is called on a non-pointer value, it returns 'this' and the |
698 | /// \p Offset is not modified. |
699 | /// |
700 | /// Note that this function will never return a nullptr. It will also never |
701 | /// manipulate the \p Offset in a way that would not match the difference |
702 | /// between the underlying value and the returned one. Thus, if no constant |
703 | /// offset was found, the returned value is the underlying one and \p Offset |
704 | /// is unchanged. |
705 | const Value *stripAndAccumulateConstantOffsets( |
706 | const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, |
707 | function_ref<bool(Value &Value, APInt &Offset)> ExternalAnalysis = |
708 | nullptr) const; |
709 | Value *stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, |
710 | bool AllowNonInbounds) { |
711 | return const_cast<Value *>( |
712 | static_cast<const Value *>(this)->stripAndAccumulateConstantOffsets( |
713 | DL, Offset, AllowNonInbounds)); |
714 | } |
715 | |
716 | /// This is a wrapper around stripAndAccumulateConstantOffsets with the |
717 | /// in-bounds requirement set to false. |
718 | const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, |
719 | APInt &Offset) const { |
720 | return stripAndAccumulateConstantOffsets(DL, Offset, |
721 | /* AllowNonInbounds */ false); |
722 | } |
723 | Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, |
724 | APInt &Offset) { |
725 | return stripAndAccumulateConstantOffsets(DL, Offset, |
726 | /* AllowNonInbounds */ false); |
727 | } |
728 | |
729 | /// Strip off pointer casts and inbounds GEPs. |
730 | /// |
731 | /// Returns the original pointer value. If this is called on a non-pointer |
732 | /// value, it returns 'this'. |
733 | const Value *stripInBoundsOffsets(function_ref<void(const Value *)> Func = |
734 | [](const Value *) {}) const; |
735 | inline Value *stripInBoundsOffsets(function_ref<void(const Value *)> Func = |
736 | [](const Value *) {}) { |
737 | return const_cast<Value *>( |
738 | static_cast<const Value *>(this)->stripInBoundsOffsets(Func)); |
739 | } |
740 | |
741 | /// Returns the number of bytes known to be dereferenceable for the |
742 | /// pointer value. |
743 | /// |
744 | /// If CanBeNull is set by this function the pointer can either be null or be |
745 | /// dereferenceable up to the returned number of bytes. |
746 | uint64_t getPointerDereferenceableBytes(const DataLayout &DL, |
747 | bool &CanBeNull) const; |
748 | |
749 | /// Returns an alignment of the pointer value. |
750 | /// |
751 | /// Returns an alignment which is either specified explicitly, e.g. via |
752 | /// align attribute of a function argument, or guaranteed by DataLayout. |
753 | Align getPointerAlignment(const DataLayout &DL) const; |
754 | |
755 | /// Translate PHI node to its predecessor from the given basic block. |
756 | /// |
757 | /// If this value is a PHI node with CurBB as its parent, return the value in |
758 | /// the PHI node corresponding to PredBB. If not, return ourself. This is |
759 | /// useful if you want to know the value something has in a predecessor |
760 | /// block. |
761 | const Value *DoPHITranslation(const BasicBlock *CurBB, |
762 | const BasicBlock *PredBB) const; |
763 | Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) { |
764 | return const_cast<Value *>( |
765 | static_cast<const Value *>(this)->DoPHITranslation(CurBB, PredBB)); |
766 | } |
767 | |
768 | /// The maximum alignment for instructions. |
769 | /// |
770 | /// This is the greatest alignment value supported by load, store, and alloca |
771 | /// instructions, and global values. |
772 | static const unsigned MaxAlignmentExponent = 29; |
773 | static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent; |
774 | |
775 | /// Mutate the type of this Value to be of the specified type. |
776 | /// |
777 | /// Note that this is an extremely dangerous operation which can create |
778 | /// completely invalid IR very easily. It is strongly recommended that you |
779 | /// recreate IR objects with the right types instead of mutating them in |
780 | /// place. |
781 | void mutateType(Type *Ty) { |
782 | VTy = Ty; |
783 | } |
784 | |
785 | /// Sort the use-list. |
786 | /// |
787 | /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is |
788 | /// expected to compare two \a Use references. |
789 | template <class Compare> void sortUseList(Compare Cmp); |
790 | |
791 | /// Reverse the use-list. |
792 | void reverseUseList(); |
793 | |
794 | private: |
795 | /// Merge two lists together. |
796 | /// |
797 | /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes |
798 | /// "equal" items from L before items from R. |
799 | /// |
800 | /// \return the first element in the list. |
801 | /// |
802 | /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update). |
803 | template <class Compare> |
804 | static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) { |
805 | Use *Merged; |
806 | Use **Next = &Merged; |
807 | |
808 | while (true) { |
809 | if (!L) { |
810 | *Next = R; |
811 | break; |
812 | } |
813 | if (!R) { |
814 | *Next = L; |
815 | break; |
816 | } |
817 | if (Cmp(*R, *L)) { |
818 | *Next = R; |
819 | Next = &R->Next; |
820 | R = R->Next; |
821 | } else { |
822 | *Next = L; |
823 | Next = &L->Next; |
824 | L = L->Next; |
825 | } |
826 | } |
827 | |
828 | return Merged; |
829 | } |
830 | |
831 | protected: |
832 | unsigned short getSubclassDataFromValue() const { return SubclassData; } |
833 | void setValueSubclassData(unsigned short D) { SubclassData = D; } |
834 | }; |
835 | |
836 | struct ValueDeleter { void operator()(Value *V) { V->deleteValue(); } }; |
837 | |
838 | /// Use this instead of std::unique_ptr<Value> or std::unique_ptr<Instruction>. |
839 | /// Those don't work because Value and Instruction's destructors are protected, |
840 | /// aren't virtual, and won't destroy the complete object. |
841 | using unique_value = std::unique_ptr<Value, ValueDeleter>; |
842 | |
843 | inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) { |
844 | V.print(OS); |
845 | return OS; |
846 | } |
847 | |
848 | void Use::set(Value *V) { |
849 | if (Val) removeFromList(); |
850 | Val = V; |
851 | if (V) V->addUse(*this); |
852 | } |
853 | |
854 | Value *Use::operator=(Value *RHS) { |
855 | set(RHS); |
856 | return RHS; |
857 | } |
858 | |
859 | const Use &Use::operator=(const Use &RHS) { |
860 | set(RHS.Val); |
861 | return *this; |
862 | } |
863 | |
864 | template <class Compare> void Value::sortUseList(Compare Cmp) { |
865 | if (!UseList || !UseList->Next) |
866 | // No need to sort 0 or 1 uses. |
867 | return; |
868 | |
869 | // Note: this function completely ignores Prev pointers until the end when |
870 | // they're fixed en masse. |
871 | |
872 | // Create a binomial vector of sorted lists, visiting uses one at a time and |
873 | // merging lists as necessary. |
874 | const unsigned MaxSlots = 32; |
875 | Use *Slots[MaxSlots]; |
876 | |
877 | // Collect the first use, turning it into a single-item list. |
878 | Use *Next = UseList->Next; |
879 | UseList->Next = nullptr; |
880 | unsigned NumSlots = 1; |
881 | Slots[0] = UseList; |
882 | |
883 | // Collect all but the last use. |
884 | while (Next->Next) { |
885 | Use *Current = Next; |
886 | Next = Current->Next; |
887 | |
888 | // Turn Current into a single-item list. |
889 | Current->Next = nullptr; |
890 | |
891 | // Save Current in the first available slot, merging on collisions. |
892 | unsigned I; |
893 | for (I = 0; I < NumSlots; ++I) { |
894 | if (!Slots[I]) |
895 | break; |
896 | |
897 | // Merge two lists, doubling the size of Current and emptying slot I. |
898 | // |
899 | // Since the uses in Slots[I] originally preceded those in Current, send |
900 | // Slots[I] in as the left parameter to maintain a stable sort. |
901 | Current = mergeUseLists(Slots[I], Current, Cmp); |
902 | Slots[I] = nullptr; |
903 | } |
904 | // Check if this is a new slot. |
905 | if (I == NumSlots) { |
906 | ++NumSlots; |
907 | assert(NumSlots <= MaxSlots && "Use list bigger than 2^32")((NumSlots <= MaxSlots && "Use list bigger than 2^32" ) ? static_cast<void> (0) : __assert_fail ("NumSlots <= MaxSlots && \"Use list bigger than 2^32\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/include/llvm/IR/Value.h" , 907, __PRETTY_FUNCTION__)); |
908 | } |
909 | |
910 | // Found an open slot. |
911 | Slots[I] = Current; |
912 | } |
913 | |
914 | // Merge all the lists together. |
915 | assert(Next && "Expected one more Use")((Next && "Expected one more Use") ? static_cast<void > (0) : __assert_fail ("Next && \"Expected one more Use\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/include/llvm/IR/Value.h" , 915, __PRETTY_FUNCTION__)); |
916 | assert(!Next->Next && "Expected only one Use")((!Next->Next && "Expected only one Use") ? static_cast <void> (0) : __assert_fail ("!Next->Next && \"Expected only one Use\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/include/llvm/IR/Value.h" , 916, __PRETTY_FUNCTION__)); |
917 | UseList = Next; |
918 | for (unsigned I = 0; I < NumSlots; ++I) |
919 | if (Slots[I]) |
920 | // Since the uses in Slots[I] originally preceded those in UseList, send |
921 | // Slots[I] in as the left parameter to maintain a stable sort. |
922 | UseList = mergeUseLists(Slots[I], UseList, Cmp); |
923 | |
924 | // Fix the Prev pointers. |
925 | for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) { |
926 | I->Prev = Prev; |
927 | Prev = &I->Next; |
928 | } |
929 | } |
930 | |
931 | // isa - Provide some specializations of isa so that we don't have to include |
932 | // the subtype header files to test to see if the value is a subclass... |
933 | // |
934 | template <> struct isa_impl<Constant, Value> { |
935 | static inline bool doit(const Value &Val) { |
936 | static_assert(Value::ConstantFirstVal == 0, "Val.getValueID() >= Value::ConstantFirstVal"); |
937 | return Val.getValueID() <= Value::ConstantLastVal; |
938 | } |
939 | }; |
940 | |
941 | template <> struct isa_impl<ConstantData, Value> { |
942 | static inline bool doit(const Value &Val) { |
943 | return Val.getValueID() >= Value::ConstantDataFirstVal && |
944 | Val.getValueID() <= Value::ConstantDataLastVal; |
945 | } |
946 | }; |
947 | |
948 | template <> struct isa_impl<ConstantAggregate, Value> { |
949 | static inline bool doit(const Value &Val) { |
950 | return Val.getValueID() >= Value::ConstantAggregateFirstVal && |
951 | Val.getValueID() <= Value::ConstantAggregateLastVal; |
952 | } |
953 | }; |
954 | |
955 | template <> struct isa_impl<Argument, Value> { |
956 | static inline bool doit (const Value &Val) { |
957 | return Val.getValueID() == Value::ArgumentVal; |
958 | } |
959 | }; |
960 | |
961 | template <> struct isa_impl<InlineAsm, Value> { |
962 | static inline bool doit(const Value &Val) { |
963 | return Val.getValueID() == Value::InlineAsmVal; |
964 | } |
965 | }; |
966 | |
967 | template <> struct isa_impl<Instruction, Value> { |
968 | static inline bool doit(const Value &Val) { |
969 | return Val.getValueID() >= Value::InstructionVal; |
970 | } |
971 | }; |
972 | |
973 | template <> struct isa_impl<BasicBlock, Value> { |
974 | static inline bool doit(const Value &Val) { |
975 | return Val.getValueID() == Value::BasicBlockVal; |
976 | } |
977 | }; |
978 | |
979 | template <> struct isa_impl<Function, Value> { |
980 | static inline bool doit(const Value &Val) { |
981 | return Val.getValueID() == Value::FunctionVal; |
982 | } |
983 | }; |
984 | |
985 | template <> struct isa_impl<GlobalVariable, Value> { |
986 | static inline bool doit(const Value &Val) { |
987 | return Val.getValueID() == Value::GlobalVariableVal; |
988 | } |
989 | }; |
990 | |
991 | template <> struct isa_impl<GlobalAlias, Value> { |
992 | static inline bool doit(const Value &Val) { |
993 | return Val.getValueID() == Value::GlobalAliasVal; |
994 | } |
995 | }; |
996 | |
997 | template <> struct isa_impl<GlobalIFunc, Value> { |
998 | static inline bool doit(const Value &Val) { |
999 | return Val.getValueID() == Value::GlobalIFuncVal; |
1000 | } |
1001 | }; |
1002 | |
1003 | template <> struct isa_impl<GlobalIndirectSymbol, Value> { |
1004 | static inline bool doit(const Value &Val) { |
1005 | return isa<GlobalAlias>(Val) || isa<GlobalIFunc>(Val); |
1006 | } |
1007 | }; |
1008 | |
1009 | template <> struct isa_impl<GlobalValue, Value> { |
1010 | static inline bool doit(const Value &Val) { |
1011 | return isa<GlobalObject>(Val) || isa<GlobalIndirectSymbol>(Val); |
1012 | } |
1013 | }; |
1014 | |
1015 | template <> struct isa_impl<GlobalObject, Value> { |
1016 | static inline bool doit(const Value &Val) { |
1017 | return isa<GlobalVariable>(Val) || isa<Function>(Val); |
1018 | } |
1019 | }; |
1020 | |
1021 | // Create wrappers for C Binding types (see CBindingWrapping.h). |
1022 | DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)inline Value *unwrap(LLVMValueRef P) { return reinterpret_cast <Value*>(P); } inline LLVMValueRef wrap(const Value *P) { return reinterpret_cast<LLVMValueRef>(const_cast< Value*>(P)); } template<typename T> inline T *unwrap (LLVMValueRef P) { return cast<T>(unwrap(P)); } |
1023 | |
1024 | // Specialized opaque value conversions. |
1025 | inline Value **unwrap(LLVMValueRef *Vals) { |
1026 | return reinterpret_cast<Value**>(Vals); |
1027 | } |
1028 | |
1029 | template<typename T> |
1030 | inline T **unwrap(LLVMValueRef *Vals, unsigned Length) { |
1031 | #ifndef NDEBUG |
1032 | for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I) |
1033 | unwrap<T>(*I); // For side effect of calling assert on invalid usage. |
1034 | #endif |
1035 | (void)Length; |
1036 | return reinterpret_cast<T**>(Vals); |
1037 | } |
1038 | |
1039 | inline LLVMValueRef *wrap(const Value **Vals) { |
1040 | return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals)); |
1041 | } |
1042 | |
1043 | } // end namespace llvm |
1044 | |
1045 | #endif // LLVM_IR_VALUE_H |