havlak.lua 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  1. -- This code is derived from the SOM benchmarks, see AUTHORS.md file.
  2. --
  3. -- Copyright (c) 2016 Francois Perrad <[email protected]>
  4. --
  5. -- Permission is hereby granted, free of charge, to any person obtaining a copy
  6. -- of this software and associated documentation files (the 'Software'), to deal
  7. -- in the Software without restriction, including without limitation the rights
  8. -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. -- copies of the Software, and to permit persons to whom the Software is
  10. -- furnished to do so, subject to the following conditions:
  11. --
  12. -- The above copyright notice and this permission notice shall be included in
  13. -- all copies or substantial portions of the Software.
  14. --
  15. -- THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. -- THE SOFTWARE.
  22. --[[
  23. The module 'bit' is available with:
  24. * LuaJIT
  25. * LuaBitOp extension which is available for:
  26. * Lua 5.1
  27. * Lua 5.2
  28. The module 'bit32' is available with:
  29. * Lua 5.2
  30. * Lua 5.3 when compiled with LUA_COMPAT_5_2
  31. The bitwise operators are added to Lua 5.3 as new lexemes (there causes
  32. lexical error in older version)
  33. --]]
  34. local band, bxor, rshift
  35. if _VERSION < 'Lua 5.3' then
  36. local bit = bit32 or require'bit'
  37. band = bit.band
  38. bxor = bit.bxor
  39. rshift = bit.rshift
  40. else
  41. band = assert(load'--[[band]] return function (a, b) return a & b end')()
  42. bxor = assert(load'--[[bxor]] return function (a, b) return a ~ b end')()
  43. rshift = assert(load'--[[rshift]] return function (a, b) return a >> b end')()
  44. end
  45. local alloc_array
  46. local ok, table_new = pcall(require, 'table.new') -- LuaJIT 2.1 extension
  47. if ok then
  48. alloc_array = function (n)
  49. local t = table_new(n, 1)
  50. t.n = n
  51. return t
  52. end
  53. else
  54. alloc_array = function (n)
  55. local t = {}
  56. t.n = n
  57. return t
  58. end
  59. end
  60. local Vector = {_CLASS = 'Vector'} do
  61. local floor = math.floor
  62. function Vector.new (size)
  63. local obj = {
  64. storage = alloc_array(size or 50),
  65. first_idx = 1,
  66. last_idx = 1,
  67. }
  68. return setmetatable(obj, {__index = Vector})
  69. end
  70. function Vector.with (elem)
  71. local v = Vector.new(1)
  72. v:append(elem)
  73. return v
  74. end
  75. function Vector:at (idx)
  76. if idx > self.storage.n then
  77. return nil
  78. end
  79. return self.storage[idx]
  80. end
  81. function Vector:at_put (idx, val)
  82. if idx > self.storage.n then
  83. local new_n = self.storage.n
  84. while idx > new_n do
  85. new_n = new_n * 2
  86. end
  87. local new_storage = alloc_array(new_n)
  88. for i = 1, self.storage.n do
  89. new_storage[i] = self.storage[i]
  90. end
  91. self.storage = new_storage
  92. end
  93. self.storage[idx] = val
  94. if self.last_idx < idx + 1 then
  95. self.last_idx = idx + 1
  96. end
  97. end
  98. function Vector:append (elem)
  99. if self.last_idx > self.storage.n then
  100. -- Need to expand capacity first
  101. local new_storage = alloc_array(2 * self.storage.n)
  102. for i = 1, self.storage.n do
  103. new_storage[i] = self.storage[i]
  104. end
  105. self.storage = new_storage
  106. end
  107. self.storage[self.last_idx] = elem
  108. self.last_idx = self.last_idx + 1
  109. end
  110. function Vector:is_empty ()
  111. return self.last_idx == self.first_idx
  112. end
  113. function Vector:each (fn)
  114. for i = self.first_idx, self.last_idx - 1 do
  115. fn(self.storage[i])
  116. end
  117. end
  118. function Vector:has_some (fn)
  119. for i = self.first_idx, self.last_idx - 1 do
  120. if fn(self.storage[i]) then
  121. return true
  122. end
  123. end
  124. return false
  125. end
  126. function Vector:get_one (fn)
  127. for i = self.first_idx, self.last_idx - 1 do
  128. local e = self.storage[i]
  129. if fn(e) then
  130. return e
  131. end
  132. end
  133. return nil
  134. end
  135. function Vector:remove_first ()
  136. if self:is_empty() then
  137. return nil
  138. end
  139. self.first_idx = self.first_idx + 1
  140. return self.storage[self.first_idx - 1]
  141. end
  142. function Vector:remove (obj)
  143. local new_array = alloc_array(self:capacity())
  144. local new_last = 1
  145. local found = false
  146. self:each(function (it)
  147. if it == obj then
  148. found = true
  149. else
  150. new_array[new_last] = it
  151. new_last = new_last + 1
  152. end
  153. end)
  154. self.storage = new_array
  155. self.last_idx = new_last
  156. self.first_idx = 1
  157. return found
  158. end
  159. function Vector:remove_all ()
  160. self.first_idx = 1
  161. self.last_idx = 1
  162. self.storage = alloc_array(self:capacity())
  163. end
  164. function Vector:size ()
  165. return self.last_idx - self.first_idx
  166. end
  167. function Vector:capacity ()
  168. return self.storage.n
  169. end
  170. function Vector:sort (fn)
  171. -- Make the argument, block, be the criterion for ordering elements of
  172. -- the receiver.
  173. -- Sort blocks with side effects may not work right.
  174. if self:size() > 0 then
  175. self:sort_range(self.first_idx, self.last_idx - 1, fn)
  176. end
  177. end
  178. function Vector:sort_range (i, j, fn)
  179. assert(fn)
  180. -- The prefix d means the data at that index.
  181. local n = j + 1 - i
  182. if n <= 1 then
  183. -- Nothing to sort
  184. return
  185. end
  186. local storage = self.storage
  187. -- Sort di, dj
  188. local di = storage[i]
  189. local dj = storage[j]
  190. -- i.e., should di precede dj?
  191. if not fn(di, dj) then
  192. local tmp = storage[i]
  193. storage[i] = storage[j]
  194. storage[j] = tmp
  195. local tt = di
  196. di = dj
  197. dj = tt
  198. end
  199. -- NOTE: For DeltaBlue, this is never reached.
  200. if n > 2 then -- More than two elements.
  201. local ij = floor((i + j) / 2) -- ij is the midpoint of i and j.
  202. local dij = storage[ij] -- Sort di,dij,dj. Make dij be their median.
  203. if fn(di, dij) then -- i.e. should di precede dij?
  204. if not fn(dij, dj) then -- i.e., should dij precede dj?
  205. local tmp = storage[j]
  206. storage[j] = storage[ij]
  207. storage[ij] = tmp
  208. dij = dj
  209. end
  210. else -- i.e. di should come after dij
  211. local tmp = storage[i]
  212. storage[i] = storage[ij]
  213. storage[ij] = tmp
  214. dij = di
  215. end
  216. if n > 3 then -- More than three elements.
  217. -- Find k>i and l<j such that dk,dij,dl are in reverse order.
  218. -- Swap k and l. Repeat this procedure until k and l pass each other.
  219. local k = i
  220. local l = j - 1
  221. while true do
  222. -- i.e. while dl succeeds dij
  223. while k <= l and fn(dij, storage[l]) do
  224. l = l - 1
  225. end
  226. k = k + 1
  227. -- i.e. while dij succeeds dk
  228. while k <= l and fn(storage[k], dij) do
  229. k = k + 1
  230. end
  231. if k > l then
  232. break
  233. end
  234. local tmp = storage[k]
  235. storage[k] = storage[l]
  236. storage[l] = tmp
  237. end
  238. -- Now l < k (either 1 or 2 less), and di through dl are all
  239. -- less than or equal to dk through dj. Sort those two segments.
  240. self:sort_range(i, l, fn)
  241. self:sort_range(k, j, fn)
  242. end
  243. end
  244. end
  245. end -- class Vector
  246. local Set = {_CLASS = 'Set'} do
  247. local INITIAL_SIZE = 10
  248. function Set.new (size)
  249. local obj = {
  250. items = Vector.new(size or INITIAL_SIZE)
  251. }
  252. return setmetatable(obj, {__index = Set})
  253. end
  254. function Set:size ()
  255. return self.items:size()
  256. end
  257. function Set:each (fn)
  258. self.items:each(fn)
  259. end
  260. function Set:has_some (fn)
  261. return self.items:has_some(fn)
  262. end
  263. function Set:get_one (fn)
  264. return self.items:get_one(fn)
  265. end
  266. function Set:add (obj)
  267. if not self:contains(obj) then
  268. self.items:append(obj)
  269. end
  270. end
  271. function Set:remove_all ()
  272. self.items:remove_all()
  273. end
  274. function Set:collect (fn)
  275. local coll = Vector.new()
  276. self:each(function (it)
  277. coll:append(fn(it))
  278. end)
  279. return coll
  280. end
  281. function Set:contains (obj)
  282. return self:has_some(function (it) return it == obj end)
  283. end
  284. end -- class Set
  285. local IdentitySet = {_CLASS = 'IdentitySet'} do
  286. setmetatable(IdentitySet, {__index = Set})
  287. function IdentitySet.new (size)
  288. local obj = Set.new(size)
  289. return setmetatable(obj, {__index = IdentitySet})
  290. end
  291. function IdentitySet:contains (obj)
  292. return self:has_some(function (it) return it == obj end)
  293. end
  294. end -- class IdentitySet
  295. local Entry = {_CLASS = 'Entry'} do
  296. function Entry.new (hash, key, value, next)
  297. local obj = {
  298. hash = hash,
  299. key = key,
  300. value = value,
  301. next = next,
  302. }
  303. return setmetatable(obj, {__index = Entry})
  304. end
  305. function Entry:match (hash, key)
  306. return self.hash == hash and self.key == key
  307. end
  308. end -- class Entry
  309. local Dictionary = {_CLASS = 'Dictionary'} do
  310. local INITIAL_CAPACITY = 16
  311. function Dictionary.new (size)
  312. local obj = {
  313. buckets = alloc_array(size or INITIAL_CAPACITY),
  314. size = 0,
  315. }
  316. return setmetatable(obj, {__index = Dictionary})
  317. end
  318. function Dictionary:hash (key)
  319. if not key then
  320. return 0
  321. end
  322. local hash = key:custom_hash()
  323. return bxor(hash, rshift(hash, 16))
  324. end
  325. function Dictionary:is_empty ()
  326. return self.size == 0
  327. end
  328. function Dictionary:get_bucket_idx (hash)
  329. return band(self.buckets.n - 1, hash) + 1
  330. end
  331. function Dictionary:get_bucket (hash)
  332. return self.buckets[self:get_bucket_idx(hash)]
  333. end
  334. function Dictionary:at (key)
  335. local hash = self:hash(key)
  336. local e = self:get_bucket(hash)
  337. while e do
  338. if e:match(hash, key) then
  339. return e.value
  340. end
  341. e = e.next
  342. end
  343. return nil
  344. end
  345. function Dictionary:contains_key (key)
  346. local hash = self:hash(key)
  347. local e = self:get_bucket(hash)
  348. while e do
  349. if e.match(hash, key) then
  350. return true
  351. end
  352. e = e.next
  353. end
  354. return false
  355. end
  356. function Dictionary:at_put (key, value)
  357. local hash = self:hash(key)
  358. local i = self:get_bucket_idx(hash)
  359. local current = self.buckets[i]
  360. if not current then
  361. self.buckets[i] = self:new_entry(key, value, hash)
  362. self.size = self.size + 1
  363. else
  364. self:insert_bucket_entry(key, value, hash, current)
  365. end
  366. if self.size > self.buckets.n then
  367. self:resize()
  368. end
  369. end
  370. function Dictionary:new_entry (key, value, hash)
  371. return Entry.new(hash, key, value, nil)
  372. end
  373. function Dictionary:insert_bucket_entry (key, value, hash, head)
  374. local current = head
  375. while true do
  376. if current:match(hash, key) then
  377. current.value = value
  378. return
  379. end
  380. if not current.next then
  381. self.size = self.size + 1
  382. current.next = self:new_entry(key, value, hash)
  383. return
  384. end
  385. current = current.next
  386. end
  387. end
  388. function Dictionary:resize ()
  389. local old_storage = self.buckets
  390. self.buckets = alloc_array(old_storage.n * 2)
  391. self:transfer_entries(old_storage)
  392. end
  393. function Dictionary:transfer_entries (old_storage)
  394. local buckets = self.buckets
  395. for i = 1, old_storage.n do
  396. local current = old_storage[i]
  397. if current then
  398. old_storage[i] = nil
  399. if not current.next then
  400. local hash = band(current.hash, buckets.n - 1) + 1
  401. buckets[hash] = current
  402. else
  403. self:split_bucket(old_storage, i, current)
  404. end
  405. end
  406. end
  407. end
  408. function Dictionary:split_bucket (old_storage, i, head)
  409. local lo_head, lo_tail = nil, nil
  410. local hi_head, hi_tail = nil, nil
  411. local current = head
  412. while current do
  413. if band(current.hash, old_storage.n) == 0 then
  414. if not lo_tail then
  415. lo_head = current
  416. else
  417. lo_tail.next = current
  418. end
  419. lo_tail = current
  420. else
  421. if not hi_tail then
  422. hi_head = current
  423. else
  424. hi_tail.next = current
  425. end
  426. hi_tail = current
  427. end
  428. current = current.next
  429. end
  430. if lo_tail then
  431. lo_tail.next = nil
  432. self.buckets[i] = lo_head
  433. end
  434. if hi_tail then
  435. hi_tail.next = nil
  436. self.buckets[i + old_storage.n] = hi_head
  437. end
  438. end
  439. function Dictionary:remove_all ()
  440. self.buckets = alloc_array(self.buckets.n)
  441. self.size = 0
  442. end
  443. function Dictionary:keys ()
  444. local keys = Vector.new(self.size)
  445. local buckets = self.buckets
  446. for i = 1, buckets.n do
  447. local current = buckets[i]
  448. while current do
  449. keys:append(current.key)
  450. current = current.next
  451. end
  452. end
  453. return keys
  454. end
  455. function Dictionary:values ()
  456. local vals = Vector.new(self.size)
  457. local buckets = self.buckets
  458. for i = 1, buckets.n do
  459. local current = buckets[i]
  460. while current do
  461. vals:append(current.value)
  462. current = current.next
  463. end
  464. end
  465. return vals
  466. end
  467. end -- class Dictionary
  468. local IdEntry = {_CLASS = 'IdEntry'} do
  469. setmetatable(IdEntry, {__index = Entry})
  470. function IdEntry.new (hash, key, value, next)
  471. local obj = Entry.new (hash, key, value, next)
  472. return setmetatable(obj, {__index = IdEntry})
  473. end
  474. function IdEntry:match (hash, key)
  475. return self.hash == hash and self.key == key
  476. end
  477. end -- class IdEntry
  478. local IdentityDictionary = {_CLASS = 'IdentityDictionary'} do
  479. setmetatable(IdentityDictionary, {__index = Dictionary})
  480. function IdentityDictionary.new (size)
  481. local obj = Dictionary.new (size)
  482. return setmetatable(obj, {__index = Dictionary})
  483. end
  484. function IdentityDictionary:new_entry (key, value, hash)
  485. return IdEntry.new(hash, key, value, nil)
  486. end
  487. end -- class IdentityDictionary
  488. local Random = {_CLASS = 'Random'} do
  489. function Random.new ()
  490. local obj = {seed = 74755}
  491. return setmetatable(obj, {__index = Random})
  492. end
  493. function Random:next ()
  494. self.seed = band(((self.seed * 1309) + 13849), 65535);
  495. return self.seed;
  496. end
  497. end -- class Random
  498. ---------------------------------
  499. local benchmark = {} do
  500. function benchmark:inner_benchmark_loop (inner_iterations)
  501. for _ = 1, inner_iterations do
  502. if not self:verify_result(self:benchmark()) then
  503. return false
  504. end
  505. end
  506. return true
  507. end
  508. function benchmark:benchmark ()
  509. error 'subclass_responsibility'
  510. end
  511. function benchmark:verify_result ()
  512. error 'subclass_responsibility'
  513. end
  514. end
  515. ---------------------------------
  516. local BasicBlock = {_CLASS = 'BasicBlock'} do
  517. function BasicBlock.new (name)
  518. local obj = {
  519. name = name,
  520. in_edges = Vector.new(2),
  521. out_edges = Vector.new(2),
  522. }
  523. return setmetatable(obj, {__index = BasicBlock})
  524. end
  525. function BasicBlock:num_pred ()
  526. return self.in_edges:size()
  527. end
  528. function BasicBlock:add_out_edge (to)
  529. self.out_edges:append(to)
  530. end
  531. function BasicBlock:add_in_edge (from)
  532. self.in_edges:append(from)
  533. end
  534. function BasicBlock:custom_hash ()
  535. return self.name
  536. end
  537. end -- class BasicBlock
  538. local BasicBlockEdge = {_CLASS = 'BasicBlockEdge'} do
  539. function BasicBlockEdge.new (cfg, from_name, to_name)
  540. local from = cfg:create_node(from_name)
  541. local to = cfg:create_node(to_name)
  542. from:add_out_edge(to)
  543. to:add_in_edge(from)
  544. local obj = {
  545. from = from,
  546. to = to,
  547. }
  548. setmetatable(obj, {__index = BasicBlockEdge})
  549. cfg:add_edge(obj)
  550. return obj
  551. end
  552. end -- class BasicBlockEdge
  553. local ControlFlowGraph = {_CLASS = 'ControlFlowGraph'} do
  554. function ControlFlowGraph.new ()
  555. local obj = {
  556. start_node = nil,
  557. basic_block_map = Vector.new(),
  558. edge_list = Vector.new(),
  559. }
  560. return setmetatable(obj, {__index = ControlFlowGraph})
  561. end
  562. function ControlFlowGraph:create_node (name)
  563. local node
  564. if self.basic_block_map:at(name) then
  565. node = self.basic_block_map:at(name)
  566. else
  567. node = BasicBlock.new(name)
  568. self.basic_block_map:at_put(name, node)
  569. end
  570. if self:num_nodes() == 1 then
  571. self.start_node = node
  572. end
  573. return node
  574. end
  575. function ControlFlowGraph:add_edge (edge)
  576. self.edge_list:append(edge)
  577. end
  578. function ControlFlowGraph:num_nodes ()
  579. return self.basic_block_map:size()
  580. end
  581. function ControlFlowGraph:get_start_basic_block ()
  582. return self.start_node
  583. end
  584. function ControlFlowGraph:get_basic_blocks ()
  585. return self.basic_block_map
  586. end
  587. end -- class ControlFlowGraph
  588. local SimpleLoop = {_CLASS = 'SimpleLoop'} do
  589. function SimpleLoop.new (bb, is_reducible)
  590. local obj = {
  591. header = bb,
  592. is_reducible = is_reducible,
  593. parent = nil,
  594. is_root = false,
  595. nesting_level = 0,
  596. depth_level = 0,
  597. counter = 0,
  598. basic_blocks = IdentitySet.new(),
  599. children = IdentitySet.new(),
  600. }
  601. if bb then
  602. obj.basic_blocks:add(bb)
  603. end
  604. return setmetatable(obj, {__index = SimpleLoop})
  605. end
  606. function SimpleLoop:add_node (bb)
  607. self.basic_blocks:add(bb)
  608. end
  609. function SimpleLoop:add_child_loop (loop)
  610. self.children:add(loop)
  611. end
  612. function SimpleLoop:set_parent (parent)
  613. self.parent = parent
  614. self.parent:add_child_loop(self)
  615. end
  616. function SimpleLoop:set_is_root ()
  617. self.is_root = true
  618. end
  619. function SimpleLoop:set_nesting_level (level)
  620. self.nesting_level = level
  621. if level == 0 then
  622. self:set_is_root()
  623. end
  624. end
  625. end -- class SimpleLoop
  626. local LoopStructureGraph = {_CLASS = 'LoopStructureGraph'} do
  627. function LoopStructureGraph.new ()
  628. local loops = Vector.new()
  629. local root = SimpleLoop.new(nil, true)
  630. local obj = {
  631. loop_counter = 0,
  632. loops = loops,
  633. root = root,
  634. }
  635. root:set_nesting_level(0)
  636. root.counter = obj.loop_counter
  637. obj.loop_counter = obj.loop_counter + 1
  638. loops:append(root)
  639. return setmetatable(obj, {__index = LoopStructureGraph})
  640. end
  641. function LoopStructureGraph:create_new_loop (bb, is_reducible)
  642. local loop = SimpleLoop.new(bb, is_reducible)
  643. loop.counter = self.loop_counter
  644. self.loop_counter = self.loop_counter + 1
  645. self.loops:append(loop)
  646. return loop
  647. end
  648. function LoopStructureGraph:calculate_nesting_level ()
  649. -- link up all 1st level loops to artificial root node.
  650. self.loops:each(function (it)
  651. if not it.is_root then
  652. if not it.parent then
  653. it:set_parent(self.root)
  654. end
  655. end
  656. end)
  657. -- recursively traverse the tree and assign levels.
  658. self:calculate_nesting_level_rec(self.root, 0)
  659. end
  660. local function max (a, b)
  661. return (a < b) and b or a
  662. end
  663. function LoopStructureGraph:calculate_nesting_level_rec (loop, depth)
  664. loop.depth_level = depth
  665. loop.children:each(function (it)
  666. self:calculate_nesting_level_rec(it, depth + 1)
  667. loop:set_nesting_level(max(loop.nesting_level, 1 + it.nesting_level))
  668. end)
  669. end
  670. function LoopStructureGraph:num_loops ()
  671. return self.loops:size()
  672. end
  673. end -- class LoopStructureGraph
  674. local UnionFindNode = {_CLASS = 'UnionFindNode'} do
  675. function UnionFindNode.new ()
  676. local obj = {
  677. dfs_number = 0,
  678. parent = nil,
  679. bb = nil,
  680. loop = nil,
  681. }
  682. return setmetatable(obj, {__index = UnionFindNode})
  683. end
  684. function UnionFindNode:init_node (bb, dfs_number)
  685. self.parent = self
  686. self.bb = bb
  687. self.dfs_number = dfs_number
  688. self.loop = nil
  689. end
  690. function UnionFindNode:find_set ()
  691. local node_list = Vector.new()
  692. local node = self
  693. while node ~= node.parent do
  694. if node.parent ~= node.parent.parent then
  695. node_list:append(node)
  696. end
  697. node = node.parent
  698. end
  699. -- Path Compression, all nodes' parents point to the 1st level parent.
  700. node_list:each(function (it)
  701. it:union(self.parent)
  702. end)
  703. return node
  704. end
  705. function UnionFindNode:union (basic_block)
  706. self.parent = basic_block
  707. end
  708. end -- class UnionFindNode
  709. local HavlakLoopFinder = {_CLASS = 'HavlakLoopFinder'} do
  710. local UNVISITED = 2147483647 -- Marker for uninitialized nodes.
  711. local MAXNONBACKPREDS = 32 * 1024 -- Safeguard against pathological algorithm behavior.
  712. function HavlakLoopFinder.new (cfg, lsg)
  713. local obj = {
  714. cfg = cfg,
  715. lsg = lsg,
  716. non_back_preds = Vector.new(),
  717. back_preds = Vector.new(),
  718. number = IdentityDictionary.new(),
  719. max_size = 0,
  720. header = nil,
  721. type = nil,
  722. last = nil,
  723. nodes = nil,
  724. }
  725. return setmetatable(obj, {__index = HavlakLoopFinder})
  726. end
  727. -- As described in the paper, determine whether a node 'w' is a
  728. -- "true" ancestor for node 'v'.
  729. --
  730. -- Dominance can be tested quickly using a pre-order trick
  731. -- for depth-first spanning trees. This is why DFS is the first
  732. -- thing we run below.
  733. function HavlakLoopFinder:is_ancestor (w, v)
  734. return (w <= v) and (v <= self.last[w])
  735. end
  736. -- DFS - Depth-First-Search
  737. --
  738. -- DESCRIPTION:
  739. -- Simple depth first traversal along out edges with node numbering.
  740. function HavlakLoopFinder:do_dfs (current_node, current)
  741. self.nodes[current]:init_node(current_node, current)
  742. self.number:at_put(current_node, current)
  743. local last_id = current
  744. local outer_blocks = current_node.out_edges
  745. outer_blocks:each(function (target)
  746. if self.number:at(target) == UNVISITED then
  747. last_id = self:do_dfs(target, last_id + 1)
  748. end
  749. end)
  750. self.last[current] = last_id
  751. return last_id
  752. end
  753. function HavlakLoopFinder:init_all_nodes ()
  754. -- Step a:
  755. -- - initialize all nodes as unvisited.
  756. -- - depth-first traversal and numbering.
  757. -- - unreached BB's are marked as dead.
  758. self.cfg:get_basic_blocks():each(function (bb)
  759. self.number:at_put(bb, UNVISITED)
  760. end)
  761. self:do_dfs(self.cfg:get_start_basic_block(), 1)
  762. end
  763. function HavlakLoopFinder:identify_edges (size)
  764. -- Step b:
  765. -- - iterate over all nodes.
  766. --
  767. -- A backedge comes from a descendant in the DFS tree, and non-backedges
  768. -- from non-descendants (following Tarjan).
  769. --
  770. -- - check incoming edges 'v' and add them to either
  771. -- - the list of backedges (backPreds) or
  772. -- - the list of non-backedges (nonBackPreds)
  773. for w = 1, size do
  774. self.header[w] = 1
  775. self.type[w] = 'BB_NONHEADER'
  776. local node_w = self.nodes[w].bb
  777. if not node_w then
  778. self.type[w] = 'BB_DEAD'
  779. else
  780. self:process_edges(node_w, w)
  781. end
  782. end
  783. end
  784. function HavlakLoopFinder:process_edges (node_w, w)
  785. local number = self.number
  786. if node_w:num_pred() > 0 then
  787. node_w.in_edges:each(function (node_v)
  788. local v = number:at(node_v)
  789. if v ~= UNVISITED then
  790. if self:is_ancestor(w, v) then
  791. self.back_preds:at(w):append(v)
  792. else
  793. self.non_back_preds:at(w):add(v)
  794. end
  795. end
  796. end)
  797. end
  798. end
  799. -- Find loops and build loop forest using Havlak's algorithm, which
  800. -- is derived from Tarjan. Variable names and step numbering has
  801. -- been chosen to be identical to the nomenclature in Havlak's
  802. -- paper (which, in turn, is similar to the one used by Tarjan).
  803. function HavlakLoopFinder:find_loops ()
  804. if not self.cfg:get_start_basic_block() then
  805. return
  806. end
  807. local size = self.cfg:num_nodes()
  808. self.non_back_preds:remove_all()
  809. self.back_preds:remove_all()
  810. self.number:remove_all()
  811. if size > self.max_size then
  812. self.header = {}
  813. self.type = {}
  814. self.last = {}
  815. self.nodes = {}
  816. self.max_size = size
  817. end
  818. for i = 1, size do
  819. self.non_back_preds:append(Set.new())
  820. self.back_preds:append(Vector.new())
  821. self.nodes[i] = UnionFindNode.new()
  822. end
  823. self:init_all_nodes()
  824. self:identify_edges(size)
  825. -- Start node is root of all other loops.
  826. self.header[0] = 0
  827. -- Step c:
  828. --
  829. -- The outer loop, unchanged from Tarjan. It does nothing except
  830. -- for those nodes which are the destinations of backedges.
  831. -- For a header node w, we chase backward from the sources of the
  832. -- backedges adding nodes to the set P, representing the body of
  833. -- the loop headed by w.
  834. --
  835. -- By running through the nodes in reverse of the DFST preorder,
  836. -- we ensure that inner loop headers will be processed before the
  837. -- headers for surrounding loops.
  838. for w = size, 1, -1 do
  839. -- this is 'P' in Havlak's paper
  840. local node_pool = Vector.new()
  841. local node_w = self.nodes[w].bb
  842. if node_w then
  843. self:step_d(w, node_pool)
  844. -- Copy nodePool to workList.
  845. local work_list = Vector.new()
  846. node_pool:each(function (it)
  847. work_list:append(it)
  848. end)
  849. if node_pool:size() ~= 0 then
  850. self.type[w] = 'BB_REDUCIBLE'
  851. end
  852. -- work the list...
  853. while not work_list:is_empty() do
  854. local x = work_list:remove_first()
  855. -- Step e:
  856. --
  857. -- Step e represents the main difference from Tarjan's method.
  858. -- Chasing upwards from the sources of a node w's backedges. If
  859. -- there is a node y' that is not a descendant of w, w is marked
  860. -- the header of an irreducible loop, there is another entry
  861. -- into this loop that avoids w.
  862. -- The algorithm has degenerated. Break and
  863. -- return in this case.
  864. local non_back_size = self.non_back_preds:at(x.dfs_number):size()
  865. if non_back_size > MAXNONBACKPREDS then
  866. return
  867. end
  868. self:step_e_process_non_back_preds(w, node_pool, work_list, x)
  869. end
  870. end
  871. -- Collapse/Unionize nodes in a SCC to a single node
  872. -- For every SCC found, create a loop descriptor and link it in.
  873. if (node_pool:size() > 0) or (self.type[w] == 'BB_SELF') then
  874. local loop = self.lsg:create_new_loop(node_w, self.type[w] ~= 'BB_IRREDUCIBLE')
  875. self:set_loop_attributes(w, node_pool, loop)
  876. end
  877. end
  878. end
  879. function HavlakLoopFinder:step_e_process_non_back_preds (w, node_pool, work_list, x)
  880. self.non_back_preds:at(x.dfs_number):each(function (it)
  881. local y = self.nodes[it]
  882. local ydash = y:find_set()
  883. if not self:is_ancestor(w, ydash.dfs_number) then
  884. self.type[w] = 'BB_IRREDUCIBLE'
  885. self.non_back_preds:at(w):add(ydash.dfs_number)
  886. else
  887. if ydash.dfs_number ~= w then
  888. if not node_pool:has_some(function (e) return e == ydash end) then
  889. work_list:append(ydash)
  890. node_pool:append(ydash)
  891. end
  892. end
  893. end
  894. end)
  895. end
  896. function HavlakLoopFinder:set_loop_attributes (w, node_pool, loop)
  897. -- At this point, one can set attributes to the loop, such as:
  898. --
  899. -- the bottom node:
  900. -- iter = backPreds[w].begin();
  901. -- loop bottom is: nodes[iter].node);
  902. --
  903. -- the number of backedges:
  904. -- backPreds[w].size()
  905. --
  906. -- whether this loop is reducible:
  907. -- type[w] != BasicBlockClass.BB_IRREDUCIBLE
  908. self.nodes[w].loop = loop
  909. node_pool:each(function (node)
  910. -- Add nodes to loop descriptor.
  911. self.header[node.dfs_number] = w
  912. node:union(self.nodes[w])
  913. -- Nested loops are not added, but linked together.
  914. if node.loop then
  915. node.loop:set_parent(loop)
  916. else
  917. loop:add_node(node.bb)
  918. end
  919. end)
  920. end
  921. function HavlakLoopFinder:step_d (w, node_pool)
  922. self.back_preds:at(w):each(function (v)
  923. if v ~= w then
  924. node_pool:append(self.nodes[v]:find_set())
  925. else
  926. self.type[w] = 'BB_SELF'
  927. end
  928. end)
  929. end
  930. end -- class HavlakLoopFinder
  931. local LoopTesterApp = {_CLASS = 'LoopTesterApp'} do
  932. function LoopTesterApp.new ()
  933. local cfg = ControlFlowGraph.new()
  934. local lsg = LoopStructureGraph.new()
  935. local obj = {
  936. cfg = cfg,
  937. lsg = lsg,
  938. }
  939. cfg:create_node(1)
  940. return setmetatable(obj, {__index = LoopTesterApp})
  941. end
  942. -- Create 4 basic blocks, corresponding to and if/then/else clause
  943. -- with a CFG that looks like a diamond
  944. function LoopTesterApp:build_diamond (start)
  945. local bb0 = start
  946. BasicBlockEdge.new(self.cfg, bb0, bb0 + 1)
  947. BasicBlockEdge.new(self.cfg, bb0, bb0 + 2)
  948. BasicBlockEdge.new(self.cfg, bb0 + 1, bb0 + 3)
  949. BasicBlockEdge.new(self.cfg, bb0 + 2, bb0 + 3)
  950. return bb0 + 3
  951. end
  952. -- Connect two existing nodes
  953. function LoopTesterApp:build_connect (start, end_)
  954. BasicBlockEdge.new(self.cfg, start, end_)
  955. end
  956. -- Form a straight connected sequence of n basic blocks
  957. function LoopTesterApp:build_straight (start, n)
  958. for i = 1, n do
  959. self:build_connect(start + i - 1, start + i)
  960. end
  961. return start + n
  962. end
  963. -- Construct a simple loop with two diamonds in it
  964. function LoopTesterApp:build_base_loop (from)
  965. local header = self:build_straight(from, 1)
  966. local diamond1 = self:build_diamond(header)
  967. local d11 = self:build_straight(diamond1, 1)
  968. local diamond2 = self:build_diamond(d11)
  969. local footer = self:build_straight(diamond2, 1)
  970. self:build_connect(diamond2, d11)
  971. self:build_connect(diamond1, header)
  972. self:build_connect(footer, from)
  973. return self:build_straight(footer, 1)
  974. end
  975. function LoopTesterApp:main (num_dummy_loops, find_loop_iterations, par_loops,
  976. ppar_loops, pppar_loops)
  977. self:construct_simple_cfg()
  978. self:add_dummy_loops(num_dummy_loops)
  979. self:construct_cfg(par_loops, ppar_loops, pppar_loops)
  980. -- Performing Loop Recognition, 1 Iteration, then findLoopIteration
  981. self:find_loops(self.lsg)
  982. for _ = 0, find_loop_iterations do
  983. self:find_loops(LoopStructureGraph.new())
  984. end
  985. self.lsg:calculate_nesting_level()
  986. return {self.lsg:num_loops(), self.cfg:num_nodes()}
  987. end
  988. function LoopTesterApp:construct_cfg (par_loops, ppar_loops, pppar_loops)
  989. local n = 3
  990. for _ = 1, par_loops do
  991. self.cfg:create_node(n + 1)
  992. self:build_connect(3, n + 1)
  993. n = n + 1
  994. for _ = 1, ppar_loops do
  995. local top = n
  996. n = self:build_straight(n, 1)
  997. for _ = 1, pppar_loops do
  998. n = self:build_base_loop(n)
  999. end
  1000. local bottom = self:build_straight(n, 1)
  1001. self:build_connect(n, top)
  1002. n = bottom
  1003. end
  1004. self:build_connect(n, 1)
  1005. end
  1006. end
  1007. function LoopTesterApp:add_dummy_loops (num_dummy_loops)
  1008. for _ = 1, num_dummy_loops do
  1009. self:find_loops(self.lsg)
  1010. end
  1011. end
  1012. function LoopTesterApp:find_loops (loop_structure)
  1013. local finder = HavlakLoopFinder.new(self.cfg, loop_structure)
  1014. finder:find_loops()
  1015. end
  1016. function LoopTesterApp:construct_simple_cfg ()
  1017. self.cfg:create_node(1)
  1018. self:build_base_loop(1)
  1019. self.cfg:create_node(2)
  1020. BasicBlockEdge.new(self.cfg, 1, 3)
  1021. end
  1022. end -- class LoopTesterApp
  1023. local havlak = {} do
  1024. setmetatable(havlak, {__index = benchmark})
  1025. function havlak:inner_benchmark_loop (inner_iterations)
  1026. local result = LoopTesterApp.new():main(inner_iterations, 50, 10, 10, 5)
  1027. return self:verify_result(result, inner_iterations)
  1028. end
  1029. function havlak:verify_result (result, inner_iterations)
  1030. if inner_iterations == 15000 then
  1031. return result[1] == 46602 and result[2] == 5213
  1032. elseif inner_iterations == 1500 then
  1033. return result[1] == 6102 and result[2] == 5213
  1034. elseif inner_iterations == 150 then
  1035. return result[1] == 2052 and result[2] == 5213
  1036. elseif inner_iterations == 15 then
  1037. return result[1] == 1647 and result[2] == 5213
  1038. elseif inner_iterations == 1 then
  1039. return result[1] == 1605 and result[2] == 5213
  1040. else
  1041. print(('No verification result for %d found'):format(inner_iterations))
  1042. print(('Result is: %d, %d'):format(result[0], result[1]))
  1043. return false
  1044. end
  1045. end
  1046. end -- object havlak
  1047. return function(N)
  1048. if N > 0 then
  1049. havlak:inner_benchmark_loop(N)
  1050. end
  1051. end