MergeFunctions.rst 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. =================================
  2. MergeFunctions pass, how it works
  3. =================================
  4. .. contents::
  5. :local:
  6. Introduction
  7. ============
  8. Sometimes code contains equal functions, or functions that does exactly the same
  9. thing even though they are non-equal on the IR level (e.g.: multiplication on 2
  10. and 'shl 1'). It could happen due to several reasons: mainly, the usage of
  11. templates and automatic code generators. Though, sometimes the user itself could
  12. write the same thing twice :-)
  13. The main purpose of this pass is to recognize such functions and merge them.
  14. This document is the extension to pass comments and describes the pass logic. It
  15. describes the algorithm that is used in order to compare functions and
  16. explains how we could combine equal functions correctly to keep the module
  17. valid.
  18. Material is brought in a top-down form, so the reader could start to learn pass
  19. from high level ideas and end with low-level algorithm details, thus preparing
  20. him or her for reading the sources.
  21. The main goal is to describe the algorithm and logic here and the concept. If
  22. you *don't want* to read the source code, but want to understand pass
  23. algorithms, this document is good for you. The author tries not to repeat the
  24. source-code and covers only common cases to avoid the cases of needing to
  25. update this document after any minor code changes.
  26. What should I know to be able to follow along with this document?
  27. -----------------------------------------------------------------
  28. The reader should be familiar with common compile-engineering principles and
  29. LLVM code fundamentals. In this article, we assume the reader is familiar with
  30. `Single Static Assignment
  31. <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_
  32. concept and has an understanding of
  33. `IR structure <http://llvm.org/docs/LangRef.html#high-level-structure>`_.
  34. We will use terms such as
  35. "`module <http://llvm.org/docs/LangRef.html#high-level-structure>`_",
  36. "`function <http://llvm.org/docs/ProgrammersManual.html#the-function-class>`_",
  37. "`basic block <http://en.wikipedia.org/wiki/Basic_block>`_",
  38. "`user <http://llvm.org/docs/ProgrammersManual.html#the-user-class>`_",
  39. "`value <http://llvm.org/docs/ProgrammersManual.html#the-value-class>`_",
  40. "`instruction
  41. <http://llvm.org/docs/ProgrammersManual.html#the-instruction-class>`_".
  42. As a good starting point, the Kaleidoscope tutorial can be used:
  43. :doc:`tutorial/index`
  44. It's especially important to understand chapter 3 of tutorial:
  45. :doc:`tutorial/LangImpl03`
  46. The reader should also know how passes work in LLVM. They could use this
  47. article as a reference and start point here:
  48. :doc:`WritingAnLLVMPass`
  49. What else? Well perhaps the reader should also have some experience in LLVM pass
  50. debugging and bug-fixing.
  51. Narrative structure
  52. -------------------
  53. The article consists of three parts. The first part explains pass functionality
  54. on the top-level. The second part describes the comparison procedure itself.
  55. The third part describes the merging process.
  56. In every part, the author tries to put the contents in the top-down form.
  57. The top-level methods will first be described followed by the terminal ones at
  58. the end, in the tail of each part. If the reader sees the reference to the
  59. method that wasn't described yet, they will find its description a bit below.
  60. Basics
  61. ======
  62. How to do it?
  63. -------------
  64. Do we need to merge functions? The obvious answer is: Yes, that is quite a
  65. possible case. We usually *do* have duplicates and it would be good to get rid
  66. of them. But how do we detect duplicates? This is the idea: we split functions
  67. into smaller bricks or parts and compare the "bricks" amount. If equal,
  68. we compare the "bricks" themselves, and then do our conclusions about functions
  69. themselves.
  70. What could the difference be? For example, on a machine with 64-bit pointers
  71. (let's assume we have only one address space), one function stores a 64-bit
  72. integer, while another one stores a pointer. If the target is the machine
  73. mentioned above, and if functions are identical, except the parameter type (we
  74. could consider it as a part of function type), then we can treat a ``uint64_t``
  75. and a ``void*`` as equal.
  76. This is just an example; more possible details are described a bit below.
  77. As another example, the reader may imagine two more functions. The first
  78. function performs a multiplication on 2, while the second one performs an
  79. arithmetic right shift on 1.
  80. Possible solutions
  81. ^^^^^^^^^^^^^^^^^^
  82. Let's briefly consider possible options about how and what we have to implement
  83. in order to create full-featured functions merging, and also what it would
  84. mean for us.
  85. Equal function detection obviously supposes that a "detector" method to be
  86. implemented and latter should answer the question "whether functions are equal".
  87. This "detector" method consists of tiny "sub-detectors", which each answers
  88. exactly the same question, but for function parts.
  89. As the second step, we should merge equal functions. So it should be a "merger"
  90. method. "Merger" accepts two functions *F1* and *F2*, and produces *F1F2*
  91. function, the result of merging.
  92. Having such routines in our hands, we can process a whole module, and merge all
  93. equal functions.
  94. In this case, we have to compare every function with every another function. As
  95. the reader may notice, this way seems to be quite expensive. Of course we could
  96. introduce hashing and other helpers, but it is still just an optimization, and
  97. thus the level of O(N*N) complexity.
  98. Can we reach another level? Could we introduce logarithmical search, or random
  99. access lookup? The answer is: "yes".
  100. Random-access
  101. """""""""""""
  102. How it could this be done? Just convert each function to a number, and gather
  103. all of them in a special hash-table. Functions with equal hashes are equal.
  104. Good hashing means, that every function part must be taken into account. That
  105. means we have to convert every function part into some number, and then add it
  106. into the hash. The lookup-up time would be small, but such a approach adds some
  107. delay due to the hashing routine.
  108. Logarithmical search
  109. """"""""""""""""""""
  110. We could introduce total ordering among the functions set, once ordered we
  111. could then implement a logarithmical search. Lookup time still depends on N,
  112. but adds a little of delay (*log(N)*).
  113. Present state
  114. """""""""""""
  115. Both of the approaches (random-access and logarithmical) have been implemented
  116. and tested and both give a very good improvement. What was most
  117. surprising is that logarithmical search was faster; sometimes by up to 15%. The
  118. hashing method needs some extra CPU time, which is the main reason why it works
  119. slower; in most cases, total "hashing" time is greater than total
  120. "logarithmical-search" time.
  121. So, preference has been granted to the "logarithmical search".
  122. Though in the case of need, *logarithmical-search* (read "total-ordering") could
  123. be used as a milestone on our way to the *random-access* implementation.
  124. Every comparison is based either on the numbers or on the flags comparison. In
  125. the *random-access* approach, we could use the same comparison algorithm.
  126. During comparison, we exit once we find the difference, but here we might have
  127. to scan the whole function body every time (note, it could be slower). Like in
  128. "total-ordering", we will track every number and flag, but instead of
  129. comparison, we should get the numbers sequence and then create the hash number.
  130. So, once again, *total-ordering* could be considered as a milestone for even
  131. faster (in theory) random-access approach.
  132. MergeFunctions, main fields and runOnModule
  133. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  134. There are two main important fields in the class:
  135. ``FnTree`` – the set of all unique functions. It keeps items that couldn't be
  136. merged with each other. It is defined as:
  137. ``std::set<FunctionNode> FnTree;``
  138. Here ``FunctionNode`` is a wrapper for ``llvm::Function`` class, with
  139. implemented “<” operator among the functions set (below we explain how it works
  140. exactly; this is a key point in fast functions comparison).
  141. ``Deferred`` – merging process can affect bodies of functions that are in
  142. ``FnTree`` already. Obviously, such functions should be rechecked again. In this
  143. case, we remove them from ``FnTree``, and mark them to be rescanned, namely
  144. put them into ``Deferred`` list.
  145. runOnModule
  146. """""""""""
  147. The algorithm is pretty simple:
  148. 1. Put all module's functions into the *worklist*.
  149. 2. Scan *worklist*'s functions twice: first enumerate only strong functions and
  150. then only weak ones:
  151. 2.1. Loop body: take a function from *worklist* (call it *FCur*) and try to
  152. insert it into *FnTree*: check whether *FCur* is equal to one of functions
  153. in *FnTree*. If there *is* an equal function in *FnTree*
  154. (call it *FExists*): merge function *FCur* with *FExists*. Otherwise add
  155. the function from the *worklist* to *FnTree*.
  156. 3. Once the *worklist* scanning and merging operations are complete, check the
  157. *Deferred* list. If it is not empty: refill the *worklist* contents with
  158. *Deferred* list and redo step 2, if the *Deferred* list is empty, then exit
  159. from method.
  160. Comparison and logarithmical search
  161. """""""""""""""""""""""""""""""""""
  162. Let's recall our task: for every function *F* from module *M*, we have to find
  163. equal functions *F`* in the shortest time possible , and merge them into a
  164. single function.
  165. Defining total ordering among the functions set allows us to organize
  166. functions into a binary tree. The lookup procedure complexity would be
  167. estimated as O(log(N)) in this case. But how do we define *total-ordering*?
  168. We have to introduce a single rule applicable to every pair of functions, and
  169. following this rule, then evaluate which of them is greater. What kind of rule
  170. could it be? Let's declare it as the "compare" method that returns one of 3
  171. possible values:
  172. -1, left is *less* than right,
  173. 0, left and right are *equal*,
  174. 1, left is *greater* than right.
  175. Of course it means, that we have to maintain
  176. *strict and non-strict order relation properties*:
  177. * reflexivity (``a <= a``, ``a == a``, ``a >= a``),
  178. * antisymmetry (if ``a <= b`` and ``b <= a`` then ``a == b``),
  179. * transitivity (``a <= b`` and ``b <= c``, then ``a <= c``)
  180. * asymmetry (if ``a < b``, then ``a > b`` or ``a == b``).
  181. As mentioned before, the comparison routine consists of
  182. "sub-comparison-routines", with each of them also consisting of
  183. "sub-comparison-routines", and so on. Finally, it ends up with primitive
  184. comparison.
  185. Below, we will use the following operations:
  186. #. ``cmpNumbers(number1, number2)`` is a method that returns -1 if left is less
  187. than right; 0, if left and right are equal; and 1 otherwise.
  188. #. ``cmpFlags(flag1, flag2)`` is a hypothetical method that compares two flags.
  189. The logic is the same as in ``cmpNumbers``, where ``true`` is 1, and
  190. ``false`` is 0.
  191. The rest of the article is based on *MergeFunctions.cpp* source code
  192. (found in *<llvm_dir>/lib/Transforms/IPO/MergeFunctions.cpp*). We would like
  193. to ask reader to keep this file open, so we could use it as a reference
  194. for further explanations.
  195. Now, we're ready to proceed to the next chapter and see how it works.
  196. Functions comparison
  197. ====================
  198. At first, let's define how exactly we compare complex objects.
  199. Complex object comparison (function, basic-block, etc) is mostly based on its
  200. sub-object comparison results. It is similar to the next "tree" objects
  201. comparison:
  202. #. For two trees *T1* and *T2* we perform *depth-first-traversal* and have
  203. two sequences as a product: "*T1Items*" and "*T2Items*".
  204. #. We then compare chains "*T1Items*" and "*T2Items*" in
  205. the most-significant-item-first order. The result of items comparison
  206. would be the result of *T1* and *T2* comparison itself.
  207. FunctionComparator::compare(void)
  208. ---------------------------------
  209. A brief look at the source code tells us that the comparison starts in the
  210. “``int FunctionComparator::compare(void)``” method.
  211. 1. The first parts to be compared are the function's attributes and some
  212. properties that is outside the “attributes” term, but still could make the
  213. function different without changing its body. This part of the comparison is
  214. usually done within simple *cmpNumbers* or *cmpFlags* operations (e.g.
  215. ``cmpFlags(F1->hasGC(), F2->hasGC())``). Below is a full list of function's
  216. properties to be compared on this stage:
  217. * *Attributes* (those are returned by ``Function::getAttributes()``
  218. method).
  219. * *GC*, for equivalence, *RHS* and *LHS* should be both either without
  220. *GC* or with the same one.
  221. * *Section*, just like a *GC*: *RHS* and *LHS* should be defined in the
  222. same section.
  223. * *Variable arguments*. *LHS* and *RHS* should be both either with or
  224. without *var-args*.
  225. * *Calling convention* should be the same.
  226. 2. Function type. Checked by ``FunctionComparator::cmpType(Type*, Type*)``
  227. method. It checks return type and parameters type; the method itself will be
  228. described later.
  229. 3. Associate function formal parameters with each other. Then comparing function
  230. bodies, if we see the usage of *LHS*'s *i*-th argument in *LHS*'s body, then,
  231. we want to see usage of *RHS*'s *i*-th argument at the same place in *RHS*'s
  232. body, otherwise functions are different. On this stage we grant the preference
  233. to those we met later in function body (value we met first would be *less*).
  234. This is done by “``FunctionComparator::cmpValues(const Value*, const Value*)``”
  235. method (will be described a bit later).
  236. 4. Function body comparison. As it written in method comments:
  237. “We do a CFG-ordered walk since the actual ordering of the blocks in the linked
  238. list is immaterial. Our walk starts at the entry block for both functions, then
  239. takes each block from each terminator in order. As an artifact, this also means
  240. that unreachable blocks are ignored.”
  241. So, using this walk we get BBs from *left* and *right* in the same order, and
  242. compare them by “``FunctionComparator::compare(const BasicBlock*, const
  243. BasicBlock*)``” method.
  244. We also associate BBs with each other, like we did it with function formal
  245. arguments (see ``cmpValues`` method below).
  246. FunctionComparator::cmpType
  247. ---------------------------
  248. Consider how type comparison works.
  249. 1. Coerce pointer to integer. If left type is a pointer, try to coerce it to the
  250. integer type. It could be done if its address space is 0, or if address spaces
  251. are ignored at all. Do the same thing for the right type.
  252. 2. If left and right types are equal, return 0. Otherwise we need to give
  253. preference to one of them. So proceed to the next step.
  254. 3. If types are of different kind (different type IDs). Return result of type
  255. IDs comparison, treating them as numbers (use ``cmpNumbers`` operation).
  256. 4. If types are vectors or integers, return result of their pointers comparison,
  257. comparing them as numbers.
  258. 5. Check whether type ID belongs to the next group (call it equivalent-group):
  259. * Void
  260. * Float
  261. * Double
  262. * X86_FP80
  263. * FP128
  264. * PPC_FP128
  265. * Label
  266. * Metadata.
  267. If ID belongs to group above, return 0. Since it's enough to see that
  268. types has the same ``TypeID``. No additional information is required.
  269. 6. Left and right are pointers. Return result of address space comparison
  270. (numbers comparison).
  271. 7. Complex types (structures, arrays, etc.). Follow complex objects comparison
  272. technique (see the very first paragraph of this chapter). Both *left* and
  273. *right* are to be expanded and their element types will be checked the same
  274. way. If we get -1 or 1 on some stage, return it. Otherwise return 0.
  275. 8. Steps 1-6 describe all the possible cases, if we passed steps 1-6 and didn't
  276. get any conclusions, then invoke ``llvm_unreachable``, since it's quite an
  277. unexpectable case.
  278. cmpValues(const Value*, const Value*)
  279. -------------------------------------
  280. Method that compares local values.
  281. This method gives us an answer to a very curious question: whether we could
  282. treat local values as equal, and which value is greater otherwise. It's
  283. better to start from example:
  284. Consider the situation when we're looking at the same place in left
  285. function "*FL*" and in right function "*FR*". Every part of *left* place is
  286. equal to the corresponding part of *right* place, and (!) both parts use
  287. *Value* instances, for example:
  288. .. code-block:: text
  289. instr0 i32 %LV ; left side, function FL
  290. instr0 i32 %RV ; right side, function FR
  291. So, now our conclusion depends on *Value* instances comparison.
  292. The main purpose of this method is to determine relation between such values.
  293. What can we expect from equal functions? At the same place, in functions
  294. "*FL*" and "*FR*" we expect to see *equal* values, or values *defined* at
  295. the same place in "*FL*" and "*FR*".
  296. Consider a small example here:
  297. .. code-block:: text
  298. define void %f(i32 %pf0, i32 %pf1) {
  299. instr0 i32 %pf0 instr1 i32 %pf1 instr2 i32 123
  300. }
  301. .. code-block:: text
  302. define void %g(i32 %pg0, i32 %pg1) {
  303. instr0 i32 %pg0 instr1 i32 %pg0 instr2 i32 123
  304. }
  305. In this example, *pf0* is associated with *pg0*, *pf1* is associated with
  306. *pg1*, and we also declare that *pf0* < *pf1*, and thus *pg0* < *pf1*.
  307. Instructions with opcode "*instr0*" would be *equal*, since their types and
  308. opcodes are equal, and values are *associated*.
  309. Instructions with opcode "*instr1*" from *f* is *greater* than instructions
  310. with opcode "*instr1*" from *g*; here we have equal types and opcodes, but
  311. "*pf1* is greater than "*pg0*".
  312. Instructions with opcode "*instr2*" are equal, because their opcodes and
  313. types are equal, and the same constant is used as a value.
  314. What we associate in cmpValues?
  315. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  316. * Function arguments. *i*-th argument from left function associated with
  317. *i*-th argument from right function.
  318. * BasicBlock instances. In basic-block enumeration loop we associate *i*-th
  319. BasicBlock from the left function with *i*-th BasicBlock from the right
  320. function.
  321. * Instructions.
  322. * Instruction operands. Note, we can meet *Value* here we have never seen
  323. before. In this case it is not a function argument, nor *BasicBlock*, nor
  324. *Instruction*. It is a global value. It is a constant, since it's the only
  325. supposed global here. The method also compares: Constants that are of the
  326. same type and if right constant can be losslessly bit-casted to the left
  327. one, then we also compare them.
  328. How to implement cmpValues?
  329. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  330. *Association* is a case of equality for us. We just treat such values as equal,
  331. but, in general, we need to implement antisymmetric relation. As mentioned
  332. above, to understand what is *less*, we can use order in which we
  333. meet values. If both values have the same order in a function (met at the same
  334. time), we then treat values as *associated*. Otherwise – it depends on who was
  335. first.
  336. Every time we run the top-level compare method, we initialize two identical
  337. maps (one for the left side, another one for the right side):
  338. ``map<Value, int> sn_mapL, sn_mapR;``
  339. The key of the map is the *Value* itself, the *value* – is its order (call it
  340. *serial number*).
  341. To add value *V* we need to perform the next procedure:
  342. ``sn_map.insert(std::make_pair(V, sn_map.size()));``
  343. For the first *Value*, map will return *0*, for the second *Value* map will
  344. return *1*, and so on.
  345. We can then check whether left and right values met at the same time with
  346. a simple comparison:
  347. ``cmpNumbers(sn_mapL[Left], sn_mapR[Right]);``
  348. Of course, we can combine insertion and comparison:
  349. .. code-block:: c++
  350. std::pair<iterator, bool>
  351. LeftRes = sn_mapL.insert(std::make_pair(Left, sn_mapL.size())), RightRes
  352. = sn_mapR.insert(std::make_pair(Right, sn_mapR.size()));
  353. return cmpNumbers(LeftRes.first->second, RightRes.first->second);
  354. Let's look, how whole method could be implemented.
  355. 1. We have to start with the bad news. Consider function self and
  356. cross-referencing cases:
  357. .. code-block:: c++
  358. // self-reference unsigned fact0(unsigned n) { return n > 1 ? n
  359. * fact0(n-1) : 1; } unsigned fact1(unsigned n) { return n > 1 ? n *
  360. fact1(n-1) : 1; }
  361. // cross-reference unsigned ping(unsigned n) { return n!= 0 ? pong(n-1) : 0;
  362. } unsigned pong(unsigned n) { return n!= 0 ? ping(n-1) : 0; }
  363. ..
  364. This comparison has been implemented in initial *MergeFunctions* pass
  365. version. But, unfortunately, it is not transitive. And this is the only case
  366. we can't convert to less-equal-greater comparison. It is a seldom case, 4-5
  367. functions of 10000 (checked in test-suite), and, we hope, the reader would
  368. forgive us for such a sacrifice in order to get the O(log(N)) pass time.
  369. 2. If left/right *Value* is a constant, we have to compare them. Return 0 if it
  370. is the same constant, or use ``cmpConstants`` method otherwise.
  371. 3. If left/right is *InlineAsm* instance. Return result of *Value* pointers
  372. comparison.
  373. 4. Explicit association of *L* (left value) and *R* (right value). We need to
  374. find out whether values met at the same time, and thus are *associated*. Or we
  375. need to put the rule: when we treat *L* < *R*. Now it is easy: we just return
  376. the result of numbers comparison:
  377. .. code-block:: c++
  378. std::pair<iterator, bool>
  379. LeftRes = sn_mapL.insert(std::make_pair(Left, sn_mapL.size())),
  380. RightRes = sn_mapR.insert(std::make_pair(Right, sn_mapR.size()));
  381. if (LeftRes.first->second == RightRes.first->second) return 0;
  382. if (LeftRes.first->second < RightRes.first->second) return -1;
  383. return 1;
  384. Now when *cmpValues* returns 0, we can proceed the comparison procedure.
  385. Otherwise, if we get (-1 or 1), we need to pass this result to the top level,
  386. and finish comparison procedure.
  387. cmpConstants
  388. ------------
  389. Performs constants comparison as follows:
  390. 1. Compare constant types using ``cmpType`` method. If the result is -1 or 1,
  391. goto step 2, otherwise proceed to step 3.
  392. 2. If types are different, we still can check whether constants could be
  393. losslessly bitcasted to each other. The further explanation is modification of
  394. ``canLosslesslyBitCastTo`` method.
  395. 2.1 Check whether constants are of the first class types
  396. (``isFirstClassType`` check):
  397. 2.1.1. If both constants are *not* of the first class type: return result
  398. of ``cmpType``.
  399. 2.1.2. Otherwise, if left type is not of the first class, return -1. If
  400. right type is not of the first class, return 1.
  401. 2.1.3. If both types are of the first class type, proceed to the next step
  402. (2.1.3.1).
  403. 2.1.3.1. If types are vectors, compare their bitwidth using the
  404. *cmpNumbers*. If result is not 0, return it.
  405. 2.1.3.2. Different types, but not a vectors:
  406. * if both of them are pointers, good for us, we can proceed to step 3.
  407. * if one of types is pointer, return result of *isPointer* flags
  408. comparison (*cmpFlags* operation).
  409. * otherwise we have no methods to prove bitcastability, and thus return
  410. result of types comparison (-1 or 1).
  411. Steps below are for the case when types are equal, or case when constants are
  412. bitcastable:
  413. 3. One of constants is a "*null*" value. Return the result of
  414. ``cmpFlags(L->isNullValue, R->isNullValue)`` comparison.
  415. 4. Compare value IDs, and return result if it is not 0:
  416. .. code-block:: c++
  417. if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
  418. return Res;
  419. 5. Compare the contents of constants. The comparison depends on the kind of
  420. constants, but on this stage it is just a lexicographical comparison. Just see
  421. how it was described in the beginning of "*Functions comparison*" paragraph.
  422. Mathematically, it is equal to the next case: we encode left constant and right
  423. constant (with similar way *bitcode-writer* does). Then compare left code
  424. sequence and right code sequence.
  425. compare(const BasicBlock*, const BasicBlock*)
  426. ---------------------------------------------
  427. Compares two *BasicBlock* instances.
  428. It enumerates instructions from left *BB* and right *BB*.
  429. 1. It assigns serial numbers to the left and right instructions, using
  430. ``cmpValues`` method.
  431. 2. If one of left or right is *GEP* (``GetElementPtr``), then treat *GEP* as
  432. greater than other instructions. If both instructions are *GEPs* use ``cmpGEP``
  433. method for comparison. If result is -1 or 1, pass it to the top-level
  434. comparison (return it).
  435. 3.1. Compare operations. Call ``cmpOperation`` method. If result is -1 or
  436. 1, return it.
  437. 3.2. Compare number of operands, if result is -1 or 1, return it.
  438. 3.3. Compare operands themselves, use ``cmpValues`` method. Return result
  439. if it is -1 or 1.
  440. 3.4. Compare type of operands, using ``cmpType`` method. Return result if
  441. it is -1 or 1.
  442. 3.5. Proceed to the next instruction.
  443. 4. We can finish instruction enumeration in 3 cases:
  444. 4.1. We reached the end of both left and right basic-blocks. We didn't
  445. exit on steps 1-3, so contents are equal, return 0.
  446. 4.2. We have reached the end of the left basic-block. Return -1.
  447. 4.3. Return 1 (we reached the end of the right basic block).
  448. cmpGEP
  449. ------
  450. Compares two GEPs (``getelementptr`` instructions).
  451. It differs from regular operations comparison with the only thing: possibility
  452. to use ``accumulateConstantOffset`` method.
  453. So, if we get constant offset for both left and right *GEPs*, then compare it as
  454. numbers, and return comparison result.
  455. Otherwise treat it like a regular operation (see previous paragraph).
  456. cmpOperation
  457. ------------
  458. Compares instruction opcodes and some important operation properties.
  459. 1. Compare opcodes, if it differs return the result.
  460. 2. Compare number of operands. If it differs – return the result.
  461. 3. Compare operation types, use *cmpType*. All the same – if types are
  462. different, return result.
  463. 4. Compare *subclassOptionalData*, get it with ``getRawSubclassOptionalData``
  464. method, and compare it like a numbers.
  465. 5. Compare operand types.
  466. 6. For some particular instructions, check equivalence (relation in our case) of
  467. some significant attributes. For example, we have to compare alignment for
  468. ``load`` instructions.
  469. O(log(N))
  470. ---------
  471. Methods described above implement order relationship. And latter, could be used
  472. for nodes comparison in a binary tree. So we can organize functions set into
  473. the binary tree and reduce the cost of lookup procedure from
  474. O(N*N) to O(log(N)).
  475. Merging process, mergeTwoFunctions
  476. ==================================
  477. Once *MergeFunctions* detected that current function (*G*) is equal to one that
  478. were analyzed before (function *F*) it calls ``mergeTwoFunctions(Function*,
  479. Function*)``.
  480. Operation affects ``FnTree`` contents with next way: *F* will stay in
  481. ``FnTree``. *G* being equal to *F* will not be added to ``FnTree``. Calls of
  482. *G* would be replaced with something else. It changes bodies of callers. So,
  483. functions that calls *G* would be put into ``Deferred`` set and removed from
  484. ``FnTree``, and analyzed again.
  485. The approach is next:
  486. 1. Most wished case: when we can use alias and both of *F* and *G* are weak. We
  487. make both of them with aliases to the third strong function *H*. Actually *H*
  488. is *F*. See below how it's made (but it's better to look straight into the
  489. source code). Well, this is a case when we can just replace *G* with *F*
  490. everywhere, we use ``replaceAllUsesWith`` operation here (*RAUW*).
  491. 2. *F* could not be overridden, while *G* could. It would be good to do the
  492. next: after merging the places where overridable function were used, still use
  493. overridable stub. So try to make *G* alias to *F*, or create overridable tail
  494. call wrapper around *F* and replace *G* with that call.
  495. 3. Neither *F* nor *G* could be overridden. We can't use *RAUW*. We can just
  496. change the callers: call *F* instead of *G*. That's what
  497. ``replaceDirectCallers`` does.
  498. Below is a detailed body description.
  499. If “F” may be overridden
  500. ------------------------
  501. As follows from ``mayBeOverridden`` comments: “whether the definition of this
  502. global may be replaced by something non-equivalent at link time”. If so, that's
  503. ok: we can use alias to *F* instead of *G* or change call instructions itself.
  504. HasGlobalAliases, removeUsers
  505. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  506. First consider the case when we have global aliases of one function name to
  507. another. Our purpose is make both of them with aliases to the third strong
  508. function. Though if we keep *F* alive and without major changes we can leave it
  509. in ``FnTree``. Try to combine these two goals.
  510. Do stub replacement of *F* itself with an alias to *F*.
  511. 1. Create stub function *H*, with the same name and attributes like function
  512. *F*. It takes maximum alignment of *F* and *G*.
  513. 2. Replace all uses of function *F* with uses of function *H*. It is the two
  514. steps procedure instead. First of all, we must take into account, all functions
  515. from whom *F* is called would be changed: since we change the call argument
  516. (from *F* to *H*). If so we must to review these caller functions again after
  517. this procedure. We remove callers from ``FnTree``, method with name
  518. ``removeUsers(F)`` does that (don't confuse with ``replaceAllUsesWith``):
  519. 2.1. ``Inside removeUsers(Value*
  520. V)`` we go through the all values that use value *V* (or *F* in our context).
  521. If value is instruction, we go to function that holds this instruction and
  522. mark it as to-be-analyzed-again (put to ``Deferred`` set), we also remove
  523. caller from ``FnTree``.
  524. 2.2. Now we can do the replacement: call ``F->replaceAllUsesWith(H)``.
  525. 3. *H* (that now "officially" plays *F*'s role) is replaced with alias to *F*.
  526. Do the same with *G*: replace it with alias to *F*. So finally everywhere *F*
  527. was used, we use *H* and it is alias to *F*, and everywhere *G* was used we
  528. also have alias to *F*.
  529. 4. Set *F* linkage to private. Make it strong :-)
  530. No global aliases, replaceDirectCallers
  531. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  532. If global aliases are not supported. We call ``replaceDirectCallers``. Just
  533. go through all calls of *G* and replace it with calls of *F*. If you look into
  534. the method you will see that it scans all uses of *G* too, and if use is callee
  535. (if user is call instruction and *G* is used as what to be called), we replace
  536. it with use of *F*.
  537. If “F” could not be overridden, fix it!
  538. """""""""""""""""""""""""""""""""""""""
  539. We call ``writeThunkOrAlias(Function *F, Function *G)``. Here we try to replace
  540. *G* with alias to *F* first. The next conditions are essential:
  541. * target should support global aliases,
  542. * the address itself of *G* should be not significant, not named and not
  543. referenced anywhere,
  544. * function should come with external, local or weak linkage.
  545. Otherwise we write thunk: some wrapper that has *G's* interface and calls *F*,
  546. so *G* could be replaced with this wrapper.
  547. *writeAlias*
  548. As follows from *llvm* reference:
  549. “Aliases act as *second name* for the aliasee value”. So we just want to create
  550. a second name for *F* and use it instead of *G*:
  551. 1. create global alias itself (*GA*),
  552. 2. adjust alignment of *F* so it must be maximum of current and *G's* alignment;
  553. 3. replace uses of *G*:
  554. 3.1. first mark all callers of *G* as to-be-analyzed-again, using
  555. ``removeUsers`` method (see chapter above),
  556. 3.2. call ``G->replaceAllUsesWith(GA)``.
  557. 4. Get rid of *G*.
  558. *writeThunk*
  559. As it written in method comments:
  560. “Replace G with a simple tail call to bitcast(F). Also replace direct uses of G
  561. with bitcast(F). Deletes G.”
  562. In general it does the same as usual when we want to replace callee, except the
  563. first point:
  564. 1. We generate tail call wrapper around *F*, but with interface that allows use
  565. it instead of *G*.
  566. 2. “As-usual”: ``removeUsers`` and ``replaceAllUsesWith`` then.
  567. 3. Get rid of *G*.