MergeFunctions.rst 31 KB

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