LLVM 24.0.0git
FunctionComparator.h
Go to the documentation of this file.
1//===- FunctionComparator.h - Function Comparator ---------------*- 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 defines the FunctionComparator and GlobalNumberState classes which
10// are used by the MergeFunctions pass for comparing functions.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_TRANSFORMS_UTILS_FUNCTIONCOMPARATOR_H
15#define LLVM_TRANSFORMS_UTILS_FUNCTIONCOMPARATOR_H
16
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/StringRef.h"
20#include "llvm/IR/Operator.h"
21#include "llvm/IR/ValueMap.h"
25#include <cstdint>
26#include <tuple>
27
28namespace llvm {
29
30class APFloat;
31class AttributeList;
32class APInt;
33class BasicBlock;
34class Constant;
35class Function;
36class GlobalValue;
37class InlineAsm;
38class Instruction;
39class MDNode;
40class Type;
41class Value;
42
43/// GlobalNumberState assigns an integer to each global value in the program,
44/// which is used by the comparison routine to order references to globals. This
45/// state must be preserved throughout the pass, because Functions and other
46/// globals need to maintain their relative order. Globals are assigned a number
47/// when they are first visited. This order is deterministic, and so the
48/// assigned numbers are as well. When two functions are merged, neither number
49/// is updated. If the symbols are weak, this would be incorrect. If they are
50/// strong, then one will be replaced at all references to the other, and so
51/// direct callsites will now see one or the other symbol, and no update is
52/// necessary. Note that if we were guaranteed unique names, we could just
53/// compare those, but this would not work for stripped bitcodes or for those
54/// few symbols without a name.
56 struct Config : ValueMapConfig<GlobalValue *> {
57 enum { FollowRAUW = false };
58 };
59
60 // Each GlobalValue is mapped to an identifier. The Config ensures when RAUW
61 // occurs, the mapping does not change. Tracking changes is unnecessary, and
62 // also problematic for weak symbols (which may be overwritten).
63 using ValueNumberMap = ValueMap<GlobalValue *, uint64_t, Config>;
64 ValueNumberMap GlobalNumbers;
65
66 // The next unused serial number to assign to a global.
67 uint64_t NextNumber = 0;
68
69public:
70 GlobalNumberState() = default;
71
74 bool Inserted;
75 std::tie(MapIter, Inserted) = GlobalNumbers.insert({Global, NextNumber});
76 if (Inserted)
77 NextNumber++;
78 return MapIter->second;
79 }
80
82 GlobalNumbers.erase(Global);
83 }
84
85 void clear() {
86 GlobalNumbers.clear();
87 }
88};
89
90/// FunctionComparator - Compares two functions to determine whether or not
91/// they will generate machine code with the same behaviour. DataLayout is
92/// used if available. The comparator always fails conservatively (erring on the
93/// side of claiming that two functions are different).
95public:
96 FunctionComparator(const Function *F1, const Function *F2,
98 : FnL(F1), FnR(F2), GlobalNumbers(GN) {}
99
100 /// Test whether the two functions have equivalent behaviour.
101 LLVM_ABI int compare();
102
103protected:
104 /// Start the comparison.
106 sn_mapL.clear();
107 sn_mapR.clear();
108 }
109
110 /// Compares the signature and other general attributes of the two functions.
111 LLVM_ABI int compareSignature() const;
112
113 /// Test whether two basic blocks have equivalent behaviour.
114 LLVM_ABI int cmpBasicBlocks(const BasicBlock *BBL,
115 const BasicBlock *BBR) const;
116
117 /// Constants comparison.
118 /// Its analog to lexicographical comparison between hypothetical numbers
119 /// of next format:
120 /// <bitcastability-trait><raw-bit-contents>
121 ///
122 /// 1. Bitcastability.
123 /// Check whether L's type could be losslessly bitcasted to R's type.
124 /// On this stage method, in case when lossless bitcast is not possible
125 /// method returns -1 or 1, thus also defining which type is greater in
126 /// context of bitcastability.
127 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
128 /// to the contents comparison.
129 /// If types differ, remember types comparison result and check
130 /// whether we still can bitcast types.
131 /// Stage 1: Types that satisfies isFirstClassType conditions are always
132 /// greater then others.
133 /// Stage 2: Vector is greater then non-vector.
134 /// If both types are vectors, then vector with greater bitwidth is
135 /// greater.
136 /// If both types are vectors with the same bitwidth, then types
137 /// are bitcastable, and we can skip other stages, and go to contents
138 /// comparison.
139 /// Stage 3: Pointer types are greater than non-pointers. If both types are
140 /// pointers of the same address space - go to contents comparison.
141 /// Different address spaces: pointer with greater address space is
142 /// greater.
143 /// Stage 4: Types are neither vectors, nor pointers. And they differ.
144 /// We don't know how to bitcast them. So, we better don't do it,
145 /// and return types comparison result (so it determines the
146 /// relationship among constants we don't know how to bitcast).
147 ///
148 /// Just for clearance, let's see how the set of constants could look
149 /// on single dimension axis:
150 ///
151 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
152 /// Where: NFCT - Not a FirstClassType
153 /// FCT - FirstClassTyp:
154 ///
155 /// 2. Compare raw contents.
156 /// It ignores types on this stage and only compares bits from L and R.
157 /// Returns 0, if L and R has equivalent contents.
158 /// -1 or 1 if values are different.
159 /// Pretty trivial:
160 /// 2.1. If contents are numbers, compare numbers.
161 /// Ints with greater bitwidth are greater. Ints with same bitwidths
162 /// compared by their contents.
163 /// 2.2. "And so on". Just to avoid discrepancies with comments
164 /// perhaps it would be better to read the implementation itself.
165 /// 3. And again about overall picture. Let's look back at how the ordered set
166 /// of constants will look like:
167 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
168 ///
169 /// Now look, what could be inside [FCT, "others"], for example:
170 /// [FCT, "others"] =
171 /// [
172 /// [double 0.1], [double 1.23],
173 /// [i32 1], [i32 2],
174 /// { double 1.0 }, ; StructTyID, NumElements = 1
175 /// { i32 1 }, ; StructTyID, NumElements = 1
176 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
177 /// { i32 1, double 1 } ; StructTyID, NumElements = 2
178 /// ]
179 ///
180 /// Let's explain the order. Float numbers will be less than integers, just
181 /// because of cmpType terms: FloatTyID < IntegerTyID.
182 /// Floats (with same fltSemantics) are sorted according to their value.
183 /// Then you can see integers, and they are, like a floats,
184 /// could be easy sorted among each others.
185 /// The structures. Structures are grouped at the tail, again because of their
186 /// TypeID: StructTyID > IntegerTyID > FloatTyID.
187 /// Structures with greater number of elements are greater. Structures with
188 /// greater elements going first are greater.
189 /// The same logic with vectors, arrays and other possible complex types.
190 ///
191 /// Bitcastable constants.
192 /// Let's assume, that some constant, belongs to some group of
193 /// "so-called-equal" values with different types, and at the same time
194 /// belongs to another group of constants with equal types
195 /// and "really" equal values.
196 ///
197 /// Now, prove that this is impossible:
198 ///
199 /// If constant A with type TyA is bitcastable to B with type TyB, then:
200 /// 1. All constants with equal types to TyA, are bitcastable to B. Since
201 /// those should be vectors (if TyA is vector), pointers
202 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
203 /// be equal to TyB.
204 /// 2. All constants with non-equal, but bitcastable types to TyA, are
205 /// bitcastable to B.
206 /// Once again, just because we allow it to vectors and pointers only.
207 /// This statement could be expanded as below:
208 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
209 /// vector B, and thus bitcastable to B as well.
210 /// 2.2. All pointers of the same address space, no matter what they point to,
211 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
212 /// So any constant equal or bitcastable to A is equal or bitcastable to B.
213 /// QED.
214 ///
215 /// In another words, for pointers and vectors, we ignore top-level type and
216 /// look at their particular properties (bit-width for vectors, and
217 /// address space for pointers).
218 /// If these properties are equal - compare their contents.
219 LLVM_ABI int cmpConstants(const Constant *L, const Constant *R) const;
220
221 /// Compares two global values by number. Uses the GlobalNumbersState to
222 /// identify the same gobals across function calls.
224
225 /// Assign or look up previously assigned numbers for the two values, and
226 /// return whether the numbers are equal. Numbers are assigned in the order
227 /// visited.
228 /// Comparison order:
229 /// Stage 1: Constants are greater than non-constants.
230 /// If both left and right are constants, then the result of
231 /// cmpConstants is used as cmpValues result.
232 /// Stage 2: InlineAsm instances are greater than others. If both left and
233 /// right are InlineAsm instances, InlineAsm* pointers casted to
234 /// integers and compared as numbers.
235 /// Stage 3: For all other cases we compare order we meet these values in
236 /// their functions. If right value was met first during scanning,
237 /// then left value is greater.
238 /// In another words, we compare serial numbers, for more details
239 /// see comments for sn_mapL and sn_mapR.
240 LLVM_ABI int cmpValues(const Value *L, const Value *R) const;
241
242 /// References to the functions being compared are equal. Used for
243 /// corresponding call targets and blockaddress functions, which stay
244 /// valid if MergeFunc replaces one body with a forwarding thunk.
245 int cmpValuesAllowingSelfRef(const Value *L, const Value *R) const;
246
247 /// Compare two Instructions for equivalence, similar to
248 /// Instruction::isSameOperationAs.
249 ///
250 /// Stages are listed in "most significant stage first" order:
251 /// On each stage below, we do comparison between some left and right
252 /// operation parts. If parts are non-equal, we assign parts comparison
253 /// result to the operation comparison result and exit from method.
254 /// Otherwise we proceed to the next stage.
255 /// Stages:
256 /// 1. Operations opcodes. Compared as numbers.
257 /// 2. Number of operands.
258 /// 3. Operation types. Compared with cmpType method.
259 /// 4. Compare operation subclass optional data as stream of bytes:
260 /// just convert it to integers and call cmpNumbers.
261 /// 5. Compare in operation operand types with cmpType in
262 /// most significant operand first order.
263 /// 6. Last stage. Check operations for some specific attributes.
264 /// For example, for Load it would be:
265 /// 6.1.Load: volatile (as boolean flag)
266 /// 6.2.Load: alignment (as integer numbers)
267 /// 6.3.Load: ordering (as underlying enum class value)
268 /// 6.4.Load: sync-scope (as integer numbers)
269 /// 6.5.Load: range metadata (as integer ranges)
270 /// On this stage its better to see the code, since its not more than 10-15
271 /// strings for particular instruction, and could change sometimes.
272 ///
273 /// Sets \p needToCmpOperands to true if the operands of the instructions
274 /// still must be compared afterwards. In this case it's already guaranteed
275 /// that both instructions have the same number of operands.
276 LLVM_ABI int cmpOperations(const Instruction *L, const Instruction *R,
277 bool &needToCmpOperands) const;
278
279 /// cmpType - compares two types,
280 /// defines total ordering among the types set.
281 ///
282 /// Return values:
283 /// 0 if types are equal,
284 /// -1 if Left is less than Right,
285 /// +1 if Left is greater than Right.
286 ///
287 /// Description:
288 /// Comparison is broken onto stages. Like in lexicographical comparison
289 /// stage coming first has higher priority.
290 /// On each explanation stage keep in mind total ordering properties.
291 ///
292 /// 0. Before comparison we coerce pointer types of 0 address space to
293 /// integer.
294 /// We also don't bother with same type at left and right, so
295 /// just return 0 in this case.
296 ///
297 /// 1. If types are of different kind (different type IDs).
298 /// Return result of type IDs comparison, treating them as numbers.
299 /// 2. If types are integers, check that they have the same width. If they
300 /// are vectors, check that they have the same count and subtype.
301 /// 3. Types have the same ID, so check whether they are one of:
302 /// * Void
303 /// * Float
304 /// * Double
305 /// * X86_FP80
306 /// * FP128
307 /// * PPC_FP128
308 /// * Label
309 /// * Metadata
310 /// We can treat these types as equal whenever their IDs are same.
311 /// 4. If Left and Right are pointers, return result of address space
312 /// comparison (numbers comparison). We can treat pointer types of same
313 /// address space as equal.
314 /// 5. If types are complex.
315 /// Then both Left and Right are to be expanded and their element types will
316 /// be checked with the same way. If we get Res != 0 on some stage, return it.
317 /// Otherwise return 0.
318 /// 6. For all other cases put llvm_unreachable.
319 LLVM_ABI int cmpTypes(Type *TyL, Type *TyR) const;
320
321 LLVM_ABI int cmpNumbers(uint64_t L, uint64_t R) const;
322 LLVM_ABI int cmpAligns(Align L, Align R) const;
323 LLVM_ABI int cmpAPInts(const APInt &L, const APInt &R) const;
325 const ConstantRange &R) const;
326 LLVM_ABI int cmpAPFloats(const APFloat &L, const APFloat &R) const;
327 LLVM_ABI int cmpMem(StringRef L, StringRef R) const;
328
329 // The two functions undergoing comparison.
330 const Function *FnL, *FnR;
331
332private:
333 int cmpOrderings(AtomicOrdering L, AtomicOrdering R) const;
334 int cmpInlineAsm(const InlineAsm *L, const InlineAsm *R) const;
335 int cmpAttrs(const AttributeList L, const AttributeList R) const;
336 int cmpMDNode(const MDNode *L, const MDNode *R) const;
337 int cmpMetadata(const Metadata *L, const Metadata *R) const;
338 int cmpInstMetadata(Instruction const *L, Instruction const *R) const;
339 int cmpOperandBundlesSchema(const CallBase &LCS, const CallBase &RCS) const;
340
341 /// Compare two GEPs for equivalent pointer arithmetic.
342 /// Parts to be compared for each comparison stage,
343 /// most significant stage first:
344 /// 1. Address space. As numbers.
345 /// 2. Constant offset, (using GEPOperator::accumulateConstantOffset method).
346 /// 3. Pointer operand type (using cmpType method).
347 /// 4. Number of operands.
348 /// 5. Compare operands, using cmpValues method.
349 LLVM_ABI int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR) const;
350 int cmpGEPs(const GetElementPtrInst *GEPL,
351 const GetElementPtrInst *GEPR) const {
352 return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
353 }
354
355 /// Assign serial numbers to values from left function, and values from
356 /// right function.
357 /// Explanation:
358 /// Being comparing functions we need to compare values we meet at left and
359 /// right sides.
360 /// Its easy to sort things out for external values. It just should be
361 /// the same value at left and right.
362 /// But for local values (those were introduced inside function body)
363 /// we have to ensure they were introduced at exactly the same place,
364 /// and plays the same role.
365 /// Let's assign serial number to each value when we meet it first time.
366 /// Values that were met at same place will be with same serial numbers.
367 /// In this case it would be good to explain few points about values assigned
368 /// to BBs and other ways of implementation (see below).
369 ///
370 /// 1. Safety of BB reordering.
371 /// It's safe to change the order of BasicBlocks in function.
372 /// Relationship with other functions and serial numbering will not be
373 /// changed in this case.
374 /// As follows from FunctionComparator::compare(), we do CFG walk: we start
375 /// from the entry, and then take each terminator. So it doesn't matter how in
376 /// fact BBs are ordered in function. And since cmpValues are called during
377 /// this walk, the numbering depends only on how BBs located inside the CFG.
378 /// So the answer is - yes. We will get the same numbering.
379 ///
380 /// 2. Impossibility to use dominance properties of values.
381 /// If we compare two instruction operands: first is usage of local
382 /// variable AL from function FL, and second is usage of local variable AR
383 /// from FR, we could compare their origins and check whether they are
384 /// defined at the same place.
385 /// But, we are still not able to compare operands of PHI nodes, since those
386 /// could be operands from further BBs we didn't scan yet.
387 /// So it's impossible to use dominance properties in general.
388 mutable DenseMap<const Value*, int> sn_mapL, sn_mapR;
389
390 // The global state we will use
391 GlobalNumberState* GlobalNumbers;
392};
393
394} // end namespace llvm
395
396#endif // LLVM_TRANSFORMS_UTILS_FUNCTIONCOMPARATOR_H
unsigned uint64_t
Atomic ordering constants.
#define LLVM_ABI
Definition Compiler.h:215
This file defines the DenseMap class.
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class represents a range of values.
This is an important base class in LLVM.
Definition Constant.h:43
FunctionComparator(const Function *F1, const Function *F2, GlobalNumberState *GN)
LLVM_ABI int cmpBasicBlocks(const BasicBlock *BBL, const BasicBlock *BBR) const
Test whether two basic blocks have equivalent behaviour.
LLVM_ABI int cmpConstantRanges(const ConstantRange &L, const ConstantRange &R) const
LLVM_ABI int compareSignature() const
Compares the signature and other general attributes of the two functions.
LLVM_ABI int cmpMem(StringRef L, StringRef R) const
LLVM_ABI int compare()
Test whether the two functions have equivalent behaviour.
LLVM_ABI int cmpAPFloats(const APFloat &L, const APFloat &R) const
LLVM_ABI int cmpTypes(Type *TyL, Type *TyR) const
cmpType - compares two types, defines total ordering among the types set.
LLVM_ABI int cmpOperations(const Instruction *L, const Instruction *R, bool &needToCmpOperands) const
Compare two Instructions for equivalence, similar to Instruction::isSameOperationAs.
LLVM_ABI int cmpNumbers(uint64_t L, uint64_t R) const
LLVM_ABI int cmpAligns(Align L, Align R) const
void beginCompare()
Start the comparison.
LLVM_ABI int cmpValues(const Value *L, const Value *R) const
Assign or look up previously assigned numbers for the two values, and return whether the numbers are ...
LLVM_ABI int cmpGlobalValues(GlobalValue *L, GlobalValue *R) const
Compares two global values by number.
int cmpValuesAllowingSelfRef(const Value *L, const Value *R) const
References to the functions being compared are equal.
LLVM_ABI int cmpConstants(const Constant *L, const Constant *R) const
Constants comparison.
LLVM_ABI int cmpAPInts(const APInt &L, const APInt &R) const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
GlobalNumberState assigns an integer to each global value in the program, which is used by the compar...
void erase(GlobalValue *Global)
uint64_t getNumber(GlobalValue *Global)
Metadata node.
Definition Metadata.h:1069
Root of the metadata hierarchy.
Definition Metadata.h:64
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
See the file comment.
Definition ValueMap.h:84
ValueMapIteratorImpl< MapT, GlobalValue *, false > iterator
Definition ValueMap.h:135
LLVM Value Representation.
Definition Value.h:75
This is an optimization pass for GlobalISel generic memory operations.
@ Global
Append to llvm.global_dtors.
AtomicOrdering
Atomic ordering for LLVM's memory model.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This class defines the default behavior for configurable aspects of ValueMap<>.
Definition ValueMap.h:53
std::conditional_t< IsConst, const ValueT &, ValueT & > second
Definition ValueMap.h:338